cdindex-parser 1.0.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.
- cdindex_parser/__init__.py +26 -0
- cdindex_parser/__main__.py +6 -0
- cdindex_parser/cli.py +89 -0
- cdindex_parser/errors.py +30 -0
- cdindex_parser/exporters.py +74 -0
- cdindex_parser/models.py +54 -0
- cdindex_parser/parser.py +256 -0
- cdindex_parser/py.typed +0 -0
- cdindex_parser/tree.py +30 -0
- cdindex_parser-1.0.0.dist-info/METADATA +114 -0
- cdindex_parser-1.0.0.dist-info/RECORD +15 -0
- cdindex_parser-1.0.0.dist-info/WHEEL +5 -0
- cdindex_parser-1.0.0.dist-info/entry_points.txt +2 -0
- cdindex_parser-1.0.0.dist-info/licenses/LICENSE +21 -0
- cdindex_parser-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Public API for cdindex-parser."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from .exporters import to_csv, to_json
|
|
6
|
+
from .models import Catalog, Entry, FileRecord, NameRecord
|
|
7
|
+
from .parser import parse_catalog, parse_file_line, parse_name_line, resolve_input_path
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version("cdindex-parser")
|
|
11
|
+
except PackageNotFoundError:
|
|
12
|
+
__version__ = "0.0.0+unknown"
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Catalog",
|
|
16
|
+
"Entry",
|
|
17
|
+
"FileRecord",
|
|
18
|
+
"NameRecord",
|
|
19
|
+
"__version__",
|
|
20
|
+
"parse_catalog",
|
|
21
|
+
"parse_file_line",
|
|
22
|
+
"parse_name_line",
|
|
23
|
+
"resolve_input_path",
|
|
24
|
+
"to_csv",
|
|
25
|
+
"to_json",
|
|
26
|
+
]
|
cdindex_parser/cli.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Command-line interface for cdindex-parser."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from importlib import metadata
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .exporters import to_csv, to_json
|
|
10
|
+
from .models import Catalog
|
|
11
|
+
from .parser import parse_catalog, resolve_input_path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
15
|
+
"""Build the argument parser for the CLI."""
|
|
16
|
+
parser = argparse.ArgumentParser(
|
|
17
|
+
prog="cdindex-parser",
|
|
18
|
+
description="Parse CD Index 2 (光碟索引大師) IDX/FILE catalogs into CSV/JSON",
|
|
19
|
+
)
|
|
20
|
+
parser.add_argument(
|
|
21
|
+
"input",
|
|
22
|
+
help=(
|
|
23
|
+
"Base name or path of the IDX/FILE pair "
|
|
24
|
+
"(e.g. mydisk, mydisk.IDX, path/to/disk)"
|
|
25
|
+
),
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument(
|
|
28
|
+
"-o",
|
|
29
|
+
"--output",
|
|
30
|
+
required=False,
|
|
31
|
+
help="Output file path (CSV or JSON, inferred from suffix unless overridden)",
|
|
32
|
+
)
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--format",
|
|
35
|
+
choices=["csv", "json"],
|
|
36
|
+
default=None,
|
|
37
|
+
help="Output format (csv or json); default inferred from --output suffix",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--encoding",
|
|
41
|
+
default="utf-16",
|
|
42
|
+
help="Input encoding (utf-16, big5, cp950); default utf-16 with BOM detection",
|
|
43
|
+
)
|
|
44
|
+
parser.add_argument(
|
|
45
|
+
"--version",
|
|
46
|
+
action="version",
|
|
47
|
+
version=f"cdindex-parser {metadata.version('cdindex-parser')}",
|
|
48
|
+
)
|
|
49
|
+
return parser
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
53
|
+
"""Parse arguments and run the conversion pipeline.
|
|
54
|
+
|
|
55
|
+
Returns an exit code suitable for ``sys.exit``.
|
|
56
|
+
"""
|
|
57
|
+
parser = build_parser()
|
|
58
|
+
args = parser.parse_args(argv)
|
|
59
|
+
|
|
60
|
+
idx_path, _ = resolve_input_path(args.input)
|
|
61
|
+
try:
|
|
62
|
+
catalog: Catalog = parse_catalog(args.input, encoding=args.encoding)
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
65
|
+
return 1
|
|
66
|
+
|
|
67
|
+
# Determine output path and format
|
|
68
|
+
output_path: str | Path
|
|
69
|
+
fmt: str
|
|
70
|
+
|
|
71
|
+
if args.output:
|
|
72
|
+
output_path = Path(args.output)
|
|
73
|
+
fmt = args.format or output_path.suffix.lstrip(".").lower() or "csv"
|
|
74
|
+
else:
|
|
75
|
+
# Default: same base name with .csv extension
|
|
76
|
+
base = Path(idx_path).with_suffix("")
|
|
77
|
+
output_path = base.with_suffix(".csv")
|
|
78
|
+
fmt = "csv"
|
|
79
|
+
|
|
80
|
+
if fmt == "csv":
|
|
81
|
+
to_csv(catalog, output_path)
|
|
82
|
+
elif fmt == "json":
|
|
83
|
+
to_json(catalog, output_path)
|
|
84
|
+
else:
|
|
85
|
+
print(f"Error: unknown format '{fmt}'", file=sys.stderr)
|
|
86
|
+
return 1
|
|
87
|
+
|
|
88
|
+
print(f"Wrote {fmt.upper()} output to {output_path}")
|
|
89
|
+
return 0
|
cdindex_parser/errors.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Exception hierarchy for cdindex-parser."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CDIndexError(Exception):
|
|
5
|
+
"""Base exception for all cdindex-parser errors."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class InputNotFoundError(CDIndexError, FileNotFoundError):
|
|
9
|
+
"""Raised when an input file cannot be found."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EncodingError(CDIndexError, UnicodeDecodeError):
|
|
13
|
+
"""Raised when the input encoding is incorrect."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LineCountMismatchError(CDIndexError, ValueError):
|
|
17
|
+
"""Raised when .IDX and .FILE line counts differ."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class IndentMismatchError(CDIndexError, ValueError):
|
|
21
|
+
"""Raised when an indentation mismatch is found."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MalformedRecordError(CDIndexError, ValueError):
|
|
25
|
+
"""Raised when a record cannot be parsed."""
|
|
26
|
+
|
|
27
|
+
def __init__(self, message: str, line_number: int | None = None):
|
|
28
|
+
"""Initialize with an optional line number for error context."""
|
|
29
|
+
self.line_number = line_number
|
|
30
|
+
super().__init__(message)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""CSV and JSON exporters for cdindex-parser catalogs."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from .models import Catalog
|
|
9
|
+
|
|
10
|
+
CSV_COLUMNS = ("FullPath", "IsDir", "SizeBytes", "MtimeStr")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def iter_rows(catalog: Catalog) -> Iterator[dict[str, object]]:
|
|
14
|
+
"""Yield each ``Entry`` as a dict with CSV-column keys.
|
|
15
|
+
|
|
16
|
+
The ``mtime`` is formatted as an ISO-8601-compatible string
|
|
17
|
+
``YYYY-MM-DDTHH:MM:SS``.
|
|
18
|
+
"""
|
|
19
|
+
for entry in catalog:
|
|
20
|
+
mtime_str = entry.mtime.strftime("%Y-%m-%dT%H:%M:%S")
|
|
21
|
+
yield {
|
|
22
|
+
"FullPath": entry.path,
|
|
23
|
+
"IsDir": "1" if entry.is_dir else "0",
|
|
24
|
+
"SizeBytes": entry.size_bytes,
|
|
25
|
+
"MtimeStr": mtime_str,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def to_csv(catalog: Catalog, out: str | Path) -> None:
|
|
30
|
+
"""Write a ``Catalog`` to CSV format.
|
|
31
|
+
|
|
32
|
+
The output uses ``newline=""`` (as recommended for ``csv.writer`` on
|
|
33
|
+
Windows) and ``csv.QUOTE_MINIMAL`` quoting.
|
|
34
|
+
"""
|
|
35
|
+
out_path = Path(out)
|
|
36
|
+
with open(out_path, "w", encoding="utf-8", newline="") as f:
|
|
37
|
+
writer = csv.writer(f, quoting=csv.QUOTE_MINIMAL)
|
|
38
|
+
writer.writerow(CSV_COLUMNS)
|
|
39
|
+
for row in iter_rows(catalog):
|
|
40
|
+
writer.writerow([row[c] for c in CSV_COLUMNS])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_json(catalog: Catalog, out: str | Path) -> None:
|
|
44
|
+
"""Write a ``Catalog`` to JSON format.
|
|
45
|
+
|
|
46
|
+
Output schema version 1:
|
|
47
|
+
|
|
48
|
+
.. code-block:: json
|
|
49
|
+
|
|
50
|
+
{
|
|
51
|
+
"version": 1,
|
|
52
|
+
"entries": [
|
|
53
|
+
{
|
|
54
|
+
"path": "dir/file.txt",
|
|
55
|
+
"is_dir": false,
|
|
56
|
+
"size_bytes": 226,
|
|
57
|
+
"mtime": "2013-11-03T14:38:30"
|
|
58
|
+
}
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
"""
|
|
62
|
+
out_path = Path(out)
|
|
63
|
+
entries_data = [
|
|
64
|
+
{
|
|
65
|
+
"path": entry.path,
|
|
66
|
+
"is_dir": entry.is_dir,
|
|
67
|
+
"size_bytes": entry.size_bytes,
|
|
68
|
+
"mtime": entry.mtime.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
69
|
+
}
|
|
70
|
+
for entry in catalog
|
|
71
|
+
]
|
|
72
|
+
data = {"version": 1, "entries": entries_data}
|
|
73
|
+
with open(out_path, "w", encoding="utf-8") as f:
|
|
74
|
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
cdindex_parser/models.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Data models for cdindex-parser catalogs."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
|
|
7
|
+
FILE_TYPE_DIR = "D"
|
|
8
|
+
FILE_TYPE_FILE = "F"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class FileRecord:
|
|
13
|
+
"""A single record from a ``.FILE`` line."""
|
|
14
|
+
|
|
15
|
+
indent: int
|
|
16
|
+
type: str # "D" | "F"
|
|
17
|
+
size: int
|
|
18
|
+
ts: int
|
|
19
|
+
mtime: datetime
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True, slots=True)
|
|
23
|
+
class NameRecord:
|
|
24
|
+
"""A single record from a ``.IDX`` line."""
|
|
25
|
+
|
|
26
|
+
indent: int
|
|
27
|
+
name: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class Entry:
|
|
32
|
+
"""A resolved catalog entry with full path."""
|
|
33
|
+
|
|
34
|
+
depth: int
|
|
35
|
+
name: str
|
|
36
|
+
is_dir: bool
|
|
37
|
+
size_bytes: int
|
|
38
|
+
mtime: datetime
|
|
39
|
+
path: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True, slots=True)
|
|
43
|
+
class Catalog:
|
|
44
|
+
"""A collection of resolved catalog entries."""
|
|
45
|
+
|
|
46
|
+
entries: tuple[Entry, ...]
|
|
47
|
+
|
|
48
|
+
def __iter__(self) -> Iterator[Entry]:
|
|
49
|
+
"""Iterate over the catalog entries."""
|
|
50
|
+
return iter(self.entries)
|
|
51
|
+
|
|
52
|
+
def __len__(self) -> int:
|
|
53
|
+
"""Return the number of entries."""
|
|
54
|
+
return len(self.entries)
|
cdindex_parser/parser.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Core parsing logic for cdindex-parser IDX/FILE catalogs."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .errors import MalformedRecordError
|
|
7
|
+
from .models import Catalog, Entry, FileRecord, NameRecord
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def resolve_input_path(input_path: str) -> tuple[str, str]:
|
|
11
|
+
"""Convert a base path or suffixed path into (.IDX path, .FILE path).
|
|
12
|
+
|
|
13
|
+
The old code used ``input_path.rstrip('.IDX').rstrip('.FILE')`` which
|
|
14
|
+
treats the argument as a *character set*, corrupting names like
|
|
15
|
+
``MyID.IDX`` → ``My`` and ``GAME.IDX`` → ``GAM``.
|
|
16
|
+
|
|
17
|
+
This function correctly strips only the recognised suffixes and
|
|
18
|
+
guarantees the returned pair has the same base name.
|
|
19
|
+
"""
|
|
20
|
+
p = Path(input_path)
|
|
21
|
+
stem = p.name
|
|
22
|
+
lower = stem.lower()
|
|
23
|
+
if lower.endswith(".idx"):
|
|
24
|
+
stem = stem[:-4] # strip .IDX (4 chars)
|
|
25
|
+
elif lower.endswith(".file"):
|
|
26
|
+
stem = stem[:-5] # strip .FILE (5 chars)
|
|
27
|
+
# else: keep the original stem (base name only)
|
|
28
|
+
base = p.parent / stem if p.parent else Path(stem)
|
|
29
|
+
idx_path = str(base) + ".IDX"
|
|
30
|
+
file_path = str(base) + ".FILE"
|
|
31
|
+
return idx_path, file_path
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def decode_dos_datetime(ts: int) -> datetime:
|
|
35
|
+
"""Decode a 32-bit DOS FAT timestamp into a ``datetime``.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
ts : int
|
|
40
|
+
32-bit integer timestamp in MS-DOS FAT ``dosdate`` format.
|
|
41
|
+
|
|
42
|
+
Returns
|
|
43
|
+
-------
|
|
44
|
+
datetime
|
|
45
|
+
``datetime`` object; ``1970-01-01T00:00:00`` if the timestamp
|
|
46
|
+
is negative or the date is invalid.
|
|
47
|
+
|
|
48
|
+
"""
|
|
49
|
+
if ts < 0:
|
|
50
|
+
return datetime(1970, 1, 1)
|
|
51
|
+
|
|
52
|
+
dos_time = ts & 0xFFFF
|
|
53
|
+
dos_date = ts >> 16
|
|
54
|
+
|
|
55
|
+
sec = (dos_time & 0x1F) * 2
|
|
56
|
+
minute = (dos_time >> 5) & 0x3F
|
|
57
|
+
hour = dos_time >> 11
|
|
58
|
+
|
|
59
|
+
day = dos_date & 0x1F
|
|
60
|
+
month = (dos_date >> 5) & 0xF
|
|
61
|
+
year = (dos_date >> 9) + 1980
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
return datetime(year, month, day, hour, minute, sec)
|
|
65
|
+
except ValueError:
|
|
66
|
+
return datetime(1970, 1, 1)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_file_line(line: str) -> FileRecord:
|
|
70
|
+
"""Parse a single line from a ``.FILE`` file.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
line : str
|
|
75
|
+
A single line from a ``.FILE`` file, expected format
|
|
76
|
+
``[D|F]<size>.<timestamp>``.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
FileRecord
|
|
81
|
+
A ``FileRecord`` dataclass instance.
|
|
82
|
+
|
|
83
|
+
Raises
|
|
84
|
+
------
|
|
85
|
+
MalformedRecordError
|
|
86
|
+
If the line does not match the expected format.
|
|
87
|
+
|
|
88
|
+
"""
|
|
89
|
+
stripped = line.lstrip("\t")
|
|
90
|
+
s = stripped.rstrip("\n\r")
|
|
91
|
+
|
|
92
|
+
if s.startswith(("D", "F")):
|
|
93
|
+
t = s[0]
|
|
94
|
+
try:
|
|
95
|
+
size_part, ts_part = s[1:].split(".", 1)
|
|
96
|
+
except ValueError as exc:
|
|
97
|
+
raise MalformedRecordError(
|
|
98
|
+
"malformed D/F line (expected '<D|F>.<size>.<ts>')"
|
|
99
|
+
) from exc
|
|
100
|
+
|
|
101
|
+
size = int(size_part)
|
|
102
|
+
ts = int(ts_part)
|
|
103
|
+
|
|
104
|
+
return FileRecord(
|
|
105
|
+
indent=len(line) - len(stripped),
|
|
106
|
+
type=t,
|
|
107
|
+
size=size,
|
|
108
|
+
ts=ts,
|
|
109
|
+
mtime=decode_dos_datetime(ts),
|
|
110
|
+
)
|
|
111
|
+
else:
|
|
112
|
+
raise MalformedRecordError("not a D/F line")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def parse_name_line(line: str) -> NameRecord:
|
|
116
|
+
"""Parse a single line from a ``.IDX`` file.
|
|
117
|
+
|
|
118
|
+
Parameters
|
|
119
|
+
----------
|
|
120
|
+
line : str
|
|
121
|
+
A single line from a ``.IDX`` file, expected to be tab-indented.
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
NameRecord
|
|
126
|
+
A ``NameRecord`` dataclass instance.
|
|
127
|
+
|
|
128
|
+
"""
|
|
129
|
+
from .models import NameRecord
|
|
130
|
+
|
|
131
|
+
stripped = line.lstrip("\t")
|
|
132
|
+
name = stripped.rstrip("\n\r")
|
|
133
|
+
indent = len(line) - len(stripped)
|
|
134
|
+
return NameRecord(indent=indent, name=name)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def parse_catalog(
|
|
138
|
+
input_path: str | Path,
|
|
139
|
+
*,
|
|
140
|
+
encoding: str = "utf-16",
|
|
141
|
+
) -> Catalog:
|
|
142
|
+
"""Parse a ``.IDX``/``.FILE`` pair and return a ``Catalog``.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
input_path : str | Path
|
|
147
|
+
Base name or path of the IDX/FILE pair. The suffix ``.IDX`` or
|
|
148
|
+
``.FILE`` is recognised; otherwise ``.IDX`` is appended.
|
|
149
|
+
encoding : str, optional
|
|
150
|
+
Text encoding for the input files. Defaults to ``"utf-16"`` (BOM-
|
|
151
|
+
detected). Other common encodings such as ``"big5"`` or
|
|
152
|
+
``"cp950"`` may be selected if the original files use a different
|
|
153
|
+
charset.
|
|
154
|
+
|
|
155
|
+
Returns
|
|
156
|
+
-------
|
|
157
|
+
Catalog
|
|
158
|
+
A ``Catalog`` containing the parsed entries.
|
|
159
|
+
|
|
160
|
+
Raises
|
|
161
|
+
------
|
|
162
|
+
InputNotFoundError
|
|
163
|
+
If either the ``.IDX`` or ``.FILE`` file does not exist.
|
|
164
|
+
LineCountMismatchError
|
|
165
|
+
If the two files have a different number of non-empty lines.
|
|
166
|
+
IndentMismatchError
|
|
167
|
+
If a data line and its corresponding name line have different
|
|
168
|
+
indentation.
|
|
169
|
+
MalformedRecordError
|
|
170
|
+
If any line cannot be parsed.
|
|
171
|
+
|
|
172
|
+
"""
|
|
173
|
+
from .errors import IndentMismatchError, InputNotFoundError, LineCountMismatchError
|
|
174
|
+
|
|
175
|
+
idx_path, file_path = resolve_input_path(str(input_path))
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
with open(file_path, encoding=encoding, errors="replace") as f:
|
|
179
|
+
file_lines = f.readlines()
|
|
180
|
+
except FileNotFoundError as exc:
|
|
181
|
+
raise InputNotFoundError(f"FILE not found: {file_path}") from exc
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
with open(idx_path, encoding=encoding, errors="replace") as f:
|
|
185
|
+
idx_lines = f.readlines()
|
|
186
|
+
except FileNotFoundError as exc:
|
|
187
|
+
raise InputNotFoundError(f"IDX not found: {idx_path}") from exc
|
|
188
|
+
|
|
189
|
+
# Filter out empty lines
|
|
190
|
+
file_lines = [line for line in file_lines if line.strip()]
|
|
191
|
+
idx_lines = [line for line in idx_lines if line.strip()]
|
|
192
|
+
|
|
193
|
+
if len(file_lines) != len(idx_lines):
|
|
194
|
+
raise LineCountMismatchError(
|
|
195
|
+
f"line count mismatch: {len(file_lines)} in .FILE, {len(idx_lines)} in .IDX"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
entries: list[Entry] = []
|
|
199
|
+
stack: list[str] = [] # path components
|
|
200
|
+
for i, (f_line, n_line) in enumerate(zip(file_lines, idx_lines, strict=False)):
|
|
201
|
+
try:
|
|
202
|
+
fld = parse_file_line(f_line)
|
|
203
|
+
except MalformedRecordError as exc:
|
|
204
|
+
raise MalformedRecordError(
|
|
205
|
+
f"error parsing .FILE line {i + 1}", line_number=i + 1
|
|
206
|
+
) from exc
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
named = parse_name_line(n_line)
|
|
210
|
+
except Exception as exc:
|
|
211
|
+
raise MalformedRecordError(
|
|
212
|
+
f"error parsing .IDX line {i + 1}", line_number=i + 1
|
|
213
|
+
) from exc
|
|
214
|
+
|
|
215
|
+
if fld.indent != named.indent:
|
|
216
|
+
raise IndentMismatchError(
|
|
217
|
+
f"indent mismatch at line {i + 1}: "
|
|
218
|
+
f".FILE has indent {fld.indent}, .IDX has indent {named.indent}"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
# Build the entry path using a stack-based algorithm
|
|
222
|
+
depth = named.indent
|
|
223
|
+
while len(stack) > depth:
|
|
224
|
+
stack.pop()
|
|
225
|
+
stack.append(named.name)
|
|
226
|
+
path = "/".join(stack)
|
|
227
|
+
|
|
228
|
+
entries.append(
|
|
229
|
+
Entry(
|
|
230
|
+
depth=depth,
|
|
231
|
+
name=named.name,
|
|
232
|
+
is_dir=fld.type == "D",
|
|
233
|
+
size_bytes=fld.size,
|
|
234
|
+
mtime=fld.mtime,
|
|
235
|
+
path=path,
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return Catalog(entries=tuple(entries))
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def match_and_dump(
|
|
243
|
+
input_path: str | Path,
|
|
244
|
+
out_path: str | Path,
|
|
245
|
+
encoding: str = "utf-16",
|
|
246
|
+
) -> None:
|
|
247
|
+
"""Compatibility wrapper that mimics the original ``match_and_dump``.
|
|
248
|
+
|
|
249
|
+
.. deprecated:: 0.3.0
|
|
250
|
+
Use ``cdindex_parser.parse_catalog`` + ``cdindex_parser.exporters``
|
|
251
|
+
instead.
|
|
252
|
+
"""
|
|
253
|
+
from .exporters import to_csv
|
|
254
|
+
|
|
255
|
+
catalog = parse_catalog(input_path, encoding=encoding)
|
|
256
|
+
to_csv(catalog, out_path)
|
cdindex_parser/py.typed
ADDED
|
File without changes
|
cdindex_parser/tree.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Path reconstruction for cdindex-parser catalog trees."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def build_paths(entries: Iterator[tuple[int, str]]) -> Iterator[str]:
|
|
7
|
+
r"""Reconstruct full paths from a (depth, name) iterator using tab indentation.
|
|
8
|
+
|
|
9
|
+
Walks the entry tree maintaining a stack of path components.
|
|
10
|
+
Each entry's depth (number of leading tabs) determines when items
|
|
11
|
+
are popped from the stack.
|
|
12
|
+
|
|
13
|
+
Parameters
|
|
14
|
+
----------
|
|
15
|
+
entries : Iterator[tuple[int, str]]
|
|
16
|
+
Sequence of (depth, name) pairs, typically from ``parse_name_line``
|
|
17
|
+
or generated from a ``Catalog``\ 's entries.
|
|
18
|
+
|
|
19
|
+
Yields
|
|
20
|
+
------
|
|
21
|
+
str
|
|
22
|
+
Full path composed of forward-slashes, e.g. ``"dir/sub/file"``.
|
|
23
|
+
|
|
24
|
+
"""
|
|
25
|
+
stack: list[str] = []
|
|
26
|
+
for depth, name in entries:
|
|
27
|
+
while len(stack) > depth:
|
|
28
|
+
stack.pop()
|
|
29
|
+
stack.append(name)
|
|
30
|
+
yield "/".join(stack)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cdindex-parser
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Parse CD Index 2 IDX/FILE files into CSV/JSON
|
|
5
|
+
Author-email: Chris Fung <chris@example.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/chriskyfung/cdindex-parser
|
|
8
|
+
Project-URL: Documentation, https://chriskyfung.github.io/cdindex-parser/
|
|
9
|
+
Project-URL: Repository, https://github.com/chriskyfung/cdindex-parser
|
|
10
|
+
Project-URL: Issues, https://github.com/chriskyfung/cdindex-parser/issues
|
|
11
|
+
Project-URL: Changelog, https://github.com/chriskyfung/cdindex-parser/blob/main/CHANGELOG.md
|
|
12
|
+
Keywords: cd-index,cdindex,parser,csv,json,legacy,dosdate,big5
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Utilities
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
30
|
+
Requires-Dist: coverage[toml]>=7; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.11; extra == "dev"
|
|
32
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
33
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
34
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
35
|
+
Requires-Dist: pre-commit>=3.8; extra == "dev"
|
|
36
|
+
Provides-Extra: docs
|
|
37
|
+
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
|
|
38
|
+
Requires-Dist: mkdocstrings[python]>=0.26; extra == "docs"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
# CD Index 2 Parser
|
|
42
|
+
|
|
43
|
+
[](https://github.com/chriskyfung/cdindex-parser/actions/workflows/ci.yml)
|
|
44
|
+
[](https://pypi.org/project/cdindex-parser/)
|
|
45
|
+
[](https://pypi.org/project/cdindex-parser/)
|
|
46
|
+
[](https://github.com/chriskyfung/cdindex-parser/blob/main/LICENSE)
|
|
47
|
+
|
|
48
|
+
**CD Index 2 Parser** converts legacy `*.IDX` and `*.FILE` files from CD Index 2 (光碟索引大師) into modern CSV/JSON formats, preserving the full file tree structure, sizes, and modification timestamps.
|
|
49
|
+
|
|
50
|
+
This tool is for anyone who has old CD/DVD index catalogs from this popular legacy software and wants to access them with modern tools.
|
|
51
|
+
|
|
52
|
+
**📖 Full Documentation: https://chriskyfung.github.io/cdindex-parser/**
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Features
|
|
57
|
+
|
|
58
|
+
- Parses file and directory structures from `.IDX` and `.FILE` pairs
|
|
59
|
+
- Correctly decodes the 32-bit MS-DOS FAT timestamps
|
|
60
|
+
- Reconstructs full file paths from tab-indented tree structures
|
|
61
|
+
- Outputs clean CSV or JSON
|
|
62
|
+
- Supports encodings like UTF-16, Big5, and CP950 for Traditional Chinese file names
|
|
63
|
+
- Zero runtime dependencies — pure Python standard library
|
|
64
|
+
- Typed API with frozen dataclasses — importable as a library
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Quick Start
|
|
69
|
+
|
|
70
|
+
Install from PyPI:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install cdindex-parser
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Parse a pair of `.IDX`/`.FILE` files into CSV:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
cdindex-parser mydisk results.csv
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Or parse into JSON:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
cdindex-parser mydisk results.json --format json
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Use it as a Python library:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from cdindex_parser import parse_catalog
|
|
92
|
+
|
|
93
|
+
catalog = parse_catalog("mydisk.IDX", encoding="utf-16")
|
|
94
|
+
for entry in catalog:
|
|
95
|
+
print(f"{entry.path} is_dir={entry.is_dir} size={entry.size_bytes}")
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## 📖 Documentation
|
|
101
|
+
|
|
102
|
+
| Document | Link |
|
|
103
|
+
|---|---|
|
|
104
|
+
| Installation | [Docs › Installation](https://chriskyfung.github.io/cdindex-parser/installation.html) |
|
|
105
|
+
| Usage | [Docs › Usage](https://chriskyfung.github.io/cdindex-parser/usage.html) |
|
|
106
|
+
| File Format | [Docs › File Format](https://chriskyfung.github.io/cdindex-parser/file-format.html) |
|
|
107
|
+
| API Reference | [Docs › API Reference](https://chriskyfung.github.io/cdindex-parser/api.html) |
|
|
108
|
+
| Troubleshooting | [Docs › Troubleshooting](https://chriskyfung.github.io/cdindex-parser/troubleshooting.html) |
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
## License
|
|
113
|
+
|
|
114
|
+
MIT License. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
cdindex_parser/__init__.py,sha256=RdUzm83K9ErUJbcDTh37njda17TxMEi6Cz4pq34L3YM,619
|
|
2
|
+
cdindex_parser/__main__.py,sha256=iTJZclZFh1YiLwjWSGxc2ddXuXxS-D_w9Yo-P57868c,139
|
|
3
|
+
cdindex_parser/cli.py,sha256=spz5JMZzZCHkxaX1Se-GSFNsGCKZ8lxHfV4QqB4gqQY,2585
|
|
4
|
+
cdindex_parser/errors.py,sha256=fAkV8ZqgqwDDAF7rDMm_8a1kYvZ1m6Gdqh4gPZ8jovM,909
|
|
5
|
+
cdindex_parser/exporters.py,sha256=rvm57NWGKf2l1iH9XwTh8lTvISOtPAZt0Vn20gz2UIE,2112
|
|
6
|
+
cdindex_parser/models.py,sha256=qWFF_Tu8yKjPmVOu-9R0cWLrMtsB2MbOSKI5IZ5si8k,1095
|
|
7
|
+
cdindex_parser/parser.py,sha256=ehq-naEBX28aIMZyj4iObRuzT5G4PzoxeoZxxMwoDM4,7395
|
|
8
|
+
cdindex_parser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
cdindex_parser/tree.py,sha256=27kH_Ltp98FNnsRSAeIPRaNIWae3kO5kU2_YYzILRj0,906
|
|
10
|
+
cdindex_parser-1.0.0.dist-info/licenses/LICENSE,sha256=GULmTAiTCDgpnbCI2g1B0B7huOb4qfe_L7AJgEpOJuE,1072
|
|
11
|
+
cdindex_parser-1.0.0.dist-info/METADATA,sha256=x4fn9VnvMJ1OVxHXHiTJo6uPE1vH1TPxh63H7av4_-Q,4266
|
|
12
|
+
cdindex_parser-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
cdindex_parser-1.0.0.dist-info/entry_points.txt,sha256=ZdUQ3RKWwepu8MGvO6YaOP5SIWcCKUnxE4rQXCUgkWc,59
|
|
14
|
+
cdindex_parser-1.0.0.dist-info/top_level.txt,sha256=cYv7h84AbUwTiqB6yoTONYFgRWcDGOHOGWbDKgfOteY,15
|
|
15
|
+
cdindex_parser-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chris K.Y. Fung
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cdindex_parser
|