+#!/usr/bin/python3
+
+import sys, getopt, subprocess, re
+
+def usage(out):
+ out.write("usage: gpgrep PATTERN FILENAME\n")
+
+opts, args = getopt.getopt(sys.argv[1:], "h")
+for o, a in opts:
+ if o == "-h":
+ usage(sys.stdout)
+ sys.exit(0)
+if len(args) < 2:
+ usage(sys.stderr)
+ sys.exit(1)
+
+try:
+ pattern = re.compile(args[0], re.IGNORECASE)
+except Exception as exc:
+ sys.stderr.write("gpgrep: %s: %s\n" % (args[0], exc))
+ sys.exit(1)
+try:
+ efp = open(args[1], "r")
+except OSError as exc:
+ sys.stderr.write("gpgrep: %s: %s\n" % (args[1], exc.strerror))
+ sys.exit(1)
+with efp, subprocess.Popen(["gpg", "--quiet", "--decrypt", "--armor"], stdin=efp, stdout=subprocess.PIPE, universal_newlines=True) as gpg:
+ try:
+ for line in gpg.stdout:
+ line = line.rstrip()
+ if len(line) > 0 and not line[0].isspace() and pattern.search(line):
+ sys.stdout.write("%s\n" % (line))
+ for line in gpg.stdout:
+ line = line.rstrip()
+ if line == "" or not line[0].isspace():
+ break
+ sys.stdout.write("%s\n" % (line))
+ sys.exit(0)
+ sys.exit(1)
+ finally:
+ gpg.stdout.close()
+ if gpg.wait() != 0:
+ sys.stderr.write("gpgrep: gpg failed\n")
+ sys.exit(1)