Skip to content

Commit 28ff4f0

Browse files
Add correction support to the change collector []
1 parent 0c7d6db commit 28ff4f0

6 files changed

Lines changed: 682 additions & 59 deletions

File tree

‎.agents/skills/edg-changes-example/SKILL.md‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,9 +145,43 @@ Steps:
145145
5. Optionally preview the result without changing anything:
146146
`edg-collect-changes --dry-run src/Changes src/pending_changes`.
147147

148-
Edit a `Changes` file directly only to correct an entry that has already
149-
been collected; then write it as **UTF-8** and verify the file still decodes
150-
(raises on failure):
148+
## Correcting an entry in the current version
149+
150+
To replace entries that were already collected into the current (newest,
151+
still open) version, write a pending entry whose first line is the
152+
`//correction: true` directive:
153+
154+
```text
155+
//correction: true
156+
[GH #12,GH #34]
157+
Corrected summary
158+
159+
Corrected description.
160+
```
161+
162+
When the entry is collected, every entry in the current version that has
163+
any of its tags is deleted, and the correction is added like any other
164+
entry, dated the day it is collected. Its tags come from its own tag block.
165+
The `--check` step and the pre-push hook report an error, and the nightly
166+
job leaves the entry in place, when any of these holds:
167+
168+
- One of its tags is on no entry in the current version. Corrections do not
169+
reach across releases, so this also covers the case where the newest
170+
version is already released.
171+
- An entry it replaces has a tag that the correction lacks. Merge every tag
172+
of the replaced entries into the correction's tag block.
173+
- Another pending correction replaces the same entry.
174+
175+
`--dry-run` lists the entries a correction would delete.
176+
177+
A problem with an issue fixed in a prior release is usually a new issue,
178+
not a correction. Give it its own ordinary entry, and in the description
179+
reference the old issue and the release it was fixed in (for example, "The
180+
fix for GH #12 in version 7.0 ...").
181+
182+
Edit a `Changes` file directly only to correct the text of an entry in a
183+
released version. Write it as **UTF-8** and verify that the file still
184+
decodes. The command raises on failure:
151185

152186
```bash
153187
python3 -c "open('path/to/Changes', encoding='utf-8').read()"

‎AGENTS.md‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,13 @@ words the spell check rejects (words already in the target `Changes` file
100100
pass without them). A nightly job runs `edg-collect-changes` to
101101
date them and move them into `Changes`. Check entries with
102102
`edg-exec -- edg-collect-changes --check src/Changes src/pending_changes`
103-
(for the directory in question). Edit a `Changes` file directly
104-
only to correct an already-collected entry. Details: skill
103+
(for the directory in question). To replace already-collected entries
104+
in the current (open) version, add a pending entry with a leading
105+
`//correction: true` directive and all of the replaced entries' tags.
106+
A problem with an issue fixed in a prior release is usually a new issue
107+
with its own entry, whose description references the old issue and the
108+
release it was fixed in. Edit a `Changes` file directly only to correct the
109+
text of an entry in a released version. Details: skill
105110
**edg-changes-example**.
106111

107112
Any `Changes` changelog in the tree (not only `src/Changes`) and every

‎dev_tools/bin/edg-check-file-changes‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,19 +244,42 @@ def _check_overlong_lines(new_file: Path,
244244

245245
return overlong_lines
246246

247+
def _check_correction(repo_path: str, entry: edgchanges.ChangesEntry
248+
) -> List[edgchanges.FormatError]:
249+
'''Return the reasons the correction entry (the pending Changes entry
250+
repo_path) can't replace entries in its Changes file.'''
251+
# As for the spell check, the Changes file is found relative to the
252+
# working directory.
253+
target_path = edgchanges.target_changes_path(Path.cwd() / repo_path)
254+
try:
255+
with open(target_path, 'r', encoding = 'utf-8') as file_handle:
256+
changes_lines = file_handle.read().split('\n')
257+
except (OSError, UnicodeDecodeError) as ex:
258+
return [
259+
edgchanges.FormatError(
260+
None,
261+
f"correction: can't read the Changes file ({ex})"
262+
)
263+
]
264+
_, errors = edgchanges.find_corrected_entries(changes_lines, entry.tags)
265+
return [edgchanges.FormatError(None, error) for error in errors]
266+
247267
def check_changes_fragment(repo_path: str, new_file: Path) -> Any:
248268
'''Check new_file, the contents of the pending Changes entry repo_path.
249269
250270
Besides the usual checks, its format is checked (see edgchanges). Its
251271
spelling is checked against the Changes file it will be collected into, not
252272
against an old version of the entry (see _check_fragment_spelling), and
253273
trailing whitespace (stripped when the entry is collected) doesn't count
254-
toward the line length.
274+
toward the line length. A correction is checked against that Changes file
275+
too (see edgchanges.find_corrected_entries).
255276
'''
256-
_, format_errors = edgchanges.parse_fragment(
277+
entry, format_errors = edgchanges.parse_fragment(
257278
new_file,
258279
check_line_length = False
259280
)
281+
if entry is not None and entry.is_correction:
282+
format_errors += _check_correction(repo_path, entry)
260283
_, prose_lines = edgchanges.read_prose(new_file)
261284
return {
262285
'format_errors': format_errors,

‎dev_tools/bin/edg-collect-changes‎

Lines changed: 101 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ conflict with every other), a change adds one *.txt entry there:
1818
Previously, ...
1919
2020
The leading //key: value directives are optional (//allowed_words: lists
21-
words the spell check should accept). Then comes the tag block, one or more
22-
comma-separated "GH #N" tags in brackets (it may wrap onto several lines), the
23-
summary line, a blank line, and the description (see edgchanges).
21+
words the spell check should accept, and "//correction: true" marks a
22+
correction, below). Then comes the tag block, one or more comma-separated
23+
"GH #N" tags in brackets (it may wrap onto several lines), the summary line, a
24+
blank line, and the description (see edgchanges).
2425
2526
Given a Changes file and its pending_changes/ directory, this tool moves
2627
every entry into the Changes file, just below the newest "Version x.y" line,
@@ -30,9 +31,15 @@ released (its header has a date), a new section is opened for the next
3031
version (--version or --version-from). A nightly job runs it for each Changes
3132
file (see .github/workflows/collect-changes.yml).
3233
34+
A correction replaces the entries in the newest (open) version that have any
35+
of its tags: they're deleted, and it's added like any other entry. Each of
36+
its tags must be on such an entry, and it must have all of their tags;
37+
otherwise (or if another correction replaces one of the same entries) it's
38+
reported and left in place, like a malformed entry.
39+
3340
With --check, the entries are only checked, by running edg-check-file-changes
34-
on them (format, spelling, typos, line length), the same check the pre-push
35-
hook does.
41+
on them (format, spelling, typos, line length, and whether corrections can
42+
be applied), the same check the pre-push hook does.
3643
'''
3744

3845
import argparse
@@ -47,20 +54,13 @@ import edgchanges
4754
import edgutil
4855

4956
from pathlib import Path
50-
from typing import Any, List, Optional, Tuple
57+
from typing import Any, Dict, List, Optional, Tuple
5158

5259
PENDING_CHANGES_KEEP_FILE_NAME = '.gitignore'
5360

5461
SEPARATOR_LINE = '-' * edgchanges.MAX_LINE_LENGTH
5562
NO_CHANGES_LINE = 'No changes.'
5663

57-
# An open version is "Version 7.1"; a released one is
58-
# "Version 7.0, September 28, 2026".
59-
VERSION_HEADER_REGEX = re.compile(
60-
r'^Version ([0-9]+\.[0-9]+)(, [A-Z][a-z]+ [0-9]{1,2}, [0-9]{4})?$'
61-
)
62-
SEPARATOR_REGEX = re.compile(r'^-+$')
63-
6464
def list_pending_dir(pending_dir: Path) -> Tuple[List[Path], List[Path]]:
6565
'''Return the entries in pending_dir, and the other files there (apart
6666
from the .gitignore that keeps the directory in git).'''
@@ -79,31 +79,16 @@ def _describe_misnamed(path: Path) -> str:
7979
f"*{edgchanges.FRAGMENT_SUFFIX})"
8080
)
8181

82-
def _find_newest_version_header(lines: List[str]) -> Optional[int]:
83-
'''Return the index of the newest Version header line.
84-
85-
Body text can also start with "Version", so a header must be the first line
86-
of the file or directly follow a separator line.
87-
'''
88-
for line_index, line in enumerate(lines):
89-
follows_separator = (
90-
line_index == 0 or
91-
SEPARATOR_REGEX.match(lines[line_index - 1]) is not None
92-
)
93-
if follows_separator and VERSION_HEADER_REGEX.match(line) is not None:
94-
return line_index
95-
return None
96-
9782
def read_open_version(changes_path: Path) -> Optional[str]:
9883
'''Return the newest version of changes_path if it's still open (i.e., its
9984
header has no release date).'''
10085
with open(changes_path, 'r', encoding = 'utf-8') as file_handle:
10186
lines = file_handle.read().split('\n')
10287

103-
header_index = _find_newest_version_header(lines)
88+
header_index = edgchanges.find_newest_version_header(lines)
10489
if header_index is None:
10590
return None
106-
header_match = VERSION_HEADER_REGEX.match(lines[header_index])
91+
header_match = edgchanges.VERSION_HEADER_REGEX.match(lines[header_index])
10792
assert header_match is not None
10893
if header_match.group(2) is not None:
10994
return None
@@ -122,10 +107,10 @@ def insert_entries(changes_text: str,
122107
ValueError if there's nowhere to put the entries.
123108
'''
124109
lines = changes_text.split('\n')
125-
header_index = _find_newest_version_header(lines)
110+
header_index = edgchanges.find_newest_version_header(lines)
126111
if header_index is None:
127112
raise ValueError('no "Version x.y" line found')
128-
header_match = VERSION_HEADER_REGEX.match(lines[header_index])
113+
header_match = edgchanges.VERSION_HEADER_REGEX.match(lines[header_index])
129114
assert header_match is not None
130115

131116
entry_lines: List[str] = []
@@ -157,6 +142,62 @@ def insert_entries(changes_text: str,
157142

158143
return '\n'.join(new_lines), inserted_lines
159144

145+
def remove_entries(changes_text: str,
146+
removed_entries: List[edgchanges.CollectedEntry]) -> str:
147+
'''Return changes_text without removed_entries (entries in it).'''
148+
lines = changes_text.split('\n')
149+
for entry in sorted(removed_entries, key = lambda entry: -entry.start):
150+
del lines[entry.start:entry.end]
151+
return '\n'.join(lines)
152+
153+
def find_corrections(changes_text: str,
154+
entries: List[edgchanges.ChangesEntry]
155+
) -> Tuple[List[edgchanges.CollectedEntry], List[str]]:
156+
'''Find the entries in changes_text that the corrections among entries
157+
replace.
158+
159+
Returns those entries and the errors found. A correction that can't be
160+
applied (see edgchanges.find_corrected_entries), or that replaces an entry
161+
another one also replaces, is removed from entries.
162+
'''
163+
changes_lines = changes_text.split('\n')
164+
errors = []
165+
bad_entries = []
166+
# The corrections replacing each entry, by its first line.
167+
correctors: Dict[int, List[edgchanges.ChangesEntry]] = {}
168+
corrected_entries: Dict[int, edgchanges.CollectedEntry] = {}
169+
for entry in entries:
170+
if not entry.is_correction:
171+
continue
172+
corrected, correction_errors = edgchanges.find_corrected_entries(
173+
changes_lines,
174+
entry.tags
175+
)
176+
if len(correction_errors) != 0:
177+
errors += [f"{entry.path}: {error}" for error in correction_errors]
178+
bad_entries.append(entry)
179+
continue
180+
for corrected_entry in corrected:
181+
correctors.setdefault(corrected_entry.start, []).append(entry)
182+
corrected_entries[corrected_entry.start] = corrected_entry
183+
184+
for start, entry_correctors in correctors.items():
185+
if len(entry_correctors) > 1:
186+
paths = ', '.join(str(entry.path) for entry in entry_correctors)
187+
errors.append(
188+
f"{paths}: corrections replacing the same entry, "
189+
f"\"{corrected_entries[start].summary}\""
190+
)
191+
bad_entries += entry_correctors
192+
193+
removed_entries = [
194+
corrected_entries[start]
195+
for start, entry_correctors in correctors.items()
196+
if not any(entry in bad_entries for entry in entry_correctors)
197+
]
198+
entries[:] = [entry for entry in entries if entry not in bad_entries]
199+
return removed_entries, errors
200+
160201
def _run_file_checks(fragment_paths: List[Path]) -> Any:
161202
'''Run edg-check-file-changes on fragment_paths and return its results.
162203
@@ -251,9 +292,10 @@ def collect(changes_path: Path, pending_dir: Path, date: datetime.date,
251292
next_version: Optional[str], *, dry_run: bool) -> bool:
252293
'''Move the entries in pending_dir into changes_path.
253294
254-
Malformed entries are reported and left in place; the others are still
255-
collected. Returns True if every entry was collected. Raises ValueError
256-
if changes_path has nowhere to put them.
295+
The entries that corrections replace are deleted from changes_path.
296+
Malformed entries, and corrections that can't be applied, are reported and
297+
left in place; the others are still collected. Returns True if every entry
298+
was collected. Raises ValueError if changes_path has nowhere to put them.
257299
'''
258300
fragment_paths, other_paths = list_pending_dir(pending_dir)
259301
for path in other_paths:
@@ -268,18 +310,27 @@ def collect(changes_path: Path, pending_dir: Path, date: datetime.date,
268310
]
269311
if entry is not None:
270312
entries.append(entry)
313+
314+
removed_entries: List[edgchanges.CollectedEntry] = []
315+
if len(entries) != 0:
316+
with open(changes_path, 'r', encoding = 'utf-8') as file_handle:
317+
changes_text = file_handle.read()
318+
removed_entries, correction_errors = find_corrections(
319+
changes_text,
320+
entries
321+
)
322+
errors += correction_errors
323+
271324
for error in errors:
272325
edgutil.eprint(error)
273326
if len(errors) != 0:
274-
edgutil.eprint('Malformed entries were left in place.')
327+
edgutil.eprint('Entries with errors were left in place.')
275328
if len(entries) == 0:
276329
return len(errors) == 0
277330

278-
with open(changes_path, 'r', encoding = 'utf-8') as file_handle:
279-
changes_text = file_handle.read()
280331
try:
281332
new_text, inserted_lines = insert_entries(
282-
changes_text,
333+
remove_entries(changes_text, removed_entries),
283334
entries,
284335
edgchanges.format_date(date),
285336
next_version
@@ -289,6 +340,11 @@ def collect(changes_path: Path, pending_dir: Path, date: datetime.date,
289340

290341
if dry_run:
291342
print(f"=== {changes_path}")
343+
for removed_entry in removed_entries:
344+
print(
345+
f"(deleted: [{','.join(removed_entry.tags)}] "
346+
f"{removed_entry.summary})"
347+
)
292348
print('\n'.join(inserted_lines))
293349
else:
294350
# Only drop the entries once they're safely in the Changes file.
@@ -297,9 +353,14 @@ def collect(changes_path: Path, pending_dir: Path, date: datetime.date,
297353
file_handle.write(new_text)
298354
for entry in entries:
299355
entry.path.unlink()
356+
removed_text = (
357+
'' if len(removed_entries) == 0 else
358+
f" (replacing {len(removed_entries)} corrected "
359+
f"{'entry' if len(removed_entries) == 1 else 'entries'})"
360+
)
300361
print(
301362
f"{changes_path}: collected {len(entries)} "
302-
f"{'entry' if len(entries) == 1 else 'entries'}"
363+
f"{'entry' if len(entries) == 1 else 'entries'}{removed_text}"
303364
)
304365

305366
return len(errors) == 0

0 commit comments

Comments
 (0)