Browse Source

Enable use as a revision control diff

Steven Myint 12 years ago
parent
commit
ed0ce1cbf3
1 changed files with 20 additions and 4 deletions
  1. 20
    4
      src/cdiff.py

+ 20
- 4
src/cdiff.py View File

@@ -17,6 +17,7 @@ IS_PY3 = sys.hexversion >= 0x03000000
17 17
 
18 18
 import os
19 19
 import re
20
+import subprocess
20 21
 import errno
21 22
 import difflib
22 23
 
@@ -471,9 +472,22 @@ def markup_to_pager(stream):
471 472
     pager.wait()
472 473
 
473 474
 
475
+def revision_control_diff(path):
476
+    """Return diff from revision control system."""
477
+    if subprocess.call(['git', 'rev-parse'], stderr=subprocess.PIPE) == 0:
478
+        return subprocess.Popen(['git', 'diff'], stdout=subprocess.PIPE).stdout
479
+
480
+
481
+def decode(line):
482
+    """Decode UTF-8 if necessary."""
483
+    try:
484
+        return line.decode('utf-8')
485
+    except AttributeError:
486
+        return line
487
+
488
+
474 489
 if __name__ == '__main__':
475 490
     import optparse
476
-    import subprocess
477 491
 
478 492
     usage = '''%s [options] [diff]''' % os.path.basename(sys.argv[0])
479 493
     description= ('''View incremental, colored diff in unified format or '''
@@ -494,13 +508,15 @@ if __name__ == '__main__':
494 508
         else:
495 509
             diff_hdl = open(args[0], mode='rt')
496 510
     elif sys.stdin.isatty():
497
-        parser.print_help()
498
-        sys.exit(1)
511
+        diff_hdl = revision_control_diff(os.getcwd())
512
+        if not diff_hdl:
513
+            parser.print_help()
514
+            sys.exit(1)
499 515
     else:
500 516
         diff_hdl = sys.stdin
501 517
 
502 518
     # FIXME: can't use generator for now due to current implementation in parser
503
-    stream = diff_hdl.readlines()
519
+    stream = [decode(l) for l in diff_hdl.readlines()]
504 520
 
505 521
     # Don't let empty diff pass thru
506 522
     if not stream: