]> git.phdru.name Git - git-scripts.git/blob - set-commit-date.py
Refactor(set-commit-date.py): Use git_log.stdout as an iterator
[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 separator = '----- GIT LOG SEPARATOR -----'
12
13 git_log = subprocess.Popen(['git', 'log', '-m', '--first-parent',
14                             '--name-only', '--no-color',
15                             '--format=%s%%n%%ct' % separator],
16                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
17                            universal_newlines=True)
18 filenames = set()
19 # stages: 1 - start of commit, 2 - timestamp, 3 - empty line, 4 - files
20 stage = 1
21 for line in git_log.stdout:
22     line = line.strip()
23     if (stage in (1, 4)) and (line == separator):  # Start of a commit
24         stage = 2
25     elif stage == 2:
26         stage = 3
27         time = int(line)
28     elif stage == 3:
29         if line == separator:  # Null-merge (git merge -s ours), no files
30             stage = 2
31             continue
32         stage = 4
33         assert line == '', line
34     elif stage == 4:
35         filename = line
36         if filename not in filenames:
37             filenames.add(filename)
38             if os.path.exists(filename):
39                 os.utime(filename, (time, time))
40     else:
41         raise ValueError("stage: %d, line: %s" % (stage, line))
42
43 git_log.wait()
44 git_log.stdout.close()