codeimprint 0.5.0a35__tar.gz → 0.5.0a36__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/CHANGELOG.md +32 -0
  2. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/PKG-INFO +1 -1
  3. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/pyproject.toml +1 -1
  4. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/__init__.py +1 -1
  5. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/cli.py +154 -26
  6. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/filelist.py +29 -7
  7. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/gitrepo.py +106 -4
  8. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/.gitignore +0 -0
  9. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/LICENSE +0 -0
  10. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/NOTICE +0 -0
  11. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/README.pypi.md +0 -0
  12. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint/__init__.py +0 -0
  13. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint/__main__.py +0 -0
  14. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/__main__.py +0 -0
  15. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/api.py +0 -0
  16. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/chainseal.py +0 -0
  17. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/config.py +0 -0
  18. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/imprint_file.py +0 -0
  19. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/linecount.py +0 -0
  20. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/ownership.py +0 -0
  21. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/project.py +0 -0
  22. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/receipt.py +0 -0
  23. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/records.py +0 -0
  24. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/timestamp.py +0 -0
  25. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/transparency.py +0 -0
  26. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/trust.py +0 -0
  27. {codeimprint-0.5.0a35 → codeimprint-0.5.0a36}/src/codeimprint_cli/tsa_roots.py +0 -0
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0a36 — No false differences from Git's line-ending conversions [CIM-BE-59-v1]
4
+
5
+ Client only; engine unchanged (0.7.0a44).
6
+
7
+ - **`imprint check --files --worktree` compares as Git would store the files.** Git itself
8
+ hashes each working file with its clean conversion (core.autocrlf, core.eol, `.gitattributes`
9
+ text/eol/filter/ident, clean filters), via `git hash-object -w --stdin-paths` into a
10
+ temporary object folder that is deleted afterwards (the index, the repository's objects and
11
+ the working files are never written). An untouched file checked out with CRLF no longer
12
+ reads as "Changed". A file Git cannot convert is compared raw, with a warning naming it.
13
+ - **New: `--raw`** (with `--worktree`) compares the working bytes; when a compared file has a
14
+ conversion, one warning: "line-ending or filter conversion is active; raw comparison may
15
+ show false differences". The `Compared` and `Result` lines say which mode was used: "as Git
16
+ would store them" or "raw bytes". In `--format json`, `compared_as`.
17
+ - **Untracked files** are listed as "Not tracked (not in the seal)", apart from "Added"
18
+ (tracked, not in the seal), and do not count as differences; `.gitignore`, the exclude list
19
+ and `.imprint/` are respected as the seal respects them. In JSON, `untracked`.
20
+ - With `core.fileMode=false` (Windows) a tracked file's mode is taken from the index, so a
21
+ sealed executable is not reported as "another mode". A link checked out as a plain file
22
+ (`core.symlinks=false`) is compared as the link it is.
23
+ - **`imprint prove --export PATH`** writes the exact sealed bytes (Git's blob at the sealed
24
+ commit, checked against the seal first); `--force` to overwrite. When the file here is not
25
+ the sealed one, the warning says whether only the line endings differ and points to
26
+ `--export`.
27
+ - **`imprint verify-file`** still fails on any byte difference, and when only the line
28
+ endings differ it says: "differs from the sealed file only in line endings; ask the owner
29
+ for the exact sealed file (imprint prove --export)".
30
+ - Help for the three commands and the README explain that a seal covers the bytes Git stores.
31
+ - Tests: `test_line_endings.py` (autocrlf true and false; `* text=auto`, `*.bat eol=crlf`,
32
+ `-text`; a clean/smudge filter; binary files; `--raw`; the index, status and objects
33
+ unchanged; untracked against added; `prove --export` and `verify-file`; core.fileMode).
34
+
3
35
  ## 0.5.0a35 — Your own file list: check, prove, verify a file [CIM-BE-58-v1]
4
36
 
5
37
  For engine 0.7.0a44.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codeimprint
3
- Version: 0.5.0a35
3
+ Version: 0.5.0a36
4
4
  Summary: CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline.
5
5
  Project-URL: Homepage, https://codeimprint.ai
6
6
  Project-URL: Hub, https://app.codeimprint.ai
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
  # Published on PyPI as `codeimprint`. The import package stays `codeimprint_cli` and the
7
7
  # command `imprint`.
8
8
  name = "codeimprint"
9
- version = "0.5.0a35"
9
+ version = "0.5.0a36"
10
10
  description = "CodeImprint: seal your code with a CodeImprint server (tamper-evident, logged and timestamped) and verify seals offline."
11
11
  readme = "README.pypi.md"
12
12
  license = "Apache-2.0"
@@ -5,4 +5,4 @@ A thin client for a CodeImprint server: it zips a project, asks the server to se
5
5
  it, and verifies Imprint files offline. All analysis happens on the server.
6
6
  """
7
7
 
8
- __version__ = "0.5.0a35"
8
+ __version__ = "0.5.0a36"
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
  import argparse
7
7
  import getpass
8
8
  import hashlib
9
+ import io
9
10
  import json
10
11
  import os
11
12
  import secrets
@@ -3342,20 +3343,76 @@ def _seal_list(client: Client, seal: str) -> dict:
3342
3343
  raise Abort(str(exc)) from exc
3343
3344
 
3344
3345
 
3345
- def _local_entries(root: Path, worktree: bool, rev: str | None) -> tuple[dict, str]:
3346
- """(entries, what was compared): a commit of this repository (default HEAD), or the
3347
- working tree. Everything is hashed here; nothing is sent."""
3346
+ RAW_WARNING = ("line-ending or filter conversion is active; raw comparison may show false "
3347
+ "differences")
3348
+
3349
+
3350
+ def _worktree_entries(root: Path, exclude: list[str], raw: bool) -> dict:
3351
+ """The working tree of a repository: {entries, untracked, mode, converted, failed}.
3352
+
3353
+ By default each file is hashed as Git would store it (Git applies its own clean filters,
3354
+ core.autocrlf, core.eol and .gitattributes, into a temporary object folder: the index,
3355
+ the repository's objects and the working files are left as they were). With ``raw`` the
3356
+ working files' bytes are hashed as they are."""
3357
+ top, under = gitrepo.toplevel(root), gitrepo.prefix(root)
3358
+ index = gitrepo.index_entries(top, under)
3359
+ loose = gitrepo.untracked(top, under)
3360
+ file_mode = gitrepo.file_mode_tracked(top)
3361
+ entries: dict[str, list] = {}
3362
+ hashed: list[str] = []
3363
+ for path in sorted(set(index) | loose, key=filelist.path_bytes):
3364
+ if path.startswith(".imprint/") or filelist.excluded(path, exclude):
3365
+ continue
3366
+ kind, oid = index.get(path, ("regular", None))
3367
+ here = root / path
3368
+ if kind == "submodule": # its recorded commit, as in the seal
3369
+ entries[path] = ["submodule", 0, oid]
3370
+ continue
3371
+ if not os.path.lexists(here) or here.is_dir():
3372
+ continue # deleted here: "removed" if the seal has it
3373
+ if here.is_symlink() or kind == "symlink":
3374
+ entries[path] = filelist.local_file(here, kind)
3375
+ entries[path][0] = "symlink" # a link checked out as a file: its text
3376
+ continue
3377
+ if file_mode:
3378
+ mode = "executable" if here.stat().st_mode & 0o111 else "regular"
3379
+ else: # no executable bit here: the index's
3380
+ mode = kind if path in index else "regular"
3381
+ entries[path] = [mode, None, None]
3382
+ hashed.append(path)
3383
+ failed: dict[str, str] = {}
3384
+ converted = gitrepo.conversions(top, [under + p for p in hashed])
3385
+ if raw:
3386
+ for path in hashed:
3387
+ _mode, size, sha = filelist.local_file(root / path)
3388
+ entries[path][1:] = [size, sha]
3389
+ else:
3390
+ digests, failed = gitrepo.stored_digests(top, [under + p for p in hashed])
3391
+ for path in hashed:
3392
+ got = digests.get(under + path)
3393
+ if got is None: # Git could not convert it: its raw bytes
3394
+ _mode, size, sha = filelist.local_file(root / path)
3395
+ got = (sha, size)
3396
+ entries[path][1:] = [got[1], got[0]]
3397
+ return {"entries": entries, "untracked": loose, "converted": converted,
3398
+ "failed": {p.removeprefix(under): why for p, why in failed.items()},
3399
+ "mode": "raw bytes" if raw else "as Git would store them"}
3400
+
3401
+
3402
+ def _local_entries(root: Path, worktree: bool, rev: str | None,
3403
+ raw: bool = False) -> tuple[dict, str, dict]:
3404
+ """(entries, what was compared, notes): a commit of this repository (default HEAD), or
3405
+ the working tree. Everything is hashed here; nothing is sent."""
3348
3406
  exclude = list(project.load_config(root).get("exclude", [])) if root.is_dir() else []
3349
3407
  git = gitrepo.is_repo(root)
3350
- if worktree or not git:
3408
+ if worktree and git:
3409
+ found = _worktree_entries(root, exclude, raw)
3410
+ return found["entries"], "the working tree", found
3411
+ if not git: # no Git: there is nothing to convert, the bytes are all
3351
3412
  entries = {p: e for p, e in project.every_file(root).items()
3352
3413
  if not filelist.excluded(p, exclude)}
3353
- if git: # a submodule is its recorded commit, as in the seal
3354
- for f in gitrepo.ls_tree_all(gitrepo.toplevel(root), "HEAD",
3355
- gitrepo.prefix(root)):
3356
- if f["mode"] == "submodule" and not filelist.excluded(f["path"], exclude):
3357
- entries[f["path"]] = ["submodule", 0, f["blob"]]
3358
- return entries, "the working tree"
3414
+ return entries, "the folder", {"mode": "raw bytes", "untracked": set(),
3415
+ "converted": [], "failed": {}}
3359
3416
  top, commit = gitrepo.toplevel(root), gitrepo.resolve(root, rev or "HEAD")
3360
3417
  listed = [f for f in gitrepo.ls_tree_all(top, commit, gitrepo.prefix(root))
3361
3418
  if not f["path"].startswith(".imprint/")]
@@ -3364,10 +3421,12 @@ def _local_entries(root: Path, worktree: bool, rev: str | None) -> tuple[dict, s
3364
3421
  for f in listed:
3365
3422
  if f["mode"] != "submodule":
3366
3423
  f["sha256"], f["size"] = digests[f["blob"]]
3367
- return filelist.entries_of(listed, exclude), f"commit {commit[:12]}"
3424
+ return filelist.entries_of(listed, exclude), f"commit {commit[:12]}", {
3425
+ "mode": "as Git stores them", "untracked": set(), "converted": [], "failed": {}}
3368
3426
 
3369
3427
 
3370
- DIFF_LABELS = (("added", "Added", "not in the seal"),
3428
+ DIFF_LABELS = (("added", "Added", "tracked, not in the seal"),
3429
+ ("untracked", "Not tracked", "not in the seal"),
3371
3430
  ("removed", "Removed", "in the seal only"),
3372
3431
  ("changed", "Changed", "other content"),
3373
3432
  ("mode", "Mode", "same content, other mode"),
@@ -3383,23 +3442,35 @@ def cmd_check_files(args) -> int:
3383
3442
  if body.get("scheme") != filelist.SCHEME:
3384
3443
  raise Abort(f"the seal lists its files with {body.get('scheme')!r}, which this "
3385
3444
  "client does not know: upgrade it")
3445
+ if args.raw and not args.worktree:
3446
+ raise Abort("--raw compares working files: use it with --worktree")
3386
3447
  try:
3387
- local, what = _local_entries(root, args.worktree, args.commit)
3448
+ local, what, notes = _local_entries(root, args.worktree, args.commit, args.raw)
3388
3449
  except gitrepo.GitError as exc:
3389
3450
  raise Abort(f"cannot read the repository: {exc}") from exc
3390
- diff = filelist.compare(filelist.sealed_entries(body), local)
3451
+ diff = filelist.compare(filelist.sealed_entries(body), local, notes["untracked"])
3391
3452
  count = sum(len(diff[k]) for k in ("added", "removed", "changed", "mode"))
3453
+ mode = notes["mode"]
3454
+ if args.raw and notes["converted"]:
3455
+ _warn(RAW_WARNING, json_out=args.format == "json")
3456
+ for path, why in sorted(notes["failed"].items()):
3457
+ _warn(f"{path}: Git could not convert it as it would store it ({why}); compared its "
3458
+ "raw bytes", json_out=args.format == "json")
3392
3459
  if args.format == "json":
3393
- print(json.dumps({"seal": seal, "compared": what, "files": body["count"],
3394
- "same": count == 0, **diff}, indent=2))
3460
+ print(json.dumps({"seal": seal, "compared": what, "compared_as": mode,
3461
+ "files": body["count"], "same": count == 0, **diff}, indent=2))
3395
3462
  else:
3396
3463
  commit = f", commit {body['commit'][:12]}" if body.get("commit") else ""
3397
3464
  _say(f"Seal {seal} ({body['count']} files{commit})",
3398
- f"Compared {what}, hashed here (nothing was sent)")
3465
+ f"Compared {what}, {mode}, hashed here (nothing was sent)")
3399
3466
  for key, label, note in DIFF_LABELS:
3400
3467
  for path in diff[key]:
3401
3468
  _say(f"{label:<10} {path} ({note})")
3402
- _say(f"Result {'every file matches the seal' if not count else f'{count} file(s) differ'}")
3469
+ verdict = ("every file matches the seal" if not count
3470
+ else f"{count} file(s) differ")
3471
+ loose = (f"; {len(diff['untracked'])} untracked file(s), not in the seal"
3472
+ if diff["untracked"] else "")
3473
+ _say(f"Result {verdict} ({mode}){loose}")
3403
3474
  if count and _ci(): # never break a build by surprise
3404
3475
  _warn(f"{count} file(s) differ from seal {seal}")
3405
3476
  return 0
@@ -3421,19 +3492,54 @@ def cmd_prove(args) -> int:
3421
3492
  raise Abort(f"{rel} is not in seal {seal}") from exc
3422
3493
  except (ApiError, NetworkError) as exc:
3423
3494
  raise Abort(f"cannot read the seal's public record: {exc}") from exc
3495
+ exported = _export_sealed(args, root, body, rel, proof) if args.export else None
3424
3496
  out = Path(args.output or f"{Path(rel).name}.proof.json")
3425
3497
  out.write_text(json.dumps(proof, indent=1, sort_keys=True) + "\n", encoding="utf-8")
3426
3498
  _say(f"Seal {seal}", f"File {rel} ({proof['kind']}, {proof['size']:,} bytes)",
3427
3499
  f"Proof {out}",
3500
+ *([f"Exported {exported} (the exact sealed bytes: hand this file over with "
3501
+ + "the proof)"] if exported else []),
3428
3502
  "Shares this file's hash, size, mode and salt only; no other file of the seal",
3429
- f"Check imprint verify-file {rel} --proof {out}")
3430
- if target.exists() or target.is_symlink():
3503
+ f"Check imprint verify-file {exported or rel} --proof {out}")
3504
+ if not exported and (target.exists() or target.is_symlink()):
3431
3505
  here = filelist.local_file(target, proof["kind"])
3432
3506
  if here[1:] != [proof["size"], proof["ref"]]:
3433
- _warn("the file here is not the sealed one: the proof is for the sealed content")
3507
+ why = ("differs from the sealed one only in line endings" if
3508
+ filelist.line_endings_only(target, proof["size"], proof["ref"])
3509
+ else "is not the sealed one (its content differs)")
3510
+ _warn(f"the file here {why}: the proof is for the sealed content, so this copy "
3511
+ "will not verify. Use --export FILE to write the exact sealed file")
3434
3512
  return 0
3435
3513
 
3436
3514
 
3515
+ def _export_sealed(args, root: Path, body: dict, rel: str, proof: dict) -> Path:
3516
+ """`imprint prove --export`: the exact bytes Git stores for the file at the sealed
3517
+ commit, checked against the seal before they are written."""
3518
+ out = Path(args.export)
3519
+ if (out.exists() or out.is_symlink()) and not args.force:
3520
+ raise Abort(f"{out} exists: pass --force to overwrite it")
3521
+ if proof["kind"] not in ("regular", "executable"):
3522
+ raise Abort(f"{rel} is sealed as {proof['kind']}: only a file's content can be "
3523
+ "exported")
3524
+ if not body.get("commit") or not gitrepo.is_repo(root):
3525
+ raise Abort("the seal names no commit of this repository to export from")
3526
+ top = gitrepo.toplevel(root)
3527
+ try:
3528
+ data = gitrepo.blob_at(top, body["commit"], gitrepo.prefix(root) + rel)
3529
+ except gitrepo.GitError as exc:
3530
+ raise Abort(f"the sealed commit {body['commit'][:12]} is not in this repository "
3531
+ f"(fetch it first): {exc}") from exc
3532
+ sha, size = filelist.hash_stream(io.BytesIO(data).read)
3533
+ if (sha, size) != (proof["ref"], proof["size"]):
3534
+ raise Abort("the sealed commit's file is not the sealed content; nothing was written")
3535
+ if out.is_symlink():
3536
+ out.unlink()
3537
+ out.write_bytes(data)
3538
+ if proof["kind"] == "executable" and os.name != "nt":
3539
+ out.chmod(out.stat().st_mode | 0o111)
3540
+ return out
3541
+
3542
+
3437
3543
  def cmd_verify_file(args) -> int:
3438
3544
  """`imprint verify-file <file> --proof P`: no account. The seal's receipt is verified,
3439
3545
  then the file's hash, through the proof, is shown to be in the sealed list."""
@@ -3475,6 +3581,11 @@ def cmd_verify_file(args) -> int:
3475
3581
  except OSError as exc:
3476
3582
  raise Abort(f"cannot read {args.file}: {exc}") from exc
3477
3583
  problems = filelist.check_proof(proof, files, here)
3584
+ if "this file's content is not the sealed one" in problems and \
3585
+ filelist.line_endings_only(args.file, proof["size"], proof["ref"]):
3586
+ problems[problems.index("this file's content is not the sealed one")] = (
3587
+ "differs from the sealed file only in line endings; ask the owner for the "
3588
+ "exact sealed file (imprint prove --export)")
3478
3589
  name = filelist.proof_path(proof)
3479
3590
  checks.append(receipt.Check("file", receipt.FAIL if problems else receipt.PASS,
3480
3591
  "; ".join(problems) if problems else
@@ -3810,25 +3921,42 @@ def build_parser() -> argparse.ArgumentParser:
3810
3921
  c.add_argument("--yes", action="store_true", help="do not ask before uploading (CI)")
3811
3922
  c.add_argument("--files", action="store_true",
3812
3923
  help="compare every file with a seal's file list, hashed here; nothing is "
3813
- "uploaded (engine 0.7.0a44, the seal's owner)")
3924
+ "uploaded (engine 0.7.0a44, the seal's owner). A seal covers the "
3925
+ "bytes Git stores")
3814
3926
  c.add_argument("--seal", help="with --files: the seal (default: this folder's baseline)")
3815
3927
  c.add_argument("--commit", help="with --files: the commit to compare (default HEAD)")
3816
3928
  c.add_argument("--worktree", action="store_true",
3817
- help="with --files: compare the working tree instead of a commit")
3929
+ help="with --files: compare the working tree, each file as Git would store "
3930
+ "it (line endings, .gitattributes and filters applied, as `git add` "
3931
+ "would; the index and your files are left as they are)")
3932
+ c.add_argument("--raw", action="store_true",
3933
+ help="with --worktree: compare the working files byte for byte, without "
3934
+ "Git's conversions (may show line-ending differences)")
3818
3935
  c.set_defaults(func=cmd_check)
3819
3936
 
3820
- pv = sub.add_parser("prove", help="make a proof that one file is in a seal (its owner)")
3937
+ pv = sub.add_parser("prove", help="make a proof that one file is in a seal (its owner)",
3938
+ epilog="The proof is for the sealed content: the bytes Git stores at "
3939
+ "the sealed commit. A working copy with other line endings "
3940
+ "(core.autocrlf) will not verify; --export writes the exact "
3941
+ "sealed file to hand over with the proof.")
3821
3942
  pv.add_argument("path", help="the file, as in the sealed folder")
3822
3943
  pv.add_argument("--seal", help="the seal (default: this folder's baseline)")
3823
3944
  pv.add_argument("--root", default=".", help="the sealed folder (default: here)")
3824
3945
  pv.add_argument("-o", "--output", help="where to write it (default <name>.proof.json)")
3825
3946
  pv.add_argument("--url", help="server URL (overrides login and CODEIMPRINT_URL)")
3947
+ pv.add_argument("--export", metavar="PATH",
3948
+ help="also write the exact sealed bytes of the file (from Git, at the "
3949
+ "sealed commit) to PATH, for the other party to verify")
3950
+ pv.add_argument("--force", action="store_true", help="with --export: overwrite PATH")
3826
3951
  pv.set_defaults(func=cmd_prove)
3827
3952
 
3828
3953
  vf = sub.add_parser("verify-file", help="check that a file is in a seal, from a proof "
3829
3954
  "(no account)",
3830
- epilog="Exit codes: 0 VERIFIED; 1 NOT VERIFIED; 2 a usage or other "
3831
- "error; 3 a newer format than this client understands.")
3955
+ epilog="The file must be byte for byte the sealed one: nothing is "
3956
+ "converted (a copy with other line endings fails; ask the owner "
3957
+ "for the exact file, `imprint prove --export`). Exit codes: 0 "
3958
+ "VERIFIED; 1 NOT VERIFIED; 2 a usage or other error; 3 a newer "
3959
+ "format than this client understands.")
3832
3960
  vf.add_argument("file", help="the file to check")
3833
3961
  vf.add_argument("--proof", required=True, help="the proof (from `imprint prove`)")
3834
3962
  vf.add_argument("--keys", metavar="FILE",
@@ -176,17 +176,19 @@ def sealed_entries(body: dict) -> dict[str, list]:
176
176
  return out
177
177
 
178
178
 
179
- def compare(sealed: dict[str, list], local: dict[str, list]) -> dict[str, list[str]]:
180
- """What differs: {added, removed, changed, mode, unhashed}, each a sorted list of paths.
181
- ``mode``: the same content with another mode. ``unhashed``: files the seal lists without
182
- a hash, which cannot be compared."""
183
- out: dict[str, list[str]] = {"added": [], "removed": [], "changed": [], "mode": [],
184
- "unhashed": []}
179
+ def compare(sealed: dict[str, list], local: dict[str, list],
180
+ untracked: set[str] = frozenset()) -> dict[str, list[str]]:
181
+ """What differs: {added, untracked, removed, changed, mode, unhashed}, each a sorted
182
+ list of paths. ``added``: tracked here, not in the seal; ``untracked``: a file Git does not
183
+ track, not in the seal. ``mode``: the same content with another mode. ``unhashed``:
184
+ files the seal lists without a hash, which cannot be compared."""
185
+ out: dict[str, list[str]] = {"added": [], "untracked": [], "removed": [], "changed": [],
186
+ "mode": [], "unhashed": []}
185
187
  for path in sorted(set(sealed) | set(local), key=path_bytes):
186
188
  if path not in local:
187
189
  out["removed"].append(path)
188
190
  elif path not in sealed:
189
- out["added"].append(path)
191
+ out["untracked" if path in untracked else "added"].append(path)
190
192
  elif sealed[path][0] == "unhashed":
191
193
  out["unhashed"].append(path)
192
194
  elif sealed[path] != local[path]:
@@ -271,6 +273,26 @@ def check_proof(proof: dict, files: dict, local: list | None) -> list[str]:
271
273
  return problems
272
274
 
273
275
 
276
+ LINE_ENDINGS_MAX = 256 * 1024 * 1024
277
+
278
+
279
+ def line_endings_only(path, size: int, ref: str) -> bool:
280
+ """Whether the file at ``path`` is the sealed content (``size``, SHA-256 ``ref``) but for
281
+ its line endings (CRLF where the seal has LF, or the other way round). Only to explain a
282
+ difference: a file that differs never verifies."""
283
+ import re
284
+ from pathlib import Path
285
+
286
+ p = Path(path)
287
+ if p.is_symlink() or not p.is_file() or p.stat().st_size > LINE_ENDINGS_MAX:
288
+ return False
289
+ data = p.read_bytes()
290
+ for other in (data.replace(b"\r\n", b"\n"), re.sub(rb"(?<!\r)\n", b"\r\n", data)):
291
+ if other != data and len(other) == size and hashlib.sha256(other).hexdigest() == ref:
292
+ return True
293
+ return False
294
+
295
+
274
296
  def local_file(path, kind_hint: str | None = None) -> list:
275
297
  """[kind, size, sha256] of a file on this machine (a link: its target text)."""
276
298
  import os
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  import os
12
12
  import subprocess
13
+ import tempfile
13
14
  from pathlib import Path
14
15
 
15
16
  from . import filelist
@@ -19,10 +20,11 @@ class GitError(Exception):
19
20
  """Not a Git repository, or a git command failed."""
20
21
 
21
22
 
22
- def _git(root: Path, *args: str, input: bytes | None = None) -> bytes:
23
+ def _git(root: Path, *args: str, input: bytes | None = None,
24
+ env: dict | None = None) -> bytes:
23
25
  try:
24
26
  done = subprocess.run(["git", "-C", str(root), *args], input=input, capture_output=True,
25
- check=True)
27
+ check=True, env=env)
26
28
  except FileNotFoundError as exc:
27
29
  raise GitError("git is not installed") from exc
28
30
  except subprocess.CalledProcessError as exc:
@@ -224,14 +226,15 @@ def ls_tree_all(root: Path, commit: str, under: str = "") -> list[dict]:
224
226
  return files
225
227
 
226
228
 
227
- def hash_blobs(root: Path, blob_ids: list[str]) -> dict[str, tuple[str, int]]:
229
+ def hash_blobs(root: Path, blob_ids: list[str],
230
+ env: dict | None = None) -> dict[str, tuple[str, int]]:
228
231
  """{blob ID: (SHA-256, size)} of each blob's raw bytes, read in parts through one
229
232
  `git cat-file --batch` process: a large file is never held whole."""
230
233
  out: dict[str, tuple[str, int]] = {}
231
234
  if not blob_ids:
232
235
  return out
233
236
  proc = subprocess.Popen(["git", "-C", str(root), "cat-file", "--batch"],
234
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
237
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
235
238
  try:
236
239
  for blob in blob_ids:
237
240
  proc.stdin.write(blob.encode() + b"\n")
@@ -259,6 +262,105 @@ def hash_blobs(root: Path, blob_ids: list[str]) -> dict[str, tuple[str, int]]:
259
262
  return out
260
263
 
261
264
 
265
+ # -- the working tree as Git would store it (client 0.5.0a36) --------------------------------
266
+ def _under(raw: bytes, under: str) -> str | None:
267
+ path = raw.decode("utf-8", errors="surrogateescape")
268
+ return path[len(under):] if path.startswith(under) and not path.endswith("/") else None
269
+
270
+
271
+ def index_entries(top: Path, under: str = "") -> dict[str, tuple[str, str]]:
272
+ """{path: (kind, object ID)} of the index (what is tracked), relative to ``under``."""
273
+ out = {}
274
+ for record in _git(top, "ls-files", "-s", "-z").split(b"\0"):
275
+ if not record:
276
+ continue
277
+ meta, _, raw = record.partition(b"\t")
278
+ mode, oid, _stage = meta.decode().split()
279
+ path = _under(raw, under)
280
+ if path is not None:
281
+ out[path] = (filelist.GIT_MODES.get(mode, "regular"), oid)
282
+ return out
283
+
284
+
285
+ def untracked(top: Path, under: str = "") -> set[str]:
286
+ """Files Git does not track and does not ignore (.gitignore, info/exclude)."""
287
+ out = set()
288
+ for raw in _git(top, "ls-files", "-z", "--others", "--exclude-standard").split(b"\0"):
289
+ path = _under(raw, under) if raw else None
290
+ if path is not None:
291
+ out.add(path)
292
+ return out
293
+
294
+
295
+ def file_mode_tracked(top: Path) -> bool:
296
+ """core.fileMode: whether this checkout records the executable bit (false on Windows)."""
297
+ try:
298
+ return _git(top, "config", "--bool", "core.filemode").strip() != b"false"
299
+ except GitError:
300
+ return True
301
+
302
+
303
+ def conversions(top: Path, paths: list[str]) -> list[str]:
304
+ """The paths (relative to ``top``) whose bytes Git converts between the working tree and
305
+ the repository: core.autocrlf, or a text, eol, filter, ident or working-tree-encoding
306
+ attribute."""
307
+ if not paths:
308
+ return []
309
+ try:
310
+ autocrlf = _git(top, "config", "core.autocrlf").strip().lower()
311
+ except GitError:
312
+ autocrlf = b""
313
+ if autocrlf in (b"true", b"input"):
314
+ return list(paths)
315
+ out = _git(top, "check-attr", "-z", "--stdin", "text", "eol", "filter", "ident",
316
+ "working-tree-encoding",
317
+ input=b"\0".join(p.encode("utf-8", "surrogateescape") for p in paths) + b"\0")
318
+ parts = out.split(b"\0")
319
+ active = set()
320
+ for i in range(0, len(parts) - 2, 3):
321
+ if parts[i + 2] not in (b"unspecified", b"unset"):
322
+ active.add(parts[i].decode("utf-8", "surrogateescape"))
323
+ return [p for p in paths if p in active]
324
+
325
+
326
+ def stored_digests(top: Path, paths: list[str]
327
+ ) -> tuple[dict[str, tuple[str, int]], dict[str, str]]:
328
+ """({path: (SHA-256, size)}, {path: why not}) of working files (relative to ``top``) as
329
+ Git would store them: clean filters, core.autocrlf, core.eol and .gitattributes applied,
330
+ by Git itself (`git hash-object --stdin-paths`). The objects go to a temporary folder
331
+ that is deleted afterwards; the repository's index, objects and working files are never
332
+ written."""
333
+ if not paths:
334
+ return {}, {}
335
+ real = _git(top, "rev-parse", "--git-path", "objects").decode().strip()
336
+ real = str(Path(real) if Path(real).is_absolute() else Path(top) / real)
337
+ with tempfile.TemporaryDirectory(prefix="codeimprint-objects-") as tmp:
338
+ env = {**os.environ, "GIT_OBJECT_DIRECTORY": tmp,
339
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES": real}
340
+ ids: dict[str, str] = {}
341
+ failed: dict[str, str] = {}
342
+ batch = [p for p in paths if "\n" not in p]
343
+ try:
344
+ out = _git(top, "hash-object", "-w", "--stdin-paths", env=env, input="".join(
345
+ p + "\n" for p in batch).encode("utf-8", "surrogateescape")).split()
346
+ ids = {p: oid.decode() for p, oid in zip(batch, out)}
347
+ rest = [p for p in paths if p not in ids]
348
+ except GitError:
349
+ rest = list(paths)
350
+ for p in rest: # one by one: say which one failed
351
+ try:
352
+ ids[p] = _git(top, "hash-object", "-w", "--", p, env=env).decode().strip()
353
+ except GitError as exc:
354
+ failed[p] = str(exc)
355
+ digests = hash_blobs(top, sorted(set(ids.values())), env=env)
356
+ return {p: digests[oid] for p, oid in ids.items()}, failed
357
+
358
+
359
+ def blob_at(top: Path, commit: str, path: str) -> bytes:
360
+ """The bytes Git stores for ``path`` (from the top) at ``commit``."""
361
+ return _git(top, "cat-file", "blob", f"{commit}:{path}")
362
+
363
+
262
364
  def read_blobs(root: Path, blob_ids: list[str]):
263
365
  """Yield (blob ID, content) for each ID, via one `git cat-file --batch` process."""
264
366
  if not blob_ids:
File without changes
File without changes