Skip to content

feat: adds a tool to consolidate (hard-link) duplicated files #970

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions tools/consolidate-libs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!/usr/bin/env python

__doc__ = """Scans src/lib/<arch>/** and does hardlinks to files
with the same name and content"""

import glob
import os
import re
from collections import defaultdict
from pathlib import Path
from typing import NamedTuple

ROOT_DIR = Path(__file__).parent.parent.absolute() / "src" / "lib" / "arch"
ARCHS = "zx48k", "zxnext"


class FileInfo(NamedTuple):
path: str
hash: int


def get_file_list(root: Path) -> list[str]:
filelist = glob.glob(str(root / "**" / "*"), recursive=True)
return [f for f in filelist if os.path.isfile(f)]


def scan_arch(root: Path) -> dict[FileInfo, list[str]]:
result = defaultdict(list)
re_arch = re.compile(r"^.*?/src/lib/arch/[^/]+/(.*)$")

files = get_file_list(root)
for file in files:
match = re_arch.match(file)
if not match:
continue

path = match.group(1)
result[FileInfo(path=path, hash=hash(open(file, "rb").read()))].append(file)

return result


def fold_files(scan: dict[FileInfo, list[str]]) -> None:
for path, files in scan.items():
if len(files) == 1:
continue

main_file = files[0]
for file in files[1:]:
print(f"Linking {main_file} to {file}")
os.unlink(file)
os.link(main_file, file)


def main():
scan = scan_arch(ROOT_DIR)
fold_files(scan)


if __name__ == "__main__":
main()