-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_github.ps1
More file actions
252 lines (225 loc) · 11.9 KB
/
backup_github.ps1
File metadata and controls
252 lines (225 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
<#
backup_github_full.ps1
GitHub Full/Lite Backup (PowerShell, with confirmation)
- LITE : Code (all branches/tags via --mirror) + Wiki
- FULL : LITE + Metadata (issues + comments, pulls + comments + reviews, labels, milestones, releases + assets, optional discussions)
- Mode auto-detected by token presence (-Token or $env:GITHUB_TOKEN)
- Confirms the decided mode with [y/N] before running
#>
param(
[Parameter(Mandatory = $true)]
[string]$RepoUrl,
[string]$OutDir = ".",
[string]$Token,
[switch]$IncludeDiscussions,
[switch]$Zip,
# Used by CMD wrapper to run metadata only after code/wiki is done
[switch]$MetaOnly
)
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
function Write-Section([string]$text) {
Write-Host ("-" * 50)
Write-Host $text
Write-Host ("-" * 50)
}
function Ensure-GitExists {
if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
throw "Git is not installed or available in PATH. Install from https://git-scm.com and try again."
}
}
function Get-EffectiveToken([string]$t) {
if (-not [string]::IsNullOrWhiteSpace($t)) { return $t }
if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_TOKEN)) { return $env:GITHUB_TOKEN }
return $null
}
function Get-RepoNameFromUrl([string]$url) {
$tmp = $url
if ($tmp.EndsWith(".git",[System.StringComparison]::OrdinalIgnoreCase)) { $tmp = $tmp.Substring(0,$tmp.Length-4) }
try { $uri = [Uri]$tmp; $name = $uri.Segments[-1].TrimEnd('/') }
catch { $name = ($tmp -split '[\\/]' | Where-Object { $_.Length -gt 0 })[-1] }
if ([string]::IsNullOrWhiteSpace($name)) { throw "Failed to extract repository name from URL. Input: $url" }
return $name
}
function Build-WikiUrl([string]$url) {
if ($url.EndsWith(".git",[System.StringComparison]::OrdinalIgnoreCase)) { return ($url.Substring(0,$url.Length-4) + ".wiki.git") }
else { return ($url.TrimEnd('/') + ".wiki.git") }
}
function New-CleanDir([string]$path) {
if (Test-Path $path) {
Write-Host "The backup folder already exists: `"$path`""
$ans = Read-Host "Do you want to OVERWRITE it? [y/N]"
if ($ans -notin @('y','Y','yes','YES')) {
Write-Host "Aborted. Nothing was changed."
exit 0
}
Write-Host "Removing existing folder..."
Remove-Item -Recurse -Force -LiteralPath $path
if (Test-Path $path) { throw "Failed to remove the existing folder. Check permissions." }
}
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
function Get-OwnerRepoFromUrl([string]$url) {
$u=$url; if ($u.EndsWith(".git",[System.StringComparison]::OrdinalIgnoreCase)) { $u=$u.Substring(0,$u.Length-4) }
$uri=[Uri]$u; $segs=$uri.Segments | ForEach-Object { $_.Trim('/') } | Where-Object { $_ }
if ($segs.Count -lt 2) { throw "Cannot parse owner/repo from: $url" }
return @{ owner=$segs[-2]; repo=$segs[-1] }
}
function Invoke-GHRestPaged {
param([string]$Url,[string]$Token)
$all=@(); $page=1
while ($true) {
$sep = ($Url -match '\?') ? '&' : '?'
$u = "$Url${sep}per_page=100&page=$page"
$resp = Invoke-WebRequest -Uri $u -Headers @{ Authorization="token $Token"; "User-Agent"="backup-script" } -UseBasicParsing
$chunk = $null; if ($resp.Content) { $chunk = $resp.Content | ConvertFrom-Json }
if ($chunk) { $all += $chunk }
$link = $resp.Headers['Link']
if (-not $link -or ($link -notmatch 'rel="next"')) { break }
$page++
}
return ,$all
}
try {
Ensure-GitExists
$effectiveToken = Get-EffectiveToken -t $Token
$mode = if ($effectiveToken) { "FULL" } else { "LITE" }
# Mode confirmation (skip only when MetaOnly, because CMD already confirmed)
if (-not $MetaOnly.IsPresent) {
Write-Section "Detected mode: $mode"
if ($mode -eq "FULL") {
Write-Host "This will back up: Code+Wiki+Metadata (issues, issue comments, PRs, PR comments/reviews, labels, milestones, releases+assets)."
} else {
Write-Host "This will back up: Code+Wiki only (no metadata). Set GITHUB_TOKEN or -Token to enable FULL mode."
}
$ans = Read-Host "Proceed with this mode? [y/N]"
if ($ans -notin @('y','Y','yes','YES')) {
Write-Host "Aborted. Nothing was changed."
exit 0
}
}
$repoName = Get-RepoNameFromUrl -url $RepoUrl
$ownerRepo = Get-OwnerRepoFromUrl -url $RepoUrl
$owner = $ownerRepo.owner; $repo = $ownerRepo.repo
$backupDir = Join-Path -Path (Resolve-Path $OutDir) -ChildPath ("{0}_backup" -f $repoName)
$codeBare = Join-Path $backupDir ("{0}.git" -f $repoName)
$wikiBare = Join-Path $backupDir ("{0}.wiki.git" -f $repoName)
$metaDir = Join-Path $backupDir "meta"
if (-not $MetaOnly.IsPresent) {
Write-Section "[1/6] Preparing backup folder: $backupDir"
New-CleanDir -path $backupDir
Write-Section "[2/6] Backing up main repository (mirror: all branches/tags)"
$gitCloneArgs = @("clone","--mirror",$RepoUrl,$codeBare)
$p = Start-Process -FilePath "git" -ArgumentList $gitCloneArgs -NoNewWindow -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "Failed to back up main repository. ExitCode=$($p.ExitCode)" }
Write-Section "[3/6] Checking Wiki"
$wikiUrl = Build-WikiUrl -url $RepoUrl
Write-Host "Wiki URL: $wikiUrl"
$ls = Start-Process -FilePath "git" -ArgumentList @("ls-remote",$wikiUrl) -NoNewWindow -Wait -PassThru `
-RedirectStandardOutput "$env:TEMP\lsremote_$repoName.txt" `
-RedirectStandardError "$env:TEMP\lsremote_$repoName.err.txt"
if ($ls.ExitCode -eq 0) {
Write-Host "Wiki repository found. Backing up Wiki..."
$pw = Start-Process -FilePath "git" -ArgumentList @("clone","--mirror",$wikiUrl,$wikiBare) -NoNewWindow -Wait -PassThru
if ($pw.ExitCode -ne 0) { Write-Warning "Wiki backup failed. Main repository backup succeeded. ExitCode=$($pw.ExitCode)" }
} else {
Write-Host "Wiki repository not found or inaccessible. Skipping..."
}
} else {
if (-not (Test-Path $backupDir)) { New-Item -ItemType Directory -Path $backupDir -Force | Out-Null }
}
if ($mode -eq "FULL") {
New-Item -ItemType Directory -Path $metaDir -Force | Out-Null
$issuesDir = Join-Path $metaDir "issues"
$pullsDir = Join-Path $metaDir "pulls"
$relsDir = Join-Path $metaDir "releases"
New-Item -ItemType Directory -Path $issuesDir -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $issuesDir "comments") -Force | Out-Null
New-Item -ItemType Directory -Path $pullsDir -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $pullsDir "comments") -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $pullsDir "reviews") -Force | Out-Null
New-Item -ItemType Directory -Path $relsDir -Force | Out-Null
New-Item -ItemType Directory -Path (Join-Path $relsDir "assets") -Force | Out-Null
Write-Section "[4/6] Exporting repository metadata (basic, labels, milestones)"
$repoInfo = Invoke-WebRequest -Uri ("https://api.github.com/repos/{0}/{1}" -f $owner,$repo) `
-Headers @{ Authorization="token $effectiveToken"; "User-Agent"="backup-script" } -UseBasicParsing
$repoInfo.Content | Out-File -FilePath (Join-Path $metaDir "repository.json") -Encoding utf8
(Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/labels" -f $owner,$repo) -Token $effectiveToken | ConvertTo-Json -Depth 100) `
| Out-File (Join-Path $metaDir "labels.json") -Encoding utf8
(Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/milestones?state=all" -f $owner,$repo) -Token $effectiveToken | ConvertTo-Json -Depth 100) `
| Out-File (Join-Path $metaDir "milestones.json") -Encoding utf8
Write-Section "[5/6] Exporting issues and pull requests (with comments/reviews)"
$issues = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/issues?state=all&filter=all" -f $owner,$repo) -Token $effectiveToken
$issues | ConvertTo-Json -Depth 100 | Out-File (Join-Path $issuesDir "issues.json") -Encoding utf8
foreach ($i in $issues) {
if ($i.pull_request) { continue }
$num = $i.number
$cmt = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/issues/{2}/comments" -f $owner,$repo,$num) -Token $effectiveToken
$cmt | ConvertTo-Json -Depth 100 | Out-File (Join-Path $issuesDir "comments\{0}.comments.json" -f $num) -Encoding utf8
}
$pulls = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/pulls?state=all" -f $owner,$repo) -Token $effectiveToken
$pulls | ConvertTo-Json -Depth 100 | Out-File (Join-Path $pullsDir "pulls.json") -Encoding utf8
foreach ($p in $pulls) {
$num = $p.number
$pc = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/pulls/{2}/comments" -f $owner,$repo,$num) -Token $effectiveToken
$pc | ConvertTo-Json -Depth 100 | Out-File (Join-Path $pullsDir "comments\{0}.comments.json" -f $num) -Encoding utf8
$prc = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/issues/{2}/comments" -f $owner,$repo,$num) -Token $effectiveToken
$prc | ConvertTo-Json -Depth 100 | Out-File (Join-Path $pullsDir "comments\{0}.issue-comments.json" -f $num) -Encoding utf8
$rvw = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/pulls/{2}/reviews" -f $owner,$repo,$num) -Token $effectiveToken
$rvw | ConvertTo-Json -Depth 100 | Out-File (Join-Path $pullsDir "reviews\{0}.reviews.json" -f $num) -Encoding utf8
}
Write-Section "[6/6] Exporting releases (and assets)"
$rels = Invoke-GHRestPaged -Url ("https://api.github.com/repos/{0}/{1}/releases" -f $owner,$repo) -Token $effectiveToken
$rels | ConvertTo-Json -Depth 100 | Out-File (Join-Path $relsDir "releases.json") -Encoding utf8
foreach ($r in $rels) {
if (-not $r.assets) { continue }
$rid = $r.id
$assetBase = Join-Path (Join-Path $relsDir "assets") ("{0}" -f $rid)
New-Item -ItemType Directory -Path $assetBase -Force | Out-Null
foreach ($a in $r.assets) {
$aname = $a.name
$dlUrl = $a.browser_download_url
if ([string]::IsNullOrWhiteSpace($dlUrl)) { continue }
$dst = Join-Path $assetBase $aname
Write-Host "Downloading asset: $aname"
Invoke-WebRequest -Uri $dlUrl -Headers @{ Authorization="token $effectiveToken"; "User-Agent"="backup-script" } -OutFile $dst -UseBasicParsing
}
}
if ($IncludeDiscussions) {
Write-Section "[Extra] Exporting discussions (experimental)"
$gql = @"
query(\$owner:String!,\$repo:String!) {
repository(owner:\$owner,name:\$repo) {
discussions(first:100, orderBy:{field:CREATED_AT, direction:ASC}) {
nodes { id number title body createdAt author { login } url }
pageInfo { hasNextPage endCursor }
}
}
}
"@
$gbody = @{ query=$gql; variables=@{ owner=$owner; repo=$repo } } | ConvertTo-Json -Depth 100
$dg = Invoke-WebRequest -Uri "https://api.github.com/graphql" -Method POST `
-Headers @{ Authorization="bearer $effectiveToken"; "User-Agent"="backup-script" } `
-Body $gbody -UseBasicParsing
$discDir = Join-Path $metaDir "discussions"
New-Item -ItemType Directory -Path $discDir -Force | Out-Null
$dg.Content | Out-File (Join-Path $discDir "discussions.json") -Encoding utf8
}
} else {
Write-Section "[Info] Running in LITE mode (Code+Wiki only). Metadata is skipped."
}
if ($Zip.IsPresent) {
$zipPath = Join-Path (Split-Path $backupDir -Parent) ("{0}.zip" -f (Split-Path $backupDir -Leaf))
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
Write-Section "[Zip] Creating ZIP archive"
Compress-Archive -Path (Join-Path $backupDir "*") -DestinationPath $zipPath -Force
Write-Host "ZIP created: $zipPath"
}
Write-Section "[Done] Backup finished ($mode mode)"
Write-Host "Backup location: $backupDir"
Write-Host " - Repository (mirror): $codeBare"
if (Test-Path $wikiBare) { Write-Host " - Wiki (mirror): $wikiBare" } else { Write-Host " - Wiki: (none)" }
if ($mode -eq "FULL") { Write-Host " - Metadata: $metaDir" } else { Write-Host " - Metadata: (skipped)" }
} catch {
Write-Error $_.Exception.Message
exit 1
}