#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2020-2025 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from re import compile, IGNORECASE, Pattern from sys import argv, exit, stderr, stdin, stdout info = ''' links [options...] [filepaths/URIs...] This script finds all web (hyper)links in the input(s) given, specifically HTTP/HTTPS links, showing each match on its own output line. It can match multiple links on each input line. ''' # no args or a leading help-option arg means show the help message and quit if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip()) exit(0) def seems_url(s: str) -> bool: protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') return any(s.startswith(p) for p in protocols) def handle_lines(w, src, links: Pattern) -> None: for line in src: for match in links.finditer(line): w.write(line[match.start():match.end()]) w.write('\n') w.flush() if any(seems_url(e) for e in argv): from io import TextIOWrapper from urllib.request import urlopen links = compile( 'https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*', flags=IGNORECASE, ) try: if argv.count('-') > 1: msg = 'reading from `-` (standard input) more than once not allowed' raise ValueError(msg) # handle all named inputs given for path in argv[1:]: if path == '-': handle_lines(stdout, stdin, links) continue if seems_url(path): with urlopen(path) as inp: with TextIOWrapper(inp, encoding='utf-8') as txt: handle_lines(stdout, txt, links) continue with open(path, encoding='utf-8') as inp: handle_lines(stdout, inp, links) if len(argv) == 1: handle_lines(stdout, stdin, links) except BrokenPipeError: # quit quietly, instead of showing a confusing error message stderr.close() exit(0) except KeyboardInterrupt: stderr.close() exit(2) except Exception as e: print(f'\x1b[31m{e}\x1b[0m', file=stderr) exit(1)