]> git.ozlabs.org Git - patchwork/blobdiff - apps/patchwork/parser.py
models: fix From header in mbox view
[patchwork] / apps / patchwork / parser.py
index 8ed36ccb59bcf3d392dc98602e8d525838ae0b98..f4605668e67a78f9f7cbd1a5e4018251ba2caf17 100644 (file)
@@ -68,7 +68,7 @@ def parse_patch(text):
         line += '\n'
 
         if state == 0:
-            if line.startswith('diff') or line.startswith('===') \
+            if line.startswith('diff ') or line.startswith('===') \
                     or line.startswith('Index: '):
                 state = 1
                 buf += line
@@ -133,6 +133,9 @@ def parse_patch(text):
                 lc[0] -= 1
             elif line.startswith('+'):
                 lc[1] -= 1
+            elif line.startswith('\ No newline at end of file'):
+                # Special case: Not included as part of the hunk's line count
+                pass
             else:
                 lc[0] -= 1
                 lc[1] -= 1
@@ -205,11 +208,34 @@ def hash_patch(str):
 
     return hash
 
-if __name__ == '__main__':
-    import sys
-    (patch, comment) = parse_patch(sys.stdin.read())
-    if patch:
+
+def main(args):
+    from optparse import OptionParser
+
+    parser = OptionParser()
+    parser.add_option('-p', '--patch', action = 'store_true',
+            dest = 'print_patch', help = 'print parsed patch')
+    parser.add_option('-c', '--comment', action = 'store_true',
+            dest = 'print_comment', help = 'print parsed comment')
+    parser.add_option('-#', '--hash', action = 'store_true',
+            dest = 'print_hash', help = 'print patch hash')
+
+    (options, args) = parser.parse_args()
+
+    # decode from (assumed) UTF-8
+    content = sys.stdin.read().decode('utf-8')
+
+    (patch, comment) = parse_patch(content)
+
+    if options.print_hash and patch:
+        print hash_patch(patch).hexdigest()
+
+    if options.print_patch and patch:
         print "Patch: ------\n" + patch
-        print "hash: %s" % hash_patch(patch).hexdigest()
-    if comment:
+
+    if options.print_comment and comment:
         print "Comment: ----\n" + comment
+
+if __name__ == '__main__':
+    import sys
+    sys.exit(main(sys.argv))