Added dispatching to the index module
[git-stats.git] / src / git_stats / index.py
blob681c5cf3077d04e4eb238f7458ccd36f3655bd91
1 #!/usr/bin/env python
3 import os
4 import sys
6 from optparse import OptionParser
7 from git_python import Git
9 from git_stats import commit
11 def stagedChanges(ignoreAddedFiles=False):
12 """Returns the paths to all files that have changes staged.
13 When calling this function the current directory should be the root
14 of the git directory that should be acted on.
16 Params:
17 ignoreAddedFiles: When True files that added newly are ignored.
19 Returns:
20 A list of paths that were changed.
21 """
23 git = Git(".")
24 result = git.diff_index("--cached", "--name-status", "HEAD")
26 log = result.split('\n')
28 changed = []
30 for line in log:
31 # Skip the last empty line
32 if len(line.lstrip()) == 0:
33 continue
35 splitline = line.split('\t')
37 # Skip files that were freshly added
38 if splitline[0] == 'A' and ignoreAddedFiles:
39 continue
41 changed.append(splitline[1])
43 return changed
45 def touched(showAll):
46 """Returns which commits touched the same files as the staged changes.
48 Args:
49 showAll: When true, all files, even new ones, are searched.
51 Returns: If there were no staged changes, None is returned.
52 Otherwise the list of matching commits is returned.
53 """
55 staged = stagedChanges(not showAll)
57 if not staged:
58 return None
60 touched = commit.commitsThatTouched(staged)
61 return touched
63 def dispatch(*args):
64 """Dispatches index related commands
65 """
67 progname = os.path.basename(sys.argv[0]) + " index"
69 parser = OptionParser(prog=progname)
71 parser.add_option(
72 "-a", "--all",
73 action="store_true",
74 help="search even new files, which usually have no matching commits")
76 (options, args) = parser.parse_args(list(args))
78 result = touched(options.all)
80 if not result:
81 print("No changes staged (or only new files added)")
82 return
84 commit.prettyPrint(result)