2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
7 Invokes git diff [args...] and inserts file:line in front of each line of diff
10 This is useful from an IDE that allows you to double-click lines that begin
11 with file:line to open and jump to that point in the file.
14 %prog [git diff args...]
25 def GitShell(args
, ignore_return
=False):
26 """A shell invocation suitable for communicating with git. Returns
27 output as list of lines, raises exception on error.
29 job
= subprocess
.Popen(args
,
31 stdout
=subprocess
.PIPE
,
32 stderr
=subprocess
.STDOUT
)
33 (out
, err
) = job
.communicate()
34 if job
.returncode
!= 0 and not ignore_return
:
36 raise Exception("Error %d running command %s" % (
37 job
.returncode
, args
))
38 return out
.split('\n')
41 def PrintGitDiff(extra_args
):
42 """Outputs git diff extra_args with file:line inserted into relevant lines."""
45 lines
= GitShell('git diff %s' % ' '.join(extra_args
))
48 # diff --git a/file.c b/file.c
49 # index 0e38c2d..8cd69ae 100644
51 if (line
.startswith('diff ') or
52 line
.startswith('index ') or
53 line
.startswith('--- ')):
57 # Get the filename from the +++ line:
59 if line
.startswith('+++ '):
60 # Filename might be /dev/null or a/file or b/file.
61 # Skip the first two characters unless it starts with /.
62 current_file
= line
[4:] if line
[4] == '/' else line
[6:]
66 # Update line number from the @@ lines:
67 # @@ -41,9 +41,9 @@ def MyFunc():
69 if line
.startswith('@@ '):
70 _
, old_nr
, new_nr
, _
= line
.split(' ', 3)
71 line_num
= int(new_nr
.split(',')[0])
74 print current_file
+ ':' + repr(line_num
) + ':' + line
76 # Increment line number for lines that start with ' ' or '+':
77 # @@ -41,4 +41,4 @@ def MyFunc():
78 # file.c:41: // existing code
79 # file.c:42: // existing code
80 # file.c:43:-// deleted code
81 # file.c:43:-// deleted code
82 # file.c:43:+// inserted code
83 # file.c:44:+// inserted code
84 if line
.startswith(' ') or line
.startswith('+'):
89 PrintGitDiff(sys
.argv
[1:])
92 if __name__
== '__main__':