giwon 0.1.0__py3-none-any.whl
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.
- giwon/__init__.py +1 -0
- giwon/cli.py +67 -0
- giwon/config.py +128 -0
- giwon/discovery/__init__.py +1 -0
- giwon/discovery/apptainer.py +47 -0
- giwon/discovery/docker.py +158 -0
- giwon/discovery/environment.py +42 -0
- giwon/discovery/git.py +165 -0
- giwon/discovery/hardware.py +326 -0
- giwon/discovery/image.py +119 -0
- giwon/discovery/pyxis.py +45 -0
- giwon/discovery/slurm.py +376 -0
- giwon/discovery/system.py +22 -0
- giwon/hashing.py +216 -0
- giwon/record.yaml +89 -0
- giwon/run.py +347 -0
- giwon/snapshot.py +134 -0
- giwon-0.1.0.dist-info/METADATA +9 -0
- giwon-0.1.0.dist-info/RECORD +21 -0
- giwon-0.1.0.dist-info/WHEEL +4 -0
- giwon-0.1.0.dist-info/entry_points.txt +3 -0
giwon/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Capture provenance around experiment executions."""
|
giwon/cli.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Parse Giwon options and launch the experiment command."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import signal
|
|
5
|
+
import sys
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated
|
|
9
|
+
|
|
10
|
+
import tyro
|
|
11
|
+
|
|
12
|
+
from giwon import run
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class Options:
|
|
17
|
+
purpose: str | None = None
|
|
18
|
+
image: str | None = None
|
|
19
|
+
config: Path | None = None
|
|
20
|
+
record_root: Path | None = None
|
|
21
|
+
hash_inputs: Annotated[
|
|
22
|
+
list[Path], tyro.conf.UseAppendAction, tyro.conf.arg(name="hash-input")
|
|
23
|
+
] = field(default_factory=list)
|
|
24
|
+
sample_bytes: int | None = None
|
|
25
|
+
record_env: Annotated[list[str], tyro.conf.UseAppendAction] = field(
|
|
26
|
+
default_factory=list
|
|
27
|
+
)
|
|
28
|
+
max_patch_bytes: int | None = None
|
|
29
|
+
patch_context: int | None = None
|
|
30
|
+
hash_outputs: bool | None = None
|
|
31
|
+
slurm_probes: bool | None = None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse(argv: list[str]) -> tuple[Options, list[str]]:
|
|
35
|
+
split = argv.index("--") if "--" in argv else len(argv)
|
|
36
|
+
options = tyro.cli(
|
|
37
|
+
Options, args=argv[:split], prog="giwon", config=(tyro.conf.DisallowNone,)
|
|
38
|
+
)
|
|
39
|
+
command = argv[split + 1 :]
|
|
40
|
+
if not command:
|
|
41
|
+
print("giwon: expected a command after --", file=sys.stderr)
|
|
42
|
+
raise SystemExit(2)
|
|
43
|
+
return options, command
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def main() -> None:
|
|
47
|
+
"""Run the experiment from command-line arguments and reproduce its exit status.
|
|
48
|
+
|
|
49
|
+
A numeric exit code does not tell the parent shell that a process died
|
|
50
|
+
from a signal. After finalization, re-deliver the child's terminating signal
|
|
51
|
+
to this wrapper so the shell observes the same termination.
|
|
52
|
+
"""
|
|
53
|
+
options, command = parse(sys.argv[1:])
|
|
54
|
+
values = asdict(options)
|
|
55
|
+
purpose = values.pop("purpose")
|
|
56
|
+
image = values.pop("image")
|
|
57
|
+
result = run.run(command, values, purpose=purpose, image=image)
|
|
58
|
+
|
|
59
|
+
if result < 0:
|
|
60
|
+
number = -result
|
|
61
|
+
if number not in {signal.SIGKILL, signal.SIGSTOP}:
|
|
62
|
+
signal.signal(number, signal.SIG_DFL)
|
|
63
|
+
signal.pthread_sigmask(signal.SIG_UNBLOCK, {number})
|
|
64
|
+
os.kill(os.getpid(), number)
|
|
65
|
+
result = 128 + number
|
|
66
|
+
|
|
67
|
+
raise SystemExit(result)
|
giwon/config.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Load and validate settings from defaults, a project file, and CLI options."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import yaml
|
|
8
|
+
|
|
9
|
+
DEFAULT_RECORD_ENV = (
|
|
10
|
+
"GIWON_DIR",
|
|
11
|
+
"GIWON_FILE",
|
|
12
|
+
"GIWON_RUN_ID",
|
|
13
|
+
"PATH",
|
|
14
|
+
"PYTHONPATH",
|
|
15
|
+
"PYTHONHOME",
|
|
16
|
+
"LD_LIBRARY_PATH",
|
|
17
|
+
"LD_PRELOAD",
|
|
18
|
+
"CUDA_VISIBLE_DEVICES",
|
|
19
|
+
"OMP_NUM_THREADS",
|
|
20
|
+
"MKL_NUM_THREADS",
|
|
21
|
+
"PYTHONHASHSEED",
|
|
22
|
+
"APPTAINER_CONTAINER",
|
|
23
|
+
"APPTAINER_COMMAND",
|
|
24
|
+
"SLURM_JOB_ID",
|
|
25
|
+
"SLURM_JOBID",
|
|
26
|
+
"SLURM_CLUSTER_NAME",
|
|
27
|
+
"SLURM_STEP_ID",
|
|
28
|
+
"SLURM_ARRAY_JOB_ID",
|
|
29
|
+
"SLURM_ARRAY_TASK_ID",
|
|
30
|
+
"SLURM_PROCID",
|
|
31
|
+
"SLURM_LOCALID",
|
|
32
|
+
"SLURM_NODEID",
|
|
33
|
+
"SLURM_JOB_GPUS",
|
|
34
|
+
"SLURM_STEP_GPUS",
|
|
35
|
+
"SLURM_CPUS_ON_NODE",
|
|
36
|
+
"SLURM_JOB_CPUS_PER_NODE",
|
|
37
|
+
"SLURM_STEP_NODELIST",
|
|
38
|
+
"SLURM_STEP_NUM_TASKS",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
DEFAULTS: dict[str, Any] = {
|
|
42
|
+
"record_root": ".snapshots",
|
|
43
|
+
"hash_inputs": [],
|
|
44
|
+
"record_env": list(DEFAULT_RECORD_ENV),
|
|
45
|
+
"max_patch_bytes": 1_048_576,
|
|
46
|
+
"patch_context": 3,
|
|
47
|
+
"sample_bytes": 1_073_741_824,
|
|
48
|
+
"hash_outputs": False,
|
|
49
|
+
"slurm_probes": True,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _path(value, base):
|
|
54
|
+
value = os.fspath(value)
|
|
55
|
+
if not value or "\0" in value:
|
|
56
|
+
raise ValueError("paths must be nonempty and contain no NUL")
|
|
57
|
+
return Path(os.path.abspath(base / Path(value).expanduser()))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _validate_yaml(values):
|
|
61
|
+
for key, value in values.items():
|
|
62
|
+
if key not in DEFAULTS:
|
|
63
|
+
raise ValueError(f"unknown configuration key: {key}")
|
|
64
|
+
if type(value) is not type(DEFAULTS[key]):
|
|
65
|
+
raise TypeError(f"invalid type for {key}: {value!r}")
|
|
66
|
+
if key in {"hash_inputs", "record_env"} and any(
|
|
67
|
+
not isinstance(item, str) for item in value
|
|
68
|
+
):
|
|
69
|
+
raise TypeError(f"{key} must contain strings")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _discover(cwd, boundary):
|
|
73
|
+
for directory in (cwd, *cwd.parents):
|
|
74
|
+
path = directory / "giwon.config.yaml"
|
|
75
|
+
if os.path.lexists(path):
|
|
76
|
+
return path
|
|
77
|
+
if directory == boundary:
|
|
78
|
+
break
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def load(
|
|
83
|
+
cwd: Path, overrides: dict[str, Any], *, git_root: Path | None = None
|
|
84
|
+
) -> dict[str, Any]:
|
|
85
|
+
cwd = Path(os.path.abspath(cwd))
|
|
86
|
+
selected = overrides.get("config")
|
|
87
|
+
selected = (
|
|
88
|
+
_path(selected, cwd) if selected is not None else _discover(cwd, git_root)
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
configured = {}
|
|
92
|
+
if selected is not None:
|
|
93
|
+
with selected.open(encoding="utf-8") as stream:
|
|
94
|
+
configured = yaml.safe_load(stream)
|
|
95
|
+
_validate_yaml(configured)
|
|
96
|
+
|
|
97
|
+
settings: dict[str, Any] = dict(DEFAULTS)
|
|
98
|
+
settings["record_root"] = _path(settings["record_root"], cwd)
|
|
99
|
+
settings["hash_inputs"] = []
|
|
100
|
+
settings["record_env"] = list(settings["record_env"])
|
|
101
|
+
|
|
102
|
+
for source, base in (
|
|
103
|
+
(configured, selected.parent if selected else cwd),
|
|
104
|
+
(overrides, cwd),
|
|
105
|
+
):
|
|
106
|
+
for key, value in source.items():
|
|
107
|
+
if value is None or key == "config":
|
|
108
|
+
continue
|
|
109
|
+
if key == "record_root":
|
|
110
|
+
settings[key] = _path(value, base)
|
|
111
|
+
elif key in {"hash_inputs", "record_env"}:
|
|
112
|
+
if key == "record_env" and any(
|
|
113
|
+
not name or "=" in name or "\0" in name for name in value
|
|
114
|
+
):
|
|
115
|
+
raise ValueError("invalid environment variable name")
|
|
116
|
+
additions = (
|
|
117
|
+
[_path(v, base) for v in value] if key == "hash_inputs" else value
|
|
118
|
+
)
|
|
119
|
+
settings[key] = list(dict.fromkeys([*settings[key], *additions]))
|
|
120
|
+
else:
|
|
121
|
+
if key in {"max_patch_bytes", "sample_bytes"} and value <= 0:
|
|
122
|
+
raise ValueError(f"{key} must be positive")
|
|
123
|
+
if key == "patch_context" and value < 0:
|
|
124
|
+
raise ValueError("patch_context must be nonnegative")
|
|
125
|
+
settings[key] = value
|
|
126
|
+
|
|
127
|
+
settings["config"] = selected
|
|
128
|
+
return settings
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Collect provenance from the execution environment."""
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Read metadata inside the Apptainer runtime containing Giwon."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from giwon import hashing
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _runtime(env):
|
|
11
|
+
"""Read current-image metadata after matching Apptainer runtime variables.
|
|
12
|
+
|
|
13
|
+
Build labels do not identify the executing engine or the final image.
|
|
14
|
+
Hash the runtime-reported image file when it is accessible; otherwise retain
|
|
15
|
+
its reference without inventing an identity or engine version.
|
|
16
|
+
"""
|
|
17
|
+
reference = env.get("APPTAINER_CONTAINER")
|
|
18
|
+
if not reference or env.get("APPTAINER_COMMAND") not in {
|
|
19
|
+
"exec",
|
|
20
|
+
"run",
|
|
21
|
+
"shell",
|
|
22
|
+
"test",
|
|
23
|
+
"instance start",
|
|
24
|
+
}:
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
metadata = Path("/.singularity.d")
|
|
28
|
+
try:
|
|
29
|
+
if not metadata.is_dir():
|
|
30
|
+
return None
|
|
31
|
+
except OSError as error:
|
|
32
|
+
print(f"giwon: unavailable Apptainer metadata: {error}", file=sys.stderr)
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
facts: dict = {"name": "apptainer", "image": {"reference": reference}}
|
|
36
|
+
try:
|
|
37
|
+
path = Path(reference)
|
|
38
|
+
if path.is_file():
|
|
39
|
+
facts["image"]["hash"] = hashing.fingerprint(path)
|
|
40
|
+
except (OSError, ValueError, RuntimeError) as error:
|
|
41
|
+
print(f"giwon: unavailable Apptainer image hash: {error}", file=sys.stderr)
|
|
42
|
+
return facts
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def collect(env: Mapping[str, str]) -> dict | None:
|
|
46
|
+
runtime = _runtime(env)
|
|
47
|
+
return {"runtime": runtime} if runtime is not None else None
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""Inspect Docker images and observe the container containing Giwon."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _query(arguments, cwd, env, *, timeout=3):
|
|
12
|
+
result = subprocess.run(
|
|
13
|
+
["docker", *arguments],
|
|
14
|
+
cwd=cwd,
|
|
15
|
+
env=env,
|
|
16
|
+
stdin=subprocess.DEVNULL,
|
|
17
|
+
capture_output=True,
|
|
18
|
+
text=True,
|
|
19
|
+
timeout=timeout,
|
|
20
|
+
check=True,
|
|
21
|
+
)
|
|
22
|
+
return json.loads(result.stdout)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def inspect_image(reference: str, cwd: Path, env: Mapping[str, str]) -> dict:
|
|
26
|
+
result = _query(["image", "inspect", "--", reference], cwd, env)
|
|
27
|
+
if not isinstance(result, list) or len(result) != 1:
|
|
28
|
+
raise ValueError("expected one Docker image")
|
|
29
|
+
|
|
30
|
+
image = result[0]
|
|
31
|
+
if not isinstance(image, dict):
|
|
32
|
+
raise TypeError("expected Docker image metadata to be a mapping")
|
|
33
|
+
|
|
34
|
+
identity = image.get("Id")
|
|
35
|
+
if not isinstance(identity, str) or not re.fullmatch(
|
|
36
|
+
r"sha256:[0-9a-f]{64}", identity
|
|
37
|
+
):
|
|
38
|
+
raise ValueError("Docker image inspection has no valid image ID")
|
|
39
|
+
if re.fullmatch(r"sha256:[0-9a-f]{64}", reference) and identity != reference:
|
|
40
|
+
raise ValueError("Docker inspection does not match the requested image ID")
|
|
41
|
+
|
|
42
|
+
facts = {"id": identity}
|
|
43
|
+
digests = image.get("RepoDigests")
|
|
44
|
+
if (
|
|
45
|
+
isinstance(digests, list)
|
|
46
|
+
and digests
|
|
47
|
+
and all(isinstance(d, str) for d in digests)
|
|
48
|
+
):
|
|
49
|
+
facts["repo_digests"] = digests
|
|
50
|
+
return facts
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def inspect_registry(reference: str, cwd: Path, env: Mapping[str, str]) -> dict:
|
|
54
|
+
manifest = _query(
|
|
55
|
+
[
|
|
56
|
+
"buildx",
|
|
57
|
+
"imagetools",
|
|
58
|
+
"inspect",
|
|
59
|
+
"--format",
|
|
60
|
+
"{{json .Manifest}}",
|
|
61
|
+
"--",
|
|
62
|
+
reference,
|
|
63
|
+
],
|
|
64
|
+
cwd,
|
|
65
|
+
env,
|
|
66
|
+
timeout=10,
|
|
67
|
+
)
|
|
68
|
+
if not isinstance(manifest, dict):
|
|
69
|
+
raise TypeError("expected a registry manifest mapping")
|
|
70
|
+
digest = manifest.get("digest")
|
|
71
|
+
if not isinstance(digest, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", digest):
|
|
72
|
+
raise ValueError("registry inspection has no valid manifest digest")
|
|
73
|
+
if "@" in reference and reference.rsplit("@", 1)[1] != digest:
|
|
74
|
+
raise ValueError("registry inspection does not match the requested digest")
|
|
75
|
+
return {"reference": reference.split("@", 1)[0] + "@" + digest}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _runtime(cwd, env):
|
|
79
|
+
"""Observe Docker using a marker or a Docker-specific current cgroup.
|
|
80
|
+
|
|
81
|
+
Hostnames can be customized and inherited cgroups can identify an outer
|
|
82
|
+
container. Inspect only one full ID from the current process's Docker
|
|
83
|
+
cgroup; a marker without that identity records only the runtime name.
|
|
84
|
+
"""
|
|
85
|
+
detected = False
|
|
86
|
+
try:
|
|
87
|
+
detected = Path("/.dockerenv").exists()
|
|
88
|
+
except OSError as error:
|
|
89
|
+
print(f"giwon: unavailable Docker marker: {error}", file=sys.stderr)
|
|
90
|
+
|
|
91
|
+
identities = set()
|
|
92
|
+
try:
|
|
93
|
+
cgroups = Path("/proc/self/cgroup").read_text()
|
|
94
|
+
identities = set(
|
|
95
|
+
re.findall(
|
|
96
|
+
r"(?:/docker/|/docker-)([0-9a-f]{64})(?:\.scope)?(?=/|$)",
|
|
97
|
+
cgroups,
|
|
98
|
+
re.MULTILINE,
|
|
99
|
+
)
|
|
100
|
+
)
|
|
101
|
+
except FileNotFoundError:
|
|
102
|
+
pass
|
|
103
|
+
except (OSError, UnicodeError) as error:
|
|
104
|
+
print(f"giwon: unavailable Docker cgroup: {error}", file=sys.stderr)
|
|
105
|
+
|
|
106
|
+
if not detected and not identities:
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
facts = {"name": "docker"}
|
|
110
|
+
if len(identities) != 1:
|
|
111
|
+
return facts
|
|
112
|
+
|
|
113
|
+
identity = identities.pop()
|
|
114
|
+
try:
|
|
115
|
+
result = _query(["container", "inspect", identity], cwd, env)
|
|
116
|
+
if not isinstance(result, list) or len(result) != 1:
|
|
117
|
+
raise ValueError("expected one Docker container")
|
|
118
|
+
container = result[0]
|
|
119
|
+
if not isinstance(container, dict) or container.get("Id") != identity:
|
|
120
|
+
raise ValueError("Docker inspection does not match the current container")
|
|
121
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
122
|
+
print(f"giwon: unavailable Docker inspection: {error}", file=sys.stderr)
|
|
123
|
+
return facts
|
|
124
|
+
|
|
125
|
+
image = {}
|
|
126
|
+
config = container.get("Config")
|
|
127
|
+
if (
|
|
128
|
+
isinstance(config, dict)
|
|
129
|
+
and isinstance(config.get("Image"), str)
|
|
130
|
+
and config["Image"]
|
|
131
|
+
):
|
|
132
|
+
image["reference"] = config["Image"]
|
|
133
|
+
image_id = container.get("Image")
|
|
134
|
+
if isinstance(image_id, str) and re.fullmatch(r"sha256:[0-9a-f]{64}", image_id):
|
|
135
|
+
image["id"] = image_id
|
|
136
|
+
if image:
|
|
137
|
+
facts["image"] = image
|
|
138
|
+
|
|
139
|
+
if "id" in image:
|
|
140
|
+
try:
|
|
141
|
+
image.update(inspect_image(image["id"], cwd, env))
|
|
142
|
+
except (OSError, ValueError, TypeError, subprocess.SubprocessError) as error:
|
|
143
|
+
print(
|
|
144
|
+
f"giwon: unavailable Docker image inspection: {error}", file=sys.stderr
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
result = _query(["version", "--format", "{{json .Server.Version}}"], cwd, env)
|
|
149
|
+
if isinstance(result, str) and result:
|
|
150
|
+
facts["version"] = result
|
|
151
|
+
except (OSError, ValueError, subprocess.SubprocessError) as error:
|
|
152
|
+
print(f"giwon: unavailable Docker runtime version: {error}", file=sys.stderr)
|
|
153
|
+
return facts
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def collect(cwd: Path, env: Mapping[str, str]) -> dict | None:
|
|
157
|
+
runtime = _runtime(cwd, env)
|
|
158
|
+
return {"runtime": runtime} if runtime is not None else None
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Capture selected child variables and observe the launch executable."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from giwon import snapshot
|
|
10
|
+
from giwon.config import DEFAULT_RECORD_ENV
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def collect(
|
|
14
|
+
command: Sequence[str],
|
|
15
|
+
env: Mapping[str, str],
|
|
16
|
+
directory: Path,
|
|
17
|
+
names: Sequence[str],
|
|
18
|
+
) -> dict[str, str]:
|
|
19
|
+
"""Collect launch facts using the prepared child environment and current cwd.
|
|
20
|
+
|
|
21
|
+
Virtualenv executables may link to a shared Python binary. Preserve the
|
|
22
|
+
launch path because resolving it can identify a different Python environment.
|
|
23
|
+
"""
|
|
24
|
+
facts = {}
|
|
25
|
+
if names:
|
|
26
|
+
variables = {
|
|
27
|
+
name: env.get(name)
|
|
28
|
+
for name in names
|
|
29
|
+
if name in env or name not in DEFAULT_RECORD_ENV
|
|
30
|
+
}
|
|
31
|
+
snapshot.write(directory / "environment.yaml", variables, normalize=False)
|
|
32
|
+
facts["variables_file"] = "environment.yaml"
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
# exec uses cwd for an empty PATH, but shutil.which treats it as no path.
|
|
36
|
+
search_path = os.pathsep.join(os.get_exec_path(env)) or os.curdir
|
|
37
|
+
executable = shutil.which(command[0], path=search_path)
|
|
38
|
+
if executable is not None:
|
|
39
|
+
facts["executable"] = str(Path(executable).absolute())
|
|
40
|
+
except (OSError, ValueError, TypeError, IndexError) as error:
|
|
41
|
+
print(f"giwon: unavailable executable observation: {error}", file=sys.stderr)
|
|
42
|
+
return facts
|
giwon/discovery/git.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Capture Git commits and local changes for replay.
|
|
2
|
+
|
|
3
|
+
Valid repositories can store branch references in reftable and the staging area
|
|
4
|
+
in v4 or split indexes, which GitPython's object readers do not fully support.
|
|
5
|
+
Read commit IDs and submodule entries through its Git-command API so the installed
|
|
6
|
+
Git interprets those formats; users need not convert their repositories for capture.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def detect(cwd: Path) -> Path | None:
|
|
15
|
+
try:
|
|
16
|
+
import git
|
|
17
|
+
except ImportError:
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
# -C preserves literal $ in paths that GitPython's working_dir expands.
|
|
22
|
+
return Path(git.Git()(C=str(cwd)).rev_parse("--show-toplevel"))
|
|
23
|
+
except (git.GitCommandNotFound, git.GitCommandError):
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _patch(repo, commit, path, budget, context):
|
|
28
|
+
"""Write a repository patch and enforce its saved-byte budget.
|
|
29
|
+
|
|
30
|
+
Git's --output writes a complete patch directly to disk. Restricting temporary
|
|
31
|
+
disk usage would require bounded streaming, so the budget caps saved output
|
|
32
|
+
and is checked after writing; temporary disk usage can exceed it.
|
|
33
|
+
"""
|
|
34
|
+
try:
|
|
35
|
+
repo.git.diff(
|
|
36
|
+
"--binary",
|
|
37
|
+
"--no-ext-diff",
|
|
38
|
+
"--no-textconv",
|
|
39
|
+
"--no-color",
|
|
40
|
+
"--no-relative",
|
|
41
|
+
"--no-renames",
|
|
42
|
+
"--src-prefix=a/",
|
|
43
|
+
"--dst-prefix=b/",
|
|
44
|
+
"--ignore-submodules=dirty",
|
|
45
|
+
"--submodule=short",
|
|
46
|
+
commit,
|
|
47
|
+
"--",
|
|
48
|
+
output=str(path),
|
|
49
|
+
unified=context,
|
|
50
|
+
)
|
|
51
|
+
size = path.stat().st_size
|
|
52
|
+
if size > budget:
|
|
53
|
+
raise ValueError("Git patches exceed max_patch_bytes")
|
|
54
|
+
if not size:
|
|
55
|
+
path.unlink()
|
|
56
|
+
return size
|
|
57
|
+
except BaseException:
|
|
58
|
+
path.unlink(missing_ok=True)
|
|
59
|
+
raise
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _remotes(repo):
|
|
63
|
+
facts = []
|
|
64
|
+
for remote in repo.remotes:
|
|
65
|
+
push_urls = repo.git.remote("get-url", "--push", "--all", "--", remote.name)
|
|
66
|
+
fact = {
|
|
67
|
+
"name": remote.name,
|
|
68
|
+
"fetch_urls": list(remote.urls),
|
|
69
|
+
"push_urls": push_urls.splitlines(),
|
|
70
|
+
}
|
|
71
|
+
facts.append(fact)
|
|
72
|
+
return facts
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _untracked_files(repo):
|
|
76
|
+
untracked = repo.git.ls_files(
|
|
77
|
+
"--others", "--exclude-standard", "-z", stdout_as_string=False
|
|
78
|
+
)
|
|
79
|
+
return [os.fsdecode(name) for name in untracked.split(b"\0") if name]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _submodules(repo, path, stack, submodule_number):
|
|
83
|
+
"""Record submodule references and schedule initialized checkouts for capture.
|
|
84
|
+
|
|
85
|
+
A submodule checkout can differ from the commit in its parent's index, so
|
|
86
|
+
record that index reference separately from the checked-out commit to preserve
|
|
87
|
+
both the parent's recorded dependency and the source actually used.
|
|
88
|
+
"""
|
|
89
|
+
submodules = []
|
|
90
|
+
index = repo.git.ls_files("--stage", "-z", stdout_as_string=False)
|
|
91
|
+
for record in index.split(b"\0"):
|
|
92
|
+
if not record:
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
metadata, raw_name = record.split(b"\t", 1)
|
|
96
|
+
mode, reference, stage = metadata.split()
|
|
97
|
+
if mode != b"160000":
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
name = os.fsdecode(raw_name)
|
|
101
|
+
if stage != b"0":
|
|
102
|
+
raise ValueError(f"unmerged Git submodule: {name}")
|
|
103
|
+
|
|
104
|
+
child = {"path": name, "reference": reference.decode("ascii")}
|
|
105
|
+
submodules.append(child)
|
|
106
|
+
checkout = path / name
|
|
107
|
+
if os.path.exists(checkout / ".git"):
|
|
108
|
+
filename = f"git-submodule-{submodule_number}.patch"
|
|
109
|
+
submodule_number += 1
|
|
110
|
+
stack.append((checkout, child, filename))
|
|
111
|
+
|
|
112
|
+
return submodules, submodule_number
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def collect(
|
|
116
|
+
root: Path, directory: Path, max_patch_bytes: int, patch_context: int
|
|
117
|
+
) -> dict[str, Any]:
|
|
118
|
+
"""Capture a repository and its nested submodules under one patch budget.
|
|
119
|
+
|
|
120
|
+
Submodules may be staged without .gitmodules entries and can contain nested
|
|
121
|
+
submodules. Read current-index gitlinks through Git instead of repo.submodules,
|
|
122
|
+
and traverse initialized checkouts depth-first with a stack of (path, record,
|
|
123
|
+
patch filename), seeded with the root. Child records are attached to their
|
|
124
|
+
parent before being pushed, so processing a stack entry fills the same nested
|
|
125
|
+
record. Uninitialized children retain only path/reference; all captured
|
|
126
|
+
checkouts consume the same patch budget.
|
|
127
|
+
"""
|
|
128
|
+
import git
|
|
129
|
+
|
|
130
|
+
facts: dict[str, Any] = {"root": str(root)}
|
|
131
|
+
stack = [(root, facts, "git.patch")]
|
|
132
|
+
patches = []
|
|
133
|
+
remaining = max_patch_bytes
|
|
134
|
+
submod_idx = 0
|
|
135
|
+
try:
|
|
136
|
+
while stack:
|
|
137
|
+
path, entry, filename = stack.pop()
|
|
138
|
+
with git.Repo(str(path), expand_vars=False) as repo:
|
|
139
|
+
# GitPython's command wrapper otherwise expands literal $ in paths
|
|
140
|
+
repo.git.set_persistent_git_options(
|
|
141
|
+
C=repo.working_dir,
|
|
142
|
+
c="diff.autoRefreshIndex=false",
|
|
143
|
+
no_optional_locks=True,
|
|
144
|
+
)
|
|
145
|
+
entry["commit"] = repo.git.rev_parse("--verify", "HEAD^{commit}")
|
|
146
|
+
if entry is facts: # runs on first iteration
|
|
147
|
+
entry["remotes"] = _remotes(repo)
|
|
148
|
+
|
|
149
|
+
entry["untracked_files"] = _untracked_files(repo)
|
|
150
|
+
patch = directory / filename
|
|
151
|
+
size = _patch(repo, entry["commit"], patch, remaining, patch_context)
|
|
152
|
+
entry["patch"] = filename if size else None
|
|
153
|
+
if size:
|
|
154
|
+
patches.append(patch)
|
|
155
|
+
remaining -= size
|
|
156
|
+
|
|
157
|
+
submodules, submod_idx = _submodules(repo, path, stack, submod_idx)
|
|
158
|
+
if submodules:
|
|
159
|
+
entry["submodules"] = submodules
|
|
160
|
+
return facts
|
|
161
|
+
|
|
162
|
+
except BaseException:
|
|
163
|
+
for patch in patches:
|
|
164
|
+
patch.unlink(missing_ok=True)
|
|
165
|
+
raise
|