# HG changeset patch # User Jeff Hammel # Date 1508266749 25200 # Node ID 6c918c07d0e31e4175b84fb491101aadb5eb0a53 # Parent 1259f9d7996160dce0e1f330e76fa877a92c5eeb [gpg] make a front-end to add a line to a gpg symmetrically encrypted file diff -r 1259f9d79961 -r 6c918c07d0e3 python/gpg_add.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/python/gpg_add.py Tue Oct 17 11:59:09 2017 -0700 @@ -0,0 +1,48 @@ +#!/usr/bin/env python + +""" +add a line to a gpg file; requires `gpg` on your path +""" + +import argparse +import os +import shutil +import subprocess +import sys +import tempfile + + +def main(args=sys.argv[1:]): + """CLI""" + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('file', help="path to GPG file") + parser.add_argument('line', help='line to add + encrypt') + options = parser.parse_args(args) + + if not os.path.isfile(options.file): + parser.error("Not a file: '{}'".format(options.file)) + + tmpdir = tempfile.mkdtemp() + try: + # decrypt the file + outfile = os.path.join(tmpdir, options.file + '.decrypted') + subprocess.check_call(['gpg', '--output', outfile, '--decrypt', options.file]) + assert os.path.exists(outfile) + + # read lines + with open(outfile) as f: + lines = f.read().strip().splitlines() + + # write the file + lines.append(options.line) + with open(outfile, 'w') as f: + f.write('\n'.join(lines)) + + # encrypt + subprocess.check_call(['gpg', '--output', options.file, '--symmetric', outfile]) + finally: + shutil.rmtree(tmpdir, ignore_errors=True) + +if __name__ == '__main__': + main()