Private/Get-FileDiff.ps1
|
function Get-FileDiff { <# .SYNOPSIS Get unified diff for a file using native git .DESCRIPTION Extracts the unified diff for a specific file, showing what changed. Handles both modified files and new files appropriately. .PARAMETER FilePath Path to the file (relative to repo root) .PARAMETER BaseBranch Base branch for comparison (default: origin/master) .PARAMETER ContextLines Number of context lines around changes (default: 10) .EXAMPLE Get-FileDiff -FilePath "src/MyTable.al" .OUTPUTS System.Object - Hashtable with FilePath, FullDiff, DiffSize, Chunks .NOTES Author: waldo Version: 1.0.0 #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$FilePath, [Parameter(Mandatory = $false)] [string]$BaseBranch = "origin/master", [Parameter(Mandatory = $false)] [int]$ContextLines = 10 ) begin { Write-Verbose "Starting $($MyInvocation.MyCommand.Name)" } process { try { Write-Verbose "Getting diff for $FilePath" if (-not (Test-Path $FilePath)) { Write-Warning "File not found: $FilePath" return $null } # Use the same compare ref as Get-ChangedFiles $compareRef = "HEAD" if ($env:BUILD_SOURCEVERSION -and $env:BUILD_SOURCEVERSION -ne '') { $compareRef = $env:BUILD_SOURCEVERSION } # Check if this is a new file (added in this branch) $fileStatus = git diff --name-status "$BaseBranch..$compareRef" -- $FilePath $isNewFile = $fileStatus -match '^A\s' if ($isNewFile) { Write-Verbose "New file detected - showing full content" # For new files, show the entire file content as the diff $diffOutput = git show "${compareRef}:${FilePath}" # Wrap in diff-like format for consistency $diffOutput = "--- /dev/null`n+++ b/$FilePath`n" + ($diffOutput -split "`n" | ForEach-Object { "+$_" } | Join-String -Separator "`n") } else { # Get unified diff with context lines $diffOutput = git diff "$BaseBranch..$compareRef" "-U$ContextLines" -- $FilePath } if ([string]::IsNullOrWhiteSpace($diffOutput)) { Write-Verbose "No changes in $FilePath" return $null } Write-Verbose "Diff size: $($diffOutput.Length) characters" return @{ FilePath = $FilePath FullDiff = $diffOutput DiffSize = $diffOutput.Length # Phase 1: Single diff unit Chunks = @(@{ Content = $diffOutput IsFullDiff = $true }) } } catch { Write-Error "Error in $($MyInvocation.MyCommand.Name): $_" throw } } end { Write-Verbose "Completed $($MyInvocation.MyCommand.Name)" } } |