blob: b2fa96a07e85b2d72866c639e77ce8fdb8c1f673 [file] [log] [blame]
Gilles Peskine40b3f412019-10-13 21:44:25 +02001#!/usr/bin/env python3
2
Gilles Peskine42f384c2020-03-27 09:23:38 +01003"""Assemble Mbed TLS change log entries into the change log file.
Gilles Peskinea2607962020-01-28 19:58:17 +01004
5Add changelog entries to the first level-2 section.
6Create a new level-2 section for unreleased changes if needed.
7Remove the input files unless --keep-entries is specified.
Gilles Peskine28af9582020-03-26 22:39:18 +01008
9In each level-3 section, entries are sorted in chronological order
10(oldest first). From oldest to newest:
11* Merged entry files are sorted according to their merge date (date of
12 the merge commit that brought the commit that created the file into
13 the target branch).
14* Committed but unmerged entry files are sorted according to the date
15 of the commit that adds them.
16* Uncommitted entry files are sorted according to their modification time.
17
18You must run this program from within a git working directory.
Gilles Peskine40b3f412019-10-13 21:44:25 +020019"""
20
Bence Szépkúti1e148272020-08-07 13:07:28 +020021# Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +000022# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskine40b3f412019-10-13 21:44:25 +020023
24import argparse
Gilles Peskine6e97c432020-03-27 19:05:18 +010025from collections import OrderedDict, namedtuple
Gilles Peskine8f46bbf2020-03-25 16:34:43 +010026import datetime
27import functools
Gilles Peskine40b3f412019-10-13 21:44:25 +020028import glob
29import os
30import re
Gilles Peskine8f46bbf2020-03-25 16:34:43 +010031import subprocess
Gilles Peskine40b3f412019-10-13 21:44:25 +020032import sys
33
34class InputFormatError(Exception):
35 def __init__(self, filename, line_number, message, *args, **kwargs):
Gilles Peskine566407d2020-01-22 15:55:36 +010036 message = '{}:{}: {}'.format(filename, line_number,
37 message.format(*args, **kwargs))
38 super().__init__(message)
Gilles Peskine40b3f412019-10-13 21:44:25 +020039
Gilles Peskine4d977a42020-03-27 19:42:50 +010040class CategoryParseError(Exception):
41 def __init__(self, line_offset, error_message):
42 self.line_offset = line_offset
43 self.error_message = error_message
44 super().__init__('{}: {}'.format(line_offset, error_message))
45
Gilles Peskine2b242492020-01-22 15:41:50 +010046class LostContent(Exception):
47 def __init__(self, filename, line):
48 message = ('Lost content from {}: "{}"'.format(filename, line))
49 super().__init__(message)
50
Dave Rodgman3901e2e2023-10-02 16:40:57 +010051class FilePathError(Exception):
52 def __init__(self, filenames):
53 message = ('Changelog filenames do not end with .txt: {}'.format(", ".join(filenames)))
54 super().__init__(message)
55
Gilles Peskineb695d5e2020-03-27 20:06:12 +010056# The category names we use in the changelog.
57# If you edit this, update ChangeLog.d/README.md.
Gilles Peskine6e97c432020-03-27 19:05:18 +010058STANDARD_CATEGORIES = (
Gilles Peskine7261fff2021-05-18 14:39:40 +020059 'API changes',
60 'Default behavior changes',
61 'Requirement changes',
62 'New deprecations',
63 'Removals',
64 'Features',
65 'Security',
66 'Bugfix',
67 'Changes',
Gilles Peskine40b3f412019-10-13 21:44:25 +020068)
69
Paul Elliottf08648d2021-03-05 12:22:51 +000070# The maximum line length for an entry
71MAX_LINE_LENGTH = 80
72
Gilles Peskine6e97c432020-03-27 19:05:18 +010073CategoryContent = namedtuple('CategoryContent', [
74 'name', 'title_line', # Title text and line number of the title
75 'body', 'body_line', # Body text and starting line number of the body
76])
77
78class ChangelogFormat:
79 """Virtual class documenting how to write a changelog format class."""
80
81 @classmethod
82 def extract_top_version(cls, changelog_file_content):
83 """Split out the top version section.
84
Gilles Peskineeebf24f2020-03-27 19:25:38 +010085 If the top version is already released, create a new top
86 version section for an unreleased version.
Gilles Peskinedba4de02020-03-30 11:37:26 +020087
88 Return ``(header, top_version_title, top_version_body, trailer)``
89 where the "top version" is the existing top version section if it's
90 for unreleased changes, and a newly created section otherwise.
91 To assemble the changelog after modifying top_version_body,
92 concatenate the four pieces.
Gilles Peskine6e97c432020-03-27 19:05:18 +010093 """
94 raise NotImplementedError
95
96 @classmethod
97 def version_title_text(cls, version_title):
98 """Return the text of a formatted version section title."""
99 raise NotImplementedError
100
101 @classmethod
102 def split_categories(cls, version_body):
103 """Split a changelog version section body into categories.
104
105 Return a list of `CategoryContent` the name is category title
106 without any formatting.
107 """
108 raise NotImplementedError
109
110 @classmethod
111 def format_category(cls, title, body):
112 """Construct the text of a category section from its title and body."""
113 raise NotImplementedError
114
115class TextChangelogFormat(ChangelogFormat):
116 """The traditional Mbed TLS changelog format."""
117
Gabor Mezei8933c042023-11-21 17:05:43 +0100118 _unreleased_version_text = '= {} x.x.x branch released xxxx-xx-xx'
Gilles Peskineeebf24f2020-03-27 19:25:38 +0100119 @classmethod
120 def is_released_version(cls, title):
121 # Look for an incomplete release date
Gilles Peskine7261fff2021-05-18 14:39:40 +0200122 return not re.search(r'[0-9x]{4}-[0-9x]{2}-[0-9x]?x', title)
Gilles Peskineeebf24f2020-03-27 19:25:38 +0100123
Gilles Peskine7261fff2021-05-18 14:39:40 +0200124 _top_version_re = re.compile(r'(?:\A|\n)(=[^\n]*\n+)(.*?\n)(?:=|$)',
Gilles Peskine6e97c432020-03-27 19:05:18 +0100125 re.DOTALL)
Gabor Mezei8933c042023-11-21 17:05:43 +0100126 _name_re = re.compile(r'=\s(.*)\s[0-9x]+\.', re.DOTALL)
Gilles Peskine6e97c432020-03-27 19:05:18 +0100127 @classmethod
128 def extract_top_version(cls, changelog_file_content):
129 """A version section starts with a line starting with '='."""
130 m = re.search(cls._top_version_re, changelog_file_content)
Gabor Mezei4e574db2023-11-22 17:48:00 +0100131 top_version_start = m.start(1)
132 top_version_end = m.end(2)
133 top_version_title = m.group(1)
134 top_version_body = m.group(2)
135 name = re.match(cls._name_re, top_version_title).group(1)
Gilles Peskineeebf24f2020-03-27 19:25:38 +0100136 if cls.is_released_version(top_version_title):
137 top_version_end = top_version_start
Gabor Mezei8933c042023-11-21 17:05:43 +0100138 top_version_title = cls._unreleased_version_text.format(name) + '\n\n'
Gilles Peskine7261fff2021-05-18 14:39:40 +0200139 top_version_body = ''
Gilles Peskine6e97c432020-03-27 19:05:18 +0100140 return (changelog_file_content[:top_version_start],
Gilles Peskineeebf24f2020-03-27 19:25:38 +0100141 top_version_title, top_version_body,
Gilles Peskine6e97c432020-03-27 19:05:18 +0100142 changelog_file_content[top_version_end:])
143
144 @classmethod
145 def version_title_text(cls, version_title):
Gilles Peskine7261fff2021-05-18 14:39:40 +0200146 return re.sub(r'\n.*', version_title, re.DOTALL)
Gilles Peskine6e97c432020-03-27 19:05:18 +0100147
Gilles Peskine7261fff2021-05-18 14:39:40 +0200148 _category_title_re = re.compile(r'(^\w.*)\n+', re.MULTILINE)
Gilles Peskine6e97c432020-03-27 19:05:18 +0100149 @classmethod
150 def split_categories(cls, version_body):
151 """A category title is a line with the title in column 0."""
Gilles Peskine4d977a42020-03-27 19:42:50 +0100152 if not version_body:
Gilles Peskine6e97c432020-03-27 19:05:18 +0100153 return []
Gilles Peskine4d977a42020-03-27 19:42:50 +0100154 title_matches = list(re.finditer(cls._category_title_re, version_body))
155 if not title_matches or title_matches[0].start() != 0:
156 # There is junk before the first category.
157 raise CategoryParseError(0, 'Junk found where category expected')
Gilles Peskine6e97c432020-03-27 19:05:18 +0100158 title_starts = [m.start(1) for m in title_matches]
159 body_starts = [m.end(0) for m in title_matches]
160 body_ends = title_starts[1:] + [len(version_body)]
Gilles Peskine7261fff2021-05-18 14:39:40 +0200161 bodies = [version_body[body_start:body_end].rstrip('\n') + '\n'
Gilles Peskine6e97c432020-03-27 19:05:18 +0100162 for (body_start, body_end) in zip(body_starts, body_ends)]
Gilles Peskine7261fff2021-05-18 14:39:40 +0200163 title_lines = [version_body[:pos].count('\n') for pos in title_starts]
164 body_lines = [version_body[:pos].count('\n') for pos in body_starts]
Gilles Peskine6e97c432020-03-27 19:05:18 +0100165 return [CategoryContent(title_match.group(1), title_line,
166 body, body_line)
167 for title_match, title_line, body, body_line
168 in zip(title_matches, title_lines, bodies, body_lines)]
169
170 @classmethod
171 def format_category(cls, title, body):
172 # `split_categories` ensures that each body ends with a newline.
173 # Make sure that there is additionally a blank line between categories.
Gilles Peskine7261fff2021-05-18 14:39:40 +0200174 if not body.endswith('\n\n'):
175 body += '\n'
176 return title + '\n' + body
Gilles Peskine6e97c432020-03-27 19:05:18 +0100177
Gilles Peskine40b3f412019-10-13 21:44:25 +0200178class ChangeLog:
Gilles Peskine42f384c2020-03-27 09:23:38 +0100179 """An Mbed TLS changelog.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200180
Gilles Peskine6e97c432020-03-27 19:05:18 +0100181 A changelog file consists of some header text followed by one or
182 more version sections. The version sections are in reverse
183 chronological order. Each version section consists of a title and a body.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200184
Gilles Peskine6e97c432020-03-27 19:05:18 +0100185 The body of a version section consists of zero or more category
186 subsections. Each category subsection consists of a title and a body.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200187
Gilles Peskine6e97c432020-03-27 19:05:18 +0100188 A changelog entry file has the same format as the body of a version section.
189
190 A `ChangelogFormat` object defines the concrete syntax of the changelog.
191 Entry files must have the same format as the changelog file.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200192 """
193
Gilles Peskinea2607962020-01-28 19:58:17 +0100194 # Only accept dotted version numbers (e.g. "3.1", not "3").
Gilles Peskineafc9db82020-01-30 11:38:01 +0100195 # Refuse ".x" in a version number where x is a letter: this indicates
196 # a version that is not yet released. Something like "3.1a" is accepted.
Gilles Peskine7261fff2021-05-18 14:39:40 +0200197 _version_number_re = re.compile(r'[0-9]+\.[0-9A-Za-z.]+')
198 _incomplete_version_number_re = re.compile(r'.*\.[A-Za-z]')
199 _only_url_re = re.compile(r'^\s*\w+://\S+\s*$')
200 _has_url_re = re.compile(r'.*://.*')
Gilles Peskinea2607962020-01-28 19:58:17 +0100201
Gilles Peskine6e97c432020-03-27 19:05:18 +0100202 def add_categories_from_text(self, filename, line_offset,
203 text, allow_unknown_category):
204 """Parse a version section or entry file."""
Gilles Peskine4d977a42020-03-27 19:42:50 +0100205 try:
206 categories = self.format.split_categories(text)
207 except CategoryParseError as e:
208 raise InputFormatError(filename, line_offset + e.line_offset,
209 e.error_message)
Gilles Peskine6e97c432020-03-27 19:05:18 +0100210 for category in categories:
211 if not allow_unknown_category and \
212 category.name not in self.categories:
213 raise InputFormatError(filename,
214 line_offset + category.title_line,
215 'Unknown category: "{}"',
Gilles Peskine7261fff2021-05-18 14:39:40 +0200216 category.name)
Paul Elliottf08648d2021-03-05 12:22:51 +0000217
218 body_split = category.body.splitlines()
Mateusz Starzyk3cfed582021-03-31 11:09:21 +0200219
Paul Elliottd75773e2021-03-18 18:07:46 +0000220 for line_number, line in enumerate(body_split, 1):
Mateusz Starzyk3cfed582021-03-31 11:09:21 +0200221 if not self._only_url_re.match(line) and \
Mateusz Starzyk6e470552021-03-24 12:13:33 +0100222 len(line) > MAX_LINE_LENGTH:
Mateusz Starzyk9b31ad62021-03-31 11:18:28 +0200223 long_url_msg = '. URL exceeding length limit must be alone in its line.' \
224 if self._has_url_re.match(line) else ""
Paul Elliottf08648d2021-03-05 12:22:51 +0000225 raise InputFormatError(filename,
Paul Elliottd75773e2021-03-18 18:07:46 +0000226 category.body_line + line_number,
Mateusz Starzykc8f44892021-03-25 14:06:50 +0100227 'Line is longer than allowed: '
228 'Length {} (Max {}){}',
229 len(line), MAX_LINE_LENGTH,
230 long_url_msg)
Paul Elliottf08648d2021-03-05 12:22:51 +0000231
Gilles Peskine6e97c432020-03-27 19:05:18 +0100232 self.categories[category.name] += category.body
233
234 def __init__(self, input_stream, changelog_format):
Gilles Peskine40b3f412019-10-13 21:44:25 +0200235 """Create a changelog object.
236
Gilles Peskine974232f2020-01-22 12:43:29 +0100237 Populate the changelog object from the content of the file
Gilles Peskine6e97c432020-03-27 19:05:18 +0100238 input_stream.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200239 """
Gilles Peskine6e97c432020-03-27 19:05:18 +0100240 self.format = changelog_format
241 whole_file = input_stream.read()
242 (self.header,
243 self.top_version_title, top_version_body,
244 self.trailer) = self.format.extract_top_version(whole_file)
245 # Split the top version section into categories.
246 self.categories = OrderedDict()
247 for category in STANDARD_CATEGORIES:
Gilles Peskine7261fff2021-05-18 14:39:40 +0200248 self.categories[category] = ''
Gabor Mezeiddffa102023-11-21 17:03:29 +0100249 if self.header:
250 offset = (self.header + self.top_version_title).count('\n') + 1
251 else:
252 offset = 0
253
Gilles Peskine6e97c432020-03-27 19:05:18 +0100254 self.add_categories_from_text(input_stream.name, offset,
255 top_version_body, True)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200256
257 def add_file(self, input_stream):
258 """Add changelog entries from a file.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200259 """
Gilles Peskinee248e832020-03-27 19:42:38 +0100260 self.add_categories_from_text(input_stream.name, 1,
Gilles Peskine6e97c432020-03-27 19:05:18 +0100261 input_stream.read(), False)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200262
263 def write(self, filename):
264 """Write the changelog to the specified file.
265 """
Gilles Peskinee151e212021-05-18 14:49:02 +0200266 with open(filename, 'w', encoding='utf-8') as out:
Gabor Mezei4e574db2023-11-22 17:48:00 +0100267 out.write(self.header)
268 out.write(self.top_version_title)
Gilles Peskine6e97c432020-03-27 19:05:18 +0100269 for title, body in self.categories.items():
270 if not body:
Gilles Peskine40b3f412019-10-13 21:44:25 +0200271 continue
Gilles Peskine6e97c432020-03-27 19:05:18 +0100272 out.write(self.format.format_category(title, body))
273 out.write(self.trailer)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200274
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100275
276@functools.total_ordering
Gilles Peskine28af9582020-03-26 22:39:18 +0100277class EntryFileSortKey:
278 """This classes defines an ordering on changelog entry files: older < newer.
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100279
Gilles Peskine28af9582020-03-26 22:39:18 +0100280 * Merged entry files are sorted according to their merge date (date of
281 the merge commit that brought the commit that created the file into
282 the target branch).
283 * Committed but unmerged entry files are sorted according to the date
284 of the commit that adds them.
285 * Uncommitted entry files are sorted according to their modification time.
286
287 This class assumes that the file is in a git working directory with
288 the target branch checked out.
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100289 """
290
291 # Categories of files. A lower number is considered older.
292 MERGED = 0
293 COMMITTED = 1
294 LOCAL = 2
295
296 @staticmethod
297 def creation_hash(filename):
298 """Return the git commit id at which the given file was created.
299
300 Return None if the file was never checked into git.
301 """
Gilles Peskine98a53aa2020-03-26 22:47:07 +0100302 hashes = subprocess.check_output(['git', 'log', '--format=%H',
303 '--follow',
304 '--', filename])
Gilles Peskine7261fff2021-05-18 14:39:40 +0200305 m = re.search('(.+)$', hashes.decode('ascii'))
Gilles Peskine13dc6342020-03-26 22:46:47 +0100306 if not m:
307 # The git output is empty. This means that the file was
308 # never checked in.
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100309 return None
Gilles Peskine13dc6342020-03-26 22:46:47 +0100310 # The last commit in the log is the oldest one, which is when the
311 # file was created.
312 return m.group(0)
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100313
314 @staticmethod
315 def list_merges(some_hash, target, *options):
316 """List merge commits from some_hash to target.
317
318 Pass options to git to select which commits are included.
319 """
320 text = subprocess.check_output(['git', 'rev-list',
321 '--merges', *options,
Gilles Peskine7261fff2021-05-18 14:39:40 +0200322 '..'.join([some_hash, target])])
323 return text.decode('ascii').rstrip('\n').split('\n')
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100324
325 @classmethod
326 def merge_hash(cls, some_hash):
327 """Return the git commit id at which the given commit was merged.
328
329 Return None if the given commit was never merged.
330 """
Gilles Peskine7261fff2021-05-18 14:39:40 +0200331 target = 'HEAD'
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100332 # List the merges from some_hash to the target in two ways.
333 # The ancestry list is the ones that are both descendants of
334 # some_hash and ancestors of the target.
335 ancestry = frozenset(cls.list_merges(some_hash, target,
336 '--ancestry-path'))
337 # The first_parents list only contains merges that are directly
338 # on the target branch. We want it in reverse order (oldest first).
339 first_parents = cls.list_merges(some_hash, target,
340 '--first-parent', '--reverse')
341 # Look for the oldest merge commit that's both on the direct path
342 # and directly on the target branch. That's the place where some_hash
343 # was merged on the target branch. See
344 # https://stackoverflow.com/questions/8475448/find-merge-commit-which-include-a-specific-commit
345 for commit in first_parents:
346 if commit in ancestry:
347 return commit
348 return None
349
350 @staticmethod
351 def commit_timestamp(commit_id):
Gilles Peskineac0f0862020-03-27 10:56:45 +0100352 """Return the timestamp of the given commit."""
353 text = subprocess.check_output(['git', 'show', '-s',
354 '--format=%ct',
355 commit_id])
356 return datetime.datetime.utcfromtimestamp(int(text))
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100357
358 @staticmethod
359 def file_timestamp(filename):
360 """Return the modification timestamp of the given file."""
361 mtime = os.stat(filename).st_mtime
362 return datetime.datetime.fromtimestamp(mtime)
363
364 def __init__(self, filename):
Gilles Peskine28af9582020-03-26 22:39:18 +0100365 """Determine position of the file in the changelog entry order.
366
367 This constructor returns an object that can be used with comparison
368 operators, with `sort` and `sorted`, etc. Older entries are sorted
369 before newer entries.
370 """
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100371 self.filename = filename
372 creation_hash = self.creation_hash(filename)
373 if not creation_hash:
374 self.category = self.LOCAL
375 self.datetime = self.file_timestamp(filename)
376 return
377 merge_hash = self.merge_hash(creation_hash)
378 if not merge_hash:
379 self.category = self.COMMITTED
380 self.datetime = self.commit_timestamp(creation_hash)
381 return
382 self.category = self.MERGED
383 self.datetime = self.commit_timestamp(merge_hash)
384
385 def sort_key(self):
Gilles Peskine28af9582020-03-26 22:39:18 +0100386 """"Return a concrete sort key for this entry file sort key object.
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100387
Gilles Peskine28af9582020-03-26 22:39:18 +0100388 ``ts1 < ts2`` is implemented as ``ts1.sort_key() < ts2.sort_key()``.
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100389 """
390 return (self.category, self.datetime, self.filename)
391
392 def __eq__(self, other):
393 return self.sort_key() == other.sort_key()
394
395 def __lt__(self, other):
396 return self.sort_key() < other.sort_key()
397
398
Gilles Peskine2b242492020-01-22 15:41:50 +0100399def check_output(generated_output_file, main_input_file, merged_files):
400 """Make sanity checks on the generated output.
401
402 The intent of these sanity checks is to have reasonable confidence
403 that no content has been lost.
404
405 The sanity check is that every line that is present in an input file
406 is also present in an output file. This is not perfect but good enough
407 for now.
408 """
Gilles Peskinedcf2ff52022-03-04 20:02:00 +0100409 with open(generated_output_file, 'r', encoding='utf-8') as fd:
410 generated_output = set(fd)
411 for line in open(main_input_file, 'r', encoding='utf-8'):
Gilles Peskine2b242492020-01-22 15:41:50 +0100412 if line not in generated_output:
Gilles Peskinedcf2ff52022-03-04 20:02:00 +0100413 raise LostContent('original file', line)
414 for merged_file in merged_files:
415 for line in open(merged_file, 'r', encoding='utf-8'):
416 if line not in generated_output:
417 raise LostContent(merged_file, line)
Gilles Peskine2b242492020-01-22 15:41:50 +0100418
419def finish_output(changelog, output_file, input_file, merged_files):
Gilles Peskine40b3f412019-10-13 21:44:25 +0200420 """Write the changelog to the output file.
421
Gilles Peskine2b242492020-01-22 15:41:50 +0100422 The input file and the list of merged files are used only for sanity
423 checks on the output.
Gilles Peskine40b3f412019-10-13 21:44:25 +0200424 """
425 if os.path.exists(output_file) and not os.path.isfile(output_file):
426 # The output is a non-regular file (e.g. pipe). Write to it directly.
427 output_temp = output_file
428 else:
429 # The output is a regular file. Write to a temporary file,
430 # then move it into place atomically.
431 output_temp = output_file + '.tmp'
432 changelog.write(output_temp)
Gilles Peskine2b242492020-01-22 15:41:50 +0100433 check_output(output_temp, input_file, merged_files)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200434 if output_temp != output_file:
435 os.rename(output_temp, output_file)
436
Gilles Peskine5e39c9e2020-01-22 14:55:37 +0100437def remove_merged_entries(files_to_remove):
438 for filename in files_to_remove:
439 os.remove(filename)
440
Gilles Peskine27a1fac2020-03-25 16:34:18 +0100441def list_files_to_merge(options):
442 """List the entry files to merge, oldest first.
443
Gilles Peskine28af9582020-03-26 22:39:18 +0100444 "Oldest" is defined by `EntryFileSortKey`.
Dave Rodgman65d8ec12023-10-02 17:19:51 +0100445
446 Also check for required .txt extension
Gilles Peskine27a1fac2020-03-25 16:34:18 +0100447 """
Dave Rodgman65d8ec12023-10-02 17:19:51 +0100448 files_to_merge = glob.glob(os.path.join(options.dir, '*'))
449
450 # Ignore 00README.md
451 readme = os.path.join(options.dir, "00README.md")
452 if readme in files_to_merge:
453 files_to_merge.remove(readme)
454
455 # Identify files without the required .txt extension
456 bad_files = [x for x in files_to_merge if not x.endswith(".txt")]
457 if bad_files:
458 raise FilePathError(bad_files)
459
Gilles Peskine7fa3eb72020-03-26 22:41:32 +0100460 files_to_merge.sort(key=EntryFileSortKey)
Gilles Peskine27a1fac2020-03-25 16:34:18 +0100461 return files_to_merge
462
Gilles Peskine40b3f412019-10-13 21:44:25 +0200463def merge_entries(options):
464 """Merge changelog entries into the changelog file.
465
466 Read the changelog file from options.input.
Dave Rodgman3901e2e2023-10-02 16:40:57 +0100467 Check that all entries have a .txt extension
Gilles Peskine40b3f412019-10-13 21:44:25 +0200468 Read entries to merge from the directory options.dir.
469 Write the new changelog to options.output.
470 Remove the merged entries if options.keep_entries is false.
471 """
Gilles Peskinee151e212021-05-18 14:49:02 +0200472 with open(options.input, 'r', encoding='utf-8') as input_file:
Gilles Peskine6e97c432020-03-27 19:05:18 +0100473 changelog = ChangeLog(input_file, TextChangelogFormat)
Gilles Peskine27a1fac2020-03-25 16:34:18 +0100474 files_to_merge = list_files_to_merge(options)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200475 if not files_to_merge:
476 sys.stderr.write('There are no pending changelog entries.\n')
477 return
478 for filename in files_to_merge:
Gilles Peskinee151e212021-05-18 14:49:02 +0200479 with open(filename, 'r', encoding='utf-8') as input_file:
Gilles Peskine40b3f412019-10-13 21:44:25 +0200480 changelog.add_file(input_file)
Gilles Peskine2b242492020-01-22 15:41:50 +0100481 finish_output(changelog, options.output, options.input, files_to_merge)
Gilles Peskine5e39c9e2020-01-22 14:55:37 +0100482 if not options.keep_entries:
483 remove_merged_entries(files_to_merge)
Gilles Peskine40b3f412019-10-13 21:44:25 +0200484
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100485def show_file_timestamps(options):
486 """List the files to merge and their timestamp.
487
488 This is only intended for debugging purposes.
489 """
490 files = list_files_to_merge(options)
491 for filename in files:
Gilles Peskine28af9582020-03-26 22:39:18 +0100492 ts = EntryFileSortKey(filename)
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100493 print(ts.category, ts.datetime, filename)
494
Gilles Peskine40b3f412019-10-13 21:44:25 +0200495def set_defaults(options):
496 """Add default values for missing options."""
497 output_file = getattr(options, 'output', None)
498 if output_file is None:
499 options.output = options.input
500 if getattr(options, 'keep_entries', None) is None:
501 options.keep_entries = (output_file is not None)
502
503def main():
504 """Command line entry point."""
505 parser = argparse.ArgumentParser(description=__doc__)
506 parser.add_argument('--dir', '-d', metavar='DIR',
507 default='ChangeLog.d',
Gilles Peskine6e910092020-01-22 15:58:18 +0100508 help='Directory to read entries from'
509 ' (default: ChangeLog.d)')
Gilles Peskine40b3f412019-10-13 21:44:25 +0200510 parser.add_argument('--input', '-i', metavar='FILE',
Gilles Peskine6e97c432020-03-27 19:05:18 +0100511 default='ChangeLog',
Gilles Peskine6e910092020-01-22 15:58:18 +0100512 help='Existing changelog file to read from and augment'
Gilles Peskine6e97c432020-03-27 19:05:18 +0100513 ' (default: ChangeLog)')
Gilles Peskine40b3f412019-10-13 21:44:25 +0200514 parser.add_argument('--keep-entries',
515 action='store_true', dest='keep_entries', default=None,
Gilles Peskine6e910092020-01-22 15:58:18 +0100516 help='Keep the files containing entries'
517 ' (default: remove them if --output/-o is not specified)')
Gilles Peskine40b3f412019-10-13 21:44:25 +0200518 parser.add_argument('--no-keep-entries',
519 action='store_false', dest='keep_entries',
Gilles Peskine6e910092020-01-22 15:58:18 +0100520 help='Remove the files containing entries after they are merged'
521 ' (default: remove them if --output/-o is not specified)')
Gilles Peskine40b3f412019-10-13 21:44:25 +0200522 parser.add_argument('--output', '-o', metavar='FILE',
Gilles Peskine6e910092020-01-22 15:58:18 +0100523 help='Output changelog file'
524 ' (default: overwrite the input)')
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100525 parser.add_argument('--list-files-only',
526 action='store_true',
Gilles Peskinec68c7c82020-03-27 19:01:35 +0100527 help=('Only list the files that would be processed '
Gilles Peskineac0f0862020-03-27 10:56:45 +0100528 '(with some debugging information)'))
Gilles Peskine40b3f412019-10-13 21:44:25 +0200529 options = parser.parse_args()
530 set_defaults(options)
Gilles Peskine8f46bbf2020-03-25 16:34:43 +0100531 if options.list_files_only:
532 show_file_timestamps(options)
533 return
Gilles Peskine40b3f412019-10-13 21:44:25 +0200534 merge_entries(options)
535
536if __name__ == '__main__':
537 main()