Add a --hyperlink-only-matches flag to hyperlinked_grep

If it's active, only matching lines get links, not file headers or context lines.
This commit is contained in:
Charlie Groves 2022-08-26 17:05:50 -04:00
parent e330c38d4a
commit f5a70adf0b

View File

@ -20,6 +20,10 @@ def write_hyperlink(write: Callable[[bytes], None], url: bytes, line: bytes, fra
def main() -> None: def main() -> None:
write_all_hyperlinks = '--hyperlink-only-matches' not in sys.argv
if not write_all_hyperlinks:
sys.argv.remove('--hyperlink-only-matches')
if not sys.stdout.isatty() and '--pretty' not in sys.argv and '-p' not in sys.argv: if not sys.stdout.isatty() and '--pretty' not in sys.argv and '-p' not in sys.argv:
os.execlp('rg', 'rg', *sys.argv[1:]) os.execlp('rg', 'rg', *sys.argv[1:])
cmdline = ['rg', '--pretty', '--with-filename'] + sys.argv[1:] cmdline = ['rg', '--pretty', '--with-filename'] + sys.argv[1:]
@ -31,7 +35,7 @@ def main() -> None:
write: Callable[[bytes], None] = cast(Callable[[bytes], None], sys.stdout.buffer.write) write: Callable[[bytes], None] = cast(Callable[[bytes], None], sys.stdout.buffer.write)
sgr_pat = re.compile(br'\x1b\[.*?m') sgr_pat = re.compile(br'\x1b\[.*?m')
osc_pat = re.compile(b'\x1b\\].*?\x1b\\\\') osc_pat = re.compile(b'\x1b\\].*?\x1b\\\\')
num_pat = re.compile(br'^(\d+)[:-]') num_pat = re.compile(br'^(\d+)([:-])')
in_result: bytes = b'' in_result: bytes = b''
hostname = socket.gethostname().encode('utf-8') hostname = socket.gethostname().encode('utf-8')
@ -43,10 +47,9 @@ def main() -> None:
if not clean_line: if not clean_line:
in_result = b'' in_result = b''
write(b'\n') write(b'\n')
continue elif in_result:
if in_result:
m = num_pat.match(clean_line) m = num_pat.match(clean_line)
if m is not None: if m is not None and (write_all_hyperlinks or m.group(2) == b':'):
write_hyperlink(write, in_result, line, frag=m.group(1)) write_hyperlink(write, in_result, line, frag=m.group(1))
else: else:
write(line) write(line)
@ -54,9 +57,10 @@ def main() -> None:
if line.strip(): if line.strip():
path = quote_from_bytes(os.path.abspath(clean_line)).encode('utf-8') path = quote_from_bytes(os.path.abspath(clean_line)).encode('utf-8')
in_result = b'file://' + hostname + path in_result = b'file://' + hostname + path
write_hyperlink(write, in_result, line) if write_all_hyperlinks:
else: write_hyperlink(write, in_result, line)
write(line) continue
write(line)
except KeyboardInterrupt: except KeyboardInterrupt:
p.send_signal(signal.SIGINT) p.send_signal(signal.SIGINT)
except (EOFError, BrokenPipeError): except (EOFError, BrokenPipeError):