ines-parser 1.2.0__py3-none-any.whl

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.
@@ -0,0 +1,46 @@
1
+ """
2
+ iNES Parser Library
3
+
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.
6
+ """
7
+
8
+ from .parser import (
9
+ parse_ines_header,
10
+ INESHeader,
11
+ INESFormat,
12
+ Mirroring,
13
+ TVSystem,
14
+ ConsoleType,
15
+ CPUTiming,
16
+ INES_HEADER_SIZE,
17
+ INES_TRAINER_SIZE,
18
+ )
19
+
20
+ from .mappers import (
21
+ get_mapper_name,
22
+ get_mapper_alternate_names,
23
+ get_mapper_notes,
24
+ get_mapper_info,
25
+ is_known_mapper,
26
+ )
27
+
28
+ __version__ = "1.2.0"
29
+ __author__ = "Leonid Kabanov"
30
+ __all__ = [
31
+ "parse_ines_header",
32
+ "INESHeader",
33
+ "INESFormat",
34
+ "Mirroring",
35
+ "TVSystem",
36
+ "ConsoleType",
37
+ "CPUTiming",
38
+ "INES_HEADER_SIZE",
39
+ "INES_TRAINER_SIZE",
40
+ "get_mapper_name",
41
+ "get_mapper_alternate_names",
42
+ "get_mapper_notes",
43
+ "get_mapper_info",
44
+ "is_known_mapper",
45
+ ]
46
+
File without changes
@@ -0,0 +1,535 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Scan and analyze iNES ROM files from directories and archives.
4
+
5
+ This script scans a directory for ROM files (.nes) and archives (.7z, .zip, .rar),
6
+ extracts and analyzes ROM headers, displaying information about mapper, mirroring,
7
+ ROM sizes, and other header fields. Supports filtering and detailed output.
8
+ """
9
+
10
+ import argparse
11
+ import sys
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+ # Repo root on path when running this file directly (not via pip console_scripts)
16
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
17
+
18
+ # Try to import libarchive - make it optional
19
+ try:
20
+ import libarchive
21
+ LIBARCHIVE_AVAILABLE = True
22
+ except ImportError:
23
+ LIBARCHIVE_AVAILABLE = False
24
+
25
+ # Import from ines_parser package
26
+ from ines_parser import parse_ines_header, INESHeader, INES_HEADER_SIZE
27
+
28
+
29
+ # Constants
30
+ DEFAULT_ARCHIVE_PATH = 'nes_archive/'
31
+ # All potential archive formats that libarchive can support
32
+ ALL_ARCHIVE_FORMATS = {'.7z', '.zip', '.rar'}
33
+ # Archive extensions depend on libarchive availability
34
+ if LIBARCHIVE_AVAILABLE:
35
+ ARCHIVE_EXTENSIONS = ALL_ARCHIVE_FORMATS
36
+ else:
37
+ ARCHIVE_EXTENSIONS = set()
38
+ # All supported extensions
39
+ SUPPORTED_EXTENSIONS = ARCHIVE_EXTENSIONS | {'.nes'}
40
+
41
+
42
+ def collect_supported_files(directory: Path) -> list[Path]:
43
+ """
44
+ Walk ``directory`` once and collect files whose extension matches a supported type.
45
+
46
+ Case-insensitive suffix match; skips entries that are not regular files or cannot be stat'd.
47
+ """
48
+ suffixes = {ext.lower() for ext in SUPPORTED_EXTENSIONS}
49
+ paths: list[Path] = []
50
+ for path in directory.rglob('*'):
51
+ try:
52
+ if not path.is_file():
53
+ continue
54
+ except OSError:
55
+ continue
56
+ if path.suffix.lower() in suffixes:
57
+ paths.append(path)
58
+ paths.sort()
59
+ return paths
60
+
61
+
62
+ def read_header_from_blocks(entry) -> Optional[bytes]:
63
+ """
64
+ Read the first INES_HEADER_SIZE bytes from an archive entry.
65
+
66
+ Args:
67
+ entry: Archive entry to read from
68
+
69
+ Returns:
70
+ Header bytes or None if insufficient data
71
+ """
72
+ blocks = []
73
+ total_size = 0
74
+
75
+ for block in entry.get_blocks():
76
+ blocks.append(block)
77
+ total_size += len(block)
78
+ if total_size >= INES_HEADER_SIZE:
79
+ break
80
+
81
+ header_bytes = b''.join(blocks)
82
+ return header_bytes[:INES_HEADER_SIZE] if len(header_bytes) >= INES_HEADER_SIZE else None
83
+
84
+
85
+ def format_header_info(header: INESHeader, show_all_fields: bool = False) -> str:
86
+ """
87
+ Format header information for display.
88
+
89
+ Args:
90
+ header: Parsed iNES header
91
+ show_all_fields: If True, show all header fields (mirroring, battery, trainer, etc.)
92
+
93
+ Returns:
94
+ Formatted string with header information
95
+ """
96
+ if not header.is_valid():
97
+ return header.format.value
98
+
99
+ # Use detailed format if requested, otherwise minimal
100
+ if show_all_fields:
101
+ return header.detailed_str()
102
+ else:
103
+ return str(header)
104
+
105
+
106
+ def matches_filters(header: INESHeader, filter_trainer: bool = False,
107
+ filter_mapper: int = None, filter_mirroring: str = None,
108
+ min_prg_size: int = None, max_prg_size: int = None,
109
+ min_chr_size: int = None, max_chr_size: int = None) -> bool:
110
+ """
111
+ Check if ROM header matches all specified filters.
112
+
113
+ Args:
114
+ header: Parsed iNES header
115
+ filter_trainer: If True, only accept ROMs with trainer
116
+ filter_mapper: If specified, only accept this mapper number
117
+ filter_mirroring: If specified, only accept this mirroring type (H/V/F)
118
+ min_prg_size: Minimum PRG ROM size in KiB
119
+ max_prg_size: Maximum PRG ROM size in KiB
120
+ min_chr_size: Minimum CHR ROM size in KiB
121
+ max_chr_size: Maximum CHR ROM size in KiB
122
+
123
+ Returns:
124
+ True if ROM matches all filters
125
+ """
126
+ if not header.is_valid():
127
+ return False
128
+
129
+ # Filter by trainer
130
+ if filter_trainer and not header.has_trainer:
131
+ return False
132
+
133
+ # Filter by mapper
134
+ if filter_mapper is not None and header.mapper != filter_mapper:
135
+ return False
136
+
137
+ # Filter by mirroring
138
+ if filter_mirroring is not None and header.mirroring.value != filter_mirroring:
139
+ return False
140
+
141
+ # Filter by PRG ROM size
142
+ prg_size_kib = header.prg_rom_size // 1024
143
+ if min_prg_size is not None and prg_size_kib < min_prg_size:
144
+ return False
145
+ if max_prg_size is not None and prg_size_kib > max_prg_size:
146
+ return False
147
+
148
+ # Filter by CHR ROM size
149
+ chr_size_kib = header.chr_rom_size // 1024
150
+ if min_chr_size is not None and chr_size_kib < min_chr_size:
151
+ return False
152
+ if max_chr_size is not None and chr_size_kib > max_chr_size:
153
+ return False
154
+
155
+ return True
156
+
157
+
158
+ def process_nes_file(file_path: Path, base_path: Path,
159
+ filter_trainer: bool = False,
160
+ show_all_fields: bool = False,
161
+ filter_mapper: int = None,
162
+ filter_mirroring: str = None,
163
+ min_prg_size: int = None,
164
+ max_prg_size: int = None,
165
+ min_chr_size: int = None,
166
+ max_chr_size: int = None) -> bool:
167
+ """
168
+ Process a plain .nes file and display ROM information.
169
+
170
+ Args:
171
+ file_path: Path to the .nes file
172
+ base_path: Base path for relative path display
173
+
174
+ Returns:
175
+ True if processing succeeded, False otherwise
176
+ """
177
+ relative_path = file_path.relative_to(base_path)
178
+
179
+ try:
180
+ with open(file_path, 'rb') as f:
181
+ header_bytes = f.read(INES_HEADER_SIZE)
182
+
183
+ if len(header_bytes) < INES_HEADER_SIZE:
184
+ print(f'{relative_path}: File too short (less than {INES_HEADER_SIZE} bytes)')
185
+ return False
186
+
187
+ # Parse header
188
+ header = parse_ines_header(header_bytes)
189
+
190
+ if not header:
191
+ print(f'{relative_path}: Failed to parse header')
192
+ return False
193
+
194
+ # Apply filters
195
+ if not matches_filters(header, filter_trainer, filter_mapper, filter_mirroring,
196
+ min_prg_size, max_prg_size, min_chr_size, max_chr_size):
197
+ return False
198
+
199
+ print(f'{relative_path}: {format_header_info(header, show_all_fields)}')
200
+ return True
201
+
202
+ except Exception as e:
203
+ print(f'{relative_path}: Error reading file: {e}')
204
+ return False
205
+
206
+
207
+ def process_archive(archive_path: Path, base_path: Path,
208
+ filter_trainer: bool = False,
209
+ show_all_fields: bool = False,
210
+ filter_mapper: int = None,
211
+ filter_mirroring: str = None,
212
+ min_prg_size: int = None,
213
+ max_prg_size: int = None,
214
+ min_chr_size: int = None,
215
+ max_chr_size: int = None) -> int:
216
+ """
217
+ Process an archive (.7z, .zip, or .rar) and display ROM information for all files.
218
+
219
+ Args:
220
+ archive_path: Path to the archive
221
+ base_path: Base path for relative path display
222
+
223
+ Returns:
224
+ Number of successfully processed files in the archive
225
+ """
226
+ if not LIBARCHIVE_AVAILABLE:
227
+ return 0
228
+
229
+ relative_path = archive_path.relative_to(base_path)
230
+ nes_files_found = 0
231
+ processed_count = 0
232
+
233
+ try:
234
+ # Open file first, then pass to libarchive to avoid repeated stat() calls
235
+ with open(archive_path, 'rb') as f:
236
+ with libarchive.fd_reader(f.fileno()) as archive:
237
+ # Process all file entries (skip directories)
238
+ for entry in archive:
239
+ if entry.isfile:
240
+ # Only process .nes files
241
+ entry_name = entry.name.lower()
242
+ if not entry_name.endswith('.nes'):
243
+ continue
244
+
245
+ nes_files_found += 1
246
+
247
+ # Read header bytes
248
+ header_bytes = read_header_from_blocks(entry)
249
+
250
+ if not header_bytes:
251
+ print(f'{relative_path}:{entry.name}: File too short (less than {INES_HEADER_SIZE} bytes)')
252
+ continue
253
+
254
+ # Parse header
255
+ header = parse_ines_header(header_bytes)
256
+
257
+ if not header:
258
+ print(f'{relative_path}:{entry.name}: Failed to parse header')
259
+ continue
260
+
261
+ # Apply filters
262
+ if not matches_filters(header, filter_trainer, filter_mapper, filter_mirroring,
263
+ min_prg_size, max_prg_size, min_chr_size, max_chr_size):
264
+ continue
265
+
266
+ print(f'{relative_path}:{entry.name}: {format_header_info(header, show_all_fields)}')
267
+ processed_count += 1
268
+
269
+ # Report if no .nes files found at all (not filtered, but actually missing)
270
+ if nes_files_found == 0:
271
+ print(f'{relative_path}: No .nes files found in archive')
272
+
273
+ return processed_count
274
+
275
+ except Exception as e:
276
+ print(f'{relative_path}: Error reading archive: {e}')
277
+ return 0
278
+
279
+
280
+ def process_file(file_path: Path, base_path: Path,
281
+ filter_trainer: bool = False,
282
+ show_all_fields: bool = False,
283
+ filter_mapper: int = None,
284
+ filter_mirroring: str = None,
285
+ min_prg_size: int = None,
286
+ max_prg_size: int = None,
287
+ min_chr_size: int = None,
288
+ max_chr_size: int = None) -> int:
289
+ """
290
+ Process a file based on its extension.
291
+
292
+ Args:
293
+ file_path: Path to the file
294
+ base_path: Base path for relative path display
295
+ filter_trainer: If True, only show files with trainer
296
+ show_all_fields: If True, show additional header fields
297
+
298
+ Returns:
299
+ Number of successfully processed ROM files (1 for .nes, N for archives)
300
+ """
301
+ ext = file_path.suffix.lower()
302
+
303
+ if ext == '.nes':
304
+ return 1 if process_nes_file(file_path, base_path, filter_trainer, show_all_fields,
305
+ filter_mapper, filter_mirroring,
306
+ min_prg_size, max_prg_size, min_chr_size, max_chr_size) else 0
307
+ elif ext in ARCHIVE_EXTENSIONS:
308
+ return process_archive(file_path, base_path, filter_trainer, show_all_fields,
309
+ filter_mapper, filter_mirroring,
310
+ min_prg_size, max_prg_size, min_chr_size, max_chr_size)
311
+ else:
312
+ return 0
313
+
314
+
315
+ def scan_directory(directory: Path,
316
+ filter_trainer: bool = False,
317
+ show_all_fields: bool = False,
318
+ filter_mapper: int = None,
319
+ filter_mirroring: str = None,
320
+ min_prg_size: int = None,
321
+ max_prg_size: int = None,
322
+ min_chr_size: int = None,
323
+ max_chr_size: int = None) -> int:
324
+ """
325
+ Scan a directory for ROM files and archives, and process them.
326
+
327
+ Searches for .nes and configured archive types in one recursive pass.
328
+
329
+ Args:
330
+ directory: Directory to scan
331
+ filter_trainer: If True, only show files with trainer
332
+ show_all_fields: If True, show additional header fields
333
+
334
+ Returns:
335
+ Number of successfully processed ROM files (counts individual ROMs in archives)
336
+ """
337
+ all_files = collect_supported_files(directory)
338
+
339
+ if not all_files:
340
+ extensions_str = ', '.join(sorted(SUPPORTED_EXTENSIONS))
341
+ print(f"No files found with extensions {extensions_str} in {directory}", file=sys.stderr)
342
+ return 0
343
+
344
+ processed_count = 0
345
+
346
+ try:
347
+ for file_path in all_files:
348
+ processed_count += process_file(file_path, directory, filter_trainer, show_all_fields,
349
+ filter_mapper, filter_mirroring,
350
+ min_prg_size, max_prg_size, min_chr_size, max_chr_size)
351
+
352
+ except KeyboardInterrupt:
353
+ print('\n\nInterrupted by user', file=sys.stderr)
354
+ return processed_count
355
+
356
+ return processed_count
357
+
358
+
359
+ def build_argument_parser() -> argparse.ArgumentParser:
360
+ """Build the command-line argument parser."""
361
+ supported_types = ", ".join(sorted(SUPPORTED_EXTENSIONS))
362
+ if not LIBARCHIVE_AVAILABLE:
363
+ supported_types += " (libarchive not available - archive support disabled)"
364
+
365
+ parser = argparse.ArgumentParser(
366
+ prog='ines_scan_roms.py',
367
+ description='Scan and analyze iNES ROM files from directories and archives',
368
+ formatter_class=argparse.RawDescriptionHelpFormatter,
369
+ epilog=f"""
370
+ Supported file types: {supported_types}
371
+
372
+ Examples:
373
+ %(prog)s
374
+ %(prog)s /path/to/roms
375
+ %(prog)s /path/to/roms --verbose
376
+ """
377
+ )
378
+ parser.add_argument(
379
+ 'directory',
380
+ nargs='?',
381
+ default=DEFAULT_ARCHIVE_PATH,
382
+ help=f'Directory containing ROM files (default: {DEFAULT_ARCHIVE_PATH})'
383
+ )
384
+ parser.add_argument(
385
+ '--verbose',
386
+ '-v',
387
+ action='store_true',
388
+ help='Verbose output'
389
+ )
390
+ parser.add_argument(
391
+ '--has-trainer',
392
+ action='store_true',
393
+ help='Show only ROMs with trainer'
394
+ )
395
+ parser.add_argument(
396
+ '--show-all',
397
+ action='store_true',
398
+ help='Show all header fields (trainer, battery, etc.)'
399
+ )
400
+ parser.add_argument(
401
+ '--mapper',
402
+ type=int,
403
+ metavar='N',
404
+ help='Filter by mapper number (e.g., --mapper 1)'
405
+ )
406
+ parser.add_argument(
407
+ '--mirroring',
408
+ choices=['H', 'V', 'F'],
409
+ metavar='TYPE',
410
+ help='Filter by mirroring type: H (horizontal), V (vertical), F (four-screen)'
411
+ )
412
+ parser.add_argument(
413
+ '--min-prg',
414
+ type=int,
415
+ metavar='KiB',
416
+ help='Minimum PRG ROM size in KiB'
417
+ )
418
+ parser.add_argument(
419
+ '--max-prg',
420
+ type=int,
421
+ metavar='KiB',
422
+ help='Maximum PRG ROM size in KiB'
423
+ )
424
+ parser.add_argument(
425
+ '--min-chr',
426
+ type=int,
427
+ metavar='KiB',
428
+ help='Minimum CHR ROM size in KiB'
429
+ )
430
+ parser.add_argument(
431
+ '--max-chr',
432
+ type=int,
433
+ metavar='KiB',
434
+ help='Maximum CHR ROM size in KiB'
435
+ )
436
+
437
+ return parser
438
+
439
+
440
+ def main() -> int:
441
+ """
442
+ Main entry point for the script.
443
+
444
+ Returns:
445
+ Exit code (0 for success, non-zero for error)
446
+ """
447
+ parser = build_argument_parser()
448
+ args = parser.parse_args()
449
+
450
+ if (
451
+ args.min_prg is not None
452
+ and args.max_prg is not None
453
+ and args.min_prg > args.max_prg
454
+ ):
455
+ print(
456
+ 'Error: --min-prg cannot be greater than --max-prg',
457
+ file=sys.stderr,
458
+ )
459
+ parser.print_help()
460
+ return 1
461
+
462
+ if (
463
+ args.min_chr is not None
464
+ and args.max_chr is not None
465
+ and args.min_chr > args.max_chr
466
+ ):
467
+ print(
468
+ 'Error: --min-chr cannot be greater than --max-chr',
469
+ file=sys.stderr,
470
+ )
471
+ parser.print_help()
472
+ return 1
473
+
474
+ # Validate directory — if we cannot scan, show usage
475
+ directory_path = Path(args.directory)
476
+
477
+ if not directory_path.exists():
478
+ print(f"Error: Directory does not exist: {args.directory}", file=sys.stderr)
479
+ parser.print_help()
480
+ return 1
481
+
482
+ if not directory_path.is_dir():
483
+ print(f"Error: Not a directory: {args.directory}", file=sys.stderr)
484
+ parser.print_help()
485
+ return 1
486
+
487
+ # Scan and process files
488
+ if args.verbose:
489
+ extensions_str = ', '.join(sorted(SUPPORTED_EXTENSIONS))
490
+ print(f"Scanning directory: {directory_path}", file=sys.stderr)
491
+ print(f"Looking for: {extensions_str}", file=sys.stderr)
492
+ if not LIBARCHIVE_AVAILABLE:
493
+ archive_types = ", ".join(sorted(ALL_ARCHIVE_FORMATS))
494
+ print(f"Warning: libarchive not available - archive support ({archive_types}) disabled", file=sys.stderr)
495
+
496
+ # Show active filters
497
+ filters = []
498
+ if args.has_trainer:
499
+ filters.append("has trainer")
500
+ if args.mapper is not None:
501
+ filters.append(f"mapper={args.mapper}")
502
+ if args.mirroring:
503
+ filters.append(f"mirroring={args.mirroring}")
504
+ if args.min_prg is not None:
505
+ filters.append(f"PRG>={args.min_prg}k")
506
+ if args.max_prg is not None:
507
+ filters.append(f"PRG<={args.max_prg}k")
508
+ if args.min_chr is not None:
509
+ filters.append(f"CHR>={args.min_chr}k")
510
+ if args.max_chr is not None:
511
+ filters.append(f"CHR<={args.max_chr}k")
512
+
513
+ if filters:
514
+ print(f"Filters: {', '.join(filters)}", file=sys.stderr)
515
+ print()
516
+
517
+ processed_count = scan_directory(directory_path,
518
+ filter_trainer=args.has_trainer,
519
+ show_all_fields=args.show_all,
520
+ filter_mapper=args.mapper,
521
+ filter_mirroring=args.mirroring,
522
+ min_prg_size=args.min_prg,
523
+ max_prg_size=args.max_prg,
524
+ min_chr_size=args.min_chr,
525
+ max_chr_size=args.max_chr)
526
+
527
+ if args.verbose:
528
+ print(f"\nProcessed {processed_count} ROM files", file=sys.stderr)
529
+
530
+ return 0
531
+
532
+
533
+ if __name__ == '__main__':
534
+ sys.exit(main())
535
+