ines-parser 1.5.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 (25) hide show
  1. {ines_parser-1.5.0 → ines_parser-2.0.0}/PKG-INFO +9 -2
  2. {ines_parser-1.5.0 → ines_parser-2.0.0}/README.md +8 -1
  3. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/__init__.py +1 -1
  4. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/ines_analyze_rom.py +149 -10
  5. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/ines_scan_roms.py +2 -0
  6. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/ines_split_rom.py +108 -17
  7. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/parser.py +9 -10
  8. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/PKG-INFO +9 -2
  9. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/SOURCES.txt +2 -1
  10. {ines_parser-1.5.0 → ines_parser-2.0.0}/pyproject.toml +1 -1
  11. ines_parser-2.0.0/tests/test_parser.py +91 -0
  12. {ines_parser-1.5.0 → ines_parser-2.0.0}/LICENSE +0 -0
  13. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/__init__.py +0 -0
  14. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/ines_rom_stats.py +0 -0
  15. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/cli/rom_fs.py +0 -0
  16. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/filename.py +0 -0
  17. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/mappers.py +0 -0
  18. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/py.typed +0 -0
  19. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser/tables.py +0 -0
  20. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/dependency_links.txt +0 -0
  21. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/entry_points.txt +0 -0
  22. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/requires.txt +0 -0
  23. {ines_parser-1.5.0 → ines_parser-2.0.0}/ines_parser.egg-info/top_level.txt +0 -0
  24. {ines_parser-1.5.0 → ines_parser-2.0.0}/setup.cfg +0 -0
  25. {ines_parser-1.5.0 → ines_parser-2.0.0}/tests/test_filename.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ines-parser
3
- Version: 1.5.0
3
+ Version: 2.0.0
4
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
@@ -30,6 +30,8 @@ Dynamic: license-file
30
30
 
31
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
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).
34
+
33
35
  ```bash
34
36
  pip install ines-parser
35
37
  pip install "ines-parser[archive]" # optional: .7z / .zip / .rar
@@ -72,16 +74,21 @@ 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
75
79
  ```
76
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
+
77
83
  ### Analyze
78
84
 
79
85
  ```bash
80
86
  ines_analyze_rom.py game.nes
87
+ ines_analyze_rom.py game.7z # GoodTools-style one-ROM archive (needs libarchive-c)
81
88
  ines_analyze_rom.py game.nes --json
82
89
  ```
83
90
 
84
- 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. Unrecognised tags are listed as unknown, never guessed.
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.
85
92
 
86
93
  ## Library
87
94
 
@@ -2,6 +2,8 @@
2
2
 
3
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
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
+
5
7
  ```bash
6
8
  pip install ines-parser
7
9
  pip install "ines-parser[archive]" # optional: .7z / .zip / .rar
@@ -44,16 +46,21 @@ ines_rom_stats.py /path/to/roms --json
44
46
  ```bash
45
47
  ines_split_rom.py game.nes
46
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
47
51
  ```
48
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
+
49
55
  ### Analyze
50
56
 
51
57
  ```bash
52
58
  ines_analyze_rom.py game.nes
59
+ ines_analyze_rom.py game.7z # GoodTools-style one-ROM archive (needs libarchive-c)
53
60
  ines_analyze_rom.py game.nes --json
54
61
  ```
55
62
 
56
- 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. Unrecognised tags are listed as unknown, never guessed.
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.
57
64
 
58
65
  ## Library
59
66
 
@@ -39,7 +39,7 @@ from .tables import (
39
39
  is_known_submapper,
40
40
  )
41
41
 
42
- __version__ = "1.5.0"
42
+ __version__ = "2.0.0"
43
43
  __author__ = "Leonid Kabanov"
44
44
  __all__ = [
45
45
  "parse_ines_header",
@@ -11,6 +11,10 @@ Combines three sources of information about one ROM:
11
11
  and cross-checks them against each other: file size vs. header sizes,
12
12
  filename region vs. header TV system, (VS)/(PC10) markers vs. header console
13
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.
14
18
  """
15
19
 
16
20
  from __future__ import annotations
@@ -23,6 +27,11 @@ from typing import Any
23
27
 
24
28
  sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
25
29
 
30
+ try:
31
+ import libarchive
32
+ except ImportError:
33
+ libarchive = None # type: ignore
34
+
26
35
  from ines_parser import (
27
36
  INES_HEADER_SIZE,
28
37
  INES_TRAINER_SIZE,
@@ -31,6 +40,7 @@ from ines_parser import (
31
40
  INESHeader,
32
41
  parse_ines_header,
33
42
  )
43
+ from ines_parser.cli.rom_fs import ALL_ARCHIVE_FORMATS, read_header_from_blocks
34
44
  from ines_parser.filename import RomFilenameInfo, expected_tv_system, parse_rom_filename
35
45
 
36
46
 
@@ -38,12 +48,58 @@ def format_size(size_bytes: int) -> str:
38
48
  return f"{size_bytes} bytes ({size_bytes / 1024:.1f} KiB)"
39
49
 
40
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
+
41
55
  def analyze_file(path: Path) -> dict[str, Any]:
42
- """Build the full report dict for one ROM file."""
43
- file_size = path.stat().st_size
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
+
44
60
  with open(path, "rb") as f:
45
61
  raw_header = f.read(INES_HEADER_SIZE)
62
+ return _build_report(path.name, raw_header, path.stat().st_size, str(path))
46
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]:
47
103
  header: INESHeader | None = None
48
104
  header_dict: dict[str, Any] | None
49
105
  if len(raw_header) < INES_HEADER_SIZE:
@@ -55,20 +111,19 @@ def analyze_file(path: Path) -> dict[str, Any]:
55
111
  header = parse_ines_header(raw_header)
56
112
  header_dict = header.to_dict() if header is not None else None
57
113
 
58
- name_info = parse_rom_filename(path.name)
114
+ name_info = parse_rom_filename(member_name)
59
115
 
60
116
  return {
61
117
  "schema_version": 1,
62
118
  "file": {
63
- "path": str(path),
64
- "size_bytes": file_size,
119
+ "path": path,
120
+ "size_bytes": rom_size,
65
121
  },
66
122
  "filename": name_info.to_dict(),
67
123
  "header": header_dict,
68
- "cross_checks": build_cross_checks(name_info, header, file_size),
69
- # Runtime-only helpers for the text renderer; stripped from JSON output.
124
+ "cross_checks": build_cross_checks(name_info, header, rom_size),
125
+ # Runtime-only helper for the text renderer; stripped from JSON output.
70
126
  "_filename_info": name_info,
71
- "_header_object": header,
72
127
  }
73
128
 
74
129
 
@@ -253,10 +308,83 @@ def filename_lines(info: RomFilenameInfo) -> list[tuple[str, str]]:
253
308
  return lines
254
309
 
255
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
+
256
379
  def print_text_report(report: dict[str, Any]) -> None:
257
380
  file_info = report["file"]
258
381
  print(f"File: {file_info['path']}")
259
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}")
260
388
 
261
389
  name_dict = report["filename"]
262
390
  print("\nFilename analysis")
@@ -274,7 +402,8 @@ def print_text_report(report: dict[str, Any]) -> None:
274
402
  detail = header_dict.get("error") or header_dict.get("format", "unknown")
275
403
  print(f" not a valid iNES image ({detail})")
276
404
  else:
277
- print(f" {report['_header_object'].detailed_str()}")
405
+ for label, value in header_lines(header_dict):
406
+ print(f" {label + ':':16} {value}")
278
407
 
279
408
  print("\nCross-checks")
280
409
  checks = report["cross_checks"]
@@ -290,7 +419,14 @@ def build_argument_parser() -> argparse.ArgumentParser:
290
419
  prog="ines_analyze_rom.py",
291
420
  description="Full analysis of a single ROM: header, filename tags, cross-checks",
292
421
  )
293
- parser.add_argument("rom", metavar="ROM", help="Path to the ROM file (.nes)")
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
+ )
294
430
  parser.add_argument(
295
431
  "--json",
296
432
  action="store_true",
@@ -316,6 +452,9 @@ def main() -> int:
316
452
  except OSError as exc:
317
453
  print(f"Error: Cannot read {args.rom}: {exc}", file=sys.stderr)
318
454
  return 1
455
+ except ValueError as exc:
456
+ print(f"Error: {exc}", file=sys.stderr)
457
+ return 1
319
458
 
320
459
  if args.json:
321
460
  public = {k: v for k, v in report.items() if not k.startswith("_")}
@@ -73,6 +73,7 @@ _FULL_COLUMNS = (
73
73
  "has_battery",
74
74
  "has_trainer",
75
75
  "four_screen",
76
+ "nametable_bit0",
76
77
  "is_vs_unisystem",
77
78
  "is_playchoice_10",
78
79
  "console_type",
@@ -112,6 +113,7 @@ _COLUMN_LABELS = {
112
113
  "has_battery": "Has Battery",
113
114
  "has_trainer": "Has Trainer",
114
115
  "four_screen": "Four Screen",
116
+ "nametable_bit0": "Nametable Bit 0",
115
117
  "is_vs_unisystem": "Vs Unisystem",
116
118
  "is_playchoice_10": "PlayChoice-10",
117
119
  "console_type": "Console Type",
@@ -3,7 +3,8 @@
3
3
  Split iNES ROM files into PRG and CHR components.
4
4
 
5
5
  This script extracts PRG ROM and CHR ROM from iNES format files,
6
- supporting both plain .nes files and .7z archives.
6
+ supporting both plain .nes files and .7z archives. Outputs can be cloned
7
+ up to a target size (e.g. an EPROM like 27C512) with --pad-prg / --pad-chr.
7
8
  """
8
9
 
9
10
  import argparse
@@ -11,7 +12,7 @@ import io
11
12
  import os
12
13
  import sys
13
14
  from pathlib import Path
14
- from typing import BinaryIO, Tuple
15
+ from typing import BinaryIO, Optional, Tuple
15
16
 
16
17
  # Repo root on path when running this file directly (not via pip console_scripts)
17
18
  sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
@@ -36,6 +37,36 @@ class ROMExtractionError(Exception):
36
37
  pass
37
38
 
38
39
 
40
+ def mirror_to(data: bytes, target_size: int, label: str) -> bytes:
41
+ """
42
+ Repeat ``data`` until it fills ``target_size``.
43
+
44
+ Useful when burning onto a larger EPROM: with the image cloned across the
45
+ whole chip, the data is the same whatever the upper address lines read.
46
+ The target must be an integer multiple of the image size (or equal to it).
47
+ """
48
+ if target_size < len(data):
49
+ raise ROMExtractionError(
50
+ f"{label} is {len(data)} bytes; cannot pad down to {target_size}"
51
+ )
52
+ if target_size == len(data):
53
+ return data
54
+ if target_size % len(data) != 0:
55
+ raise ROMExtractionError(
56
+ f"{label} is {len(data)} bytes; {target_size} is not an integer multiple, "
57
+ "cannot mirror evenly"
58
+ )
59
+ return data * (target_size // len(data))
60
+
61
+
62
+ def apply_padding(data: bytes, target_kib: int, label: str) -> Tuple[bytes, str]:
63
+ """Clone ``data`` up to ``target_kib``; returns (data, output note)."""
64
+ result = mirror_to(data, target_kib * 1024, label)
65
+ if len(result) == len(data):
66
+ return result, ""
67
+ return result, f", mirrored to {len(result)}"
68
+
69
+
39
70
  def generate_output_filenames(input_filename: str) -> Tuple[str, str]:
40
71
  """
41
72
  Generate output filenames for PRG and CHR ROM files.
@@ -113,15 +144,23 @@ def check_overwrite_permission(prg_fname: str, chr_fname: str, force: bool,
113
144
  return response in ('y', 'yes')
114
145
 
115
146
 
116
- def extract_rom_data(file_name: str, nes_file: BinaryIO, force: bool = False) -> None:
147
+ def extract_rom_data(
148
+ file_name: str,
149
+ nes_file: BinaryIO,
150
+ force: bool = False,
151
+ pad_prg_kib: Optional[int] = None,
152
+ pad_chr_kib: Optional[int] = None,
153
+ ) -> None:
117
154
  """
118
155
  Extract PRG and CHR ROM data from an iNES file.
119
-
156
+
120
157
  Args:
121
158
  file_name: Name of the ROM file (for output naming)
122
159
  nes_file: File-like object containing the ROM data
123
160
  force: If True, overwrite existing files without confirmation
124
-
161
+ pad_prg_kib: Clone the PRG output up to this size in KiB (None keeps it as-is)
162
+ pad_chr_kib: Clone the CHR output up to this size in KiB (None keeps it as-is)
163
+
125
164
  Raises:
126
165
  ROMExtractionError: If extraction fails or overwrite denied
127
166
  """
@@ -161,10 +200,15 @@ def extract_rom_data(file_name: str, nes_file: BinaryIO, force: bool = False) ->
161
200
  raise ROMExtractionError(
162
201
  f"EOF reached while reading PRG part: expected {header.prg_rom_size} bytes, got {len(prg_data)}"
163
202
  )
203
+ prg_note = ""
204
+ if pad_prg_kib is not None:
205
+ prg_data, prg_note = apply_padding(prg_data, pad_prg_kib, "PRG ROM")
164
206
  with open(prg_fname, 'wb') as prg:
165
207
  prg.write(prg_data)
166
- print(f"Extracted PRG ROM: {prg_fname} ({header.prg_rom_size} bytes)")
167
-
208
+ print(f"Extracted PRG ROM: {prg_fname} ({header.prg_rom_size} bytes{prg_note})")
209
+ elif pad_prg_kib is not None:
210
+ raise ROMExtractionError("--pad-prg given, but this ROM has no PRG ROM")
211
+
168
212
  # Extract CHR ROM
169
213
  if header.chr_rom_size > 0:
170
214
  chr_data = nes_file.read(header.chr_rom_size)
@@ -172,9 +216,14 @@ def extract_rom_data(file_name: str, nes_file: BinaryIO, force: bool = False) ->
172
216
  raise ROMExtractionError(
173
217
  f"EOF reached while reading CHR part: expected {header.chr_rom_size} bytes, got {len(chr_data)}"
174
218
  )
219
+ chr_note = ""
220
+ if pad_chr_kib is not None:
221
+ chr_data, chr_note = apply_padding(chr_data, pad_chr_kib, "CHR ROM")
175
222
  with open(chr_fname, 'wb') as chr_file:
176
223
  chr_file.write(chr_data)
177
- print(f"Extracted CHR ROM: {chr_fname} ({header.chr_rom_size} bytes)")
224
+ print(f"Extracted CHR ROM: {chr_fname} ({header.chr_rom_size} bytes{chr_note})")
225
+ elif pad_chr_kib is not None:
226
+ raise ROMExtractionError("--pad-chr given, but this ROM has no CHR ROM (CHR-RAM game?)")
178
227
 
179
228
  # Verify we've read at least the expected amount of data.
180
229
  # Extra trailing data is allowed, but we report it for visibility.
@@ -192,14 +241,21 @@ def extract_rom_data(file_name: str, nes_file: BinaryIO, force: bool = False) ->
192
241
  )
193
242
 
194
243
 
195
- def process_archive(filename: str, force: bool = False) -> None:
244
+ def process_archive(
245
+ filename: str,
246
+ force: bool = False,
247
+ pad_prg_kib: Optional[int] = None,
248
+ pad_chr_kib: Optional[int] = None,
249
+ ) -> None:
196
250
  """
197
251
  Process an archive (.7z, .zip, or .rar) and extract the first .nes ROM file.
198
-
252
+
199
253
  Args:
200
254
  filename: Path to the archive
201
255
  force: If True, overwrite existing files without confirmation
202
-
256
+ pad_prg_kib: Clone the PRG output up to this size in KiB (None keeps it as-is)
257
+ pad_chr_kib: Clone the CHR output up to this size in KiB (None keeps it as-is)
258
+
203
259
  Raises:
204
260
  ROMExtractionError: If processing fails or libarchive not available
205
261
  """
@@ -242,20 +298,27 @@ def process_archive(filename: str, force: bool = False) -> None:
242
298
 
243
299
  # Create BytesIO object and extract
244
300
  bio = io.BytesIO(data)
245
- extract_rom_data(entry.name, bio, force)
301
+ extract_rom_data(entry.name, bio, force, pad_prg_kib, pad_chr_kib)
246
302
  return
247
303
 
248
304
 
249
- def process_nes_file(filename: str, force: bool = False) -> None:
305
+ def process_nes_file(
306
+ filename: str,
307
+ force: bool = False,
308
+ pad_prg_kib: Optional[int] = None,
309
+ pad_chr_kib: Optional[int] = None,
310
+ ) -> None:
250
311
  """
251
312
  Process a plain .nes file.
252
-
313
+
253
314
  Args:
254
315
  filename: Path to the .nes file
255
316
  force: If True, overwrite existing files without confirmation
317
+ pad_prg_kib: Clone the PRG output up to this size in KiB (None keeps it as-is)
318
+ pad_chr_kib: Clone the CHR output up to this size in KiB (None keeps it as-is)
256
319
  """
257
320
  with open(filename, "rb") as nes_file:
258
- extract_rom_data(filename, nes_file, force)
321
+ extract_rom_data(filename, nes_file, force, pad_prg_kib, pad_chr_kib)
259
322
 
260
323
 
261
324
  def parse_arguments() -> argparse.Namespace:
@@ -281,6 +344,24 @@ def parse_arguments() -> argparse.Namespace:
281
344
  action='store_true',
282
345
  help='Overwrite existing output files without confirmation'
283
346
  )
347
+ parser.add_argument(
348
+ '--pad-prg',
349
+ type=int,
350
+ metavar='KIB',
351
+ help=(
352
+ 'Clone the PRG image up to this size in KiB (e.g. 64 for a 27C512 EPROM); '
353
+ 'the target must be an integer multiple of the image size, never truncates'
354
+ )
355
+ )
356
+ parser.add_argument(
357
+ '--pad-chr',
358
+ type=int,
359
+ metavar='KIB',
360
+ help=(
361
+ 'Clone the CHR image up to this size in KiB (e.g. 64 for a 27C512 EPROM); '
362
+ 'the target must be an integer multiple of the image size, never truncates'
363
+ )
364
+ )
284
365
  return parser.parse_args()
285
366
 
286
367
 
@@ -317,9 +398,19 @@ def main() -> int:
317
398
  print(f"Error: Unsupported file extension: {file_ext}", file=sys.stderr)
318
399
  print("For archive format support, install libarchive-c: pip install libarchive-c", file=sys.stderr)
319
400
  return 1
320
- process_archive(args.filename, force=args.force)
401
+ process_archive(
402
+ args.filename,
403
+ force=args.force,
404
+ pad_prg_kib=args.pad_prg,
405
+ pad_chr_kib=args.pad_chr,
406
+ )
321
407
  elif file_ext == '.nes':
322
- process_nes_file(args.filename, force=args.force)
408
+ process_nes_file(
409
+ args.filename,
410
+ force=args.force,
411
+ pad_prg_kib=args.pad_prg,
412
+ pad_chr_kib=args.pad_chr,
413
+ )
323
414
  else:
324
415
  print(f"Error: Unsupported file extension: {file_ext}", file=sys.stderr)
325
416
  all_extensions = SUPPORTED_EXTENSIONS | ARCHIVE_EXTENSIONS
@@ -92,6 +92,10 @@ class INESHeader:
92
92
  self.has_battery = bool(flags6 & 0x02)
93
93
  self.has_trainer = bool(flags6 & 0x04)
94
94
  self.four_screen = bool(flags6 & 0x08)
95
+ # Raw value of flags-6 bit 0 (hard-wired nametable arrangement). It is
96
+ # normally implied by `mirroring`, but mappers like 30 and 218 combine
97
+ # it with the four-screen bit, so it is exposed separately.
98
+ self.nametable_bit0 = bool(flags6 & 0x01)
95
99
  mapper_low = (flags6 & 0xF0) >> 4
96
100
 
97
101
  # Parse Flags 7
@@ -337,28 +341,20 @@ class INESHeader:
337
341
  def to_dict(self) -> Dict[str, Any]:
338
342
  """
339
343
  Convert header to dictionary for easy access.
340
-
341
- ``prg_rom_size_kib`` and ``chr_rom_size_kib`` are deprecated; prefer
342
- ``prg_rom_size // 1024`` and ``chr_rom_size // 1024``. They remain in
343
- 1.x for compatibility and are planned for removal in 2.0.
344
344
  """
345
345
  if not self.is_valid():
346
346
  return {
347
347
  'format': self.format.value,
348
348
  'valid': False
349
349
  }
350
-
350
+
351
351
  mapper_info = self.get_mapper_info()
352
-
352
+
353
353
  result = {
354
354
  'format': self.format.value,
355
355
  'valid': True,
356
356
  'prg_rom_size': self.prg_rom_size,
357
357
  'chr_rom_size': self.chr_rom_size,
358
- # Deprecated: use prg_rom_size // 1024 and chr_rom_size // 1024.
359
- # Kept for 1.x compatibility; planned removal in 2.0.
360
- 'prg_rom_size_kib': self.prg_rom_size // 1024,
361
- 'chr_rom_size_kib': self.chr_rom_size // 1024,
362
358
  'mapper': self.mapper,
363
359
  'mapper_name': mapper_info['name'],
364
360
  'mapper_alternates': mapper_info['alternates'],
@@ -367,6 +363,7 @@ class INESHeader:
367
363
  'has_battery': self.has_battery,
368
364
  'has_trainer': self.has_trainer,
369
365
  'four_screen': self.four_screen,
366
+ 'nametable_bit0': self.nametable_bit0,
370
367
  'is_vs_unisystem': self.is_vs_unisystem,
371
368
  'is_playchoice_10': self.is_playchoice_10,
372
369
  'console_type': self.console_type.value,
@@ -488,6 +485,8 @@ class INESHeader:
488
485
  parts.append("Trainer: Yes")
489
486
  if self.has_battery:
490
487
  parts.append("Battery: Yes")
488
+ if self.four_screen:
489
+ parts.append(f"Nametable bit 0: {self.nametable_bit0}")
491
490
  if self.is_vs_unisystem:
492
491
  parts.append("VS Unisystem")
493
492
  if self.is_playchoice_10:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ines-parser
3
- Version: 1.5.0
3
+ Version: 2.0.0
4
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
@@ -30,6 +30,8 @@ Dynamic: license-file
30
30
 
31
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
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).
34
+
33
35
  ```bash
34
36
  pip install ines-parser
35
37
  pip install "ines-parser[archive]" # optional: .7z / .zip / .rar
@@ -72,16 +74,21 @@ 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
75
79
  ```
76
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
+
77
83
  ### Analyze
78
84
 
79
85
  ```bash
80
86
  ines_analyze_rom.py game.nes
87
+ ines_analyze_rom.py game.7z # GoodTools-style one-ROM archive (needs libarchive-c)
81
88
  ines_analyze_rom.py game.nes --json
82
89
  ```
83
90
 
84
- 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. Unrecognised tags are listed as unknown, never guessed.
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.
85
92
 
86
93
  ## Library
87
94
 
@@ -19,4 +19,5 @@ ines_parser/cli/ines_rom_stats.py
19
19
  ines_parser/cli/ines_scan_roms.py
20
20
  ines_parser/cli/ines_split_rom.py
21
21
  ines_parser/cli/rom_fs.py
22
- tests/test_filename.py
22
+ tests/test_filename.py
23
+ tests/test_parser.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ines-parser"
7
- version = "1.5.0"
7
+ version = "2.0.0"
8
8
  description = "Parse iNES/NES 2.0 ROM headers and ROM filename tags; CLI to scan, export, summarize, analyze, and split ROMs"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -0,0 +1,91 @@
1
+ """Tests for ines_parser.parser: header field parsing."""
2
+
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
9
+
10
+ from ines_parser import INESHeader, Mirroring, parse_ines_header # noqa: E402
11
+
12
+ MAGIC = b"NES\x1a"
13
+
14
+
15
+ def raw_bytes(fields: dict) -> bytes:
16
+ b = bytearray(16)
17
+ b[0:4] = MAGIC
18
+ for offset, value in fields.items():
19
+ b[offset] = value
20
+ return bytes(b)
21
+
22
+
23
+ class TestNametableBit0:
24
+ """Flags-6 bit 0 stays meaningful together with the four-screen bit
25
+ (mapper 30/218/286 conventions), so it is exposed separately."""
26
+
27
+ def test_four_screen_with_bit0(self):
28
+ # Real-world pattern: flags 6 = 0xEB (bit 0 + bit 3 both set).
29
+ h = INESHeader(raw_bytes({6: 0xEB}))
30
+ assert h.four_screen
31
+ assert h.mirroring == Mirroring.FOUR_SCREEN
32
+ assert h.nametable_bit0
33
+
34
+ def test_four_screen_without_bit0(self):
35
+ h = INESHeader(raw_bytes({6: 0xE8}))
36
+ assert h.four_screen
37
+ assert not h.nametable_bit0
38
+
39
+ def test_vertical_implies_bit0(self):
40
+ h = INESHeader(raw_bytes({6: 0x41}))
41
+ assert h.mirroring == Mirroring.VERTICAL
42
+ assert h.nametable_bit0
43
+
44
+ def test_horizontal_clears_bit0(self):
45
+ h = INESHeader(raw_bytes({6: 0x40}))
46
+ assert h.mirroring == Mirroring.HORIZONTAL
47
+ assert not h.nametable_bit0
48
+
49
+ def test_to_dict_contains_bit0(self):
50
+ h = parse_ines_header(raw_bytes({6: 0xEB}))
51
+ assert h is not None
52
+ d = h.to_dict()
53
+ assert d["nametable_bit0"] is True
54
+ assert d["four_screen"] is True
55
+
56
+ def test_detailed_str_mentions_bit0_for_four_screen(self):
57
+ h = parse_ines_header(raw_bytes({6: 0xEB}))
58
+ assert "Nametable bit 0: True" in h.detailed_str()
59
+ plain = parse_ines_header(raw_bytes({6: 0x40}))
60
+ assert "Nametable bit 0" not in plain.detailed_str()
61
+
62
+
63
+ class TestBasicParsing:
64
+ def test_classic_mmc3(self):
65
+ h = INESHeader(raw_bytes({4: 2, 5: 1, 6: 0x41}))
66
+ assert h.mapper == 4
67
+ assert h.prg_rom_size == 32 * 1024
68
+ assert h.chr_rom_size == 8 * 1024
69
+ assert h.mirroring == Mirroring.VERTICAL
70
+ assert h.format.value == "iNES"
71
+
72
+ def test_mapper_high_nibble(self):
73
+ h = INESHeader(raw_bytes({4: 2, 6: 0x20, 7: 0x20}))
74
+ assert h.mapper == 34
75
+
76
+ def test_nes2_mapper_and_submapper(self):
77
+ h = INESHeader(raw_bytes({6: 0xC0, 7: 0x08, 8: 0x31}))
78
+ assert h.format.value == "NES 2.0"
79
+ assert h.mapper == 268
80
+ assert h.submapper == 3
81
+
82
+ def test_parse_factory_garbage_handling(self):
83
+ # Short input raises inside INESHeader, so the lenient factory
84
+ # converts it to None.
85
+ assert parse_ines_header(b"short") is None
86
+ # Wrong magic and UNIF are detected but not parsed: a header object
87
+ # comes back, flagged invalid rather than None.
88
+ for raw in (b"NEX\x1a" + b"\x00" * 12, b"UNIF" + b"\x00" * 12):
89
+ h = parse_ines_header(raw)
90
+ assert h is not None
91
+ assert not h.is_valid()
File without changes
File without changes