File: links.py 1 #!/usr/bin/python3 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2024 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 from io import TextIOWrapper 27 from re import compile, Pattern 28 from sys import argv, exit, stderr, stdin, stdout 29 30 31 info = ''' 32 links [options...] [filepaths/URIs...] 33 34 This script finds all web (hyper)links in the input(s) given, specifically 35 HTTP/HTTPS links, showing each match on its own output line. It can match 36 multiple links on each input line. 37 ''' 38 39 # no args or a leading help-option arg means show the help message and quit 40 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): 41 print(info.strip(), file=stderr) 42 exit(0) 43 44 45 def fail(msg, code: int = 1) -> None: 46 'Show the error message given, and quit the app right away.' 47 print(f'\x1b[31m{msg}\x1b[0m', file=stderr) 48 exit(code) 49 50 51 def seems_url(s: str) -> bool: 52 protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') 53 return any(s.startswith(p) for p in protocols) 54 55 56 def handle_lines(w, src, links: Pattern) -> None: 57 for line in src: 58 for match in links.finditer(line): 59 w.write(line[match.start():match.end()]) 60 w.write('\n') 61 w.flush() 62 63 64 try: 65 if argv.count('-') > 1: 66 msg = 'reading from `-` (standard input) more than once not allowed' 67 raise ValueError(msg) 68 69 if any(seems_url(e) for e in argv): 70 from urllib.request import urlopen 71 72 links_src = 'https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*' 73 links = compile(links_src) 74 75 # handle all named inputs given 76 for path in argv[1:]: 77 if path == '-': 78 handle_lines(stdout, stdin, links) 79 continue 80 81 if seems_url(path): 82 with urlopen(path) as inp: 83 with TextIOWrapper(inp, encoding='utf-8') as txt: 84 handle_lines(stdout, txt, links) 85 continue 86 87 with open(path, encoding='utf-8') as inp: 88 handle_lines(stdout, inp, links) 89 90 if len(argv) == 1: 91 handle_lines(stdout, stdin, links) 92 except BrokenPipeError: 93 # quit quietly, instead of showing a confusing error message 94 stderr.close() 95 except KeyboardInterrupt: 96 exit(2) 97 except Exception as e: 98 fail(e, 1)