Skip to content

Commit

Permalink
Add Show-InvokeGitReturn: fixes Issue #90 (#96)
Browse files Browse the repository at this point in the history
- Added private functions:
  - `Out-GitResult` - Displays `Invoke-Git` returned hashtable
    via Write-Verbose and Write-Debug localized messages.
    Fixes [Issue 90](#90)
  - `Hide-GitToken` - Used to redact the token from the specified 
    git command so that the command can be safely outputted in logs.
- `Publish-WikiContent`
  - Restored to original structure.
- `Invoke-Git`
  - Added `-PassThru` switch to return result hashtable and not throw
    regardless of ExitCode value when used.
  - Throws when ExitCode -ne 0 and `-PassThru` switch not used.
  - Calls `Out-GitResult` when using `-Debug` or `-Verbose`.
  • Loading branch information
phbits authored Aug 5, 2021
1 parent 0201b6f commit 3f90e74
Show file tree
Hide file tree
Showing 11 changed files with 726 additions and 172 deletions.
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Added private functions:
- `Out-GitResult` - Displays `Invoke-Git` returned hashtable
via Write-Verbose and Write-Debug localized messages.
Fixes [Issue 90](https://github.com/dsccommunity/DscResource.DocGenerator/issues/90)
- `Hide-GitToken` - Used to redact the token from the specified
git command so that the command can be safely outputted in logs.

### Changed

- `Publish-WikiContent`
- Restored to original structure.
- `Invoke-Git`
- Added `-PassThru` switch to return result hashtable and not throw
regardless of ExitCode value when used.
- Throws when ExitCode -ne 0 and `-PassThru` switch not used.
- Calls `Out-GitResult` when using `-Debug` or `-Verbose`.

## [0.9.1] - 2021-07-14

### Added
Expand Down
35 changes: 35 additions & 0 deletions source/Private/Hide-GitToken.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<#
.SYNOPSIS
Redacts token from Invoke-Git command.
.DESCRIPTION
Redacts the token from the specified git command so that the command can be safely outputted in logs.
.PARAMETER Command
Command passed to Invoke-Git
.EXAMPLE
Hide-GitToken -Command @( 'remote', 'add', 'origin', 'https://user:[email protected]/Owner/Repo.git' )
Returns a string to be used for logs.
#>

function Hide-GitToken
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory=$true)]
[System.String[]]
$Command
)

[System.String] $returnValue = $Command -join ' '

[System.String] $returnValue = $returnValue -replace "gh(p|o|u|s|r)_([A-Za-z0-9]{1,251})",'**REDACTED-TOKEN**'

[System.String] $returnValue = $returnValue -replace "[0-9a-f]{40}",'**REDACTED-TOKEN**'

return $returnValue
}
92 changes: 92 additions & 0 deletions source/Private/Out-GitResult.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<#
.SYNOPSIS
Shows return object from Invoke-Git.
.DESCRIPTION
When Invoke-Git returns a non-zero exit code, this function shows the result.
.PARAMETER ExitCode
ExitCode returned from running git command.
.PARAMETER StandardOutput
Standard Output returned from running git command.
.PARAMETER StandardError
Standard Error returned from running git command.
.PARAMETER Command
Command arguments passed to git.
.PARAMETER WorkingDirectory
Working Directory used when running git command.
.EXAMPLE
$splatParameters = @{
'ExitCode' = 128
'StandardOutput' = 'StandardOutput-128'
'StandardError' = 'StandardError-128'
'Command' = 'commit --message "some message"'
'WorkingDirectory' = 'C:\some\path\'
}
Out-GitResult @splatParameters
Shows the Invoke-Git result of a commit.
.NOTES
$NULL values are allowed since string formatter `-f` will convert it to an
empty string before Write-Verbose/Write-Debug process `-Message`.
#>

function Out-GitResult
{
[CmdletBinding()]
[OutputType()]
param
(
[Parameter(Mandatory = $true)]
[System.Int32]
$ExitCode,

[Parameter()]
[System.String]
$StandardOutput,

[Parameter()]
[System.String]
$StandardError,

[Parameter(Mandatory = $true)]
[System.String[]]
$Command,

[Parameter(Mandatory = $true)]
[System.String]
$WorkingDirectory
)

switch ($Command[0].ToUpper())
{
'CLONE'
{
if ($ExitCode -eq 128)
{
Write-Verbose -Message $script:localizedData.WikiGitCloneFailMessage
}
}
'COMMIT'
{
if ($ExitCode -eq 1)
{
Write-Verbose -Message $localizedData.NothingToCommitToWiki
}
}
}

Write-Verbose -Message ($script:localizedData.InvokeGitStandardOutputMessage -f $StandardOutput)
Write-Verbose -Message ($script:localizedData.InvokeGitStandardErrorMessage -f $StandardError)
Write-Verbose -Message ($script:localizedData.InvokeGitExitCodeMessage -f $ExitCode)

Write-Debug -Message ($script:localizedData.InvokeGitCommandDebug -f $(Hide-GitToken -Command $Command))
Write-Debug -Message ($script:localizedData.InvokeGitWorkingDirectoryDebug -f $WorkingDirectory)
}
73 changes: 45 additions & 28 deletions source/Public/Invoke-Git.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@
.DESCRIPTION
Invokes a git command with command line arguments using System.Diagnostics.Process.
Throws an error when git ExitCode -ne 0 and -PassThru switch -eq $false (or omitted).
.PARAMETER WorkingDirectory
The path to the git working directory.
.PARAMETER Timeout
Milliseconds to wait for process to exit.
.PARAMETER PassThru
Switch parameter when enabled will return result object of running git command.
.PARAMETER Arguments
The arguments to pass to the Git executable.
Expand All @@ -20,7 +25,7 @@
Invokes the Git executable to clone the specified repository to the working directory.
.EXAMPLE
Invoke-Git -WorkingDirectory 'C:\SomeDirectory' -Arguments @( 'status' ) -TimeOut 10000
Invoke-Git -WorkingDirectory 'C:\SomeDirectory' -Arguments @( 'status' ) -TimeOut 10000 -PassThru
Invokes the Git executable to return the status while having a 10000 millisecond timeout.
#>
Expand All @@ -35,31 +40,25 @@ function Invoke-Git
[System.String]
$WorkingDirectory,

[Parameter(Mandatory = $false)]
[Parameter()]
[System.Int32]
$TimeOut = 120000,

[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru,

[Parameter(ValueFromRemainingArguments = $true)]
[System.String[]]
$Arguments
)

$returnValue = @{
'ExitCode' = -1
'StandardOutput' = ''
'StandardError' = ''
$gitResult = @{
'ExitCode' = -1
'StandardOutput' = ''
'StandardError' = ''
}

$argumentsJoined = $Arguments -join ' '

# Trying to remove any access token from the debug output.
if ($argumentsJoined -match ':[\d|a-f].*@')
{
$argumentsJoined = $argumentsJoined -replace ':[\d|a-f].*@', ':RedactedToken@'
}

Write-Debug -Message ($localizedData.InvokingGitMessage -f $argumentsJoined)

try
{
$process = New-Object -TypeName System.Diagnostics.Process
Expand All @@ -76,13 +75,9 @@ function Invoke-Git
{
if ($process.WaitForExit($TimeOut) -eq $true)
{
$returnValue.ExitCode = $process.ExitCode
$returnValue.StandardOutput = $process.StandardOutput.ReadToEnd()
$returnValue.StandardError = $process.StandardError.ReadToEnd()

# Remove all new lines at end of string.
$returnValue.StandardOutput = $returnValue.StandardOutput -replace '[\r?\n]+$'
$returnValue.StandardError = $returnValue.StandardError -replace '[\r?\n]+$'
$gitResult.ExitCode = $process.ExitCode
$gitResult.StandardOutput = $process.StandardOutput.ReadToEnd()
$gitResult.StandardError = $process.StandardError.ReadToEnd()
}
}
}
Expand All @@ -96,11 +91,33 @@ function Invoke-Git
{
$process.Dispose()
}
}

Write-Debug -Message ('{0}: {1}' -f $MyInvocation.MyCommand.Name, ($localizedData.InvokeGitExitCodeMessage -f $returnValue.ExitCode))
Write-Debug -Message ('{0}: {1}' -f $MyInvocation.MyCommand.Name, ($localizedData.InvokeGitStandardOutputMessage -f $returnValue.StandardOutput))
Write-Debug -Message ('{0}: {1}' -f $MyInvocation.MyCommand.Name, ($localizedData.InvokeGitStandardErrorMessage -f $returnValue.StandardError))
if ($VerbosePreference -ne 'SilentlyContinue' -or `
$DebugPreference -ne 'SilentlyContinue' -or `
$PSBoundParameters['Verbose'] -eq $true -or `
$PSBoundParameters['Debug'] -eq $true)
{
$outGitResultSplat = $gitResult.Clone()

return $returnValue
$outGitResultSplat.Add('Command', $Arguments)
$outGitResultSplat.Add('WorkingDirectory', $WorkingDirectory)

Out-GitResult @outGitResultSplat
}

if ($gitResult.ExitCode -ne 0 -and $PassThru -eq $false)
{
$throwMessage = "$($script:localizedData.InvokeGitCommandDebug -f $(Hide-GitToken -Command $Arguments))`n" +`
"$($script:localizedData.InvokeGitExitCodeMessage -f $gitResult.ExitCode)`n" +`
"$($script:localizedData.InvokeGitStandardOutputMessage -f $gitResult.StandardOutput)`n" +`
"$($script:localizedData.InvokeGitStandardErrorMessage -f $gitResult.StandardError)`n"

throw $throwMessage
}
}

if ($PSBoundParameters['PassThru'] -eq $true)
{
return $gitResult
}
}
81 changes: 29 additions & 52 deletions source/Public/Publish-WikiContent.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -112,78 +112,55 @@ function Publish-WikiContent
{
Write-Verbose -Message $script:localizedData.ConfigGlobalGitMessage

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--global', 'core.autocrlf', $GlobalCoreAutoCrLf )
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--global', 'core.autocrlf', $GlobalCoreAutoCrLf )
}

Write-Verbose -Message ($script:localizedData.CloneWikiGitRepoMessage -f $WikiRepoName)

$gitCloneResult = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'clone', $wikiRepoName, $tempPath )
Invoke-Git -WorkingDirectory $tempPath -Arguments @( 'clone', $wikiRepoName, $tempPath )

if ($gitCloneResult.ExitCode -eq 0)
{
$copyWikiFileParameters = @{
Path = $Path
DestinationPath = $tempPath
Force = $true
}

Copy-WikiFolder @copyWikiFileParameters
$copyWikiFileParameters = @{
Path = $Path
DestinationPath = $tempPath
Force = $true
}

New-WikiSidebar -ModuleName $ModuleName -Path $tempPath
New-WikiFooter -Path $tempPath
Copy-WikiFolder @copyWikiFileParameters

Write-Verbose -Message $script:localizedData.ConfigLocalGitMessage
New-WikiSidebar -ModuleName $ModuleName -Path $tempPath
New-WikiFooter -Path $tempPath

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--local', 'user.email', $GitUserEmail )
Write-Verbose -Message $script:localizedData.ConfigLocalGitMessage

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--local', 'user.name', $GitUserName )
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--local', 'user.email', $GitUserEmail )

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'remote', 'set-url', 'origin', "https://$($GitUserName):$($GitHubAccessToken)@github.com/$OwnerName/$RepositoryName.wiki.git" )
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'config', '--local', 'user.name', $GitUserName )

Write-Verbose -Message $localizedData.AddWikiContentToGitRepoMessage
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'remote', 'set-url', 'origin', "https://$($GitUserName):$($GitHubAccessToken)@github.com/$OwnerName/$RepositoryName.wiki.git" )

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'add', '*' )
Write-Verbose -Message $localizedData.AddWikiContentToGitRepoMessage

Write-Verbose -Message ($localizedData.CommitAndTagRepoChangesMessage -f $ModuleVersion)
Invoke-Git -WorkingDirectory $tempPath -Arguments @( 'add', '*' )

$gitCommitResult = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'commit', '--message', "`"$($localizedData.UpdateWikiCommitMessage -f $ModuleVersion)`"" )
Write-Verbose -Message ($localizedData.CommitAndTagRepoChangesMessage -f $ModuleVersion)

if ($gitCommitResult.ExitCode -eq 0)
{
$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'tag', '--annotate', $ModuleVersion, '--message', $ModuleVersion )
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'commit', '--message', "`"$($localizedData.UpdateWikiCommitMessage -f $ModuleVersion)`"" )

Write-Verbose -Message $localizedData.PushUpdatedRepoMessage
Write-Verbose -Message $localizedData.PushUpdatedRepoMessage

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'push', 'origin' )
Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'tag', '--annotate', $ModuleVersion, '--message', $ModuleVersion )

$null = Invoke-Git -WorkingDirectory $tempPath `
-Arguments @( 'push', 'origin', $ModuleVersion )
Invoke-Git -WorkingDirectory $tempPath -Arguments @( 'push', 'origin' )

Write-Verbose -Message $localizedData.PublishWikiContentCompleteMessage
}
else
{
Write-Warning -Message $localizedData.NothingToCommitToWiki
}
}
else
{
Write-Verbose -Message $script:localizedData.WikiGitCloneFailMessage
Invoke-Git -WorkingDirectory $tempPath -Arguments @( 'push', 'origin', $ModuleVersion )

Write-Debug -Message ($script:localizedData.WikiGitCloneFailMessageDebug -f $wikiRepoName)
Write-Debug -Message ($script:localizedData.InvokeGitStandardOutput -f $gitCloneResult.StandardOutput)
Write-Debug -Message ($script:localizedData.InvokeGitStandardError -f $gitCloneResult.StandardError)
Write-Debug -Message ($script:localizedData.InvokeGitExitCodeMessage -f $gitCloneResult.ExitCode)
}
Write-Verbose -Message $localizedData.PublishWikiContentCompleteMessage
}
finally
{
Expand Down
Loading

0 comments on commit 3f90e74

Please sign in to comment.