|
| 1 | +"""*Dfetch* can filter files in the repo. |
| 2 | +
|
| 3 | +It can either accept no input to list all files. A list of files can be piped in (such as through ``find``) |
| 4 | +or it can be used as a wrapper around a certain tool to block or allow files under control by dfetch. |
| 5 | +""" |
| 6 | + |
| 7 | +import argparse |
| 8 | +import os |
| 9 | +import sys |
| 10 | +from pathlib import Path |
| 11 | +from typing import Optional |
| 12 | + |
| 13 | +import dfetch.commands.command |
| 14 | +import dfetch.log |
| 15 | +import dfetch.manifest.manifest |
| 16 | +from dfetch.log import get_logger |
| 17 | +from dfetch.util.cmdline import run_on_cmdline_uncaptured |
| 18 | +from dfetch.util.util import in_directory |
| 19 | + |
| 20 | +logger = get_logger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class Filter(dfetch.commands.command.Command): |
| 24 | + """Filter files based on flags and pass on any command. |
| 25 | +
|
| 26 | + Based on the provided arguments filter files, and call the given arguments or print them out if no command given. |
| 27 | + """ |
| 28 | + |
| 29 | + SILENT = True |
| 30 | + |
| 31 | + @staticmethod |
| 32 | + def create_menu(subparsers: dfetch.commands.command.SubparserActionType) -> None: |
| 33 | + """Add the parser menu for this action.""" |
| 34 | + parser = dfetch.commands.command.Command.parser(subparsers, Filter) |
| 35 | + parser.add_argument( |
| 36 | + "--in-manifest", |
| 37 | + "-i", |
| 38 | + action="store_true", |
| 39 | + default=False, |
| 40 | + help="Keep files that came here through the manifest.", |
| 41 | + ) |
| 42 | + |
| 43 | + parser.add_argument( |
| 44 | + "cmd", |
| 45 | + metavar="<cmd>", |
| 46 | + type=str, |
| 47 | + nargs="?", |
| 48 | + help="Command to call", |
| 49 | + ) |
| 50 | + |
| 51 | + parser.add_argument( |
| 52 | + "args", |
| 53 | + metavar="<args>", |
| 54 | + type=str, |
| 55 | + nargs="*", |
| 56 | + help="Arguments to pass to the command", |
| 57 | + ) |
| 58 | + |
| 59 | + def __call__(self, args: argparse.Namespace) -> None: |
| 60 | + """Perform the filter.""" |
| 61 | + if not args.verbose: |
| 62 | + dfetch.log.set_level("ERROR") |
| 63 | + manifest = dfetch.manifest.manifest.get_manifest() |
| 64 | + |
| 65 | + pwd = Path.cwd() |
| 66 | + topdir = Path(manifest.path).parent |
| 67 | + with in_directory(topdir): |
| 68 | + |
| 69 | + project_paths = { |
| 70 | + Path(project.destination).resolve() for project in manifest.projects |
| 71 | + } |
| 72 | + |
| 73 | + input_list = self._determine_input_list(args) |
| 74 | + block_inside, block_outside = self._filter_files( |
| 75 | + pwd, topdir, project_paths, input_list |
| 76 | + ) |
| 77 | + |
| 78 | + blocklist = block_outside if args.in_manifest else block_inside |
| 79 | + |
| 80 | + filtered_args = [arg for arg in input_list if arg not in blocklist] |
| 81 | + |
| 82 | + if args.cmd: |
| 83 | + run_on_cmdline_uncaptured(logger, [args.cmd] + filtered_args) |
| 84 | + else: |
| 85 | + print(os.linesep.join(filtered_args)) |
| 86 | + |
| 87 | + def _determine_input_list(self, args: argparse.Namespace) -> list[str]: |
| 88 | + """Determine list of inputs to process.""" |
| 89 | + input_list: list[str] = list(str(arg) for arg in args.args) |
| 90 | + if not sys.stdin.isatty(): |
| 91 | + input_list += list(str(arg).strip() for arg in sys.stdin.readlines()) |
| 92 | + |
| 93 | + # If no input from stdin or args loop over all files |
| 94 | + if not input_list: |
| 95 | + input_list = list( |
| 96 | + str(file) for file in Path(".").rglob("*") if file.is_file() |
| 97 | + ) |
| 98 | + |
| 99 | + return input_list |
| 100 | + |
| 101 | + def _filter_files( |
| 102 | + self, pwd: Path, topdir: Path, project_paths: set[Path], input_list: list[str] |
| 103 | + ) -> tuple[list[str], list[str]]: |
| 104 | + """Filter files in input_set in files in one of the project_paths or not.""" |
| 105 | + block_inside: list[str] = [] |
| 106 | + block_outside: list[str] = [] |
| 107 | + |
| 108 | + for path_or_arg in input_list: |
| 109 | + arg_abs_path = Path(pwd / path_or_arg.strip()).resolve() |
| 110 | + if not arg_abs_path.exists(): |
| 111 | + logger.print_info_line(path_or_arg.strip(), "not a file / dir") |
| 112 | + continue |
| 113 | + try: |
| 114 | + arg_abs_path.relative_to(topdir) |
| 115 | + except ValueError: |
| 116 | + logger.print_info_line(path_or_arg.strip(), "outside project") |
| 117 | + block_inside.append(path_or_arg) |
| 118 | + block_outside.append(path_or_arg) |
| 119 | + continue |
| 120 | + |
| 121 | + containing_dir = self._file_in_project(arg_abs_path, project_paths) |
| 122 | + |
| 123 | + if containing_dir: |
| 124 | + block_inside.append(path_or_arg) |
| 125 | + logger.print_info_line( |
| 126 | + path_or_arg.strip(), f"inside project ({containing_dir})" |
| 127 | + ) |
| 128 | + else: |
| 129 | + block_outside.append(path_or_arg) |
| 130 | + logger.print_info_line(path_or_arg.strip(), "not inside any project") |
| 131 | + |
| 132 | + return block_inside, block_outside |
| 133 | + |
| 134 | + def _file_in_project(self, file: Path, project_paths: set[Path]) -> Optional[Path]: |
| 135 | + """Check if a specific file is somewhere in one of the project paths.""" |
| 136 | + for project_path in project_paths: |
| 137 | + try: |
| 138 | + file.relative_to(project_path) |
| 139 | + return project_path |
| 140 | + except ValueError: |
| 141 | + continue |
| 142 | + return None |
0 commit comments