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 re import compile, Pattern 27 from sys import argv, exit, stderr, stdin, stdout 28 29 30 info = ''' 31 links [options...] [filepaths/URIs...] 32 33 This script finds all web (hyper)links in the input(s) given, specifically 34 HTTP/HTTPS links, showing each match on its own output line. It can match 35 multiple links on each input line. 36 ''' 37 38 # no args or a leading help-option arg means show the help message and quit 39 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): 40 print(info.strip()) 41 exit(0) 42 43 44 def seems_url(s: str) -> bool: 45 protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:') 46 return any(s.startswith(p) for p in protocols) 47 48 49 def handle_lines(w, src, links: Pattern) -> None: 50 for line in src: 51 for match in links.finditer(line): 52 w.write(line[match.start():match.end()]) 53 w.write('\n') 54 w.flush() 55 56 57 try: 58 if argv.count('-') > 1: 59 msg = 'reading from `-` (standard input) more than once not allowed' 60 raise ValueError(msg) 61 62 if any(seems_url(e) for e in argv): 63 from io import TextIOWrapper 64 from urllib.request import urlopen 65 66 links_src = 'https?://[A-Za-z0-9+_.:%-]+(/[A-Za-z0-9+_.%/,#?&=-]*)*' 67 links = compile(links_src) 68 69 # handle all named inputs given 70 for path in argv[1:]: 71 if path == '-': 72 handle_lines(stdout, stdin, links) 73 continue 74 75 if seems_url(path): 76 with urlopen(path) as inp: 77 with TextIOWrapper(inp, encoding='utf-8') as txt: 78 handle_lines(stdout, txt, links) 79 continue 80 81 with open(path, encoding='utf-8') as inp: 82 handle_lines(stdout, inp, links) 83 84 if len(argv) == 1: 85 handle_lines(stdout, stdin, links) 86 except BrokenPipeError: 87 # quit quietly, instead of showing a confusing error message 88 stderr.close() 89 except KeyboardInterrupt: 90 exit(2) 91 except Exception as e: 92 print(f'\x1b[31m{e}\x1b[0m', file=stderr) 93 exit(1)