Debian Codegraph @

helper/update_changelog.py

raw
1 #!/usr/bin/env python3
2 import typer
3 import os
4 import glob
5 import subprocess
6 import sys
7 from dateutil import parser
8 from dateutil import tz
9 from typing import (
10 Annotated, Optional
11 )
12 from pathlib import Path
13
14
15 def main(
16 since: Annotated[
17 Optional[Path], typer.Option(
18 help='changes since the latest entry in the reference file'
19 )
20 ] = None,
21 file: Annotated[
22 Optional[Path], typer.Option(
23 help='changes from the given file'
24 )
25 ] = None,
26 utc: Annotated[
27 Optional[bool], typer.Option(
28 '--utc',
29 help='print date/time in UTC'
30 )
31 ] = False,
32 fix: Annotated[
33 Optional[bool], typer.Option(
34 '--fix',
35 help='lookup .fix files and apply them'
36 )
37 ] = False
38 ):
39 if not since and not file:
40 print('Either --since or --file must be specified')
41 sys.exit(1)
42 if since and file:
43 print('Only one of --since or --file must be specified')
44 sys.exit(1)
45
46 # Commandline arguments
47 arguments = {
48 '--since': since,
49 '--file': file,
50 '--utc': utc,
51 '--fix': fix
52 }
53
54 # Latest date of the given reference file
55 date_reference = None
56
57 # List of skipped commits older than date_reference
58 skip_list = []
59
60 # hash of git history log entries
61 log_data = {}
62
63 # raw list of log lines from git history or reference file
64 log_lines = []
65
66 # Author and Date
67 log_author = None
68 log_date = None
69
70 # changelog header line
71 log_start = '-' * 67 + os.linesep
72
73 # date format for rpm changelog
74 date_format = '%a %b %d %T %Z %Y'
75
76 # commit message
77 commit_message = []
78
79 # Open reference log file
80 reference_file = arguments['--since'] or arguments['--file']
81
82 # Custom fix files
83 fix_dict = {}
84 if arguments['--fix']:
85 for fix in glob.iglob(f'{os.path.dirname(reference_file)}/*.fix'):
86 sys.stderr.write(f'Reading fix: {fix}{os.linesep}')
87 with open(fix, 'r') as fixlog:
88 commit = fixlog.readline()
89 fix_dict[commit] = fixlog.read()
90
91 if arguments['--since']:
92 # Read latest date from reference file
93 with open(reference_file, 'r') as gitlog:
94 # read commit and author
95 gitlog.readline()
96 gitlog.readline()
97 # read date
98 latest_date = gitlog.readline().replace('AuthorDate:', '').strip()
99 date_reference = parser.parse(latest_date)
100
101 # Read git history since latest entry from reference file
102 process = subprocess.Popen(
103 [
104 'git', 'log', '--no-merges', '--format=fuller',
105 '--since="{0}"'.format(latest_date)
106 ], stdout=subprocess.PIPE
107 )
108 from_git_log = True
109 for line in iter(process.stdout.readline, b''):
110 if line.startswith(b'commit'):
111 commit = line.decode()
112 if from_git_log and fix_dict.get(commit):
113 sys.stderr.write(f' Apply fix for: {commit}')
114 from_git_log = False
115 log_lines.append(line)
116 for fix_line in fix_dict.get(commit).split(os.linesep):
117 log_lines.append(fix_line.encode())
118 elif not from_git_log:
119 from_git_log = True
120
121 if from_git_log:
122 log_lines.append(line)
123 else:
124 with open(reference_file, 'rb') as gitlog:
125 log_lines = gitlog.readlines()
126
127 # Iterate over log data and convert to changelog format
128 for line_data in log_lines:
129 line = line_data.decode(encoding='utf-8')
130 if line.startswith('commit'):
131 if commit_message:
132 commit_message.pop(0)
133 message_header = commit_message.pop(0).lstrip()
134 message_body = []
135 for line in commit_message:
136 message_line = line.lstrip()
137 if not message_line:
138 message_body.append(os.linesep)
139 else:
140 message_body.append(
141 ' {0}{1}'.format(message_line, os.linesep)
142 )
143 log_data[log_date] = ''.join(
144 [
145 log_start,
146 '{0} - {1}{2}{2}'.format(
147 log_date.astimezone(
148 tz.UTC if arguments['--utc'] else tz.tzlocal()
149 ).strftime(date_format), log_author, os.linesep
150 ),
151 '- {0}{1}'.format(
152 message_header, os.linesep
153 )
154 ] + message_body
155 )
156 commit_message = []
157 elif line.startswith('Author:'):
158 log_author = line.replace('Author:', '').strip()
159 elif line.startswith('AuthorDate:'):
160 log_date = parser.parse(line.replace('AuthorDate:', '').strip())
161 elif line.startswith('Commit:'):
162 pass
163 elif line.startswith('CommitDate:'):
164 pass
165 else:
166 commit_message.append(line.strip())
167
168 # print in changelog format on stdout
169 for author_date in reversed(sorted(log_data.keys())):
170 if date_reference:
171 if date_reference < author_date:
172 sys.stdout.write(log_data[author_date])
173 else:
174 skip_list.append(author_date)
175 else:
176 sys.stdout.write(log_data[author_date])
177
178 # print inconsistencies if any on stderr
179 if skip_list:
180 sys.stderr.write(
181 'Reference Date: {0}{1}'.format(date_reference, os.linesep)
182 )
183 for date in skip_list:
184 sys.stderr.write(
185 ' + Skipped: {0}: past reference{1}'.format(
186 date, os.linesep
187 )
188 )
189
190 if __name__ == "__main__":
191 typer.run(main)