tarfilter/taridshift: use argparse

This commit is contained in:
Johannes 'josch' Schauer 2020-11-27 00:32:14 +01:00
parent 3731393c7a
commit c51c69ca13
Signed by: josch
GPG key ID: F2CBA5C78FBD83E1
2 changed files with 26 additions and 10 deletions

View file

@ -33,7 +33,13 @@ class FilterAction(argparse.Action):
def main(): def main():
parser = argparse.ArgumentParser(description="filter a tarball") parser = argparse.ArgumentParser(
description="""\
Filters a tarball on standard input by the same rules as the dpkg --path-exclude
and --path-include options and writes resulting tarball to standard output. See
dpkg(1) for information on how these two options work in detail.
"""
)
parser.add_argument( parser.add_argument(
"--path-exclude", "--path-exclude",
metavar="pattern", metavar="pattern",

View file

@ -20,14 +20,24 @@
import tarfile import tarfile
import sys import sys
import argparse
def main(): def main():
if len(sys.argv) < 2: parser = argparse.ArgumentParser(
print("usage: %s idshift" % sys.argv[0], file=sys.stderr) description="""\
exit(1) Accepts a tarball on standard input and prints a tarball on standard output
with the same contents but all uid and gid ownership information shifted by the
idshift = int(sys.argv[1]) value given as first command line argument.
"""
)
parser.add_argument(
"idshift",
metavar="NUM",
type=int,
help="Integer value by which to shift the uid and gid of each entry",
)
args = parser.parse_args()
# starting with Python 3.8, the default format became PAX_FORMAT, so this # starting with Python 3.8, the default format became PAX_FORMAT, so this
# is only for compatibility with older versions of Python 3 # is only for compatibility with older versions of Python 3
@ -35,15 +45,15 @@ def main():
fileobj=sys.stdout.buffer, mode="w|", format=tarfile.PAX_FORMAT fileobj=sys.stdout.buffer, mode="w|", format=tarfile.PAX_FORMAT
) as out_tar: ) as out_tar:
for member in in_tar: for member in in_tar:
if idshift < 0 and -idshift > member.uid: if args.idshift < 0 and -args.idshift > member.uid:
print("uid cannot be negative", file=sys.stderr) print("uid cannot be negative", file=sys.stderr)
exit(1) exit(1)
if idshift < 0 and -idshift > member.gid: if args.idshift < 0 and -args.idshift > member.gid:
print("gid cannot be negative", file=sys.stderr) print("gid cannot be negative", file=sys.stderr)
exit(1) exit(1)
member.uid += idshift member.uid += args.idshift
member.gid += idshift member.gid += args.idshift
if member.isfile(): if member.isfile():
with in_tar.extractfile(member) as file: with in_tar.extractfile(member) as file:
out_tar.addfile(member, file) out_tar.addfile(member, file)