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

75 statements  

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

1"""ESGamelistEmitter — generates gamelist.xml for EmulationStation targets. 

2 

3Ports the core logic from ``stages/metadata.py::GenerateMetadataStage``. 

4 

5Key differences from the legacy stage: 

6- Input is a ``LayoutPlan`` + ``output_dir`` (no ``StageContext``) 

7- Database lookups go through ``KnowledgeBase`` (no direct SQLAlchemy) 

8- Multi-disc handling: M3U files are primary; .chd files with a sibling .m3u 

9 are hidden (path starts with ``./``) 

10- Returns a list of ``ArtifactDecl`` (the gamelist.xml as an artifact) 

11 

12The gamelist.xml format is identical to what the legacy stage produced, 

13so existing Batocera/RocknIX installations require no changes. 

14""" 

15 

16from __future__ import annotations 

17 

18import logging 

19import re 

20from pathlib import Path 

21from typing import TYPE_CHECKING 

22from xml.etree import ElementTree as ET 

23 

24from romfarmer.ir.actions import ArtifactDecl, Retention 

25from romfarmer.ir.layout import LayoutPlan 

26 

27if TYPE_CHECKING: 

28 from romfarmer.analysis.knowledge import KnowledgeBase 

29 from romfarmer.targets.emitters.base import PostHook 

30 from romfarmer.targets.profiles.loader import ConcreteTargetProfile 

31 

32logger = logging.getLogger(__name__) 

33 

34_DISC_TAG = re.compile(r"\s*\((?:Disc|Disk|CD)\s*\d+\)", re.IGNORECASE) 

35 

36 

37def _canonical(stem: str) -> str: 

38 """Strip disc tags for grouping and M3U playlist naming.""" 

39 return _DISC_TAG.sub("", stem).strip() 

40 

41 

42class ESGamelistEmitter: 

43 """Generates ``gamelist.xml`` for EmulationStation-based frontends. 

44 

45 Used by targets with ``MetadataDialect.ES_GAMELIST`` (Batocera, RocknIX, 

46 RetroArch + ES-DE, …). 

47 """ 

48 

49 def plan_layout( 

50 self, 

51 output_dir: Path, 

52 profile: ConcreteTargetProfile, 

53 ) -> LayoutPlan: 

54 """Delegates to GenericEmitter — layout is format-agnostic.""" 

55 from romfarmer.targets.emitters.generic import GenericEmitter 

56 

57 return GenericEmitter().plan_layout(output_dir, profile) 

58 

59 def emit_metadata( 

60 self, 

61 layout: LayoutPlan, 

62 output_dir: Path, 

63 kb: KnowledgeBase, 

64 profile: ConcreteTargetProfile, 

65 ) -> list[ArtifactDecl]: 

66 """Write ``gamelist.xml`` to *output_dir* and return its artifact declaration.""" 

67 if not profile.metadata_enabled: 

68 return [] 

69 

70 gamelist = ET.Element("gameList") 

71 processed: set[str] = set() 

72 

73 # Collect all files 

74 chd_files: dict[str, Path] = {} 

75 m3u_files: dict[str, Path] = {} 

76 

77 for entry in layout.entries: 

78 abs_path = output_dir / entry.relative_path 

79 if abs_path.suffix.lower() == ".chd": 

80 canonical = _canonical(abs_path.stem) 

81 chd_files[abs_path.name] = abs_path 

82 elif abs_path.suffix.lower() == ".m3u": 

83 canonical = _canonical(abs_path.stem) 

84 m3u_files[canonical] = abs_path 

85 

86 # Add M3U entries first (multi-disc primary) 

87 for canonical, m3u_path in sorted(m3u_files.items()): 

88 if m3u_path.name in processed: 

89 continue 

90 game_elem = self._make_game_elem(m3u_path, output_dir, kb) 

91 gamelist.append(game_elem) 

92 processed.add(m3u_path.name) 

93 # Mark individual CHDs as hidden 

94 for chd_name, chd_path in chd_files.items(): 

95 if _canonical(chd_path.stem) == canonical: 

96 hidden_elem = self._make_game_elem(chd_path, output_dir, kb, hidden=True) 

97 gamelist.append(hidden_elem) 

98 processed.add(chd_name) 

99 

100 # Add remaining files not covered by M3U 

101 for entry in layout.entries: 

102 abs_path = output_dir / entry.relative_path 

103 if abs_path.name in processed: 

104 continue 

105 game_elem = self._make_game_elem(abs_path, output_dir, kb) 

106 gamelist.append(game_elem) 

107 processed.add(abs_path.name) 

108 

109 # Sort by name 

110 games = gamelist.findall("game") 

111 gamelist.clear() 

112 for g in sorted(games, key=lambda e: e.findtext("name") or ""): 

113 gamelist.append(g) 

114 

115 # Write 

116 gamelist_path = output_dir / "gamelist.xml" 

117 tree = ET.ElementTree(gamelist) 

118 ET.indent(tree, space=" ") 

119 tree.write( 

120 str(gamelist_path), 

121 encoding="utf-8", 

122 xml_declaration=True, 

123 ) 

124 logger.info("ESGamelistEmitter: wrote %s (%d entries)", gamelist_path, len(games)) 

125 

126 return [ 

127 ArtifactDecl( 

128 logical_name="gamelist.xml", 

129 kind="gamelist", 

130 retention=Retention.TERMINAL, 

131 ) 

132 ] 

133 

134 def post_process(self, root: Path) -> list[PostHook]: 

135 return [] 

136 

137 # ------------------------------------------------------------------ 

138 

139 def _make_game_elem( 

140 self, 

141 path: Path, 

142 output_dir: Path, 

143 kb: KnowledgeBase, 

144 hidden: bool = False, 

145 ) -> ET.Element: 

146 """Build a ``<game>`` element for *path*.""" 

147 game = ET.Element("game") 

148 

149 rel = path.relative_to(output_dir) if path.is_relative_to(output_dir) else path 

150 ET.SubElement(game, "path").text = f"./{rel}" 

151 ET.SubElement(game, "name").text = _canonical(path.stem) 

152 

153 if hidden: 

154 ET.SubElement(game, "hidden").text = "true" 

155 

156 # Try to enrich from KnowledgeBase 

157 try: 

158 rating = kb.get_rating( 

159 path.parent.name, # platform = parent dir name 

160 _canonical(path.stem), 

161 ) 

162 if rating is not None: 

163 ET.SubElement(game, "rating").text = f"{rating:.1f}" 

164 except Exception: 

165 pass 

166 

167 return game