File: xnargs.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 itertools import islice, chain
  27 from subprocess import call
  28 from sys import argv, exit, stderr, stdin, stdout
  29 
  30 
  31 info = '''
  32 xnargs [args...]
  33 
  34 
  35 Similar to `xargs`, eXtra Null-separated ARGumentS takes such strings from
  36 standard-input and uses them to extend the cmd/arg list given as cmd-line
  37 arguments, running the resulting extended command.
  38 
  39 This tool is a very convenient way to pass filepaths which may have any
  40 allowed (null-bytes aren't allowed) symbol in them to another app/tool.
  41 '''
  42 
  43 
  44 if len(argv) < 2 or argv[1] in ('-h', '--h', '-help', '--help'):
  45     print(info.strip())
  46     exit(0)
  47 
  48 
  49 try:
  50     # extras = stdin.buffer.read()
  51     # extras = extras.lstrip(b'\xef\xbb\xbf').rstrip(b'\x00')
  52     # extras = (str(e, encoding='utf-8') for e in extras.split(b'\x00'))
  53     extras = stdin.read()
  54     extras = extras.lstrip('\xef\xbb\xbf').rstrip('\x00')
  55     extras = (e for e in extras.split('\x00'))
  56     args = chain(islice(argv, 1, None), extras)
  57     exit(call(args, stdin=stdin, stdout=stdout, stderr=stderr))
  58 except BrokenPipeError:
  59     stderr.close()
  60     exit(0)
  61 except KeyboardInterrupt:
  62     exit(2)
  63 except Exception as e:
  64     print(f'\x1b[31m{e}\x1b[0m', file=stderr)
  65     exit(1)