Added gpgrep.
authorFredrik Tolf <fredrik@dolda2000.com>
Fri, 12 Oct 2018 16:50:40 +0000 (18:50 +0200)
committerFredrik Tolf <fredrik@dolda2000.com>
Fri, 12 Oct 2018 16:50:40 +0000 (18:50 +0200)
gpgrep [new file with mode: 0755]

diff --git a/gpgrep b/gpgrep
new file mode 100755 (executable)
index 0000000..7734a8d
--- /dev/null
+++ b/gpgrep
@@ -0,0 +1,44 @@
+#!/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)