← Files Unix CopilotARCHIVED FILE

examples/safe_file_inventory.py

1.27 KB · Nov 10, 2026 · 06:45 UTC

↓ Download file

See the change to this file →

#!/usr/bin/env python3
"""Read-only inventory of files matching a suffix, safely representing odd paths.

Example: python3 examples/safe_file_inventory.py ./data --suffix .log
Prints JSON, performs no file mutations and does not follow directory symlinks.
"""
import argparse
import json
import os
from pathlib import Path


def inventory(base:Path,suffix:str)->list[dict]:
    base=base.resolve(strict=True)
    if not base.is_dir():raise NotADirectoryError(str(base))
    result=[]
    for directory, dirs, files in os.walk(base,followlinks=False):
        dirs[:]=[d for d in dirs if not (Path(directory)/d).is_symlink()]
        for name in files:
            p=Path(directory)/name
            if p.is_symlink() or (suffix and not name.endswith(suffix)):continue
            try: size=p.stat().st_size
            except OSError: continue
            result.append({'relative_path':str(p.relative_to(base)), 'size_bytes':size})
    return sorted(result,key=lambda item:item['relative_path'])


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('directory',type=Path)
    p.add_argument('--suffix',default='')
    args=p.parse_args()
    print(json.dumps({'files':inventory(args.directory,args.suffix)},ensure_ascii=False,indent=2))

if __name__=='__main__':main()

SHA-256: 8f7c155aa61f47d5ff6b1416c9eb853b4e21d123a137aa2829e8c5233abc143c