Skip to content

API Reference

filename_ingest

Source code in src/filename_ingest/__init__.py
6
7
8
9
def build_pattern(plaintext: str) -> re.Pattern:
    # Compiles a case-insensitive regex that captures optional leading and trailing separator characters around the word
    escaped = re.escape(plaintext)
    return re.compile(rf"(?P<leading>[-_.\s]?){escaped}(?P<trailing>[-_.\s]?)", re.IGNORECASE)
Source code in src/filename_ingest/__init__.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def rename_files(directory: Path, plaintext: str, dry_run: bool = False) -> None:
    # Iterates all files in the directory and renames each one by removing the plaintext word and its adjacent separator
    pattern = build_pattern(plaintext)

    def replacement(m: re.Match) -> str:
        # Keep one separator only when the word is flanked on both sides, otherwise drop both word and separator
        if m.group("leading") and m.group("trailing"):
            return m.group("leading")
        return ""

    for file in directory.iterdir():
        if not file.is_file():
            continue
        new_stem = pattern.sub(replacement, file.stem)
        new_name = new_stem + file.suffix
        if new_name == file.name:
            continue
        new_path = file.with_name(new_name)
        print(f"{file.name} -> {new_name}")
        if not dry_run:
            file.rename(new_path)

filename_ingest.archive

Source code in src/filename_ingest/archive.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def create_archive(
    # Bundles all files in directory plus test-output.txt and test-results.xml into a timestamped zip archive
    directory: Path,
    output_dir: Path = Path("."),
    *,
    test_output: Path = Path("test-output.txt"),
    test_results: Path = Path("test-results.xml"),
) -> Path:
    stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
    name = f"test_{stamp}_{uuid.uuid4()}.zip"
    dest = output_dir / name

    with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as zf:
        for f in sorted(directory.iterdir()):
            if f.is_file():
                zf.write(f, f.name)
        for artifact in (test_output, test_results):
            if artifact.exists():
                zf.write(artifact, artifact.name)

    return dest