Coverage for src/romfarmer/targets/emitters/materializer.py: 0%

73 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-04 16:33 -0700

1"""Materializer — hardlink/copy files from a source set into the output tree. 

2 

3This module ports the ``_link_or_copy`` helper from ``stages/organize.py`` 

4and the organisation-style logic (flat, balanced, minimal, rich). 

5 

6It is the only component that performs disk writes during EMIT. All other 

7emitter components are pure (return data). 

8""" 

9 

10from __future__ import annotations 

11 

12import logging 

13import os 

14import re 

15import shutil 

16from pathlib import Path 

17 

18logger = logging.getLogger(__name__) 

19 

20# --------------------------------------------------------------------------- 

21# Low-level copy primitive 

22# --------------------------------------------------------------------------- 

23 

24 

25def link_or_copy(src: Path, dest: Path) -> None: 

26 """Hardlink *src* to *dest*, falling back to copy if cross-device. 

27 

28 Ported from ``stages/organize.py::_link_or_copy``. Hardlinks are 

29 preferred: they are instant and consume no additional disk space. 

30 """ 

31 dest.parent.mkdir(parents=True, exist_ok=True) 

32 try: 

33 os.link(src, dest) 

34 except OSError: 

35 shutil.copy2(src, dest) 

36 

37 

38# --------------------------------------------------------------------------- 

39# Organisation styles 

40# --------------------------------------------------------------------------- 

41 

42 

43def _first_letter(name: str) -> str: 

44 """Return the first letter of *name*, uppercased; digits become '0-9'.""" 

45 stem = Path(name).stem 

46 ch = stem[0].upper() if stem else "0" 

47 return "0-9" if ch.isdigit() else ch 

48 

49 

50def _is_rom_file(path: Path) -> bool: 

51 """Return True for files that belong in the main ROM listing.""" 

52 return path.suffix.lower() not in {".xml", ".jpg", ".png", ".mp4", ".txt"} 

53 

54 

55class Materializer: 

56 """Organises a flat list of files into the output directory. 

57 

58 Organisation styles match the legacy ``OrganizationStyle`` values: 

59 - ``flat`` — all files directly in output_dir 

60 - ``balanced`` — letter subdirs (A/, B/, …, 0-9/) when > threshold 

61 - ``minimal`` — numeric subdirs only when count > threshold 

62 - ``rich`` — always use letter subdirs 

63 

64 Args: 

65 style: Organisation style (default ``"flat"``). 

66 balanced_threshold: File count above which ``balanced`` adds subdirs 

67 (default 500). 

68 move: When True, remove the source path after a successful place 

69 (used for in-place reorganisation of the executor's output dir 

70 so ROMs don't appear twice — top-level *and* in a letter 

71 subdir). Default False preserves sources (CAS-side usage). 

72 """ 

73 

74 _BALANCED_THRESHOLD = 500 

75 

76 def __init__( 

77 self, 

78 style: str = "flat", 

79 balanced_threshold: int = _BALANCED_THRESHOLD, 

80 move: bool = False, 

81 ) -> None: 

82 self._style = style.lower() 

83 self._threshold = balanced_threshold 

84 self._move = move 

85 

86 def emit(self, files: list[Path], output_dir: Path) -> list[Path]: 

87 """Place *files* into *output_dir* using the configured style. 

88 

89 Returns the list of destination paths. 

90 """ 

91 output_dir.mkdir(parents=True, exist_ok=True) 

92 if self._style == "rich": 

93 return self._emit_by_letter(files, output_dir) 

94 if self._style == "balanced" and len(files) > self._threshold: 

95 return self._emit_by_letter(files, output_dir) 

96 if self._style == "minimal" and len(files) > self._threshold: 

97 return self._emit_numeric(files, output_dir) 

98 return self._emit_flat(files, output_dir) 

99 

100 # ------------------------------------------------------------------ 

101 

102 def _emit_flat(self, files: list[Path], dest_dir: Path) -> list[Path]: 

103 placed: list[Path] = [] 

104 for src in files: 

105 dest = dest_dir / src.name 

106 if not dest.exists(): 

107 link_or_copy(src, dest) 

108 self._maybe_remove_source(src, dest) 

109 placed.append(dest) 

110 return placed 

111 

112 def _emit_by_letter(self, files: list[Path], dest_dir: Path) -> list[Path]: 

113 placed: list[Path] = [] 

114 for src in files: 

115 subdir = dest_dir / _first_letter(src.name) 

116 dest = subdir / src.name 

117 if not dest.exists(): 

118 link_or_copy(src, dest) 

119 self._maybe_remove_source(src, dest) 

120 placed.append(dest) 

121 return placed 

122 

123 def _emit_numeric(self, files: list[Path], dest_dir: Path) -> list[Path]: 

124 """Group by first numeric block of the stem; fallback to flat.""" 

125 placed: list[Path] = [] 

126 for src in files: 

127 m = re.search(r"\d+", Path(src).stem) 

128 if m: 

129 prefix = str(int(m.group()) // 100 * 100) # e.g. "0", "100", "200" 

130 subdir = dest_dir / prefix 

131 else: 

132 subdir = dest_dir 

133 dest = subdir / src.name 

134 if not dest.exists(): 

135 link_or_copy(src, dest) 

136 self._maybe_remove_source(src, dest) 

137 placed.append(dest) 

138 return placed 

139 

140 def _maybe_remove_source(self, src: Path, dest: Path) -> None: 

141 """In move mode, unlink *src* once *dest* exists (hardlink-safe).""" 

142 if not self._move: 

143 return 

144 try: 

145 if src.resolve() != dest.resolve() and src.exists() and dest.exists(): 

146 src.unlink() 

147 except OSError: # pragma: no cover — best-effort cleanup 

148 logger.debug("Materializer: could not remove source %s", src)