]> git.phdru.name Git - git-scripts.git/blob - set-commit-date.py
Feat(submodules/remove): Add option `-c`
[git-scripts.git] / set-commit-date.py
1 #! /usr/bin/env python
2
3 # Find commit date/time for every commit, list files in the commit
4 # and set the file's modification time to the date/time of the latest commit.
5
6 # Adapted from https://git.wiki.kernel.org/index.php/ExampleScripts#Setting_the_timestamps_of_the_files_to_the_commit_timestamp_of_the_commit_which_last_touched_them  # noqa
7
8 import os
9 import subprocess
10
11 git_root = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'],
12                                    universal_newlines=True).rstrip('\n')
13 os.chdir(git_root)
14
15 separator = '----- GIT LOG SEPARATOR -----'
16
17 git_log = subprocess.Popen(['git', 'log', '-m', '--first-parent',
18                             '--name-only', '--no-color',
19                             '--format=%s%%n%%ct' % separator],
20                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
21                            universal_newlines=True)
22 filenames = set()
23 # stages: 1 - start of commit, 2 - timestamp, 3 - empty line, 4 - files
24 stage = 1
25 for line in git_log.stdout:
26     line = line.strip()
27     if (stage in (1, 4)) and (line == separator):  # Start of a commit
28         stage = 2
29     elif stage == 2:
30         stage = 3
31         time = int(line)
32     elif stage == 3:
33         if line == separator:  # Null-merge (git merge -s ours), no files
34             stage = 2
35             continue
36         stage = 4
37         assert line == '', line
38     elif stage == 4:
39         filename = line
40         if filename not in filenames:
41             filenames.add(filename)
42             if os.path.exists(filename):
43                 os.utime(filename, (time, time))
44     else:
45         raise ValueError("stage: %d, line: %s" % (stage, line))
46
47 git_log.wait()
48 git_log.stdout.close()