initial
This commit is contained in:
23 files changed
+2117
No files matched your search
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
Shared components for devtools package.
|
||||
"""
|
||||
|
||||
from .config import BaseConfig
|
||||
from .git import GitService
|
||||
from .ai import AIService
|
||||
|
||||
__all__ = ["BaseConfig", "GitService", "AIService"]
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
Shared AI service for devtools.
|
||||
"""
|
||||
import requests
|
||||
import os
|
||||
from typing import List, Dict, Optional, Any
|
||||
from .config import BaseConfig
|
||||
|
||||
class AIService:
|
||||
"""Base AI service that can be extended by specific tools."""
|
||||
|
||||
def __init__(self, config: BaseConfig):
|
||||
"""Initialize AI service with configuration."""
|
||||
self.config = config
|
||||
self._setup_ai()
|
||||
|
||||
def _setup_ai(self) -> None:
|
||||
"""Set up the AI model with configuration."""
|
||||
self.api_key = self.config.get_env_or_config("OPENROUTER_API_KEY")
|
||||
if not self.api_key:
|
||||
raise ValueError("OpenRouter API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = self.config.get("model", "mistralai/mixtral-8x7b-instruct")
|
||||
self.api_url = "https://openrouter.ai/api/v1/chat/completions"
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"HTTP-Referer": "https://github.com/S4NKALP/DevTools",
|
||||
"X-Title": "DevTools",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
|
||||
"""Create a prompt for the AI model."""
|
||||
return [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt}
|
||||
]
|
||||
|
||||
def generate_completion(self,
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
top_p: float = 0.95) -> str:
|
||||
"""Generate a completion from the AI model."""
|
||||
messages = self._create_prompt(system_prompt, user_prompt)
|
||||
|
||||
try:
|
||||
# Convert config values to proper types
|
||||
temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
|
||||
tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
|
||||
|
||||
payload = {
|
||||
"model": self.model,
|
||||
"messages": messages,
|
||||
"temperature": temp,
|
||||
"max_tokens": tokens,
|
||||
"top_p": float(top_p),
|
||||
"stream": False
|
||||
}
|
||||
|
||||
# Remove None values
|
||||
payload = {k: v for k, v in payload.items() if v is not None}
|
||||
|
||||
response = requests.post(
|
||||
self.api_url,
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
error_json = response.json()
|
||||
if "error" in error_json:
|
||||
error_msg = error_json["error"]
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"OpenRouter API error: {error_msg}")
|
||||
|
||||
result = response.json()
|
||||
|
||||
if "choices" in result and len(result["choices"]) > 0:
|
||||
return result["choices"][0]["message"]["content"].strip()
|
||||
|
||||
return ""
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"AI generation failed: {str(e)}")
|
||||
|
||||
def generate_batch_completions(self,
|
||||
system_prompt: str,
|
||||
prompts: List[str],
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None) -> List[str]:
|
||||
"""Generate completions for multiple prompts."""
|
||||
completions = []
|
||||
for prompt in prompts:
|
||||
completion = self.generate_completion(
|
||||
system_prompt,
|
||||
prompt,
|
||||
temperature,
|
||||
max_tokens
|
||||
)
|
||||
completions.append(completion)
|
||||
return completions
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Shared configuration system.
|
||||
"""
|
||||
import os
|
||||
import yaml
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
class BaseConfig:
|
||||
"""Base configuration class."""
|
||||
|
||||
def __init__(self, default_config: Dict[str, Any] = None):
|
||||
"""Initialize base configuration.
|
||||
|
||||
Args:
|
||||
default_config: Default configuration values
|
||||
"""
|
||||
self._config = default_config or {}
|
||||
|
||||
def get(self, key: str, default: Any = None) -> Any:
|
||||
"""Get a configuration value.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
default: Default value if key not found
|
||||
|
||||
Returns:
|
||||
Configuration value
|
||||
"""
|
||||
return self._config.get(key, default)
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
"""Set a configuration value.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
value: Configuration value
|
||||
"""
|
||||
self._config[key] = value
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
"""Delete a configuration value.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
"""
|
||||
if key in self._config:
|
||||
del self._config[key]
|
||||
|
||||
def get_all(self) -> Dict[str, Any]:
|
||||
"""Get all configuration values.
|
||||
|
||||
Returns:
|
||||
Dictionary of all configuration values
|
||||
"""
|
||||
return self._config.copy()
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all configuration values."""
|
||||
self._config = {}
|
||||
|
||||
def validate(self) -> bool:
|
||||
"""Override in subclasses for validation logic."""
|
||||
return True
|
||||
|
||||
def get_env_or_config(self, key: str, env_var: Optional[str] = None) -> Optional[str]:
|
||||
"""Get value from environment variable or config.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
env_var: Environment variable name (defaults to key.upper())
|
||||
"""
|
||||
env_var = env_var or key.upper()
|
||||
return self._config.get(key) or os.getenv(env_var)
|
||||
|
||||
class Config(BaseConfig):
|
||||
"""Configuration manager for devtools."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize configuration."""
|
||||
super().__init__()
|
||||
self.config_dir = self._get_config_dir()
|
||||
self.config_file = self.config_dir / "config.yaml"
|
||||
self._ensure_config_dir()
|
||||
self._load_config()
|
||||
|
||||
def _get_config_dir(self) -> Path:
|
||||
"""Get the configuration directory.
|
||||
|
||||
Returns:
|
||||
Path to config directory
|
||||
"""
|
||||
return Path.home() / ".devtools"
|
||||
|
||||
def _ensure_config_dir(self) -> None:
|
||||
"""Ensure configuration directory exists."""
|
||||
self.config_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _load_config(self) -> None:
|
||||
"""Load configuration from file."""
|
||||
if self.config_file.exists():
|
||||
with open(self.config_file, "r") as f:
|
||||
self._config = yaml.safe_load(f) or {}
|
||||
else:
|
||||
self._config = {}
|
||||
|
||||
def _save_config(self) -> None:
|
||||
"""Save configuration to file."""
|
||||
with open(self.config_file, "w") as f:
|
||||
yaml.dump(self._config, f, default_flow_style=False, sort_keys=False)
|
||||
|
||||
def set(self, key: str, value: Any) -> None:
|
||||
"""Set a configuration value.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
value: Configuration value
|
||||
"""
|
||||
super().set(key, value)
|
||||
self._save_config()
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
"""Delete a configuration value.
|
||||
|
||||
Args:
|
||||
key: Configuration key
|
||||
"""
|
||||
super().delete(key)
|
||||
self._save_config()
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all configuration values."""
|
||||
super().clear()
|
||||
self._save_config()
|
||||
@@ -0,0 +1,231 @@
|
||||
"""
|
||||
Shared Git service for devtools.
|
||||
"""
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional, Tuple
|
||||
import os
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
class GitService:
|
||||
"""Base Git service that can be extended by specific tools."""
|
||||
|
||||
def __init__(self, repo_path: str):
|
||||
"""Initialize GitService with repository path."""
|
||||
self.repo_path = repo_path
|
||||
if not os.path.exists(os.path.join(repo_path, '.git')):
|
||||
raise ValueError(f"Not a git repository: {repo_path}")
|
||||
|
||||
def _is_git_repo(self) -> bool:
|
||||
"""Check if the current directory is a git repository."""
|
||||
try:
|
||||
subprocess.run(
|
||||
["git", "rev-parse", "--is-inside-work-tree"],
|
||||
cwd=self.repo_path,
|
||||
check=True,
|
||||
capture_output=True
|
||||
)
|
||||
return True
|
||||
except subprocess.CalledProcessError:
|
||||
return False
|
||||
|
||||
def _run_git_command(self, args: List[str]) -> Tuple[str, str]:
|
||||
"""Run a git command and return its output."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["git"] + args,
|
||||
cwd=self.repo_path,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
return result.stdout.strip(), result.stderr.strip()
|
||||
except subprocess.CalledProcessError as e:
|
||||
return e.stdout.strip(), e.stderr.strip()
|
||||
|
||||
def get_staged_files(self) -> List[str]:
|
||||
"""Get list of staged files."""
|
||||
stdout, _ = self._run_git_command(["diff", "--cached", "--name-only"])
|
||||
return stdout.splitlines() if stdout else []
|
||||
|
||||
def get_unstaged_files(self) -> List[str]:
|
||||
"""Get list of unstaged files."""
|
||||
stdout, _ = self._run_git_command(["ls-files", "--modified", "--others", "--exclude-standard"])
|
||||
return stdout.splitlines() if stdout else []
|
||||
|
||||
def get_diff(self, file_path: str, staged: bool = True) -> str:
|
||||
"""Get diff for a specific file."""
|
||||
args = ["diff", "--cached" if staged else ""]
|
||||
if file_path:
|
||||
args.append(file_path)
|
||||
stdout, _ = self._run_git_command(args)
|
||||
return stdout
|
||||
|
||||
def get_all_diffs(self, staged: bool = True) -> Dict[str, str]:
|
||||
"""Get diffs for all changed files."""
|
||||
files = self.get_staged_files() if staged else self.get_unstaged_files()
|
||||
return {file: self.get_diff(file, staged) for file in files}
|
||||
|
||||
def commit(self, message: str, sign: bool = False) -> bool:
|
||||
"""Create a commit with the given message."""
|
||||
args = ["commit"]
|
||||
if sign:
|
||||
args.append("-S")
|
||||
args.extend(["-m", message])
|
||||
stdout, stderr = self._run_git_command(args)
|
||||
return not stderr
|
||||
|
||||
def get_repo_name(self) -> str:
|
||||
"""Get the repository name."""
|
||||
stdout, _ = self._run_git_command(["rev-parse", "--show-toplevel"])
|
||||
return Path(stdout).name
|
||||
|
||||
def get_current_branch(self) -> str:
|
||||
"""Get the current branch name."""
|
||||
stdout, _ = self._run_git_command(["rev-parse", "--abbrev-ref", "HEAD"])
|
||||
return stdout
|
||||
|
||||
def push(self, branch: Optional[str] = None) -> bool:
|
||||
"""Push changes to remote."""
|
||||
if not branch:
|
||||
branch = self.get_current_branch()
|
||||
stdout, stderr = self._run_git_command(["push", "origin", branch])
|
||||
return not stderr
|
||||
|
||||
def get_staged_changes(self, files: Optional[List[str]] = None) -> Dict[str, str]:
|
||||
"""Get staged changes for specified files or all staged changes."""
|
||||
try:
|
||||
diffs = {} # Initialize diffs at the start
|
||||
|
||||
if files:
|
||||
for file in files:
|
||||
result = subprocess.run(
|
||||
['git', 'diff', '--staged', '--', file],
|
||||
cwd=self.repo_path,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
if result.stdout:
|
||||
diffs[file] = result.stdout
|
||||
else:
|
||||
result = subprocess.run(
|
||||
['git', 'diff', '--staged'],
|
||||
cwd=self.repo_path,
|
||||
capture_output=True,
|
||||
text=True
|
||||
)
|
||||
if result.stdout:
|
||||
# Parse the diff to get individual file changes
|
||||
current_file = None
|
||||
current_diff = []
|
||||
|
||||
for line in result.stdout.split('\n'):
|
||||
if line.startswith('diff --git'):
|
||||
if current_file and current_diff:
|
||||
diffs[current_file] = '\n'.join(current_diff)
|
||||
current_file = line.split('b/')[-1].strip()
|
||||
current_diff = [line]
|
||||
elif current_file:
|
||||
current_diff.append(line)
|
||||
|
||||
if current_file and current_diff:
|
||||
diffs[current_file] = '\n'.join(current_diff)
|
||||
|
||||
return diffs
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception(f"Failed to get staged changes: {str(e)}")
|
||||
|
||||
def stage_all_changes(self) -> None:
|
||||
"""Stage all changes in the repository."""
|
||||
try:
|
||||
subprocess.run(
|
||||
['git', 'add', '.'],
|
||||
cwd=self.repo_path,
|
||||
check=True
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception(f"Failed to stage changes: {str(e)}")
|
||||
|
||||
def get_commit_history(self, since: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, str]]:
|
||||
"""Get commit history.
|
||||
|
||||
Args:
|
||||
since: Get commits since this reference (tag, commit, etc.)
|
||||
limit: Maximum number of commits to return
|
||||
"""
|
||||
args = [
|
||||
"log",
|
||||
"--pretty=format:%H%n%an%n%ad%n%B%n==END==",
|
||||
"--date=format:%Y-%m-%d %H:%M:%S %z"
|
||||
]
|
||||
|
||||
if since:
|
||||
args.append(f"{since}..HEAD")
|
||||
if limit:
|
||||
args.append(f"-n {limit}")
|
||||
|
||||
stdout, _ = self._run_git_command(args)
|
||||
|
||||
commits = []
|
||||
current_commit = []
|
||||
|
||||
for line in stdout.split('\n'):
|
||||
if line == "==END==":
|
||||
if current_commit:
|
||||
commit_hash, author, date, *message_lines = current_commit
|
||||
commits.append({
|
||||
'hash': commit_hash,
|
||||
'author': author,
|
||||
'date': date,
|
||||
'message': '\n'.join(message_lines)
|
||||
})
|
||||
current_commit = []
|
||||
else:
|
||||
current_commit.append(line)
|
||||
|
||||
return commits
|
||||
|
||||
def get_commits_since_tag(self, tag: str) -> List[Dict[str, str]]:
|
||||
"""Get commits since a tag.
|
||||
|
||||
Args:
|
||||
tag: Git tag to use as reference point
|
||||
|
||||
Returns:
|
||||
List of commit dictionaries with hash and message
|
||||
"""
|
||||
cmd = ["git", "log", f"{tag}..HEAD", "--pretty=format:%H|%s"]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd=self.repo_path)
|
||||
result.check_returncode()
|
||||
|
||||
commits = []
|
||||
for line in result.stdout.splitlines():
|
||||
hash_, message = line.split("|", 1)
|
||||
commits.append({"hash": hash_, "message": message})
|
||||
|
||||
return commits
|
||||
|
||||
def get_commits_since_date(self, days: int) -> List[Dict[str, str]]:
|
||||
"""Get commits since a date.
|
||||
|
||||
Args:
|
||||
days: Number of days to look back
|
||||
|
||||
Returns:
|
||||
List of commit dictionaries with hash and message
|
||||
"""
|
||||
# Calculate date
|
||||
date = datetime.now() - timedelta(days=days)
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
|
||||
# Get commits
|
||||
cmd = ["git", "log", f"--since={date_str}", "--pretty=format:%H|%s"]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, cwd=self.repo_path)
|
||||
result.check_returncode()
|
||||
|
||||
commits = []
|
||||
for line in result.stdout.splitlines():
|
||||
hash_, message = line.split("|", 1)
|
||||
commits.append({"hash": hash_, "message": message})
|
||||
|
||||
return commits
|
||||
Reference in new issue
Block a user