Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions scripts/python/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,78 @@ def get_feature_paths(
)


def _sorted_preset_ids(presets_dir: Path) -> list[str]:
registry = presets_dir / ".registry"
if registry.is_file():
# Mirrors bash: any failure while reading or sorting the registry
# (invalid JSON, non-dict shapes, unorderable priority values) falls
# back to the directory scan below.
try:
data = json.loads(registry.read_text(encoding="utf-8"))
presets = data.get("presets", {})
return [
pid
for pid, meta in sorted(
presets.items(),
key=lambda kv: kv[1].get("priority", 10)
if isinstance(kv[1], dict)
else 10,
)
if isinstance(meta, dict) and meta.get("enabled", True) is not False
]
except Exception:
pass
try:
return sorted(
p.name
for p in presets_dir.iterdir()
if p.is_dir() and not p.name.startswith(".")
)
except OSError:
return []


def resolve_template(template_name: str, repo_root: Path) -> Path | None:
"""Resolve a template name to a file path using the priority stack.

Order (mirrors resolve_template in scripts/bash/common.sh):
1. .specify/templates/overrides/
2. .specify/presets/<preset-id>/templates/ (sorted by .registry priority)
3. .specify/extensions/<ext-id>/templates/ (hidden directories skipped)
4. .specify/templates/ (core)
"""
base = repo_root / ".specify" / "templates"

override = base / "overrides" / f"{template_name}.md"
if override.is_file():
return override

presets_dir = repo_root / ".specify" / "presets"
if presets_dir.is_dir():
for preset_id in _sorted_preset_ids(presets_dir):
candidate = presets_dir / preset_id / "templates" / f"{template_name}.md"
if candidate.is_file():
return candidate

ext_dir = repo_root / ".specify" / "extensions"
if ext_dir.is_dir():
try:
extensions = sorted(p for p in ext_dir.iterdir() if p.is_dir())
except OSError:
extensions = []
for ext in extensions:
if ext.name.startswith("."):
continue
candidate = ext / "templates" / f"{template_name}.md"
if candidate.is_file():
return candidate

core = base / f"{template_name}.md"
if core.is_file():
return core
return None


def get_invoke_separator(repo_root: Path) -> str:
integration_json = repo_root / ".specify" / "integration.json"
if not integration_json.is_file():
Expand Down
311 changes: 311 additions & 0 deletions scripts/python/create_new_feature.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,311 @@
#!/usr/bin/env python3
"""Create a new feature directory and spec file."""

from __future__ import annotations

import datetime
import json
import re
import shlex
import shutil
import sys
from dataclasses import dataclass
from pathlib import Path

try:
from common import get_repo_root, persist_feature_json, resolve_template
except ImportError: # pragma: no cover - direct execution from unusual cwd
sys.path.insert(0, str(Path(__file__).resolve().parent))
from common import get_repo_root, persist_feature_json, resolve_template


def _json_line(payload: object) -> str:
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n"


_STOP_WORDS = frozenset(
"""
i a an the to for of in on at by with from is are was were be been being
have has had do does did will would should could can may might must shall
this that these those my your our their want need add get set
""".split()
)

_MAX_BRANCH_LENGTH = 244


def _usage(argv0: str) -> str:
return (
f"Usage: {argv0} [--json] [--dry-run] [--allow-existing-branch] "
"[--short-name <name>] [--number N] [--timestamp] <feature_description>"
)


def _help_text(argv0: str) -> str:
return f"""{_usage(argv0)}

Options:
--json Output in JSON format
--dry-run Compute feature name and paths without creating directories or files
--allow-existing-branch Reuse an existing feature directory if it already exists
--short-name <name> Provide a custom short name (2-4 words) for the feature
--number N Specify branch number manually (overrides auto-detection)
--timestamp Use timestamp prefix (YYYYMMDD-HHMMSS) instead of sequential numbering
--help, -h Show this help message

Examples:
{argv0} 'Add user authentication system' --short-name 'user-auth'
{argv0} 'Implement OAuth2 integration for API' --number 5
{argv0} --timestamp --short-name 'user-auth' 'Add user authentication'
"""


@dataclass(frozen=True)
class Args:
json_mode: bool = False
dry_run: bool = False
allow_existing: bool = False
short_name: str = ""
branch_number: str = ""
use_timestamp: bool = False
description: str = ""


def _parse_args(argv: list[str], argv0: str) -> Args:
json_mode = False
dry_run = False
allow_existing = False
short_name = ""
branch_number = ""
use_timestamp = False
rest: list[str] = []

i = 0
while i < len(argv):
arg = argv[i]
if arg == "--json":
json_mode = True
elif arg == "--dry-run":
dry_run = True
elif arg == "--allow-existing-branch":
allow_existing = True
elif arg in {"--short-name", "--number"}:
if i + 1 >= len(argv) or argv[i + 1].startswith("--"):
print(f"Error: {arg} requires a value", file=sys.stderr)
raise SystemExit(1)
i += 1
if arg == "--short-name":
short_name = argv[i]
else:
branch_number = argv[i]
elif arg == "--timestamp":
use_timestamp = True
elif arg in {"--help", "-h"}:
sys.stdout.write(_help_text(argv0))
raise SystemExit(0)
else:
rest.append(arg)
i += 1

description = " ".join(rest).strip()
if not description:
if rest:
print(
"Error: Feature description cannot be empty or contain only whitespace",
file=sys.stderr,
)
else:
print(_usage(argv0), file=sys.stderr)
raise SystemExit(1)

return Args(
json_mode=json_mode,
dry_run=dry_run,
allow_existing=allow_existing,
short_name=short_name,
branch_number=branch_number,
use_timestamp=use_timestamp,
description=description,
)


def _clean_branch_name(name: str) -> str:
cleaned = re.sub(r"[^a-z0-9]", "-", name.lower())
cleaned = re.sub(r"-+", "-", cleaned)
return cleaned.strip("-")


def _generate_branch_name(description: str) -> str:
clean = re.sub(r"[^a-z0-9]", " ", description.lower())
meaningful: list[str] = []
for word in clean.split():
if word in _STOP_WORDS:
continue
if len(word) >= 3:
meaningful.append(word)
# Keep short words that appear as an uppercase acronym in the original,
# mirroring the bash twin's case-sensitive `grep -qw` check.
elif re.search(
rf"(?<![0-9A-Za-z_]){re.escape(word.upper())}(?![0-9A-Za-z_])",
description,
):
meaningful.append(word)

if meaningful:
max_words = 4 if len(meaningful) == 4 else 3
return "-".join(meaningful[:max_words])

cleaned = _clean_branch_name(description)
return "-".join([part for part in cleaned.split("-") if part][:3])


def _get_highest_from_specs(specs_dir: Path) -> int:
highest = 0
if not specs_dir.is_dir():
return highest
for entry in specs_dir.iterdir():
if not entry.is_dir():
continue
name = entry.name
# Match sequential prefixes (>=3 digits), but skip timestamp dirs.
if re.match(r"^[0-9]{3,}-", name) and not re.match(
r"^[0-9]{8}-[0-9]{6}-", name
):
number = int(re.match(r"^[0-9]+", name).group(), 10)
highest = max(highest, number)
return highest


def main(argv: list[str] | None = None) -> int:
argv0 = sys.argv[0]
args = _parse_args(list(argv if argv is not None else sys.argv[1:]), argv0)

repo_root = get_repo_root(Path(__file__))
specs_dir = repo_root / "specs"
if not args.dry_run:
specs_dir.mkdir(parents=True, exist_ok=True)

if args.short_name:
branch_suffix = _clean_branch_name(args.short_name)
else:
branch_suffix = _generate_branch_name(args.description)

branch_number = args.branch_number
if args.use_timestamp and branch_number:
print(
"[specify] Warning: --number is ignored when --timestamp is used",
file=sys.stderr,
)
branch_number = ""

if args.use_timestamp:
feature_num = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
else:
if branch_number:
try:
number = int(branch_number, 10)
except ValueError:
print(
f"Error: --number must be an integer, got '{branch_number}'",
file=sys.stderr,
)
return 1
else:
number = _get_highest_from_specs(specs_dir) + 1
feature_num = f"{number:03d}"
branch_name = f"{feature_num}-{branch_suffix}"

# GitHub enforces a 244-byte limit on branch names.
if len(branch_name) > _MAX_BRANCH_LENGTH:
max_suffix_length = _MAX_BRANCH_LENGTH - (len(feature_num) + 1)
truncated_suffix = re.sub(r"-$", "", branch_suffix[:max_suffix_length])
original_branch_name = branch_name
branch_name = f"{feature_num}-{truncated_suffix}"
print(
"[specify] Warning: Branch name exceeded GitHub's 244-byte limit",
file=sys.stderr,
)
print(
f"[specify] Original: {original_branch_name} "
f"({len(original_branch_name)} bytes)",
file=sys.stderr,
)
print(
f"[specify] Truncated to: {branch_name} ({len(branch_name)} bytes)",
file=sys.stderr,
)

feature_dir = specs_dir / branch_name
spec_file = feature_dir / "spec.md"

if not args.dry_run:
if feature_dir.is_dir() and not args.allow_existing:
if args.use_timestamp:
print(
f"Error: Feature directory '{feature_dir}' already exists. "
"Rerun to get a new timestamp or use a different --short-name.",
file=sys.stderr,
)
else:
print(
f"Error: Feature directory '{feature_dir}' already exists. "
"Please use a different feature name or specify a different "
"number with --number.",
file=sys.stderr,
)
return 1

feature_dir.mkdir(parents=True, exist_ok=True)

if not spec_file.is_file():
template = resolve_template("spec-template", repo_root)
if template is not None and template.is_file():
shutil.copy(template, spec_file)
else:
print(
"Warning: Spec template not found; created empty spec file",
file=sys.stderr,
)
spec_file.touch()

# Persist to .specify/feature.json so downstream commands can find the feature.
persist_feature_json(repo_root, str(feature_dir))

# Inform the user how to set feature state in their own shell.
print(
f"# To persist: export SPECIFY_FEATURE={shlex.quote(branch_name)}",
file=sys.stderr,
)
print(
"# export "
f"SPECIFY_FEATURE_DIRECTORY={shlex.quote(str(feature_dir))}",
file=sys.stderr,
)

if args.json_mode:
payload: dict[str, object] = {
"BRANCH_NAME": branch_name,
"SPEC_FILE": str(spec_file),
"FEATURE_NUM": feature_num,
}
if args.dry_run:
payload["DRY_RUN"] = True
sys.stdout.write(_json_line(payload))
else:
print(f"BRANCH_NAME: {branch_name}")
print(f"SPEC_FILE: {spec_file}")
print(f"FEATURE_NUM: {feature_num}")
if not args.dry_run:
print(
"# To persist in your shell: export "
f"SPECIFY_FEATURE={shlex.quote(branch_name)}"
)
print(
"# export "
f"SPECIFY_FEATURE_DIRECTORY={shlex.quote(str(feature_dir))}"
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading