🔧 Based on the provided code snippets, the commit message for the changes in the README.md file should be:

This commit is contained in:
sankalp committed 2025-06-04 13:18:51 +05:45
1 parent 89af435abc
commit 13d0353fa9
11 files changed
+919 -399

No files matched your search

+61 -1
View File
@@ -10,7 +10,7 @@ $ git clone https://github.com/S4NKALP/DevTools.git
$ cd devtools $ cd devtools
# Install in editable mode # Install in editable mode
$ pipx install -e . $ pip install -e .
``` ```
## Configuration ## Configuration
@@ -35,6 +35,9 @@ devtools config set ANTHROPIC_API_KEY "your-anthropic-api-key"
# For Hugging Face # For Hugging Face
devtools config set HUGGINGFACE_API_KEY "your-huggingface-api-key" devtools config set HUGGINGFACE_API_KEY "your-huggingface-api-key"
# Set GitHub token (recommended for license generator)
devtools config set GITHUB_TOKEN "your-github-token"
``` ```
Or set them in your environment: Or set them in your environment:
@@ -46,6 +49,9 @@ export OPENAI_API_KEY="your-openai-api-key"
export GOOGLE_API_KEY="your-google-api-key" export GOOGLE_API_KEY="your-google-api-key"
export ANTHROPIC_API_KEY="your-anthropic-api-key" export ANTHROPIC_API_KEY="your-anthropic-api-key"
export HUGGINGFACE_API_KEY="your-huggingface-api-key" export HUGGINGFACE_API_KEY="your-huggingface-api-key"
# GitHub token for license generator
export GITHUB_TOKEN="your-github-token"
``` ```
Or create a `.env` file in your project root: Or create a `.env` file in your project root:
@@ -56,6 +62,7 @@ OPENAI_API_KEY=your-openai-api-key
GOOGLE_API_KEY=your-google-api-key GOOGLE_API_KEY=your-google-api-key
ANTHROPIC_API_KEY=your-anthropic-api-key ANTHROPIC_API_KEY=your-anthropic-api-key
HUGGINGFACE_API_KEY=your-huggingface-api-key HUGGINGFACE_API_KEY=your-huggingface-api-key
GITHUB_TOKEN=your-github-token
``` ```
### Managing Configuration ### Managing Configuration
@@ -87,6 +94,7 @@ OPENAI_API_KEY:
GOOGLE_API_KEY: GOOGLE_API_KEY:
ANTHROPIC_API_KEY: ANTHROPIC_API_KEY:
HUGGINGFACE_API_KEY: HUGGINGFACE_API_KEY:
GITHUB_TOKEN:
# AI Settings # AI Settings
provider: openrouter # or "openai", "gemini", "claude", "huggingface" provider: openrouter # or "openai", "gemini", "claude", "huggingface"
@@ -274,6 +282,52 @@ The generator uses the gitignore.io API to fetch templates. No API key is requir
--- ---
### License Generator
Generate LICENSE files for your project using templates from GitHub's license API.
```bash
# List available licenses
devtools license list
# Generate a license
devtools license generate [OPTIONS]
```
**Options:**
- `--type, -t TYPE` Type of license to generate (e.g., mit, apache-2.0, gpl-3.0)
- `--author, -a NAME` Name of the author/copyright holder
- `--year, -y YEAR` Year for the copyright notice (defaults to current year)
- `--output, -o FILE` Output file path (default: LICENSE)
Example:
```bash
# List available licenses
devtools license list
# Interactive mode
devtools license generate
# With all options specified
devtools license generate --type mit --author "John Doe" --year 2024 --output LICENSE
```
The license generator uses GitHub's license API to fetch templates. For optimal performance:
1. Set up a GitHub token:
```bash
devtools config set GITHUB_TOKEN "your-github-token"
```
This increases your API rate limit from 60 to 5,000 requests per hour.
2. If no token is set, the tool will use a fallback list of common licenses.
If an invalid license type is provided, the tool will display a list of available licenses.
---
## Features ## Features
- **Commit Message Generator:** - **Commit Message Generator:**
@@ -292,6 +346,11 @@ The generator uses the gitignore.io API to fetch templates. No API key is requir
- Uses gitignore.io API for up-to-date templates - Uses gitignore.io API for up-to-date templates
- No API key required - No API key required
- Falls back to generic template if API is unavailable - Falls back to generic template if API is unavailable
- **License Generator:**
- Generates LICENSE files using GitHub's license API
- Supports all licenses available on GitHub
- Interactive license selection
- Automatic year and author replacement
## Requirements ## Requirements
@@ -303,6 +362,7 @@ The generator uses the gitignore.io API to fetch templates. No API key is requir
- Google API key - Google API key
- Anthropic API key - Anthropic API key
- Hugging Face API key - Hugging Face API key
- GitHub token (recommended for license generator)
## Development ## Development
+266 -72
View File
@@ -1,12 +1,13 @@
""" """
Changelog generation CLI. Changelog generation CLI.
""" """
import os
import click import click
from rich.console import Console from rich.console import Console
from rich.prompt import Prompt, Confirm from rich.prompt import Prompt, Confirm
from rich.progress import Progress, SpinnerColumn, TextColumn from rich.progress import Progress, SpinnerColumn, TextColumn
from .generator import ChangelogGenerator from .generator import ChangelogGenerator
from ..commitgen.config import CommitGenConfig from ..shared.config import Config
console = Console() console = Console()
@@ -16,96 +17,289 @@ def cli():
pass pass
@cli.command() @cli.command()
@click.option("--version", "-v", required=True, help="Version number") @click.option("--version", "-v", required=True, help="Version number for the changelog entry")
@click.option("--from-tag", "-t", help="Generate changelog from this tag")
@click.option("--days", "-d", type=int, help="Generate changelog from the last N days")
@click.option("--commits", "-n", type=int, help="Generate changelog from the last N commits")
@click.option("--output", "-o", default="CHANGELOG.md", help="Output file path") @click.option("--output", "-o", default="CHANGELOG.md", help="Output file path")
@click.option("--temperature", "-t", type=float, default=0.7, help="AI temperature") @click.option("--temperature", type=float, default=0.7, help="AI temperature (0.0-1.0)")
def generate(version: str, output: str, temperature: float): def generate(version: str, from_tag: str, days: int, commits: int, output: str, temperature: float):
"""Generate a changelog interactively.""" """Generate a changelog from git history."""
with Progress( try:
SpinnerColumn(), # Get configuration
TextColumn("[progress.description]{task.description}"), config = Config()
console=console
) as progress:
# Initialize services
progress.add_task("Initializing...", total=None)
config = CommitGenConfig()
generator = ChangelogGenerator(config)
# Collect changes # Validate version format
console.print("\n[bold]Enter your changes (one per line). Start each line with an emoji to indicate the type:[/]") if not version.startswith("v"):
console.print("✨ Added") version = f"v{version}"
console.print("🔄 Changed")
console.print("🐛 Fixed")
console.print("🚀 Performance")
console.print("📝 Documentation")
console.print("🔧 Maintenance")
console.print("🗑️ Removed")
console.print("🔒 Security")
console.print("\nPress Ctrl+D (Unix) or Ctrl+Z (Windows) when done.\n")
changes_text = [] # Get git history
while True: if from_tag:
try: # Get commits since tag
line = Prompt.ask("") cmd = f"git log {from_tag}..HEAD --pretty=format:%s"
if line: elif days:
changes_text.append(line) # Get commits from last N days
except EOFError: cmd = f"git log --since='{days} days ago' --pretty=format:%s"
break elif commits:
# Get last N commits
cmd = f"git log -n {commits} --pretty=format:%s"
else:
# Get all commits
cmd = "git log --pretty=format:%s"
if not changes_text: # Execute git command
console.print("[yellow]No changes provided. Exiting.") result = os.popen(cmd).read().strip()
if not result:
console.print("[yellow]No commits found in the specified range")
return return
# Parse changes # Split into individual commits
progress.add_task("Parsing changes...", total=None) commit_messages = [msg.strip() for msg in result.split("\n") if msg.strip()]
changes = generator.parse_changes_from_text("\n".join(changes_text))
# Group commits by type
groups = {
"✨ Added": [],
"🔄 Changed": [],
"🐛 Fixed": [],
"🚀 Performance": [],
"📝 Documentation": [],
"🔧 Maintenance": [],
"🗑️ Removed": [],
"🔒 Security": []
}
# Map commit types to groups
type_map = {
"feat": "✨ Added",
"add": "✨ Added",
"new": "✨ Added",
"change": "🔄 Changed",
"update": "🔄 Changed",
"fix": "🐛 Fixed",
"bug": "🐛 Fixed",
"perf": "🚀 Performance",
"docs": "📝 Documentation",
"chore": "🔧 Maintenance",
"refactor": "🔧 Maintenance",
"remove": "🗑️ Removed",
"delete": "🗑️ Removed",
"security": "🔒 Security"
}
# Categorize commits
for msg in commit_messages:
msg_lower = msg.lower()
categorized = False
# Check for type prefixes
for type_key, group in type_map.items():
if msg_lower.startswith(type_key):
groups[group].append(msg)
categorized = True
break
# If not categorized, check for keywords
if not categorized:
for type_key, group in type_map.items():
if type_key in msg_lower:
groups[group].append(msg)
break
else:
# Default to maintenance if no match
groups["🔧 Maintenance"].append(msg)
# Generate changelog # Generate changelog
progress.add_task("Generating changelog...", total=None) changelog = f"# Changelog\n\n## {version}\n\n"
generator.update_changelog_file(version, changes, output, temperature)
console.print(f"\n[green]Generated changelog at {output}") # Add each group
for group, messages in groups.items():
if messages:
changelog += f"### {group}\n\n"
for msg in messages:
changelog += f"- {msg}\n"
changelog += "\n"
# Write to file
with open(output, "w") as f:
f.write(changelog)
console.print(f"[green]✓[/green] Changelog generated successfully at: {output}")
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
@cli.command() @cli.command()
@click.option("--version", "-v", required=True, help="Version number") @click.option("--version", "-v", required=True, help="Version number for the changelog entry")
@click.option("--input", "-i", required=True, help="Input file with changes")
@click.option("--output", "-o", default="CHANGELOG.md", help="Output file path") @click.option("--output", "-o", default="CHANGELOG.md", help="Output file path")
@click.option("--temperature", "-t", type=float, default=0.7, help="AI temperature") @click.option("--temperature", type=float, default=0.7, help="AI temperature (0.0-1.0)")
def generate_from_file(version: str, input: str, output: str, temperature: float): def generate_interactive(version: str, output: str, temperature: float):
"""Generate a changelog from a file.""" """Generate a changelog interactively."""
with Progress( try:
SpinnerColumn(), # Get configuration
TextColumn("[progress.description]{task.description}"), config = Config()
console=console
) as progress:
# Initialize services
progress.add_task("Initializing...", total=None)
config = CommitGenConfig()
generator = ChangelogGenerator(config)
# Read changes from file # Validate version format
progress.add_task("Reading changes...", total=None) if not version.startswith("v"):
try: version = f"v{version}"
with open(input, "r") as f:
changes_text = f.read()
except FileNotFoundError:
console.print(f"[red]Input file not found: {input}")
return
# Parse changes # Initialize groups
progress.add_task("Parsing changes...", total=None) groups = {
changes = generator.parse_changes_from_text(changes_text) "✨ Added": [],
"🔄 Changed": [],
"🐛 Fixed": [],
"🚀 Performance": [],
"📝 Documentation": [],
"🔧 Maintenance": [],
"🗑️ Removed": [],
"🔒 Security": []
}
if not changes: console.print("\n[bold cyan]Enter your changes (press Enter twice to finish):[/bold cyan]")
console.print("[yellow]No changes found in input file.") console.print("[dim]Start each line with an emoji to categorize it:[/dim]")
return console.print("✨ - Added")
console.print("🔄 - Changed")
console.print("🐛 - Fixed")
console.print("🚀 - Performance")
console.print("📝 - Documentation")
console.print("🔧 - Maintenance")
console.print("🗑️ - Removed")
console.print("🔒 - Security")
console.print("\n[dim]Example: ✨ Added new feature X[/dim]\n")
while True:
line = click.prompt("", default="", show_default=False)
if not line:
break
# Categorize based on emoji
for group in groups:
if line.startswith(group.split()[0]):
groups[group].append(line)
break
else:
# Default to maintenance if no emoji
groups["🔧 Maintenance"].append(line)
# Generate changelog # Generate changelog
progress.add_task("Generating changelog...", total=None) changelog = f"# Changelog\n\n## {version}\n\n"
generator.update_changelog_file(version, changes, output, temperature)
console.print(f"\n[green]Generated changelog at {output}") # Add each group
for group, messages in groups.items():
if messages:
changelog += f"### {group}\n\n"
for msg in messages:
changelog += f"- {msg}\n"
changelog += "\n"
# Write to file
with open(output, "w") as f:
f.write(changelog)
console.print(f"[green]✓[/green] Changelog generated successfully at: {output}")
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
@cli.command()
@click.option("--version", "-v", required=True, help="Version number for the changelog entry")
@click.option("--input", "-i", required=True, help="Input file with changes")
@click.option("--output", "-o", default="CHANGELOG.md", help="Output file path")
@click.option("--temperature", type=float, default=0.7, help="AI temperature (0.0-1.0)")
def generate_from_file(version: str, input: str, output: str, temperature: float):
"""Generate a changelog from a file."""
try:
# Get configuration
config = Config()
# Validate version format
if not version.startswith("v"):
version = f"v{version}"
# Read input file
with open(input, "r") as f:
changes = f.read().strip()
if not changes:
console.print("[yellow]No changes found in input file")
return
# Split into lines
lines = [line.strip() for line in changes.split("\n") if line.strip()]
# Initialize groups
groups = {
"✨ Added": [],
"🔄 Changed": [],
"🐛 Fixed": [],
"🚀 Performance": [],
"📝 Documentation": [],
"🔧 Maintenance": [],
"🗑️ Removed": [],
"🔒 Security": []
}
# Categorize changes
for line in lines:
line_lower = line.lower()
categorized = False
# Check for emoji prefixes
for group in groups:
if line.startswith(group.split()[0]):
groups[group].append(line)
categorized = True
break
# If not categorized, check for keywords
if not categorized:
type_map = {
"add": "✨ Added",
"new": "✨ Added",
"change": "🔄 Changed",
"update": "🔄 Changed",
"fix": "🐛 Fixed",
"bug": "🐛 Fixed",
"perf": "🚀 Performance",
"docs": "📝 Documentation",
"chore": "🔧 Maintenance",
"refactor": "🔧 Maintenance",
"remove": "🗑️ Removed",
"delete": "🗑️ Removed",
"security": "🔒 Security"
}
for type_key, group in type_map.items():
if type_key in line_lower:
groups[group].append(line)
break
else:
# Default to maintenance if no match
groups["🔧 Maintenance"].append(line)
# Generate changelog
changelog = f"# Changelog\n\n## {version}\n\n"
# Add each group
for group, messages in groups.items():
if messages:
changelog += f"### {group}\n\n"
for msg in messages:
changelog += f"- {msg}\n"
changelog += "\n"
# Write to file
with open(output, "w") as f:
f.write(changelog)
console.print(f"[green]✓[/green] Changelog generated successfully at: {output}")
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
# Add command aliases # Add command aliases
cli.add_command(generate, name="g") cli.add_command(generate, name="g")
cli.add_command(generate_interactive, name="i")
cli.add_command(generate_from_file, name="f") cli.add_command(generate_from_file, name="f")
if __name__ == "__main__":
cli()
+23 -34
View File
@@ -1,13 +1,11 @@
""" """
Changelog generation using AI. Changelog generation using AI.
""" """
from typing import List, Dict, Optional from typing import List, Dict, Optional
from ..shared.ai import AIService from ..shared.ai import AIService
from ..shared.config import Config from ..shared.config import Config
from ..shared.git import GitService from ..shared.git import GitService
class ChangelogGenerator(AIService): class ChangelogGenerator(AIService):
"""AI-powered changelog generator.""" """AI-powered changelog generator."""
@@ -39,12 +37,7 @@ class ChangelogGenerator(AIService):
raise ValueError("GitService not provided") raise ValueError("GitService not provided")
return self.git_service.get_commit_history(limit=n) return self.git_service.get_commit_history(limit=n)
def generate_changelog( def generate_changelog(self, version: str, changes: List[Dict[str, str]], temperature: Optional[float] = None) -> str:
self,
version: str,
changes: List[Dict[str, str]],
temperature: Optional[float] = None,
) -> str:
"""Generate a changelog from a list of changes. """Generate a changelog from a list of changes.
Args: Args:
@@ -72,23 +65,20 @@ class ChangelogGenerator(AIService):
- 🔒 Security""" - 🔒 Security"""
# Format changes for the prompt # Format changes for the prompt
changes_text = "\n".join(f"{change['message']}" for change in changes) changes_text = "\n".join(
f"{change['message']}"
user_prompt = f"Generate a changelog for version { for change in changes
version
} with these changes:\n\n{changes_text}"
return self.generate_completion(
system_prompt, user_prompt, temperature=temperature
) )
def update_changelog_file( user_prompt = f"Generate a changelog for version {version} with these changes:\n\n{changes_text}"
self,
version: str, return self.generate_completion(
changes: List[Dict[str, str]], system_prompt,
output_file: str, user_prompt,
temperature: Optional[float] = None, temperature=temperature
) -> None: )
def update_changelog_file(self, version: str, changes: List[Dict[str, str]], output_file: str, temperature: Optional[float] = None) -> None:
"""Generate and update a changelog file. """Generate and update a changelog file.
Args: Args:
@@ -142,23 +132,21 @@ class ChangelogGenerator(AIService):
"📝": "Documentation", "📝": "Documentation",
"🔧": "Maintenance", "🔧": "Maintenance",
"🗑️": "Removed", "🗑️": "Removed",
"🔒": "Security", "🔒": "Security"
} }
for marker, type_ in type_markers.items(): for marker, type_ in type_markers.items():
if line.startswith(marker): if line.startswith(marker):
# Save previous change if exists # Save previous change if exists
if current_type and current_description: if current_type and current_description:
changes.append( changes.append({
{ "type": current_type,
"type": current_type, "description": " ".join(current_description)
"description": " ".join(current_description), })
}
)
# Start new change # Start new change
current_type = type_ current_type = type_
current_description = [line[len(marker) :].strip()] current_description = [line[len(marker):].strip()]
break break
else: else:
# Continue current change # Continue current change
@@ -167,8 +155,9 @@ class ChangelogGenerator(AIService):
# Add last change if exists # Add last change if exists
if current_type and current_description: if current_type and current_description:
changes.append( changes.append({
{"type": current_type, "description": " ".join(current_description)} "type": current_type,
) "description": " ".join(current_description)
})
return changes return changes
+6 -2
View File
@@ -7,12 +7,14 @@ from rich.table import Table
from .shared.config import Config from .shared.config import Config
from .gitignore.cli import cli as gitignore_cli from .gitignore.cli import cli as gitignore_cli
from .commitgen.cli import cli as commit_cli from .commitgen.cli import cli as commit_cli
from .licensegen.cli import license as license_cli
from .changelog.cli import cli as changelog_cli
console = Console() console = Console()
@click.group() @click.group()
def cli(): def cli():
"""Developer tools CLI.""" """DevTools - A collection of developer tools."""
pass pass
@cli.group() @cli.group()
@@ -70,8 +72,10 @@ def clear():
console.print("[green]Cleared all configuration") console.print("[green]Cleared all configuration")
# Add subcommands # Add subcommands
cli.add_command(gitignore_cli, name="gitignore")
cli.add_command(commit_cli, name="commit") cli.add_command(commit_cli, name="commit")
cli.add_command(changelog_cli, name="changelog")
cli.add_command(gitignore_cli, name="gitignore")
cli.add_command(license_cli, name="license")
if __name__ == "__main__": if __name__ == "__main__":
cli() cli()
+33 -82
View File
@@ -1,7 +1,6 @@
""" """
Command-line interface for commitgen tool. Command-line interface for commitgen tool.
""" """
import click import click
from rich.console import Console from rich.console import Console
from rich.prompt import Prompt from rich.prompt import Prompt
@@ -18,47 +17,27 @@ import os
console = Console() console = Console()
@click.group() @click.group()
def cli(): def cli():
"""Generate commit messages and changelogs using AI.""" """Generate commit messages and changelogs using AI."""
pass pass
@cli.command() @cli.command()
@click.option( @click.option('--files', '-f', multiple=True, help='Specific files to generate commit messages for')
"--files", @click.option('--repo', '-r', help='Repository path')
"-f", @click.option('--commit', '-c', is_flag=True, help='Automatically commit changes')
multiple=True, @click.option('--push', '-p', is_flag=True, help='Push changes after commit')
help="Specific files to generate commit messages for", @click.option('--conventional/--no-conventional', default=True, help='Use conventional commit format')
) @click.option('--no-stage', is_flag=True, help='Skip automatic staging of changes')
@click.option("--repo", "-r", help="Repository path") @click.option('--sign', is_flag=True, help='Sign commits with GPG')
@click.option("--commit", "-c", is_flag=True, help="Automatically commit changes") @click.option('--temperature', type=float, help='AI temperature (0.0-1.0)')
@click.option("--push", "-p", is_flag=True, help="Push changes after commit") def generate(files: tuple, repo: str, commit: bool, push: bool, conventional: bool, no_stage: bool, sign: bool, temperature: float):
@click.option(
"--conventional/--no-conventional",
default=True,
help="Use conventional commit format",
)
@click.option("--no-stage", is_flag=True, help="Skip automatic staging of changes")
@click.option("--sign", is_flag=True, help="Sign commits with GPG")
@click.option("--temperature", type=float, help="AI temperature (0.0-1.0)")
def generate(
files: tuple,
repo: str,
commit: bool,
push: bool,
conventional: bool,
no_stage: bool,
sign: bool,
temperature: float,
):
"""Generate commit messages for staged changes""" """Generate commit messages for staged changes"""
try: try:
with Progress( with Progress(
SpinnerColumn(), SpinnerColumn(),
TextColumn("[progress.description]{task.description}"), TextColumn("[progress.description]{task.description}"),
console=console, console=console
) as progress: ) as progress:
# Initialize services # Initialize services
config = Config() config = Config()
@@ -82,9 +61,7 @@ def generate(
# Generate commit message # Generate commit message
task = progress.add_task("Generating commit message...", total=None) task = progress.add_task("Generating commit message...", total=None)
commit_message = ai_service.generate_commit_message( commit_message = ai_service.generate_commit_message(staged_changes, temperature)
staged_changes, temperature
)
progress.update(task, completed=True) progress.update(task, completed=True)
# Show preview and confirm # Show preview and confirm
@@ -103,46 +80,31 @@ def generate(
console.print("[green]Changes committed successfully![/green]") console.print("[green]Changes committed successfully![/green]")
else: else:
console.print( console.print("[yellow]Use --commit to apply the commit message.[/yellow]")
"[yellow]Use --commit to apply the commit message.[/yellow]"
)
except Exception as e: except Exception as e:
console.print(f"[red]Error: {str(e)}[/red]") console.print(f"[red]Error: {str(e)}[/red]")
raise click.Abort() raise click.Abort()
@cli.group() @cli.group()
def changelog(): def changelog():
"""Generate and manage changelogs""" """Generate and manage changelogs"""
pass pass
@changelog.command(name='generate')
@changelog.command(name="generate") @click.option('--version', '-v', required=True, help='Version number for the changelog entry')
@click.option( @click.option('--from-tag', '-t', help='Generate changelog from this tag')
"--version", "-v", required=True, help="Version number for the changelog entry" @click.option('--days', '-d', type=int, help='Generate changelog from the last N days')
) @click.option('--commits', '-n', type=int, help='Generate changelog from the last N commits')
@click.option("--from-tag", "-t", help="Generate changelog from this tag") @click.option('--output', '-o', help='Output file path (default: CHANGELOG.md)')
@click.option("--days", "-d", type=int, help="Generate changelog from the last N days") @click.option('--temperature', type=float, help='AI temperature (0.0-1.0)')
@click.option( def generate_log(version: str, from_tag: str, days: int, commits: int, output: str, temperature: float):
"--commits", "-n", type=int, help="Generate changelog from the last N commits"
)
@click.option("--output", "-o", help="Output file path (default: CHANGELOG.md)")
@click.option("--temperature", type=float, help="AI temperature (0.0-1.0)")
def generate_log(
version: str,
from_tag: str,
days: int,
commits: int,
output: str,
temperature: float,
):
"""Generate a changelog from git history""" """Generate a changelog from git history"""
try: try:
with Progress( with Progress(
SpinnerColumn(), SpinnerColumn(),
TextColumn("[progress.description]{task.description}"), TextColumn("[progress.description]{task.description}"),
console=console, console=console
) as progress: ) as progress:
# Initialize services # Initialize services
config = Config() config = Config()
@@ -165,9 +127,7 @@ def generate_log(
progress.update(task, completed=True) progress.update(task, completed=True)
if not entries: if not entries:
console.print( console.print("[yellow]No conventional commits found in the specified range.[/yellow]")
"[yellow]No conventional commits found in the specified range.[/yellow]"
)
return return
task = progress.add_task("Generating changelog...", total=None) task = progress.add_task("Generating changelog...", total=None)
@@ -175,24 +135,20 @@ def generate_log(
changelog_gen.update_changelog_file(version, entries, output_path) changelog_gen.update_changelog_file(version, entries, output_path)
progress.update(task, completed=True) progress.update(task, completed=True)
console.print( console.print(f"[green]Changelog generated successfully at {output_path}![/green]")
f"[green]Changelog generated successfully at {output_path}![/green]"
)
except Exception as e: except Exception as e:
console.print(f"[red]Error: {str(e)}[/red]") console.print(f"[red]Error: {str(e)}[/red]")
raise click.Abort() raise click.Abort()
@cli.group() @cli.group()
def config(): def config():
"""Manage configuration""" """Manage configuration"""
pass pass
@config.command() @config.command()
@click.option("--key", "-k", required=True, help="Configuration key") @click.option('--key', '-k', required=True, help='Configuration key')
@click.option("--value", "-v", required=True, help="Configuration value") @click.option('--value', '-v', required=True, help='Configuration value')
def set(key: str, value: str): def set(key: str, value: str):
"""Set configuration value""" """Set configuration value"""
try: try:
@@ -203,24 +159,20 @@ def set(key: str, value: str):
console.print(f"[red]Error: {str(e)}[/red]") console.print(f"[red]Error: {str(e)}[/red]")
raise click.Abort() raise click.Abort()
@config.command() @config.command()
def show(): def show():
"""Show current configuration""" """Show current configuration"""
try: try:
config = Config() config = Config()
console.print( console.print(Panel(
Panel( "\n".join(f"{k}: {v}" for k, v in config.get_all().items()),
"\n".join(f"{k}: {v}" for k, v in config.get_all().items()), title="[blue]Current Configuration[/blue]",
title="[blue]Current Configuration[/blue]", border_style="blue"
border_style="blue", ))
)
)
except Exception as e: except Exception as e:
console.print(f"[red]Error: {str(e)}[/red]") console.print(f"[red]Error: {str(e)}[/red]")
raise click.Abort() raise click.Abort()
@cli.command() @cli.command()
def status(): def status():
"""Show the current state of the repository.""" """Show the current state of the repository."""
@@ -283,11 +235,10 @@ def status():
console.print(f"[red]Error: {str(e)}[/red]") console.print(f"[red]Error: {str(e)}[/red]")
raise click.Abort() raise click.Abort()
# Add command aliases # Add command aliases
cli.add_command(generate, name="g") cli.add_command(generate, name='g')
cli.add_command(config, name="c") cli.add_command(config, name='c')
cli.add_command(changelog, name="log") cli.add_command(changelog, name='log')
if __name__ == "__main__": if __name__ == "__main__":
cli() cli()
+5
View File
@@ -35,6 +35,11 @@ class CommitGenGitService(GitService):
if not self.commit(message, sign=sign): if not self.commit(message, sign=sign):
raise Exception("Failed to commit changes") raise Exception("Failed to commit changes")
def push_changes(self) -> None:
"""Push changes to the current branch."""
if not self.push():
raise Exception("Failed to push changes")
def get_recent_commits(self, limit: int = 10) -> List[str]: def get_recent_commits(self, limit: int = 10) -> List[str]:
"""Get recent commit messages.""" """Get recent commit messages."""
commits = self.get_commit_history(limit=limit) commits = self.get_commit_history(limit=limit)
+5
View File
@@ -0,0 +1,5 @@
"""License generator module for DevTools."""
from .generator import generate_license
__all__ = ["generate_license"]
+249
View File
@@ -0,0 +1,249 @@
"""License generator CLI."""
import os
import click
from rich.console import Console
from rich.table import Table
from rich.prompt import Confirm, Prompt
from rich.panel import Panel
from ..shared.config import Config
from .generator import license_generator, generate_license
import re
console = Console()
@click.group()
def license():
"""License generation commands."""
pass
@license.command()
@click.option("--type", "-t", help="Type of license to generate")
@click.option("--author", "-a", help="Name of the author/copyright holder")
@click.option("--year", "-y", type=int, help="Year for the copyright notice")
@click.option("--output", "-o", default="LICENSE", help="Output file path")
@click.option("--multi", "-m", is_flag=True, help="Generate multiple licenses")
def generate(type: str, author: str, year: int, output: str, multi: bool):
"""Generate a license file."""
try:
# If no author specified, prompt for it
if not author:
author = click.prompt("Enter author name")
# Fetch available licenses
licenses = license_generator.fetch_available_licenses()
if not licenses:
console.print("[yellow]No licenses available")
return
# Create selection table
table = Table(show_header=True, header_style="bold magenta")
table.add_column("No.", style="dim", width=4)
table.add_column("License Key", style="dim", width=15)
table.add_column("Name", width=30)
table.add_column("Permissions", width=40)
# Add rows with numbers
for i, license in enumerate(licenses, 1):
table.add_row(
str(i),
license["key"],
license["name"],
format_permissions(license.get("permissions", []))
)
# Display table
console.print("\nSelect license(s) to generate:")
console.print(table)
if multi:
# Get user selection for multiple licenses
while True:
try:
selection = click.prompt("Enter license numbers (e.g., 1,3,5)").split(",")
selected_indices = [int(s.strip()) for s in selection if s.strip()]
# Validate selection
if not selected_indices:
console.print("[yellow]No licenses selected")
continue
if any(i < 1 or i > len(licenses) for i in selected_indices):
console.print("[red]Invalid selection. Please enter valid numbers.")
continue
# Get selected licenses
selected_licenses = [licenses[i-1] for i in selected_indices]
# Show confirmation
console.print("\nSelected licenses:")
for license in selected_licenses:
console.print(f"- {license['name']} ({license['key']})")
if Confirm.ask("\nGenerate these licenses?"):
break
else:
console.print("\nPlease select licenses again:")
continue
except ValueError:
console.print("[red]Invalid input. Please enter numbers separated by commas.")
continue
else:
# Get user selection for single license
while True:
try:
selection = click.prompt("Enter license number")
selected_index = int(selection.strip())
# Validate selection
if selected_index < 1 or selected_index > len(licenses):
console.print("[red]Invalid selection. Please enter a valid number.")
continue
# Get selected license
selected_license = licenses[selected_index - 1]
# Show confirmation
console.print(f"\nSelected license: {selected_license['name']} ({selected_license['key']})")
if Confirm.ask("\nGenerate this license?"):
selected_licenses = [selected_license]
break
else:
console.print("\nPlease select a license again:")
continue
except ValueError:
console.print("[red]Invalid input. Please enter a number.")
continue
# Generate each license
for license in selected_licenses:
license_type = license["key"]
# Generate output filename
if len(selected_licenses) == 1:
output_file = output
else:
base, ext = os.path.splitext(output)
output_file = f"{base}_{license_type}{ext}"
try:
output_path = generate_license(
license_type=license_type,
author=author,
year=year,
output_file=output_file
)
console.print(f"[green]✓[/green] Generated {license_type} license at: {output_path}")
except ValueError as e:
console.print(f"[red]Error generating {license_type} license:[/red] {str(e)}")
continue
# Create a combined README section
if len(selected_licenses) > 1:
readme_path = "LICENSE.md"
with open(readme_path, "w") as f:
f.write("# Licenses\n\n")
f.write("This project is licensed under multiple licenses:\n\n")
for license in selected_licenses:
f.write(f"- [{license['name']}](LICENSE_{license['key']})\n")
console.print(f"\n[green]✓[/green] Created license summary at: {readme_path}")
except ValueError as e:
console.print(f"[red]Error:[/red] {str(e)}")
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
@license.command()
def list():
"""List available licenses."""
show_licenses()
def format_permissions(permissions: list) -> str:
"""Format permissions list into a readable string."""
if not permissions:
return "N/A"
# Map permission keys to readable names
permission_map = {
"commercial-use": "Commercial Use",
"modifications": "Modifications",
"distribution": "Distribution",
"private-use": "Private Use",
"patent-use": "Patent Use"
}
# Convert each permission to its readable name
readable_permissions = [
permission_map.get(perm, perm.replace("-", " ").title())
for perm in permissions
]
return ", ".join(readable_permissions)
def truncate_description(description: str, max_length: int = 60) -> str:
"""Truncate description to a maximum length and add ellipsis if needed."""
if not description:
return "No description available"
# Remove HTML tags
description = re.sub(r'<[^>]+>', '', description)
# Remove URLs
description = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', description)
# Clean up whitespace
description = ' '.join(description.split())
if len(description) <= max_length:
return description
# Find the last space before max_length
last_space = description[:max_length].rfind(" ")
if last_space == -1:
last_space = max_length
return description[:last_space] + "..."
def show_licenses():
"""Display available licenses in a table."""
try:
# Load token from config
config = Config()
github_token = config.get("github_token")
if github_token:
os.environ["GITHUB_TOKEN"] = github_token
# Fetch available licenses
licenses = license_generator.fetch_available_licenses()
if not licenses:
console.print("[yellow]No licenses available")
return
# Create table
table = Table(show_header=True, header_style="bold magenta")
table.add_column("License Key", style="dim", width=15)
table.add_column("Name", width=30)
table.add_column("Permissions", width=40)
# Add rows
for license in licenses:
table.add_row(
license["key"],
license["name"],
format_permissions(license.get("permissions", []))
)
# Display table
console.print("\nAvailable Licenses:")
console.print(table)
console.print("\nTo generate a license, use: [bold]devtools license generate[/bold]")
console.print("To generate multiple licenses, use: [bold]devtools license generate --multi[/bold]")
except Exception as e:
console.print(f"[red]Error:[/red] {str(e)}")
if __name__ == "__main__":
license()
+130
View File
@@ -0,0 +1,130 @@
"""License generator module."""
import os
import requests
from typing import Dict, List, Optional
from ..shared.config import Config
class LicenseGenerator:
"""License generator using GitHub API."""
def __init__(self):
"""Initialize the license generator."""
self.api_base_url = "https://api.github.com"
self.config = Config()
def _get_headers(self) -> Dict[str, str]:
"""Get headers for API requests."""
# Try to get token from config first
token = self.config.get("github_token")
# Then try environment variable
if not token:
token = os.environ.get("GITHUB_TOKEN")
headers = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "DevTools/1.0"
}
if token:
headers["Authorization"] = f"Bearer {token}"
return headers
def fetch_available_licenses(self) -> List[Dict]:
"""Fetch available licenses from GitHub API."""
try:
# Get headers with token
headers = self._get_headers()
# First check rate limit
rate_limit_response = requests.get(
f"{self.api_base_url}/rate_limit",
headers=headers
)
if rate_limit_response.status_code == 200:
rate_limit_data = rate_limit_response.json()
# Check if we have remaining requests
remaining = rate_limit_data.get("resources", {}).get("core", {}).get("remaining", 0)
if remaining == 0:
raise ValueError("GitHub API rate limit exceeded. Please set a GitHub token using:\ndevtools config set GITHUB_TOKEN YOUR_GITHUB_TOKEN")
# Fetch list of licenses
response = requests.get(
f"{self.api_base_url}/licenses",
headers=headers
)
if response.status_code == 403:
raise ValueError("GitHub API rate limit exceeded. Please set a GitHub token using:\ndevtools config set GITHUB_TOKEN YOUR_GITHUB_TOKEN")
response.raise_for_status()
licenses = response.json()
# Fetch detailed info for each license
detailed_licenses = []
for license in licenses:
try:
license_response = requests.get(
f"{self.api_base_url}/licenses/{license['key']}",
headers=headers
)
if license_response.status_code == 200:
license_data = license_response.json()
detailed_licenses.append({
"key": license_data["key"],
"name": license_data["name"],
"description": license_data.get("description", "No description available"),
"permissions": license_data.get("permissions", []),
"conditions": license_data.get("conditions", []),
"limitations": license_data.get("limitations", [])
})
except Exception:
continue
return detailed_licenses
except requests.exceptions.RequestException as e:
raise ValueError(f"Error fetching licenses: {str(e)}")
def get_license_template(self, license_type: str) -> str:
"""Get license template from GitHub API."""
try:
response = requests.get(
f"{self.api_base_url}/licenses/{license_type}",
headers=self._get_headers()
)
response.raise_for_status()
return response.json()["body"]
except requests.exceptions.RequestException as e:
raise ValueError(f"Error fetching license template: {str(e)}")
def generate_license(self, license_type: str, author: str, year: Optional[int] = None) -> str:
"""Generate license content with author and year."""
template = self.get_license_template(license_type)
# Replace placeholders
content = template.replace("[year]", str(year) if year else "")
content = content.replace("[fullname]", author)
return content
# Create a singleton instance
license_generator = LicenseGenerator()
def generate_license(license_type: str, author: str, year: Optional[int] = None, output_file: str = "LICENSE") -> str:
"""Generate a license file."""
try:
# Generate license content
content = license_generator.generate_license(license_type, author, year)
# Write to file
with open(output_file, "w") as f:
f.write(content)
return output_file
except Exception as e:
raise ValueError(f"Error generating license: {str(e)}")
+114 -177
View File
@@ -1,14 +1,12 @@
""" """
Shared AI service for devtools. Shared AI service for devtools.
""" """
import requests import requests
import os import os
from typing import List, Dict, Optional, Any from typing import List, Dict, Optional, Any
from abc import ABC, abstractmethod from abc import ABC, abstractmethod
from .config import BaseConfig from .config import BaseConfig
class AIProvider(ABC): class AIProvider(ABC):
"""Base class for AI providers.""" """Base class for AI providers."""
@@ -18,18 +16,15 @@ class AIProvider(ABC):
pass pass
@abstractmethod @abstractmethod
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
"""Generate a completion from the AI model.""" """Generate a completion from the AI model."""
pass pass
class OpenRouterProvider(AIProvider): class OpenRouterProvider(AIProvider):
"""OpenRouter AI provider implementation.""" """OpenRouter AI provider implementation."""
@@ -37,9 +32,7 @@ class OpenRouterProvider(AIProvider):
self.config = config self.config = config
self.api_key = config.get_env_or_config("OPENROUTER_API_KEY") self.api_key = config.get_env_or_config("OPENROUTER_API_KEY")
if not self.api_key: if not self.api_key:
raise ValueError( raise ValueError("OpenRouter API key not found. Please set it in config or environment.")
"OpenRouter API key not found. Please set it in config or environment."
)
self.model = config.get("model", "mistralai/mixtral-8x7b-instruct") self.model = config.get("model", "mistralai/mixtral-8x7b-instruct")
self.api_url = "https://openrouter.ai/api/v1/chat/completions" self.api_url = "https://openrouter.ai/api/v1/chat/completions"
@@ -47,38 +40,26 @@ class OpenRouterProvider(AIProvider):
"Authorization": f"Bearer {self.api_key}", "Authorization": f"Bearer {self.api_key}",
"HTTP-Referer": "https://github.com/S4NKALP/DevTools", "HTTP-Referer": "https://github.com/S4NKALP/DevTools",
"X-Title": "DevTools", "X-Title": "DevTools",
"Content-Type": "application/json", "Content-Type": "application/json"
} }
def _create_prompt( def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
self, system_prompt: str, user_prompt: str
) -> List[Dict[str, str]]:
return [ return [
{"role": "system", "content": system_prompt}, {"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}, {"role": "user", "content": user_prompt}
] ]
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
messages = self._create_prompt(system_prompt, user_prompt) messages = self._create_prompt(system_prompt, user_prompt)
try: try:
temp = ( temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
temperature tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
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 = { payload = {
"model": self.model, "model": self.model,
@@ -86,13 +67,16 @@ class OpenRouterProvider(AIProvider):
"temperature": temp, "temperature": temp,
"max_tokens": tokens, "max_tokens": tokens,
"top_p": float(top_p), "top_p": float(top_p),
"stream": False, "stream": False
} }
payload = {k: v for k, v in payload.items() if v is not None} payload = {k: v for k, v in payload.items() if v is not None}
response = requests.post( 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: if response.status_code != 200:
@@ -115,7 +99,6 @@ class OpenRouterProvider(AIProvider):
except Exception as e: except Exception as e:
raise Exception(f"AI generation failed: {str(e)}") raise Exception(f"AI generation failed: {str(e)}")
class OpenAIProvider(AIProvider): class OpenAIProvider(AIProvider):
"""OpenAI provider implementation.""" """OpenAI provider implementation."""
@@ -123,59 +106,48 @@ class OpenAIProvider(AIProvider):
self.config = config self.config = config
self.api_key = config.get_env_or_config("OPENAI_API_KEY") self.api_key = config.get_env_or_config("OPENAI_API_KEY")
if not self.api_key: if not self.api_key:
raise ValueError( raise ValueError("OpenAI API key not found. Please set it in config or environment.")
"OpenAI API key not found. Please set it in config or environment."
)
self.model = config.get("model", "gpt-4-turbo-preview") self.model = config.get("model", "gpt-4-turbo-preview")
self.api_url = "https://api.openai.com/v1/chat/completions" self.api_url = "https://api.openai.com/v1/chat/completions"
self.headers = { self.headers = {
"Authorization": f"Bearer {self.api_key}", "Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json", "Content-Type": "application/json"
} }
def _create_prompt( def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
self, system_prompt: str, user_prompt: str
) -> List[Dict[str, str]]:
return [ return [
{"role": "system", "content": system_prompt}, {"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}, {"role": "user", "content": user_prompt}
] ]
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
messages = self._create_prompt(system_prompt, user_prompt) messages = self._create_prompt(system_prompt, user_prompt)
try: try:
temp = ( temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
temperature tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
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 = { payload = {
"model": self.model, "model": self.model,
"messages": messages, "messages": messages,
"temperature": temp, "temperature": temp,
"max_tokens": tokens, "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} payload = {k: v for k, v in payload.items() if v is not None}
response = requests.post( 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: if response.status_code != 200:
@@ -198,7 +170,6 @@ class OpenAIProvider(AIProvider):
except Exception as e: except Exception as e:
raise Exception(f"AI generation failed: {str(e)}") raise Exception(f"AI generation failed: {str(e)}")
class GeminiProvider(AIProvider): class GeminiProvider(AIProvider):
"""Google Gemini provider implementation.""" """Google Gemini provider implementation."""
@@ -206,53 +177,43 @@ class GeminiProvider(AIProvider):
self.config = config self.config = config
self.api_key = config.get_env_or_config("GOOGLE_API_KEY") self.api_key = config.get_env_or_config("GOOGLE_API_KEY")
if not self.api_key: if not self.api_key:
raise ValueError( raise ValueError("Google API key not found. Please set it in config or environment.")
"Google API key not found. Please set it in config or environment."
)
self.model = config.get("model", "gemini-pro") self.model = config.get("model", "gemini-pro")
self.api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{ self.api_url = f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent"
self.model self.headers = {
}:generateContent" "Content-Type": "application/json"
self.headers = {"Content-Type": "application/json"} }
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
try: try:
temp = ( temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
temperature tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
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 # Combine system and user prompts for Gemini
full_prompt = f"{system_prompt}\n\n{user_prompt}" full_prompt = f"{system_prompt}\n\n{user_prompt}"
payload = { payload = {
"contents": [{"parts": [{"text": full_prompt}]}], "contents": [{
"parts": [{"text": full_prompt}]
}],
"generationConfig": { "generationConfig": {
"temperature": temp, "temperature": temp,
"maxOutputTokens": tokens, "maxOutputTokens": tokens,
"topP": float(top_p), "topP": float(top_p)
}, }
} }
response = requests.post( response = requests.post(
f"{self.api_url}?key={self.api_key}", f"{self.api_url}?key={self.api_key}",
headers=self.headers, headers=self.headers,
json=payload, json=payload,
timeout=30, timeout=30
) )
if response.status_code != 200: if response.status_code != 200:
@@ -275,7 +236,6 @@ class GeminiProvider(AIProvider):
except Exception as e: except Exception as e:
raise Exception(f"AI generation failed: {str(e)}") raise Exception(f"AI generation failed: {str(e)}")
class ClaudeProvider(AIProvider): class ClaudeProvider(AIProvider):
"""Anthropic Claude provider implementation.""" """Anthropic Claude provider implementation."""
@@ -283,60 +243,49 @@ class ClaudeProvider(AIProvider):
self.config = config self.config = config
self.api_key = config.get_env_or_config("ANTHROPIC_API_KEY") self.api_key = config.get_env_or_config("ANTHROPIC_API_KEY")
if not self.api_key: if not self.api_key:
raise ValueError( raise ValueError("Anthropic API key not found. Please set it in config or environment.")
"Anthropic API key not found. Please set it in config or environment."
)
self.model = config.get("model", "claude-3-opus-20240229") self.model = config.get("model", "claude-3-opus-20240229")
self.api_url = "https://api.anthropic.com/v1/messages" self.api_url = "https://api.anthropic.com/v1/messages"
self.headers = { self.headers = {
"x-api-key": self.api_key, "x-api-key": self.api_key,
"anthropic-version": "2023-06-01", "anthropic-version": "2023-06-01",
"content-type": "application/json", "content-type": "application/json"
} }
def _create_prompt( def _create_prompt(self, system_prompt: str, user_prompt: str) -> List[Dict[str, str]]:
self, system_prompt: str, user_prompt: str
) -> List[Dict[str, str]]:
return [ return [
{"role": "system", "content": system_prompt}, {"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}, {"role": "user", "content": user_prompt}
] ]
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
messages = self._create_prompt(system_prompt, user_prompt) messages = self._create_prompt(system_prompt, user_prompt)
try: try:
temp = ( temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
temperature tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
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 = { payload = {
"model": self.model, "model": self.model,
"messages": messages, "messages": messages,
"temperature": temp, "temperature": temp,
"max_tokens": tokens, "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} payload = {k: v for k, v in payload.items() if v is not None}
response = requests.post( 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: if response.status_code != 200:
@@ -359,7 +308,6 @@ class ClaudeProvider(AIProvider):
except Exception as e: except Exception as e:
raise Exception(f"AI generation failed: {str(e)}") raise Exception(f"AI generation failed: {str(e)}")
class HuggingFaceProvider(AIProvider): class HuggingFaceProvider(AIProvider):
"""Hugging Face provider implementation.""" """Hugging Face provider implementation."""
@@ -367,40 +315,28 @@ class HuggingFaceProvider(AIProvider):
self.config = config self.config = config
self.api_key = config.get_env_or_config("HUGGINGFACE_API_KEY") self.api_key = config.get_env_or_config("HUGGINGFACE_API_KEY")
if not self.api_key: if not self.api_key:
raise ValueError( raise ValueError("Hugging Face API key not found. Please set it in config or environment.")
"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.model = config.get("model", "mistralai/Mixtral-8x7B-Instruct-v0.1")
self.api_url = f"https://api-inference.huggingface.co/models/{self.model}" self.api_url = f"https://api-inference.huggingface.co/models/{self.model}"
self.headers = { self.headers = {
"Authorization": f"Bearer {self.api_key}", "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: def _create_prompt(self, system_prompt: str, user_prompt: str) -> str:
# Format prompt according to model's requirements # Format prompt according to model's requirements
return f"<s>[INST] {system_prompt}\n\n{user_prompt} [/INST]" return f"<s>[INST] {system_prompt}\n\n{user_prompt} [/INST]"
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
try: try:
temp = ( temp = temperature if temperature is not None else float(self.config.get("temperature", 0.7))
temperature tokens = max_tokens if max_tokens is not None else int(self.config.get("max_tokens", 150))
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) prompt = self._create_prompt(system_prompt, user_prompt)
@@ -410,12 +346,15 @@ class HuggingFaceProvider(AIProvider):
"temperature": temp, "temperature": temp,
"max_new_tokens": tokens, "max_new_tokens": tokens,
"top_p": float(top_p), "top_p": float(top_p),
"return_full_text": False, "return_full_text": False
}, }
} }
response = requests.post( 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: if response.status_code != 200:
@@ -438,7 +377,6 @@ class HuggingFaceProvider(AIProvider):
except Exception as e: except Exception as e:
raise Exception(f"AI generation failed: {str(e)}") raise Exception(f"AI generation failed: {str(e)}")
class AIService: class AIService:
"""Base AI service that can be extended by specific tools.""" """Base AI service that can be extended by specific tools."""
@@ -457,43 +395,42 @@ class AIService:
"openai": OpenAIProvider, "openai": OpenAIProvider,
"gemini": GeminiProvider, "gemini": GeminiProvider,
"claude": ClaudeProvider, "claude": ClaudeProvider,
"huggingface": HuggingFaceProvider, "huggingface": HuggingFaceProvider
} }
if provider not in providers: if provider not in providers:
raise ValueError( raise ValueError(f"Unsupported AI provider: {provider}. Supported providers: {', '.join(providers.keys())}")
f"Unsupported AI provider: {provider}. Supported providers: {
', '.join(providers.keys())
}"
)
return providers[provider]() return providers[provider]()
def generate_completion( def generate_completion(self,
self, system_prompt: str,
system_prompt: str, user_prompt: str,
user_prompt: str, temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None,
max_tokens: Optional[int] = None, top_p: float = 0.95) -> str:
top_p: float = 0.95,
) -> str:
"""Generate a completion from the AI model.""" """Generate a completion from the AI model."""
return self.provider.generate_completion( 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( def generate_batch_completions(self,
self, system_prompt: str,
system_prompt: str, prompts: List[str],
prompts: List[str], temperature: Optional[float] = None,
temperature: Optional[float] = None, max_tokens: Optional[int] = None) -> List[str]:
max_tokens: Optional[int] = None,
) -> List[str]:
"""Generate completions for multiple prompts.""" """Generate completions for multiple prompts."""
completions = [] completions = []
for prompt in prompts: for prompt in prompts:
completion = self.generate_completion( completion = self.generate_completion(
system_prompt, prompt, temperature, max_tokens system_prompt,
prompt,
temperature,
max_tokens
) )
completions.append(completion) completions.append(completion)
return completions return completions
+27 -31
View File
@@ -1,21 +1,19 @@
""" """
Shared Git service for devtools. Shared Git service for devtools.
""" """
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from typing import List, Dict, Optional, Tuple from typing import List, Dict, Optional, Tuple
import os import os
from datetime import datetime, timedelta from datetime import datetime, timedelta
class GitService: class GitService:
"""Base Git service that can be extended by specific tools.""" """Base Git service that can be extended by specific tools."""
def __init__(self, repo_path: str): def __init__(self, repo_path: str):
"""Initialize GitService with repository path.""" """Initialize GitService with repository path."""
self.repo_path = repo_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}") raise ValueError(f"Not a git repository: {repo_path}")
def _is_git_repo(self) -> bool: def _is_git_repo(self) -> bool:
@@ -25,7 +23,7 @@ class GitService:
["git", "rev-parse", "--is-inside-work-tree"], ["git", "rev-parse", "--is-inside-work-tree"],
cwd=self.repo_path, cwd=self.repo_path,
check=True, check=True,
capture_output=True, capture_output=True
) )
return True return True
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
@@ -39,7 +37,7 @@ class GitService:
cwd=self.repo_path, cwd=self.repo_path,
check=True, check=True,
capture_output=True, capture_output=True,
text=True, text=True
) )
return result.stdout.strip(), result.stderr.strip(), result.returncode return result.stdout.strip(), result.stderr.strip(), result.returncode
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
@@ -52,9 +50,7 @@ class GitService:
def get_unstaged_files(self) -> List[str]: def get_unstaged_files(self) -> List[str]:
"""Get list of unstaged files.""" """Get list of unstaged files."""
stdout, _, _ = self._run_git_command( stdout, _, _ = self._run_git_command(["ls-files", "--modified", "--others", "--exclude-standard"])
["ls-files", "--modified", "--others", "--exclude-standard"]
)
return stdout.splitlines() if stdout else [] return stdout.splitlines() if stdout else []
def get_diff(self, file_path: str, staged: bool = True) -> str: def get_diff(self, file_path: str, staged: bool = True) -> str:
@@ -104,36 +100,36 @@ class GitService:
if files: if files:
for file in files: for file in files:
result = subprocess.run( result = subprocess.run(
["git", "diff", "--staged", "--", file], ['git', 'diff', '--staged', '--', file],
cwd=self.repo_path, cwd=self.repo_path,
capture_output=True, capture_output=True,
text=True, text=True
) )
if result.stdout: if result.stdout:
diffs[file] = result.stdout diffs[file] = result.stdout
else: else:
result = subprocess.run( result = subprocess.run(
["git", "diff", "--staged"], ['git', 'diff', '--staged'],
cwd=self.repo_path, cwd=self.repo_path,
capture_output=True, capture_output=True,
text=True, text=True
) )
if result.stdout: if result.stdout:
# Parse the diff to get individual file changes # Parse the diff to get individual file changes
current_file = None current_file = None
current_diff = [] current_diff = []
for line in result.stdout.split("\n"): for line in result.stdout.split('\n'):
if line.startswith("diff --git"): if line.startswith('diff --git'):
if current_file and current_diff: if current_file and current_diff:
diffs[current_file] = "\n".join(current_diff) diffs[current_file] = '\n'.join(current_diff)
current_file = line.split("b/")[-1].strip() current_file = line.split('b/')[-1].strip()
current_diff = [line] current_diff = [line]
elif current_file: elif current_file:
current_diff.append(line) current_diff.append(line)
if current_file and current_diff: if current_file and current_diff:
diffs[current_file] = "\n".join(current_diff) diffs[current_file] = '\n'.join(current_diff)
return diffs return diffs
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
@@ -142,13 +138,15 @@ class GitService:
def stage_all_changes(self) -> None: def stage_all_changes(self) -> None:
"""Stage all changes in the repository.""" """Stage all changes in the repository."""
try: 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: except subprocess.CalledProcessError as e:
raise Exception(f"Failed to stage changes: {str(e)}") raise Exception(f"Failed to stage changes: {str(e)}")
def get_commit_history( def get_commit_history(self, since: Optional[str] = None, limit: Optional[int] = None) -> List[Dict[str, str]]:
self, since: Optional[str] = None, limit: Optional[int] = None
) -> List[Dict[str, str]]:
"""Get commit history. """Get commit history.
Args: Args:
@@ -158,7 +156,7 @@ class GitService:
args = [ args = [
"log", "log",
"--pretty=format:%H%n%an%n%ad%n%B%n==END==", "--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: if since:
@@ -171,18 +169,16 @@ class GitService:
commits = [] commits = []
current_commit = [] current_commit = []
for line in stdout.split("\n"): for line in stdout.split('\n'):
if line == "==END==": if line == "==END==":
if current_commit: if current_commit:
commit_hash, author, date, *message_lines = current_commit commit_hash, author, date, *message_lines = current_commit
commits.append( commits.append({
{ 'hash': commit_hash,
"hash": commit_hash, 'author': author,
"author": author, 'date': date,
"date": date, 'message': '\n'.join(message_lines)
"message": "\n".join(message_lines), })
}
)
current_commit = [] current_commit = []
else: else:
current_commit.append(line) current_commit.append(line)