🔧 Based on the provided code snippets, the commit message for the changes in the README.md file should be:
This commit is contained in:
11 files changed
+1033
-513
No files matched your search
+174
-237
@@ -1,100 +1,84 @@
|
||||
"""
|
||||
Shared AI service for devtools.
|
||||
"""
|
||||
|
||||
import requests
|
||||
import os
|
||||
from typing import List, Dict, Optional, Any
|
||||
from abc import ABC, abstractmethod
|
||||
from .config import BaseConfig
|
||||
|
||||
|
||||
class AIProvider(ABC):
|
||||
"""Base class for AI providers."""
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
"""Set up the provider with configuration."""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
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:
|
||||
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."""
|
||||
pass
|
||||
|
||||
|
||||
class OpenRouterProvider(AIProvider):
|
||||
"""OpenRouter AI provider implementation."""
|
||||
|
||||
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
self.config = config
|
||||
self.api_key = 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."
|
||||
)
|
||||
|
||||
raise ValueError("OpenRouter API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = 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",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def _create_prompt(
|
||||
self, system_prompt: str, user_prompt: str
|
||||
) -> List[Dict[str, str]]:
|
||||
def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
|
||||
return [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_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:
|
||||
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:
|
||||
messages = self._create_prompt(system_prompt, user_prompt)
|
||||
|
||||
|
||||
try:
|
||||
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))
|
||||
)
|
||||
|
||||
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,
|
||||
"stream": False
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
self.api_url,
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
@@ -104,80 +88,68 @@ class OpenRouterProvider(AIProvider):
|
||||
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)}")
|
||||
|
||||
|
||||
class OpenAIProvider(AIProvider):
|
||||
"""OpenAI provider implementation."""
|
||||
|
||||
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
self.config = config
|
||||
self.api_key = config.get_env_or_config("OPENAI_API_KEY")
|
||||
if not self.api_key:
|
||||
raise ValueError(
|
||||
"OpenAI API key not found. Please set it in config or environment."
|
||||
)
|
||||
|
||||
raise ValueError("OpenAI API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = config.get("model", "gpt-4-turbo-preview")
|
||||
self.api_url = "https://api.openai.com/v1/chat/completions"
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def _create_prompt(
|
||||
self, system_prompt: str, user_prompt: str
|
||||
) -> List[Dict[str, str]]:
|
||||
def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
|
||||
return [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_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:
|
||||
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:
|
||||
messages = self._create_prompt(system_prompt, user_prompt)
|
||||
|
||||
|
||||
try:
|
||||
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))
|
||||
)
|
||||
|
||||
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),
|
||||
"top_p": float(top_p)
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
self.api_url,
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
@@ -187,74 +159,63 @@ class OpenAIProvider(AIProvider):
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"OpenAI 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)}")
|
||||
|
||||
|
||||
class GeminiProvider(AIProvider):
|
||||
"""Google Gemini provider implementation."""
|
||||
|
||||
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
self.config = config
|
||||
self.api_key = config.get_env_or_config("GOOGLE_API_KEY")
|
||||
if not self.api_key:
|
||||
raise ValueError(
|
||||
"Google API key not found. Please set it in config or environment."
|
||||
)
|
||||
|
||||
raise ValueError("Google API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = config.get("model", "gemini-pro")
|
||||
self.api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{
|
||||
self.model
|
||||
}:generateContent"
|
||||
self.headers = {"Content-Type": "application/json"}
|
||||
self.api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent"
|
||||
self.headers = {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
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:
|
||||
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:
|
||||
try:
|
||||
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))
|
||||
)
|
||||
|
||||
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))
|
||||
|
||||
# Combine system and user prompts for Gemini
|
||||
full_prompt = f"{system_prompt}\n\n{user_prompt}"
|
||||
|
||||
|
||||
payload = {
|
||||
"contents": [{"parts": [{"text": full_prompt}]}],
|
||||
"contents": [{
|
||||
"parts": [{"text": full_prompt}]
|
||||
}],
|
||||
"generationConfig": {
|
||||
"temperature": temp,
|
||||
"maxOutputTokens": tokens,
|
||||
"topP": float(top_p),
|
||||
},
|
||||
"topP": float(top_p)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
response = requests.post(
|
||||
f"{self.api_url}?key={self.api_key}",
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
@@ -264,81 +225,69 @@ class GeminiProvider(AIProvider):
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"Gemini API error: {error_msg}")
|
||||
|
||||
|
||||
result = response.json()
|
||||
|
||||
|
||||
if "candidates" in result and len(result["candidates"]) > 0:
|
||||
return result["candidates"][0]["content"]["parts"][0]["text"].strip()
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"AI generation failed: {str(e)}")
|
||||
|
||||
|
||||
class ClaudeProvider(AIProvider):
|
||||
"""Anthropic Claude provider implementation."""
|
||||
|
||||
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
self.config = config
|
||||
self.api_key = config.get_env_or_config("ANTHROPIC_API_KEY")
|
||||
if not self.api_key:
|
||||
raise ValueError(
|
||||
"Anthropic API key not found. Please set it in config or environment."
|
||||
)
|
||||
|
||||
raise ValueError("Anthropic API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = config.get("model", "claude-3-opus-20240229")
|
||||
self.api_url = "https://api.anthropic.com/v1/messages"
|
||||
self.headers = {
|
||||
"x-api-key": self.api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"content-type": "application/json",
|
||||
"content-type": "application/json"
|
||||
}
|
||||
|
||||
def _create_prompt(
|
||||
self, system_prompt: str, user_prompt: str
|
||||
) -> List[Dict[str, str]]:
|
||||
def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
|
||||
return [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_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:
|
||||
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:
|
||||
messages = self._create_prompt(system_prompt, user_prompt)
|
||||
|
||||
|
||||
try:
|
||||
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))
|
||||
)
|
||||
|
||||
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),
|
||||
"top_p": float(top_p)
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
self.api_url,
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
@@ -348,76 +297,66 @@ class ClaudeProvider(AIProvider):
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"Claude API error: {error_msg}")
|
||||
|
||||
|
||||
result = response.json()
|
||||
|
||||
|
||||
if "content" in result and len(result["content"]) > 0:
|
||||
return result["content"][0]["text"].strip()
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"AI generation failed: {str(e)}")
|
||||
|
||||
|
||||
class HuggingFaceProvider(AIProvider):
|
||||
"""Hugging Face provider implementation."""
|
||||
|
||||
|
||||
def setup(self, config: BaseConfig) -> None:
|
||||
self.config = config
|
||||
self.api_key = config.get_env_or_config("HUGGINGFACE_API_KEY")
|
||||
if not self.api_key:
|
||||
raise ValueError(
|
||||
"Hugging Face API key not found. Please set it in config or environment."
|
||||
)
|
||||
|
||||
raise ValueError("Hugging Face API key not found. Please set it in config or environment.")
|
||||
|
||||
self.model = config.get("model", "mistralai/Mixtral-8x7B-Instruct-v0.1")
|
||||
self.api_url = f"https://api-inference.huggingface.co/models/{self.model}"
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def _create_prompt(self, system_prompt: str, user_prompt: str) -> str:
|
||||
# Format prompt according to model's requirements
|
||||
return f"<s>[INST] {system_prompt}\n\n{user_prompt} [/INST]"
|
||||
|
||||
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:
|
||||
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:
|
||||
try:
|
||||
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))
|
||||
)
|
||||
|
||||
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))
|
||||
|
||||
prompt = self._create_prompt(system_prompt, user_prompt)
|
||||
|
||||
|
||||
payload = {
|
||||
"inputs": prompt,
|
||||
"parameters": {
|
||||
"temperature": temp,
|
||||
"max_new_tokens": tokens,
|
||||
"top_p": float(top_p),
|
||||
"return_full_text": False,
|
||||
},
|
||||
"return_full_text": False
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
response = requests.post(
|
||||
self.api_url, headers=self.headers, json=payload, timeout=30
|
||||
self.api_url,
|
||||
headers=self.headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
|
||||
if response.status_code != 200:
|
||||
error_msg = response.text
|
||||
try:
|
||||
@@ -427,21 +366,20 @@ class HuggingFaceProvider(AIProvider):
|
||||
except:
|
||||
pass
|
||||
raise Exception(f"Hugging Face API error: {error_msg}")
|
||||
|
||||
|
||||
result = response.json()
|
||||
|
||||
|
||||
if isinstance(result, list) and len(result) > 0:
|
||||
return result[0]["generated_text"].strip()
|
||||
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"AI generation failed: {str(e)}")
|
||||
|
||||
|
||||
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
|
||||
@@ -451,49 +389,48 @@ class AIService:
|
||||
def _get_provider(self) -> AIProvider:
|
||||
"""Get the appropriate AI provider based on configuration."""
|
||||
provider = self.config.get("provider", "openrouter").lower()
|
||||
|
||||
|
||||
providers = {
|
||||
"openrouter": OpenRouterProvider,
|
||||
"openai": OpenAIProvider,
|
||||
"gemini": GeminiProvider,
|
||||
"claude": ClaudeProvider,
|
||||
"huggingface": HuggingFaceProvider,
|
||||
"huggingface": HuggingFaceProvider
|
||||
}
|
||||
|
||||
|
||||
if provider not in providers:
|
||||
raise ValueError(
|
||||
f"Unsupported AI provider: {provider}. Supported providers: {
|
||||
', '.join(providers.keys())
|
||||
}"
|
||||
)
|
||||
|
||||
raise ValueError(f"Unsupported AI provider: {provider}. Supported providers: {', '.join(providers.keys())}")
|
||||
|
||||
return providers[provider]()
|
||||
|
||||
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:
|
||||
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."""
|
||||
return self.provider.generate_completion(
|
||||
system_prompt, user_prompt, temperature, max_tokens, top_p
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
temperature,
|
||||
max_tokens,
|
||||
top_p
|
||||
)
|
||||
|
||||
def generate_batch_completions(
|
||||
self,
|
||||
system_prompt: str,
|
||||
prompts: List[str],
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
) -> List[str]:
|
||||
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
|
||||
system_prompt,
|
||||
prompt,
|
||||
temperature,
|
||||
max_tokens
|
||||
)
|
||||
completions.append(completion)
|
||||
return completions
|
||||
return completions
|
||||
+44
-48
@@ -1,21 +1,19 @@
|
||||
"""
|
||||
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")):
|
||||
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:
|
||||
@@ -25,7 +23,7 @@ class GitService:
|
||||
["git", "rev-parse", "--is-inside-work-tree"],
|
||||
cwd=self.repo_path,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
capture_output=True
|
||||
)
|
||||
return True
|
||||
except subprocess.CalledProcessError:
|
||||
@@ -39,7 +37,7 @@ class GitService:
|
||||
cwd=self.repo_path,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
text=True
|
||||
)
|
||||
return result.stdout.strip(), result.stderr.strip(), result.returncode
|
||||
except subprocess.CalledProcessError as e:
|
||||
@@ -52,9 +50,7 @@ class GitService:
|
||||
|
||||
def get_unstaged_files(self) -> List[str]:
|
||||
"""Get list of unstaged files."""
|
||||
stdout, _, _ = self._run_git_command(
|
||||
["ls-files", "--modified", "--others", "--exclude-standard"]
|
||||
)
|
||||
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:
|
||||
@@ -104,36 +100,36 @@ class GitService:
|
||||
if files:
|
||||
for file in files:
|
||||
result = subprocess.run(
|
||||
["git", "diff", "--staged", "--", file],
|
||||
['git', 'diff', '--staged', '--', file],
|
||||
cwd=self.repo_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
text=True
|
||||
)
|
||||
if result.stdout:
|
||||
diffs[file] = result.stdout
|
||||
else:
|
||||
result = subprocess.run(
|
||||
["git", "diff", "--staged"],
|
||||
['git', 'diff', '--staged'],
|
||||
cwd=self.repo_path,
|
||||
capture_output=True,
|
||||
text=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"):
|
||||
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()
|
||||
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)
|
||||
diffs[current_file] = '\n'.join(current_diff)
|
||||
|
||||
return diffs
|
||||
except subprocess.CalledProcessError as e:
|
||||
@@ -142,15 +138,17 @@ class GitService:
|
||||
def stage_all_changes(self) -> None:
|
||||
"""Stage all changes in the repository."""
|
||||
try:
|
||||
subprocess.run(["git", "add", "."], cwd=self.repo_path, check=True)
|
||||
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]]:
|
||||
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
|
||||
@@ -158,78 +156,76 @@ class GitService:
|
||||
args = [
|
||||
"log",
|
||||
"--pretty=format:%H%n%an%n%ad%n%B%n==END==",
|
||||
"--date=format:%Y-%m-%d %H:%M:%S %z",
|
||||
"--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"):
|
||||
|
||||
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),
|
||||
}
|
||||
)
|
||||
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
|
||||
|
||||
return commits
|
||||
Reference in new issue
Block a user