ines-parser 1.4.0__tar.gz → 2.0.0__tar.gz

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.
Files changed (26) hide show
  1. {ines_parser-1.4.0 → ines_parser-2.0.0}/PKG-INFO +27 -5
  2. ines_parser-2.0.0/README.md +95 -0
  3. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/__init__.py +14 -2
  4. ines_parser-2.0.0/ines_parser/cli/ines_analyze_rom.py +468 -0
  5. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/cli/ines_rom_stats.py +3 -4
  6. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/cli/ines_scan_roms.py +7 -5
  7. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/cli/ines_split_rom.py +114 -24
  8. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/cli/rom_fs.py +2 -3
  9. ines_parser-2.0.0/ines_parser/filename.py +397 -0
  10. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/parser.py +9 -10
  11. ines_parser-2.0.0/ines_parser/py.typed +0 -0
  12. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/PKG-INFO +27 -5
  13. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/SOURCES.txt +6 -1
  14. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/entry_points.txt +1 -0
  15. {ines_parser-1.4.0 → ines_parser-2.0.0}/pyproject.toml +3 -2
  16. ines_parser-2.0.0/tests/test_filename.py +292 -0
  17. ines_parser-2.0.0/tests/test_parser.py +91 -0
  18. ines_parser-1.4.0/README.md +0 -73
  19. {ines_parser-1.4.0 → ines_parser-2.0.0}/LICENSE +0 -0
  20. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/cli/__init__.py +0 -0
  21. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/mappers.py +0 -0
  22. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser/tables.py +0 -0
  23. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/dependency_links.txt +0 -0
  24. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/requires.txt +0 -0
  25. {ines_parser-1.4.0 → ines_parser-2.0.0}/ines_parser.egg-info/top_level.txt +0 -0
  26. {ines_parser-1.4.0 → ines_parser-2.0.0}/setup.cfg +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ines-parser
3
- Version: 1.4.0
4
- Summary: Parse iNES/NES 2.0 ROM headers; CLI to scan, export, summarize, and split ROMs
3
+ Version: 2.0.0
4
+ Summary: Parse iNES/NES 2.0 ROM headers and ROM filename tags; CLI to scan, export, summarize, analyze, and split ROMs
5
5
  Author: Leonid Kabanov
6
6
  License-Expression: MIT
7
7
  Project-URL: Homepage, https://github.com/ponchick/ines-parser
@@ -28,7 +28,9 @@ Dynamic: license-file
28
28
 
29
29
  # iNES Parser
30
30
 
31
- Python library and CLI for NES ROMs in iNES / NES 2.0 format: parse headers, scan collections, export reports, summarize mappers, and split PRG/CHR. Requires Python 3.10+.
31
+ Python library and CLI for NES ROMs in iNES / NES 2.0 format: parse headers and ROM filename tags, scan collections, export reports, summarize mappers, analyze single ROMs, and split PRG/CHR. Requires Python 3.10+.
32
+
33
+ For reading **and writing** complete `.nes` files (assembling ROMs from PRG/CHR parts, patching header fields, serializing headers) see the companion project [`ines-file`](https://github.com/ponchick/ines-file).
32
34
 
33
35
  ```bash
34
36
  pip install ines-parser
@@ -44,7 +46,7 @@ ines_scan_roms.py /path/to/roms
44
46
  # or: python -m ines_parser.cli.ines_scan_roms /path/to/roms
45
47
  ```
46
48
 
47
- Same idea for `ines_rom_stats.py` and `ines_split_rom.py`.
49
+ Same idea for `ines_rom_stats.py`, `ines_split_rom.py`, and `ines_analyze_rom.py`.
48
50
 
49
51
  ### Scan
50
52
 
@@ -72,12 +74,26 @@ ines_rom_stats.py /path/to/roms --json
72
74
  ```bash
73
75
  ines_split_rom.py game.nes
74
76
  ines_split_rom.py roms.7z # prompts before overwrite; use --force to skip
77
+ ines_split_rom.py game.nes --pad-chr 64 # clone CHR to fill a 27C512 EPROM
78
+ ines_split_rom.py game.nes --pad-prg 128 --pad-chr 64
79
+ ```
80
+
81
+ `--pad-prg` / `--pad-chr` clone the image across the whole target size in KiB: for burning a larger EPROM the data then reads the same whatever the upper address lines return. The target must be an integer multiple of the image size; nothing is ever truncated.
82
+
83
+ ### Analyze
84
+
85
+ ```bash
86
+ ines_analyze_rom.py game.nes
87
+ ines_analyze_rom.py game.7z # GoodTools-style one-ROM archive (needs libarchive-c)
88
+ ines_analyze_rom.py game.nes --json
75
89
  ```
76
90
 
91
+ Full report for one ROM file: file size, iNES header, and naming-convention tags parsed from the filename — GoodTools style (`(JU) [!] [b] [hIR] [T+Rus] (VS) (PC10)`) and No-Intro style (`(USA) (Rev A) (Beta 1) (En,Fr,De)`) — plus cross-checks between them: file size vs. header, filename region vs. TV system, `(VS)`/`(PC10)` vs. console type, `[!]` vs. header validity. For archives, tags come from the inner `.nes` name and sizes refer to the uncompressed ROM. Unrecognised tags are listed as unknown, never guessed.
92
+
77
93
  ## Library
78
94
 
79
95
  ```python
80
- from ines_parser import parse_ines_header
96
+ from ines_parser import parse_ines_header, parse_rom_filename
81
97
 
82
98
  with open("game.nes", "rb") as f:
83
99
  header = parse_ines_header(f.read(16))
@@ -85,6 +101,12 @@ with open("game.nes", "rb") as f:
85
101
  if header and header.is_valid():
86
102
  print(header)
87
103
  print(header.detailed_str())
104
+
105
+ info = parse_rom_filename("Super Mario Bros. (JU) [!].nes")
106
+ print(info.title) # Super Mario Bros.
107
+ print(info.regions) # ('Japan', 'USA')
108
+ print(info.verified) # True
109
+ print(info.to_dict()) # JSON-friendly; adds expected_tv_system
88
110
  ```
89
111
 
90
112
  ## Docs
@@ -0,0 +1,95 @@
1
+ # iNES Parser
2
+
3
+ Python library and CLI for NES ROMs in iNES / NES 2.0 format: parse headers and ROM filename tags, scan collections, export reports, summarize mappers, analyze single ROMs, and split PRG/CHR. Requires Python 3.10+.
4
+
5
+ For reading **and writing** complete `.nes` files (assembling ROMs from PRG/CHR parts, patching header fields, serializing headers) see the companion project [`ines-file`](https://github.com/ponchick/ines-file).
6
+
7
+ ```bash
8
+ pip install ines-parser
9
+ pip install "ines-parser[archive]" # optional: .7z / .zip / .rar
10
+ ```
11
+
12
+ ## CLI
13
+
14
+ After install the tools are on your `PATH`. From a checkout:
15
+
16
+ ```bash
17
+ ines_scan_roms.py /path/to/roms
18
+ # or: python -m ines_parser.cli.ines_scan_roms /path/to/roms
19
+ ```
20
+
21
+ Same idea for `ines_rom_stats.py`, `ines_split_rom.py`, and `ines_analyze_rom.py`.
22
+
23
+ ### Scan
24
+
25
+ ```bash
26
+ ines_scan_roms.py /path/to/roms
27
+ ines_scan_roms.py /a /b --mapper 4 --show-all
28
+ ines_scan_roms.py /path/to/roms --format csv -o roms.csv
29
+ ines_scan_roms.py /path/to/roms --format csv -d ';' -o roms.csv
30
+ ines_scan_roms.py /path/to/roms --format csv --show-all -o roms-full.csv
31
+ ```
32
+
33
+ Filters: `--mapper`, `--mirroring H|V|F`, `--has-trainer`, `--min-prg` / `--max-prg`, `--min-chr` / `--max-chr` (KiB).
34
+
35
+ `--format text|html|csv|json` (default text). `-o` writes to a file. `--show-all` adds full header fields. For CSV, `-d` / `--delimiter` sets the separator (default `,`; use `;` for Excel with Russian locale, `tab` for TSV-style).
36
+
37
+ ### Stats
38
+
39
+ ```bash
40
+ ines_rom_stats.py /path/to/roms
41
+ ines_rom_stats.py /path/to/roms --json
42
+ ```
43
+
44
+ ### Split
45
+
46
+ ```bash
47
+ ines_split_rom.py game.nes
48
+ ines_split_rom.py roms.7z # prompts before overwrite; use --force to skip
49
+ ines_split_rom.py game.nes --pad-chr 64 # clone CHR to fill a 27C512 EPROM
50
+ ines_split_rom.py game.nes --pad-prg 128 --pad-chr 64
51
+ ```
52
+
53
+ `--pad-prg` / `--pad-chr` clone the image across the whole target size in KiB: for burning a larger EPROM the data then reads the same whatever the upper address lines return. The target must be an integer multiple of the image size; nothing is ever truncated.
54
+
55
+ ### Analyze
56
+
57
+ ```bash
58
+ ines_analyze_rom.py game.nes
59
+ ines_analyze_rom.py game.7z # GoodTools-style one-ROM archive (needs libarchive-c)
60
+ ines_analyze_rom.py game.nes --json
61
+ ```
62
+
63
+ Full report for one ROM file: file size, iNES header, and naming-convention tags parsed from the filename — GoodTools style (`(JU) [!] [b] [hIR] [T+Rus] (VS) (PC10)`) and No-Intro style (`(USA) (Rev A) (Beta 1) (En,Fr,De)`) — plus cross-checks between them: file size vs. header, filename region vs. TV system, `(VS)`/`(PC10)` vs. console type, `[!]` vs. header validity. For archives, tags come from the inner `.nes` name and sizes refer to the uncompressed ROM. Unrecognised tags are listed as unknown, never guessed.
64
+
65
+ ## Library
66
+
67
+ ```python
68
+ from ines_parser import parse_ines_header, parse_rom_filename
69
+
70
+ with open("game.nes", "rb") as f:
71
+ header = parse_ines_header(f.read(16))
72
+
73
+ if header and header.is_valid():
74
+ print(header)
75
+ print(header.detailed_str())
76
+
77
+ info = parse_rom_filename("Super Mario Bros. (JU) [!].nes")
78
+ print(info.title) # Super Mario Bros.
79
+ print(info.regions) # ('Japan', 'USA')
80
+ print(info.verified) # True
81
+ print(info.to_dict()) # JSON-friendly; adds expected_tv_system
82
+ ```
83
+
84
+ ## Docs
85
+
86
+ - `docs/iNES.md` — iNES header notes
87
+ - `docs/NES2.0.md` — NES 2.0 header layout
88
+ - `docs/List of iNES mappers.md` — mapper and submapper name tables (from `ines_parser/tables.py`)
89
+ - `docs/NES 2.0 lookups.md` — Vs. PPU/hardware, extended console, expansion device names
90
+ - [NESdev iNES](https://www.nesdev.org/wiki/INES)
91
+ - [NESdev NES 2.0](https://www.nesdev.org/wiki/NES_2.0)
92
+
93
+ ## License
94
+
95
+ MIT — see `LICENSE`.
@@ -2,7 +2,8 @@
2
2
  iNES Parser Library
3
3
 
4
4
  A Python library for parsing iNES format NES ROM files.
5
- Supports iNES 1.0, NES 2.0, Archaic iNES formats, and UNIF detection.
5
+ Supports iNES 1.0, NES 2.0, Archaic iNES formats, and UNIF detection,
6
+ plus GoodTools/No-Intro ROM filename conventions.
6
7
  """
7
8
 
8
9
  from .parser import (
@@ -17,6 +18,13 @@ from .parser import (
17
18
  INES_TRAINER_SIZE,
18
19
  )
19
20
 
21
+ from .filename import (
22
+ parse_rom_filename,
23
+ RomFilenameInfo,
24
+ DumpStatus,
25
+ expected_tv_system,
26
+ )
27
+
20
28
  from .tables import (
21
29
  get_mapper_name,
22
30
  get_mapper_alternate_names,
@@ -31,7 +39,7 @@ from .tables import (
31
39
  is_known_submapper,
32
40
  )
33
41
 
34
- __version__ = "1.4.0"
42
+ __version__ = "2.0.0"
35
43
  __author__ = "Leonid Kabanov"
36
44
  __all__ = [
37
45
  "parse_ines_header",
@@ -43,6 +51,10 @@ __all__ = [
43
51
  "CPUTiming",
44
52
  "INES_HEADER_SIZE",
45
53
  "INES_TRAINER_SIZE",
54
+ "parse_rom_filename",
55
+ "RomFilenameInfo",
56
+ "DumpStatus",
57
+ "expected_tv_system",
46
58
  "get_mapper_name",
47
59
  "get_mapper_alternate_names",
48
60
  "get_mapper_notes",
@@ -0,0 +1,468 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Full analysis of a single iNES ROM file.
4
+
5
+ Combines three sources of information about one ROM:
6
+
7
+ - the file itself (size),
8
+ - the iNES / NES 2.0 header,
9
+ - the filename's naming-convention tags (GoodTools / No-Intro style),
10
+
11
+ and cross-checks them against each other: file size vs. header sizes,
12
+ filename region vs. header TV system, (VS)/(PC10) markers vs. header console
13
+ type, [!] verified marker vs. header validity.
14
+
15
+ The ROM may sit inside an archive (.7z / .zip / .rar with libarchive-c
16
+ installed, GoodTools-style one-ROM archives): tags are then read from the
17
+ inner ROM name and sizes refer to the uncompressed ROM.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import sys
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
29
+
30
+ try:
31
+ import libarchive
32
+ except ImportError:
33
+ libarchive = None # type: ignore
34
+
35
+ from ines_parser import (
36
+ INES_HEADER_SIZE,
37
+ INES_TRAINER_SIZE,
38
+ ConsoleType,
39
+ INESFormat,
40
+ INESHeader,
41
+ parse_ines_header,
42
+ )
43
+ from ines_parser.cli.rom_fs import ALL_ARCHIVE_FORMATS, read_header_from_blocks
44
+ from ines_parser.filename import RomFilenameInfo, expected_tv_system, parse_rom_filename
45
+
46
+
47
+ def format_size(size_bytes: int) -> str:
48
+ return f"{size_bytes} bytes ({size_bytes / 1024:.1f} KiB)"
49
+
50
+
51
+ # Compact enum letters are fine for machine output; spell them out in the report.
52
+ _MIRRORING_NAMES = {"H": "Horizontal", "V": "Vertical", "F": "Four-screen"}
53
+
54
+
55
+ def analyze_file(path: Path) -> dict[str, Any]:
56
+ """Build the full report dict for one ROM file (.nes or an archive with one)."""
57
+ if path.suffix.lower() in ALL_ARCHIVE_FORMATS:
58
+ return _analyze_archive(path)
59
+
60
+ with open(path, "rb") as f:
61
+ raw_header = f.read(INES_HEADER_SIZE)
62
+ return _build_report(path.name, raw_header, path.stat().st_size, str(path))
63
+
64
+
65
+ def _analyze_archive(path: Path) -> dict[str, Any]:
66
+ """Analyze the first .nes member of an archive (GoodTools-style one-ROM archives)."""
67
+ if libarchive is None:
68
+ raise ValueError("archive support requires libarchive-c: pip install libarchive-c")
69
+
70
+ member_name: str | None = None
71
+ member_size = 0
72
+ header_bytes: bytes | None = None
73
+ nes_count = 0
74
+ with open(path, "rb") as f:
75
+ with libarchive.fd_reader(f.fileno()) as archive:
76
+ for entry in archive:
77
+ if not entry.isfile or not entry.name.lower().endswith(".nes"):
78
+ continue
79
+ nes_count += 1
80
+ if member_name is None:
81
+ member_name = entry.name
82
+ member_size = entry.size or 0
83
+ header_bytes = read_header_from_blocks(entry)
84
+
85
+ if member_name is None:
86
+ raise ValueError(f"no .nes ROM found inside {path.name}")
87
+
88
+ report = _build_report(
89
+ Path(member_name).name, header_bytes or b"", member_size, str(path)
90
+ )
91
+ report["file"]["archive_member"] = member_name
92
+ if nes_count > 1:
93
+ report["file"]["archive_member_count"] = nes_count
94
+ return report
95
+
96
+
97
+ def _build_report(
98
+ member_name: str,
99
+ raw_header: bytes,
100
+ rom_size: int,
101
+ path: str,
102
+ ) -> dict[str, Any]:
103
+ header: INESHeader | None = None
104
+ header_dict: dict[str, Any] | None
105
+ if len(raw_header) < INES_HEADER_SIZE:
106
+ header_dict = {
107
+ "valid": False,
108
+ "error": f"file too short for a {INES_HEADER_SIZE}-byte header",
109
+ }
110
+ else:
111
+ header = parse_ines_header(raw_header)
112
+ header_dict = header.to_dict() if header is not None else None
113
+
114
+ name_info = parse_rom_filename(member_name)
115
+
116
+ return {
117
+ "schema_version": 1,
118
+ "file": {
119
+ "path": path,
120
+ "size_bytes": rom_size,
121
+ },
122
+ "filename": name_info.to_dict(),
123
+ "header": header_dict,
124
+ "cross_checks": build_cross_checks(name_info, header, rom_size),
125
+ # Runtime-only helper for the text renderer; stripped from JSON output.
126
+ "_filename_info": name_info,
127
+ }
128
+
129
+
130
+ def _check(name: str, status: str, detail: str) -> dict[str, str]:
131
+ return {"check": name, "status": status, "detail": detail}
132
+
133
+
134
+ def build_cross_checks(
135
+ name_info: RomFilenameInfo,
136
+ header: INESHeader | None,
137
+ file_size: int,
138
+ ) -> list[dict[str, str]]:
139
+ """Compare filename facts, header fields and the actual file size."""
140
+ checks: list[dict[str, str]] = []
141
+ header_valid = header is not None and header.is_valid()
142
+
143
+ # --- File size vs sizes declared in the header ---
144
+ if header is not None and header.is_valid():
145
+ expected = (
146
+ INES_HEADER_SIZE
147
+ + (INES_TRAINER_SIZE if header.has_trainer else 0)
148
+ + header.prg_rom_size
149
+ + header.chr_rom_size
150
+ )
151
+ parts = [
152
+ f"{INES_HEADER_SIZE} header",
153
+ f"{header.prg_rom_size} PRG",
154
+ f"{header.chr_rom_size} CHR",
155
+ ]
156
+ if header.has_trainer:
157
+ parts.insert(1, f"{INES_TRAINER_SIZE} trainer")
158
+ composition = " + ".join(parts)
159
+ if header.misc_rom_count:
160
+ checks.append(_check(
161
+ "file size vs header",
162
+ "skipped",
163
+ "header declares miscellaneous ROMs of unstated size",
164
+ ))
165
+ elif file_size == expected:
166
+ checks.append(_check(
167
+ "file size vs header", "ok", f"exactly {composition}"
168
+ ))
169
+ elif file_size > expected:
170
+ checks.append(_check(
171
+ "file size vs header",
172
+ "warning",
173
+ f"{file_size - expected} trailing byte(s) beyond {composition}",
174
+ ))
175
+ else:
176
+ checks.append(_check(
177
+ "file size vs header",
178
+ "warning",
179
+ f"file is {expected - file_size} byte(s) shorter than {composition}",
180
+ ))
181
+
182
+ # --- Filename region vs header TV system ---
183
+ tv_system = header.tv_system
184
+ if tv_system is not None:
185
+ note = "" if header.format == INESFormat.NES_2_0 else \
186
+ " (iNES 1.0 TV bits are unofficial)"
187
+ expected_tv = expected_tv_system(name_info.regions)
188
+ if not name_info.regions:
189
+ checks.append(_check(
190
+ "filename region vs TV system",
191
+ "skipped",
192
+ "no region tags in the filename",
193
+ ))
194
+ elif expected_tv is None:
195
+ checks.append(_check(
196
+ "filename region vs TV system",
197
+ "skipped",
198
+ f"regions {', '.join(name_info.regions)} do not imply a single TV system",
199
+ ))
200
+ elif tv_system.value not in ("NTSC", "PAL"):
201
+ checks.append(_check(
202
+ "filename region vs TV system",
203
+ "skipped",
204
+ f"header TV system {tv_system.value} is not directly comparable",
205
+ ))
206
+ elif expected_tv == tv_system.value:
207
+ checks.append(_check(
208
+ "filename region vs TV system",
209
+ "ok",
210
+ f"{', '.join(name_info.regions)} imply {expected_tv}; "
211
+ f"header says {tv_system.value}{note}",
212
+ ))
213
+ else:
214
+ checks.append(_check(
215
+ "filename region vs TV system",
216
+ "warning",
217
+ f"{', '.join(name_info.regions)} imply {expected_tv}, "
218
+ f"but header says {tv_system.value}{note}",
219
+ ))
220
+
221
+ # --- (VS) / (PC10) filename markers vs header console type ---
222
+ header_is_vs = (
223
+ header.console_type == ConsoleType.VS_SYSTEM or header.is_vs_unisystem
224
+ )
225
+ if name_info.is_vs or header_is_vs:
226
+ both = name_info.is_vs and header_is_vs
227
+ checks.append(_check(
228
+ "Vs. System marker vs header console type",
229
+ "ok" if both else "warning",
230
+ "filename (VS) and header console type agree"
231
+ if both
232
+ else "filename (VS) marker" if name_info.is_vs
233
+ else "header console type says Vs. System",
234
+ ))
235
+
236
+ header_is_pc10 = (
237
+ header.console_type == ConsoleType.PLAYCHOICE_10 or header.is_playchoice_10
238
+ )
239
+ if name_info.is_playchoice or header_is_pc10:
240
+ both = name_info.is_playchoice and header_is_pc10
241
+ checks.append(_check(
242
+ "PlayChoice-10 marker vs header console type",
243
+ "ok" if both else "warning",
244
+ "filename (PC10) and header console type agree"
245
+ if both
246
+ else "filename (PC10) marker" if name_info.is_playchoice
247
+ else "header console type says PlayChoice-10",
248
+ ))
249
+
250
+ # --- [!] verified dump vs header validity ---
251
+ if name_info.verified:
252
+ if header_valid:
253
+ checks.append(_check(
254
+ "verified dump marker vs header",
255
+ "ok",
256
+ "[!] claims a verified dump; header is a valid iNES image",
257
+ ))
258
+ else:
259
+ checks.append(_check(
260
+ "verified dump marker vs header",
261
+ "warning",
262
+ "[!] claims a verified dump, but the header is not a valid iNES image",
263
+ ))
264
+
265
+ return checks
266
+
267
+
268
+ def filename_lines(info: RomFilenameInfo) -> list[tuple[str, str]]:
269
+ """(label, value) pairs for the text report; only non-default facts."""
270
+ lines: list[tuple[str, str]] = []
271
+
272
+ def add(label: str, value: str) -> None:
273
+ lines.append((label, value))
274
+
275
+ if info.regions:
276
+ add("Regions", ", ".join(info.regions))
277
+ if info.languages:
278
+ add("Languages", ", ".join(info.languages))
279
+ add("Dump status", info.dump_status.value)
280
+ extra_flags = [f for f in info.dump_flags if f != info.dump_status.value]
281
+ if extra_flags:
282
+ add("Dump flags", ", ".join(extra_flags))
283
+ if info.is_hack:
284
+ add("Hack", f"yes ({info.hack_tag})" if info.hack_tag else "yes")
285
+ if info.is_translation:
286
+ marker = "+" if info.translation_is_newer else "-"
287
+ language = info.translation_language or "?"
288
+ add("Translation", f"[T{marker}{language}]")
289
+ if info.is_unlicensed:
290
+ add("Unlicensed", "yes")
291
+ if info.is_public_domain:
292
+ add("Public domain", "yes")
293
+ if info.is_vs:
294
+ add("Vs. System", "yes")
295
+ if info.is_playchoice:
296
+ add("PlayChoice-10", "yes")
297
+ if info.is_nintendo_power:
298
+ add("Nintendo Power", "yes")
299
+ if info.multipart_index is not None:
300
+ add("Multipart", str(info.multipart_index))
301
+ if info.prerelease:
302
+ suffix = f" {info.prerelease_index}" if info.prerelease_index else ""
303
+ add("Prerelease", f"{info.prerelease}{suffix}")
304
+ if info.revision:
305
+ add("Revision", info.revision)
306
+ if info.version:
307
+ add("Version", info.version)
308
+ return lines
309
+
310
+
311
+ def header_lines(header: dict[str, Any]) -> list[tuple[str, str]]:
312
+ """(label, value) pairs for the text report.
313
+
314
+ Mirrors the field selection of ``INESHeader.detailed_str()`` but yields one
315
+ line per field; facts equal to their default (no battery, no trainer, ...) are
316
+ omitted.
317
+ """
318
+ lines: list[tuple[str, str]] = []
319
+
320
+ def add(label: str, value: object) -> None:
321
+ lines.append((label, str(value)))
322
+
323
+ def kib(size_bytes: int) -> str:
324
+ return f"{size_bytes // 1024} KiB"
325
+
326
+ def labeled(number: object, name: object) -> str:
327
+ return f"{number} ({name})" if name else str(number)
328
+
329
+ add("Format", header["format"])
330
+ add("Mapper", labeled(header["mapper"], header["mapper_name"]))
331
+ if header.get("mapper_alternates"):
332
+ add("Alt names", ", ".join(header["mapper_alternates"]))
333
+ if header.get("mapper_notes"):
334
+ add("Notes", header["mapper_notes"])
335
+ # Submapper 0 is the plain "no distinct submapper" default: skip it.
336
+ if header.get("submapper"):
337
+ add("Submapper", labeled(header["submapper"], header.get("submapper_name")))
338
+ add("Mirroring", _MIRRORING_NAMES.get(header["mirroring"], header["mirroring"]))
339
+ add("PRG ROM", kib(header["prg_rom_size"]))
340
+ add("CHR ROM", kib(header["chr_rom_size"]))
341
+ for label, key in (
342
+ ("PRG RAM", "prg_ram_size"),
343
+ ("PRG NVRAM", "prg_nvram_size"),
344
+ ("CHR RAM", "chr_ram_size"),
345
+ ("CHR NVRAM", "chr_nvram_size"),
346
+ ):
347
+ if header.get(key):
348
+ add(label, kib(header[key]))
349
+ if header.get("cpu_timing"):
350
+ add("CPU timing", header["cpu_timing"])
351
+ if header.get("vs_ppu_type") is not None:
352
+ add("Vs. PPU type", labeled(header["vs_ppu_type"], header.get("vs_ppu_type_name")))
353
+ if header.get("vs_hw_type") is not None:
354
+ add("Vs. hardware", labeled(header["vs_hw_type"], header.get("vs_hw_type_name")))
355
+ if header.get("extended_console_type") is not None:
356
+ add("Ext. console", header.get("extended_console_type_name") or header["extended_console_type"])
357
+ if header.get("misc_rom_count"):
358
+ add("Misc ROMs", header["misc_rom_count"])
359
+ if header.get("has_trainer"):
360
+ add("Trainer", "yes")
361
+ if header.get("has_battery"):
362
+ add("Battery", "yes")
363
+ if header.get("four_screen"):
364
+ add("Four-screen", "yes")
365
+ add("Nametable bit 0", "yes" if header.get("nametable_bit0") else "no")
366
+ if header.get("is_vs_unisystem"):
367
+ add("Vs. Unisystem", "yes")
368
+ if header.get("is_playchoice_10"):
369
+ add("PlayChoice-10", "yes")
370
+ if header.get("console_type") and header["console_type"] != "NES/Famicom":
371
+ add("Console type", header["console_type"])
372
+ if header.get("tv_system"):
373
+ add("TV system", header["tv_system"])
374
+ if "has_bus_conflicts" in header and header.get("format") != "NES 2.0":
375
+ add("Bus conflicts", "yes" if header["has_bus_conflicts"] else "no")
376
+ return lines
377
+
378
+
379
+ def print_text_report(report: dict[str, Any]) -> None:
380
+ file_info = report["file"]
381
+ print(f"File: {file_info['path']}")
382
+ print(f"Size: {format_size(file_info['size_bytes'])}")
383
+ member = file_info.get("archive_member")
384
+ if member:
385
+ count = file_info.get("archive_member_count")
386
+ note = f" (1 of {count} .nes members)" if count else ""
387
+ print(f"Member: {member}{note}")
388
+
389
+ name_dict = report["filename"]
390
+ print("\nFilename analysis")
391
+ print(f" {'Title:':16} {name_dict['title']}")
392
+ for label, value in filename_lines(report["_filename_info"]):
393
+ print(f" {label + ':':16} {value}")
394
+ if name_dict.get("unknown_tokens"):
395
+ print(f" {'Unknown tokens:':16} {' '.join(name_dict['unknown_tokens'])}")
396
+
397
+ print("\niNES header")
398
+ header_dict = report["header"]
399
+ if header_dict is None:
400
+ print(" no header (file too short)")
401
+ elif not header_dict.get("valid"):
402
+ detail = header_dict.get("error") or header_dict.get("format", "unknown")
403
+ print(f" not a valid iNES image ({detail})")
404
+ else:
405
+ for label, value in header_lines(header_dict):
406
+ print(f" {label + ':':16} {value}")
407
+
408
+ print("\nCross-checks")
409
+ checks = report["cross_checks"]
410
+ if not checks:
411
+ print(" (none; header not valid or nothing to compare)")
412
+ return
413
+ for check in checks:
414
+ print(f" {check['status'].upper():8} {check['check']}: {check['detail']}")
415
+
416
+
417
+ def build_argument_parser() -> argparse.ArgumentParser:
418
+ parser = argparse.ArgumentParser(
419
+ prog="ines_analyze_rom.py",
420
+ description="Full analysis of a single ROM: header, filename tags, cross-checks",
421
+ )
422
+ parser.add_argument(
423
+ "rom",
424
+ metavar="ROM",
425
+ help=(
426
+ "Path to the ROM file (.nes) or an archive containing one "
427
+ "(.7z/.zip/.rar; requires libarchive-c)"
428
+ ),
429
+ )
430
+ parser.add_argument(
431
+ "--json",
432
+ action="store_true",
433
+ help="Print machine-readable JSON instead of the text report",
434
+ )
435
+ return parser
436
+
437
+
438
+ def main() -> int:
439
+ parser = build_argument_parser()
440
+ args = parser.parse_args()
441
+
442
+ path = Path(args.rom)
443
+ if not path.exists():
444
+ print(f"Error: File does not exist: {args.rom}", file=sys.stderr)
445
+ return 1
446
+ if not path.is_file():
447
+ print(f"Error: Not a file: {args.rom}", file=sys.stderr)
448
+ return 1
449
+
450
+ try:
451
+ report = analyze_file(path)
452
+ except OSError as exc:
453
+ print(f"Error: Cannot read {args.rom}: {exc}", file=sys.stderr)
454
+ return 1
455
+ except ValueError as exc:
456
+ print(f"Error: {exc}", file=sys.stderr)
457
+ return 1
458
+
459
+ if args.json:
460
+ public = {k: v for k, v in report.items() if not k.startswith("_")}
461
+ print(json.dumps(public, indent=2))
462
+ else:
463
+ print_text_report(report)
464
+ return 0
465
+
466
+
467
+ if __name__ == "__main__":
468
+ sys.exit(main())