|
1 | | -#!/usr/bin/env pypy3 |
2 | | -# encoding: utf-8 |
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +Shorten file paths for notational-fzf-vim display. |
3 | 5 |
|
4 | | -# Supposedly, importing so that you don't need dots in names speeds up a |
5 | | -# script, and the point of this one is to run fast. |
| 6 | +Reads lines in format `filename:linenum:contents` from stdin, |
| 7 | +outputs `filename:linenum:shortname:linenum:contents` with colored paths. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
6 | 11 |
|
7 | 12 | import platform |
| 13 | +import sys |
8 | 14 | from os import pardir |
9 | 15 | from os.path import abspath, expanduser, join, sep, split, splitdrive |
10 | 16 | from pathlib import PurePath |
11 | | -from sys import stdin |
12 | 17 |
|
| 18 | +# ANSI color codes |
| 19 | +GREEN = "\033[32m" |
| 20 | +PURPLE = "\033[35m" |
| 21 | +CYAN = "\033[36m" |
| 22 | +RESET = "\033[0m" |
13 | 23 |
|
14 | | -# These are floated to the top so they aren't recalculated every loop. The |
15 | | -# most restrictive replacements should come earlier. |
| 24 | +# Path replacements (most restrictive first) |
16 | 25 | REPLACEMENTS = ("", pardir, "~") |
17 | | -old_paths = [abspath(expanduser(replacement)) for replacement in REPLACEMENTS] |
| 26 | +OLD_PATHS = [abspath(expanduser(r)) for r in REPLACEMENTS] |
18 | 27 | IS_WINDOWS = platform.system().lower() == "windows" |
19 | 28 |
|
20 | 29 |
|
| 30 | +def color(text: str, color_code: str) -> str: |
| 31 | + """Wrap text in ANSI color codes.""" |
| 32 | + return f"{color_code}{text}{RESET}" |
| 33 | + |
| 34 | + |
21 | 35 | def prettyprint_path(path: str, old_path: str, replacement: str) -> str: |
22 | | - # Pretty print the path prefix |
| 36 | + """Replace path prefix and shorten remaining components to first char.""" |
23 | 37 | path = path.replace(old_path, replacement, 1) |
24 | | - # Truncate the rest of the path to a single character. |
25 | | - short_path = join(replacement, *[x[0] for x in PurePath(path).parts[1:]]) |
| 38 | + parts = PurePath(path).parts[1:] # Skip the replacement prefix |
| 39 | + short_path = join(replacement, *(p[0] for p in parts)) |
26 | 40 | return short_path |
27 | 41 |
|
28 | 42 |
|
29 | | -def shorten(path: str): |
30 | | - """Returns 2 strings, the shortened parent directory and the filename.""" |
31 | | - # We don't want to shorten the filename, just its parent directory, so we |
32 | | - # `split()` and just shorten `path`. |
| 43 | +def shorten(path: str) -> tuple[str, str]: |
| 44 | + """Returns shortened parent directory and filename.""" |
33 | 45 | path, filename = split(path) |
34 | 46 |
|
35 | | - # use empty replacement for current directory. it expands correctly |
36 | | - |
37 | | - for replacement, old_path in zip(REPLACEMENTS, old_paths): |
| 47 | + for replacement, old_path in zip(REPLACEMENTS, OLD_PATHS): |
38 | 48 | if path.startswith(old_path): |
39 | 49 | short_path = prettyprint_path(path, old_path, replacement) |
40 | | - # to avoid multiple replacements |
41 | 50 | break |
42 | | - |
43 | | - # If no replacement was found, shorten the entire path. |
44 | 51 | else: |
45 | | - short_path = join(*[x[0] for x in PurePath(path).parts]) |
| 52 | + # No replacement matched - shorten entire path |
| 53 | + parts = PurePath(path).parts |
| 54 | + short_path = join(*(p[0] for p in parts)) if parts else "" |
46 | 55 |
|
47 | 56 | return short_path, filename |
48 | 57 |
|
49 | 58 |
|
50 | | -GREEN = "\033[32m" |
51 | | -PURPLE = "\033[35m" # looks pink to me |
52 | | -CYAN = "\033[36m" |
53 | | - |
54 | | -RESET = "\033[0m" |
55 | | - |
56 | | -# RED = '\033[31m' |
57 | | -# BLUE = '\033[34m' |
58 | | -# LIGHTRED = '\033[91m' |
59 | | -# YELLOW = '\033[93m' |
60 | | -# LIGHTBLUE = '\033[94m' |
61 | | -# LIGHTCYAN = '\033[96m' |
62 | | - |
63 | | - |
64 | | -def color(line, color): |
65 | | - return color + line + RESET |
66 | | - |
67 | | - |
68 | 59 | def process_line(line: str) -> str: |
69 | | - # Expected format is colon separated `name:line number:contents` |
70 | | - |
| 60 | + """Process a single line from ripgrep output.""" |
| 61 | + # Handle Windows drive letters (e.g., C:\path) |
71 | 62 | if IS_WINDOWS: |
72 | | - # Windows paths may contain a colon, e.g. C:\Windows\ which messes up the split |
73 | | - # splitdrive(string) results in the following: |
74 | | - # Windows drive letter, e.g. C:\Windows\Folder\Foo.txt -> ('C', '\Windows\Folder\Foo.txt') |
75 | | - # Windows UNC path, e.g. \\Server\Share\Folder\Foo.txt -> ('\\Server\Share', '\Folder\Foo.txt') |
76 | | - # *nix, e.g. /any/path/to/file.txt -> ('', '/any/path/to/file.txt') |
77 | | - _, line = splitdrive(line) # Toss the drive letter since it's not necessary. |
78 | | - filename, linenum, contents = line.split(sep=":", maxsplit=2) |
79 | | - |
80 | | - # Drop trailing newline. |
| 63 | + _, line = splitdrive(line) |
| 64 | + |
| 65 | + # Parse filename:linenum:contents |
| 66 | + try: |
| 67 | + filename, linenum, contents = line.split(sep=":", maxsplit=2) |
| 68 | + except ValueError: |
| 69 | + return line # Return unchanged if format unexpected |
| 70 | + |
81 | 71 | contents = contents.rstrip() |
82 | 72 |
|
83 | | - # Normalize path for further processing. |
| 73 | + # Normalize path (skip on Windows to avoid prepending cwd) |
84 | 74 | if not IS_WINDOWS: |
85 | | - # This prepends cwd in Windows which is unnecessary. |
86 | 75 | filename = abspath(filename) |
87 | 76 |
|
88 | 77 | shortened_parent, basename = shorten(filename) |
89 | | - # The conditional is to avoid a leading slash if the parent is replaced |
90 | | - # with an empty directory. The slash is manually colored because otherwise |
91 | | - # `os.path.join` won't do it. |
| 78 | + |
| 79 | + # Build colored short name |
92 | 80 | if shortened_parent: |
93 | | - colored_short_name = color(shortened_parent + sep, PURPLE) + color( |
94 | | - basename, CYAN |
95 | | - ) |
| 81 | + colored_short_name = color(shortened_parent + sep, PURPLE) + color(basename, CYAN) |
96 | 82 | else: |
97 | 83 | colored_short_name = color(basename, CYAN) |
98 | 84 |
|
99 | | - # Format is: long form, line number, short form, line number, rest of line. This is so Vim can process it. |
100 | | - formatted_line = ":".join( |
101 | | - [ |
102 | | - color(filename, CYAN), |
103 | | - color(linenum, GREEN), |
104 | | - colored_short_name, |
105 | | - color(linenum, GREEN), |
106 | | - contents, |
107 | | - ] |
108 | | - ) |
109 | | - return formatted_line |
110 | | - |
111 | | - # We print the long and short forms, and one form is picked in the Vim script that uses this. |
112 | | - # print(formatted_line) |
| 85 | + # Output format: long_path:linenum:short_path:linenum:contents |
| 86 | + return ":".join([ |
| 87 | + color(filename, CYAN), |
| 88 | + color(linenum, GREEN), |
| 89 | + colored_short_name, |
| 90 | + color(linenum, GREEN), |
| 91 | + contents, |
| 92 | + ]) |
113 | 93 |
|
114 | 94 |
|
115 | | -if __name__ == "__main__": |
116 | | - # Use stdin.buffer to handle binary data, then decode with error handling |
117 | | - # This prevents the script from crashing on files with non-UTF-8 content |
118 | | - for raw_line in stdin.buffer: |
| 95 | +def main() -> None: |
| 96 | + """Read from stdin and process each line.""" |
| 97 | + for raw_line in sys.stdin.buffer: |
119 | 98 | try: |
120 | 99 | line = raw_line.decode("utf-8") |
121 | 100 | print(process_line(line)) |
122 | 101 | except UnicodeDecodeError: |
123 | | - # Skip lines that can't be decoded as UTF-8 (e.g., binary files) |
124 | | - # Try latin-1 as fallback since it can decode any byte sequence |
| 102 | + # Try latin-1 as fallback (can decode any byte sequence) |
125 | 103 | try: |
126 | 104 | line = raw_line.decode("latin-1") |
127 | 105 | print(process_line(line)) |
128 | 106 | except Exception: |
129 | | - # If all else fails, skip this line entirely |
130 | | - pass |
| 107 | + pass # Skip completely malformed lines |
131 | 108 | except Exception: |
132 | | - # Skip lines that cause other errors (malformed input, etc.) |
133 | | - pass |
| 109 | + pass # Skip lines that cause other errors |
| 110 | + |
| 111 | + |
| 112 | +if __name__ == "__main__": |
| 113 | + main() |
0 commit comments