1#!/usr/bin/env python3 2 3import argparse 4import fnmatch 5import itertools 6import os 7import pathlib 8import sys 9 10parser = argparse.ArgumentParser( 11 "ignore-filter", 12 description="Filter files from stdin using a .gitignore-style filter file", 13) 14parser.add_argument("filename", nargs="+", help="The filter file", type=str) 15 16args = parser.parse_args() 17 18ignore_patterns = list() 19for f in args.filename: 20 if not os.path.exists(f): 21 raise RuntimeError(f"File {args.filename} does not exist.") 22 with open(f, "r") as ignore_file: 23 for line in [i.strip() for i in ignore_file.readlines()]: 24 # Ignore comments. 25 if line.startswith("#"): 26 continue 27 28 # Drop leading "/" or "./" ( this isn't 100% correct for 29 # .gitignore format) . 30 if line.startswith("/"): 31 line = line[1:] 32 elif line.startswith("./"): 33 line = line[2:] 34 35 ignore_patterns.append(line) 36 37for c in sys.stdin: 38 candidate = c.strip() 39 match = False 40 for seg in itertools.accumulate( 41 pathlib.PurePath(candidate).parts, os.path.join 42 ): 43 if any(fnmatch.fnmatch(seg, i) for i in ignore_patterns): 44 match = True 45 break 46 if not match: 47 print(candidate) 48