-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap-github.ps1
More file actions
293 lines (233 loc) · 8.18 KB
/
bootstrap-github.ps1
File metadata and controls
293 lines (233 loc) · 8.18 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
$ErrorActionPreference = "Stop"
function Write-Info($msg) { Write-Host "[INFO] $msg" -ForegroundColor Cyan }
function Write-Ok($msg) { Write-Host "[OK] $msg" -ForegroundColor Green }
function Write-Warn($msg) { Write-Host "[WARN] $msg" -ForegroundColor Yellow }
function Write-Fail($msg) { Write-Host "[ERROR] $msg" -ForegroundColor Red }
function Write-Step($msg) { Write-Host "[STEP] $msg" -ForegroundColor Magenta }
function Test-CommandExists {
param([string]$CommandName)
return $null -ne (Get-Command $CommandName -ErrorAction SilentlyContinue)
}
function Invoke-Git {
param(
[Parameter(Mandatory = $true)]
[string[]]$Args
)
$cmdText = "git " + ($Args -join " ")
Write-Info $cmdText
$output = & git @Args 2>&1
$exit = $LASTEXITCODE
if ($output) {
($output | Out-String).TrimEnd() | ForEach-Object {
if ($_ -ne "") {
Write-Host " $_" -ForegroundColor DarkGray
}
}
}
if ($exit -ne 0) {
$text = ($output | Out-String).Trim()
if ([string]::IsNullOrWhiteSpace($text)) {
$text = "Git command failed: $cmdText"
}
throw $text
}
return $output
}
function Get-GitOutputSafe {
param(
[Parameter(Mandatory = $true)]
[string[]]$Args
)
$output = & git @Args 2>$null
if ($LASTEXITCODE -ne 0) {
return $null
}
return ($output | Out-String).Trim()
}
function Resolve-ProjectPath {
$currentPath = (Get-Location).Path
$scriptPath = Split-Path -Parent $PSCommandPath
Write-Host ""
Write-Host "Detected current folder : $currentPath" -ForegroundColor Gray
Write-Host "Bootstrap script folder : $scriptPath" -ForegroundColor Gray
Write-Host ""
$answer = Read-Host "Use current folder as project folder? (Y/n)"
if ([string]::IsNullOrWhiteSpace($answer) -or $answer -match "^(y|yes)$") {
return $currentPath
}
$enteredPath = Read-Host "Enter project folder path"
if ([string]::IsNullOrWhiteSpace($enteredPath)) {
throw "Project folder path must not be empty."
}
if (-not (Test-Path -LiteralPath $enteredPath)) {
throw "Project folder does not exist: $enteredPath"
}
return (Resolve-Path -LiteralPath $enteredPath).Path
}
function Test-IsGitRepo {
param(
[Parameter(Mandatory = $true)]
[string]$ProjectPath
)
$gitFolder = Join-Path $ProjectPath ".git"
return (Test-Path -LiteralPath $gitFolder)
}
function Test-HasCommit {
$null = & git rev-parse --verify HEAD 2>$null
return ($LASTEXITCODE -eq 0)
}
function Get-CurrentBranchSafe {
return (Get-GitOutputSafe -Args @("branch", "--show-current"))
}
function Ensure-RepoInitialized {
param(
[Parameter(Mandatory = $true)]
[string]$ProjectPath
)
Write-Step "Checking whether .git exists"
$gitFolder = Join-Path $ProjectPath ".git"
Write-Info "Expected .git path: $gitFolder"
if (Test-IsGitRepo -ProjectPath $ProjectPath) {
Write-Warn "Git repository already exists in this folder."
return
}
Write-Step "Initializing repository"
Invoke-Git -Args @("init", "-b", "main") | Out-Null
if (-not (Test-IsGitRepo -ProjectPath $ProjectPath)) {
throw "git init reported success, but .git folder was not created."
}
Write-Ok "Initialized new git repository with branch main"
}
function Ensure-MainBranch {
Write-Step "Checking current branch"
$branch = Get-CurrentBranchSafe
if ([string]::IsNullOrWhiteSpace($branch)) {
if (Test-HasCommit) {
Write-Warn "Could not detect current branch cleanly, but repository already has commits."
}
else {
Write-Warn "Repository has no first commit yet. main will become active after the first commit."
}
return
}
if ($branch -ne "main") {
Write-Step "Renaming branch to main"
Invoke-Git -Args @("branch", "-M", "main") | Out-Null
Write-Ok "Renamed branch to main"
}
else {
Write-Ok "Branch is already main"
}
}
function Ensure-Origin {
param(
[Parameter(Mandatory = $true)]
[string]$RepoUrl
)
Write-Step "Checking remote origin"
$remotes = Get-GitOutputSafe -Args @("remote")
$remoteList = @()
if (-not [string]::IsNullOrWhiteSpace($remotes)) {
$remoteList = $remotes -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ }
}
if ($remoteList -contains "origin") {
$existingOrigin = Get-GitOutputSafe -Args @("remote", "get-url", "origin")
if ([string]::IsNullOrWhiteSpace($existingOrigin)) {
throw "Remote 'origin' exists but its URL could not be read."
}
if ($existingOrigin -eq $RepoUrl) {
Write-Ok "Remote origin already correct"
return
}
Write-Warn "Remote origin already exists: $existingOrigin"
$overwrite = Read-Host "Overwrite origin with new URL? (y/n)"
if ($overwrite -match "^(y|yes)$") {
Invoke-Git -Args @("remote", "set-url", "origin", $RepoUrl) | Out-Null
Write-Ok "Updated remote origin to: $RepoUrl"
return
}
throw "Aborted because remote origin points to a different repository."
}
Write-Step "Adding remote origin"
Invoke-Git -Args @("remote", "add", "origin", $RepoUrl) | Out-Null
Write-Ok "Added remote origin: $RepoUrl"
}
function Ensure-Commit {
param(
[Parameter(Mandatory = $true)]
[string]$CommitMessage
)
Write-Step "Staging files"
Invoke-Git -Args @("add", ".") | Out-Null
$status = Get-GitOutputSafe -Args @("status", "--porcelain")
$hasCommit = Test-HasCommit
if ([string]::IsNullOrWhiteSpace($status)) {
if ($hasCommit) {
Write-Warn "Nothing to commit. Repository already has at least one commit."
return
}
throw "Repository has no commit yet and there are no files available for an initial commit."
}
if (-not $hasCommit) {
Write-Warn "No commit exists yet. Creating initial commit now."
}
Write-Step "Creating commit"
Invoke-Git -Args @("commit", "-m", $CommitMessage) | Out-Null
if (-not $hasCommit) {
Write-Ok "Initial commit created: $CommitMessage"
}
else {
Write-Ok "Commit created: $CommitMessage"
}
}
function Ensure-UpstreamPush {
Write-Step "Pushing branch to GitHub"
if (-not (Test-HasCommit)) {
throw "Cannot push because the repository still has no commit."
}
$branch = Get-CurrentBranchSafe
if ([string]::IsNullOrWhiteSpace($branch)) {
$branch = "main"
Write-Warn "Current branch could not be detected cleanly. Assuming main for push."
}
Invoke-Git -Args @("push", "-u", "origin", $branch) | Out-Null
Write-Ok "Pushed $branch to origin"
}
try {
if (-not (Test-CommandExists "git")) {
throw "Git was not found in PATH."
}
$projectPath = Resolve-ProjectPath
Set-Location -LiteralPath $projectPath
Write-Host ""
Write-Host "=== GitHub Bootstrap for Current Project ===" -ForegroundColor White
Write-Host "Project folder: $projectPath" -ForegroundColor Gray
Write-Host ""
Write-Step "Verifying working folder"
Write-Info "Current location after Set-Location: $((Get-Location).Path)"
$repoName = Read-Host "GitHub repository name"
if ([string]::IsNullOrWhiteSpace($repoName)) {
throw "Repository name must not be empty."
}
$commitMessage = Read-Host "Commit message"
if ([string]::IsNullOrWhiteSpace($commitMessage)) {
$commitMessage = "Initial commit"
Write-Warn "Empty commit message entered. Using: Initial commit"
}
$repoUrl = "https://github.com/olaf-h/$repoName.git"
Write-Host ""
Write-Info "Repository URL will be: $repoUrl"
Write-Host ""
Ensure-RepoInitialized -ProjectPath $projectPath
Ensure-MainBranch
Ensure-Origin -RepoUrl $repoUrl
Ensure-Commit -CommitMessage $commitMessage
Ensure-UpstreamPush
Write-Host ""
Write-Ok "Done. Your project is now connected to GitHub."
}
catch {
Write-Host ""
Write-Fail $_.Exception.Message
exit 1
}