@giamme/forge 0.20.0 → 0.22.0
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.
- package/CHANGELOG.md +36 -0
- package/README.md +13 -3
- package/VERSION +1 -1
- package/bin/forge.js +104 -0
- package/docs/README.md +1 -0
- package/docs/development.md +1 -1
- package/docs/install.md +91 -2
- package/docs/reviews.md +6 -4
- package/docs/troubleshooting.md +1 -1
- package/forge +4 -0
- package/forge.cmd +56 -0
- package/package.json +5 -3
- package/scripts/forge-artifact.sh +5 -1
- package/scripts/forge-config.py +10 -9
- package/scripts/forge-control.py +61 -38
- package/scripts/forge-dispatch.sh +108 -31
- package/scripts/forge-group.py +2 -1
- package/scripts/forge-guard.py +207 -38
- package/scripts/forge-handoff.py +14 -17
- package/scripts/forge-install.sh +82 -9
- package/scripts/forge-issues.py +5 -2
- package/scripts/forge-lib-env.sh +158 -0
- package/scripts/forge-lib-group.sh +5 -5
- package/scripts/forge-lib-plans.sh +8 -3
- package/scripts/forge-lib-task.sh +40 -15
- package/scripts/forge-memory.sh +2 -0
- package/scripts/forge-metrics.sh +6 -1
- package/scripts/forge-parallel.sh +174 -53
- package/scripts/forge-planner.py +28 -2
- package/scripts/forge-pre-review.py +11 -4
- package/scripts/forge-ripwire.py +68 -22
- package/scripts/forge-route.py +10 -3
- package/scripts/forge-runs-compact.py +3 -2
- package/scripts/forge-runs-rm.py +14 -14
- package/scripts/forge-runtime.py +38 -21
- package/scripts/forge-schedule.py +90 -56
- package/scripts/forge-shadow.py +16 -9
- package/scripts/forge-solo.sh +6 -2
- package/scripts/forge-summarize.py +7 -3
- package/scripts/forge-sweep.py +8 -3
- package/scripts/forge-ui.py +8 -13
- package/scripts/forge-update.sh +6 -1
- package/scripts/forge-verify.py +30 -23
- package/scripts/forge-win.sh +156 -0
- package/scripts/forge_brief/__init__.py +7 -2
- package/scripts/forge_brief/proposals.py +13 -3
- package/scripts/forge_decide/budget.py +18 -8
- package/scripts/forge_decide/replay.py +15 -5
- package/scripts/forge_findings/apply.py +2 -1
- package/scripts/forge_findings/store.py +16 -4
- package/scripts/forge_findings/triage.py +6 -15
- package/scripts/forge_flock.py +102 -0
- package/scripts/forge_fractal/__init__.py +7 -3
- package/scripts/forge_fractal/cli.py +7 -2
- package/scripts/forge_fractal/execution.py +14 -14
- package/scripts/forge_fractal/invocation.py +3 -2
- package/scripts/forge_fractal/pipeline.py +2 -1
- package/scripts/forge_fractal/selection.py +2 -1
- package/scripts/forge_identity.py +2 -1
- package/scripts/forge_locations.py +14 -4
- package/scripts/forge_posix.py +125 -0
- package/scripts/forge_proc.py +507 -0
- package/scripts/forge_registry.py +17 -8
- package/scripts/forge_retro/__init__.py +8 -2
- package/scripts/forge_retro/issues.py +2 -1
- package/scripts/forge_side/__init__.py +32 -14
- package/scripts/forge_storage.py +11 -1
- package/ui/forge_ui/control.py +42 -14
- package/ui/forge_ui/reader.py +24 -18
- package/ui/forge_ui/server.py +10 -1
- package/ui/forge_ui/static/scene3d.js +23 -2
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Cross-platform advisory file locking with ``fcntl.flock`` semantics.
|
|
2
|
+
|
|
3
|
+
Uses ``fcntl.flock`` on POSIX and ``msvcrt.locking`` on Windows so callers in
|
|
4
|
+
``scripts/``, ``ui/forge_ui/``, and ``tests/`` share one locking interface.
|
|
5
|
+
On Windows, ``LOCK_SH`` is promoted to an exclusive lock and locks byte
|
|
6
|
+
``_LOCK_OFFSET`` (1 GiB) rather than byte 0 so non-locking readers of normal
|
|
7
|
+
file data are not blocked by mandatory Win32 byte-range locks; ``LOCK_UN`` on
|
|
8
|
+
an unlocked descriptor is a no-op matching POSIX ``flock``.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import errno
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
try:
|
|
18
|
+
import fcntl as _fcntl
|
|
19
|
+
except ImportError:
|
|
20
|
+
_fcntl = None
|
|
21
|
+
|
|
22
|
+
if _fcntl is not None:
|
|
23
|
+
LOCK_SH = _fcntl.LOCK_SH
|
|
24
|
+
LOCK_EX = _fcntl.LOCK_EX
|
|
25
|
+
LOCK_NB = _fcntl.LOCK_NB
|
|
26
|
+
LOCK_UN = _fcntl.LOCK_UN
|
|
27
|
+
else:
|
|
28
|
+
import msvcrt as _msvcrt
|
|
29
|
+
|
|
30
|
+
LOCK_SH = 1
|
|
31
|
+
LOCK_EX = 2
|
|
32
|
+
LOCK_NB = 4
|
|
33
|
+
LOCK_UN = 8
|
|
34
|
+
|
|
35
|
+
_LOCK_OFFSET = 0x40000000 # 1 GiB sentinel byte; msvcrt does not extend file size
|
|
36
|
+
|
|
37
|
+
# Cygwin (Windows MSYS2 mode): flock sometimes fails with EFAULT when threads of one process lock
|
|
38
|
+
# the same file at the same moment, and the same call succeeds when repeated.
|
|
39
|
+
_CYGWIN = sys.platform == 'cygwin'
|
|
40
|
+
_CYGWIN_EFAULT_TRIES = 100 # 10 ms apart: about a second
|
|
41
|
+
|
|
42
|
+
_BUSY_ERRNOS = frozenset(
|
|
43
|
+
getattr(errno, name)
|
|
44
|
+
for name in ('EACCES', 'EAGAIN', 'EWOULDBLOCK', 'EDEADLK')
|
|
45
|
+
if hasattr(errno, name)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _fileno(fd_or_file) -> int:
|
|
50
|
+
return fd_or_file if isinstance(fd_or_file, int) else fd_or_file.fileno()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _msvcrt_lock_sentinel(fd: int, mode: int) -> None:
|
|
54
|
+
"""Lock or unlock ``_LOCK_OFFSET`` on ``fd`` while preserving seek offset."""
|
|
55
|
+
pos = os.lseek(fd, 0, os.SEEK_CUR)
|
|
56
|
+
try:
|
|
57
|
+
os.lseek(fd, _LOCK_OFFSET, os.SEEK_SET)
|
|
58
|
+
_msvcrt.locking(fd, mode, 1)
|
|
59
|
+
finally:
|
|
60
|
+
os.lseek(fd, pos, os.SEEK_SET)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def flock(fd_or_file, operation: int) -> None:
|
|
64
|
+
"""Acquire or release an advisory lock matching ``fcntl.flock`` semantics."""
|
|
65
|
+
if _fcntl is not None:
|
|
66
|
+
if not _CYGWIN:
|
|
67
|
+
_fcntl.flock(fd_or_file, operation)
|
|
68
|
+
return
|
|
69
|
+
for attempt in range(_CYGWIN_EFAULT_TRIES):
|
|
70
|
+
try:
|
|
71
|
+
_fcntl.flock(fd_or_file, operation)
|
|
72
|
+
return
|
|
73
|
+
except OSError as exc:
|
|
74
|
+
if exc.errno != errno.EFAULT or attempt == _CYGWIN_EFAULT_TRIES - 1:
|
|
75
|
+
raise
|
|
76
|
+
time.sleep(0.01)
|
|
77
|
+
|
|
78
|
+
fd = _fileno(fd_or_file)
|
|
79
|
+
nonblocking = bool(operation & LOCK_NB)
|
|
80
|
+
base_op = operation & ~LOCK_NB
|
|
81
|
+
|
|
82
|
+
if base_op == LOCK_UN:
|
|
83
|
+
try:
|
|
84
|
+
_msvcrt_lock_sentinel(fd, _msvcrt.LK_UNLCK)
|
|
85
|
+
except OSError as exc:
|
|
86
|
+
if exc.errno not in (errno.EACCES, errno.EPERM, errno.EINVAL):
|
|
87
|
+
raise
|
|
88
|
+
return
|
|
89
|
+
|
|
90
|
+
if base_op not in (LOCK_EX, LOCK_SH):
|
|
91
|
+
raise ValueError(f'unsupported flock operation: {operation!r}')
|
|
92
|
+
|
|
93
|
+
while True:
|
|
94
|
+
try:
|
|
95
|
+
_msvcrt_lock_sentinel(fd, _msvcrt.LK_NBLCK)
|
|
96
|
+
return
|
|
97
|
+
except OSError as exc:
|
|
98
|
+
if exc.errno not in _BUSY_ERRNOS:
|
|
99
|
+
raise
|
|
100
|
+
if nonblocking:
|
|
101
|
+
raise BlockingIOError(errno.EAGAIN, exc.strerror or 'Resource temporarily unavailable') from exc
|
|
102
|
+
time.sleep(0.05)
|
|
@@ -2,15 +2,19 @@
|
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
4
|
import contextlib
|
|
5
|
-
import fcntl
|
|
6
5
|
import importlib.util
|
|
7
6
|
import json
|
|
8
7
|
import os
|
|
9
8
|
from pathlib import Path
|
|
10
9
|
import re
|
|
11
10
|
import subprocess
|
|
11
|
+
import sys
|
|
12
12
|
|
|
13
13
|
SCRIPTS = Path(__file__).resolve().parents[1]
|
|
14
|
+
if str(SCRIPTS) not in sys.path:
|
|
15
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
16
|
+
import forge_flock as fcntl # noqa: E402
|
|
17
|
+
import forge_proc # noqa: E402
|
|
14
18
|
REVISION = '18793200c0d7e8cdb2db369ea3abe5647a1e15e4'
|
|
15
19
|
VERSION = '1.2.0'
|
|
16
20
|
ARCHIVE_SHA256 = '3f7714ee0baec05af8d856db2b00d63398026fae2fcf50edbee542671126072c'
|
|
@@ -80,5 +84,5 @@ def command(argv: list, *, cwd: Path | None = None, timeout: float = 120, input:
|
|
|
80
84
|
|
|
81
85
|
|
|
82
86
|
def artifact(verb: str, *args: object) -> str:
|
|
83
|
-
return command(
|
|
84
|
-
|
|
87
|
+
return command(forge_proc.bash_cmd('-c', 'source "$1"; shift; "$@"', 'forge',
|
|
88
|
+
SCRIPTS / 'forge-artifact.sh', verb, *args)).decode().strip()
|
|
@@ -142,11 +142,16 @@ def internal(argv: list[str]) -> int:
|
|
|
142
142
|
remember(managed_run(Path(os.environ['FORGE_FRACTAL_RUN']).name), argv[1:])
|
|
143
143
|
return 0
|
|
144
144
|
if argv[0] == '_lock':
|
|
145
|
-
|
|
145
|
+
_scripts = str(Path(__file__).resolve().parents[1])
|
|
146
|
+
if _scripts not in sys.path:
|
|
147
|
+
sys.path.insert(0, _scripts)
|
|
148
|
+
import forge_flock as fcntl
|
|
149
|
+
import forge_proc
|
|
146
150
|
handle = (Path(argv[1]) / 'pipeline.lock').open('a')
|
|
147
151
|
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
148
152
|
os.set_inheritable(handle.fileno(), True)
|
|
149
|
-
|
|
153
|
+
forge_proc.exec_or_exit(forge_proc.bash_cmd(*argv[2:]), env=dict(os.environ, FORGE_SOLO_LOCK=argv[1]),
|
|
154
|
+
inherit_fds=True)
|
|
150
155
|
raise ValueError('Unknown internal command')
|
|
151
156
|
|
|
152
157
|
|
|
@@ -22,6 +22,7 @@ import time
|
|
|
22
22
|
import uuid
|
|
23
23
|
|
|
24
24
|
from . import SCRIPTS, artifact, command, identifier, lock, managed_run, read_json, runtime_python, write_json
|
|
25
|
+
import forge_proc
|
|
25
26
|
|
|
26
27
|
PROTOCOL = '''
|
|
27
28
|
Forge owns coordination and independent QA. Implement and run requested checks.
|
|
@@ -64,17 +65,17 @@ def terminate(process: subprocess.Popen) -> None:
|
|
|
64
65
|
# Every managed invocation is its own session; never signal an arbitrary PID.
|
|
65
66
|
if process.poll() is not None:
|
|
66
67
|
return
|
|
67
|
-
|
|
68
|
-
os.killpg(process.pid, signal.SIGTERM)
|
|
68
|
+
forge_proc.kill_tree(process.pid, force=False)
|
|
69
69
|
try:
|
|
70
70
|
process.wait(timeout=2)
|
|
71
71
|
except subprocess.TimeoutExpired:
|
|
72
|
-
|
|
73
|
-
os.killpg(process.pid, signal.SIGKILL)
|
|
72
|
+
forge_proc.kill_tree(process.pid, force=True)
|
|
74
73
|
process.wait(timeout=2)
|
|
75
74
|
|
|
76
75
|
|
|
77
76
|
def process_identity(pid: int) -> str:
|
|
77
|
+
if forge_proc.IS_WINDOWS:
|
|
78
|
+
return forge_proc.process_start_time(pid) or ''
|
|
78
79
|
return subprocess.run(['ps', '-p', str(pid), '-o', 'lstart=,comm='], capture_output=True, text=True).stdout.strip()
|
|
79
80
|
|
|
80
81
|
|
|
@@ -83,8 +84,7 @@ def reap_recorded(task: Path) -> None:
|
|
|
83
84
|
recorded = read_json(path)
|
|
84
85
|
pid = recorded['pid']
|
|
85
86
|
if recorded['identity'] and process_identity(pid) == recorded['identity']:
|
|
86
|
-
|
|
87
|
-
os.killpg(pid, signal.SIGKILL)
|
|
87
|
+
forge_proc.kill_tree(pid, force=True)
|
|
88
88
|
|
|
89
89
|
|
|
90
90
|
@contextlib.contextmanager
|
|
@@ -111,9 +111,9 @@ def bridge(step: Path, prompt: Path, model: str) -> int:
|
|
|
111
111
|
role = config.get('role', 'dwarf')
|
|
112
112
|
if role not in ('dwarf', 'planner'):
|
|
113
113
|
raise ValueError('Unsupported Fractal bridge role')
|
|
114
|
-
argv =
|
|
115
|
-
|
|
116
|
-
|
|
114
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', role, model,
|
|
115
|
+
'--repo', config['workspace'], '--run-dir', str(step), '--prompt-file', str(prompt),
|
|
116
|
+
'--timeout', str(max(1, math.ceil(config['remaining']))), '--output', 'summary')
|
|
117
117
|
if config['yolo'] and role == 'dwarf':
|
|
118
118
|
argv.append('--yolo')
|
|
119
119
|
# Stay in the bridge session so its entire descendant group is reapable.
|
|
@@ -460,7 +460,7 @@ def supervise(run: Path, task: Path) -> int:
|
|
|
460
460
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
461
461
|
elapsed = read_json(task / 'state.json').get('elapsed', 0)
|
|
462
462
|
process = subprocess.Popen([str(runtime_python()), str(SCRIPTS / 'forge-fractal.py'),
|
|
463
|
-
'_worker', run.name, task.name],
|
|
463
|
+
'_worker', run.name, task.name], **forge_proc.popen_group_kwargs())
|
|
464
464
|
previous = time.monotonic()
|
|
465
465
|
try:
|
|
466
466
|
while process.poll() is None:
|
|
@@ -575,7 +575,7 @@ def dispatch(argv: list[str]) -> int:
|
|
|
575
575
|
|
|
576
576
|
def limited_dispatch(run: Path, argv: list[str]) -> int:
|
|
577
577
|
if argv[0] == 'doctor':
|
|
578
|
-
return subprocess.call(
|
|
578
|
+
return subprocess.call(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv))
|
|
579
579
|
limit = read_json(run / 'run.json')['limits']['deadline']
|
|
580
580
|
output = Path(argv[argv.index('--run-dir') + 1])
|
|
581
581
|
review = Path(argv[argv.index('--repo') + 1])
|
|
@@ -632,13 +632,13 @@ def qa_dispatch(run: Path, task: Path, argv: list[str], limit: int) -> int:
|
|
|
632
632
|
if record.exists():
|
|
633
633
|
old = read_json(record)
|
|
634
634
|
if old['identity'] and process_identity(old['pid']) == old['identity']:
|
|
635
|
-
|
|
636
|
-
os.killpg(old['pid'], signal.SIGKILL)
|
|
635
|
+
forge_proc.kill_tree(old['pid'], force=True)
|
|
637
636
|
while True:
|
|
638
637
|
try:
|
|
639
638
|
with slot(run, check):
|
|
640
639
|
check()
|
|
641
|
-
process = subprocess.Popen(
|
|
640
|
+
process = subprocess.Popen(forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh', *argv),
|
|
641
|
+
**forge_proc.popen_group_kwargs())
|
|
642
642
|
write_json(record, dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
643
643
|
try:
|
|
644
644
|
while process.poll() is None:
|
|
@@ -6,7 +6,8 @@ import threading
|
|
|
6
6
|
import time
|
|
7
7
|
import uuid
|
|
8
8
|
|
|
9
|
-
from . import read_json, write_json
|
|
9
|
+
from . import SCRIPTS, read_json, write_json
|
|
10
|
+
import forge_proc
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def _dataset_step(task, node: dict, directory: Path, **values) -> None:
|
|
@@ -54,7 +55,7 @@ def run_step(tree, node: dict, workspace: Path, prompt: str, *, phase: str = 'im
|
|
|
54
55
|
cost = None
|
|
55
56
|
try:
|
|
56
57
|
with output.open('w') as stream:
|
|
57
|
-
process = agent.spawn(invocation,
|
|
58
|
+
process = agent.spawn(invocation, **forge_proc.popen_group_kwargs())
|
|
58
59
|
write_json(directory / 'process.json', dict(pid=process.pid, identity=process_identity(process.pid)))
|
|
59
60
|
def drain():
|
|
60
61
|
for line in process.stdout:
|
|
@@ -8,13 +8,14 @@ import subprocess
|
|
|
8
8
|
import time
|
|
9
9
|
|
|
10
10
|
from . import artifact, lock, read_json, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def remember(run: Path, argv: list[str]) -> None:
|
|
14
15
|
with lock(run / 'pipeline-record.lock'):
|
|
15
16
|
config = read_json(run / 'run.json')
|
|
16
17
|
if 'pipeline_argv' not in config:
|
|
17
|
-
config.update(pipeline_argv=
|
|
18
|
+
config.update(pipeline_argv=forge_proc.bash_cmd(*argv), pipeline_cwd=str(Path.cwd()))
|
|
18
19
|
write_json(run / 'run.json', config)
|
|
19
20
|
|
|
20
21
|
|
|
@@ -8,6 +8,7 @@ from pathlib import Path
|
|
|
8
8
|
import sys
|
|
9
9
|
|
|
10
10
|
from . import DEFAULTS, SCRIPTS, command, managed_run, read_json, state_root, write_json
|
|
11
|
+
import forge_proc
|
|
11
12
|
from .install import doctor, install
|
|
12
13
|
|
|
13
14
|
|
|
@@ -17,7 +18,7 @@ def resolve(spec: str, role: str, yolo: bool = False, dry: bool = False) -> dict
|
|
|
17
18
|
root = Path(tmp)
|
|
18
19
|
prompt = root / 'input'
|
|
19
20
|
prompt.write_text('Offline resolution')
|
|
20
|
-
argv =
|
|
21
|
+
argv = forge_proc.bash_cmd(SCRIPTS / 'forge-dispatch.sh')
|
|
21
22
|
if dry:
|
|
22
23
|
argv += [role, spec, '--run-dir', root, '--prompt-file', prompt, '--dry-run']
|
|
23
24
|
else:
|
|
@@ -20,6 +20,7 @@ import stat
|
|
|
20
20
|
import subprocess
|
|
21
21
|
|
|
22
22
|
import forge_locations
|
|
23
|
+
import forge_posix
|
|
23
24
|
import forge_registry
|
|
24
25
|
|
|
25
26
|
# A file in <run>/tasks/<id>/ sits three directories under the run dir.
|
|
@@ -254,7 +255,7 @@ def _first_line(path: str) -> str | None:
|
|
|
254
255
|
def _read_bytes(path, limit: int) -> bytes | None:
|
|
255
256
|
"""The start of a regular file. A FIFO, a directory or a missing path is unknown, and never blocks."""
|
|
256
257
|
try:
|
|
257
|
-
fd = os.open(os.fspath(path), os.O_RDONLY |
|
|
258
|
+
fd = os.open(os.fspath(path), os.O_RDONLY | forge_posix.O_NONBLOCK)
|
|
258
259
|
except OSError:
|
|
259
260
|
return None
|
|
260
261
|
try:
|
|
@@ -34,7 +34,6 @@ from __future__ import annotations
|
|
|
34
34
|
|
|
35
35
|
import contextlib
|
|
36
36
|
import errno
|
|
37
|
-
import fcntl
|
|
38
37
|
import json
|
|
39
38
|
import os
|
|
40
39
|
from pathlib import Path
|
|
@@ -42,6 +41,12 @@ import subprocess
|
|
|
42
41
|
import sys
|
|
43
42
|
import time
|
|
44
43
|
|
|
44
|
+
_SCRIPTS = str(Path(__file__).resolve().parent)
|
|
45
|
+
if _SCRIPTS not in sys.path:
|
|
46
|
+
sys.path.insert(0, _SCRIPTS)
|
|
47
|
+
import forge_flock as fcntl # noqa: E402
|
|
48
|
+
import forge_posix # noqa: E402
|
|
49
|
+
|
|
45
50
|
VERSION = 1
|
|
46
51
|
LOCK_WAIT_S = 0.5
|
|
47
52
|
READ_MAX = 64 << 20
|
|
@@ -115,7 +120,8 @@ def _lock(wait_s):
|
|
|
115
120
|
"""The file's lock, tried for `wait_s`; yields whether it is held. Never raises."""
|
|
116
121
|
fd = None
|
|
117
122
|
try:
|
|
118
|
-
fd =
|
|
123
|
+
fd = forge_posix.open_nofollow(config_dir() / 'locations.lock',
|
|
124
|
+
os.O_RDWR | os.O_CREAT, 0o644)
|
|
119
125
|
deadline = time.monotonic() + wait_s
|
|
120
126
|
while True:
|
|
121
127
|
try:
|
|
@@ -141,7 +147,11 @@ def append(records: list[dict]) -> bool:
|
|
|
141
147
|
config_dir().mkdir(parents=True, exist_ok=True)
|
|
142
148
|
data = ''.join(json.dumps(dict(r, v=VERSION), sort_keys=True, separators=(',', ':')) + '\n' for r in records).encode()
|
|
143
149
|
with _lock(LOCK_WAIT_S):
|
|
144
|
-
fd =
|
|
150
|
+
fd = forge_posix.open_nofollow(
|
|
151
|
+
file_path(),
|
|
152
|
+
os.O_WRONLY | os.O_APPEND | os.O_CREAT | forge_posix.O_NONBLOCK | forge_posix.O_NOFOLLOW,
|
|
153
|
+
0o644,
|
|
154
|
+
)
|
|
145
155
|
try:
|
|
146
156
|
if not os.path.isfile(file_path()):
|
|
147
157
|
return False
|
|
@@ -204,7 +214,7 @@ def gone(kind, path, by='forge') -> bool:
|
|
|
204
214
|
|
|
205
215
|
def _first_line(path) -> str | None:
|
|
206
216
|
try:
|
|
207
|
-
fd = os.open(path, os.O_RDONLY |
|
|
217
|
+
fd = os.open(path, os.O_RDONLY | forge_posix.O_NONBLOCK)
|
|
208
218
|
with os.fdopen(fd, 'rb') as stream:
|
|
209
219
|
if not os.path.isfile(path):
|
|
210
220
|
return None
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Cross-platform POSIX open-flag and directory-handle helpers.
|
|
2
|
+
|
|
3
|
+
On POSIX, keeps exact kernel-enforced ``O_NOFOLLOW``, ``O_NONBLOCK``,
|
|
4
|
+
``O_CLOEXEC``, ``O_DIRECTORY``, and ``dir_fd`` semantics. On Windows, validates
|
|
5
|
+
symlinks and NTFS reparse points (junctions) via ``os.lstat`` before opening
|
|
6
|
+
(note: the lstat-then-open fallback is best-effort/TOCTOU on Windows).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import errno
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import stat
|
|
14
|
+
|
|
15
|
+
IS_WINDOWS = os.name == 'nt'
|
|
16
|
+
_MSYS_PATH_RE = re.compile(r'^/([a-zA-Z])(?:/(.*))?$')
|
|
17
|
+
|
|
18
|
+
O_NOFOLLOW = getattr(os, 'O_NOFOLLOW', 0)
|
|
19
|
+
O_NONBLOCK = getattr(os, 'O_NONBLOCK', 0)
|
|
20
|
+
O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0)
|
|
21
|
+
O_DIRECTORY = getattr(os, 'O_DIRECTORY', 0)
|
|
22
|
+
|
|
23
|
+
_REPARSE_ATTR = getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400)
|
|
24
|
+
|
|
25
|
+
SUPPORTS_DIR_FD = (
|
|
26
|
+
os.open in os.supports_dir_fd
|
|
27
|
+
and os.stat in os.supports_dir_fd
|
|
28
|
+
and os.unlink in os.supports_dir_fd
|
|
29
|
+
and os.mkdir in os.supports_dir_fd
|
|
30
|
+
and os.rename in os.supports_dir_fd
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _is_link_or_reparse(st: os.stat_result) -> bool:
|
|
35
|
+
return stat.S_ISLNK(st.st_mode) or bool(getattr(st, 'st_file_attributes', 0) & _REPARSE_ATTR)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _reject_symlink(path: os.PathLike | str) -> None:
|
|
39
|
+
"""Raise ELOOP if ``path`` is a symlink or reparse point (Windows fallback)."""
|
|
40
|
+
try:
|
|
41
|
+
st = os.lstat(path)
|
|
42
|
+
except FileNotFoundError:
|
|
43
|
+
return
|
|
44
|
+
if _is_link_or_reparse(st):
|
|
45
|
+
raise OSError(errno.ELOOP, 'Too many levels of symbolic links', os.fspath(path))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def open_nofollow(path: os.PathLike | str, flags: int, mode: int = 0o777) -> int:
|
|
49
|
+
"""Open ``path`` without following symlinks or junctions."""
|
|
50
|
+
if O_NOFOLLOW != 0:
|
|
51
|
+
flags |= O_NOFOLLOW
|
|
52
|
+
else:
|
|
53
|
+
_reject_symlink(path)
|
|
54
|
+
return os.open(path, flags, mode)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def open_dir(path: os.PathLike | str, *, nofollow: bool = True) -> int | str:
|
|
58
|
+
"""Open a real directory safely; returns an int dir_fd on POSIX or path str on Windows."""
|
|
59
|
+
flags = os.O_RDONLY | O_DIRECTORY | (O_NOFOLLOW if nofollow else 0) | O_CLOEXEC
|
|
60
|
+
if SUPPORTS_DIR_FD:
|
|
61
|
+
return os.open(path, flags)
|
|
62
|
+
st = os.lstat(path)
|
|
63
|
+
if nofollow and _is_link_or_reparse(st):
|
|
64
|
+
raise OSError(errno.ELOOP, 'Too many levels of symbolic links', os.fspath(path))
|
|
65
|
+
if not stat.S_ISDIR(st.st_mode):
|
|
66
|
+
raise OSError(errno.ENOTDIR, 'Not a directory', os.fspath(path))
|
|
67
|
+
return os.fspath(path)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def close_dir(handle: int | str) -> None:
|
|
71
|
+
if isinstance(handle, int):
|
|
72
|
+
os.close(handle)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def enter_dir(handle: int | str, part: str, *, nofollow: bool = True) -> int | str:
|
|
76
|
+
if isinstance(handle, int):
|
|
77
|
+
flags = os.O_RDONLY | O_DIRECTORY | (O_NOFOLLOW if nofollow else 0) | O_CLOEXEC
|
|
78
|
+
return os.open(part, flags, dir_fd=handle)
|
|
79
|
+
return open_dir(os.path.join(handle, part), nofollow=nofollow)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def mkdir_at(handle: int | str, part: str) -> None:
|
|
83
|
+
if isinstance(handle, int):
|
|
84
|
+
os.mkdir(part, dir_fd=handle)
|
|
85
|
+
else:
|
|
86
|
+
os.mkdir(os.path.join(handle, part))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def stat_at(handle: int | str, leaf: str, *, follow_symlinks: bool = False) -> os.stat_result:
|
|
90
|
+
if isinstance(handle, int):
|
|
91
|
+
return os.stat(leaf, dir_fd=handle, follow_symlinks=follow_symlinks)
|
|
92
|
+
return os.stat(os.path.join(handle, leaf), follow_symlinks=follow_symlinks)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def open_at(handle: int | str, leaf: str, flags: int, mode: int = 0o644) -> int:
|
|
96
|
+
if isinstance(handle, int):
|
|
97
|
+
return os.open(leaf, flags, mode, dir_fd=handle)
|
|
98
|
+
return open_nofollow(os.path.join(handle, leaf), flags, mode)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def replace_at(handle: int | str, src: str, dst: str) -> None:
|
|
102
|
+
if isinstance(handle, int):
|
|
103
|
+
os.replace(src, dst, src_dir_fd=handle, dst_dir_fd=handle)
|
|
104
|
+
else:
|
|
105
|
+
os.replace(os.path.join(handle, src), os.path.join(handle, dst))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def unlink_at(handle: int | str, leaf: str) -> None:
|
|
109
|
+
if isinstance(handle, int):
|
|
110
|
+
os.unlink(leaf, dir_fd=handle)
|
|
111
|
+
else:
|
|
112
|
+
os.unlink(os.path.join(handle, leaf))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def host_path(path: os.PathLike | str) -> str:
|
|
116
|
+
"""Convert an MSYS/Git-Bash `/c/...` path to `C:/...` on native Windows."""
|
|
117
|
+
text = os.fspath(path)
|
|
118
|
+
if IS_WINDOWS and text:
|
|
119
|
+
if text.startswith('\\\\?\\') and len(text) >= 6 and text[5] == ':':
|
|
120
|
+
text = text[4:]
|
|
121
|
+
m = _MSYS_PATH_RE.fullmatch(text)
|
|
122
|
+
if m:
|
|
123
|
+
rest = m.group(2) or ''
|
|
124
|
+
return f'{m.group(1).upper()}:/{rest}'
|
|
125
|
+
return text
|