131 lines
5.2 KiB
Python
Executable File
131 lines
5.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Install implemented Forge skills into a user-level Codex skills directory."""
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import sys
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
SKILLS = ROOT / 'skills'
|
|
RESERVED = {'bortstack-context', 'bortstack-new', 'bortstack-contributor', 'bortstack-design'}
|
|
NAME = re.compile(r'^[a-z][a-z0-9-]*$')
|
|
|
|
|
|
def manifest(path):
|
|
file = path / 'SKILL.md'
|
|
if not file.is_file() or file.is_symlink():
|
|
raise ValueError(f'{path.name}: missing SKILL.md')
|
|
lines = file.read_text(encoding='utf-8').splitlines()
|
|
if not lines or lines[0].strip() != '---':
|
|
raise ValueError(f'{path.name}: missing YAML front matter')
|
|
try:
|
|
end = lines.index('---', 1)
|
|
except ValueError:
|
|
raise ValueError(f'{path.name}: unclosed YAML front matter') from None
|
|
fields = {}
|
|
for line in lines[1:end]:
|
|
if not line.strip() or line.lstrip().startswith('#'):
|
|
continue
|
|
if ':' not in line:
|
|
raise ValueError(f'{path.name}: invalid metadata line')
|
|
key, value = line.split(':', 1)
|
|
if key.strip() in fields:
|
|
raise ValueError(f'{path.name}: duplicate {key.strip()}')
|
|
fields[key.strip()] = value.strip().strip('"\'')
|
|
if fields.get('name') != path.name or not NAME.fullmatch(path.name):
|
|
raise ValueError(f'{path.name}: name must match directory')
|
|
if not fields.get('description'):
|
|
raise ValueError(f'{path.name}: missing description')
|
|
if not any(line.strip() for line in lines[end + 1:]):
|
|
raise ValueError(f'{path.name}: empty skill body')
|
|
return fields
|
|
|
|
|
|
def discover():
|
|
return sorted(p for p in SKILLS.iterdir() if p.is_dir() and not p.is_symlink() and (p / 'SKILL.md').exists())
|
|
|
|
|
|
def destination():
|
|
codex_home = os.environ.get('CODEX_HOME')
|
|
return Path(codex_home).expanduser() / 'skills' if codex_home else Path.home() / '.codex' / 'skills'
|
|
|
|
|
|
def safe_source(path):
|
|
for entry in path.rglob('*'):
|
|
if entry.is_symlink():
|
|
raise ValueError(f'{path.name}: source contains symlink: {entry.relative_to(path)}')
|
|
if entry.is_file() and (entry.name.startswith('.env') or entry.suffix.lower() in {'.pem', '.key', '.p12', '.pfx'} or entry.name.lower() in {'id_rsa', 'id_ed25519'}):
|
|
raise ValueError(f'{path.name}: possible credential file: {entry.relative_to(path)}')
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
group = parser.add_mutually_exclusive_group(required=True)
|
|
group.add_argument('--list', action='store_true')
|
|
group.add_argument('--dry-run', action='store_true')
|
|
group.add_argument('--install', action='append', metavar='NAME')
|
|
group.add_argument('--all', action='store_true')
|
|
parser.add_argument('--dest', type=Path, default=None, help='skills directory (default: CODEX_HOME/skills or ~/.codex/skills)')
|
|
parser.add_argument('--link', action='store_true', help='development symlinks instead of copies')
|
|
args = parser.parse_args(argv)
|
|
dest = (args.dest or destination()).expanduser()
|
|
found = discover()
|
|
valid = {}
|
|
errors = []
|
|
for path in found:
|
|
try:
|
|
manifest(path)
|
|
safe_source(path)
|
|
valid[path.name] = path
|
|
except (ValueError, UnicodeError) as exc:
|
|
errors.append(str(exc))
|
|
if args.list:
|
|
for name in sorted(RESERVED | set(valid)):
|
|
print(f'{name}: {"implemented" if name in valid else "reserved"} -> {dest / name}')
|
|
for error in errors:
|
|
print(f'INVALID: {error}', file=sys.stderr)
|
|
return 1 if errors else 0
|
|
requested = list(valid) if args.all or args.dry_run else args.install
|
|
problems = list(errors)
|
|
for name in requested:
|
|
if name not in valid:
|
|
problems.append(f'{name}: missing, reserved, or invalid skill')
|
|
if problems:
|
|
for problem in problems:
|
|
print(f'ERROR: {problem}', file=sys.stderr)
|
|
return 1
|
|
conflicts = [name for name in requested if (dest / name).exists() or (dest / name).is_symlink()]
|
|
for name in requested:
|
|
print(f'{"CONFLICT" if name in conflicts else "PLAN" if args.dry_run else "INSTALL"}: {name} -> {dest / name}')
|
|
if conflicts:
|
|
print('Existing installations are never overwritten. Remove or move a destination explicitly before retrying.', file=sys.stderr)
|
|
return 1
|
|
if args.dry_run:
|
|
return 0
|
|
dest.mkdir(parents=True, exist_ok=True)
|
|
for name in requested:
|
|
target = dest / name
|
|
if args.link:
|
|
try:
|
|
target.symlink_to(valid[name], target_is_directory=True)
|
|
except OSError as exc:
|
|
print(f'ERROR: symlink failed for {name}: {exc}', file=sys.stderr)
|
|
return 1
|
|
else:
|
|
temp = Path(tempfile.mkdtemp(prefix=f'.{name}-', dir=dest))
|
|
try:
|
|
shutil.copytree(valid[name], temp, dirs_exist_ok=True, symlinks=False)
|
|
temp.rename(target)
|
|
except OSError as exc:
|
|
shutil.rmtree(temp, ignore_errors=True)
|
|
print(f'ERROR: installation failed for {name}: {exc}', file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|