#!/usr/bin/python # The MIT License (MIT) # # Copyright (c) 2026 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 itertools import islice from sys import argv, exit, stderr, stdin, stdout info = ''' save [options...] [filepaths...] This script reads all bytes from the standard input, and only after that saves those data to the file given. Nothing is saved when not given any filenames. A single dash used as a name refers to the standard output, and can be used more than once. All (optional) leading options start with either single or double-dash: -a, -append append/extend (instead of replace) existing file-data -h, -help show this help message ''' # 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) skip = 1 output_mode = 'wb' for s in islice(argv, 1, None): if s == '-': break if s == '--': skip += 1 break if s in ('-a', '--a', '-append', '--append'): output_mode = 'ab' skip += 1 continue if s.startswith('-'): print(f'save: unsupported option {s}', file=stderr) exit(1) break if len(argv) <= skip: print(info.strip(), file=stderr) exit(1) try: data = stdin.buffer.read() for name in islice(argv, skip, None): if name == '-': stdout.buffer.write(data) continue with open(name, output_mode) as out: out.write(data) except KeyboardInterrupt: exit(2) except Exception as e: print(str(e), file=stderr) exit(1)