-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRepoHerd.psm1
More file actions
3081 lines (2640 loc) · 121 KB
/
RepoHerd.psm1
File metadata and controls
3081 lines (2640 loc) · 121 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# RepoHerd Module
# Contains all function definitions for RepoHerd tool
# Version 9.1.0
#Requires -Version 7.6
# Module-scoped state variables
$script:Version = "9.1.0"
$script:ScriptPath = ""
$script:ErrorFile = ""
$script:DebugLogFile = ""
$script:SuccessCount = 0
$script:FailureCount = 0
$script:PostCheckoutScriptExecutions = 0
$script:PostCheckoutScriptFailures = 0
$script:SshCredentials = @{}
$script:RepositoryDictionary = @{}
$script:CurrentDepth = 0
$script:ProcessedDependencyFiles = @()
$script:DefaultApiCompatibility = 'Permissive'
$script:RecursiveMode = $true
$script:DefaultDependencyFileName = ""
$script:PostCheckoutScriptsEnabled = $true
$script:ErrorContextEnabled = $false
$script:DryRun = $false
$script:EnableDebug = $false
$script:MaxDepth = 5
$script:OutputFile = ""
$script:ErrorMessages = @()
$script:PostCheckoutScriptResults = @()
function Initialize-RepoHerd {
<#
.SYNOPSIS
Initializes module state from entry point parameters
.DESCRIPTION
Sets all module-scoped variables based on the parameters passed from the entry point script.
Must be called before any other module functions.
.PARAMETER ScriptPath
The directory containing the entry point script
.PARAMETER DryRun
When true, skip destructive git operations
.PARAMETER EnableDebug
When true, enable debug logging to file
.PARAMETER DisableRecursion
When true, disable recursive dependency processing
.PARAMETER MaxDepth
Maximum recursion depth for dependency processing
.PARAMETER ApiCompatibility
API compatibility mode: Strict or Permissive
.PARAMETER DisablePostCheckoutScripts
When true, skip post-checkout script execution
.PARAMETER EnableErrorContext
When true, show detailed error context with stack traces
.PARAMETER OutputFile
Path to write structured JSON results file
#>
param(
[Parameter(Mandatory=$true)]
[string]$ScriptPath,
[switch]$DryRun,
[switch]$EnableDebug,
[switch]$DisableRecursion,
[int]$MaxDepth = 5,
[ValidateSet('Strict', 'Permissive')]
[string]$ApiCompatibility = 'Permissive',
[switch]$DisablePostCheckoutScripts,
[switch]$EnableErrorContext,
[string]$OutputFile = ""
)
$script:ScriptPath = $ScriptPath
$script:ErrorFile = Join-Path $ScriptPath "RepoHerd_Errors.txt"
$script:DebugLogFile = Join-Path $ScriptPath ("debug_log_{0}.txt" -f (Get-Date -Format "yyyyMMddHHmm"))
$script:SuccessCount = 0
$script:FailureCount = 0
$script:PostCheckoutScriptExecutions = 0
$script:PostCheckoutScriptFailures = 0
$script:SshCredentials = @{}
$script:RepositoryDictionary = @{}
$script:CurrentDepth = 0
$script:ProcessedDependencyFiles = @()
$script:DefaultApiCompatibility = $ApiCompatibility
$script:RecursiveMode = -not $DisableRecursion
$script:DefaultDependencyFileName = ""
$script:PostCheckoutScriptsEnabled = -not $DisablePostCheckoutScripts
$script:ErrorContextEnabled = $EnableErrorContext
$script:DryRun = [bool]$DryRun
$script:EnableDebug = [bool]$EnableDebug
$script:MaxDepth = $MaxDepth
$script:OutputFile = $OutputFile
$script:ErrorMessages = @()
$script:PostCheckoutScriptResults = @()
# Initialize error file
if (Test-Path $script:ErrorFile) {
Remove-Item $script:ErrorFile -Force
}
}
function Write-ErrorWithContext {
<#
.SYNOPSIS
Writes an error with full context including line numbers and stack trace
.DESCRIPTION
Captures the error context including the exact line where the error occurred,
the function name, and the full stack trace for debugging
#>
param(
[Parameter(Mandatory=$true)]
$ErrorRecord,
[string]$AdditionalMessage = ""
)
# If error context is not enabled, just write a simple error message
if (-not $script:ErrorContextEnabled) {
$simpleMessage = $ErrorRecord.Exception.Message
if ($AdditionalMessage) {
$simpleMessage = "$AdditionalMessage : $simpleMessage"
}
Write-Log $simpleMessage -Level Error
return
}
# Get error details
$errorLine = $ErrorRecord.InvocationInfo.ScriptLineNumber
$errorColumn = $ErrorRecord.InvocationInfo.OffsetInLine
$errorScript = $ErrorRecord.InvocationInfo.ScriptName
$errorCommand = $ErrorRecord.InvocationInfo.Line.Trim()
$errorFunction = $ErrorRecord.InvocationInfo.MyCommand.Name
$errorException = $ErrorRecord.Exception.Message
# Build detailed error message
$errorDetails = @"
========================================
ERROR DETAILS
========================================
Exception: $errorException
Location: Line $errorLine, Column $errorColumn
Script: $errorScript
Function: $errorFunction
Command: $errorCommand
"@
if ($AdditionalMessage) {
$errorDetails += "`nAdditional Info: $AdditionalMessage"
}
# Add stack trace
if ($ErrorRecord.ScriptStackTrace) {
$errorDetails += @"
Stack Trace:
----------------------------------------
$($ErrorRecord.ScriptStackTrace)
========================================
"@
}
Write-Log $errorDetails -Level Error
# Also write a condensed version for quick reference
Write-Log "ERROR at line $errorLine in $errorFunction : $errorException" -Level Error
}
function Invoke-WithErrorContext {
<#
.SYNOPSIS
Executes a script block with enhanced error context reporting
#>
param(
[Parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock,
[string]$Context = ""
)
try {
& $ScriptBlock
}
catch {
Write-ErrorWithContext -ErrorRecord $_ -AdditionalMessage $Context
throw
}
}
function Write-Log {
param(
[string]$Message,
[ValidateSet('Info', 'Warning', 'Error', 'Debug', 'Verbose')]
[string]$Level = 'Info'
)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logMessage = "[$timestamp] [$Level] $Message"
switch ($Level) {
'Error' {
Write-Host $logMessage -ForegroundColor Red
Add-Content -Path $script:ErrorFile -Value $logMessage
$script:ErrorMessages += $Message
}
'Warning' {
Write-Host $logMessage -ForegroundColor Yellow
}
'Debug' {
if ($script:EnableDebug) {
Write-Host $logMessage -ForegroundColor Cyan
Add-Content -Path $script:DebugLogFile -Value $logMessage
}
}
'Verbose' {
if ($VerbosePreference -eq 'Continue') {
Write-Host $logMessage -ForegroundColor Gray
}
}
default {
Write-Host $logMessage
}
}
if ($script:EnableDebug -and $Level -ne 'Debug') {
Add-Content -Path $script:DebugLogFile -Value $logMessage
}
}
function ConvertTo-VersionPattern {
<#
.SYNOPSIS
Parses a version pattern and determines its type and constraints
.DESCRIPTION
Supports three patterns:
- x.y.z: Lowest applicable version (existing behavior)
- x.y.*: Floating patch version
- x.*: Floating minor.patch version
#>
param(
[string]$VersionPattern
)
Write-Log "Parsing version pattern: $VersionPattern" -Level Debug
# Check for floating version patterns
if ($VersionPattern -match '^(\d+)\.(\d+)\.\*$') {
# x.y.* pattern - floating patch
return @{
Type = "FloatingPatch"
Major = [int]$Matches[1]
Minor = [int]$Matches[2]
Patch = $null
OriginalPattern = $VersionPattern
}
}
elseif ($VersionPattern -match '^(\d+)\.\*$') {
# x.* pattern - floating minor.patch
return @{
Type = "FloatingMinor"
Major = [int]$Matches[1]
Minor = $null
Patch = $null
OriginalPattern = $VersionPattern
}
}
elseif ($VersionPattern -match '^(\d+)\.(\d+)\.(\d+)$') {
# x.y.z pattern - lowest applicable (existing)
return @{
Type = "LowestApplicable"
Major = [int]$Matches[1]
Minor = [int]$Matches[2]
Patch = [int]$Matches[3]
OriginalPattern = $VersionPattern
}
}
else {
throw "Invalid version pattern '$VersionPattern'. Supported formats: x.y.z, x.y.*, x.*"
}
}
function Test-SemVerCompatibility {
<#
.SYNOPSIS
Tests if an available version is compatible with a version pattern
.DESCRIPTION
Handles both traditional SemVer compatibility and new floating version patterns
#>
param(
[Version]$Available,
[hashtable]$VersionPattern
)
$major = $Available.Major
$minor = $Available.Minor
$patch = $Available.Build # Build = Patch in Version object
switch ($VersionPattern.Type) {
"LowestApplicable" {
# Existing SemVer logic
if ($VersionPattern.Major -eq 0) {
# Special handling for 0.x.y versions
return $major -eq 0 -and
$minor -eq $VersionPattern.Minor -and
$patch -ge $VersionPattern.Patch
}
# Standard SemVer: compatible if same major and >= requested minor.patch
return $major -eq $VersionPattern.Major -and
($minor -gt $VersionPattern.Minor -or
($minor -eq $VersionPattern.Minor -and $patch -ge $VersionPattern.Patch))
}
"FloatingPatch" {
# x.y.* - same major.minor, any patch >= 0
if ($VersionPattern.Major -eq 0) {
# Special handling for 0.x.* versions
return $major -eq 0 -and $minor -eq $VersionPattern.Minor
}
return $major -eq $VersionPattern.Major -and $minor -eq $VersionPattern.Minor
}
"FloatingMinor" {
# x.* - same major, any minor.patch >= 0
if ($VersionPattern.Major -eq 0) {
# Special handling for 0.* versions
return $major -eq 0
}
return $major -eq $VersionPattern.Major
}
default {
throw "Unknown version pattern type: $($VersionPattern.Type)"
}
}
}
function Get-CompatibleVersionsForPattern {
<#
.SYNOPSIS
Gets all versions compatible with a specific version pattern
#>
param(
[hashtable]$ParsedVersions, # tag -> Version mapping
[hashtable]$VersionPattern
)
$compatible = @()
foreach ($entry in $ParsedVersions.GetEnumerator()) {
if (Test-SemVerCompatibility -Available $entry.Value -VersionPattern $VersionPattern) {
$compatible += [PSCustomObject]@{
Tag = $entry.Key
Version = $entry.Value
}
}
}
if ($compatible.Count -eq 0) {
# Format available versions for error message
$availableFormatted = $ParsedVersions.GetEnumerator() |
Sort-Object { $_.Value } |
ForEach-Object { "$($_.Key) ($($_.Value.Major).$($_.Value.Minor).$($_.Value.Build))" }
throw "No compatible version found for pattern '$($VersionPattern.OriginalPattern)'. " +
"Available versions: $($availableFormatted -join ', ')"
}
# Sort by version to ensure consistent ordering
$compatible = $compatible | Sort-Object { $_.Version }
Write-Log "Found $($compatible.Count) compatible versions for pattern '$($VersionPattern.OriginalPattern)'" -Level Debug
return $compatible
}
function Select-VersionFromIntersection {
<#
.SYNOPSIS
Selects the appropriate version from intersection based on specification types
.DESCRIPTION
If any pattern is floating, select highest version; otherwise select lowest
#>
param(
[array]$IntersectionVersions, # Array of PSCustomObject with Tag and Version
[hashtable]$RequestedPatterns # caller -> VersionPattern mapping
)
# Check if any pattern is floating
$hasFloatingPattern = $false
foreach ($pattern in $RequestedPatterns.Values) {
if ($pattern.Type -eq "FloatingPatch" -or $pattern.Type -eq "FloatingMinor") {
$hasFloatingPattern = $true
break
}
}
if ($hasFloatingPattern) {
# Select highest (most recent) version
$selected = $IntersectionVersions | Sort-Object { $_.Version } | Select-Object -Last 1
Write-Log "Floating version detected - selecting highest compatible version: $(Format-SemVersion $selected.Version) (tag: $($selected.Tag))" -Level Info
}
else {
# Select lowest version (existing behavior)
$selected = $IntersectionVersions | Sort-Object { $_.Version } | Select-Object -First 1
Write-Log "All patterns are lowest-applicable - selecting lowest compatible version: $(Format-SemVersion $selected.Version) (tag: $($selected.Tag))" -Level Info
}
return $selected
}
function Get-RepositoryVersions {
<#
.SYNOPSIS
Parses all repository tags using the specified regex pattern to extract SemVer versions
.DESCRIPTION
One-time parsing of all tags in a repository to build a cache of tag->version mappings
#>
param(
[string]$RepoPath,
[string]$VersionRegex = "^v?(\d+)\.(\d+)\.(\d+)$"
)
Write-Log "Parsing SemVer versions from repository at: $RepoPath" -Level Debug
Write-Log "Using version regex: $VersionRegex" -Level Debug
# Validate regex has at least 3 capture groups
try {
$compiledRegex = [regex]::new($VersionRegex)
$testMatch = $compiledRegex.Match("v1.2.3")
if ($compiledRegex.GetGroupNumbers().Count -lt 4) { # 0 + 3 groups
throw "Version regex must have at least 3 capture groups for major.minor.patch"
}
}
catch {
throw "Invalid version regex '$VersionRegex': $_"
}
$parsedVersions = @{}
$parseErrors = @()
# Get all tags from repository
try {
Push-Location $RepoPath
# Get all tags
$gitCommand = "git tag -l"
Write-Log "Executing: $gitCommand" -Level Debug
$tags = Invoke-Expression $gitCommand 2>&1
if ($LASTEXITCODE -ne 0) {
throw "Failed to get tags: $tags"
}
Pop-Location
foreach ($tag in $tags) {
if ([string]::IsNullOrWhiteSpace($tag)) { continue }
$tag = $tag.Trim()
$match = $compiledRegex.Match($tag)
if ($match.Success -and $match.Groups.Count -ge 4) {
try {
$major = [int]$match.Groups[1].Value
$minor = [int]$match.Groups[2].Value
$patch = [int]$match.Groups[3].Value
# Version constructor expects Major.Minor.Build.Revision
# We use Build for Patch and leave Revision as -1
$version = [Version]::new($major, $minor, $patch)
$parsedVersions[$tag] = $version
Write-Log "Parsed tag '$tag' as version $($major).$($minor).$($patch)" -Level Debug
}
catch {
$parseErrors += "Failed to parse version from tag '$tag': $_"
Write-Log "Failed to parse version from tag '$tag': $_" -Level Warning
}
}
}
if ($parsedVersions.Count -eq 0) {
$errorMsg = "No tags matching SemVer pattern '$VersionRegex' found in repository.`n"
$errorMsg += "Found tags: $($tags -join ', ')"
if ($parseErrors.Count -gt 0) {
$errorMsg += "`nParse errors:`n" + ($parseErrors -join "`n")
}
throw $errorMsg
}
Write-Log "Successfully parsed $($parsedVersions.Count) SemVer tags" -Level Info
return @{
ParsedVersions = $parsedVersions
CompiledRegex = $compiledRegex
}
}
catch {
Pop-Location -ErrorAction SilentlyContinue
throw
}
}
function Get-SemVersionIntersection {
<#
.SYNOPSIS
Gets the intersection of two sets of version objects
#>
param(
[array]$Set1, # Array of PSCustomObject with Tag and Version properties
[array]$Set2
)
$intersection = @()
foreach ($v1 in $Set1) {
foreach ($v2 in $Set2) {
if ($v1.Tag -eq $v2.Tag) {
$intersection += $v1
break
}
}
}
return $intersection
}
function Format-SemVersion {
<#
.SYNOPSIS
Formats a Version object as a SemVer string
#>
param(
[Version]$Version
)
return "$($Version.Major).$($Version.Minor).$($Version.Build)"
}
function Test-DependencyConfiguration {
<#
.SYNOPSIS
Validates that repository configuration hasn't changed in incompatible ways
#>
param(
[PSCustomObject]$NewRepo,
[hashtable]$ExistingRepo
)
$repoUrl = $NewRepo.'Repository URL'
# Determine dependency resolution mode
$newMode = if ($NewRepo.PSObject.Properties['Dependency Resolution']) {
$NewRepo.'Dependency Resolution'
} else {
"Agnostic"
}
# Rule 1: Dependency Resolution mode cannot change
if ($ExistingRepo.ContainsKey('DependencyResolution') -and
$ExistingRepo.DependencyResolution -ne $newMode) {
$errorMessage = "Repository '$repoUrl' configuration conflict:`n" +
"Previously discovered with Dependency Resolution: $($ExistingRepo.DependencyResolution)`n" +
"Now attempting to use Dependency Resolution: $newMode`n" +
"Dependency Resolution mode cannot change once established."
throw $errorMessage
}
# Rule 2: Version Regex cannot change (for SemVer mode)
if ($newMode -eq "SemVer" -and $ExistingRepo.ContainsKey('VersionRegex')) {
$newRegex = if ($NewRepo.PSObject.Properties['Version Regex']) {
$NewRepo.'Version Regex'
} else {
"^v?(\d+)\.(\d+)\.(\d+)$"
}
if ($ExistingRepo.VersionRegex -ne $newRegex) {
$errorMessage = "Repository '$repoUrl' configuration conflict:`n" +
"Previously discovered with Version Regex: $($ExistingRepo.VersionRegex)`n" +
"Now attempting to use Version Regex: $newRegex`n" +
"Version Regex cannot change once established."
throw $errorMessage
}
}
}
function Test-InteractiveSession {
<#
.SYNOPSIS
Checks if the current session is interactive (can show GUI dialogs)
.DESCRIPTION
Returns $false when running under pwsh -NonInteractive or in a non-user-interactive
environment (e.g., CI pipelines, automated tests, services).
#>
if (-not [Environment]::UserInteractive) {
return $false
}
# Check if PowerShell was launched with -NonInteractive
$cmdArgs = [Environment]::GetCommandLineArgs()
if ($cmdArgs -contains '-NonInteractive') {
return $false
}
return $true
}
function Show-ErrorDialog {
param(
[string]$Title = "Git Error",
[string]$Message
)
if (-not (Test-InteractiveSession)) {
return
}
Add-Type -AssemblyName System.Windows.Forms
$null = [System.Windows.Forms.MessageBox]::Show($Message, $Title, 'OK', 'Error')
}
function Show-ConfirmDialog {
param(
[string]$Title = "Confirmation Required",
[string]$Message
)
if (-not (Test-InteractiveSession)) {
return $true
}
Add-Type -AssemblyName System.Windows.Forms
$result = [System.Windows.Forms.MessageBox]::Show($Message, $Title, 'YesNo', 'Question')
return $result -eq 'Yes'
}
function Test-GitInstalled {
try {
$null = git --version
return $true
}
catch {
Write-Log "Git is not installed or not in PATH" -Level Error
Show-ErrorDialog -Message "Git is not installed or not accessible in PATH. Please install Git and try again."
return $false
}
}
function Test-GitLfsInstalled {
try {
$null = git lfs version
return $true
}
catch {
Write-Log "Git LFS is not installed" -Level Warning
return $false
}
}
function Test-SshTransportAvailable {
<#
.SYNOPSIS
Tests whether the platform-appropriate SSH transport is available.
.DESCRIPTION
On Windows, checks for plink.exe (PuTTY SSH client).
On macOS/Linux, checks for the ssh command (OpenSSH client).
.OUTPUTS
[bool] True if SSH transport is available, False otherwise.
#>
try {
if ($IsWindows) {
$null = Get-Command plink.exe -ErrorAction Stop
Write-Log "PuTTY plink found" -Level Debug
return $true
}
else {
$null = Get-Command ssh -ErrorAction Stop
Write-Log "OpenSSH client found" -Level Debug
return $true
}
}
catch {
if ($IsWindows) {
Write-Log "Plink is not installed or not in PATH" -Level Warning
}
else {
Write-Log "OpenSSH client (ssh) is not installed or not in PATH" -Level Warning
}
return $false
}
}
function Get-RepositoryUrl {
param(
[string]$RepoPath
)
try {
Push-Location $RepoPath
$url = git config --get remote.origin.url 2>$null
Pop-Location
return $url
}
catch {
Pop-Location
return $null
}
}
function Get-HostnameFromUrl {
param(
[string]$Url
)
Write-Log "Extracting hostname from URL: $Url" -Level Debug
# Handle different URL formats
if ($Url -match '^git@([^:]+):') {
# git@hostname:path format
$hostname = $matches[1]
Write-Log "Matched git@ format, extracted hostname: $hostname" -Level Debug
return $hostname
}
elseif ($Url -match '^ssh://(?:[^@]+@)?([^:/]+)(?::\d+)?') {
# ssh://[user@]hostname[:port]/path format
$hostname = $matches[1]
Write-Log "Matched ssh:// format, extracted hostname: $hostname" -Level Debug
return $hostname
}
elseif ($Url -match '^https?://(?:[^@]+@)?([^:/]+)') {
# http(s)://[user@]hostname[:port]/path format
$hostname = $matches[1]
Write-Log "Matched http(s):// format, extracted hostname: $hostname" -Level Debug
return $hostname
}
Write-Log "No matching URL format found for: $Url" -Level Debug
return $null
}
function Get-SshKeyForUrl {
param(
[string]$Url
)
$hostname = Get-HostnameFromUrl -Url $Url
if (-not $hostname) {
Write-Log "Could not extract hostname from URL: $Url" -Level Debug
return $null
}
Write-Log "Looking for SSH key for hostname: $hostname (from URL: $Url)" -Level Debug
# Check exact hostname match first
if ($script:SshCredentials.ContainsKey($hostname)) {
Write-Log "Found SSH key for hostname: $hostname" -Level Debug
return $script:SshCredentials[$hostname]
}
# Check with ssh:// prefix
$sshHostname = "ssh://$hostname"
if ($script:SshCredentials.ContainsKey($sshHostname)) {
Write-Log "Found SSH key for ssh://$hostname" -Level Debug
return $script:SshCredentials[$sshHostname]
}
Write-Log "No SSH key found for hostname: $hostname" -Level Debug
return $null
}
function Set-GitSshKey {
<#
.SYNOPSIS
Configures Git SSH authentication for the current repository.
.DESCRIPTION
Dispatches to platform-specific SSH setup:
- Windows: PuTTY/plink via Set-GitSshKeyPlink
- macOS/Linux: OpenSSH via Set-GitSshKeyOpenSsh
.PARAMETER SshKeyPath
Path to the SSH private key file.
.PARAMETER RepoUrl
The repository URL (used for logging context).
.OUTPUTS
[bool] True if SSH was configured successfully, False otherwise.
#>
param(
[string]$SshKeyPath,
[string]$RepoUrl = ""
)
if (-not (Test-Path $SshKeyPath)) {
Write-Log "SSH key file not found: $SshKeyPath" -Level Error
return $false
}
# Detect key format
$keyContent = Get-Content $SshKeyPath -Raw -ErrorAction SilentlyContinue
$isPuttyKey = $keyContent -match 'PuTTY-User-Key-File'
if ($IsWindows) {
return Set-GitSshKeyPlink -SshKeyPath $SshKeyPath -IsPuttyKey $isPuttyKey
}
else {
return Set-GitSshKeyOpenSsh -SshKeyPath $SshKeyPath -IsPuttyKey $isPuttyKey
}
}
function Set-GitSshKeyPlink {
<#
.SYNOPSIS
Configures Git to use PuTTY/plink for SSH on Windows.
.DESCRIPTION
Validates the key is in PuTTY format, ensures plink.exe and Pageant are available,
and sets the GIT_SSH environment variable to plink.exe.
#>
param(
[string]$SshKeyPath,
[bool]$IsPuttyKey
)
# Check key file permissions (Windows ACL)
$acl = Get-Acl $SshKeyPath
Write-Log "SSH key file permissions: $($acl.Owner)" -Level Debug
if (-not (Test-SshTransportAvailable)) {
Write-Log "Plink not found. Please install PuTTY or add plink.exe to PATH" -Level Error
Show-ErrorDialog -Message "Plink.exe not found!`n`nPlease either:`n1. Install PuTTY (which includes plink)`n2. Add plink.exe to your PATH"
return $false
}
if (-not $IsPuttyKey) {
Write-Log "SSH key is not in PuTTY format" -Level Error
Show-ErrorDialog -Message "The SSH key is not in PuTTY format (.ppk).`n`nPlease convert your key to PuTTY format using PuTTYgen."
return $false
}
# Check if Pageant is running
$pageantProcess = Get-Process pageant -ErrorAction SilentlyContinue
if (-not $pageantProcess) {
Write-Log "Pageant not running. Attempting to start it..." -Level Info
# Try to find and start Pageant
$pageantPath = Get-Command pageant.exe -ErrorAction SilentlyContinue
if ($pageantPath) {
Start-Process pageant.exe
Start-Sleep -Seconds 2
Show-ErrorDialog -Title "Pageant Started" -Message "Pageant has been started.`n`nPlease add your SSH key to Pageant:`n1. Right-click the Pageant icon in system tray`n2. Select 'Add Key'`n3. Browse to: $SshKeyPath`n4. Enter your passphrase`n`nThen click OK to continue."
} else {
Show-ErrorDialog -Message "Pageant not found. Please start Pageant and add your key before continuing."
return $false
}
}
# Configure Git to use plink
$plinkPath = (Get-Command plink.exe).Source
$env:GIT_SSH = $plinkPath
Write-Log "Configured Git to use PuTTY/plink: $plinkPath" -Level Debug
return $true
}
function Set-GitSshKeyOpenSsh {
<#
.SYNOPSIS
Configures Git to use OpenSSH for SSH on macOS/Linux.
.DESCRIPTION
Validates the key is in OpenSSH format (rejects PuTTY .ppk keys),
checks file permissions, and sets GIT_SSH_COMMAND with the explicit key path.
#>
param(
[string]$SshKeyPath,
[bool]$IsPuttyKey
)
# Reject PuTTY keys on Unix
if ($IsPuttyKey) {
Write-Log "SSH key is in PuTTY format (.ppk), which is not supported on macOS/Linux" -Level Error
Write-Log "Convert with: puttygen '$SshKeyPath' -O private-openssh -o <output_path>" -Level Error
return $false
}
if (-not (Test-SshTransportAvailable)) {
Write-Log "OpenSSH client (ssh) not found in PATH" -Level Error
return $false
}
# Check key file permissions (Unix)
$fileItem = Get-Item $SshKeyPath
if ($null -ne $fileItem.UnixMode) {
$mode = $fileItem.UnixMode
# Warn if group or other have any permissions (should be --- for both)
if ($mode -match '.{4}[^\-].{2}$' -or $mode -match '.{7}[^\-]') {
Write-Log "SSH key file has overly permissive permissions: $mode. Run: chmod 600 '$SshKeyPath'" -Level Warning
}
}
# Set GIT_SSH_COMMAND with explicit key
$env:GIT_SSH_COMMAND = "ssh -i `"$SshKeyPath`" -o IdentitiesOnly=yes"
Write-Log "Configured Git to use OpenSSH with key: $SshKeyPath" -Level Debug
return $true
}
function Get-GitTagDates {
param(
[string]$RepoPath
)
Write-Log "Fetching tag dates for repository at: $RepoPath" -Level Debug
if (-not (Test-Path $RepoPath)) {
Write-Log "Repository path does not exist: $RepoPath" -Level Warning
return @{}
}
try {
Push-Location $RepoPath
# Fetch all tags with their dates using git for-each-ref
# This is more efficient than git log for each tag
$gitCommand = "git for-each-ref --sort=creatordate --format='%(refname:short)|%(creatordate:iso8601)' refs/tags"
Write-Log "Executing tag date fetch: $gitCommand" -Level Debug
if ($script:DryRun) {
Write-Log "DRY RUN: Would fetch tag dates from repository" -Level Verbose
Pop-Location
return @{}
}
$output = Invoke-Expression $gitCommand 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Log "Git command failed to fetch tag dates: $output" -Level Warning
Pop-Location
return @{}
}
$tagDates = @{}
$tagCount = 0
foreach ($line in $output) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
$parts = $line -split '\|', 2
if ($parts.Count -eq 2) {
$tagName = $parts[0].Trim()
$dateString = $parts[1].Trim()
try {
$tagDate = [DateTime]::Parse($dateString)
$tagDates[$tagName] = $tagDate
$tagCount++
Write-Log "Parsed tag: $tagName -> $($tagDate.ToString('yyyy-MM-dd HH:mm:ss'))" -Level Debug
}
catch {
Write-Log "Failed to parse date for tag '$tagName': $dateString" -Level Warning
}
}
}
Pop-Location
Write-Log "Successfully fetched dates for $tagCount tags" -Level Info
# Output discovered tags in verbose mode
if ($VerbosePreference -eq 'Continue') {
Write-Log "Discovered tags and dates:" -Level Verbose
$sortedTags = $tagDates.GetEnumerator() | Sort-Object Value
foreach ($tag in $sortedTags) {
Write-Log " $($tag.Key): $($tag.Value.ToString('yyyy-MM-dd HH:mm:ss'))" -Level Verbose
}
}
return $tagDates
}
catch {
Pop-Location -ErrorAction SilentlyContinue
Write-Log "Error fetching tag dates: $_" -Level Warning
return @{}
}
}
function Resolve-TagsByDate {
param(
[array]$Tags,
[hashtable]$TagDates,
[string]$RepositoryUrl,
[string]$Context = "compatibility resolution"
)
if ($TagDates.Count -eq 0) {
Write-Log "No tag dates available for $Context, returning tags in original order" -Level Debug
return $Tags
}
Write-Log "Performing tag temporal sorting for $Context on repository: $RepositoryUrl" -Level Debug
# Separate tags that have dates from those that don't
$tagsWithDates = @()