changeset 847:6c918c07d0e3

[gpg] make a front-end to add a line to a gpg symmetrically encrypted file
author Jeff Hammel <k0scist@gmail.com>
date Tue, 17 Oct 2017 11:59:09 -0700
parents 1259f9d79961
children a3ee050ae568
files python/gpg_add.py
diffstat 1 files changed, 48 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /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()