-
Notifications
You must be signed in to change notification settings - Fork 10.5k
feat(scripts): port create-new-feature, setup-plan and setup-tasks to Python #3386
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
marcelsafin
wants to merge
6
commits into
github:main
Choose a base branch
from
marcelsafin:feat/3280-port-core-scripts
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,427
−1
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e1fcd0c
feat(scripts): port create-new-feature, setup-plan and setup-tasks to…
marcelsafin 83a5dca
fix(tests): treat only None env as unset in parity run helper
marcelsafin d4e4c5e
fix(scripts): fall back to directory scan on any registry error, skip…
marcelsafin 9817517
feat(templates): add py: lines for setup_plan and setup_tasks
marcelsafin 5f2f78e
fix: support py variant in skills placeholder resolver
marcelsafin e223c98
test: pin clean-error behavior for invalid --number
marcelsafin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right,
--no-gitdoes not exist in any variant. That was a description error on my part, not missing code: the flag list should have said--allow-existing-branchonly. PR description fixed. The bash twin has no--no-giteither, so implementing it here would break parity scope.