mirror of
https://github.com/ProjectLeonida/mandy.git
synced 2026-12-06 09:08:38 +00:00
navmesh_index: report missing input before mode checks, handle write OSError, separate chmod/unlink cleanup, and align pattern matching
This commit is contained in:
@ -629,6 +629,87 @@ class OutputPathTest(unittest.TestCase):
|
||||
self.assertIn("--out is a directory", r.stderr)
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
def test_missing_input_with_pattern_reports_does_not_exist(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
missing = os.path.join(tmp, "no_such_dir")
|
||||
out = os.path.join(tmp, "report.json")
|
||||
r = subprocess.run([sys.executable, "-I", TOOL, missing, "--pattern", "*.bin", "--out", out],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(r.returncode, 2, r.stderr)
|
||||
self.assertIn("does not exist", r.stderr)
|
||||
self.assertNotIn("applies to a directory", r.stderr)
|
||||
self.assertFalse(os.path.exists(out))
|
||||
|
||||
def test_unwritable_output_exits_cleanly_without_traceback(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
source = os.path.join(tmp, "carved")
|
||||
os.makedirs(source)
|
||||
with open(os.path.join(source, "p.bin"), "wb") as f:
|
||||
f.write(page())
|
||||
plain = os.path.join(tmp, "plain")
|
||||
with open(plain, "wb") as f:
|
||||
f.write(b"x")
|
||||
r = subprocess.run([sys.executable, "-I", TOOL, source, "--out", os.path.join(plain, "out.json")],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(r.returncode, 2, r.stderr)
|
||||
self.assertIn("ERROR:", r.stderr)
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
|
||||
if os.name == "nt":
|
||||
ro = os.path.join(tmp, "ro.json")
|
||||
previous = '{"previous": true}\n'
|
||||
with open(ro, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(previous)
|
||||
os.chmod(ro, 0o444)
|
||||
self.addCleanup(lambda: os.path.exists(ro) and os.chmod(ro, 0o600))
|
||||
r = subprocess.run([sys.executable, "-I", TOOL, source, "--out", ro],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(r.returncode, 2, r.stderr)
|
||||
self.assertIn("ERROR:", r.stderr)
|
||||
self.assertNotIn("Traceback", r.stderr)
|
||||
with open(ro, encoding="utf-8") as f:
|
||||
self.assertEqual(f.read(), previous)
|
||||
self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".navmesh_index-")], [])
|
||||
|
||||
def test_cleanup_still_unlinks_temp_when_chmod_fails(self):
|
||||
tool = load_tool_module()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
dest = os.path.join(tmp, "report.json")
|
||||
real_chmod = os.chmod
|
||||
|
||||
def fail_restore(path, mode, *args, **kwargs):
|
||||
if isinstance(path, str) and os.path.basename(path).startswith(".navmesh_index-") and mode == 0o600:
|
||||
raise OSError("chmod failed")
|
||||
return real_chmod(path, mode, *args, **kwargs)
|
||||
|
||||
with mock.patch.object(tool.os, "replace", side_effect=OSError("replace denied")), \
|
||||
mock.patch.object(tool.os, "chmod", side_effect=fail_restore):
|
||||
with self.assertRaises(OSError):
|
||||
tool.write_outputs([], {"streams": 0}, dest, None)
|
||||
self.assertEqual([n for n in os.listdir(tmp) if n.startswith(".navmesh_index-")], [])
|
||||
|
||||
def test_is_scanned_input_matches_slash_and_globstar_patterns(self):
|
||||
tool = load_tool_module()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = os.path.join(tmp, "carved")
|
||||
sub = os.path.join(root, "sub")
|
||||
os.makedirs(sub)
|
||||
nested = os.path.join(sub, "0001.bin")
|
||||
with open(nested, "wb") as f:
|
||||
f.write(page())
|
||||
other = os.path.join(sub, "ignore.txt")
|
||||
with open(other, "wb") as f:
|
||||
f.write(b"text")
|
||||
|
||||
self.assertTrue(tool.is_scanned_input(nested, root, "sub/*.bin"))
|
||||
self.assertTrue(tool.is_scanned_input(nested, root, "**/sub/*.bin"))
|
||||
self.assertFalse(tool.is_scanned_input(other, root, "sub/*.bin"))
|
||||
|
||||
# Simulate a case-variant / resolved path where the fallback glob does not see a match.
|
||||
with mock.patch.object(tool.glob, "iglob", return_value=iter(())):
|
||||
self.assertTrue(tool.is_scanned_input(nested, root, "sub/*.bin"))
|
||||
self.assertTrue(tool.is_scanned_input(nested, root, "**/sub/*.bin"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@ -35,11 +35,9 @@ import time
|
||||
import zlib
|
||||
from contextlib import suppress
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from file_mode import published_mode # noqa: E402
|
||||
|
||||
# -I keeps the script directory off sys.path, so add it explicitly before importing the sibling module.
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from file_mode import published_mode # noqa: E402
|
||||
from report_paths import same_report_path # noqa: E402
|
||||
from zero_span import gap_split # noqa: E402
|
||||
|
||||
@ -163,6 +161,13 @@ def scan_archive(path, start=None, limit=None):
|
||||
return rows, summary
|
||||
|
||||
|
||||
def _pattern_query(pattern):
|
||||
query = pattern.replace(os.altsep, os.sep) if os.altsep else pattern
|
||||
if query.split(os.sep, 1)[0] != "**":
|
||||
query = os.path.join("**", query)
|
||||
return query
|
||||
|
||||
|
||||
def scan_directory(root, pattern=None):
|
||||
"""Read the first 128 bytes of each matching carved file. Rows are marker matches only."""
|
||||
pattern = pattern or "*.bin"
|
||||
@ -170,9 +175,7 @@ def scan_directory(root, pattern=None):
|
||||
t0 = time.time()
|
||||
# Escape only the caller's root: a folder named "carve[1]" would otherwise be read as a character
|
||||
# class by glob and match nothing. The pattern (and "**") stays as the caller's glob.
|
||||
query = pattern.replace(os.altsep, os.sep) if os.altsep else pattern
|
||||
if query.split(os.sep, 1)[0] != "**":
|
||||
query = os.path.join("**", query)
|
||||
query = _pattern_query(pattern)
|
||||
matches = glob.iglob(os.path.join(glob.escape(os.fspath(root)), query), recursive=True)
|
||||
# Separated ** segments (e.g. **/tiles/**/*.bin) can still match a pathname more than once.
|
||||
for path in sorted(set(matches) if query.split(os.sep).count("**") > 1 else matches):
|
||||
@ -232,10 +235,11 @@ def _publish(dest, write, newline):
|
||||
os.replace(temp, dest)
|
||||
except BaseException:
|
||||
if temp is not None:
|
||||
# The staging file may have inherited a read-only destination's mode; make it deletable
|
||||
# first, or Windows strands it beside the report when the replace fails.
|
||||
with suppress(OSError):
|
||||
# The staging file may have inherited a read-only destination's mode; make it deletable
|
||||
# first, or Windows strands it beside the report when the replace fails.
|
||||
os.chmod(temp, 0o600)
|
||||
with suppress(OSError):
|
||||
os.unlink(temp)
|
||||
raise
|
||||
|
||||
@ -296,13 +300,16 @@ def is_scanned_input(path, input_path, pattern):
|
||||
break
|
||||
root = parent
|
||||
else:
|
||||
if (fnmatch.fnmatch(os.path.relpath(target, root), pattern)
|
||||
or fnmatch.fnmatch(os.path.basename(target), pattern)):
|
||||
rel = os.path.relpath(target, root)
|
||||
pat = pattern.replace(os.altsep, os.sep) if os.altsep else pattern
|
||||
rel_pat = pat[len("**" + os.sep):] if pat.startswith("**" + os.sep) else pat
|
||||
if (fnmatch.fnmatch(rel, pat) or fnmatch.fnmatch(rel, rel_pat)
|
||||
or (os.sep not in pat and fnmatch.fnmatch(os.path.basename(target), pat))):
|
||||
return True
|
||||
# A different spelling or a hard link anywhere can still refer to a scanned file.
|
||||
return any(same_report_path(target, scanned)
|
||||
for scanned in glob.iglob(
|
||||
os.path.join(glob.escape(os.fspath(input_path)), "**", pattern), recursive=True))
|
||||
os.path.join(glob.escape(os.fspath(input_path)), _pattern_query(pattern)), recursive=True))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@ -314,11 +321,6 @@ def main() -> int:
|
||||
ap.add_argument("--limit", type=byte_count, help="maximum bytes to scan in an archive")
|
||||
ap.add_argument("--pattern", default=None, help="directory input glob (default: *.bin)")
|
||||
a = ap.parse_args()
|
||||
is_dir = os.path.isdir(a.input)
|
||||
if is_dir and (a.start is not None or a.limit is not None):
|
||||
ap.error("--start and --limit apply to a single archive, not a directory")
|
||||
if not is_dir and a.pattern is not None:
|
||||
ap.error("--pattern applies to a directory, not an archive")
|
||||
base = os.path.basename(os.path.normpath(a.input))
|
||||
out_path = a.out or os.path.splitext(base)[0] + ".navmesh-index.json"
|
||||
if a.csv and same_report_path(out_path, a.csv):
|
||||
@ -326,11 +328,17 @@ def main() -> int:
|
||||
for flag, path in (("--out", out_path), ("--csv", a.csv)):
|
||||
if path and os.path.isdir(path): # open() on a folder ends the run in a PermissionError traceback
|
||||
ap.error(f"{flag} is a directory: {path}")
|
||||
if path and is_scanned_input(path, a.input, a.pattern):
|
||||
ap.error(f"{flag} would overwrite the input {path}")
|
||||
if not os.path.exists(a.input):
|
||||
print(f"ERROR: {a.input}: does not exist", file=sys.stderr)
|
||||
return 2
|
||||
is_dir = os.path.isdir(a.input)
|
||||
if is_dir and (a.start is not None or a.limit is not None):
|
||||
ap.error("--start and --limit apply to a single archive, not a directory")
|
||||
if not is_dir and a.pattern is not None:
|
||||
ap.error("--pattern applies to a directory, not an archive")
|
||||
for flag, path in (("--out", out_path), ("--csv", a.csv)):
|
||||
if path and is_scanned_input(path, a.input, a.pattern):
|
||||
ap.error(f"{flag} would overwrite the input {path}")
|
||||
below_normal()
|
||||
|
||||
if is_dir:
|
||||
@ -349,7 +357,11 @@ def main() -> int:
|
||||
ap.error(str(e))
|
||||
|
||||
add_distribution(summary, rows)
|
||||
written = write_outputs(rows, summary, out_path, a.csv)
|
||||
try:
|
||||
written = write_outputs(rows, summary, out_path, a.csv)
|
||||
except OSError as e:
|
||||
print(f"ERROR: cannot write {e.filename or out_path}: {e.strerror or e}", file=sys.stderr)
|
||||
return 2
|
||||
print(json.dumps(summary, indent=1))
|
||||
print(f"wrote {out_path}" + (f", {', '.join(written)}" if written else ""))
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user