#!/usr/bin/env python3 """ Fast manual grouping helper. Run without arguments to enter paths/ranges interactively, or run: python3 grouping.py path/to/file/or/directory [...] Files are sorted by their current path and moved into one folder named [first stem]-[last stem] inside the working directory. """ from __future__ import annotations import glob import os import shlex import shutil import sys from pathlib import Path from tools.console import launch_terminal_if_needed, pause_if_interactive, prompt_input from tools.filenames import group_stem from tools.filesystem import ( cleanup_roots_from_args, collect_files, determine_working_dir, entered_path, path_completion, path_completions, remove_empty_dirs, unique_path, ) def range_lexer(value: str) -> shlex.shlex: lexer = shlex.shlex(value, posix=True) lexer.whitespace_split = True lexer.commenters = lexer.escape = "" return lexer def sibling_items(source: Path) -> list[Path]: folders = source.is_dir() return sorted( (item for item in source.parent.iterdir() if (item.is_dir() if folders else item.is_file())), key=lambda item: (item.name.casefold(), item.name), ) def range_completions(text: str) -> list[str]: lexer = range_lexer(text) try: first = lexer.get_token() except ValueError: # Completing inside an unfinished quote. first = lexer.token if first and "*" in first: return [] if lexer.state != " ": return [shlex.quote(path) for path in path_completions(first or "")] boundary = lexer.instream.tell() prefix = text[:boundary] remainder = text[boundary:] prefix += remainder[:len(remainder) - len(remainder.lstrip())] second = range_lexer(remainder) tokens: list[str] = [] try: tokens.extend(second) except ValueError: tokens.append(second.token) if len(tokens) > 1: return [] value = tokens[0] if tokens else "" if value.lstrip("+-").isdecimal() or "*" in value: return [] source = entered_path(first).absolute() if not (source.is_file() or source.is_dir()): return [] directory = "" if value.startswith(("/", "~")) or Path(value).is_absolute(): directory = os.path.join(str(source.parent), "") if value.startswith("~"): home = str(Path.home()) + os.sep if not directory.startswith(home): return [] directory = "~/" + directory[len(home):] if directory != value and directory.startswith(value): return [prefix + shlex.quote(directory)] if not value.startswith(directory): return [] value = value[len(directory):] return [ prefix + shlex.quote(directory + item.name) for item in sibling_items(source) if item.name.startswith(value) ] def expand_range(value: str) -> tuple[Path, list[Path]]: tokens = list(range_lexer(value)) if len(tokens) not in {1, 2}: raise ValueError("Enter a path/pattern, two range endpoints, or a path and count; quote names containing spaces.") first = entered_path(tokens[0]).absolute() if any("*" in token for token in tokens): if len(tokens) != 1: raise ValueError("Wildcards are only supported in a single-path entry, not a range or count.") pattern = glob.escape(str(first)).replace("[*]", "*") matches = sorted( (path for name in glob.glob(pattern) if (path := Path(name)).is_file() or path.is_dir()), key=lambda path: (str(path).casefold(), str(path)), ) if not matches: raise ValueError(f"No files or directories match: {first}") return Path(os.path.commonpath([path.parent for path in matches])).resolve(), matches if not (first.is_file() or first.is_dir()): raise ValueError(f"File or directory not found: {first}") parent = first.parent if len(tokens) == 1: return parent.resolve(), [first] siblings = sibling_items(first) names = [item.name for item in siblings] start = names.index(first.name) if tokens[1].lstrip("+-").isdecimal(): count = int(tokens[1]) if count < 1: raise ValueError("Count must be a positive integer, including the starting item.") if count > len(siblings) - start: raise ValueError(f"Requested {count} items, but only {len(siblings) - start} remain from {first.name}.") return parent.resolve(), siblings[start:start + count] last = entered_path(tokens[1]) if not last.is_absolute(): if last.parent != Path("."): raise ValueError("The second endpoint must be a name or an absolute path.") last = parent / last if last.parent.resolve() != parent.resolve(): raise ValueError("Range endpoints must be in the same directory.") if not (last.is_file() or last.is_dir()): raise ValueError(f"File or directory not found: {last}") if first.is_dir() != last.is_dir(): raise ValueError("Range endpoints must both be files or both be directories.") start, end = sorted((start, names.index(last.name))) return parent.resolve(), siblings[start:end + 1] def prompt_group_ranges() -> tuple[list[str], Path | None]: print("Enter selections, one per line:") print(" /photos/A.jpg One file or folder (folders are collected recursively)") print(" /photos/DSC*.JPG Wildcard: * matches zero or more characters in a name") print(" /photos/A.jpg C.jpg Inclusive range, in either order, both files or both folders") print(" /photos/A.jpg 5 Five files starting at A.jpg (or five folders if A is a folder)") print("Ranges/counts use alphabetical order and skip the other type; counts include A.") print("Range endpoints must share a directory; B can be a name or an absolute path.") print("Wildcards cannot be combined with ranges/counts. Use an absolute path for a numeric endpoint name.") print('Quote paths/names containing spaces: "/photos/Trip A" "Trip C". Tab completes paths.') print("Leave the line empty to group all selections together.") args: list[str] = [] working_dir = None with path_completion(range_completions): while True: value = prompt_input("Selection: ").strip() if not value: return args, working_dir try: parent, paths = expand_range(value) if working_dir is not None and parent != working_dir: raise ValueError(f"Use entries from the working directory: {working_dir}") except ValueError as exc: print(exc) continue if working_dir is None: working_dir = parent print(f"Working directory: {working_dir}") args.extend(str(path) for path in paths) print(f"Selected {len(paths)} file(s)/folder(s).") def collect_group_files(args: list[str]) -> list[Path]: return collect_files(args, sort_by_name=True) def group_files(files: list[Path], working_dir: Path) -> Path | None: if not files: return None sorted_files = sorted(files, key=lambda item: item.name.lower()) first = group_stem(sorted_files[0]) last = group_stem(sorted_files[-1]) target_dir = working_dir / f"{first}-{last}" target_dir.mkdir(parents=True, exist_ok=True) for source in sorted_files: if source.parent == target_dir: continue destination = unique_path(target_dir / source.name) shutil.move(str(source), str(destination)) return target_dir def print_removed_dirs(removed_dirs: list[Path]) -> None: if not removed_dirs: return print("Removed empty director" + ("y:" if len(removed_dirs) == 1 else "ies:")) for directory in removed_dirs: print(f" - {directory}") def run(argv: list[str]) -> int: try: if argv[1:]: args = argv[1:] working_dir = determine_working_dir(args) else: args, working_dir = prompt_group_ranges() if not args: print("No inputs selected.") return 0 except RuntimeError as exc: print(exc) return 1 cleanup_roots = cleanup_roots_from_args(args) files = collect_group_files(args) if not files: print("No files to group.") assert working_dir is not None target_dir = group_files(files, working_dir) if target_dir is not None: print(f"Moved {len(files)} file(s) into {target_dir}") removed_dirs = remove_empty_dirs(cleanup_roots, keep_dirs={working_dir.resolve()}) print_removed_dirs(removed_dirs) return 0 def main(argv: list[str]) -> int: if launch_terminal_if_needed(argv): return 0 try: return run(argv) finally: pause_if_interactive() if __name__ == "__main__": raise SystemExit(main(sys.argv))