Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jenol/cb483e3f0f598ab5afefeab755f95fd6 to your computer and use it in GitHub Desktop.
Save jenol/cb483e3f0f598ab5afefeab755f95fd6 to your computer and use it in GitHub Desktop.
Script to create a new github pull request and add and update a file.
$ErrorActionPreference = "Stop"
#https://github.com/settings/tokens/new?scopes=repo
$githubAuth = "use your own"
$headers = @{
Accept = "application/vnd.github.v3+json"
Authorization = "bearer $githubAuth"
}
$baseUrl = "https://api.github.com"
function Get-GitResource($url) {
try {
return Invoke-RestMethod -Method GET -Uri $url -Headers $headers
} catch {
if($_.Exception.Response.StatusCode -eq "NotFound") {
return $null
}
throw $_.Exception
}
}
function Upsert-GitBranch($organization, $repoName, $fromRef, $featureName) {
$refs = Get-GitResource "$baseUrl/repos/$organization/$repoName/git/refs/heads"
$branch = $refs | ? { $_.ref -eq "refs/heads/$featureName" }
if (!$branch) {
$from = $refs | ? { $_.ref -eq $fromRef }
if (!$from) {
throw "fromRef not found"
}
$body = ConvertTo-Json @{
ref = "refs/heads/$featureName"
sha = $from.object.sha
}
$branch = Invoke-RestMethod -Method POST -Uri "$baseUrl/repos/$organization/$repoName/git/refs" -Headers $headers -Body $body
}
return $branch
}
function Upsert-GitContent($organization, $repoName, $branchName, $path, $text, $comment) {
$content = Get-GitResource "$baseUrl/repos/$organization/$repoName/contents/$($path)?ref=$branchName"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($text)
$data = @{
message = $comment
content = [Convert]::ToBase64String($bytes)
branch = $branchName
}
if ($content) {
$data.Add("sha", $content.sha)
}
$body = ConvertTo-Json $data
Invoke-RestMethod -Method PUT -Uri "$baseUrl/repos/$organization/$repoName/contents/$($path)" -Headers $headers -Body $body
}
function Get-GitPr($organization, $repoName, $title, $head, $base) {
$pr = Get-GitResource "$baseUrl/repos/$organization/$repoName/pulls" | ? { $_.title -eq $title }
if (!$pr) {
$body = ConvertTo-Json @{
title = $title
head = $head
base = $base
}
$pr = Invoke-RestMethod -Method POST -Uri "$baseUrl/repos/$organization/$repoName/pulls" -Headers $headers -Body $body
}
return $pr
}
$branch = Upsert-GitBranch "your org" "your repo" "refs/heads/main" "your new feature branch"
Upsert-GitContent "your org" "your repo" "your new feature branch" "file path" "file content" "commit comments"
Get-GitPr "your org" "your repo" "your pr name" "your new feature branch" "refs/heads/main"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment