File: dedup.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2020-2025 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 sys import argv, exit, stderr, stdin, stdout
  27 from typing import List, Set
  28 
  29 
  30 info = '''
  31 dedup [options...] [filepaths/URIs...]
  32 
  33 This script reads/fetches all named sources given to it, and only outputs
  34 each exact same line once, deduplicating lines. Named sources can be a mix
  35 of filepaths and URIs.
  36 
  37 Each non-empty input ends with a line feed, even when the original data
  38 don't.
  39 
  40 The help option is `-h`, `--h`, `-help`, or `--help`.
  41 '''
  42 
  43 # a leading help-option arg means show the help message and quit
  44 if len(argv) == 2 and argv[1] in ('-h', '--h', '-help', '--help'):
  45     print(info.strip())
  46     exit(0)
  47 
  48 
  49 def seems_url(s: str) -> bool:
  50     protocols = ('https://', 'http://', 'file://', 'ftp://', 'data:')
  51     return any(s.startswith(p) for p in protocols)
  52 
  53 
  54 def run(args: List[str]) -> None:
  55     paths = set()
  56     lines = set()
  57 
  58     if any(seems_url(e) for e in args):
  59         from io import TextIOWrapper
  60         from urllib.request import urlopen
  61 
  62     for path in args:
  63         if path in paths:
  64             continue
  65         paths.add(path)
  66 
  67         if path == '-':
  68             handle_lines(stdout, inp, lines)
  69             continue
  70 
  71         if seems_url(path):
  72             with urlopen(path) as inp:
  73                 with TextIOWrapper(inp, encoding='utf-8') as txt:
  74                     handle_lines(stdout, txt, lines)
  75             continue
  76 
  77         with open(path, encoding='utf-8') as inp:
  78             handle_lines(stdout, inp, lines)
  79 
  80     if len(args) == 0:
  81         handle_lines(stdout, stdin, lines)
  82 
  83 
  84 def handle_lines(w, src, got: Set[str]) -> None:
  85     for line in src:
  86         if line in got:
  87             continue
  88         got.add(line)
  89 
  90         w.write(line)
  91         if not line.endswith('\n'):
  92             w.write('\n')
  93 
  94 
  95 try:
  96     run(argv[1:])
  97 except BrokenPipeError:
  98     # quit quietly, instead of showing a confusing error message
  99     stderr.close()
 100 except KeyboardInterrupt:
 101     exit(2)
 102 except Exception as e:
 103     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
 104     exit(1)