| 1 | #!/usr/bin/python3 |
| 2 | |
| 3 | import sys, getopt, subprocess, re |
| 4 | |
| 5 | def usage(out): |
| 6 | out.write("usage: gpgrep PATTERN FILENAME\n") |
| 7 | |
| 8 | opts, args = getopt.getopt(sys.argv[1:], "h") |
| 9 | for o, a in opts: |
| 10 | if o == "-h": |
| 11 | usage(sys.stdout) |
| 12 | sys.exit(0) |
| 13 | if len(args) < 2: |
| 14 | usage(sys.stderr) |
| 15 | sys.exit(1) |
| 16 | |
| 17 | try: |
| 18 | pattern = re.compile(args[0], re.IGNORECASE) |
| 19 | except Exception as exc: |
| 20 | sys.stderr.write("gpgrep: %s: %s\n" % (args[0], exc)) |
| 21 | sys.exit(1) |
| 22 | try: |
| 23 | efp = open(args[1], "r") |
| 24 | except OSError as exc: |
| 25 | sys.stderr.write("gpgrep: %s: %s\n" % (args[1], exc.strerror)) |
| 26 | sys.exit(1) |
| 27 | with efp, subprocess.Popen(["gpg", "--quiet", "--decrypt", "--armor"], stdin=efp, stdout=subprocess.PIPE, universal_newlines=True) as gpg: |
| 28 | try: |
| 29 | for line in gpg.stdout: |
| 30 | line = line.rstrip() |
| 31 | if len(line) > 0 and not line[0].isspace() and pattern.search(line): |
| 32 | sys.stdout.write("%s\n" % (line)) |
| 33 | for line in gpg.stdout: |
| 34 | line = line.rstrip() |
| 35 | if line == "" or not line[0].isspace(): |
| 36 | break |
| 37 | sys.stdout.write("%s\n" % (line)) |
| 38 | sys.exit(0) |
| 39 | sys.exit(1) |
| 40 | finally: |
| 41 | gpg.stdout.close() |
| 42 | if gpg.wait() != 0: |
| 43 | sys.stderr.write("gpgrep: gpg failed\n") |
| 44 | sys.exit(1) |