- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcarry.py
More file actions
Latest commit
executable file
·465 lines (421 loc) · 18.4 KB
/
Copy pathcarry.py
File metadata and controls
executable file
·465 lines (421 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env python3
"""Check or apply manifest-owned trees from the hub to a fleet worktree."""
importargparse
importfnmatch
importhashlib
importjson
importos
importpathlib
importsubprocess
importsys
fromdataclassesimportdataclass
fromtypingimportAny
ROOT=pathlib.Path(__file__).resolve().parent.parent
classCarryError(RuntimeError):
"""A state that prevents a safe carry decision."""
@dataclass(frozen=True)
classInventory:
files: dict[str, bytes]
directories: frozenset[str]
digest: str
defload_json(path: pathlib.Path) ->Any:
try:
returnjson.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) asexc:
raiseCarryError(f"cannot read {path}: {exc}") fromexc
defrelative_root(root: pathlib.Path, value: str) ->pathlib.Path:
declared=pathlib.PurePosixPath(value)
ifdeclared==pathlib.PurePosixPath(".") ordeclared.is_absolute() or".."indeclared.parts:
raiseCarryError(
f"path must be repository-relative and below the repository root without '..': {value}"
)
resolved_root=root.resolve()
candidate=resolved_root/value
resolved_candidate=candidate.resolve(strict=False)
try:
resolved_candidate.relative_to(resolved_root)
exceptValueErrorasexc:
raiseCarryError(f"path escapes repository root: {value}") fromexc
current=resolved_root
forpartinpathlib.PurePosixPath(value).parts:
current/=part
ifcurrent.is_symlink():
raiseCarryError(f"symlink is not allowed: {current}")
returncandidate
defincluded(path: str, patterns: list[str]) ->bool:
returnany(
pattern=="**/*"
orfnmatch.fnmatchcase(path, pattern)
orpathlib.PurePosixPath(path).match(pattern)
forpatterninpatterns
)
definventory(root: pathlib.Path, patterns: list[str]) ->Inventory:
files: dict[str, bytes] = {}
directories: set[str] =set()
ifroot.is_symlink():
raiseCarryError(f"symlink is not allowed: {root}")
ifnotroot.exists():
raiseCarryError(f"tree root does not exist: {root}")
ifnotroot.is_dir():
raiseCarryError(f"tree root is not a directory: {root}")
forcurrent, dirnames, filenamesinos.walk(root, followlinks=False):
current_path=pathlib.Path(current)
fornamein [*dirnames, *filenames]:
path=current_path/name
ifpath.is_symlink():
raiseCarryError(f"symlink is not allowed: {path}")
relative_dir=current_path.relative_to(root).as_posix()
if (
relative_dir!="."
andnotdirnames
andnotfilenames
andincluded(relative_dir+"/placeholder", patterns)
):
directories.add(relative_dir)
fornameinfilenames:
path=current_path/name
relative=path.relative_to(root).as_posix()
ifincluded(relative, patterns):
try:
files[relative] =path.read_bytes()
exceptOSErrorasexc:
raiseCarryError(f"cannot read {path}: {exc}") fromexc
digest=hashlib.sha256()
forrelativeinsorted(directories):
digest.update(b"directory\0")
digest.update(relative.encode())
digest.update(b"\0")
forrelative, contentinsorted(files.items()):
digest.update(b"file\0")
digest.update(relative.encode())
digest.update(b"\0")
digest.update(content)
digest.update(b"\0")
returnInventory(files, frozenset(directories), digest.hexdigest())
defcompare(source: Inventory, target: Inventory|None) ->dict[str, Any]:
target_files= {} iftargetisNoneelsetarget.files
target_directories=frozenset() iftargetisNoneelsetarget.directories
return {
"missing": sorted(set(source.files) -set(target_files)),
"missingDirectories": sorted(source.directories-target_directories),
"modified": sorted(
path
forpathinset(source.files) &set(target_files)
ifsource.files[path] !=target_files[path]
),
"extra": sorted(set(target_files) -set(source.files)),
"extraDirectories": sorted(target_directories-source.directories),
"sourceDigest": source.digest,
"targetDigest": NoneiftargetisNoneelsetarget.digest,
"missingRoot": targetisNone,
}
defapply_tree(
source: Inventory,
target_root: pathlib.Path,
repository_root: pathlib.Path,
result: dict[str, Any],
) ->list[str]:
changes: list[str] = []
required_directories=set(source.directories)
forrelativein [*source.files, *source.directories]:
required_directories.update(
str(parent) forparentinpathlib.PurePosixPath(relative).parentsifstr(parent) !="."
)
defremove_empty_ancestors(directory: pathlib.Path) ->None:
whiledirectory!=target_rootanddirectory.exists() andnotany(directory.iterdir()):
relative=directory.relative_to(target_root).as_posix()
ifrelativeinrequired_directories:
return
directory.rmdir()
changes.append(f"remove {directory.relative_to(repository_root)}")
directory=directory.parent
created_roots= []
current=target_root
whilecurrent!=repository_rootandnotcurrent.exists():
created_roots.append(current)
current=current.parent
target_root.mkdir(parents=True, exist_ok=True)
changes.extend(
f"create {directory.relative_to(repository_root)}"fordirectoryinreversed(created_roots)
)
forrelativeinresult["missingDirectories"]:
destination=target_root/relative
destination.mkdir(parents=True, exist_ok=True)
changes.append(f"create {destination.relative_to(repository_root)}")
forrelativein [*result["missing"], *result["modified"]]:
destination=target_root/relative
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_bytes(source.files[relative])
changes.append(f"write {destination.relative_to(repository_root)}")
forrelativeinresult["extra"]:
destination=target_root/relative
destination.unlink()
changes.append(f"remove {destination.relative_to(repository_root)}")
remove_empty_ancestors(destination.parent)
forrelativeinsorted(
result["extraDirectories"],
key=lambdavalue: len(pathlib.PurePosixPath(value).parts),
reverse=True,
):
directory=target_root/relative
ifdirectory.exists() andnotany(directory.iterdir()):
directory.rmdir()
changes.append(f"remove {directory.relative_to(repository_root)}")
remove_empty_ancestors(directory.parent)
returnchanges
defgit(root: pathlib.Path, *args: str) ->str:
result=subprocess.run(["git", *args], cwd=root, capture_output=True, text=True, check=False)
ifresult.returncode!=0:
raiseCarryError(result.stderr.strip() orf"git {' '.join(args)} failed")
returnresult.stdout.strip()
defgit_is_ancestor(root: pathlib.Path, ancestor: str, descendant: str) ->bool:
result=subprocess.run(
["git", "merge-base", "--is-ancestor", ancestor, descendant],
cwd=root,
capture_output=True,
text=True,
check=False,
)
ifresult.returncodenotin (0, 1):
raiseCarryError(result.stderr.strip() or"git merge-base --is-ancestor failed")
returnresult.returncode==0
defgit_status_paths(root: pathlib.Path) ->list[str]:
result=subprocess.run(
["git", "status", "--porcelain=v1", "-z", "--untracked-files=all"],
cwd=root,
capture_output=True,
check=False,
)
ifresult.returncode!=0:
raiseCarryError(os.fsdecode(result.stderr).strip() or"git status failed")
fields=result.stdout.split(b"\0")
iffieldsandnotfields[-1]:
fields.pop()
paths: list[str] = []
index=0
whileindex<len(fields):
entry=fields[index]
iflen(entry) <4orentry[2:3] !=b" ":
raiseCarryError("git status returned malformed porcelain output")
paths.append(os.fsdecode(entry[3:]))
ifb"R"inentry[:2] orb"C"inentry[:2]:
index+=1
ifindex>=len(fields):
raiseCarryError("git status returned an incomplete rename or copy")
paths.append(os.fsdecode(fields[index]))
index+=1
returnpaths
defnormalized_origin(value: str) ->str:
value=value.strip().rstrip("/").removesuffix(".git")
ifvalue.startswith("git@github.com:"):
return"https://github.com/"+value.removeprefix("git@github.com:")
ifvalue.startswith("ssh://git@github.com/"):
return"https://github.com/"+value.removeprefix("ssh://git@github.com/")
returnvalue
defverify_hub(hub: pathlib.Path, registry: dict[str, Any]) ->str:
entry=resolve_repo("ProjectTemplate", registry)
origin=normalized_origin(git(hub, "config", "--get", "remote.origin.url"))
iforigin!=normalized_origin(entry["url"]):
raiseCarryError("hub origin does not match the ProjectTemplate registry entry")
git(hub, "fetch", "origin", "main")
head=git(hub, "rev-parse", "HEAD")
ifhead!=git(hub, "rev-parse", "origin/main"):
raiseCarryError("hub checkout is not at freshly fetched origin/main")
ifgit(hub, "status", "--porcelain"):
raiseCarryError("hub checkout has local changes")
returnhead
defapplicable(selector: str|list[str], values: set[str]) ->bool:
ifselector=="*":
returnTrue
tokens=selectorifisinstance(selector, list) else [selector]
returnbool(set(tokens) &values)
defvalidate_declarations(declarations: list[Any], hub: pathlib.Path) ->None:
required= {"source", "target", "fidelity", "appliesTo", "include", "prune"}
allowed=required| {"allowHubTarget"}
forindex, leftinenumerate(declarations):
ifnotisinstance(left, dict):
raiseCarryError(f"tree declaration must be an object: {left!r}")
missing=required-set(left)
unknown=set(left) -allowed
ifmissing:
raiseCarryError(f"tree declaration is missing: {', '.join(sorted(missing))}")
ifunknown:
raiseCarryError(f"tree declaration has unknown fields: {', '.join(sorted(unknown))}")
ifnotisinstance(left["source"], str) ornotleft["source"]:
raiseCarryError("tree declaration source must be a non-empty string")
ifnotisinstance(left["target"], str) ornotleft["target"]:
raiseCarryError("tree declaration target must be a non-empty string")
ifleft.get("fidelity") !="verbatim-tree":
raiseCarryError(f"tree declaration has unsupported fidelity: {left.get('fidelity')}")
selector=left["appliesTo"]
ifnot (
isinstance(selector, str)
or (
isinstance(selector, list)
andselector
andall(isinstance(item, str) foriteminselector)
)
):
raiseCarryError(
"tree declaration appliesTo must be a string or non-empty string array"
)
include=left["include"]
ifnot (
isinstance(include, list)
andinclude
andall(isinstance(pattern, str) andpatternforpatternininclude)
):
raiseCarryError("tree declaration include must be a non-empty string array")
ifnotisinstance(left["prune"], bool):
raiseCarryError("tree declaration prune must be a boolean")
if"allowHubTarget"inleftandnotisinstance(left["allowHubTarget"], bool):
raiseCarryError("tree declaration allowHubTarget must be a boolean")
relative_root(hub, left["source"])
relative_root(hub, left["target"])
forrightindeclarations[index+1 :]:
left_target=pathlib.PurePosixPath(left["target"])
right_target=pathlib.PurePosixPath(right["target"])
overlaps= (
left_target==right_target
orleft_targetinright_target.parents
orright_targetinleft_target.parents
)
ifoverlaps:
raiseCarryError(
f"overlapping tree declarations have conflicting ownership: {left_target} and {right_target}"
)
defresolve_repo(name: str, registry: dict[str, Any]) ->dict[str, Any]:
matches= [entryforentryinregistry.get("repos", []) ifentry.get("name") ==name]
iflen(matches) !=1:
raiseCarryError(f"repository is not uniquely registered: {name}")
returnmatches[0]
defverify_target(
target: pathlib.Path, entry: dict[str, Any], owned_roots: list[pathlib.Path]
) ->None:
top=pathlib.Path(git(target, "rev-parse", "--show-toplevel")).resolve()
iftop!=target.resolve():
raiseCarryError(f"target must name the repository root: {target}")
ifnormalized_origin(git(target, "config", "--get", "remote.origin.url")) !=normalized_origin(
entry["url"]
):
raiseCarryError("target origin does not match the registry entry")
branch=git(target, "branch", "--show-current")
ifnotbranchorbranchin {"main", "develop"}:
raiseCarryError("target must be an isolated feature-branch worktree")
git(target, "fetch", "origin", "develop")
ifnotgit_is_ancestor(target, "origin/develop", "HEAD"):
raiseCarryError("target branch must contain the current origin/develop head")
worktree_rows=git(target, "worktree", "list", "--porcelain").splitlines()
ifsum(row==f"worktree {target.resolve()}"forrowinworktree_rows) !=1:
raiseCarryError("target is not a registered git worktree")
dirty= []
forrelativeingit_status_paths(target):
path= (target/relative).resolve(strict=False)
ifnotany(path==rootorrootinpath.parentsforrootinowned_roots):
dirty.append(relative)
ifdirty:
raiseCarryError(f"target has unrelated changes: {', '.join(sorted(dirty))}")
defrun(mode: str, name: str, target: pathlib.Path, hub: pathlib.Path=ROOT) ->int:
registry=load_json(hub/"registry/repos.json")
manifest=load_json(hub/"spec/files.json")
hub_commit=verify_hub(hub, registry)
entry=resolve_repo(name, registry)
defaults=registry.get("defaults", {})
selectors=set(entry.get("types", []))
selectors.add(entry.get("workflowModel") ordefaults.get("workflowModel") or"release")
selectors.add(entry.get("releaseTrigger") ordefaults.get("releaseTrigger") or"two-phase")
ifentry.get("consumerModel"):
selectors.add(entry["consumerModel"])
all_declarations=manifest.get("trees")
ifnotisinstance(all_declarations, list):
raiseCarryError("manifest trees must be an array")
validate_declarations(all_declarations, hub)
declarations= [
declaration
fordeclarationinall_declarations
ifapplicable(declaration.get("appliesTo", "*"), selectors)
]
ifname=="ProjectTemplate"andany(
notitem.get("allowHubTarget", False) foritemindeclarations
):
raiseCarryError("a declaration does not allow ProjectTemplate as its target")
owned_roots= [relative_root(target, item["target"]) foritemindeclarations]
verify_target(target, entry, owned_roots)
print(f"hubCommit: {hub_commit}")
print(f"repository: {name}")
print(f"types: {','.join(entry.get('types', []))}")
print(f"declarations: {len(declarations)}")
clean=True
fordeclarationindeclarations:
source_root=relative_root(hub, declaration["source"])
target_root=relative_root(target, declaration["target"])
source=inventory(source_root, declaration["include"])
target_patterns= ["**/*"] ifdeclaration.get("prune") elsedeclaration["include"]
target_inventory=inventory(target_root, target_patterns) iftarget_root.exists() elseNone
result=compare(source, target_inventory)
ifnotdeclaration.get("prune"):
result["extra"] = []
result["extraDirectories"] = []
print(
json.dumps(
{"source": declaration["source"], "target": declaration["target"], **result},
sort_keys=True,
)
)
declaration_clean= (
notany(
result[key]
forkeyin (
"missing",
"missingDirectories",
"modified",
"extra",
"extraDirectories",
)
)
andnotresult["missingRoot"]
)
clean=cleananddeclaration_clean
ifmode=="apply"andnotdeclaration_clean:
forchangeinapply_tree(source, target_root, target, result):
print(change)
final=compare(source, inventory(target_root, target_patterns))
print(
json.dumps(
{
"source": declaration["source"],
"target": declaration["target"],
"postApply": True,
**final,
},
sort_keys=True,
)
)
if (
any(
final[key]
forkeyin (
"missing",
"missingDirectories",
"modified",
"extra",
"extraDirectories",
)
)
orfinal["missingRoot"]
):
raiseCarryError(f"post-apply comparison failed for {declaration['target']}")
return0ifmode=="apply"orcleanelse1
defmain() ->int:
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument("mode", choices=("check", "apply"))
parser.add_argument("repository")
parser.add_argument("--target", required=True, type=pathlib.Path)
args=parser.parse_args()
try:
returnrun(args.mode, args.repository, args.target.resolve())
exceptCarryErrorasexc:
print(f"ERROR: {exc}", file=sys.stderr)
return2
if__name__=="__main__":
raiseSystemExit(main())