-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpwsh-gitignore-template.ps1
More file actions
344 lines (292 loc) · 11.7 KB
/
Copy pathpwsh-gitignore-template.ps1
File metadata and controls
344 lines (292 loc) · 11.7 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# ======================================================================
# Cross-platform: auto-copy .gitignore after `git init`
# - PowerShell 7+ on Windows / macOS / Linux
# - Put AFTER posh-git or other module imports in your $PROFILE
#
# Git Init Wrapper v1.0.0 - Cross-platform auto .gitignore
#
# Commands:
# $Global:GIT_INIT_WRAPPER_DEBUG = $true|$false # toggle debug output
# New-GitIgnoreTemplate [-UseGitConfig] [-SetEnvironment] [-Path <file>] [-Content <text>]
# Get-GitIgnoreTemplatePaths [-Refresh] # returns FoundPath/Candidates
# Show-GitIgnoreTemplatePaths # pretty diagnostics (defined below)
# Copy-GitIgnoreFromTemplate -WorkTree <dir> [-Force] # manual copy
# git init [options] [dir] # normal usage; .gitignore is created silently
# ======================================================================
# --- DEBUG switch (set to $true to see messages; $false = silent) ---
$Global:GIT_INIT_WRAPPER_DEBUG = $false
function __DBG { param([string]$Msg,[string]$Color='Gray'); if ($Global:GIT_INIT_WRAPPER_DEBUG) { Write-Host $Msg -ForegroundColor $Color } }
# Resolve real git binary cross-platform (avoid recursion if a 'git' function exists)
$Global:__RealGitExe = (Get-Command git -CommandType Application -ErrorAction SilentlyContinue).Source
if (-not $Global:__RealGitExe -and $IsWindows) {
$Global:__RealGitExe = (Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue).Source
}
if (-not $Global:__RealGitExe) { $Global:__RealGitExe = 'git' } # best-effort fallback
# ---------- 5s cached template discovery ----------
$script:__TplCache = $null
function Get-GitIgnoreTemplatePaths {
param([switch]$Refresh)
if ($Refresh -or -not $script:__TplCache -or (Get-Date) -gt $script:__TplCache.Expires) {
$candidates = New-Object System.Collections.Generic.List[string]
# 1) Explicit environment variable (process/user/system)
if ($env:GIT_IGNORE_TEMPLATE) { $candidates.Add($env:GIT_IGNORE_TEMPLATE) }
# 2) git config init.templateDir (global then system)
try {
$g = & $Global:__RealGitExe config --global --get init.templateDir 2>$null
if ($g) { $candidates.Add( (Join-Path $g '.gitignore') ) }
} catch {}
try {
$s = & $Global:__RealGitExe config --system --get init.templateDir 2>$null
if ($s) { $candidates.Add( (Join-Path $s '.gitignore') ) }
} catch {}
# 3) Common locations (OS-aware)
$candidates.Add("$HOME/.git-templates/.gitignore")
$candidates.Add("$HOME/.gitignore-template")
if ($IsWindows) {
if ($env:APPDATA) { $candidates.Add("$env:APPDATA/git/templates/.gitignore") }
if ($env:ProgramData) { $candidates.Add("$env:ProgramData/Git/templates/.gitignore") }
} else {
$candidates.Add("$HOME/.config/git/templates/.gitignore")
$candidates.Add("/usr/share/git-core/templates/.gitignore")
$candidates.Add("/usr/local/share/git-core/templates/.gitignore")
}
$found = $null
foreach ($p in $candidates) {
if ($p -and (Test-Path -LiteralPath $p)) { $found = $p; break }
}
$script:__TplCache = [pscustomobject]@{
FoundPath = $found
Candidates = $candidates
Expires = (Get-Date).AddSeconds(5)
}
}
return $script:__TplCache
}
function Show-GitIgnoreTemplatePaths {
$info = Get-GitIgnoreTemplatePaths -Refresh
Write-Host ""
Write-Host "Template Search Results:" -ForegroundColor Cyan
$found = if ($info.FoundPath) { $info.FoundPath } else { 'None' }
Write-Host "Found: $found" -ForegroundColor $(if ($info.FoundPath) { 'Green' } else { 'Yellow' })
Write-Host ""
Write-Host "Searched (in order):" -ForegroundColor Gray
foreach ($p in $info.Candidates) {
$exists = Test-Path -LiteralPath $p
$tick = if ($exists) { '✓' } else { ' ' }
Write-Host (" {0} {1}" -f $tick, $p) -ForegroundColor $(if ($exists) { 'Green' } else { 'DarkGray' })
}
}
function Copy-GitIgnoreFromTemplate {
param(
[Parameter(Mandatory=$true)] [string]$WorkTree,
[switch]$Force
)
$info = Get-GitIgnoreTemplatePaths
$template = $info.FoundPath
if (-not $template) {
__DBG "ℹ No .gitignore template found. Set `$env:GIT_IGNORE_TEMPLATE or create $HOME/.git-templates/.gitignore" 'Yellow'
return
}
$dest = Join-Path $WorkTree '.gitignore'
if ((Test-Path -LiteralPath $dest) -and -not $Force) {
__DBG "⚠ .gitignore already exists in $WorkTree (use -Force to overwrite)" 'Yellow'
return
}
try {
Copy-Item -LiteralPath $template -Destination $dest -Force
__DBG "✓ Created .gitignore in $WorkTree from $template" 'Green'
} catch {
__DBG "✗ Failed to copy .gitignore: $_" 'Red'
}
}
# ---------- Wrapper: intercept ANY `init`; pass all else through ----------
function git {
param([Parameter(ValueFromRemainingArguments=$true)] [string[]]$Args)
# No args -> call real git; keep exit code, print nothing
if (-not $Args -or $Args.Count -eq 0) {
& $Global:__RealGitExe
$global:LASTEXITCODE = $LASTEXITCODE
if ($Global:GIT_INIT_WRAPPER_DEBUG -and $LASTEXITCODE -ne 0) { __DBG "git exited with code $LASTEXITCODE" 'Yellow' }
return
}
# Find 'init' anywhere (handles: git -C dir --no-pager init -q -b main target)
$lower = $Args | ForEach-Object { $_.ToLowerInvariant() }
$initIndex = $lower.IndexOf('init')
if ($initIndex -ge 0) {
# Run real git first (so the repo actually exists)
& $Global:__RealGitExe @Args
$exitCode = $LASTEXITCODE
$global:LASTEXITCODE = $exitCode
if ($exitCode -ne 0) { if ($Global:GIT_INIT_WRAPPER_DEBUG) { __DBG "git exited with code $exitCode" 'Yellow' } ; return }
# Skip bare repos
if ($Args -contains '--bare') { return }
# Determine effective base dir from the last '-C <dir>'
$baseDir = (Get-Location).Path
for ($i = 0; $i -lt $Args.Count - 1; $i++) {
if ($Args[$i] -eq '-C') {
try { $baseDir = (Resolve-Path -LiteralPath $Args[$i+1]).Path } catch {}
}
}
# Last non-flag token AFTER 'init' is the candidate target dir (if any)
$dirArg = $null
for ($i = $initIndex + 1; $i -lt $Args.Count; $i++) {
$tok = $Args[$i]
if ($tok -eq '--') { continue }
if ($tok -like '-*') { continue }
$dirArg = $tok
}
# Determine repo root
$repoRoot = $null
try {
if ($dirArg) {
$candidate = (Resolve-Path -LiteralPath (Join-Path $baseDir $dirArg) -ErrorAction SilentlyContinue).Path
if ($candidate) { $repoRoot = $candidate }
}
if (-not $repoRoot) {
$repoRoot = (& $Global:__RealGitExe -C $baseDir rev-parse --show-toplevel 2>$null)
}
} catch {}
if (-not $repoRoot) { $repoRoot = $baseDir }
# Double-check: not a bare repo
try {
$isBare = (& $Global:__RealGitExe -C $repoRoot rev-parse --is-bare-repository 2>$null) -eq 'true'
} catch { $isBare = $false }
if (-not $isBare) {
Copy-GitIgnoreFromTemplate -WorkTree $repoRoot
}
return
}
# Not an 'init' call -> pass through, keep exit code, print nothing
& $Global:__RealGitExe @Args
$global:LASTEXITCODE = $LASTEXITCODE
if ($Global:GIT_INIT_WRAPPER_DEBUG -and $LASTEXITCODE -ne 0) { __DBG "git exited with code $LASTEXITCODE" 'Yellow' }
return
}
# ---------- Helper to create/set a template quickly ----------
function New-GitIgnoreTemplate {
[CmdletBinding()]
param(
[string]$Path,
[switch]$UseGitConfig, # Create under git's init.templateDir (and set it if missing)
[switch]$SetEnvironment, # Persist $env:GIT_IGNORE_TEMPLATE (profile on Unix; User env on Windows)
[string]$Content
)
if ($UseGitConfig) {
$tplDir = & $Global:__RealGitExe config --global --get init.templateDir 2>$null
if (-not $tplDir) {
$tplDir = "$HOME/.git-templates"
& $Global:__RealGitExe config --global init.templateDir $tplDir | Out-Null
__DBG "✓ Set git global init.templateDir to $tplDir" 'Green'
}
if (-not (Test-Path -LiteralPath $tplDir)) { New-Item -ItemType Directory -Path $tplDir -Force | Out-Null }
if (-not $Path) { $Path = (Join-Path $tplDir '.gitignore') }
} else {
if (-not $Path) { $Path = "$HOME/.git-templates/.gitignore" }
$dir = Split-Path $Path -Parent
if (-not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
}
if (-not $Content) {
@"
# Created by https://www.toptal.com/developers/gitignore/api/git,linux,macos,windows
# Edit at https://www.toptal.com/developers/gitignore?templates=git,linux,macos,windows
### Git ###
# Created by git for backups. To disable backups in Git:
# $ git config --global mergetool.keepBackup false
*.orig
# Created by git when using merge tools for conflicts
*.BACKUP.*
*.BASE.*
*.LOCAL.*
*.REMOTE.*
*_BACKUP_*.txt
*_BASE_*.txt
*_LOCAL_*.txt
*_REMOTE_*.txt
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# End of https://www.toptal.com/developers/gitignore/api/git,linux,macos,windows
"@ | Set-Content -Path $Path -Encoding UTF8
} else {
$Content | Set-Content -Path $Path -Encoding UTF8
}
__DBG "✓ Template written: $Path" 'Green'
if ($SetEnvironment) {
if ($IsWindows) {
[Environment]::SetEnvironmentVariable('GIT_IGNORE_TEMPLATE', $Path, 'User')
__DBG "✓ Set User env var GIT_IGNORE_TEMPLATE=$Path" 'Green'
} else {
try {
Add-Content -Path $PROFILE -Value "`n`$env:GIT_IGNORE_TEMPLATE = '$Path'"
__DBG "✓ Appended to `$PROFILE to persist GIT_IGNORE_TEMPLATE" 'Green'
} catch {
__DBG "⚠ Could not write to `$PROFILE; set manually: `$env:GIT_IGNORE_TEMPLATE = '$Path'" 'Yellow'
}
}
$env:GIT_IGNORE_TEMPLATE = $Path # current session
Get-GitIgnoreTemplatePaths -Refresh | Out-Null
}
}
# ---------- Session status (only when DEBUG=true) ----------
if ($Global:GIT_INIT_WRAPPER_DEBUG) {
$__status = Get-GitIgnoreTemplatePaths
if ($__status.FoundPath) {
__DBG "✓ Git 'init' wrapper active; template: $($__status.FoundPath)" 'Green'
} else {
__DBG "ℹ Git 'init' wrapper active; no template found. Run: New-GitIgnoreTemplate" 'Yellow'
}
}
# ======================================================================