Coverage for src/romfarmer/engine/transforms/archive.py: 82%

40 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Archive transform — compress a ROM to 7z or ZIP. 

2 

3Extracted from ``romfarmer.stages.compress_archive.CompressArchiveStage``. 

4Uses the system ``7z`` binary for compression. 

5""" 

6 

7from __future__ import annotations 

8 

9import shutil 

10import subprocess 

11from collections.abc import Mapping 

12from pathlib import Path 

13 

14from .base import Transform, TransformError, pinned_env 

15 

16# Determinism pins (IMPL_VERSIONS["7z"] == 2). Changing these requires a bump. 

17# -mtm=off do not store file modification times 

18# -mmt=4 fixed thread count: LZMA2 block layout depends on it 

19_DETERMINISM_FLAGS = ("-mtm=off", "-mmt=4") 

20 

21 

22class ArchiveTransform: 

23 """Compress a ROM file to 7z or ZIP format. 

24 

25 Recognised params: 

26 format: ``"7z"`` (default) or ``"zip"`` 

27 compression_level: ``"9"`` (default) 

28 method: LZMA2 for 7z, Deflate for zip (defaults by format) 

29 sevenzip_path: override path to 7z binary 

30 """ 

31 

32 name = "7z" 

33 

34 def run( 

35 self, 

36 inputs: list[Path], 

37 params: Mapping[str, str], 

38 scratch: Path, 

39 ) -> list[Path]: 

40 if not inputs: 

41 raise TransformError("ArchiveTransform: no input files provided") 

42 

43 input_file = inputs[0] 

44 fmt = params.get("format", "7z") 

45 level = params.get("compression_level", "9") 

46 tool = self._find_7z(params.get("sevenzip_path")) 

47 if tool is None: 

48 raise TransformError("7z not found; install p7zip or set sevenzip_path param") 

49 

50 ext = ".7z" if fmt == "7z" else ".zip" 

51 output_path = scratch / (input_file.stem + ext) 

52 

53 cmd = [ 

54 str(tool), 

55 "a", 

56 f"-mx={level}", 

57 *_DETERMINISM_FLAGS, 

58 str(output_path), 

59 str(input_file), 

60 ] 

61 if fmt == "zip": 

62 cmd = [ 

63 str(tool), 

64 "a", 

65 "-tzip", 

66 f"-mx={level}", 

67 *_DETERMINISM_FLAGS, 

68 str(output_path), 

69 str(input_file), 

70 ] 

71 

72 result = subprocess.run(cmd, capture_output=True, text=True, check=False, env=pinned_env()) 

73 if result.returncode not in (0, 1): # 7z returns 1 for warnings 

74 raise TransformError(f"7z failed for {input_file.name}: {result.stderr[:500]}") 

75 if not output_path.exists(): 

76 raise TransformError(f"7z did not produce expected output {output_path}") 

77 return [output_path] 

78 

79 @staticmethod 

80 def _find_7z(override: str | None) -> Path | None: 

81 if override: 

82 p = Path(override) 

83 return p if p.exists() else None 

84 for name in ("7z", "7zz", "7za"): 

85 found = shutil.which(name) 

86 if found: 

87 return Path(found) 

88 return None 

89 

90 

91_: Transform = ArchiveTransform()