Add mailcap post.
[blog.git] / posts / mailcap / mailcap-test.py
diff --git a/posts/mailcap/mailcap-test.py b/posts/mailcap/mailcap-test.py
new file mode 100755 (executable)
index 0000000..8990b7c
--- /dev/null
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Copyright (C) 2011 W. Trevor King <wking@drexel.edu>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this program.  If not, see
+# <http://www.gnu.org/licenses/>.
+
+"View files using mailcap-specified commands."
+
+import mailcap as _mailcap
+import mimetypes as _mimetypes
+import subprocess as _subprocess
+
+
+_CAPS = _mailcap.getcaps()
+
+def view(filename, mime=None):
+    if mime is None:
+        mime,encoding = _mimetypes.guess_type(filename)
+        if mime is None:
+            return 1
+        print('guessed {} for {}'.format(mime, filename))
+    match = _mailcap.findmatch(_CAPS, mime, filename=filename)
+    if match[0] is None:
+        return 1
+    print('view {} with {}'.format(filename, match[0]))
+    return _subprocess.call(match[0], shell=True)
+
+
+if __name__ == '__main__':
+    import argparse
+    import sys
+
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument(
+        'files', metavar='FILE', nargs='+', help='file to view')
+
+    args = parser.parse_args()
+
+    for filename in args.files:
+        rc = view(filename)
+        if rc != 0:
+            sys.exit(rc)