Branchwell

Skillfarm / skills · skillfarm.ai / tools / convert / convert.py

1#!/usr/bin/env python3
2"""Convert skills written for one agent into copies that read the same in Claude Code, Codex CLI and Gemini CLI.
3
4 python3 tools/convert/convert.py --source-root <folder holding the cloned source repos> [--check]
5
6What a conversion does, and nothing more:
7 1. Rewrites the SKILL.md front matter to the open Agent Skills format (agentskills.io) and records where the
8 skill came from.
9 2. Puts a short note above the original text that tells any agent how to read Claude-only wording, and lists
10 what the skill needs installed. The original text below the note is kept byte for byte.
11 3. Replaces sandbox-only output paths in example files with paths that exist on any machine.
12 4. Writes NOTICE.md with the source, the licence and every change made.
13
14Every rule is mechanical, so the same source always gives the same output. `--check` converts into a temporary
15folder and fails when the result differs from what is committed.
16"""
17from __future__ import annotations
18
19import argparse
20import filecmp
21import hashlib
22import re
23import shutil
24import sys
25import tempfile
26from pathlib import Path
27
28import yaml
29
30VERSION = '1'
31HERE = Path(__file__).resolve().parent
32REPO = HERE.parent.parent
33OUT = REPO / 'converted'
34
35TEXT_SUFFIXES = {'.md', '.py', '.js', '.mjs', '.cjs', '.ts', '.sh', '.txt', '.json', '.html', '.css', '.yaml', '.yml'}
36NAME_RE = re.compile(r'^[a-z0-9]+(-[a-z0-9]+)*$')
37FRONT_RE = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
38
39# Front matter keys only Claude Code reads. They are dropped and listed in NOTICE.md.
40CLAUDE_ONLY_KEYS = ['model', 'argument-hint', 'disable-model-invocation', 'user-invocable', 'context', 'agent', 'hooks', 'when_to_use', 'version']
41
42# Python import name -> package to install. Imports not listed here install under their own name.
43PIP_NAMES = {'PIL': 'pillow', 'pptx': 'python-pptx', 'yaml': 'pyyaml', 'cv2': 'opencv-python', 'docx': 'python-docx', 'bs4': 'beautifulsoup4', 'fitz': 'pymupdf', 'sklearn': 'scikit-learn'}
44NODE_BUILTINS = {'fs', 'path', 'os', 'util', 'child_process', 'crypto', 'http', 'https', 'url', 'stream', 'zlib', 'events', 'assert', 'buffer', 'readline', 'process', 'module', 'worker_threads', 'perf_hooks'}
45
46# Programs a skill calls: (label shown to the reader, pattern that shows the skill uses it).
47PROGRAMS = [
48 ('LibreOffice (`soffice`)', re.compile(r'\b(soffice|libreoffice)\b', re.I)),
49 ('Poppler (`pdftoppm`)', re.compile(r'\b(pdftoppm|pdftotext|pdfimages|poppler)\b', re.I)),
50 ('Pandoc', re.compile(r'\bpandoc\b')),
51 ('FFmpeg', re.compile(r'\bffmpeg\b', re.I)),
52 ('qpdf', re.compile(r'\bqpdf\b')),
53 ('Tesseract', re.compile(r'\b(tesseract|pytesseract)\b', re.I)),
54]
55
56# Wording that only makes sense inside Claude: (key, pattern). Each one found adds a line to the note.
57SIGNALS = [
58 ('subagents', re.compile(r'\bsub-?agents?\b', re.I)),
59 ('artifacts', re.compile(r'\bclaude\.ai\b|\b(HTML|interactive|single) artifacts?\b', re.I)),
60 ('tools', re.compile(r'\b(str_replace|create_file|present_files|bash_tool|AskUserQuestion|TodoWrite)\b|\bview tool\b')),
61 ('preinstalled', re.compile(r'\bpre-?installed\b', re.I)),
62 ('claude', re.compile(r'\bClaude (should|will|can|must|may|is|has|reads|needs|does|interprets|uses|loads)\b|\b(next|another|future) Claude\b')),
63]
64
65# Sandbox paths that do not exist outside Claude's own sandbox -> a path that works anywhere.
66PATH_RULES = [('/mnt/user-data/outputs/', './'), ('/mnt/user-data/uploads/', './')]
67LEFTOVER_RE = re.compile(r'/mnt/user-data|/mnt/skills|/home/claude')
68
69# Description wording that names one agent -> neutral wording.
70DESCRIPTION_RULES = [
71 (re.compile(r'\bClaude should use this skill\b'), 'Use this skill'),
72 (re.compile(r'\bClaude (should|will|can|needs to)\b'), r'the agent \1'),
73]
74
75
76class ConvertError(Exception):
77 pass
78
79
80def sha(path: Path) -> str:
81 return hashlib.sha256(path.read_bytes()).hexdigest()
82
83
84def read_text(path: Path) -> str | None:
85 if path.suffix.lower() not in TEXT_SUFFIXES:
86 return None
87 try:
88 return path.read_text(encoding='utf-8')
89 except UnicodeDecodeError:
90 return None
91
92
93def split_front(text: str, where: str) -> tuple[dict, str]:
94 m = FRONT_RE.match(text)
95 if not m:
96 raise ConvertError(f'{where}: SKILL.md has no front matter')
97 front = yaml.safe_load(m.group(1))
98 if not isinstance(front, dict):
99 raise ConvertError(f'{where}: front matter is not a mapping')
100 return front, text[m.end():]
101
102
103def python_imports(code: str) -> set[str]:
104 found = set()
105 for m in re.finditer(r'^[ \t]*(?:import|from)[ \t]+([A-Za-z_][A-Za-z0-9_]*)', code, re.M):
106 found.add(m.group(1))
107 return found
108
109
110def node_imports(code: str) -> set[str]:
111 found = set()
112 for m in re.finditer(r'''(?:require\(|from[ \t]+|import[ \t]+)['"]([^'"\n]+)['"]''', code):
113 name = m.group(1)
114 if name.startswith(('.', '/', 'node:')):
115 continue
116 parts = name.split('/')
117 found.add('/'.join(parts[:2]) if name.startswith('@') else parts[0])
118 return found
119
120
121def fenced(text: str, langs: tuple[str, ...]) -> str:
122 return '\n'.join(m.group(2) for m in re.finditer(r'```([A-Za-z0-9_+-]*)[^\n]*\n(.*?)```', text, re.S) if m.group(1).lower() in langs)
123
124
125NPM_NAME_RE = re.compile(r'^(@[a-z0-9~-][a-z0-9._~-]*/)?[a-z0-9~-][a-z0-9._~-]*$')
126PIP_NAME_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]*$')
127
128
129def installs(text: str, tool: str) -> set[str]:
130 """Package names that follow `pip install` or `npm install` anywhere in a document."""
131 found = set()
132 for m in re.finditer(tool + r' install((?:[ \t]+[@A-Za-z0-9][A-Za-z0-9@/._~-]*)+)', text):
133 found |= {w.rstrip('.') for w in m.group(1).split() if not w.startswith('-')}
134 return found
135
136
137def requirements(src: Path) -> dict:
138 """What the skill needs on the machine: what its own scripts import, and what its written examples use."""
139 script_py: set[str] = set()
140 script_node: set[str] = set()
141 doc_py: set[str] = set()
142 doc_node: set[str] = set()
143 runs_node = False
144 everything = []
145 for path in sorted(src.rglob('*')):
146 if not path.is_file():
147 continue
148 text = read_text(path)
149 if text is None:
150 continue
151 everything.append(text)
152 suffix = path.suffix.lower()
153 if suffix == '.py':
154 # A name is the skill's own module when a file or folder of that name sits beside the script or above it.
155 above = [d for d in path.parents if d == src or src in d.parents]
156 script_py |= {n for n in python_imports(text) if not any((d / f'{n}.py').exists() or (d / n).is_dir() for d in above)}
157 elif suffix in {'.js', '.mjs', '.cjs', '.ts'}:
158 script_node |= node_imports(text)
159 runs_node = runs_node or 'require(' in text or text.startswith('#!/usr/bin/env node')
160 elif suffix == '.md':
161 doc_py |= python_imports(fenced(text, ('python', 'py'))) | installs(text, 'pip')
162 doc_node |= node_imports(text) | installs(text, 'npm')
163 blob = '\n'.join(everything)
164 stdlib = set(sys.stdlib_module_names)
165
166 def py_names(found: set[str]) -> set[str]:
167 return {PIP_NAMES.get(n, n) for n in found if n not in stdlib and not n.startswith('_') and PIP_NAME_RE.match(n)}
168
169 def node_names(found: set[str]) -> set[str]:
170 return {n for n in found if n not in NODE_BUILTINS and NPM_NAME_RE.match(n)}
171
172 lower = lambda names: sorted(names, key=str.lower) # noqa: E731
173 spy, snode = py_names(script_py), node_names(script_node)
174 own = {p.stem for p in src.rglob('*.py')} | {p.name for p in src.rglob('*') if p.is_dir()}
175 dpy = {n for n in py_names(doc_py - own) if n.lower() not in {x.lower() for x in spy}}
176 dnode = node_names(doc_node) - snode
177 return {
178 'script_py': lower(spy), 'script_node': lower(snode), 'doc_py': lower(dpy), 'doc_node': lower(dnode),
179 'programs': [label for label, pattern in PROGRAMS if pattern.search(blob)],
180 'python': bool(spy) or any(src.rglob('*.py')), 'node': bool(snode) or runs_node,
181 }
182
183
184def ticks(names: list[str]) -> str:
185 return ', '.join(f'`{n}`' for n in names)
186
187
188def needs_lines(req: dict) -> list[str]:
189 """One line per kind of need, for the note. Empty when the skill is text only."""
190 lines = []
191 scripts = []
192 if req['python']:
193 scripts.append('Python 3' + (f" with {ticks(req['script_py'])}" if req['script_py'] else ''))
194 if req['node']:
195 scripts.append('Node.js' + (f" with {ticks(req['script_node'])}" if req['script_node'] else ''))
196 if scripts:
197 lines.append('**Its scripts need:** ' + '; '.join(scripts) + '.')
198 examples = []
199 if req['doc_py']:
200 examples.append(f"Python packages {ticks(req['doc_py'])}")
201 if req['doc_node']:
202 examples.append(f"Node.js packages {ticks(req['doc_node'])}")
203 if examples:
204 lines.append('**Its written examples also use:** ' + '; '.join(examples) + '. Install only the ones a task calls for.')
205 if req['programs']:
206 lines.append('**Programs it calls:** ' + ', '.join(req['programs']) + '.')
207 return lines
208
209
210def needs_short(req: dict) -> str:
211 """The same needs as one plain phrase, for the front matter and the index."""
212 parts = []
213 if req['python']:
214 parts.append('Python 3' + (f" with {', '.join(req['script_py'])}" if req['script_py'] else ''))
215 if req['node']:
216 parts.append('Node.js' + (f" with {', '.join(req['script_node'])}" if req['script_node'] else ''))
217 parts += [re.sub(r'[`]', '', p) for p in req['programs']]
218 if req['doc_py'] or req['doc_node']:
219 parts.append('more packages for some tasks (see the note in SKILL.md)')
220 return '; '.join(parts)
221
222
223def signals(src: Path) -> set[str]:
224 found = set()
225 for path in sorted(src.rglob('*.md')):
226 text = read_text(path) or ''
227 for key, pattern in SIGNALS:
228 if pattern.search(text):
229 found.add(key)
230 return found
231
232
233def note(source: dict, name: str, sig: set[str], needs: list[str], bundled: bool) -> str:
234 url = f"https://github.com/{source['repo']}/tree/{source['commit']}/{source['path']}/{name}"
235 lines = [
236 f"> **Skillfarm multi-agent version.** Converted from [{source['repo']}]({url}) by {source['maker']} so it reads the same in Claude Code, Codex CLI and Gemini CLI. "
237 'The original text follows this note unchanged. NOTICE.md lists every change.',
238 '>',
239 '> How to read it, whichever agent you are:',
240 ]
241 if 'claude' in sig:
242 lines.append('> - Where it says "Claude", it means you, the agent running this skill.')
243 if 'subagents' in sig:
244 lines.append('> - Where it asks for subagents and you cannot start any, do those steps yourself, one at a time.')
245 if 'artifacts' in sig:
246 lines.append('> - Where it says "artifact" or claude.ai, write the result to a file in the working folder and tell the person its path.')
247 if 'tools' in sig:
248 lines.append('> - Tool names in the text are Claude\'s. Use your own tool for the same job, and ask questions in plain chat.')
249 if 'preinstalled' in sig or needs:
250 lines.append('> - It was written for a sandbox with its tools already installed. Here, check that what it needs is present before you start, and ask the person before you install anything.')
251 if bundled:
252 lines.append("> - File paths in the text are relative to this skill's folder.")
253 if len(lines) == 3:
254 lines[2] = '> It needs nothing changed to run in any of the three.'
255 for line in needs:
256 lines += ['>', f'> {line}']
257 return '\n'.join(lines) + '\n'
258
259
260def dump_front(front: dict) -> str:
261 return yaml.safe_dump(front, sort_keys=False, allow_unicode=True, width=100, default_flow_style=False)
262
263
264def convert_skill(source: dict, src: Path, dst: Path) -> dict:
265 name = src.name
266 where = f"{source['repo']}/{name}"
267 if not NAME_RE.match(name) or len(name) > 64:
268 raise ConvertError(f'{where}: folder name is not a valid skill name')
269 licence_file = next((p for p in sorted(src.iterdir()) if p.is_file() and p.name.lower().startswith('license')), None)
270 if licence_file is None:
271 raise ConvertError(f'{where}: no licence file in the skill folder')
272 original = (src / 'SKILL.md').read_text(encoding='utf-8')
273 front, body = split_front(original, where)
274 changes: list[str] = []
275
276 if front.get('name') != name:
277 raise ConvertError(f"{where}: front matter name {front.get('name')!r} does not match its folder")
278 description = ' '.join(str(front.get('description') or '').split())
279 if not description:
280 raise ConvertError(f'{where}: no description')
281 new_description = description
282 for pattern, repl in DESCRIPTION_RULES:
283 new_description = pattern.sub(repl, new_description)
284 if new_description != description:
285 changes.append('SKILL.md: description reworded so it names no single agent. It read: "' + description + '"')
286 if len(new_description) > 1024:
287 raise ConvertError(f'{where}: description is {len(new_description)} characters, over the 1,024 limit')
288
289 bundled = any(p.is_file() and p.name != 'SKILL.md' and p != licence_file for p in src.rglob('*'))
290 req = requirements(src)
291 needs = needs_lines(req)
292 short = needs_short(req)
293 sig = signals(src)
294
295 shutil.copytree(src, dst)
296 changed_files: set[str] = {'SKILL.md'}
297 for path in sorted(dst.rglob('*')):
298 if not path.is_file() or path.name == 'SKILL.md':
299 continue
300 text = read_text(path)
301 if text is None:
302 continue
303 new = text
304 count = 0
305 for old, repl in PATH_RULES:
306 count += new.count(old)
307 new = new.replace(old, repl)
308 if count:
309 rel = path.relative_to(dst).as_posix()
310 if path.suffix in {'.py', '.sh'}:
311 marker = '# Changed by Skillfarm: sandbox output paths now point at the working folder. See NOTICE.md.\n'
312 new = (new.split('\n', 1)[0] + '\n' + marker + new.split('\n', 1)[1]) if new.startswith('#!') else marker + new
313 path.write_text(new, encoding='utf-8')
314 changed_files.add(rel)
315 changes.append(f'{rel}: sandbox path `/mnt/user-data/...` replaced with `./` in {count} place{"s" if count != 1 else ""}, and a comment added saying so.')
316
317 out_front: dict = {'name': name, 'description': new_description}
318 out_front['license'] = f"{source['license']}. Complete terms in {licence_file.name}"
319 compat = 'Converted by Skillfarm to read the same in Claude Code, Codex CLI and Gemini CLI.'
320 if short:
321 compat += ' Needs ' + short + '.'
322 if front.get('compatibility'):
323 compat = str(front['compatibility']).strip() + ' ' + compat
324 if len(compat) > 500:
325 compat = compat[:497].rsplit(' ', 1)[0] + '...'
326 out_front['compatibility'] = compat
327 if 'allowed-tools' in front:
328 out_front['allowed-tools'] = front['allowed-tools']
329 metadata = {str(k): str(v) for k, v in (front.get('metadata') or {}).items()} if isinstance(front.get('metadata'), dict) else {}
330 metadata.update({
331 'source': f"https://github.com/{source['repo']}/tree/{source['commit']}/{source['path']}/{name}",
332 'source-commit': source['commit'],
333 'original-author': source['maker'],
334 'converted-by': 'Skillfarm (https://skillfarm.ai)',
335 'converter-version': VERSION,
336 })
337 out_front['metadata'] = metadata
338 dropped = [k for k in front if k in CLAUDE_ONLY_KEYS]
339 unknown = [k for k in front if k not in {'name', 'description', 'license', 'compatibility', 'metadata', 'allowed-tools'} and k not in CLAUDE_ONLY_KEYS]
340 if unknown:
341 raise ConvertError(f'{where}: front matter has keys the converter does not know: {", ".join(unknown)}')
342
343 changes.insert(0, 'SKILL.md: front matter rewritten to the open Agent Skills format. The licence line now names the licence, and `compatibility` and `metadata` (source, commit, author, converter) were added.'
344 + (f' Dropped keys only Claude Code reads: {", ".join(dropped)}.' if dropped else ''))
345 changes.insert(1, 'SKILL.md: a note was added above the original text. It says this is a modified copy, tells any agent how to read Claude-only wording' + (', and lists what the skill needs installed.' if needs else '.'))
346 (dst / 'SKILL.md').write_text('---\n' + dump_front(out_front) + '---\n\n' + note(source, name, sig, needs, bundled) + body, encoding='utf-8')
347
348 same = sum(1 for p in src.rglob('*') if p.is_file() and p.relative_to(src).as_posix() not in changed_files)
349 notice = [
350 '# Notice',
351 '',
352 f'This folder is a modified copy of the skill `{name}` by {source["maker"]}.',
353 '',
354 f"- Original: https://github.com/{source['repo']}/tree/{source['commit']}/{source['path']}/{name}",
355 f"- Licence: {source['license_name']}. The full text is in {licence_file.name}, unchanged.",
356 f'- Copyright stays with the original authors. Protomota and Skillfarm claim no ownership of the original work, and {source["maker"]} has not reviewed or endorsed this copy.',
357 f'- Converted by Skillfarm (https://skillfarm.ai) with `tools/convert` version {VERSION}, so the skill reads the same in Claude Code, Codex CLI and Gemini CLI.',
358 ]
359 if source.get('third_party_notices'):
360 notice.append(f"- The original repo's third-party notices are kept beside this folder, in `converted/{third_party_name(source)}`.")
361 notice += ['', '## Changes from the original', ''] + [f'- {c}' for c in changes] + ['- NOTICE.md: added.', '', f'The text of SKILL.md below the note, and the other {same} file{"s" if same != 1 else ""}, are byte for byte the same as the original.', '']
362 (dst / 'NOTICE.md').write_text('\n'.join(notice), encoding='utf-8')
363 return {'name': name, 'description': new_description, 'needs': short, 'changed': sorted(changed_files), 'files': same + len(changed_files) + 1}
364
365
366def third_party_name(source: dict) -> str:
367 return 'THIRD_PARTY_NOTICES-' + source['repo'].replace('/', '-') + '.md'
368
369
370def validate(source: dict, src: Path, dst: Path) -> list[str]:
371 """Checks on one converted skill. Returns a list of problems, empty when it is sound."""
372 problems = []
373 name = dst.name
374 text = (dst / 'SKILL.md').read_text(encoding='utf-8')
375 try:
376 front, body = split_front(text, name)
377 except ConvertError as e:
378 return [str(e)]
379 if front.get('name') != name or not NAME_RE.match(name):
380 problems.append('name does not match the folder')
381 if not (1 <= len(front.get('description', '')) <= 1024):
382 problems.append('description is empty or over 1,024 characters')
383 if len(front.get('compatibility', '')) > 500:
384 problems.append('compatibility is over 500 characters')
385 if not all(isinstance(v, str) for v in front.get('metadata', {}).values()):
386 problems.append('metadata values must be text')
387 _, original_body = split_front((src / 'SKILL.md').read_text(encoding='utf-8'), name)
388 if not body.endswith(original_body):
389 problems.append('the original SKILL.md text is not intact below the note')
390 for path in src.rglob('*'):
391 if not path.is_file():
392 continue
393 rel = path.relative_to(src)
394 twin = dst / rel
395 if not twin.is_file():
396 problems.append(f'missing file {rel.as_posix()}')
397 elif rel.as_posix() != 'SKILL.md' and sha(path) != sha(twin):
398 new = read_text(twin) or ''
399 if 'Changed by Skillfarm' not in new:
400 problems.append(f'{rel.as_posix()} differs from the original without a change notice')
401 for path in dst.rglob('*'):
402 if path.is_file() and path.name != 'NOTICE.md':
403 t = read_text(path)
404 if t and LEFTOVER_RE.search(t):
405 problems.append(f'{path.relative_to(dst).as_posix()} still has a sandbox-only path')
406 for m in re.finditer(r'\]\(([^)#\s]+)(?:#[^)]*)?\)', body):
407 target = m.group(1)
408 if re.match(r'^[a-z][a-z0-9+.-]*:', target) or target.startswith('/'):
409 continue
410 if not (dst / target).exists():
411 problems.append(f'SKILL.md links to {target}, which is not in the folder')
412 if not (dst / 'NOTICE.md').is_file():
413 problems.append('NOTICE.md is missing')
414 return problems
415
416
417def index(results: list[dict], skipped: list[dict]) -> str:
418 lines = [
419 '# Converted skills',
420 '',
421 'Skills written for one agent, converted by [Skillfarm](https://skillfarm.ai) so they read the same in Claude Code, Codex CLI and Gemini CLI.',
422 'Each folder is a modified copy of someone else\'s work, used under its licence. The original author keeps the credit and the copyright, and each folder\'s NOTICE.md links to the original and lists every change.',
423 '',
424 'The conversion is mechanical and small on purpose: the front matter moves to the open [Agent Skills](https://agentskills.io/specification) format, a short note tells any agent how to read Claude-only wording and what the skill needs installed, and sandbox-only paths are replaced. The author\'s own text is kept as it was. The converter is in [`tools/convert`](../tools/convert).',
425 '',
426 '## Install one',
427 '',
428 '```sh',
429 'npx skills add https://github.com/protomota/skills/tree/main/converted/<name> -a claude-code -g -y',
430 '```',
431 '',
432 'Use `-a codex` or `-a gemini-cli` for the other agents.',
433 '',
434 '## What is here',
435 '',
436 '| Skill | Original | Licence | Needs |',
437 '|---|---|---|---|',
438 ]
439 for r in results:
440 s = r['source']
441 lines.append(f"| [{r['name']}]({r['name']}/SKILL.md) | [{s['repo']}](https://github.com/{s['repo']}/tree/{s['commit']}/{s['path']}/{r['name']}) by {s['maker']} | {s['license']} | {r['needs'] or 'Nothing extra'} |")
442 if skipped:
443 lines += ['', '## Not converted', '', 'These stay as links to the original, with the reason.', '', '| Skill | Original | Why |', '|---|---|---|']
444 for k in skipped:
445 s = k['source']
446 lines.append(f"| {k['name']} | [{s['repo']}](https://github.com/{s['repo']}/tree/{s['commit']}/{s['path']}/{k['name']}) | {k['why']} |")
447 return '\n'.join(lines) + '\n'
448
449
450def run(source_root: Path, out: Path) -> tuple[list[dict], list[dict], list[str]]:
451 sources = yaml.safe_load((HERE / 'sources.yaml').read_text(encoding='utf-8'))
452 results, skipped, problems = [], [], []
453 if out.exists():
454 shutil.rmtree(out)
455 out.mkdir(parents=True)
456 for source in sources:
457 root = source_root / source['checkout'] / source['path']
458 if not root.is_dir():
459 raise ConvertError(f"{source['repo']}: {root} not found. Clone the repo at commit {source['commit']} first.")
460 skip = source.get('skip') or {}
461 for src in sorted(p for p in root.iterdir() if (p / 'SKILL.md').is_file()):
462 if src.name in skip:
463 skipped.append({'name': src.name, 'why': skip[src.name], 'source': source})
464 continue
465 dst = out / src.name
466 if dst.exists():
467 raise ConvertError(f'{src.name}: two sources convert to the same name')
468 r = convert_skill(source, src, dst)
469 r['source'] = source
470 results.append(r)
471 problems += [f"{src.name}: {p}" for p in validate(source, src, dst)]
472 if source.get('third_party_notices'):
473 shutil.copyfile(source_root / source['checkout'] / source['third_party_notices'], out / third_party_name(source))
474 (out / 'README.md').write_text(index(results, skipped), encoding='utf-8')
475 return results, skipped, problems
476
477
478def same_tree(a: Path, b: Path) -> bool:
479 cmp = filecmp.dircmp(a, b)
480 if cmp.left_only or cmp.right_only or cmp.funny_files:
481 return False
482 _, mismatch, errors = filecmp.cmpfiles(a, b, cmp.common_files, shallow=False)
483 return not mismatch and not errors and all(same_tree(a / d, b / d) for d in cmp.common_dirs)
484
485
486def main() -> int:
487 ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
488 ap.add_argument('--source-root', required=True, type=Path, help='folder that holds the cloned source repos named in sources.yaml')
489 ap.add_argument('--check', action='store_true', help='convert into a temporary folder and fail if it differs from converted/')
490 args = ap.parse_args()
491 try:
492 if args.check:
493 with tempfile.TemporaryDirectory() as tmp:
494 results, skipped, problems = run(args.source_root, Path(tmp) / 'converted')
495 if not same_tree(Path(tmp) / 'converted', OUT):
496 problems.append('converted/ is out of date: run the converter again and commit the result')
497 else:
498 results, skipped, problems = run(args.source_root, OUT)
499 except ConvertError as e:
500 print(f'error: {e}', file=sys.stderr)
501 return 2
502 for r in results:
503 print(f"converted {r['name']:<24} {r['files']:>3} files needs: {r['needs'] or '-'}")
504 for k in skipped:
505 print(f"skipped {k['name']:<24} {k['why']}")
506 for p in problems:
507 print(f'PROBLEM {p}', file=sys.stderr)
508 print(f'{len(results)} converted, {len(skipped)} skipped, {len(problems)} problems')
509 return 1 if problems else 0
510
511
512if __name__ == '__main__':
513 sys.exit(main())