forked from StartAutomating/ugit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOut-Git.ps1
280 lines (243 loc) · 12.1 KB
/
Out-Git.ps1
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
function Out-Git
{
<#
.Synopsis
Outputs Git to PowerShell
.Description
Outputs Git as PowerShell Objects.
Git Output can be provided by any number of extensions to Out-Git.
Extensions use two attributes to indicate if they should be run:
~~~PowerShell
[Management.Automation.Cmdlet("Out","Git")] # This signals that this is an extension for Out-Git
[ValidatePattern("RegularExpression")] # This is run on $GitCommand to determine if the extension should run.
~~~
.LINK
Invoke-Git
.Example
# Log entries are returned as objects, with properties and methods.
git log -n 1 | Get-Member
.Example
# Status entries are converted into objects.
git status
.Example
# Display untracked files.
git status | Select-Object -ExpandProperty Untracked
.Example
# Display the list of branches, as objects.
git branch
.NOTES
Out-Git will generate two events upon completion. They will have the source identifiers of "Out-Git" and "Out-Git $GitArgument"
#>
[CmdletBinding(PositionalBinding=$false)]
param(
# One or more output lines from Git.
[Parameter(ValueFromPipeline)]
[Alias('GitOutputLines')]
[string[]]
$GitOutputLine,
# The arguments that were passed to git.
[string[]]
$GitArgument,
# The root of the current git repository.
[string]
$GitRoot,
# The timestamp. This can be used for tracking. Defaults to [DateTime]::Now
[DateTime]
$TimeStamp = [DateTime]::Now
)
begin {
# First, we need to determine what the combined git command was.
# Luckily, this is easy: just combine "git" with the list of git argument
$gitCommand = @('git') + $GitArgument[0..$GitArgument.Length] -join ' '
# Now we need to see if we have have a cached for extension mapping.
if (-not $script:GitExtensionMappingCache) {
$script:GitExtensionMappingCache = @{} # If we don't, create one.
}
if (-not $script:GitExtensionMappingCache[$gitCommand]) { # If we don't have a cached extension list
# let's initialize an empty variable to keep any extension validation errors.
$extensionValidationErrors = $null
# Then we create a hashtable containing the parameters to Get-UGitExtension:
$uGitExtensionParams = @{
CommandName = $MyInvocation.MyCommand # We want extensions for this command
ValidateInput = $gitCommand # that are valid, given $GitCommand.
}
# If -Verbose is -Debug is set, we will want to populate extensionValidationErrors
if ($VerbosePreference -ne 'silentlyContinue' -or
$DebugPreference -ne 'silentlyContinue') {
$uGitExtensionParams.ErrorAction = 'SilentlyContinue' # We do not want to display errors
$uGitExtensionParams.ErrorVariable = 'extensionValidationErrors' # we want to redirect them into $extensionValidationErrors.
$uGitExtensionParams.AllValid = $true # and we want to see that all of the validation attributes are correct.
} else {
$uGitExtensionParams.ErrorAction = 'Ignore'
}
# Now we get a list of git output extensions and store it in the cache.
$script:GitExtensionMappingCache[$gitCommand] = $gitOutputExtensions = @(Get-UGitExtension @uGitExtensionParams)
# If any of them had errors, and we want to see the -Verbose channel
if ($extensionValidationErrors -and $VerbosePreference -ne 'silentlyContinue') {
foreach ($validationError in $extensionValidationErrors) {
Write-Verbose "$validationError" # write the validation errors to verbose.
# It should be noted that there will almost always be validation errors,
# since most extensions will not apply to a given $GitCommand
}
}
} else {
# If there was already an extension cached, we can skip the previous steps and just reuse the cached extensions.
$gitOutputExtensions = $script:GitExtensionMappingCache[$gitCommand]
}
# Next we want to create a collection of SteppablePipelines.
# These allow us to run the begin/process/end blocks of each Extension.
$steppablePipelines =
[Collections.ArrayList]::new(@(if ($gitOutputExtensions) {
foreach ($ext in $gitOutputExtensions) {
$scriptCmd = {& $ext}
$scriptCmd.GetSteppablePipeline()
}
}))
# Next we need to start any steppable pipelines.
# Each extension can break, continue in it's begin block to indicate it should not be processed.
$spi = 0
$spiToRemove = @()
$beginIsRunning = $false
# Walk over each steppable pipeline.
:NextExtension foreach ($steppable in $steppablePipelines) {
if ($beginIsRunning) { # If beginIsRunning is set, then the last steppable pipeline continued
$spiToRemove+=$steppablePipelines[$spi] # so mark it to be removed.
}
$beginIsRunning = $true # Note that beginIsRunning=$false,
try {
$steppable.Begin($true) # then try to run begin
} catch {
$PSCmdlet.WriteError($_) # Write any exceptions as errors
}
$beginIsRunning = $false # Note that beginIsRunning=$false
$spi++ # and increment the index.
}
# If this is still true, an extenion used 'break', which signals to stop processing of it any subsequent pipelines.
if ($beginIsRunning) {
$spiToRemove += @(for (; $spi -lt $steppablePipelines.Count; $spi++) {
$steppablePipelines[$spi]
})
}
# Remove all of the steppable pipelines that signaled they no longer wish to run.
foreach ($tr in $spiToRemove) {
$steppablePipelines.Remove($tr)
}
$AllGitOutput = [Collections.Queue]::new()
$ProcessedOutput = [Collections.Queue]::new()
}
process {
# Walk over each output.
foreach ($out in $GitOutputLine) {
# If the out was a literal string of 'System.Management.Automation.RemoteException',
if ("$out" -eq "System.Management.Automation.RemoteException") {
# ignore it and continue (these things happen with some exes from time to time).
continue
}
$AllGitOutput.Enqueue($out)
# Wrap the output in a PSObject
$gitOut = [PSObject]::new($out)
# Next, clear it's typenames and determine an automatic typename.
# The first typename is the complete set of arguments ( separated by periods )
# Followed by each smaller set of arguments, separated by periods
# Followed by a PSTypeName of 'git'
# Thus, for example, git clone $repo
# Would have the typenames of :"git.clone.$repo.output", "git.clone.output","git.output"
$gitOut.pstypenames.clear()
for ($n = $GitArgument.Length - 1 ; $n -ge 0; $n--) {
$gitOut.pstypenames.add(@('git') + $GitArgument[0..$n] + @('output') -join '.')
}
$gitOut.pstypenames.add('git.output')
# All gitOutput should attach the original output line, as well as the command that produced that line.
$gitOut.psobject.properties.add([PSNoteProperty]::new('GitOutput',"$out"))
$gitOut.psobject.properties.add([PSNoteProperty]::new('GitCommand',
$(@('git') + $GitArgument) -join ' ')
)
# If the output started with "error" or "fatal"
if ("$out" -match "^(?:error|fatal):") {
$exception = [Exception]::new($("$out" -replace '^(?:error|fatal):')) # Create an exception
$PSCmdlet.WriteError( # and write an error using $psCmdlet (this simplifies the displayed callstack).
[Management.Automation.ErrorRecord]::new($exception,"$GitCommand", 'NotSpecified',$gitOut)
)
# If there was an error, cancel all steppable pipelines (thus stopping any extensions)
$steppablePipelines = @()
continue # then move onto the next output.
} else {
Write-Verbose "$out"
}
if ("$out" -match '^hint:') {
Write-Warning ("$out" -replace '^hint:')
continue
}
if (-not $steppablePipelines) {
# If we do not have steppable pipelines, output directly
$gitOut
}
else {
# If we have steppable pipelines, then we have to do a similar operation as we did for begin.
$spi = 0
$spiToRemove = @()
$processIsRunning = $false
# We have to walk thru each steppable pipeline,
:NextExtension foreach ($steppable in $steppablePipelines) {
if ($processIsRunning) { # if $ProcessIsRunning, the pipeline was skipped with continue.
$spiToRemove+=$steppablePipelines[$spi] # and we should add it to the list of pipelines to remove
}
$processIsRunning = $true # Set $processIsRunning,
try {
$steppable.Process($gitOut) | & {
process {
$ProcessedOutput.Enqueue($_)
$_
}
} # attempt to run process, using the $gitOut object.
} catch {
$PSCmdlet.WriteError($_) # (catch any exceptions and write them as errors).
}
$processIsRunning = $false # Set $processIsRunning to $false for the next step.
}
if ($processIsRunning) { # If $ProcessIsRunning was true, the extension used break
# which should signal cancellation of all subsequent extensions.
$spiToRemove += @(for (; $spi -lt $steppablePipelines.Count; $spi++) {
$steppablePipelines[$spi]
})
$gitOut # We will also output the gitOut object in this case.
}
# Remove any steppable pipelines we need to remove.
foreach ($tr in $spiToRemove) { $steppablePipelines.Remove($tr) }
}
}
}
end {
$global:lastGitOutput = $AllGitOutput.ToArray()
# End remaining steppable pipelines need to end.
# Ending does not support the cancellation of other extensions.
foreach ($steppable in $steppablePipelines) {
try {
$steppable.End() | & { process {
$ProcessedOutput.Enqueue($_)
$_
}}
} catch {
Write-Error -ErrorRecord $_
}
}
if (-not $global:gitHistory -or
$global:gitHistory -isnot [Collections.IDictionary]) {
$global:gitHistory = [Ordered]@{}
}
$messageData = [Ordered]@{
OutputObject = $ProcessedOutput.ToArray()
GitOutputLine = $AllGitOutput.ToArray()
GitArgument = $GitArgument
GitCommand = @(@("git") + $GitArgument) -join ' '
GitRoot = $GitRoot
TimeStamp = $TimeStamp
}
$eventSourceIds = @("Out-Git","Out-Git $gitArgument")
$null =
foreach ($sourceIdentifier in $eventSourceIds) {
New-Event -SourceIdentifier $sourceIdentifier -MessageData $messageData
}
$global:gitHistory["$($MyInvocation.HistoryId)::$GitRoot::$GitArgument"] = $messageData
}
}