Skip to content

Commit 6b620c3

Browse files
Add correction support to the change collector []
1 parent fd29a1a commit 6b620c3

6 files changed

Lines changed: 817 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
@@ -149,9 +149,43 @@ Steps:
149149
5. Optionally preview the result without changing anything:
150150
`edg-collect-changes --dry-run src/Changes src/pending_changes`.
151151

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

156190
```bash
157191
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: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,78 @@ def _check_overlong_lines(new_file: Path,
398398

399399
return overlong_lines
400400

401+
def _find_correction_conflicts(
402+
fragment_path: Path, changes_lines: List[str],
403+
corrected: List[edgchanges.CollectedEntry]
404+
) -> List[str]:
405+
'''Return the errors for the entries among corrected (those the correction
406+
at fragment_path replaces in the Changes file whose lines are
407+
changes_lines) that another pending correction replaces too.
408+
409+
The other corrections are the ones beside fragment_path. As in
410+
edg-collect-changes, one that can't be applied itself doesn't count.
411+
'''
412+
corrected_starts = {entry.start for entry in corrected}
413+
errors: List[str] = []
414+
if not fragment_path.parent.is_dir():
415+
return errors
416+
for other_path in sorted(fragment_path.parent.iterdir()):
417+
if (other_path == fragment_path or not other_path.is_file() or
418+
not edgchanges.is_fragment_path(other_path.as_posix())):
419+
continue
420+
try:
421+
other_entry, _ = edgchanges.parse_fragment(
422+
other_path,
423+
check_line_length = False
424+
)
425+
except OSError:
426+
continue
427+
if other_entry is None or not other_entry.is_correction:
428+
continue
429+
other_corrected, other_errors = edgchanges.find_corrected_entries(
430+
changes_lines,
431+
other_entry.tags
432+
)
433+
if len(other_errors) != 0:
434+
continue
435+
for other_corrected_entry in other_corrected:
436+
if other_corrected_entry.start in corrected_starts:
437+
errors.append(
438+
f"correction: {other_path.name} also replaces the entry "
439+
f"\"{other_corrected_entry.summary}\"; combine the corrections"
440+
)
441+
return errors
442+
443+
def _check_correction(repo_path: str, entry: edgchanges.ChangesEntry
444+
) -> List[edgchanges.FormatError]:
445+
'''Return the reasons the correction entry (the pending Changes entry
446+
repo_path) can't replace entries in its Changes file.'''
447+
# As for the spell check, the Changes file is found relative to the
448+
# working directory.
449+
fragment_path = Path.cwd() / repo_path
450+
target_path = edgchanges.target_changes_path(fragment_path)
451+
try:
452+
with open(target_path, 'r', encoding = 'utf-8') as file_handle:
453+
changes_lines = file_handle.read().split('\n')
454+
except (OSError, UnicodeDecodeError) as ex:
455+
return [
456+
edgchanges.FormatError(
457+
None,
458+
f"correction: can't read the Changes file ({ex})"
459+
)
460+
]
461+
corrected, errors = edgchanges.find_corrected_entries(
462+
changes_lines,
463+
entry.tags
464+
)
465+
if len(errors) == 0:
466+
errors = _find_correction_conflicts(
467+
fragment_path,
468+
changes_lines,
469+
corrected
470+
)
471+
return [edgchanges.FormatError(None, error) for error in errors]
472+
401473
def check_changes_fragment(allowlist: edgspelling.Allowlist,
402474
repo_path: str,
403475
new_file: Path) -> Any:
@@ -407,12 +479,16 @@ def check_changes_fragment(allowlist: edgspelling.Allowlist,
407479
spelling is checked against the Changes file it will be collected into, not
408480
against an old version of the entry (see _check_fragment_spelling), and
409481
trailing whitespace (stripped when the entry is collected) doesn't count
410-
toward the line length.
482+
toward the line length. A correction is checked against that Changes file
483+
too (see edgchanges.find_corrected_entries), and against the other pending
484+
corrections beside repo_path (see _find_correction_conflicts).
411485
'''
412-
_, format_errors = edgchanges.parse_fragment(
486+
entry, format_errors = edgchanges.parse_fragment(
413487
new_file,
414488
check_line_length = False
415489
)
490+
if entry is not None and entry.is_correction:
491+
format_errors += _check_correction(repo_path, entry)
416492
_, prose_lines = edgchanges.read_prose(new_file)
417493
return {
418494
'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)