greenaihack 0.0.1__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.
greenaihack/local.py ADDED
@@ -0,0 +1,197 @@
1
+ """Portable local credentials and SSH identity handling."""
2
+
3
+ import configparser
4
+ import csv
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import os
9
+ import re
10
+ import subprocess
11
+ import tempfile
12
+ from pathlib import Path
13
+ from urllib.parse import urlsplit
14
+
15
+ from cryptography.hazmat.primitives import serialization
16
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
17
+ from platformdirs import user_data_path
18
+
19
+
20
+ class SetupError(Exception):
21
+ pass
22
+
23
+
24
+ def run(args, cwd=None):
25
+ try:
26
+ result = subprocess.run(
27
+ args,
28
+ cwd=cwd,
29
+ text=True,
30
+ encoding="utf-8",
31
+ errors="replace",
32
+ capture_output=True,
33
+ timeout=30,
34
+ check=False,
35
+ )
36
+ except (OSError, subprocess.TimeoutExpired):
37
+ raise SetupError(
38
+ f"Could not run {args[0]}; check that it is installed and available"
39
+ ) from None
40
+ if result.returncode:
41
+ # Do not include arbitrary process output; it can contain credentials.
42
+ raise SetupError(
43
+ f"{args[0]} {args[1]} failed; check the repository and local permissions"
44
+ )
45
+ return result.stdout.strip()
46
+
47
+
48
+ def repository():
49
+ return Path(run(["git", "rev-parse", "--show-toplevel"])).resolve()
50
+
51
+
52
+ def private_directory(path: Path):
53
+ if path.is_symlink():
54
+ raise SetupError("Credential directories must not be symlinks")
55
+ path.mkdir(parents=True, exist_ok=True, mode=0o700)
56
+ if os.name == "nt":
57
+ output = run(["whoami", "/user", "/fo", "csv", "/nh"])
58
+ sid = next(csv.reader(io.StringIO(output)))[1]
59
+ run(["icacls", str(path), "/inheritance:r", "/grant:r", f"*{sid}:(OI)(CI)F"])
60
+ else:
61
+ path.chmod(0o700)
62
+
63
+
64
+ def atomic_write(path: Path, content: str, private=False):
65
+ if path.is_symlink():
66
+ raise SetupError(f"Refusing to replace symlink: {path.name}")
67
+ fd, temporary = tempfile.mkstemp(dir=path.parent, prefix=".greenaihack-")
68
+ try:
69
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream:
70
+ stream.write(content)
71
+ if not private and path.exists():
72
+ os.chmod(temporary, path.stat().st_mode & 0o777)
73
+ os.replace(temporary, path)
74
+ finally:
75
+ if os.path.exists(temporary):
76
+ os.unlink(temporary)
77
+
78
+
79
+ def machine_directory(root: Path, api: str, team_id: str):
80
+ base = Path(
81
+ os.getenv(
82
+ "GREENAIHACK_HOME", str(user_data_path("greenaihack", appauthor=False))
83
+ )
84
+ )
85
+ base = base.expanduser().absolute()
86
+ if base.resolve().is_relative_to(root):
87
+ raise SetupError("GREENAIHACK_HOME must be outside the repository")
88
+ private_directory(base)
89
+ identifier = hashlib.sha256(f"{api}/{team_id}".encode()).hexdigest()[:24]
90
+ directory = base / identifier
91
+ private_directory(directory)
92
+ return directory
93
+
94
+
95
+ def identity(directory: Path):
96
+ private_path = directory / "id_ed25519"
97
+ if private_path.is_symlink():
98
+ raise SetupError("SSH keys must not be symlinks")
99
+ if not private_path.exists():
100
+ key = Ed25519PrivateKey.generate()
101
+ atomic_write(
102
+ private_path,
103
+ key.private_bytes(
104
+ serialization.Encoding.PEM,
105
+ serialization.PrivateFormat.OpenSSH,
106
+ serialization.NoEncryption(),
107
+ ).decode(),
108
+ private=True,
109
+ )
110
+ if os.name != "nt":
111
+ private_path.chmod(0o600)
112
+ key = serialization.load_ssh_private_key(private_path.read_bytes(), password=None)
113
+ if not isinstance(key, Ed25519PrivateKey):
114
+ raise SetupError("The machine key is not Ed25519")
115
+ public_key = (
116
+ key.public_key()
117
+ .public_bytes(
118
+ serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH
119
+ )
120
+ .decode()
121
+ )
122
+ return private_path, public_key
123
+
124
+
125
+ def ssh_remote(url, directory, private_path):
126
+ if url.startswith("ssh://"):
127
+ parsed = urlsplit(url)
128
+ host, port, user, path = (
129
+ parsed.hostname,
130
+ parsed.port or 22,
131
+ parsed.username,
132
+ parsed.path.lstrip("/"),
133
+ )
134
+ else:
135
+ match = re.fullmatch(r"([^@]+)@([^:]+):(.+)", url)
136
+ if not match:
137
+ raise SetupError("The backend returned an invalid GitLab SSH URL")
138
+ user, host, path = match.groups()
139
+ port = 22
140
+ if (
141
+ user != "git"
142
+ or not re.fullmatch(r"[A-Za-z0-9.-]+", host or "")
143
+ or not re.fullmatch(r"[\w./-]+", path)
144
+ ):
145
+ raise SetupError("The backend returned an invalid GitLab SSH URL")
146
+ alias = "greenaihack-" + directory.name
147
+ ssh_dir = Path.home() / ".ssh"
148
+ private_directory(ssh_dir)
149
+ config = ssh_dir / "config"
150
+ if config.is_symlink():
151
+ raise SetupError(
152
+ "SSH config is a symlink; configure the dedicated key manually"
153
+ )
154
+ existing = config.read_text(encoding="utf-8") if config.exists() else ""
155
+ start, end = f"# greenaihack {alias} begin", f"# greenaihack {alias} end"
156
+ key_path = private_path.as_posix()
157
+ if any(c in key_path for c in '\n\r"'):
158
+ raise SetupError("SSH identity path contains unsupported characters")
159
+ block = (
160
+ f"{start}\nHost {alias}\n HostName {host}\n User git\n Port {port}\n"
161
+ f' HostKeyAlias {host}\n IdentityFile "{key_path}"\n IdentitiesOnly yes\nHost *\n{end}\n'
162
+ )
163
+ # Put specific settings before a possible existing Host * stanza.
164
+ existing = re.sub(
165
+ re.escape(start) + r".*?" + re.escape(end) + r"\n?",
166
+ "",
167
+ existing,
168
+ flags=re.DOTALL,
169
+ ).lstrip("\n")
170
+ atomic_write(config, block + "\n" + existing, private=True)
171
+ return f"git@{alias}:{path}"
172
+
173
+
174
+ def save_credentials(directory: Path, api: str, result: dict):
175
+ atomic_write(
176
+ directory / "session.json",
177
+ json.dumps(
178
+ {
179
+ "api_url": api,
180
+ "team_id": result["team"]["id"],
181
+ "session_token": result["session_token"],
182
+ "expires_at": result["session_expires_at"],
183
+ },
184
+ indent=2,
185
+ )
186
+ + "\n",
187
+ private=True,
188
+ )
189
+ storage = result["storage"]
190
+ parser = configparser.RawConfigParser()
191
+ parser["default"] = {
192
+ "aws_access_key_id": storage["access_key_id"],
193
+ "aws_secret_access_key": storage["secret_access_key"],
194
+ }
195
+ stream = io.StringIO()
196
+ parser.write(stream)
197
+ atomic_write(directory / "storage-credentials", stream.getvalue(), private=True)
greenaihack/project.py ADDED
@@ -0,0 +1,331 @@
1
+ """Shared starter/configuration files and local Git/DVC wiring."""
2
+
3
+ import configparser
4
+ import contextlib
5
+ import io
6
+ import json
7
+ import subprocess
8
+ from pathlib import Path
9
+
10
+ from .local import SetupError, atomic_write, run, save_credentials, ssh_remote
11
+
12
+ CONFIG = "greenaihack.json"
13
+ REMOTE = 'remote "greenaihack"'
14
+
15
+
16
+ def load(root: Path):
17
+ path = root / CONFIG
18
+ if path.is_symlink():
19
+ raise SetupError(f"{CONFIG} must not be a symlink")
20
+ if not path.exists():
21
+ return None
22
+ try:
23
+ config = json.loads(path.read_text(encoding="utf-8"))
24
+ if config["schema_version"] != 1 or not all(
25
+ isinstance(config[k], str) and config[k]
26
+ for k in ("api_url", "event_id", "team_id", "team_name")
27
+ ):
28
+ raise ValueError()
29
+ # Configurations written before team_slug existed are backfilled on setup.
30
+ if "team_slug" in config and not (
31
+ isinstance(config["team_slug"], str) and config["team_slug"]
32
+ ):
33
+ raise ValueError()
34
+ return config
35
+ except (ValueError, KeyError, TypeError):
36
+ raise SetupError(
37
+ f"Invalid {CONFIG}; restore the team's shared configuration"
38
+ ) from None
39
+
40
+
41
+ def preflight(root: Path):
42
+ for name in (
43
+ CONFIG,
44
+ "pyproject.toml",
45
+ "my_eval.py",
46
+ "models",
47
+ "models/.gitkeep",
48
+ ".gitignore",
49
+ ".gitlab-ci.yml",
50
+ ".dvc",
51
+ ".dvc/config",
52
+ ".dvc/config.local",
53
+ ".dvc/.gitignore",
54
+ ".dvcignore",
55
+ ):
56
+ if (root / name).is_symlink():
57
+ raise SetupError(f"Refusing to configure a symlink: {name}")
58
+ tracked = run(["git", "ls-files", "--", ".dvc/config.local"], cwd=root)
59
+ if tracked:
60
+ raise SetupError("Remove .dvc/config.local from Git tracking before continuing")
61
+ existing = (
62
+ run(["git", "remote", "get-url", "greenaihack"], cwd=root)
63
+ if "greenaihack" in run(["git", "remote"], cwd=root).splitlines()
64
+ else None
65
+ )
66
+ if existing and not existing.startswith("git@greenaihack-"):
67
+ raise SetupError(
68
+ "A remote named greenaihack already exists; rename it before continuing"
69
+ )
70
+
71
+
72
+ def create(root, relative, content):
73
+ path = root / relative
74
+ path.parent.mkdir(parents=True, exist_ok=True)
75
+ try:
76
+ with path.open("x", encoding="utf-8", newline="\n") as stream:
77
+ stream.write(content)
78
+ except FileExistsError:
79
+ return False
80
+ return True
81
+
82
+
83
+ GITIGNORE = [
84
+ "/.dvc/config.local",
85
+ "/.dvc/cache/",
86
+ "/.dvc/tmp/",
87
+ "/.venv/",
88
+ "__pycache__/",
89
+ ]
90
+ DVC_GITIGNORE = ["/config.local", "/cache", "/tmp"]
91
+
92
+
93
+ def missing_lines(path, lines):
94
+ existing = path.read_text(encoding="utf-8") if path.exists() else ""
95
+ return [line for line in lines if line not in existing.splitlines()]
96
+
97
+
98
+ def append_lines(path, lines):
99
+ missing = missing_lines(path, lines)
100
+ if missing:
101
+ existing = path.read_text(encoding="utf-8") if path.exists() else ""
102
+ atomic_write(
103
+ path,
104
+ existing
105
+ + ("\n" if existing and not existing.endswith("\n") else "")
106
+ + "\n".join(missing)
107
+ + "\n",
108
+ )
109
+ return bool(missing)
110
+
111
+
112
+ def dvc_config(path):
113
+ parser = configparser.RawConfigParser()
114
+ if path.exists():
115
+ parser.read(path, encoding="utf-8")
116
+ # DVC writes quoted section names; also accept unquoted config files.
117
+ quoted = "'" + REMOTE + "'"
118
+ if parser.has_section(quoted):
119
+ if parser.has_section(REMOTE):
120
+ raise SetupError("Duplicate greenaihack DVC remote")
121
+ parser[REMOTE] = dict(parser[quoted])
122
+ parser.remove_section(quoted)
123
+ return parser
124
+
125
+
126
+ def write_ini(path, parser):
127
+ stream = io.StringIO()
128
+ parser.write(stream)
129
+ atomic_write(path, stream.getvalue())
130
+
131
+
132
+ STARTER = {
133
+ "pyproject.toml": (
134
+ '[project]\nname = "greenaihack-team"\nversion = "0.1.0"\nrequires-python = ">=3.12"\ndependencies = []\n\n[tool.uv]\npackage = false\n'
135
+ ),
136
+ "my_eval.py": (
137
+ '"""Replace this public-sample inference fixture with your model."""\nimport json\nfrom pathlib import Path\n\ndef main():\n Path("predictions.json").write_text(json.dumps({"predictions": [0, 1, 0]}))\n\n\nif __name__ == "__main__":\n main()\n'
138
+ ),
139
+ "models/.gitkeep": "",
140
+ ".gitlab-ci.yml": (
141
+ "# The submission project uses organizer-controlled CI configuration.\n# Evaluation is triggered through the API; pushes do not schedule jobs.\nworkflow:\n rules:\n - when: never\n"
142
+ ),
143
+ }
144
+
145
+
146
+ def configure(root, api, result, directory, private_path, register):
147
+ """Write shared and local configuration; return the shared files written."""
148
+ written = []
149
+ team, storage = result["team"], result["storage"]
150
+ current = load(root)
151
+ if current and (current["api_url"] != api or current["team_id"] != team["id"]):
152
+ raise SetupError(
153
+ "This repository is already configured for another team or API"
154
+ )
155
+ preflight(root)
156
+ dvc_dir = root / ".dvc"
157
+ dvc_dir.mkdir(exist_ok=True)
158
+ shared = dvc_config(dvc_dir / "config")
159
+ expected = {
160
+ "url": storage["remote_url"],
161
+ "endpointurl": storage["endpoint_url"],
162
+ "region": storage["region"],
163
+ }
164
+ if shared.has_section(REMOTE):
165
+ if any(shared[REMOTE].get(key) != value for key, value in expected.items()):
166
+ raise SetupError(
167
+ "The existing greenaihack DVC remote conflicts with team storage settings"
168
+ )
169
+ shared_addition = ""
170
+ else:
171
+ shared_addition = (
172
+ "\n["
173
+ + REMOTE
174
+ + "]\n"
175
+ + "".join(f" {key} = {value}\n" for key, value in expected.items())
176
+ )
177
+ if not shared.has_section("core"):
178
+ shared_addition += "\n[core]\n remote = greenaihack\n"
179
+ local = dvc_config(dvc_dir / "config.local")
180
+ if not local.has_section(REMOTE):
181
+ local.add_section(REMOTE)
182
+ local[REMOTE].update(
183
+ credentialpath=(directory / "storage-credentials").as_posix(), profile="default"
184
+ )
185
+ save_credentials(directory, api, result)
186
+ remote = ssh_remote(result["gitlab"]["ssh_url"], directory, private_path)
187
+ if append_lines(root / ".gitignore", GITIGNORE):
188
+ written.append(".gitignore")
189
+ if append_lines(dvc_dir / ".gitignore", DVC_GITIGNORE):
190
+ written.append(".dvc/.gitignore")
191
+ if shared_addition:
192
+ path = dvc_dir / "config"
193
+ existing = path.read_text(encoding="utf-8") if path.exists() else ""
194
+ atomic_write(path, existing + shared_addition)
195
+ written.append(".dvc/config")
196
+ write_ini(dvc_dir / "config.local", local)
197
+ if create(root, ".dvcignore", "# Add files DVC should ignore here.\n"):
198
+ written.append(".dvcignore")
199
+ if "greenaihack" in run(["git", "remote"], cwd=root).splitlines():
200
+ run(["git", "remote", "set-url", "greenaihack", remote], cwd=root)
201
+ else:
202
+ run(["git", "remote", "add", "greenaihack", remote], cwd=root)
203
+ # Never make the submission remote the default push target.
204
+ config = current or {
205
+ "schema_version": 1,
206
+ "api_url": api,
207
+ "event_id": team["event_id"],
208
+ "team_id": team["id"],
209
+ "team_name": team["name"],
210
+ "team_slug": team["slug"],
211
+ "submission_remote": "greenaihack",
212
+ "dvc_remote": "greenaihack",
213
+ "defaults": {"script": "my_eval.py", "models": []},
214
+ }
215
+ if not current and create(root, CONFIG, json.dumps(config, indent=2) + "\n"):
216
+ written.append(CONFIG)
217
+ elif current and current.get("team_slug") != team["slug"]:
218
+ config = {**current, "team_slug": team["slug"]}
219
+ atomic_write(root / CONFIG, json.dumps(config, indent=2) + "\n")
220
+ written.append(CONFIG)
221
+ if register:
222
+ written += [path for path, text in STARTER.items() if create(root, path, text)]
223
+ return written
224
+
225
+
226
+ def lock(root):
227
+ """Create uv.lock, which submissions require; return whether it exists."""
228
+ lockfile = root / "uv.lock"
229
+ if not lockfile.exists() and (root / "pyproject.toml").exists():
230
+ with contextlib.suppress(OSError, subprocess.TimeoutExpired):
231
+ subprocess.run(
232
+ ["uv", "lock", "--quiet"],
233
+ cwd=root,
234
+ capture_output=True,
235
+ timeout=300,
236
+ check=False,
237
+ )
238
+ return lockfile.exists()
239
+
240
+
241
+ def planned_files(root, register):
242
+ """Shared files configure() would create or update; changes nothing."""
243
+ current = load(root)
244
+ planned = [] if current and "team_slug" in current else [CONFIG]
245
+ if missing_lines(root / ".gitignore", GITIGNORE):
246
+ planned.append(".gitignore")
247
+ if missing_lines(root / ".dvc/.gitignore", DVC_GITIGNORE):
248
+ planned.append(".dvc/.gitignore")
249
+ if not dvc_config(root / ".dvc/config").has_section(REMOTE):
250
+ planned.append(".dvc/config")
251
+ if not (root / ".dvcignore").exists():
252
+ planned.append(".dvcignore")
253
+ if register:
254
+ planned += [path for path in STARTER if not (root / path).exists()]
255
+ # register runs uv lock; pyproject.toml exists or is created above.
256
+ if not (root / "uv.lock").exists():
257
+ planned.append("uv.lock")
258
+ return planned
259
+
260
+
261
+ def setup_changes(root, written):
262
+ """Setup files to commit: written by this run, or created but never committed."""
263
+ shared = (CONFIG, "uv.lock", *STARTER)
264
+ candidates = sorted(
265
+ set(written) | {path for path in shared if (root / path).exists()}
266
+ )
267
+ # Porcelain lists only changed, non-ignored paths; these names need no quoting.
268
+ status = run(
269
+ ["git", "status", "--porcelain", "--untracked-files=all", "--", *candidates],
270
+ cwd=root,
271
+ )
272
+ changed = {line.split(maxsplit=1)[-1] for line in status.splitlines()}
273
+ tracked = set(run(["git", "ls-files", "--", *candidates], cwd=root).splitlines())
274
+ # Never sweep up a student's own edits to files that were already tracked.
275
+ return [
276
+ p for p in candidates if p in changed and (p in written or p not in tracked)
277
+ ]
278
+
279
+
280
+ def query(root, *args):
281
+ """Run a Git query whose failure only means the value is unset."""
282
+ try:
283
+ return run(["git", *args], cwd=root) or None
284
+ except SetupError:
285
+ return None
286
+
287
+
288
+ def push_target(root):
289
+ """Return (remote, branch) to share setup files on, or None.
290
+
291
+ Pushes go to the same-named branch, like Git's default push.default=simple,
292
+ so a feature branch tracking origin/main never pushes onto main.
293
+ """
294
+ branch = query(root, "symbolic-ref", "--quiet", "--short", "HEAD")
295
+ if not branch:
296
+ return None
297
+ remote = query(root, "config", f"branch.{branch}.remote")
298
+ if not remote:
299
+ others = [
300
+ r
301
+ for r in run(["git", "remote"], cwd=root).splitlines()
302
+ if r != "greenaihack"
303
+ ]
304
+ if "origin" in others:
305
+ remote = "origin"
306
+ elif len(others) == 1:
307
+ remote = others[0]
308
+ # Never publish collaboration work to the submission remote.
309
+ if not remote or remote == "greenaihack":
310
+ return None
311
+ return remote, branch
312
+
313
+
314
+ def commit(root, paths, message):
315
+ run(["git", "add", "--", *paths], cwd=root)
316
+ # Commit only these paths, leaving anything else the student staged alone.
317
+ return attached(root, "commit", "--quiet", "-m", message, "--", *paths)
318
+
319
+
320
+ def push(root, remote, branch):
321
+ has_upstream = query(root, "config", f"branch.{branch}.merge")
322
+ tracking = [] if has_upstream else ["--set-upstream"]
323
+ return attached(root, "push", *tracking, remote, branch)
324
+
325
+
326
+ def attached(root, *args):
327
+ """Run Git on the terminal so hooks, signing and credential prompts work."""
328
+ try:
329
+ return subprocess.run(["git", *args], cwd=root, check=False).returncode == 0
330
+ except OSError:
331
+ return False