Skip to content

fix(skills): fix pr-reference diff parsing, path quoting, and line counting - #3167

Open
Chaitanya A (ChaitanyaAIML-lab) wants to merge 1 commit into
microsoft:mainfrom
ChaitanyaAIML-lab:contributions/issue-3149
Open

Chaitanya A (ChaitanyaAIML-lab) wants to merge 1 commit into
microsoft:mainfrom
ChaitanyaAIML-lab:contributions/issue-3149

Conversation

@ChaitanyaAIML-lab

Copy link
Copy Markdown

Description

Fixes #3149.

This change resolves diff parsing and line counting discrepancies in the pr-reference skill readers:

  1. Diff formatting: Removed artificial 2-space indentation on diff blocks in generate.ps1, preserving standard git diff format expected by downstream tools.
  2. Quoted paths: Added -c core.quotePath=false to git diff calls and implemented unquoting logic (Resolve-UnquotedGitPath in PowerShell and POSIX octal replacement in Bash) to handle filenames with spaces and non-ASCII characters.
  3. Hunk line counting: Updated line counters in read-diff.ps1 and read-diff.sh to 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.
  4. Header parsing: Anchored diff headers in list-changed-files.ps1 and list-changed-files.sh to prevent diff content (such as +diff --git) from being misidentified as file headers.
  5. Sort parity: Standardized changed file list sorting to case-insensitive ordinal order matching LC_ALL=C sort -f.

How Was This Tested?

  • Ran full Pester suite (Invoke-PesterTests.ps1) covering generate, list-changed-files, read-diff, and shared modules (167 passing tests, exit code 0).
  • Added regression tests for indented XML diff blocks, bare addition lines, embedded hunk headers, and path unquoting.
  • Verified output parity between Bash and PowerShell scripts on identical test diffs.
  • Validated PowerShell scripts with PSScriptAnalyzer and verified Bash script syntax with bash -n.

- 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

@WilliamBerryiii Bill Berry (WilliamBerryiii) left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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+') {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +115 to +122
elseif ($line -match '^[ ]*</full_diff>') {
if ($currentBlock.Count -gt 0) {
$blocks += ($currentBlock -join [Environment]::NewLine)
$currentBlock.Clear()
}
$inDiff = $false
break
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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') {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +224 to +225
if ($line -match '^[ ]*\+') { $added++ }
elseif ($line -match '^[ ]*-') { $removed++ }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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+)") {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +130 to +140
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 }

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 '

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/--file matching, stopping at </full_diff>, and the mapfile replacement.
  • Fixes #3149 will close the issue on merge. If some of its expectations end up out of scope, Refs #3149 keeps it open for follow-up.
  • Since the readers now parse more PR-controlled content, please revisit the shared/pr-reference entry in scripts/linting/skill-security-classification.json (currently exempt), or add a SECURITY.md per skill-security-model.instructions.md.
  • Please update references/REFERENCE.md and SKILL.md for the new counting, sorting, and path-decoding behavior.

Please comment if you have questions about any of these, and we can discuss further.

Comment on lines +141 to +153
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
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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+(.+)$') {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 -Summary file list.
  • An unchanged context line diff --git a/x b/x inside a hunk closes the current file with partial counts and starts a phantom entry x. 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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +188 to +191
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}")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of edge cases in this unquoting:

  • The sed rule rewrites any backslash followed by a digit, including the second half of an escaped \\. git writes the file foo\123 as "foo\\123", and this produces foo\0123.
  • echo "${old_path%\"}" prints nothing for a file named -n or -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.

Comment on lines +174 to 195
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Comment on lines +158 to +172
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 }
}
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +207 to +212
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'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 433 to +434
$diffBlock = if ($DiffOutput) {
($DiffOutput | ForEach-Object { " $_" }) -join [Environment]::NewLine
$DiffOutput -join [Environment]::NewLine

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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('"')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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('"')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
$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-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.40625% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.71%. Comparing base (727e262) to head (14f0361).
⚠️ Report is 89 commits behind head on main.

Files with missing lines Patch % Lines
...shared/pr-reference/scripts/list-changed-files.ps1 91.22% 5 Missing ⚠️
...b/skills/shared/pr-reference/scripts/read-diff.ps1 90.90% 3 Missing ⚠️
...hub/skills/shared/pr-reference/scripts/shared.psm1 91.42% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Flag Coverage Δ
docusaurus ?
pester 83.92% <91.40%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...ub/skills/shared/pr-reference/scripts/generate.ps1 95.07% <100.00%> (-0.71%) ⬇️
...b/skills/shared/pr-reference/scripts/read-diff.ps1 94.61% <90.90%> (-1.58%) ⬇️
...hub/skills/shared/pr-reference/scripts/shared.psm1 93.10% <91.42%> (-2.73%) ⬇️
...shared/pr-reference/scripts/list-changed-files.ps1 92.03% <91.22%> (-2.00%) ⬇️

... and 16 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(skills): pr-reference readers return empty or wrong results for generate.ps1 output and undercount diff lines

4 participants