updates
This commit is contained in:
73 files changed
+3290
-4522
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,28 @@
|
||||
from importlib import import_module
|
||||
|
||||
|
||||
def generate_with_ai(
|
||||
prompt, provider="gemini", api_key=None, model="gemini-2.5-flash", **kwargs
|
||||
):
|
||||
"""Generates AI-based content such as commit messages using the specified provider and model.
|
||||
This function dynamically loads and initializes the provider class, sets the API key, and invokes the provider's generate method with the provided prompt and additional parameters.
|
||||
|
||||
Args:
|
||||
prompt (str): The input prompt used to generate content.
|
||||
provider (str): The name of the provider module and class to use; defaults to "gemini".
|
||||
api_key (str, optional): The API key for authenticating with the provider. Should be provided via config file or kwargs.
|
||||
model (str): The name of the model to use with the provider; defaults to "gemini".
|
||||
**kwargs: Additional keyword arguments to pass to the provider's generate method.
|
||||
|
||||
Returns:
|
||||
str: The generated content produced by the AI provider.
|
||||
"""
|
||||
try:
|
||||
provider_module = import_module(f"devgen.providers.{provider}")
|
||||
class_name = "".join([x.capitalize() for x in provider.split("_")]) + "Provider"
|
||||
provider_class = getattr(provider_module, class_name)
|
||||
except (ModuleNotFoundError, AttributeError) as e:
|
||||
raise ImportError(f"Provider `{provider}` not found or invalid: {e}") from e
|
||||
|
||||
provider_instance = provider_class()
|
||||
return provider_instance.generate(prompt, api_key=api_key, model=model, **kwargs)
|
||||
Whitespace-only changes.
@@ -0,0 +1,38 @@
|
||||
import typer
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from devgen.modules.changelog_generator import ChangelogGenerator
|
||||
|
||||
app = typer.Typer(
|
||||
name="changelog",
|
||||
help="📝 Generate changelogs from git history.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("generate")
|
||||
def generate_changelog(
|
||||
output: Annotated[
|
||||
str,
|
||||
typer.Option(
|
||||
"--output",
|
||||
"-o",
|
||||
help="Output file path.",
|
||||
),
|
||||
] = "CHANGELOG.md",
|
||||
from_ref: Annotated[
|
||||
str,
|
||||
typer.Option(
|
||||
"--from",
|
||||
"-f",
|
||||
help="Starting git reference (tag or hash). Defaults to last tag.",
|
||||
),
|
||||
] = "",
|
||||
) -> None:
|
||||
generator = ChangelogGenerator()
|
||||
try:
|
||||
generator.run(output_file=output, from_ref=from_ref)
|
||||
except Exception as e:
|
||||
typer.secho(f"Error generating changelog: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
@@ -0,0 +1,96 @@
|
||||
from typing import Annotated
|
||||
|
||||
import typer
|
||||
|
||||
from devgen.modules.commit_generator import run_commit_engine
|
||||
from devgen.utils import (
|
||||
configure_logger,
|
||||
delete_file,
|
||||
get_commit_dry_run_path,
|
||||
get_git_staged_files,
|
||||
get_main_log_path,
|
||||
read_file_content,
|
||||
)
|
||||
|
||||
app = typer.Typer(
|
||||
name="commit",
|
||||
help="🚀 AI-powered semantic commit message generator.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("run")
|
||||
def run_commit(
|
||||
dry_run: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--dry-run",
|
||||
help="Simulate the commit process without making changes.",
|
||||
),
|
||||
] = False,
|
||||
push: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--push",
|
||||
help="Automatically push changes to the remote repository.",
|
||||
),
|
||||
] = False,
|
||||
debug: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--debug",
|
||||
help="Enable debug mode for detailed logging.",
|
||||
),
|
||||
] = False,
|
||||
force_rebuild: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--force-rebuild",
|
||||
help="Force regeneration of commit messages.",
|
||||
),
|
||||
] = False,
|
||||
) -> None:
|
||||
log_file = get_main_log_path()
|
||||
logger = configure_logger("devgen.cli.commit", log_file)
|
||||
logger.info(f"Log file: {log_file}")
|
||||
logger.info(
|
||||
f"Options: dry_run={dry_run}, push={push}, debug={debug}, force={force_rebuild}"
|
||||
)
|
||||
|
||||
run_commit_engine(
|
||||
dry_run=dry_run,
|
||||
push=push,
|
||||
debug=debug,
|
||||
force_rebuild=force_rebuild,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
|
||||
@app.command("clear-cache")
|
||||
def clear_cache() -> None:
|
||||
if delete_file(get_commit_dry_run_path()):
|
||||
typer.secho("Cache cleared.", fg=typer.colors.GREEN)
|
||||
else:
|
||||
typer.secho("[i] No cache found.", fg=typer.colors.YELLOW)
|
||||
|
||||
|
||||
@app.command("list-cached")
|
||||
def list_cached() -> None:
|
||||
content = read_file_content(get_commit_dry_run_path())
|
||||
if content:
|
||||
typer.secho("--- Cached Dry-Run ---", fg=typer.colors.CYAN)
|
||||
typer.echo(content)
|
||||
else:
|
||||
typer.secho("[i] No cache found.", fg=typer.colors.YELLOW)
|
||||
|
||||
|
||||
@app.command("validate")
|
||||
def validate() -> None:
|
||||
staged = get_git_staged_files()
|
||||
if staged:
|
||||
typer.secho(f"{len(staged)} staged file(s):", fg=typer.colors.GREEN)
|
||||
for f in staged:
|
||||
typer.echo(f"- {f}")
|
||||
else:
|
||||
typer.secho("[i] No staged files.", fg=typer.colors.RED)
|
||||
@@ -0,0 +1,133 @@
|
||||
from typing import List, Optional
|
||||
|
||||
import questionary
|
||||
import typer
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from devgen.modules.gitignore_generator import GitignoreGenerator
|
||||
|
||||
app = typer.Typer(
|
||||
name="gitignore",
|
||||
help="🙈 Generate .gitignore files from GitHub templates.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("list")
|
||||
def list_templates(
|
||||
cached: Annotated[
|
||||
bool, typer.Option("--cached", "-c", help="List only cached templates.")
|
||||
] = False,
|
||||
) -> None:
|
||||
generator = GitignoreGenerator()
|
||||
try:
|
||||
if cached:
|
||||
templates = generator.list_cached_templates()
|
||||
typer.secho("Cached Templates:", fg=typer.colors.CYAN, bold=True)
|
||||
else:
|
||||
typer.secho("Fetching available templates...", fg=typer.colors.YELLOW)
|
||||
templates = generator.list_available_templates()
|
||||
typer.secho("Available Templates:", fg=typer.colors.CYAN, bold=True)
|
||||
|
||||
if not templates:
|
||||
typer.echo("No templates found.")
|
||||
return
|
||||
|
||||
# Print in columns or just list
|
||||
typer.echo(", ".join(templates))
|
||||
|
||||
except Exception as e:
|
||||
typer.secho(f"Error: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
|
||||
@app.command("generate")
|
||||
def generate_gitignore(
|
||||
templates: Annotated[
|
||||
Optional[List[str]],
|
||||
typer.Argument(
|
||||
help="Names of templates to include (e.g. Python Node). If empty, interactive mode is used."
|
||||
),
|
||||
] = None,
|
||||
output: Annotated[
|
||||
str,
|
||||
typer.Option("--output", "-o", help="Output file path."),
|
||||
] = ".gitignore",
|
||||
append: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--append/--overwrite",
|
||||
"-a/-w",
|
||||
help="Append to existing file or overwrite.",
|
||||
),
|
||||
] = True,
|
||||
offline: Annotated[
|
||||
bool,
|
||||
typer.Option("--offline", help="Use only cached templates."),
|
||||
] = False,
|
||||
) -> None:
|
||||
generator = GitignoreGenerator()
|
||||
|
||||
if not templates:
|
||||
# Interactive mode
|
||||
try:
|
||||
if offline:
|
||||
available = generator.list_cached_templates()
|
||||
else:
|
||||
typer.secho("Fetching templates list...", fg=typer.colors.YELLOW)
|
||||
available = generator.list_available_templates()
|
||||
|
||||
if not available:
|
||||
typer.secho("No templates available.", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
from devgen.utils import get_questionary_style
|
||||
|
||||
style = get_questionary_style()
|
||||
|
||||
# Interactive search loop
|
||||
selected_templates = []
|
||||
while True:
|
||||
# Filter out already selected
|
||||
choices = [t for t in available if t not in selected_templates]
|
||||
# Add "Done" option at the top
|
||||
choices.insert(0, "Done (Finish selection)")
|
||||
|
||||
choice = questionary.autocomplete(
|
||||
"Search for a template (type to search, select 'Done' to finish):",
|
||||
choices=choices,
|
||||
ignore_case=True,
|
||||
match_middle=True,
|
||||
validate=lambda x: x in choices or x == "",
|
||||
style=style,
|
||||
).ask()
|
||||
|
||||
if not choice or choice.startswith("Done"):
|
||||
break
|
||||
|
||||
selected_templates.append(choice)
|
||||
typer.secho(f"Added '{choice}'", fg=typer.colors.GREEN)
|
||||
|
||||
templates = selected_templates
|
||||
|
||||
if not templates:
|
||||
typer.secho("No templates selected.", fg=typer.colors.YELLOW)
|
||||
raise typer.Exit()
|
||||
|
||||
except typer.Exit:
|
||||
raise
|
||||
except KeyboardInterrupt:
|
||||
typer.secho("\n Cancelled by user", fg=typer.colors.YELLOW)
|
||||
raise typer.Exit()
|
||||
except Exception as e:
|
||||
typer.secho(f"Error fetching templates: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
try:
|
||||
generator.generate(
|
||||
templates, output_file=output, append=append, offline=offline
|
||||
)
|
||||
except Exception as e:
|
||||
typer.secho(f"Error generating .gitignore: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
@@ -0,0 +1,91 @@
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import questionary
|
||||
import typer
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from devgen.modules.license_generator import LicenseGenerator
|
||||
|
||||
app = typer.Typer(
|
||||
name="license",
|
||||
help="📄 Generate open source licenses.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("generate")
|
||||
def generate_license(
|
||||
output: Annotated[
|
||||
str,
|
||||
typer.Option(
|
||||
"--output",
|
||||
"-o",
|
||||
help="Output file path.",
|
||||
),
|
||||
] = "LICENSE",
|
||||
) -> None:
|
||||
generator = LicenseGenerator()
|
||||
licenses = generator.list_licenses()
|
||||
|
||||
if not licenses:
|
||||
typer.secho("❌ No license templates found.", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
from devgen.utils import get_questionary_style
|
||||
|
||||
style = get_questionary_style()
|
||||
|
||||
# 1. Select License
|
||||
choices = [
|
||||
questionary.Choice(
|
||||
title=f"{lic['name']} ({lic['key']})",
|
||||
value=lic["key"],
|
||||
description=lic["description"],
|
||||
)
|
||||
for lic in licenses
|
||||
]
|
||||
|
||||
license_key = questionary.select(
|
||||
"Select a License:",
|
||||
choices=choices,
|
||||
use_indicator=True,
|
||||
use_shortcuts=True,
|
||||
style=style,
|
||||
).ask()
|
||||
|
||||
if not license_key:
|
||||
raise typer.Exit()
|
||||
|
||||
# 2. Enter Author Name
|
||||
# Try to guess from git config if possible, but for now just empty default
|
||||
author = questionary.text("Enter Author Name:", style=style).ask()
|
||||
|
||||
if not author:
|
||||
typer.secho("❌ Author name is required.", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
# 3. Enter Year
|
||||
current_year = str(datetime.now().year)
|
||||
year = questionary.text("Enter Year:", default=current_year, style=style).ask()
|
||||
|
||||
# Generate
|
||||
try:
|
||||
content = generator.render_license(license_key, author, year)
|
||||
|
||||
output_path = Path(output)
|
||||
if output_path.exists():
|
||||
overwrite = questionary.confirm(
|
||||
f"File {output} already exists. Overwrite?", default=False, style=style
|
||||
).ask()
|
||||
if not overwrite:
|
||||
typer.secho("Operation cancelled.", fg=typer.colors.YELLOW)
|
||||
raise typer.Exit()
|
||||
|
||||
output_path.write_text(content, encoding="utf-8")
|
||||
typer.secho(f"\n License generated at {output_path}", fg=typer.colors.GREEN)
|
||||
|
||||
except Exception as e:
|
||||
typer.secho(f"\n Failed to generate license: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
@@ -0,0 +1,99 @@
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
|
||||
import toml
|
||||
import typer
|
||||
|
||||
from devgen.cli.changelog import app as changelog_app
|
||||
from devgen.cli.commit import app as commit_app
|
||||
from devgen.cli.gitignore import app as gitignore_app
|
||||
from devgen.cli.license import app as license_app
|
||||
from devgen.cli.release import app as release_app
|
||||
from devgen.cli.setup import app as setup_app
|
||||
|
||||
app = typer.Typer(
|
||||
name="devgen",
|
||||
help="devgen-py: AI-Powered Git Commit & Release Automation.",
|
||||
add_completion=False,
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
def _version_callback(value: bool) -> None:
|
||||
"""Displays the application version retrieved from pyproject.toml if the input value is True, then exits the program. If the version information cannot be found or the file is missing or malformed, outputs an error message before exiting.
|
||||
|
||||
Args:
|
||||
value (bool): A boolean flag indicating whether to display the version and exit.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Raises:
|
||||
typer.Exit: Exits the program after attempting to display the version or an error message.
|
||||
"""
|
||||
if value:
|
||||
try:
|
||||
pyproject_path = Path(__file__).parent.parent.parent / "pyproject.toml"
|
||||
pyproject_data = toml.load(pyproject_path)
|
||||
# Try standard PEP 621 first, then fallback
|
||||
version = pyproject_data.get("project", {}).get("version")
|
||||
if not version:
|
||||
version = (
|
||||
pyproject_data.get("tool", {}).get("poetry", {}).get("version")
|
||||
)
|
||||
|
||||
if version:
|
||||
typer.echo(f"devgen version: {version}")
|
||||
else:
|
||||
typer.secho(
|
||||
"Error: Version not found in pyproject.toml",
|
||||
fg=typer.colors.RED,
|
||||
err=True,
|
||||
)
|
||||
except (FileNotFoundError, KeyError, Exception) as e:
|
||||
typer.secho(
|
||||
f"Error: Could not determine version: {e}",
|
||||
fg=typer.colors.RED,
|
||||
err=True,
|
||||
)
|
||||
raise typer.Exit()
|
||||
|
||||
|
||||
@app.callback()
|
||||
def main_callback(
|
||||
version: Annotated[
|
||||
bool | None,
|
||||
typer.Option(
|
||||
"--version",
|
||||
"-v",
|
||||
callback=_version_callback,
|
||||
is_eager=True,
|
||||
help="Show the application version and exit.",
|
||||
),
|
||||
] = None,
|
||||
) -> None:
|
||||
"""Displays the application version information when the --version or -v option is used. If the flag is set, shows the version and exits; otherwise, provides guidance on using other commands with devgen.
|
||||
|
||||
Args:
|
||||
version (bool or None, optional): A flag indicating whether to display the application version, set via command-line options --version or -v. Defaults to None.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
app.add_typer(commit_app, name="commit")
|
||||
app.add_typer(setup_app, name="setup")
|
||||
app.add_typer(changelog_app, name="changelog")
|
||||
app.add_typer(license_app, name="license")
|
||||
app.add_typer(gitignore_app, name="gitignore")
|
||||
app.add_typer(release_app, name="release")
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
app()
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n Operation cancelled by user.")
|
||||
raise typer.Exit(code=130)
|
||||
@@ -0,0 +1,30 @@
|
||||
import typer
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from devgen.modules.release_note_generator import ReleaseNotesGenerator
|
||||
|
||||
app = typer.Typer(
|
||||
name="release",
|
||||
help="🚀 Generate release notes from git history.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("notes")
|
||||
def generate_release_notes(
|
||||
version: Annotated[
|
||||
str,
|
||||
typer.Option("--version", "-v", help="Version for this release (ex: 1.4.0)"),
|
||||
] = "Unreleased",
|
||||
output: Annotated[
|
||||
str,
|
||||
typer.Option("--output", "-o", help="Output file path."),
|
||||
] = "RELEASE-NOTES.md",
|
||||
from_ref: Annotated[
|
||||
str,
|
||||
typer.Option("--from", "-f", help="Start reference. Defaults to last tag."),
|
||||
] = "",
|
||||
):
|
||||
generator = ReleaseNotesGenerator()
|
||||
generator.run(output_file=output, version=version, from_ref=from_ref)
|
||||
@@ -0,0 +1,76 @@
|
||||
from pathlib import Path
|
||||
|
||||
import questionary
|
||||
import typer
|
||||
import yaml
|
||||
|
||||
app = typer.Typer(
|
||||
name="setup",
|
||||
help="⚙️ Setup and configuration management.",
|
||||
no_args_is_help=True,
|
||||
rich_markup_mode="markdown",
|
||||
)
|
||||
|
||||
|
||||
@app.command("config")
|
||||
def setup_config() -> None:
|
||||
typer.secho("🛠️ Interactive Configuration Setup", fg=typer.colors.CYAN, bold=True)
|
||||
|
||||
config_path = Path.home() / ".devgen.yaml"
|
||||
current_config = {}
|
||||
if config_path.exists():
|
||||
try:
|
||||
with config_path.open("r", encoding="utf-8") as f:
|
||||
current_config = yaml.safe_load(f) or {}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from devgen.utils import get_questionary_style
|
||||
|
||||
style = get_questionary_style()
|
||||
|
||||
# Questions
|
||||
provider = questionary.select(
|
||||
"Select AI Provider:",
|
||||
choices=["gemini", "openai", "huggingface", "openrouter", "anthropic"],
|
||||
default=current_config.get("provider", "gemini"),
|
||||
style=style,
|
||||
).ask()
|
||||
|
||||
model_default = current_config.get("model", "gemini-2.5-flash")
|
||||
|
||||
model = questionary.text(
|
||||
"Enter Model Name:", default=model_default, style=style
|
||||
).ask()
|
||||
|
||||
api_key = questionary.password(
|
||||
"Enter API Key (leave empty to keep existing or none):", style=style
|
||||
).ask()
|
||||
|
||||
if not api_key:
|
||||
api_key = current_config.get("api_key", "")
|
||||
|
||||
emoji_choice = questionary.select(
|
||||
"Use Emojis in Commit Messages?",
|
||||
choices=["Yes", "No"],
|
||||
default="Yes" if current_config.get("emoji", True) else "No",
|
||||
style=style,
|
||||
).ask()
|
||||
emoji = emoji_choice == "Yes"
|
||||
|
||||
# Save Config
|
||||
new_config = {
|
||||
"provider": provider,
|
||||
"model": model,
|
||||
"api_key": api_key,
|
||||
"emoji": emoji,
|
||||
}
|
||||
|
||||
try:
|
||||
with config_path.open("w", encoding="utf-8") as f:
|
||||
yaml.dump(new_config, f, default_flow_style=False)
|
||||
typer.secho(f"\n Configuration saved to {config_path}", fg=typer.colors.GREEN)
|
||||
typer.echo(yaml.dump(new_config, default_flow_style=False))
|
||||
except Exception as e:
|
||||
typer.secho(f"\n Failed to save configuration: {e}", fg=typer.colors.RED)
|
||||
raise typer.Exit(code=1)
|
||||
Whitespace-only changes.
@@ -0,0 +1,181 @@
|
||||
import re
|
||||
import subprocess
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from devgen.utils import configure_logger
|
||||
|
||||
|
||||
class ChangelogGenerator:
|
||||
"""Generates a changelog from git history using Semantic Release style."""
|
||||
|
||||
def __init__(self, logger=None):
|
||||
self.logger = logger or configure_logger("devgen.changelog")
|
||||
|
||||
def _exec_git(self, args: List[str]) -> str:
|
||||
"""Executes a git command."""
|
||||
try:
|
||||
res = subprocess.run(
|
||||
args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=True,
|
||||
)
|
||||
return res.stdout.strip()
|
||||
except subprocess.CalledProcessError as e:
|
||||
self.logger.error(f"Git command failed: {e}")
|
||||
raise RuntimeError(f"Git command failed: {e}")
|
||||
|
||||
def get_commits(self, from_ref: str = "", to_ref: str = "HEAD") -> List[str]:
|
||||
"""Fetches commit messages in the specified range."""
|
||||
range_spec = f"{from_ref}..{to_ref}" if from_ref else to_ref
|
||||
# Format: hash|author|date|subject|body
|
||||
fmt = "%H|%an|%ad|%s|%b"
|
||||
cmd = ["git", "log", f"--format={fmt}", "--date=short", range_spec]
|
||||
|
||||
if not from_ref:
|
||||
# If no start ref, try to find the last tag
|
||||
try:
|
||||
last_tag = self._exec_git(["git", "describe", "--tags", "--abbrev=0"])
|
||||
cmd = [
|
||||
"git",
|
||||
"log",
|
||||
f"--format={fmt}",
|
||||
"--date=short",
|
||||
f"{last_tag}..HEAD",
|
||||
]
|
||||
self.logger.info(f"Generating changelog from last tag: {last_tag}")
|
||||
except RuntimeError:
|
||||
self.logger.info("No tags found, generating for all commits.")
|
||||
cmd = ["git", "log", f"--format={fmt}", "--date=short"]
|
||||
|
||||
return self._exec_git(cmd).split("\n")
|
||||
|
||||
def parse_commits(self, raw_commits: List[str]) -> Dict[str, List[Dict]]:
|
||||
"""Parses raw commit strings into structured data."""
|
||||
groups = defaultdict(list)
|
||||
# Conventional Commit Regex: type(scope)!: subject
|
||||
cc_pattern = re.compile(r"^(\w+)(?:\(([^)]+)\))?(!?):\s+(.*)")
|
||||
|
||||
for line in raw_commits:
|
||||
if not line.strip():
|
||||
continue
|
||||
|
||||
parts = line.split("|", 4)
|
||||
if len(parts) < 4:
|
||||
continue
|
||||
|
||||
commit_hash, author, date, subject, body = (
|
||||
parts[0],
|
||||
parts[1],
|
||||
parts[2],
|
||||
parts[3],
|
||||
parts[4] if len(parts) > 4 else "",
|
||||
)
|
||||
|
||||
match = cc_pattern.match(subject)
|
||||
if match:
|
||||
c_type, c_scope, breaking, c_subject = match.groups()
|
||||
entry = {
|
||||
"hash": commit_hash,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"scope": c_scope,
|
||||
"subject": c_subject,
|
||||
"body": body,
|
||||
"breaking": bool(breaking),
|
||||
}
|
||||
|
||||
if breaking:
|
||||
groups["BREAKING CHANGES"].append(entry)
|
||||
|
||||
if c_type in ["feat", "feature"]:
|
||||
groups["Features"].append(entry)
|
||||
elif c_type in ["fix", "bug"]:
|
||||
groups["Bug Fixes"].append(entry)
|
||||
elif c_type in ["docs"]:
|
||||
groups["Documentation"].append(entry)
|
||||
elif c_type in [
|
||||
"style",
|
||||
"refactor",
|
||||
"perf",
|
||||
"test",
|
||||
"build",
|
||||
"ci",
|
||||
"chore",
|
||||
]:
|
||||
groups["Other Changes"].append(entry)
|
||||
else:
|
||||
groups["Other Changes"].append(entry)
|
||||
else:
|
||||
# Non-conventional commits
|
||||
groups["Other Changes"].append(
|
||||
{
|
||||
"hash": commit_hash,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"scope": None,
|
||||
"subject": subject,
|
||||
"body": body,
|
||||
"breaking": False,
|
||||
}
|
||||
)
|
||||
|
||||
return groups
|
||||
|
||||
def generate_markdown(
|
||||
self, groups: Dict[str, List[Dict]], version: str = "Unreleased"
|
||||
) -> str:
|
||||
"""Generates markdown changelog from parsed commits."""
|
||||
date_str = datetime.now().strftime("%Y-%m-%d")
|
||||
md = [f"# {version} ({date_str})\n"]
|
||||
|
||||
# Order: Breaking, Features, Fixes, Docs, Others
|
||||
order = [
|
||||
"BREAKING CHANGES",
|
||||
"Features",
|
||||
"Bug Fixes",
|
||||
"Documentation",
|
||||
"Other Changes",
|
||||
]
|
||||
|
||||
for section in order:
|
||||
commits = groups.get(section)
|
||||
if commits:
|
||||
md.append(f"## {section}\n")
|
||||
for c in commits:
|
||||
scope = f"**{c['scope']}**: " if c["scope"] else ""
|
||||
md.append(f"- {scope}{c['subject']} ({c['hash'][:7]})")
|
||||
md.append("")
|
||||
|
||||
return "\n".join(md)
|
||||
|
||||
def run(self, output_file: Optional[str] = "CHANGELOG.md", from_ref: str = ""):
|
||||
"""Main execution method."""
|
||||
raw_commits = self.get_commits(from_ref)
|
||||
if not raw_commits or not raw_commits[0]:
|
||||
self.logger.warning("No commits found.")
|
||||
return
|
||||
|
||||
parsed = self.parse_commits(raw_commits)
|
||||
md_content = self.generate_markdown(parsed)
|
||||
|
||||
if output_file:
|
||||
path = Path(output_file)
|
||||
# If file exists, prepend? For now, just overwrite or append logic could be complex.
|
||||
# Let's implement prepend logic if file exists.
|
||||
if path.exists():
|
||||
old_content = path.read_text(encoding="utf-8")
|
||||
new_content = md_content + "\n\n" + old_content
|
||||
path.write_text(new_content, encoding="utf-8")
|
||||
else:
|
||||
path.write_text(md_content, encoding="utf-8")
|
||||
|
||||
self.logger.info(f"Changelog written to {output_file}")
|
||||
print(f"Changelog updated: {output_file}")
|
||||
else:
|
||||
print(md_content)
|
||||
@@ -0,0 +1,257 @@
|
||||
import subprocess
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from devgen.ai import generate_with_ai
|
||||
from devgen.utils import (
|
||||
configure_logger,
|
||||
extract_commit_messages,
|
||||
get_commit_dry_run_path,
|
||||
is_file_recent,
|
||||
load_template_env,
|
||||
sanitize_ai_commit_message,
|
||||
)
|
||||
|
||||
|
||||
class CommitEngineError(Exception):
|
||||
"""Exception raised for errors in the commit engine."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class CommitEngine:
|
||||
"""
|
||||
Engine for generating AI-powered commit messages.
|
||||
Handles detection of changes, grouping, AI generation, and git operations.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dry_run: bool = False,
|
||||
push: bool = False,
|
||||
debug: bool = False,
|
||||
force_rebuild: bool = False,
|
||||
provider: str = "gemini",
|
||||
model: str = "gemini-2.5-flash",
|
||||
logger: Any | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.dry_run = dry_run
|
||||
self.push = push
|
||||
self.debug = debug
|
||||
self.force_rebuild = force_rebuild
|
||||
self.provider = provider
|
||||
self.model = model
|
||||
self.logger = logger or configure_logger(
|
||||
"devgen.commit", Path.home() / ".cache" / "devgen" / "commit.log"
|
||||
)
|
||||
self.kwargs = kwargs
|
||||
self.dry_run_path = get_commit_dry_run_path()
|
||||
self.template_env = load_template_env("commit")
|
||||
|
||||
# Load config from ~/.devgen.yaml
|
||||
from devgen.utils import load_config
|
||||
|
||||
self.config = load_config()
|
||||
|
||||
def _exec_git(self, args: List[str], allow_error: bool = False) -> str:
|
||||
"""Executes a git command."""
|
||||
try:
|
||||
res = subprocess.run(
|
||||
args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=not allow_error,
|
||||
)
|
||||
return res.stdout.strip()
|
||||
except subprocess.CalledProcessError as e:
|
||||
msg = f"Git command failed: {' '.join(e.cmd)}\nError: {e.stderr.strip()}"
|
||||
self.logger.error(msg)
|
||||
raise CommitEngineError(msg) from e
|
||||
|
||||
def detect_changes(self) -> List[str]:
|
||||
"""Detects changed, deleted, or untracked files."""
|
||||
out = self._exec_git(
|
||||
[
|
||||
"git",
|
||||
"ls-files",
|
||||
"--deleted",
|
||||
"--modified",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
]
|
||||
)
|
||||
return [f.strip() for f in out.split("\n") if f.strip()]
|
||||
|
||||
def group_files(self, files: List[str]) -> Dict[str, List[str]]:
|
||||
"""Groups files by their parent directory."""
|
||||
groups = defaultdict(list)
|
||||
for f in files:
|
||||
parent = str(Path(f).parent)
|
||||
key = "root" if parent == "." else parent
|
||||
groups[key].append(f)
|
||||
return groups
|
||||
|
||||
def generate_diff(self, files: List[str]) -> str:
|
||||
"""Generates diff for specific files."""
|
||||
return self._exec_git(["git", "--no-pager", "diff", "--staged", "--", *files])
|
||||
|
||||
def _init_dry_run(self):
|
||||
"""Initializes the dry-run file."""
|
||||
self.dry_run_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.dry_run_path.open("w", encoding="utf-8") as f:
|
||||
ts = datetime.now().astimezone().strftime("%Y-%m-%d %H:%M:%S (%Z)")
|
||||
f.write(f"# Dry Run: Commit Messages\n_Generated: {ts}_\n\n")
|
||||
|
||||
def _log_dry_run(self, group: str, msg: str):
|
||||
"""Appends a dry-run entry."""
|
||||
with self.dry_run_path.open("a", encoding="utf-8") as f:
|
||||
f.write(f"## Group: `{group}`\n\n```md\n{msg}\n```\n\n---\n\n")
|
||||
|
||||
def stage_files(self, files: List[str]):
|
||||
"""Stages files in git."""
|
||||
if not files:
|
||||
return
|
||||
self.logger.info(f"Staging: {files}")
|
||||
self._exec_git(["git", "add", *files])
|
||||
|
||||
def commit_staged(self, msg: str):
|
||||
"""Commits staged changes."""
|
||||
self.logger.info(f"Committing:\n{msg}")
|
||||
self._exec_git(["git", "commit", "-m", msg])
|
||||
|
||||
def push_commits(self):
|
||||
"""Pushes commits to remote."""
|
||||
self.logger.info("Pushing to remote...")
|
||||
self._exec_git(["git", "push"])
|
||||
self.logger.info("Push successful.")
|
||||
|
||||
def generate_message(self, group: str, diff: str, cache: Dict[str, str]) -> str:
|
||||
"""Generates a commit message using AI or cache."""
|
||||
if not self.force_rebuild and group in cache:
|
||||
self.logger.info(f"Using cached message for {group}")
|
||||
return cache[group]
|
||||
|
||||
# Get settings from config or kwargs
|
||||
provider = (
|
||||
self.kwargs.get("provider") or self.config.get("provider") or self.provider
|
||||
)
|
||||
model = self.kwargs.get("model") or self.config.get("model") or self.model
|
||||
api_key = self.kwargs.get("api_key") or self.config.get("api_key")
|
||||
use_emoji = self.config.get("emoji", True)
|
||||
|
||||
template = self.template_env.get_template("commit_message.j2")
|
||||
prompt = template.render(group_name=group, diff_text=diff, use_emoji=use_emoji)
|
||||
|
||||
raw = generate_with_ai(
|
||||
prompt,
|
||||
provider=provider,
|
||||
model=model,
|
||||
api_key=api_key,
|
||||
debug=self.debug,
|
||||
**self.kwargs,
|
||||
)
|
||||
return sanitize_ai_commit_message(raw)
|
||||
|
||||
def is_ahead_of_remote(self) -> bool:
|
||||
"""Checks if local branch has unpushed commits."""
|
||||
try:
|
||||
self._exec_git(["git", "fetch", "origin"])
|
||||
count = self._exec_git(
|
||||
["git", "rev-list", "--count", "@{u}..HEAD"], allow_error=True
|
||||
)
|
||||
if count and int(count) > 0:
|
||||
return True
|
||||
except CommitEngineError:
|
||||
# Maybe no upstream
|
||||
return bool(self._exec_git(["git", "rev-parse", "HEAD"], allow_error=True))
|
||||
return False
|
||||
|
||||
def load_cache(self) -> Dict[str, str]:
|
||||
"""Loads dry-run cache."""
|
||||
if self.dry_run:
|
||||
self._init_dry_run()
|
||||
return {}
|
||||
if not self.force_rebuild and is_file_recent(self.dry_run_path):
|
||||
self.logger.info(f"Loading cache from {self.dry_run_path}")
|
||||
return extract_commit_messages(self.dry_run_path)
|
||||
return {}
|
||||
|
||||
def process_group(
|
||||
self, group: str, files: List[str], cache: Dict[str, str]
|
||||
) -> bool:
|
||||
"""Processes a single file group."""
|
||||
self.stage_files(files)
|
||||
diff = self.generate_diff(files)
|
||||
|
||||
if not diff.strip():
|
||||
self.logger.info(f"Skipping empty diff for {group}")
|
||||
self._exec_git(["git", "reset", "HEAD", "--", *files])
|
||||
return True
|
||||
|
||||
msg = self.generate_message(group, diff, cache)
|
||||
if not msg:
|
||||
self.logger.error(f"Empty message for {group}")
|
||||
return False
|
||||
|
||||
if self.dry_run:
|
||||
self._log_dry_run(group, msg)
|
||||
self._exec_git(["git", "reset", "HEAD", "--", *files])
|
||||
else:
|
||||
self.commit_staged(msg)
|
||||
|
||||
return True
|
||||
|
||||
def execute(self):
|
||||
"""Main execution method."""
|
||||
files = self.detect_changes()
|
||||
ahead = self.is_ahead_of_remote()
|
||||
|
||||
if not files and not ahead:
|
||||
self.logger.info("Nothing to commit or push.")
|
||||
return
|
||||
|
||||
failed = []
|
||||
if files:
|
||||
groups = self.group_files(files)
|
||||
cache = self.load_cache()
|
||||
|
||||
for group, group_files in groups.items():
|
||||
try:
|
||||
if not self.process_group(group, group_files, cache):
|
||||
failed.append(group)
|
||||
except KeyboardInterrupt:
|
||||
self.logger.warning("\nOperation interrupted by user.")
|
||||
raise
|
||||
else:
|
||||
self.logger.info("No changes to commit, checking push...")
|
||||
|
||||
if self.push and not self.dry_run:
|
||||
if not failed:
|
||||
self.push_commits()
|
||||
else:
|
||||
self.logger.error("Push aborted due to failed commits.")
|
||||
|
||||
if self.dry_run:
|
||||
self.logger.info(f"Dry run done. See {self.dry_run_path}")
|
||||
else:
|
||||
self.logger.info("Done.")
|
||||
if failed:
|
||||
self.logger.warning(f"Failed groups: {failed}")
|
||||
|
||||
|
||||
def run_commit_engine(**kwargs):
|
||||
"""Entry point for the commit engine."""
|
||||
logger = configure_logger("devgen.commit")
|
||||
try:
|
||||
engine = CommitEngine(**kwargs)
|
||||
engine.execute()
|
||||
except Exception as e:
|
||||
logger.error(f"Commit engine failed: {e}", exc_info=True)
|
||||
|
||||
|
||||
__all__ = ["run_commit_engine"]
|
||||
@@ -0,0 +1,116 @@
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import requests
|
||||
|
||||
from devgen.utils import configure_logger
|
||||
|
||||
|
||||
class GitignoreGenerator:
|
||||
"""Fetches and manages .gitignore templates from GitHub."""
|
||||
|
||||
def __init__(self, logger=None):
|
||||
self.logger = logger or configure_logger("devgen.gitignore")
|
||||
self.cache_dir = Path.home() / ".cache" / "devgen" / "gitignore"
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.api_url = "https://api.github.com/repos/github/gitignore/contents/"
|
||||
self.raw_url_base = "https://raw.githubusercontent.com/github/gitignore/main/"
|
||||
|
||||
def list_available_templates(self) -> List[str]:
|
||||
"""Lists available templates from GitHub."""
|
||||
try:
|
||||
response = requests.get(self.api_url, timeout=10)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return [
|
||||
item["name"].replace(".gitignore", "")
|
||||
for item in data
|
||||
if item["name"].endswith(".gitignore")
|
||||
]
|
||||
except requests.RequestException as e:
|
||||
self.logger.error(f"Failed to fetch templates: {e}")
|
||||
raise RuntimeError(f"Failed to fetch templates: {e}")
|
||||
|
||||
def list_cached_templates(self) -> List[str]:
|
||||
"""Lists cached templates."""
|
||||
if not self.cache_dir.exists():
|
||||
return []
|
||||
return [f.stem for f in self.cache_dir.glob("*.gitignore")]
|
||||
|
||||
def get_template_content(
|
||||
self, name: str, use_cache: bool = True, offline: bool = False
|
||||
) -> str:
|
||||
"""Fetches template content from cache or GitHub."""
|
||||
cache_file = self.cache_dir / f"{name}.gitignore"
|
||||
|
||||
if offline:
|
||||
if cache_file.exists():
|
||||
self.logger.info(f"Using cached template for {name}")
|
||||
return cache_file.read_text(encoding="utf-8")
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"Template '{name}' not found in cache (offline mode)."
|
||||
)
|
||||
|
||||
# Try to fetch from GitHub
|
||||
try:
|
||||
url = f"{self.raw_url_base}{name}.gitignore"
|
||||
response = requests.get(url, timeout=10)
|
||||
|
||||
if response.status_code == 404:
|
||||
# Try with capitalized first letter if lowercase fails, though the list should be accurate
|
||||
# The GitHub repo is case-sensitive for raw URLs usually matching the filename.
|
||||
# The list_available_templates returns exact filenames (minus extension).
|
||||
# So if we use the name from the list, it should be correct.
|
||||
# However, if user inputs manually, we might need to handle case.
|
||||
raise RuntimeError(f"Template '{name}' not found on GitHub.")
|
||||
|
||||
response.raise_for_status()
|
||||
content = response.text
|
||||
|
||||
if use_cache:
|
||||
cache_file.write_text(content, encoding="utf-8")
|
||||
self.logger.info(f"Cached template for {name}")
|
||||
|
||||
return content
|
||||
|
||||
except requests.RequestException as e:
|
||||
if cache_file.exists():
|
||||
self.logger.warning(f"Failed to fetch {name}, using cache: {e}")
|
||||
return cache_file.read_text(encoding="utf-8")
|
||||
raise RuntimeError(f"Failed to fetch {name} and no cache available: {e}")
|
||||
|
||||
def generate(
|
||||
self,
|
||||
templates: List[str],
|
||||
output_file: str = ".gitignore",
|
||||
append: bool = True,
|
||||
offline: bool = False,
|
||||
):
|
||||
"""Generates the .gitignore file."""
|
||||
content = ""
|
||||
for name in templates:
|
||||
try:
|
||||
tpl_content = self.get_template_content(name, offline=offline)
|
||||
content += f"\n### {name} ###\n{tpl_content}\n"
|
||||
except Exception as e:
|
||||
self.logger.error(str(e))
|
||||
print(f" Error fetching {name}: {e}")
|
||||
|
||||
if not content:
|
||||
return
|
||||
|
||||
mode = "a" if append else "w"
|
||||
path = Path(output_file)
|
||||
|
||||
if path.exists() and append:
|
||||
print(f"Appending to {output_file}...")
|
||||
elif path.exists() and not append:
|
||||
print(f"Overwriting {output_file}...")
|
||||
else:
|
||||
print(f"Creating {output_file}...")
|
||||
|
||||
with path.open(mode, encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
|
||||
print(f" Successfully wrote to {output_file}")
|
||||
@@ -0,0 +1,80 @@
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
|
||||
class LicenseGenerator:
|
||||
"""Generates license files from templates."""
|
||||
|
||||
def __init__(self):
|
||||
self.templates_dir = (
|
||||
Path(__file__).parent.parent / "prompt_templates" / "licenses"
|
||||
)
|
||||
|
||||
def list_licenses(self) -> List[Dict[str, str]]:
|
||||
"""Lists available license templates."""
|
||||
licenses = []
|
||||
if not self.templates_dir.exists():
|
||||
return []
|
||||
|
||||
for file_path in self.templates_dir.glob("*.json"):
|
||||
try:
|
||||
with file_path.open("r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
licenses.append(
|
||||
{
|
||||
"key": data.get("key", file_path.stem),
|
||||
"name": data.get("name", "Unknown License"),
|
||||
"description": data.get("description", ""),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Sort by name
|
||||
return sorted(licenses, key=lambda x: x["name"])
|
||||
|
||||
def get_license_template(self, key: str) -> Optional[Dict]:
|
||||
"""Loads a specific license template by key."""
|
||||
# We assume key matches filename for simplicity, or we search.
|
||||
# Based on file listing, filenames match keys (e.g. mit.json -> mit)
|
||||
file_path = self.templates_dir / f"{key}.json"
|
||||
if not file_path.exists():
|
||||
return None
|
||||
|
||||
try:
|
||||
with file_path.open("r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def render_license(self, key: str, author: str, year: str = "") -> str:
|
||||
"""Renders the license content with placeholders replaced."""
|
||||
template_data = self.get_license_template(key)
|
||||
if not template_data:
|
||||
raise ValueError(f"License template '{key}' not found.")
|
||||
|
||||
content = template_data.get("template", "")
|
||||
|
||||
if not year:
|
||||
year = str(datetime.now().year)
|
||||
|
||||
# Replace placeholders
|
||||
# Support various formats found in templates
|
||||
year_placeholders = ["[year]", "[yyyy]", "{{year}}", "<year>"]
|
||||
author_placeholders = [
|
||||
"[fullname]",
|
||||
"[name of copyright owner]",
|
||||
"{{author}}",
|
||||
"<name of author>",
|
||||
"[author]",
|
||||
]
|
||||
|
||||
for p in year_placeholders:
|
||||
content = content.replace(p, year)
|
||||
|
||||
for p in author_placeholders:
|
||||
content = content.replace(p, author)
|
||||
|
||||
return content
|
||||
@@ -0,0 +1,66 @@
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from devgen.modules.changelog_generator import ChangelogGenerator
|
||||
from devgen.utils import configure_logger
|
||||
|
||||
|
||||
class ReleaseNotesGenerator(ChangelogGenerator):
|
||||
"""Generate short, clean release notes from git history."""
|
||||
|
||||
SECTION_EMOJIS = {
|
||||
"BREAKING CHANGES": "⚠️",
|
||||
"Features": "✨",
|
||||
"Bug Fixes": "🐛",
|
||||
"Documentation": "📚",
|
||||
"Refactor": "♻️",
|
||||
"Tests": "✅",
|
||||
"Chore": "🔧",
|
||||
"Style": "✨",
|
||||
"Other Changes": "🧹",
|
||||
}
|
||||
|
||||
def __init__(self, logger=None):
|
||||
super().__init__(logger or configure_logger("devgen.releasenotes"))
|
||||
|
||||
def generate_release_markdown(self, groups, version="Unreleased"):
|
||||
"""Generate human-friendly release notes."""
|
||||
date_str = datetime.now().strftime("%Y-%m-%d")
|
||||
md = [f"## 🚀 Release {version} — {date_str}\n"]
|
||||
|
||||
order = [
|
||||
"BREAKING CHANGES",
|
||||
"Features",
|
||||
"Bug Fixes",
|
||||
"Documentation",
|
||||
"Other Changes",
|
||||
]
|
||||
|
||||
for section in order:
|
||||
commits = groups.get(section)
|
||||
if not commits:
|
||||
continue
|
||||
|
||||
emoji = self.SECTION_EMOJIS.get(section, "")
|
||||
md.append(f"### {emoji} {section}")
|
||||
|
||||
for c in commits:
|
||||
scope = f"**{c['scope']}**: " if c["scope"] else ""
|
||||
md.append(f"- {scope}{c['subject']}")
|
||||
|
||||
md.append("")
|
||||
|
||||
return "\n".join(md)
|
||||
|
||||
def run(self, output_file="RELEASE-NOTES.md", version="Unreleased", from_ref=""):
|
||||
"""Main logic: get commits → parse → generate → write."""
|
||||
raw_commits = self.get_commits(from_ref)
|
||||
if not raw_commits or not raw_commits[0]:
|
||||
print("❗ No commits found for release notes.")
|
||||
return
|
||||
|
||||
parsed = self.parse_commits(raw_commits)
|
||||
md = self.generate_release_markdown(parsed, version=version)
|
||||
|
||||
Path(output_file).write_text(md, encoding="utf-8")
|
||||
print(f" Release notes written to {output_file}")
|
||||
@@ -0,0 +1,21 @@
|
||||
from devgen.providers.anthropic import AnthropicProvider
|
||||
from devgen.providers.gemini import GeminiProvider
|
||||
from devgen.providers.huggingface import HuggingfaceProvider
|
||||
from devgen.providers.openai import OpenaiProvider
|
||||
from devgen.providers.openrouter import OpenrouterProvider
|
||||
|
||||
|
||||
def get_provider(name):
|
||||
name_lower = name.lower()
|
||||
if name_lower == "gemini":
|
||||
return GeminiProvider()
|
||||
elif name_lower == "openai":
|
||||
return OpenaiProvider()
|
||||
elif name_lower == "huggingface":
|
||||
return HuggingfaceProvider()
|
||||
elif name_lower == "openrouter":
|
||||
return OpenrouterProvider()
|
||||
elif name_lower == "anthropic":
|
||||
return AnthropicProvider()
|
||||
|
||||
raise NotImplementedError(f"Provider '{name}' is not implemented yet.")
|
||||
@@ -0,0 +1,23 @@
|
||||
import anthropic
|
||||
|
||||
|
||||
class AnthropicProvider:
|
||||
"""Generates content using Anthropic's Claude models."""
|
||||
|
||||
def generate(
|
||||
self, prompt: str, api_key: str, model: str = "claude-3-opus-20240229", **kwargs
|
||||
) -> str:
|
||||
"""Generates a response using the Anthropic API."""
|
||||
if not api_key:
|
||||
raise ValueError("Anthropic API key is required.")
|
||||
|
||||
try:
|
||||
client = anthropic.Anthropic(api_key=api_key)
|
||||
message = client.messages.create(
|
||||
model=model,
|
||||
max_tokens=1024,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
)
|
||||
return message.content[0].text.strip()
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Anthropic generation failed: {e}")
|
||||
@@ -0,0 +1,24 @@
|
||||
import google.generativeai as genai
|
||||
|
||||
|
||||
class GeminiProvider:
|
||||
"""Generates content using Google's Gemini models."""
|
||||
|
||||
def generate(
|
||||
self, prompt: str, api_key: str, model: str = "gemini-pro", **kwargs
|
||||
) -> str:
|
||||
"""Generates a response using the Gemini API."""
|
||||
if not api_key:
|
||||
raise ValueError("Gemini API key is required.")
|
||||
|
||||
genai.configure(api_key=api_key)
|
||||
|
||||
# Handle model name mapping if needed, or trust user input
|
||||
# gemini-pro is a common default
|
||||
|
||||
try:
|
||||
model_instance = genai.GenerativeModel(model)
|
||||
response = model_instance.generate_content(prompt)
|
||||
return response.text.strip()
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Gemini generation failed: {e}")
|
||||
@@ -0,0 +1,45 @@
|
||||
import requests
|
||||
|
||||
|
||||
class HuggingfaceProvider:
|
||||
"""Generates content using Hugging Face Inference API."""
|
||||
|
||||
API_URL_TEMPLATE = "https://api-inference.huggingface.co/models/{model}"
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
api_key: str,
|
||||
model: str = "mistralai/Mistral-7B-Instruct-v0.2",
|
||||
**kwargs,
|
||||
) -> str:
|
||||
"""Generates a response using Hugging Face API."""
|
||||
if not api_key:
|
||||
raise ValueError("Hugging Face API token is required.")
|
||||
|
||||
api_url = self.API_URL_TEMPLATE.format(model=model)
|
||||
headers = {"Authorization": f"Bearer {api_key}"}
|
||||
|
||||
# HF models often expect specific prompting formats, but we'll send raw prompt
|
||||
# Some models are text-generation, some are conversational.
|
||||
# Assuming text-generation for generic usage.
|
||||
|
||||
payload = {
|
||||
"inputs": prompt,
|
||||
"parameters": {"max_new_tokens": 500, "return_full_text": False},
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(api_url, headers=headers, json=payload)
|
||||
response.raise_for_status()
|
||||
result = response.json()
|
||||
|
||||
if isinstance(result, list) and "generated_text" in result[0]:
|
||||
return result[0]["generated_text"].strip()
|
||||
elif isinstance(result, dict) and "error" in result:
|
||||
raise RuntimeError(f"Hugging Face API error: {result['error']}")
|
||||
else:
|
||||
return str(result)
|
||||
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Hugging Face generation failed: {e}")
|
||||
@@ -0,0 +1,48 @@
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
class OpenaiProvider:
|
||||
"""Generates a response string using the OpenAI ChatCompletion API based on the provided prompt and parameters. This method initializes an OpenAI client with the given API key, sends a chat completion request with specified model and additional parameters, and returns the content of the generated message.
|
||||
|
||||
Args:
|
||||
prompt (str): The input prompt to generate a response for.
|
||||
api_key (str): The API key used to authenticate with the OpenAI service.
|
||||
model (str, optional): The model to use for generation; defaults to "gpt-4o".
|
||||
**kwargs: Additional keyword arguments to customize the API request (e.g., temperature).
|
||||
|
||||
Returns:
|
||||
str: The content of the generated response message.
|
||||
"""
|
||||
|
||||
DEFAULT_MODEL = "gpt-4o"
|
||||
|
||||
def generate(
|
||||
self, prompt: str, api_key: str, model: str | None = None, **kwargs
|
||||
) -> str:
|
||||
"""Generates a response from the OpenAI ChatCompletion API based on the provided prompt and parameters.
|
||||
|
||||
Creates a client instance with the specified API key, sends a chat completion request using the selected model and additional parameters, and returns the generated message content as a string.
|
||||
|
||||
Args:
|
||||
prompt (str): Prompt input.
|
||||
api_key (str): OpenAI API key.
|
||||
model (str, optional): Model to use (default: gpt-4o).
|
||||
**kwargs: Additional OpenAI ChatCompletion parameters (e.g., temperature).
|
||||
|
||||
Returns:
|
||||
str: Generated response content.
|
||||
"""
|
||||
# 1. Create a client instance with the API key.
|
||||
try:
|
||||
client = OpenAI(api_key=api_key)
|
||||
except Exception as e:
|
||||
# Add error handling if the client fails to initialize
|
||||
raise RuntimeError(f"Failed to initialize OpenAI client: {e}")
|
||||
|
||||
# 2. Use the modern API syntax: client.chat.completions.create
|
||||
response = client.chat.completions.create(
|
||||
model=model or self.DEFAULT_MODEL,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
**kwargs,
|
||||
)
|
||||
return response.choices[0].message.content.strip()
|
||||
@@ -0,0 +1,33 @@
|
||||
from openai import OpenAI
|
||||
|
||||
|
||||
class OpenrouterProvider:
|
||||
"""Generates content using OpenRouter (OpenAI-compatible API)."""
|
||||
|
||||
BASE_URL = "https://openrouter.ai/api/v1"
|
||||
|
||||
def generate(
|
||||
self, prompt: str, api_key: str, model: str = "openai/gpt-3.5-turbo", **kwargs
|
||||
) -> str:
|
||||
"""Generates a response using OpenRouter."""
|
||||
if not api_key:
|
||||
raise ValueError("OpenRouter API key is required.")
|
||||
|
||||
try:
|
||||
client = OpenAI(
|
||||
base_url=self.BASE_URL,
|
||||
api_key=api_key,
|
||||
)
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model=model,
|
||||
messages=[{"role": "user", "content": prompt}],
|
||||
extra_headers={
|
||||
"HTTP-Referer": "https://github.com/S4NKALP/devgen", # Optional
|
||||
"X-Title": "devgen CLI", # Optional
|
||||
},
|
||||
**kwargs,
|
||||
)
|
||||
return response.choices[0].message.content.strip()
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"OpenRouter generation failed: {e}")
|
||||
@@ -0,0 +1,15 @@
|
||||
|
||||
Analyze the following git diff for the directory `{{ group_name }}` and generate a detailed semantic release commit message4. Format the output as:
|
||||
1. A summary title in semantic release format (type(scope): summary) — scope can be the directory or 'root'.
|
||||
2. A short summary paragraph if needed.
|
||||
3. Bullet points listing the main changes, grouped as 'New Features', 'Enhancements & Refinements', and 'Bug Fixes' if relevant. Use bold for feature/section names.
|
||||
{% if use_emoji %}
|
||||
4. Use appropriate emojis for the commit type and sections (e.g., 🚀 for features, 🐛 for bugs).
|
||||
{% else %}
|
||||
4. Do NOT use any emojis in the commit message.
|
||||
{% endif %}
|
||||
Output only the commit message, don't include explanations or extra text.
|
||||
|
||||
Here is the git diff for `{{ group_name }}`:
|
||||
|
||||
{{ diff_text }}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "agpl-3.0",
|
||||
"name": "GNU Affero General Public License v3.0",
|
||||
"spdx_id": "AGPL-3.0",
|
||||
"description": "Permissions of this strongest copyleft license are conditioned on making available complete source code of licensed works and modifications, which include larger works using a licensed work, under the same license. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights. When a modified version is used to provide a service over a network, the complete source code of the modified version must be made available.",
|
||||
"template": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (c) {{year}} {{author}}\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate. Many developers of free software are heartened and\nencouraged by the resulting cooperation. However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community. It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server. Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals. This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n \"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The \"source code\" for a work means the prefeLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "apache-2.0",
|
||||
"name": "Apache License 2.0",
|
||||
"spdx_id": "Apache-2.0",
|
||||
"description": "A permissive license whose main conditions require preservation of copyright and license notices. Contributors provide an express grant of patent rights. Licensed works, modifications, and larger works may be distributed under different terms and without source code.",
|
||||
"template": " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this LicLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "bsd-2-clause",
|
||||
"name": "BSD 2-Clause \"Simplified\" License",
|
||||
"spdx_id": "BSD-2-Clause",
|
||||
"description": "A permissive license that comes in two variants, the <a href=\"/licenses/bsd-2-clause/\">BSD 2-Clause</a> and <a href=\"/licenses/bsd-3-clause/\">BSD 3-Clause</a>. Both have very minute differences to the MIT license.",
|
||||
"template": "BSD 2-Clause License\n\nCopyright (c) [year], [fullname]\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "bsd-3-clause",
|
||||
"name": "BSD 3-Clause \"New\" or \"Revised\" License",
|
||||
"spdx_id": "BSD-3-Clause",
|
||||
"description": "A permissive license similar to the <a href=\"/licenses/bsd-2-clause/\">BSD 2-Clause License</a>, but with a 3rd clause that prohibits others from using the name of the copyright holder or its contributors to promote derived products without written consent.",
|
||||
"template": "BSD 3-Clause License\n\nCopyright (c) [year], [fullname]\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "bsl-1.0",
|
||||
"name": "Boost Software License 1.0",
|
||||
"spdx_id": "BSL-1.0",
|
||||
"description": "A simple permissive license only requiring preservation of copyright and license notices for source (and not binary) distribution. Licensed works, modifications, and larger works may be distributed under different terms and without source code.",
|
||||
"template": "Boost Software License - Version 1.0 - August 17th, 2003\n\nPermission is hereby granted, free of charge, to any person or organization\nobtaining a copy of the software and accompanying documentation covered by\nthis license (the \"Software\") to use, reproduce, display, distribute,\nexecute, and transmit the Software, and to prepare derivative works of the\nSoftware, and to permit third-parties to whom the Software is furnished to\ndo so, all subject to the following:\n\nThe copyright notices in the Software and this entire statement, including\nthe above license grant, this restriction and the following disclaimer,\nmust be included in all copies of the Software, in whole or in part, and\nall derivative works of the Software, unless such copies or derivative\nworks are solely in the form of machine-executable object code generated by\na source language processor.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT\nSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE\nFOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "cc0-1.0",
|
||||
"name": "Creative Commons Zero v1.0 Universal",
|
||||
"spdx_id": "CC0-1.0",
|
||||
"description": "The <a href=\"https://creativecommons.org/publicdomain/zero/1.0/\">Creative Commons CC0 Public Domain Dedication</a> waives copyright interest in a work you've created and dedicates it to the world-wide public domain. Use CC0 to opt out of copyright entirely and ensure your work has the widest reach. As with the Unlicense and typical software licenses, CC0 disclaims warranties. CC0 is very similar to the Unlicense.",
|
||||
"template": "Creative Commons Legal Code\n\nCC0 1.0 Universal\n\n CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN\n ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS\n PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM\n THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED\n HEREUNDER.\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclusive Copyright and Related Rights (defined below) upon the creator\nand subsequent owner(s) (each and all, an \"owner\") of an original work of\nauthorship and/or a database (each, a \"Work\").\n\nCertain owners wish to permanently relinquish those rights to a Work for\nthe purpose of contributing to a commons of creative, cultural and\nscientific works (\"Commons\") that the public can reliably and without fear\nof later claims of infringement build upon, modify, incorporate in other\nworks, reuse and redistribute as freely as possible in any form whatsoever\nand for any purposes, including without limitation commercial purposes.\nThese owners may contribute to the Commons to promote the ideal of a free\nculture and the further production of creative, cultural and scientific\nworks, or to gain reputation or greater distribution for their Work in\npart through the use and efforts of others.\n\nFor these and/or other purposes and motivations, and without any\nexpectation of additional consideration or compensation, the person\nassociating CC0 with a Work (the \"Affirmer\"), to the extent that he or she\nis an owner of Copyright and Related Rights in the Work, voluntarily\nelects to apply CC0 to the Work and publicly distribute the Work under its\nterms, with knowledge of his or her Copyright and Related Rights in the\nWork and the meaning and intended legal effect of CC0 on those rights.\n\n1. Copyright and Related Rights. A Work made available under CC0 may be\nprotected by copyright and related or neighboring rights (\"Copyright and\nRelated Rights\"). Copyright and Related Rights include, but are not\nlimited to, the following:\n\n i. the right to reproduce, adapt, distribute, perform, display,\n communicate, and translate a Work;\n ii. moral rights retained by the original author(s) and/or performer(s);\niii. publicity and privacy rights pertaining to a person's image or\n likeness depicted in a Work;\n iv. rights protecting against unfair competition in regards to a Work,\n subject to the limitations in paragraph 4(a), below;\n v. rights protecting the extraction, dissemination, use and reuse of data\n in a Work;\n vi. database rights (such as those arising under Directive 96/9/EC of the\n European Parliament and of the Council of 11 March 1996 on the legal\n protection of databases, and under any national implementation\n thereof, including any amended or successor version of such\n directive); and\nvii. other similar, equivalent or corresponding rights throughout the\n world based on applicable law or treaty, and any national\n implementations thereof.\n\n2. Waiver. To the greatest extent permitted by, but not in contravention\nof, applicable law, Affirmer hereby overtly, fully, permanently,\nirrevocably and unconditionally waives, abandons, and surrenders all of\nAffirmer's Copyright and Related Rights and associated claims and causes\nof action, whether now known or unknown (including existing as well as\nfuture claims and causes of action), in the Work (i) in all territories\nworldwide, (ii) for the maximum duration provided by applicable law or\ntreaty (including future time extensions), (iii) in any current or future\nmedium and for any number of copies, and (iv) for any purpose whatsoever,\nincluding without limitation commercial, advertising or promotional\npurposes (the \"Waiver\"). Affirmer makes the Waiver for the benefit of each\nmember of the public at large and to the detriment of Affirmer's heirs and\nsuccessors, fully intending that such Waiver shall not be subject to\nrevocation, rescission, cancellation, termination, or any other legal or\nequitable action to disrupt the quiet enjoyment of the Work by the public\nas contemplated by Affirmer's express Statement of Purpose.\n\n3. Public License Fallback. Should any part of the Waiver for any reason\nbe judged legally invalid or ineffective under applicable law, then the\nWaiver shall be preserved to the maximum extent permitted taking into\naccount Affirmer's express Statement of Purpose. In addition, to the\nextent the Waiver is so judged Affirmer hereby grants to each affected\nperson a royalty-free, non transferable, non sublicensable, non exclusive,\nirrevocable and unconditional license to exercise Affirmer's CopyrighLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "epl-2.0",
|
||||
"name": "Eclipse Public License 2.0",
|
||||
"spdx_id": "EPL-2.0",
|
||||
"description": "This commercially-friendly copyleft license provides the ability to commercially license binaries; a modern royalty-free patent license grant; and the ability for linked works to use other licenses, including commercial ones.",
|
||||
"template": "Eclipse Public License - v 2.0\n\n THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE\n PUBLIC LICENSE (\"AGREEMENT\"). ANY USE, REPRODUCTION OR DISTRIBUTION\n OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.\n\n1. DEFINITIONS\n\n\"Contribution\" means:\n\n a) in the case of the initial Contributor, the initial content\n Distributed under this Agreement, and\n\n b) in the case of each subsequent Contributor:\n i) changes to the Program, and\n ii) additions to the Program;\n where such changes and/or additions to the Program originate from\n and are Distributed by that particular Contributor. A Contribution\n \"originates\" from a Contributor if it was added to the Program by\n such Contributor itself or anyone acting on such Contributor's behalf.\n Contributions do not include changes or additions to the Program that\n are not Modified Works.\n\n\"Contributor\" means any person or entity that Distributes the Program.\n\n\"Licensed Patents\" mean patent claims licensable by a Contributor which\nare necessarily infringed by the use or sale of its Contribution alone\nor when combined with the Program.\n\n\"Program\" means the Contributions Distributed in accordance with this\nAgreement.\n\n\"Recipient\" means anyone who receives the Program under this Agreement\nor any Secondary License (as applicable), including Contributors.\n\n\"Derivative Works\" shall mean any work, whether in Source Code or other\nform, that is based on (or derived from) the Program and for which the\neditorial revisions, annotations, elaborations, or other modifications\nrepresent, as a whole, an original work of authorship.\n\n\"Modified Works\" shall mean any work in Source Code or other form that\nresults from an addition to, deletion from, or modification of the\ncontents of the Program, including, for purposes of clarity any new file\nin Source Code form that contains any contents of the Program. Modified\nWorks shall not include works that contain only declarations,\ninterfaces, types, classes, structures, or files of the Program solely\nin each case in order to link to, bind by name, or subclass the Program\nor Modified Works thereof.\n\n\"Distribute\" means the acts of a) distributing or b) making available\nin any manner that enables the transfer of a copy.\n\n\"Source Code\" means the form of a Program preferred for making\nmodifications, including but not limited to software source code,\ndocumentation source, and configuration files.\n\n\"Secondary License\" means either the GNU General Public License,\nVersion 2.0, or any later versions of that license, including any\nexceptions or additional permissions as identified by the initial\nContributor.\n\n2. GRANT OF RIGHTS\n\n a) Subject to the terms of this Agreement, each Contributor hereby\n grants Recipient a non-exclusive, worldwide, royalty-free copyright\n license to reproduce, prepare Derivative Works of, publicly display,\n publicly perform, Distribute and sublicense the Contribution of such\n Contributor, if any, and such Derivative Works.\n\n b) Subject to the terms of this Agreement, each Contributor hereby\n grants Recipient a non-exclusive, worldwide, royalty-free patent\n license under Licensed Patents to make, use, sell, offer to sell,\n import and otherwise transfer the Contribution of such Contributor,\n if any, in Source Code or other form. This patent license shall\n apply to the combination of the Contribution and the Program if, at\n the time the Contribution is added by the Contributor, such addition\n of the Contribution causes such combination to be covered by the\n Licensed Patents. The patent license shall not apply to any other\n combinations which include the Contribution. No hardware per se is\n licensed hereunder.\n\n c) Recipient understands that although each Contributor grants the\n licenses to its Contributions set forth herein, no assurances are\n provided by any Contributor that the Program does not infringe the\n patent or other intellectual property rights of any other entity.\n Each Contributor disclaims any liability to Recipient for claims\n brought by any other entity based on infringement of intellectual\n property rights or otherwise. As a condition to exercising the\n rights and licenses granted hereunder, each Recipient hereby\n assumes sole responsibility to secure any other intellectual\n property rights needed, if any. For example, if a third party\n patent license is required to allow Recipient to Distribute the\n Program, it is Recipient's responsibility to acquire that license\n before distributing the Program.\n\n d) Each Contributor represents that to its knowledge it has\n sufficient copyright rights in its Contribution, if any, to grant\n the copyright license set forth in this Agreement.\n\n e) Notwithstanding the terms of any Secondary License, no\n Contributor makes additional grants to any Recipient (othLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "gpl-2.0",
|
||||
"name": "GNU General Public License v2.0",
|
||||
"spdx_id": "GPL-2.0",
|
||||
"description": "The GNU GPL is the most widely used free software license and has a strong copyleft requirement. When distributing derived works, the source code of the work must be made available under the same license. There are multiple variants of the GNU GPL, each with different requirements.",
|
||||
"template": " GNU GENERAL PUBLIC LICENSE\n Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The licenses for most software are designed to take away your\nfreedom to share and change it. By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users. This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it. (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.) You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have. You must make sure that they, too, receive or can get the\nsource code. And you must show them these terms so they know their\nrights.\n\n We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware. If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n Finally, any free program is threatened constantly by software\npatents. We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary. To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n GNU GENERAL PUBLIC LICENSE\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n 0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License. The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage. (Hereinafter, translation is included without limitation in\nthe term \"modification\".) Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope. The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n 1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n 2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n a) You must cause the modified Line truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "gpl-3.0",
|
||||
"name": "GNU General Public License v3.0",
|
||||
"spdx_id": "GPL-3.0",
|
||||
"description": "Permissions of this strong copyleft license are conditioned on making available complete source code of licensed works and modifications, which include larger works using a licensed work, under the same license. Copyright and license notices must be preserved. Contributors provide an express grant of patent rights.",
|
||||
"template": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (c) {{year}} {{author}}\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\n Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n \"This License\" refers to version 3 of the GNU General Public License.\n\n \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n \"The Program\" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as \"you\". \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To \"convey\" a work means any kind of propagation that enables other\nparties to make Line truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "lgpl-2.1",
|
||||
"name": "GNU Lesser General Public License v2.1",
|
||||
"spdx_id": "LGPL-2.1",
|
||||
"description": "Primarily used for software libraries, the GNU LGPL requires that derived works be licensed under the same license, but works that only link to it do not fall under this restriction. There are two commonly used versions of the GNU LGPL.",
|
||||
"template": " GNU LESSER GENERAL PUBLIC LICENSE\n Version 2.1, February 1999\n\n Copyright (C) 1991, 1999 Free Software Foundation, Inc.\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n[This is the first released version of the Lesser GPL. It also counts\n as the successor of the GNU Library Public License, version 2, hence\n the version number 2.1.]\n\n Preamble\n\n The licenses for most software are designed to take away your\nfreedom to share and change it. By contrast, the GNU General Public\nLicenses are intended to guarantee your freedom to share and change\nfree software--to make sure the software is free for all its users.\n\n This license, the Lesser General Public License, applies to some\nspecially designated software packages--typically libraries--of the\nFree Software Foundation and other authors who decide to use it. You\ncan use it too, but we suggest you first think carefully about whether\nthis license or the ordinary General Public License is the better\nstrategy to use in any particular case, based on the explanations below.\n\n When we speak of free software, we are referring to freedom of use,\nnot price. Our General Public Licenses are designed to make sure that\nyou have the freedom to distribute copies of free software (and charge\nfor this service if you wish); that you receive source code or can get\nit if you want it; that you can change the software and use pieces of\nit in new free programs; and that you are informed that you can do\nthese things.\n\n To protect your rights, we need to make restrictions that forbid\ndistributors to deny you these rights or to ask you to surrender these\nrights. These restrictions translate to certain responsibilities for\nyou if you distribute copies of the library or if you modify it.\n\n For example, if you distribute copies of the library, whether gratis\nor for a fee, you must give the recipients all the rights that we gave\nyou. You must make sure that they, too, receive or can get the source\ncode. If you link other code with the library, you must provide\ncomplete object files to the recipients, so that they can relink them\nwith the library after making changes to the library and recompiling\nit. And you must show them these terms so they know their rights.\n\n We protect your rights with a two-step method: (1) we copyright the\nlibrary, and (2) we offer you this license, which gives you legal\npermission to copy, distribute and/or modify the library.\n\n To protect each distributor, we want to make it very clear that\nthere is no warranty for the free library. Also, if the library is\nmodified by someone else and passed on, the recipients should know\nthat what they have is not the original version, so that the original\nauthor's reputation will not be affected by problems that might be\nintroduced by others.\n\n Finally, software patents pose a constant threat to the existence of\nany free program. We wish to make sure that a company cannot\neffectively restrict the users of a free program by obtaining a\nrestrictive license from a patent holder. Therefore, we insist that\nany patent license obtained for a version of the library must be\nconsistent with the full freedom of use specified in this license.\n\n Most GNU software, including some libraries, is covered by the\nordinary GNU General Public License. This license, the GNU Lesser\nGeneral Public License, applies to certain designated libraries, and\nis quite different from the ordinary General Public License. We use\nthis license for certain libraries in order to permit linking those\nlibraries into non-free programs.\n\n When a program is linked with a library, whether statically or using\na shared library, the combination of the two is legally speaking a\ncombined work, a derivative of the original library. The ordinary\nGeneral Public License therefore permits such linking only if the\nentire combination fits its criteria of freedom. The Lesser General\nPublic License permits more lax criteria for linking other code with\nthe library.\n\n We call this license the \"Lesser\" General Public License because it\ndoes Less to protect the user's freedom than the ordinary General\nPublic License. It also provides other free software developers Less\nof an advantage over competing non-free programs. These disadvantages\nare the reason we use the ordinary General Public License for many\nlibraries. However, the Lesser license provides advantages in certain\nspecial circumstances.\n\n For example, on rare occasions, there may be a special need to\nencourage the widest possible use of a certain library, so that it becomes\na de-facto standard. To achieve this, non-free programs must be\nallowed to use the library. A more frequent case is that a free\nLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "mit",
|
||||
"name": "MIT License",
|
||||
"spdx_id": "MIT",
|
||||
"description": "A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.",
|
||||
"template": "MIT License\n\nCopyright (c) [year] [fullname]\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "mpl-2.0",
|
||||
"name": "Mozilla Public License 2.0",
|
||||
"spdx_id": "MPL-2.0",
|
||||
"description": "Permissions of this weak copyleft license are conditioned on making available source code of licensed files and modifications of those files under the same license (or in certain cases, one of the GNU licenses). Copyright and license notices must be preserved. Contributors provide an express grant of patent rights. However, a larger work using the licensed work may be distributed under different terms and without source code for files added in the larger work.",
|
||||
"template": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n means each individual or legal entity that creates, contributes to\n the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n means the combination of the Contributions of others (if any) used\n by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n means Source Code Form to which the initial Contributor has attached\n the notice in Exhibit A, the Executable Form of such Source Code\n Form, and Modifications of such Source Code Form, in each case\n including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n means\n\n (a) that the initial Contributor has attached the notice described\n in Exhibit B to the Covered Software; or\n\n (b) that the Covered Software was made available under the terms of\n version 1.1 or earlier of the License, but not also under the\n terms of a Secondary License.\n\n1.6. \"Executable Form\"\n means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n means a work that combines Covered Software with other material, in\n a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n means this document.\n\n1.9. \"Licensable\"\n means having the right to grant, to the maximum extent possible,\n whether at the time of the initial grant or subsequently, any and\n all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n means any of the following:\n\n (a) any file in Source Code Form that results from an addition to,\n deletion from, or modification of the contents of Covered\n Software; or\n\n (b) any new file in Source Code Form that contains any Covered\n Software.\n\n1.11. \"Patent Claims\" of a Contributor\n means any patent claim(s), including without limitation, method,\n process, and apparatus claims, in any patent Licensable by such\n Contributor that would be infringed, but for the grant of the\n License, by the making, using, selling, offering for sale, having\n made, import, or transfer of either its Contributions or its\n Contributor Version.\n\n1.12. \"Secondary License\"\n means either the GNU General Public License, Version 2.0, the GNU\n Lesser General Public License, Version 2.1, the GNU Affero General\n Public License, Version 3.0, or any later versions of those\n licenses.\n\n1.13. \"Source Code Form\"\n means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n means an individual or a legal entity exercising rights under this\n License. For legal entities, \"You\" includes any entity that\n controls, is controlled by, or is under common control with You. For\n purposes of this definition, \"control\" means (a) the power, direct\n or indirect, to cause the direction or management of such entity,\n whether by contract or otherwise, or (b) ownership of more than\n fifty percent (50%) of the outstanding shares or beneficial\n ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n Licensable by such Contributor to use, reproduce, make available,\n modify, display, perform, distribute, and otherwise exploit its\n Contributions, either on an unmodified basis, with Modifications, or\n as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n for sale, have made, import, and otherwise transfer either its\n Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n or\n\n(b) for infringements caused by: (i) Your and any other third party's\n modifications of Covered Software, or (ii) the combination of its\n Contributions with other software (except as part of its Contributor\n Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n its Contributions.\n\nThis License does not grant any rights in the trademaLine truncated
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"key": "unlicense",
|
||||
"name": "The Unlicense",
|
||||
"spdx_id": "Unlicense",
|
||||
"description": "A license with no conditions whatsoever which dedicates works to the public domain. Unlicensed works, modifications, and larger works may be distributed under different terms and without source code.",
|
||||
"template": "This is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, compile, sell, or\ndistribute this software, either in source code form or as a compiled\nbinary, for any purpose, commercial or non-commercial, and by any\nmeans.\n\nIn jurisdictions that recognize copyright laws, the author or authors\nof this software dedicate any and all copyright interest in the\nsoftware to the public domain. We make this dedication for the benefit\nof the public at large and to the detriment of our heirs and\nsuccessors. We intend this dedication to be an overt act of\nrelinquishment in perpetuity of all present and future rights to this\nsoftware under copyright law.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n\nFor more information, please refer to <https://unlicense.org>\n"
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import yaml
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
|
||||
|
||||
def ensure_log_directory() -> Path:
|
||||
log_dir = Path.home() / ".cache" / "devgen"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return log_dir
|
||||
|
||||
|
||||
def get_main_log_path() -> Path:
|
||||
return ensure_log_directory() / "devgen.log"
|
||||
|
||||
|
||||
def get_commit_dry_run_path() -> Path:
|
||||
return ensure_log_directory() / "commit_dry_run.md"
|
||||
|
||||
|
||||
def is_file_recent(file_path: Path | str, max_age_minutes: int = 120) -> bool:
|
||||
path = Path(file_path)
|
||||
if not path.exists():
|
||||
return False
|
||||
return (time.time() - path.stat().st_mtime) <= max_age_minutes * 60
|
||||
|
||||
|
||||
def sanitize_ai_commit_message(raw_text: str) -> str:
|
||||
lines = raw_text.strip().split("\n")
|
||||
cleaned_lines = []
|
||||
in_block = False
|
||||
# Regex for conventional commit header
|
||||
header_pattern = re.compile(
|
||||
r"^(feat|fix|chore|refactor|docs|style|test|build|ci)(\(.*\))?!?: .*"
|
||||
)
|
||||
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if in_block:
|
||||
if header_pattern.match(stripped) or "**Sponsor**" in line:
|
||||
break
|
||||
cleaned_lines.append(line)
|
||||
elif header_pattern.match(stripped):
|
||||
in_block = True
|
||||
cleaned_lines.append(line)
|
||||
|
||||
return "\n".join(cleaned_lines).strip() if cleaned_lines else ""
|
||||
|
||||
|
||||
def parse_markdown_sections(
|
||||
filepath: Path | str, marker_pattern: str
|
||||
) -> dict[str, str]:
|
||||
path = Path(filepath)
|
||||
if not path.exists():
|
||||
return {}
|
||||
|
||||
with path.open(encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
results = {}
|
||||
matches = re.findall(marker_pattern, content, re.DOTALL)
|
||||
for key, value in matches:
|
||||
results[key] = value.strip()
|
||||
return results
|
||||
|
||||
|
||||
def extract_commit_messages(filepath: Path | str) -> dict[str, str]:
|
||||
pattern = r"## Group: `(.*?)`\s*```md\n(.*?)\n```"
|
||||
return parse_markdown_sections(filepath, pattern)
|
||||
|
||||
|
||||
def configure_logger(
|
||||
name: str = "devgen", log_file: Optional[Path | str] = None
|
||||
) -> logging.Logger:
|
||||
logger = logging.getLogger(name)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
if logger.hasHandlers():
|
||||
logger.handlers.clear()
|
||||
|
||||
formatter = logging.Formatter(
|
||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
|
||||
# Console handler
|
||||
ch = logging.StreamHandler()
|
||||
ch.setFormatter(formatter)
|
||||
logger.addHandler(ch)
|
||||
|
||||
# File handler
|
||||
if log_file:
|
||||
path = Path(log_file)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fh = logging.FileHandler(path, mode="w", encoding="utf-8")
|
||||
fh.setFormatter(formatter)
|
||||
logger.addHandler(fh)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
def get_git_staged_files() -> list[str]:
|
||||
try:
|
||||
res = subprocess.run(
|
||||
["git", "diff", "--name-only", "--cached"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return [f for f in res.stdout.splitlines() if f.strip()]
|
||||
except subprocess.CalledProcessError:
|
||||
return []
|
||||
|
||||
|
||||
def read_file_content(filepath: Path | str) -> Optional[str]:
|
||||
path = Path(filepath)
|
||||
if path.exists():
|
||||
return path.read_text(encoding="utf-8")
|
||||
return None
|
||||
|
||||
|
||||
def delete_file(filepath: Path | str) -> bool:
|
||||
path = Path(filepath)
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def load_template_env(sub_dir: str) -> Environment:
|
||||
template_dir = Path(__file__).parent / "prompt_templates" / sub_dir
|
||||
return Environment(loader=FileSystemLoader(template_dir))
|
||||
|
||||
|
||||
def load_config() -> Dict[str, Any]:
|
||||
config_path = Path.home() / ".devgen.yaml"
|
||||
|
||||
if not config_path.exists():
|
||||
default_config = {
|
||||
"provider": "gemini",
|
||||
"model": "gemini-2.5-flash",
|
||||
"api_key": "",
|
||||
"emoji": True,
|
||||
}
|
||||
try:
|
||||
with config_path.open("w", encoding="utf-8") as f:
|
||||
yaml.dump(default_config, f, default_flow_style=False)
|
||||
# We don't print here to avoid noise during normal execution
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to create default config at {config_path}: {e}")
|
||||
return {}
|
||||
|
||||
try:
|
||||
with config_path.open("r", encoding="utf-8") as f:
|
||||
return yaml.safe_load(f) or {}
|
||||
except Exception as e:
|
||||
print(f"Warning: Failed to load config from {config_path}: {e}")
|
||||
return {}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ensure_log_directory",
|
||||
"get_main_log_path",
|
||||
"get_commit_dry_run_path",
|
||||
"is_file_recent",
|
||||
"sanitize_ai_commit_message",
|
||||
"extract_commit_messages",
|
||||
"configure_logger",
|
||||
"get_git_staged_files",
|
||||
"read_file_content",
|
||||
"delete_file",
|
||||
"load_template_env",
|
||||
"load_config",
|
||||
"get_questionary_style",
|
||||
]
|
||||
|
||||
|
||||
def get_questionary_style():
|
||||
from questionary import Style
|
||||
|
||||
return Style(
|
||||
[
|
||||
("qmark", "fg:#673ab7 bold"), # Token.QuestionMark
|
||||
("question", "bold"), # Token.Question
|
||||
("answer", "fg:#f44336 bold"), # Token.Answer
|
||||
("pointer", "fg:#673ab7 bold"), # Token.Pointer
|
||||
("highlighted", "fg:#673ab7 bold"), # Token.Selected
|
||||
("selected", "fg:#cc5454"), # Token.SelectedItem
|
||||
("separator", "fg:#cc5454"), # Token.Separator
|
||||
("instruction", ""), # Token.Instruction
|
||||
("text", ""), # Token.Text
|
||||
("disabled", "fg:#858585 italic"), # Token.Disabled
|
||||
]
|
||||
)
|
||||
Reference in new issue
Block a user