Repository navigation
fix(skills): fix pr-reference diff parsing, path quoting, and line counting - #3167
Chaitanya A (ChaitanyaAIML-lab) wants to merge 1 commit into
Conversation
- stop indenting diff blocks in generate.ps1 to preserve diff formatting - pass core.quotePath=false to git diff in generate scripts - decode quoted and octal-escaped file paths in PowerShell and Bash readers - anchor diff headers to avoid matching embedded diff text inside hunks - count all added and removed lines after first hunk header - enforce ordinal sorting parity across platforms - add regression tests for indented diffs, bare additions, and path unquoting Fixes microsoft#3149
There was a problem hiding this comment.
Thank you, Chaitanya A (@ChaitanyaAIML-lab). We moved these suggestions to line-level comments in the review below so each one sits next to the code it refers to.
Bill Berry (WilliamBerryiii)
left a comment
There was a problem hiding this comment.
Thank you for this PR, Chaitanya A (@ChaitanyaAIML-lab), and for digging into the pr-reference problems in #3149. Switching generate.ps1 to column-0 output, the line-based block splitter, ordinal sorting, and the new Pester tests are all good steps.
We left suggested changes inline. Beyond those, please add bash tests that run both twins against shared fixtures, as #3149 asks, and fill in the repository PR template. Please comment if you have questions about any of the suggestions, and we can discuss further.
| $inDiff = $false | ||
|
|
||
| foreach ($line in $lines) { | ||
| if ($line -match '^[ ]*diff --git\s+') { |
There was a problem hiding this comment.
Now that generate.ps1 writes diff lines at column 0, could we anchor this at column 0 (^diff --git ) here and in the other three readers? Unchanged context lines in a unified diff start with one space, so ^[ ]* also matches a context line whose content is diff --git ... and opens a phantom block. Files on main such as references/REFERENCE.md and tests/list-changed-files.Tests.ps1 already contain lines like that, so a later PR that edits near them would trigger it.
| elseif ($line -match '^[ ]*</full_diff>') { | ||
| if ($currentBlock.Count -gt 0) { | ||
| $blocks += ($currentBlock -join [Environment]::NewLine) | ||
| $currentBlock.Clear() | ||
| } | ||
| $inDiff = $false | ||
| break | ||
| } |
There was a problem hiding this comment.
This break runs before <full_diff> opens, so the scan also covers the <commits> section. A commit-message line of </full_diff> (two-space indented by generate.ps1, column 0 from generate.sh) ends the scan before any real file, and the list comes back empty. Could we start collecting only after the opening <full_diff> line and stop at the last </full_diff>? Get-DiffSummary in read-diff.ps1 (line 198) has the same pattern.
| if (-not $oldPath -and $newPath) { $oldPath = $newPath } | ||
| } | ||
| elseif ($diffBlock -match 'deleted file mode') { | ||
| elseif ($diffBlock -match '(?m)^[ ]*deleted file mode') { |
There was a problem hiding this comment.
These (?m) checks run over the whole block, including hunk lines. An unchanged context line deleted file mode 100644 marks a modified file as Deleted, and -ExcludeType Deleted (what the Code Review flow passes) then drops it. The rename from/rename to checks at lines 138 and 141 can replace the reported path the same way, and the bash twin does the same at list-changed-files.sh lines 150-157. Could we read extended-header metadata only from the lines before the first @@, as Get-DiffSummary already does for its path overrides?
| if ($line -match '^[ ]*\+') { $added++ } | ||
| elseif ($line -match '^[ ]*-') { $removed++ } |
There was a problem hiding this comment.
With ^[ ]*, a context line whose content starts with + or - is counted too. For example, an unchanged Markdown bullet - item counts as a removal. On commit 9411f4e this rule reports +280/-62, while git diff --numstat reports +280/-59. Inside a hunk, matching only column 0 (^\+ and ^-) gives the --numstat behavior #3149 asks for. The same applies to read-diff.sh lines 172-177.
| if ($line -match "^diff --git") { | ||
| if ($line -match "a/$escapedPath b/") { | ||
| if ($line -match '^[ ]*diff --git') { | ||
| if ($line -match "(?:a/|`"a/)$escapedPath(?:`"|\s+)" -or $line -match "(?:b/|`"b/)$escapedPath(?:`"|\s*`$|\s+)") { |
There was a problem hiding this comment.
This match isn't bounded on the left, so -File src/x.ts also matches a/lib/src/x.ts b/lib/src/x.ts through the b/ in lib/, and that block can come back instead of the requested one. Could we match the header tokens exactly, meaning the quoted or unquoted a/<path> followed by the b/ token? read-diff.sh line 200 uses index() with no right boundary either, so --file app.ts also selects app.tsx.
| if ($next -match '[0-7]' -and ($i + 3) -lt $trimmed.Length -and $trimmed[$i + 2] -match '[0-7]' -and $trimmed[$i + 3] -match '[0-7]') { | ||
| $octStr = $trimmed.Substring($i + 1, 3) | ||
| $byteVal = [Convert]::ToByte($octStr, 8) | ||
| $bytes.Add($byteVal) | ||
| $i += 4 | ||
| continue | ||
| } | ||
| elseif ($next -eq 't') { $bytes.Add(9); $i += 2; continue } | ||
| elseif ($next -eq 'n') { $bytes.Add(10); $i += 2; continue } | ||
| elseif ($next -eq '"') { $bytes.Add(34); $i += 2; continue } | ||
| elseif ($next -eq '\') { $bytes.Add(92); $i += 2; continue } |
There was a problem hiding this comment.
With core.quotePath=false, git still quotes paths that contain control characters, a quote, or a backslash. Decoding \n, \t, and octal escapes such as \033 turns those back into raw characters in line-oriented output, so one file name containing a newline is listed as two entries. Could we keep those paths in their escaped form for output? Separately, [Convert]::ToByte throws for octal values above \377, so limiting the branch to \000 through \377 would avoid a crash. The bash printf "%b" path in list-changed-files.sh lines 188-191 and read-diff.sh line 186 has the same decoding behavior.
| added=$(grep -A 1000 "diff --git a/${file} b/" "${INPUT_FILE}" | grep -m 1 -B 1000 "^diff --git" | grep -c "^+" 2>/dev/null || echo "0") | ||
| removed=$(grep -A 1000 "diff --git a/${file} b/" "${INPUT_FILE}" | grep -m 1 -B 1000 "^diff --git" | grep -c "^-" 2>/dev/null || echo "0") | ||
| echo " ${file} (+${added}/-${removed})" | ||
| awk ' |
There was a problem hiding this comment.
This block conflicts with #3140 on main, which rewrote the same summary section and added { sub(/\r$/, "") } so CRLF output from generate.ps1 on Windows parses correctly. When you rebase, could you keep that CRLF handling in the new awk program?
|
|
||
| printf '%s\n' "${results[@]}" | sort -t'|' -k1 | ||
| if [[ ${#results[@]} -gt 0 ]]; then | ||
| printf '%s\n' "${results[@]}" | LC_ALL=C sort -f -t'|' -k1 |
There was a problem hiding this comment.
-k1 with -t'|' runs to the end of the line, so the key includes the |type suffix. Because | sorts after ., LICENSE.md comes before LICENSE here, while Format-PathOrdinal puts LICENSE first. -k1,1 would sort on the path field only and match the PowerShell order #3149 asks for.
Bill Berry (WilliamBerryiii)
left a comment
There was a problem hiding this comment.
Thanks again, Chaitanya A (@ChaitanyaAIML-lab). This follow-up covers the rest of our feedback. The inline comments above add a few more edge cases in the readers, and a few items relate to the PR itself:
- The description says the headers were anchored, but the readers now accept leading spaces (
^[ ]*). Could you update it to describe the change as made? - The description also mentions verified Bash/PowerShell parity. Could you add the parity tests, or note how it was checked, so reviewers can reproduce it?
- A few behavior changes aren't described yet: the
-File/--filematching, stopping at</full_diff>, and themapfilereplacement. Fixes #3149will close the issue on merge. If some of its expectations end up out of scope,Refs #3149keeps it open for follow-up.- Since the readers now parse more PR-controlled content, please revisit the
shared/pr-referenceentry inscripts/linting/skill-security-classification.json(currentlyexempt), or add aSECURITY.mdperskill-security-model.instructions.md. - Please update
references/REFERENCE.mdandSKILL.mdfor the new counting, sorting, and path-decoding behavior.
Please comment if you have questions about any of these, and we can discuss further.
| if ($line -match '^[ ]*diff --git') { | ||
| if ($line -match "(?:a/|`"a/)$escapedPath(?:`"|\s+)" -or $line -match "(?:b/|`"b/)$escapedPath(?:`"|\s*`$|\s+)") { | ||
| $inTargetFile = $true | ||
| } | ||
| elseif ($inTargetFile) { | ||
| break | ||
| } | ||
| } | ||
| elseif ($line -match '^[ ]*</full_diff>') { | ||
| if ($inTargetFile) { | ||
| break | ||
| } | ||
| } |
There was a problem hiding this comment.
Get-FileDiff scans the whole file, including the <commits> section. A commit-message block with diff --git a/src/auth.ts b/src/auth.ts, a short hunk, and </full_diff> makes -File src/auth.ts return that text instead of the real diff. An unchanged context line starting with diff --git or </full_diff> inside the requested file also ends the output early. Restricting the scan to the <full_diff> section and matching headers at column 0 would cover both cases.
|
|
||
| foreach ($line in $Content) { | ||
| if ($line -match "^diff --git a/(.+?) b/") { | ||
| if ($line -match '^[ ]*diff --git\s+(.+)$') { |
There was a problem hiding this comment.
Two related cases for the summary:
- Commit-message lines are scanned too, so a commit body containing
diff --git ...lines can add entries to the-Summaryfile list. - An unchanged context line
diff --git a/x b/xinside a hunk closes the current file with partial counts and starts a phantom entryx. Following context lines such as+++ b/...can then rename that phantom entry.
read-diff.sh lines 117-124 behave the same way.
| ) | ||
|
|
||
| $diffArgs = @('--no-pager', 'diff', $ComparisonRef) | ||
| $diffArgs = @('-c', 'core.quotePath=false', '--no-pager', 'diff', $ComparisonRef) |
There was a problem hiding this comment.
With core.quotePath=false, git writes non-ASCII bytes as-is, including bidirectional control characters such as U+202E (right-to-left override). Before this change they were octal-escaped. A file name can then display with a misleading extension, for example a .ps1 file that reads as .jpg. Could the readers escape bidirectional and other control characters when they print paths?
| old_path=$(echo "${old_path%\"}" | sed -E 's/^"//; s/\\([0-7])/\\0\1/g') | ||
| old_path=$(printf "%b" "${old_path}") | ||
| new_path=$(echo "${new_path%\"}" | sed -E 's/^"//; s/\\([0-7])/\\0\1/g') | ||
| new_path=$(printf "%b" "${new_path}") |
There was a problem hiding this comment.
A couple of edge cases in this unquoting:
- The
sedrule rewrites any backslash followed by a digit, including the second half of an escaped\\. git writes the filefoo\123as"foo\\123", and this producesfoo\0123. echo "${old_path%\"}"prints nothing for a file named-nor-e.printf '%s'avoids that.
The same sequence appears four times here and in read-diff.sh lines 185-186. One helper function would keep the copies consistent.
| if [[ -z "$old_path" || -z "$new_path" ]]; then | ||
| if [[ "$header" =~ ^\"a/(.+)\"[[:space:]]+\"b/(.+)\"$ ]]; then | ||
| [[ -z "$old_path" ]] && old_path="${BASH_REMATCH[1]}" | ||
| [[ -z "$new_path" ]] && new_path="${BASH_REMATCH[2]}" | ||
| elif [[ "$header" =~ ^a/(.+)[[:space:]]+b/(.+)$ ]]; then | ||
| [[ -z "$old_path" ]] && old_path="${BASH_REMATCH[1]}" | ||
| [[ -z "$new_path" ]] && new_path="${BASH_REMATCH[2]}" | ||
| fi | ||
| elif [[ "$old_path" != "$new_path" ]]; then | ||
| fi | ||
|
|
||
| [[ -z "$new_path" ]] && new_path="$old_path" | ||
| [[ -z "$old_path" ]] && old_path="$new_path" | ||
|
|
||
| # Unquote paths | ||
| old_path=$(echo "${old_path%\"}" | sed -E 's/^"//; s/\\([0-7])/\\0\1/g') | ||
| old_path=$(printf "%b" "${old_path}") | ||
| new_path=$(echo "${new_path%\"}" | sed -E 's/^"//; s/\\([0-7])/\\0\1/g') | ||
| new_path=$(printf "%b" "${new_path}") | ||
|
|
||
| if [[ "$old_path" != "$new_path" ]]; then | ||
| change_type="renamed" | ||
| fi |
There was a problem hiding this comment.
When ---/+++ leave one side unset (deleted, added, binary, or mode-only files), the greedy ^a/(.+)[[:space:]]+b/(.+)$ fallback mis-splits paths that contain b/. For example, a deleted d b/e gets new_path=e. Lines 193-195 then switch the type from deleted to renamed, so the file passes through --exclude-type deleted. list-changed-files.ps1 line 165 uses the same greedy fallback. For /dev/null cases, could we reuse the known side's path rather than splitting the header?
| if (-not $oldPath -or -not $newPath) { | ||
| if ($diffBlock -match '(?m)^[ ]*diff --git\s+(.+)$') { | ||
| $header = $Matches[1].Trim() | ||
| if ($header -match '^"a/(.+?)"\s+"b/(.+?)"$') { | ||
| if (-not $oldPath) { $oldPath = Resolve-UnquotedGitPath $Matches[1] } | ||
| if (-not $newPath) { $newPath = Resolve-UnquotedGitPath $Matches[2] } | ||
| } | ||
| elseif ($header -match '^a/(.+)\s+b/(.+)$') { | ||
| $candOld = $Matches[1] | ||
| $candNew = $Matches[2] | ||
| if (-not $oldPath) { $oldPath = Resolve-UnquotedGitPath $candOld } | ||
| if (-not $newPath) { $newPath = Resolve-UnquotedGitPath $candNew } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
This path resolution is repeated in Get-DiffSummary (read-diff.ps1 lines 186-218) with different precedence. Here rename to wins and +++ is skipped; there +++ can overwrite it. #3149 came from the twins drifting apart, so a single helper in shared.psm1 that both readers call would help keep them aligned.
| print file "\t" added "\t" removed | ||
| } | ||
| } | ||
| ' "${INPUT_FILE}" | LC_ALL=C sort -f -k1,1 | while IFS=$'\t' read -r raw_f added removed; do |
There was a problem hiding this comment.
The awk program prints tab-separated fields, but sort -f -k1,1 splits on blanks, so a path containing a space sorts on its first word only. LC_ALL=C sort -f -t$'\t' -k1,1 would sort on the whole path.
| It 'Sorts string arrays using ordinal comparison' { | ||
| $items = @('b.ts', 'A.ts', 'a.ts') | ||
| $sorted = $items | Format-PathOrdinal | ||
| $sorted[0] | Should -Be 'A.ts' | ||
| $sorted[1] | Should -Be 'a.ts' | ||
| $sorted[2] | Should -Be 'b.ts' |
There was a problem hiding this comment.
A.ts and a.ts compare equal under OrdinalIgnoreCase, and List.Sort isn't stable, so their order isn't guaranteed. Should -Be is case-insensitive, so this test passes in either order. GNU sort -f breaks ties with a byte comparison (A.ts before a.ts). Adding an Ordinal tie-break in Format-PathOrdinal and asserting with Should -BeExactly would make the order deterministic and testable.
| $diffBlock = if ($DiffOutput) { | ||
| ($DiffOutput | ForEach-Object { " $_" }) -join [Environment]::NewLine | ||
| $DiffOutput -join [Environment]::NewLine |
There was a problem hiding this comment.
This changes the persisted output format, but generate.Tests.ps1 doesn't assert the column-0 diff lines or the core.quotePath=false argument. #3149 also asks for a generate.ps1-format fixture. Could you add a test that checks Get-PrXmlContent emits unindented diff lines, plus a mock check for the -c core.quotePath=false arguments?
| return "" | ||
| } | ||
|
|
||
| $trimmed = $Path.Trim().Trim('"') |
There was a problem hiding this comment.
Trim('"') removes every leading and trailing quote, not just one surrounding pair. git quotes a file named foo" as "foo\"", which becomes foo\ here. git's C quoting also emits \a, \b, \f, \v, and \r, which this decoder leaves undecoded.
| return "" | ||
| } | ||
|
|
||
| $trimmed = $Path.Trim().Trim('"') |
There was a problem hiding this comment.
Could you double-check two edge cases in Resolve-UnquotedGitPath? Trim('"') removes every edge quote, so git's quoting of a file named a" ("a\"") comes back as a\ (I reproduced this against this branch). Stripping at most one quote from each end would avoid that:
| $trimmed = $Path.Trim().Trim('"') | |
| $trimmed = $Path.Trim() | |
| if ($trimmed.Length -ge 2 -and $trimmed.StartsWith('"') -and $trimmed.EndsWith('"')) { $trimmed = $trimmed.Substring(1, $trimmed.Length - 2) } |
Git's C-style quoting also emits \a, \b, \f, \r and \v (see core.quotePath), which this function leaves undecoded ("a\rb" returns a\rb), while the bash printf %b path decodes them. That might leave the two twins disagreeing on those names, so adding those escapes next to \t and \n could keep them aligned.
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #3167 +/- ##
==========================================
- Coverage 86.79% 86.71% -0.09%
==========================================
Files 132 117 -15
Lines 15196 15044 -152
Branches 46 0 -46
==========================================
- Hits 13189 13045 -144
+ Misses 2001 1999 -2
+ Partials 6 0 -6
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Description
Fixes #3149.
This change resolves diff parsing and line counting discrepancies in the
pr-referenceskill readers:generate.ps1, preserving standard git diff format expected by downstream tools.-c core.quotePath=falseto git diff calls and implemented unquoting logic (Resolve-UnquotedGitPathin PowerShell and POSIX octal replacement in Bash) to handle filenames with spaces and non-ASCII characters.read-diff.ps1andread-diff.shto count all added and removed lines within hunks (after the first@@marker). This fixes undercounting of bare+lines, markdown lists, YAML delimiters, and comment lines.list-changed-files.ps1andlist-changed-files.shto prevent diff content (such as+diff --git) from being misidentified as file headers.LC_ALL=C sort -f.How Was This Tested?
Invoke-PesterTests.ps1) coveringgenerate,list-changed-files,read-diff, andsharedmodules (167 passing tests, exit code 0).bash -n.