Mercurial > hg > config
comparison python/gpg_add.py @ 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 | |
children | a3ee050ae568 |
comparison
equal
deleted
inserted
replaced
846:1259f9d79961 | 847:6c918c07d0e3 |
---|---|
1 #!/usr/bin/env python | |
2 | |
3 """ | |
4 add a line to a gpg file; requires `gpg` on your path | |
5 """ | |
6 | |
7 import argparse | |
8 import os | |
9 import shutil | |
10 import subprocess | |
11 import sys | |
12 import tempfile | |
13 | |
14 | |
15 def main(args=sys.argv[1:]): | |
16 """CLI""" | |
17 | |
18 parser = argparse.ArgumentParser(description=__doc__) | |
19 parser.add_argument('file', help="path to GPG file") | |
20 parser.add_argument('line', help='line to add + encrypt') | |
21 options = parser.parse_args(args) | |
22 | |
23 if not os.path.isfile(options.file): | |
24 parser.error("Not a file: '{}'".format(options.file)) | |
25 | |
26 tmpdir = tempfile.mkdtemp() | |
27 try: | |
28 # decrypt the file | |
29 outfile = os.path.join(tmpdir, options.file + '.decrypted') | |
30 subprocess.check_call(['gpg', '--output', outfile, '--decrypt', options.file]) | |
31 assert os.path.exists(outfile) | |
32 | |
33 # read lines | |
34 with open(outfile) as f: | |
35 lines = f.read().strip().splitlines() | |
36 | |
37 # write the file | |
38 lines.append(options.line) | |
39 with open(outfile, 'w') as f: | |
40 f.write('\n'.join(lines)) | |
41 | |
42 # encrypt | |
43 subprocess.check_call(['gpg', '--output', options.file, '--symmetric', outfile]) | |
44 finally: | |
45 shutil.rmtree(tmpdir, ignore_errors=True) | |
46 | |
47 if __name__ == '__main__': | |
48 main() |