Get-GitHubPrFilePatch.ps1
1 <# 2 .SYNOPSIS 3 Retrieves the unified diff patch for a specific file in a GitHub pull request. 4 5 .DESCRIPTION 6 This script fetches the patch content (unified diff format) for a specified file 7 within a pull request. It uses the GitHub CLI (gh) to query the GitHub API and 8 retrieve file change information. 9 10 .PARAMETER PullRequestNumber 11 The pull request number to query. 12 13 .PARAMETER FilePath 14 The relative path to the file in the repository (e.g., "src/modules/main.cpp"). 15 16 .PARAMETER RepositoryOwner 17 The GitHub repository owner. Defaults to "microsoft". 18 19 .PARAMETER RepositoryName 20 The GitHub repository name. Defaults to "PowerToys". 21 22 .EXAMPLE 23 .\Get-GitHubPrFilePatch.ps1 -PullRequestNumber 42374 -FilePath "src/modules/cmdpal/main.cpp" 24 Retrieves the patch for main.cpp in PR #42374. 25 26 .EXAMPLE 27 .\Get-GitHubPrFilePatch.ps1 -PullRequestNumber 42374 -FilePath "README.md" -RepositoryOwner "myorg" -RepositoryName "myrepo" 28 Retrieves the patch from a different repository. 29 30 .NOTES 31 Requires GitHub CLI (gh) to be installed and authenticated. 32 Run 'gh auth login' if not already authenticated. 33 34 .LINK 35 https://cli.github.com/ 36 #> 37 38 [CmdletBinding()] 39 param( 40 [Parameter(Mandatory = $true, HelpMessage = "Pull request number")] 41 [int]$PullRequestNumber, 42 43 [Parameter(Mandatory = $true, HelpMessage = "Relative path to the file in the repository")] 44 [string]$FilePath, 45 46 [Parameter(Mandatory = $false, HelpMessage = "Repository owner")] 47 [string]$RepositoryOwner = "microsoft", 48 49 [Parameter(Mandatory = $false, HelpMessage = "Repository name")] 50 [string]$RepositoryName = "PowerToys" 51 ) 52 53 # Construct GitHub API path for pull request files 54 $apiPath = "repos/$RepositoryOwner/$RepositoryName/pulls/$PullRequestNumber/files?per_page=250" 55 56 # Query GitHub API to get all files in the pull request 57 try { 58 $pullRequestFiles = gh api $apiPath | ConvertFrom-Json 59 } catch { 60 Write-Error "Failed to query GitHub API for PR #$PullRequestNumber. Ensure gh CLI is authenticated. Details: $_" 61 exit 1 62 } 63 64 # Find the matching file in the pull request 65 $matchedFile = $pullRequestFiles | Where-Object { $_.filename -eq $FilePath } 66 67 if (-not $matchedFile) { 68 Write-Error "File '$FilePath' not found in PR #$PullRequestNumber." 69 exit 1 70 } 71 72 # Check if patch content exists 73 if (-not $matchedFile.patch) { 74 Write-Warning "File '$FilePath' has no patch content (possibly binary or too large)." 75 return 76 } 77 78 # Output the patch content 79 $matchedFile.patch