initial
This commit is contained in:
23 files changed
+2117
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
DevTools - A collection of developer tools.
|
||||
"""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
Changelog generation using AI.
|
||||
"""
|
||||
|
||||
from .generator import ChangelogGenerator
|
||||
|
||||
__all__ = [
|
||||
"ChangelogGenerator"
|
||||
]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
Changelog generation CLI.
|
||||
"""
|
||||
import click
|
||||
from rich.console import Console
|
||||
from rich.prompt import Prompt, Confirm
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||||
from .generator import ChangelogGenerator
|
||||
from ..commitgen.config import CommitGenConfig
|
||||
|
||||
console = Console()
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Generate changelogs."""
|
||||
pass
|
||||
|
||||
@cli.command()
|
||||
@click.option("--version", "-v", required=True, help="Version number")
|
||||
@click.option("--output", "-o", default="CHANGELOG.md", help="Output file path")
|
||||
@click.option("--temperature", "-t", type=float, default=0.7, help="AI temperature")
|
||||
def generate(version: str, output: str, temperature: float):
|
||||
"""Generate a changelog interactively."""
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
progress.add_task("Initializing...", total=None)
|
||||
config = CommitGenConfig()
|
||||
generator = ChangelogGenerator(config)
|
||||
|
||||
# Collect changes
|
||||
console.print("\n[bold]Enter your changes (one per line). Start each line with an emoji to indicate the type:[/]")
|
||||
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("\nPress Ctrl+D (Unix) or Ctrl+Z (Windows) when done.\n")
|
||||
|
||||
changes_text = []
|
||||
while True:
|
||||
try:
|
||||
line = Prompt.ask("")
|
||||
if line:
|
||||
changes_text.append(line)
|
||||
except EOFError:
|
||||
break
|
||||
|
||||
if not changes_text:
|
||||
console.print("[yellow]No changes provided. Exiting.")
|
||||
return
|
||||
|
||||
# Parse changes
|
||||
progress.add_task("Parsing changes...", total=None)
|
||||
changes = generator.parse_changes_from_text("\n".join(changes_text))
|
||||
|
||||
# Generate changelog
|
||||
progress.add_task("Generating changelog...", total=None)
|
||||
generator.update_changelog_file(version, changes, output, temperature)
|
||||
|
||||
console.print(f"\n[green]Generated changelog at {output}")
|
||||
|
||||
@cli.command()
|
||||
@click.option("--version", "-v", required=True, help="Version number")
|
||||
@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", "-t", type=float, default=0.7, help="AI temperature")
|
||||
def generate_from_file(version: str, input: str, output: str, temperature: float):
|
||||
"""Generate a changelog from a file."""
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
progress.add_task("Initializing...", total=None)
|
||||
config = CommitGenConfig()
|
||||
generator = ChangelogGenerator(config)
|
||||
|
||||
# Read changes from file
|
||||
progress.add_task("Reading changes...", total=None)
|
||||
try:
|
||||
with open(input, "r") as f:
|
||||
changes_text = f.read()
|
||||
except FileNotFoundError:
|
||||
console.print(f"[red]Input file not found: {input}")
|
||||
return
|
||||
|
||||
# Parse changes
|
||||
progress.add_task("Parsing changes...", total=None)
|
||||
changes = generator.parse_changes_from_text(changes_text)
|
||||
|
||||
if not changes:
|
||||
console.print("[yellow]No changes found in input file.")
|
||||
return
|
||||
|
||||
# Generate changelog
|
||||
progress.add_task("Generating changelog...", total=None)
|
||||
generator.update_changelog_file(version, changes, output, temperature)
|
||||
|
||||
console.print(f"\n[green]Generated changelog at {output}")
|
||||
|
||||
# Add command aliases
|
||||
cli.add_command(generate, name="g")
|
||||
cli.add_command(generate_from_file, name="f")
|
||||
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
Changelog generation using AI.
|
||||
"""
|
||||
from typing import List, Dict, Optional
|
||||
from ..shared.ai import AIService
|
||||
from ..shared.config import Config
|
||||
from ..shared.git import GitService
|
||||
|
||||
class ChangelogGenerator(AIService):
|
||||
"""AI-powered changelog generator."""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
"""Initialize changelog generator."""
|
||||
super().__init__(config)
|
||||
|
||||
def generate_changelog(self, version: str, changes: List[Dict[str, str]], temperature: Optional[float] = None) -> str:
|
||||
"""Generate a changelog from a list of changes.
|
||||
|
||||
Args:
|
||||
version: Version number for the changelog
|
||||
changes: List of changes, each with 'type' and 'description'
|
||||
temperature: AI temperature for generation
|
||||
|
||||
Returns:
|
||||
Generated changelog content
|
||||
"""
|
||||
system_prompt = """You are a helpful AI that generates changelogs.
|
||||
Follow these rules:
|
||||
1. Group changes by type (Added, Changed, Fixed, etc.)
|
||||
2. Keep descriptions concise but informative
|
||||
3. Use past tense
|
||||
4. Start each entry with a verb
|
||||
5. Use emojis for each type:
|
||||
- ✨ Added
|
||||
- 🔄 Changed
|
||||
- 🐛 Fixed
|
||||
- 🚀 Performance
|
||||
- 📝 Documentation
|
||||
- 🔧 Maintenance
|
||||
- 🗑️ Removed
|
||||
- 🔒 Security"""
|
||||
|
||||
# Format changes for the prompt
|
||||
changes_text = "\n".join(
|
||||
f"{change['type']}: {change['description']}"
|
||||
for change in changes
|
||||
)
|
||||
|
||||
user_prompt = f"Generate a changelog for version {version} with these changes:\n\n{changes_text}"
|
||||
|
||||
return self.generate_completion(
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
temperature=temperature
|
||||
)
|
||||
|
||||
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.
|
||||
|
||||
Args:
|
||||
version: Version number for the changelog
|
||||
changes: List of changes, each with 'type' and 'description'
|
||||
output_file: Path to the changelog file
|
||||
temperature: AI temperature for generation
|
||||
"""
|
||||
changelog_content = self.generate_changelog(version, changes, temperature)
|
||||
|
||||
# Read existing changelog if it exists
|
||||
try:
|
||||
with open(output_file, "r") as f:
|
||||
existing_content = f.read()
|
||||
except FileNotFoundError:
|
||||
existing_content = ""
|
||||
|
||||
# Add new changelog entry at the top
|
||||
new_content = f"## {version}\n\n{changelog_content}\n\n"
|
||||
if existing_content:
|
||||
new_content += existing_content
|
||||
|
||||
# Write updated changelog
|
||||
with open(output_file, "w") as f:
|
||||
f.write(new_content)
|
||||
|
||||
def parse_changes_from_text(self, text: str) -> List[Dict[str, str]]:
|
||||
"""Parse changes from text input.
|
||||
|
||||
Args:
|
||||
text: Text containing changes
|
||||
|
||||
Returns:
|
||||
List of changes with type and description
|
||||
"""
|
||||
changes = []
|
||||
current_type = None
|
||||
current_description = []
|
||||
|
||||
for line in text.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
|
||||
# Check if line starts with a type marker
|
||||
type_markers = {
|
||||
"✨": "Added",
|
||||
"🔄": "Changed",
|
||||
"🐛": "Fixed",
|
||||
"🚀": "Performance",
|
||||
"📝": "Documentation",
|
||||
"🔧": "Maintenance",
|
||||
"🗑️": "Removed",
|
||||
"🔒": "Security"
|
||||
}
|
||||
|
||||
for marker, type_ in type_markers.items():
|
||||
if line.startswith(marker):
|
||||
# Save previous change if exists
|
||||
if current_type and current_description:
|
||||
changes.append({
|
||||
"type": current_type,
|
||||
"description": " ".join(current_description)
|
||||
})
|
||||
|
||||
# Start new change
|
||||
current_type = type_
|
||||
current_description = [line[len(marker):].strip()]
|
||||
break
|
||||
else:
|
||||
# Continue current change
|
||||
if current_type:
|
||||
current_description.append(line)
|
||||
|
||||
# Add last change if exists
|
||||
if current_type and current_description:
|
||||
changes.append({
|
||||
"type": current_type,
|
||||
"description": " ".join(current_description)
|
||||
})
|
||||
|
||||
return changes
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
Main CLI for devtools.
|
||||
"""
|
||||
import click
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from .shared.config import Config
|
||||
from .gitignore.cli import cli as gitignore_cli
|
||||
from .commitgen.cli import cli as commit_cli
|
||||
|
||||
console = Console()
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Developer tools CLI."""
|
||||
pass
|
||||
|
||||
@cli.group()
|
||||
def config():
|
||||
"""Manage configuration."""
|
||||
pass
|
||||
|
||||
@config.command()
|
||||
@click.argument("key")
|
||||
@click.argument("value")
|
||||
def set(key: str, value: str):
|
||||
"""Set a configuration value."""
|
||||
config = Config()
|
||||
config.set(key, value)
|
||||
console.print(f"[green]Set {key} to {value}")
|
||||
|
||||
@config.command()
|
||||
@click.argument("key", required=False)
|
||||
def show(key: str = None):
|
||||
"""Show configuration values."""
|
||||
config = Config()
|
||||
if key:
|
||||
value = config.get(key)
|
||||
if value is None:
|
||||
console.print(f"[yellow]No value set for {key}")
|
||||
else:
|
||||
console.print(f"{key}: {value}")
|
||||
else:
|
||||
table = Table(title="Configuration")
|
||||
table.add_column("Key", style="cyan")
|
||||
table.add_column("Value", style="green")
|
||||
|
||||
for k, v in config.get_all().items():
|
||||
table.add_row(k, str(v))
|
||||
|
||||
console.print(table)
|
||||
|
||||
@config.command()
|
||||
@click.argument("key")
|
||||
def delete(key: str):
|
||||
"""Delete a configuration value."""
|
||||
config = Config()
|
||||
if key in config.get_all():
|
||||
config.delete(key)
|
||||
console.print(f"[green]Deleted {key}")
|
||||
else:
|
||||
console.print(f"[yellow]No value set for {key}")
|
||||
|
||||
@config.command()
|
||||
def clear():
|
||||
"""Clear all configuration values."""
|
||||
if click.confirm("Are you sure you want to clear all configuration?"):
|
||||
config = Config()
|
||||
config.clear()
|
||||
console.print("[green]Cleared all configuration")
|
||||
|
||||
# Add subcommands
|
||||
cli.add_command(gitignore_cli, name="gitignore")
|
||||
cli.add_command(commit_cli, name="commit")
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
Commit message generator using AI.
|
||||
"""
|
||||
|
||||
from ..shared.config import Config
|
||||
from .generator import CommitGenerator
|
||||
from .git import CommitGenGitService
|
||||
from ..changelog import ChangelogGenerator
|
||||
|
||||
__all__ = [
|
||||
"Config",
|
||||
"CommitGenerator",
|
||||
"CommitGenGitService",
|
||||
"ChangelogGenerator"
|
||||
]
|
||||
@@ -0,0 +1,247 @@
|
||||
"""
|
||||
Command-line interface for commitgen tool.
|
||||
"""
|
||||
import click
|
||||
from rich.console import Console
|
||||
from rich.prompt import Prompt
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich.syntax import Syntax
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||||
from ..shared.config import Config
|
||||
from .git import CommitGenGitService
|
||||
from .generator import CommitGenerator
|
||||
from ..changelog import ChangelogGenerator
|
||||
from ..shared.git import GitService
|
||||
import os
|
||||
|
||||
console = Console()
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Generate commit messages and changelogs using AI."""
|
||||
pass
|
||||
|
||||
@cli.command()
|
||||
@click.option('--files', '-f', multiple=True, help='Specific files to generate commit messages for')
|
||||
@click.option('--repo', '-r', help='Repository path')
|
||||
@click.option('--commit', '-c', is_flag=True, help='Automatically commit changes')
|
||||
@click.option('--push', '-p', is_flag=True, help='Push changes after commit')
|
||||
@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"""
|
||||
try:
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
config = Config()
|
||||
git_service = CommitGenGitService(config)
|
||||
ai_service = CommitGenerator(config)
|
||||
|
||||
# Stage all changes if not disabled
|
||||
if not no_stage:
|
||||
task = progress.add_task("Staging changes...", total=None)
|
||||
git_service.stage_all_changes()
|
||||
progress.update(task, completed=True)
|
||||
|
||||
# Get staged changes
|
||||
task = progress.add_task("Analyzing changes...", total=None)
|
||||
staged_changes = git_service.get_staged_changes(files)
|
||||
progress.update(task, completed=True)
|
||||
|
||||
if not staged_changes:
|
||||
console.print("[yellow]No staged changes found.[/yellow]")
|
||||
return
|
||||
|
||||
# Generate commit message
|
||||
task = progress.add_task("Generating commit message...", total=None)
|
||||
commit_message = ai_service.generate_commit_message(staged_changes, temperature)
|
||||
progress.update(task, completed=True)
|
||||
|
||||
# Show preview and confirm
|
||||
console.print("\n[bold]Generated commit message:[/bold]")
|
||||
console.print(Panel(commit_message, title="Preview", border_style="blue"))
|
||||
|
||||
if commit:
|
||||
if Prompt.ask("\nApply this commit message?", choices=["y", "n"], default="y") == "y":
|
||||
task = progress.add_task("Committing changes...", total=None)
|
||||
git_service.commit_changes(commit_message, sign=sign)
|
||||
progress.update(task, completed=True)
|
||||
|
||||
if push:
|
||||
task = progress.add_task("Pushing changes...", total=None)
|
||||
git_service.push_changes()
|
||||
progress.update(task, completed=True)
|
||||
|
||||
console.print("[green]Changes committed successfully![/green]")
|
||||
else:
|
||||
console.print("[yellow]Commit cancelled.[/yellow]")
|
||||
else:
|
||||
console.print("[yellow]Use --commit to apply the commit message.[/yellow]")
|
||||
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error: {str(e)}[/red]")
|
||||
raise click.Abort()
|
||||
|
||||
@cli.group()
|
||||
def changelog():
|
||||
"""Generate and manage changelogs"""
|
||||
pass
|
||||
|
||||
@changelog.command(name='generate')
|
||||
@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', 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"""
|
||||
try:
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
config = Config()
|
||||
git_service = CommitGenGitService(config)
|
||||
changelog_gen = ChangelogGenerator(config, git_service)
|
||||
|
||||
task = progress.add_task("Analyzing commit history...", total=None)
|
||||
|
||||
# Determine which method to use for getting commits
|
||||
if from_tag:
|
||||
entries = changelog_gen.get_commits(from_tag)
|
||||
elif days:
|
||||
entries = changelog_gen.get_commits_since_date(days)
|
||||
elif commits:
|
||||
entries = changelog_gen.get_last_n_commits(commits)
|
||||
else:
|
||||
# Default: get commits from the last 7 days
|
||||
entries = changelog_gen.get_commits_since_date(7)
|
||||
|
||||
progress.update(task, completed=True)
|
||||
|
||||
if not entries:
|
||||
console.print("[yellow]No conventional commits found in the specified range.[/yellow]")
|
||||
return
|
||||
|
||||
task = progress.add_task("Generating changelog...", total=None)
|
||||
output_path = output if output else "CHANGELOG.md"
|
||||
changelog_gen.update_changelog_file(version, entries, output_path)
|
||||
progress.update(task, completed=True)
|
||||
|
||||
console.print(f"[green]Changelog generated successfully at {output_path}![/green]")
|
||||
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error: {str(e)}[/red]")
|
||||
raise click.Abort()
|
||||
|
||||
@cli.group()
|
||||
def config():
|
||||
"""Manage configuration"""
|
||||
pass
|
||||
|
||||
@config.command()
|
||||
@click.option('--key', '-k', required=True, help='Configuration key')
|
||||
@click.option('--value', '-v', required=True, help='Configuration value')
|
||||
def set(key: str, value: str):
|
||||
"""Set configuration value"""
|
||||
try:
|
||||
config = Config()
|
||||
config.set(key, value)
|
||||
console.print(f"[green]Configuration updated: {key}={value}[/green]")
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error: {str(e)}[/red]")
|
||||
raise click.Abort()
|
||||
|
||||
@config.command()
|
||||
def show():
|
||||
"""Show current configuration"""
|
||||
try:
|
||||
config = Config()
|
||||
console.print(Panel(
|
||||
"\n".join(f"{k}: {v}" for k, v in config.get_all().items()),
|
||||
title="[blue]Current Configuration[/blue]",
|
||||
border_style="blue"
|
||||
))
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error: {str(e)}[/red]")
|
||||
raise click.Abort()
|
||||
|
||||
@cli.command()
|
||||
def status():
|
||||
"""Show the current state of the repository."""
|
||||
try:
|
||||
# Initialize services
|
||||
git = GitService(os.getcwd())
|
||||
|
||||
# Get repository info
|
||||
repo_name = git.get_repo_name()
|
||||
current_branch = git.get_current_branch()
|
||||
|
||||
# Get changes
|
||||
staged_files = git.get_staged_files()
|
||||
unstaged_files = git.get_unstaged_files()
|
||||
|
||||
# Create status table
|
||||
table = Table(title=f"Repository Status: {repo_name} ({current_branch})")
|
||||
table.add_column("Status", style="cyan")
|
||||
table.add_column("Files", style="green")
|
||||
|
||||
# Add staged changes
|
||||
if staged_files:
|
||||
staged_content = "\n".join(f" • {file}" for file in staged_files)
|
||||
table.add_row("Staged", staged_content)
|
||||
else:
|
||||
table.add_row("Staged", "No staged changes")
|
||||
|
||||
# Add unstaged changes
|
||||
if unstaged_files:
|
||||
unstaged_content = "\n".join(f" • {file}" for file in unstaged_files)
|
||||
table.add_row("Unstaged", unstaged_content)
|
||||
else:
|
||||
table.add_row("Unstaged", "No unstaged changes")
|
||||
|
||||
# Show status
|
||||
console.print("\n[bold]Repository Status:[/bold]")
|
||||
console.print(table)
|
||||
|
||||
# Show diffs if there are changes
|
||||
if staged_files or unstaged_files:
|
||||
console.print("\n[bold]Changes:[/bold]")
|
||||
|
||||
# Show staged diffs
|
||||
if staged_files:
|
||||
console.print("\n[cyan]Staged Changes:[/cyan]")
|
||||
for file in staged_files:
|
||||
diff = git.get_diff(file, staged=True)
|
||||
if diff:
|
||||
console.print(Syntax(diff, "diff", theme="monokai"))
|
||||
|
||||
# Show unstaged diffs
|
||||
if unstaged_files:
|
||||
console.print("\n[yellow]Unstaged Changes:[/yellow]")
|
||||
for file in unstaged_files:
|
||||
diff = git.get_diff(file, staged=False)
|
||||
if diff:
|
||||
console.print(Syntax(diff, "diff", theme="monokai"))
|
||||
|
||||
except Exception as e:
|
||||
console.print(f"[red]Error: {str(e)}[/red]")
|
||||
raise click.Abort()
|
||||
|
||||
# Add command aliases
|
||||
cli.add_command(generate, name='g')
|
||||
cli.add_command(config, name='c')
|
||||
cli.add_command(changelog, name='log')
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
Commit message and changelog generation using AI.
|
||||
"""
|
||||
from typing import List, Dict, Optional
|
||||
from ..shared.ai import AIService
|
||||
from ..shared.config import Config
|
||||
|
||||
class CommitGenerator(AIService):
|
||||
"""AI-powered commit message and changelog generator."""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
"""Initialize commit generator."""
|
||||
super().__init__(config)
|
||||
|
||||
def generate_commit_message(self, diff: str, temperature: Optional[float] = None) -> str:
|
||||
"""Generate a commit message from a diff."""
|
||||
system_prompt = """You are a helpful AI that generates git commit messages. Keep responses concise and follow the conventional commit format.
|
||||
|
||||
Format: type(scope): description
|
||||
Types and their emojis:
|
||||
- feat: ✨ (new feature)
|
||||
- fix: 🐛 (bug fix)
|
||||
- docs: 📚 (documentation)
|
||||
- style: 💅 (formatting, missing semi colons, etc)
|
||||
- refactor: ♻️ (refactoring code)
|
||||
- test: ✅ (adding tests)
|
||||
- chore: 🔧 (maintenance)
|
||||
|
||||
The message should be a single line and follow the conventional commit format strictly. Include the appropriate emoji at the start of the message."""
|
||||
|
||||
user_prompt = f"Write a conventional commit message for these changes:\n\n{diff}"
|
||||
|
||||
message = self.generate_completion(
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
temperature=temperature
|
||||
)
|
||||
|
||||
# Clean up the response to ensure it's a valid commit message
|
||||
message = message.split('\n')[0].strip() # Take only the first line
|
||||
|
||||
# Ensure the message starts with an emoji
|
||||
if not any(emoji in message for emoji in ['✨', '🐛', '📚', '💅', '♻️', '✅', '🔧']):
|
||||
# Add appropriate emoji based on the commit type
|
||||
if message.startswith('feat'):
|
||||
message = '✨ ' + message
|
||||
elif message.startswith('fix'):
|
||||
message = '🐛 ' + message
|
||||
elif message.startswith('docs'):
|
||||
message = '📚 ' + message
|
||||
elif message.startswith('style'):
|
||||
message = '💅 ' + message
|
||||
elif message.startswith('refactor'):
|
||||
message = '♻️ ' + message
|
||||
elif message.startswith('test'):
|
||||
message = '✅ ' + message
|
||||
elif message.startswith('chore'):
|
||||
message = '🔧 ' + message
|
||||
else:
|
||||
message = '🔧 ' + message # Default to chore
|
||||
|
||||
return message
|
||||
|
||||
def generate_changelog(self, commits: List[str], version: str, temperature: Optional[float] = None) -> str:
|
||||
"""Generate a changelog from a list of commits."""
|
||||
system_prompt = """You are a helpful AI that generates changelogs.
|
||||
Follow these rules:
|
||||
1. Group changes by type (Added, Changed, Fixed, etc.)
|
||||
2. Keep descriptions concise but informative
|
||||
3. Use past tense
|
||||
4. Start each entry with a verb"""
|
||||
|
||||
user_prompt = f"Generate a changelog for version {version} with these commits:\n\n" + "\n".join(commits)
|
||||
|
||||
return self.generate_completion(
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
temperature=temperature
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
Git service for commit_gen tool.
|
||||
"""
|
||||
from typing import List, Optional
|
||||
from ..shared.git import GitService
|
||||
from ..shared.config import Config
|
||||
import os
|
||||
|
||||
class CommitGenGitService(GitService):
|
||||
"""Git service for commit_gen tool."""
|
||||
|
||||
def __init__(self, config: Config):
|
||||
"""Initialize commit_gen git service."""
|
||||
super().__init__(os.getcwd()) # Use current directory as repo path
|
||||
self.config = config
|
||||
|
||||
def get_staged_changes(self, files: Optional[List[str]] = None) -> str:
|
||||
"""Get staged changes as a diff.
|
||||
|
||||
Args:
|
||||
files: Optional list of files to get changes for
|
||||
"""
|
||||
diffs = self.get_all_diffs(staged=True)
|
||||
if files:
|
||||
diffs = {file: diff for file, diff in diffs.items() if file in files}
|
||||
return "\n\n".join(f"Changes in {file}:\n{diff}" for file, diff in diffs.items())
|
||||
|
||||
def get_unstaged_changes(self) -> str:
|
||||
"""Get unstaged changes as a diff."""
|
||||
diffs = self.get_all_diffs(staged=False)
|
||||
return "\n\n".join(f"Changes in {file}:\n{diff}" for file, diff in diffs.items())
|
||||
|
||||
def commit_changes(self, message: str, sign: bool = False) -> None:
|
||||
"""Commit changes with the given message."""
|
||||
if not self.commit(message, sign=sign):
|
||||
raise Exception("Failed to commit changes")
|
||||
|
||||
def get_recent_commits(self, limit: int = 10) -> List[str]:
|
||||
"""Get recent commit messages."""
|
||||
commits = self.get_commit_history(limit=limit)
|
||||
return [commit["message"] for commit in commits]
|
||||
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
Gitignore generator module.
|
||||
"""
|
||||
|
||||
from .cli import cli
|
||||
from .generator import GitignoreGenerator
|
||||
from .detector import ProjectDetector
|
||||
|
||||
__all__ = [
|
||||
"cli",
|
||||
"GitignoreGenerator",
|
||||
"ProjectDetector"
|
||||
]
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
Gitignore generation CLI.
|
||||
"""
|
||||
import os
|
||||
import click
|
||||
from rich.console import Console
|
||||
from rich.prompt import Confirm
|
||||
from rich.progress import Progress, SpinnerColumn, TextColumn
|
||||
from .generator import GitignoreGenerator
|
||||
from .detector import ProjectDetector
|
||||
|
||||
console = Console()
|
||||
|
||||
@click.group()
|
||||
def cli():
|
||||
"""Generate .gitignore files."""
|
||||
pass
|
||||
|
||||
@cli.command()
|
||||
@click.option("--directory", "-d", default=".", help="Directory to scan")
|
||||
@click.option("--output", "-o", default=".gitignore", help="Output file path")
|
||||
def auto(directory: str, output: str):
|
||||
"""Automatically detect project types and generate .gitignore."""
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
progress.add_task("Initializing...", total=None)
|
||||
detector = ProjectDetector(directory)
|
||||
generator = GitignoreGenerator()
|
||||
|
||||
# Detect project types
|
||||
progress.add_task("Detecting project types...", total=None)
|
||||
detected_types = detector.detect_project_types()
|
||||
|
||||
if not detected_types:
|
||||
console.print("[yellow]No project types detected. Using generic .gitignore.")
|
||||
else:
|
||||
console.print(f"\n[green]Detected project types:[/] {', '.join(detected_types)}")
|
||||
|
||||
# Check if output file exists
|
||||
if os.path.exists(output):
|
||||
if not Confirm.ask(f"\n[yellow]File {output} already exists. Overwrite?"):
|
||||
return
|
||||
|
||||
# Generate .gitignore
|
||||
progress.add_task("Generating .gitignore...", total=None)
|
||||
generator.update_gitignore_file(detected_types, output)
|
||||
|
||||
console.print(f"\n[green]Generated .gitignore at {output}")
|
||||
|
||||
@cli.command()
|
||||
@click.argument("types", nargs=-1, required=True)
|
||||
@click.option("--output", "-o", default=".gitignore", help="Output file path")
|
||||
def generate(types: tuple, output: str):
|
||||
"""Generate .gitignore for specified types."""
|
||||
with Progress(
|
||||
SpinnerColumn(),
|
||||
TextColumn("[progress.description]{task.description}"),
|
||||
console=console
|
||||
) as progress:
|
||||
# Initialize services
|
||||
progress.add_task("Initializing...", total=None)
|
||||
generator = GitignoreGenerator()
|
||||
|
||||
# Check if output file exists
|
||||
if os.path.exists(output):
|
||||
if not Confirm.ask(f"\n[yellow]File {output} already exists. Overwrite?"):
|
||||
return
|
||||
|
||||
# Generate .gitignore
|
||||
progress.add_task("Generating .gitignore...", total=None)
|
||||
generator.update_gitignore_file(list(types), output)
|
||||
|
||||
console.print(f"\n[green]Generated .gitignore at {output}")
|
||||
|
||||
# Add command aliases
|
||||
cli.add_command(auto, name="a")
|
||||
cli.add_command(generate, name="g")
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""
|
||||
Project type detection for gitignore generation.
|
||||
"""
|
||||
import os
|
||||
from typing import List, Dict, Set
|
||||
|
||||
class ProjectDetector:
|
||||
"""Detect project types based on file patterns."""
|
||||
|
||||
# File patterns for different project types
|
||||
PROJECT_PATTERNS = {
|
||||
# Languages
|
||||
"python": ["*.py", "requirements.txt", "setup.py", "Pipfile", "pyproject.toml"],
|
||||
"javascript": ["package.json", "*.js", "*.jsx", "*.ts", "*.tsx"],
|
||||
"typescript": ["tsconfig.json", "*.ts", "*.tsx"],
|
||||
"java": ["*.java", "pom.xml", "build.gradle", "*.class"],
|
||||
"kotlin": ["*.kt", "*.kts"],
|
||||
"go": ["go.mod", "go.sum", "*.go"],
|
||||
"rust": ["Cargo.toml", "Cargo.lock", "*.rs"],
|
||||
"ruby": ["Gemfile", "*.rb", "*.gemspec"],
|
||||
"php": ["composer.json", "*.php"],
|
||||
"csharp": ["*.cs", "*.csproj", "*.sln"],
|
||||
"swift": ["*.swift", "*.xcodeproj"],
|
||||
"objective-c": ["*.m", "*.h", "*.mm"],
|
||||
|
||||
# Frameworks
|
||||
"django": ["manage.py", "wsgi.py", "asgi.py"],
|
||||
"flask": ["app.py", "flask_app.py"],
|
||||
"fastapi": ["main.py", "app.py"],
|
||||
"react": ["src/App.js", "src/App.tsx"],
|
||||
"vue": ["vue.config.js", "*.vue"],
|
||||
"angular": ["angular.json", "tsconfig.json"],
|
||||
"spring": ["application.properties", "application.yml"],
|
||||
"laravel": ["artisan", "composer.json"],
|
||||
"rails": ["config/routes.rb", "Gemfile"],
|
||||
"express": ["app.js", "server.js"],
|
||||
"next": ["next.config.js"],
|
||||
"nuxt": ["nuxt.config.js"],
|
||||
|
||||
# Build Tools
|
||||
"maven": ["pom.xml"],
|
||||
"gradle": ["build.gradle", "settings.gradle"],
|
||||
"npm": ["package.json"],
|
||||
"yarn": ["yarn.lock"],
|
||||
"pip": ["requirements.txt"],
|
||||
"poetry": ["pyproject.toml"],
|
||||
"cargo": ["Cargo.toml"],
|
||||
"composer": ["composer.json"],
|
||||
|
||||
# IDEs and Editors
|
||||
"vscode": [".vscode/settings.json"],
|
||||
"intellij": [".idea/workspace.xml"],
|
||||
"eclipse": [".project", ".classpath"],
|
||||
"vim": [".vimrc", ".vim/"],
|
||||
"emacs": [".emacs", ".emacs.d/"],
|
||||
"sublime": ["*.sublime-project", "*.sublime-workspace"],
|
||||
"atom": [".atom/"],
|
||||
|
||||
# Operating Systems
|
||||
"windows": ["*.exe", "*.dll", "*.sys"],
|
||||
"macos": [".DS_Store", "*.app"],
|
||||
"linux": ["*.so", "*.o"],
|
||||
|
||||
# Testing Frameworks
|
||||
"jest": ["jest.config.js"],
|
||||
"pytest": ["pytest.ini", "conftest.py"],
|
||||
"junit": ["junit.xml"],
|
||||
"mocha": ["mocha.opts"],
|
||||
|
||||
# Documentation
|
||||
"sphinx": ["docs/conf.py"],
|
||||
"mkdocs": ["mkdocs.yml"],
|
||||
"docusaurus": ["docusaurus.config.js"],
|
||||
|
||||
# Databases
|
||||
"postgresql": ["*.sql", "*.dump"],
|
||||
"mysql": ["*.sql", "*.dump"],
|
||||
"mongodb": ["*.bson"],
|
||||
"sqlite": ["*.db", "*.sqlite"],
|
||||
|
||||
# Cloud Platforms
|
||||
"aws": [".aws/", "aws.json"],
|
||||
"azure": ["azure.yaml", "azure.json"],
|
||||
"gcp": ["gcloud.json"],
|
||||
|
||||
# Containerization
|
||||
"docker": ["Dockerfile", "docker-compose.yml"],
|
||||
"kubernetes": ["k8s/", "*.yaml"],
|
||||
|
||||
# CI/CD
|
||||
"github-actions": [".github/workflows/"],
|
||||
"gitlab-ci": [".gitlab-ci.yml"],
|
||||
"jenkins": ["Jenkinsfile"],
|
||||
"travis": [".travis.yml"],
|
||||
"circleci": [".circleci/config.yml"],
|
||||
|
||||
# Static Site Generators
|
||||
"jekyll": ["_config.yml"],
|
||||
"hugo": ["config.toml", "config.yaml"],
|
||||
"gatsby": ["gatsby-config.js"],
|
||||
|
||||
# Game Development
|
||||
"unity": ["*.unity", "*.unityproj"],
|
||||
"unreal": ["*.uproject"],
|
||||
|
||||
# Machine Learning
|
||||
"tensorflow": ["*.pb", "*.h5"],
|
||||
"pytorch": ["*.pt", "*.pth"],
|
||||
"scikit-learn": ["*.joblib"]
|
||||
}
|
||||
|
||||
def __init__(self, directory: str = "."):
|
||||
"""Initialize project detector.
|
||||
|
||||
Args:
|
||||
directory: Directory to scan
|
||||
"""
|
||||
self.directory = directory
|
||||
|
||||
def detect_project_types(self) -> List[str]:
|
||||
"""Detect project types in the directory.
|
||||
|
||||
Returns:
|
||||
List of detected project types
|
||||
"""
|
||||
detected_types = set()
|
||||
|
||||
# Scan directory for files
|
||||
for root, _, files in os.walk(self.directory):
|
||||
for file in files:
|
||||
file_path = os.path.join(root, file)
|
||||
rel_path = os.path.relpath(file_path, self.directory)
|
||||
|
||||
# Check each project type's patterns
|
||||
for type_, patterns in self.PROJECT_PATTERNS.items():
|
||||
if any(self._matches_pattern(rel_path, pattern) for pattern in patterns):
|
||||
detected_types.add(type_)
|
||||
|
||||
return sorted(list(detected_types))
|
||||
|
||||
def _matches_pattern(self, path: str, pattern: str) -> bool:
|
||||
"""Check if a path matches a pattern.
|
||||
|
||||
Args:
|
||||
path: Path to check
|
||||
pattern: Pattern to match
|
||||
|
||||
Returns:
|
||||
True if path matches pattern
|
||||
"""
|
||||
# Handle directory patterns
|
||||
if pattern.endswith("/"):
|
||||
return path.startswith(pattern[:-1])
|
||||
|
||||
# Handle wildcard patterns
|
||||
if "*" in pattern:
|
||||
import fnmatch
|
||||
return fnmatch.fnmatch(path, pattern)
|
||||
|
||||
# Handle exact matches
|
||||
return path == pattern
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
Gitignore generator using gitignore.io API.
|
||||
"""
|
||||
import os
|
||||
import requests
|
||||
from typing import List, Dict
|
||||
|
||||
class GitignoreGenerator:
|
||||
"""Gitignore generator using gitignore.io API."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize gitignore generator."""
|
||||
self.api_url = "https://www.toptal.com/developers/gitignore/api"
|
||||
|
||||
def generate_gitignore(self, types: List[str]) -> str:
|
||||
"""Generate .gitignore content for specified types.
|
||||
|
||||
Args:
|
||||
types: List of project types
|
||||
|
||||
Returns:
|
||||
Generated .gitignore content
|
||||
"""
|
||||
if not types:
|
||||
return self._get_generic_gitignore()
|
||||
|
||||
try:
|
||||
# Get gitignore content from API
|
||||
response = requests.get(f"{self.api_url}/{','.join(types)}")
|
||||
response.raise_for_status()
|
||||
|
||||
# Add header
|
||||
header = "# Generated by devtools gitignore generator\n"
|
||||
header += f"# Types: {', '.join(types)}\n\n"
|
||||
|
||||
return header + response.text
|
||||
|
||||
except requests.RequestException:
|
||||
# Fallback to generic gitignore if API fails
|
||||
return self._get_generic_gitignore()
|
||||
|
||||
def _get_generic_gitignore(self) -> str:
|
||||
"""Get a generic .gitignore template.
|
||||
|
||||
Returns:
|
||||
Generic .gitignore content
|
||||
"""
|
||||
return """# Generic .gitignore
|
||||
# Generated by devtools gitignore generator
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# IDE files
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Build directories
|
||||
build/
|
||||
dist/
|
||||
out/
|
||||
target/
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
venv/
|
||||
env/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.temp
|
||||
*.bak
|
||||
"""
|
||||
|
||||
def update_gitignore_file(self, types: List[str], output_file: str) -> None:
|
||||
"""Generate and update a .gitignore file.
|
||||
|
||||
Args:
|
||||
types: List of project types
|
||||
output_file: Path to the .gitignore file
|
||||
"""
|
||||
content = self.generate_gitignore(types)
|
||||
|
||||
# Write to file
|
||||
with open(output_file, "w") as f:
|
||||
f.write(content)
|
||||
@@ -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