3 import os, re, argparse, subprocess
4 from datetime import datetime
6 NULL_COMMIT_RE = re.compile(r'\0\0commit [a-f0-9]{40}$|\0$')
10 cmd = 'git rev-parse --show-toplevel 2>/dev/null || echo .'
11 top_dir = subprocess.check_output(cmd, shell=True, encoding='utf-8').strip()
12 args.git_dir = os.path.join(top_dir, '.git')
16 git = [ 'git', '--git-dir=' + args.git_dir ]
19 cmd = git + 'ls-tree -z -r --name-only'.split() + [ args.tree ]
21 cmd = git + 'ls-files -z'.split()
23 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf-8')
24 out = proc.communicate()[0]
25 ls = set(out.split('\0'))
29 # All modified files keep their current mtime.
30 proc = subprocess.Popen(git + 'status -z --no-renames'.split(), stdout=subprocess.PIPE, encoding='utf-8')
31 out = proc.communicate()[0]
32 for fn in out.split('\0'):
33 if fn == '' or (fn[0] != 'M' and fn[1] != 'M'):
37 mtime = os.lstat(fn).st_mtime
38 print_line(fn, mtime, mtime)
41 cmd = git + 'log -r --name-only --format=%x00commit%x20%H%n%x00commit_time%x20%ct%n --no-renames -z'.split()
44 cmd += ['--'] + args.files
46 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, encoding='utf-8')
47 for line in proc.stdout:
49 m = re.match(r'^\0commit_time (\d+)$', line)
51 commit_time = int(m[1])
52 elif NULL_COMMIT_RE.search(line):
53 line = NULL_COMMIT_RE.sub('', line)
54 files = set(fn for fn in line.split('\0') if fn in ls)
60 mtime = os.lstat(fn).st_mtime
62 print_line(fn, mtime, commit_time)
63 elif mtime != commit_time:
65 print(f"Setting {fn}")
66 os.utime(fn, (commit_time, commit_time), follow_symlinks = False)
73 def print_line(fn, mtime, commit_time):
75 ts = str(commit_time).rjust(10)
77 ts = datetime.utcfromtimestamp(commit_time).strftime("%Y-%m-%d %H:%M:%S")
78 chg = '.' if mtime == commit_time else '*'
82 if __name__ == '__main__':
83 parser = argparse.ArgumentParser(description="Set the times of the files in the current git checkout to their last-changed time.", add_help=False)
84 parser.add_argument('--git-dir', metavar='GIT_DIR', help="The git dir to query (defaults to affecting the current git checkout).")
85 parser.add_argument('--tree', metavar='TREE-ISH', help="The tree-ish to query (defaults to the current branch).")
86 parser.add_argument('--prefix', metavar='PREFIX_STR', help="Prepend the PREFIX_STR to each filename we tweak (defaults to the top of current checkout).")
87 parser.add_argument('--quiet', '-q', action='store_true', help="Don't output the changed-file information.")
88 parser.add_argument('--list', '-l', action='count', help="List files & times instead of changing them. Repeat for Unix timestamp instead of human readable.")
89 parser.add_argument('files', metavar='FILE', nargs='*', help="Specify a subset of checked-out files to tweak.")
90 parser.add_argument("--help", "-h", action="help", help="Output this help message and exit.")
91 args = parser.parse_args()