Skip to content

Commit

Permalink
Update Invoke-Git to use System.Diagnostics.Process
Browse files Browse the repository at this point in the history
  • Loading branch information
phbits committed Jun 21, 2021
1 parent 0be498b commit e298ac3
Show file tree
Hide file tree
Showing 8 changed files with 524 additions and 88 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Get-MofSchemaObject`
- Refactored to reduce code duplication when adding functions for supporting
composite resources.
- Converted `Invoke-Git` cmdlet to use `System.Diagnostics.Process` for improved error handling.
- `Get-ClassResourceCommentBasedHelp`
- Renamed this function to `Get-CommentBasedHelp` so that it made sense to
use with composite DSC resources.
- Enabled the function to extract the comment block if it is not at the top
of the script file to support composite resources.
- `Invoke-Git`
- Converted to public function.
- Updated to use `System.Diagnostics.Process` for improved error handling.

### Fixed

Expand Down
90 changes: 90 additions & 0 deletions source/Public/Invoke-Git.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<#
.SYNOPSIS
Invokes the git command.
.PARAMETER WorkingDirectory
The path to the git working directory.
.PARAMETER Timeout
Seconds to wait for process to exit.
.PARAMETER Arguments
The arguments to pass to the Git executable.
.EXAMPLE
Invoke-Git clone https://github.com/X-Guardian/xActiveDirectory.wiki.git --quiet
Invokes the Git executable to clone the specified repository to the current working directory.
#>

function Invoke-Git
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$WorkingDirectory,

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

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

$returnValue = @{
'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
$process.StartInfo.Arguments = $Arguments
$process.StartInfo.CreateNoWindow = $true
$process.StartInfo.FileName = 'git.exe'
$process.StartInfo.RedirectStandardOutput = $true
$process.StartInfo.RedirectStandardError = $true
$process.StartInfo.UseShellExecute = $false
$process.StartInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$process.StartInfo.WorkingDirectory = $WorkingDirectory

if ($process.Start() -eq $true)
{
if ($process.WaitForExit($TimeOut) -eq $true)
{
$returnValue.ExitCode = $process.ExitCode
$returnValue.StandardOutput = $process.StandardOutput.ReadToEnd()
$returnValue.StandardError = $process.StandardError.ReadToEnd()
}
}
}
catch
{
throw $_
}
finally
{
if ($process)
{
$process.Dispose()
}
}

return $returnValue
}
97 changes: 57 additions & 40 deletions source/Public/Publish-WikiContent.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -99,68 +99,85 @@ function Publish-WikiContent

try
{
Write-Verbose -Message $script:localizedData.ConfigGlobalGitMessage

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

$wikiRepoName = "https://github.com/$OwnerName/$RepositoryName.wiki.git"

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

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

$copyWikiFileParameters = @{
Path = $Path
DestinationPath = $tempPath
Force = $true
}
if ($gitCloneResult.ExitCode -eq 0)
{
Write-Verbose -Message $script:localizedData.ConfigGlobalGitMessage

Copy-WikiFolder @copyWikiFileParameters
if ($PSBoundParameters.ContainsKey('GlobalCoreAutoCrLf'))
{
$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'config', '--local', 'core.autocrlf', $GlobalCoreAutoCrLf )
}

New-WikiSidebar -ModuleName $ModuleName -Path $tempPath
New-WikiFooter -Path $tempPath
$copyWikiFileParameters = @{
Path = $Path
DestinationPath = $tempPath
Force = $true
}

Write-Verbose -Message $script:localizedData.ConfigLocalGitMessage
Copy-WikiFolder @copyWikiFileParameters

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

Write-Verbose -Message $localizedData.AddWikiContentToGitRepoMessage
Set-Location -Path $tempPath

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

Write-Verbose -Message ($localizedData.CommitAndTagRepoChangesMessage -f $ModuleVersion)
$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'config', '--local', 'user.email', $GitUserEmail )

$invokeGitResult = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'commit', '--message', "`"$($localizedData.UpdateWikiCommitMessage -f $ModuleVersion)`"", '--quiet' )
$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'config', '--local', 'user.name', $GitUserName )

if ($invokeGitResult -eq 0)
{
$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'tag', '--annotate', $ModuleVersion, '--message', $ModuleVersion )
-Arguments @( 'remote', 'set-url', 'origin', "https://$($GitUserName):$($GitHubAccessToken)@github.com/$OwnerName/$RepositoryName.wiki.git" )

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

$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'push', 'origin', '--quiet' )
$null = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'push', 'origin', $ModuleVersion, '--quiet' )
-Arguments @( 'add', '*' )

Write-Verbose -Message ($localizedData.CommitAndTagRepoChangesMessage -f $ModuleVersion)

$gitCommitResult = Invoke-Git -WorkingDirectory $tempPath.FullName `
-Arguments @( 'commit', '--message', "`"$($localizedData.UpdateWikiCommitMessage -f $ModuleVersion)`"", '--quiet' )

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

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

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

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

Write-Verbose -Message $localizedData.PublishWikiContentCompleteMessage
}
else
{
Write-Warning -Message $localizedData.NothingToCommitToWiki
}
}
else
{
Write-Warning -Message $localizedData.NothingToCommitToWiki
Write-Verbose -Message $script:localizedData.WikiGitCloneFailMessage

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)
}
}
finally
Expand Down
70 changes: 36 additions & 34 deletions source/en-US/DscResource.DocGenerator.strings.psd1
Original file line number Diff line number Diff line change
@@ -1,41 +1,43 @@
# English strings
ConvertFrom-StringData @'
FoundMofFilesMessage = Found {0} MOF files in path '{1}'.
GenerateHelpDocumentMessage = Generating help document for '{0}'.
OutputHelpDocumentMessage = Outputting help document to '{0}'.
GenerateWikiPageMessage = Generating wiki page for '{0}'.
OutputWikiPageMessage = Outputting wiki page to '{0}'.
NoDescriptionFileFoundWarning = No README.md description file found for '{0}', skipping.
MultipleDescriptionFileFoundWarning = {1} README.md description files found for '{0}', skipping.
NoExampleFileFoundWarning = No Example files found.
CreateTempDirMessage = Creating a temporary working directory.
ConfigGlobalGitMessage = Configuring global Git settings.
ConfigLocalGitMessage = Configuring local Git settings.
CloneWikiGitRepoMessage = Cloning the Wiki Git Repository '{0}'.
AddWikiContentToGitRepoMessage = Adding the Wiki Content to the Git Repository.
CommitAndTagRepoChangesMessage = Committing the changes to the Repository and adding build tag '{0}'.
PushUpdatedRepoMessage = Pushing the updated Repository to the Git Wiki.
PublishWikiContentCompleteMessage = Publish Wiki Content complete.
UpdateWikiCommitMessage = Updating Wiki with the content for module version '{0}'.
NewTempFolderCreationError = Unable to create a temporary working folder in '{0}'.
InvokingGitMessage = Invoking Git '{0}'.
GenerateWikiSidebarMessage = Generating Wiki Sidebar '{0}'.
GenerateWikiFooterMessage = Generating Wiki Footer '{0}'.
CopyWikiFoldersMessage = Copying Wiki files from '{0}'.
CopyFileMessage = Copying file '{0}' to the Wiki.
AddFileToSideBar = Adding file '{0}' to the Wiki Sidebar.
NothingToCommitToWiki = There are no changes to the documentation to commit and push to the Wiki.
FoundClassBasedMessage = Found {0} class-based resources in the built module '{1}'.
FoundClassResourcePropertyMessage = Found property '{0}' in the resource '{1}'.
CommentBasedHelpMessage = Reading comment-based help from source file '{0}'.
FoundResourceExamplesMessage = Found {0} examples.
IgnoreAstParseErrorMessage = Errors was found during parsing of comment-based help. These errors were ignored: {0}
FoundMofFilesMessage = Found {0} MOF files in path '{1}'.
GenerateHelpDocumentMessage = Generating help document for '{0}'.
OutputHelpDocumentMessage = Outputting help document to '{0}'.
GenerateWikiPageMessage = Generating wiki page for '{0}'.
OutputWikiPageMessage = Outputting wiki page to '{0}'.
NoDescriptionFileFoundWarning = No README.md description file found for '{0}', skipping.
MultipleDescriptionFileFoundWarning = {1} README.md description files found for '{0}', skipping.
NoExampleFileFoundWarning = No Example files found.
CreateTempDirMessage = Creating a temporary working directory.
ConfigGlobalGitMessage = Configuring global Git settings.
ConfigLocalGitMessage = Configuring local Git settings.
CloneWikiGitRepoMessage = Cloning the Wiki Git Repository '{0}'.
AddWikiContentToGitRepoMessage = Adding the Wiki Content to the Git Repository.
CommitAndTagRepoChangesMessage = Committing the changes to the Repository and adding build tag '{0}'.
PushUpdatedRepoMessage = Pushing the updated Repository to the Git Wiki.
PublishWikiContentCompleteMessage = Publish Wiki Content complete.
UpdateWikiCommitMessage = Updating Wiki with the content for module version '{0}'.
NewTempFolderCreationError = Unable to create a temporary working folder in '{0}'.
InvokingGitMessage = Invoking Git '{0}'.
GenerateWikiSidebarMessage = Generating Wiki Sidebar '{0}'.
GenerateWikiFooterMessage = Generating Wiki Footer '{0}'.
CopyWikiFoldersMessage = Copying Wiki files from '{0}'.
CopyFileMessage = Copying file '{0}' to the Wiki.
AddFileToSideBar = Adding file '{0}' to the Wiki Sidebar.
NothingToCommitToWiki = There are no changes to the documentation to commit and push to the Wiki.
FoundClassBasedMessage = Found {0} class-based resources in the built module '{1}'.
FoundClassResourcePropertyMessage = Found property '{0}' in the resource '{1}'.
ClassBasedCommentBasedHelpMessage = Reading comment-based help from source file '{0}'.
FoundResourceExamplesMessage = Found {0} examples.
IgnoreAstParseErrorMessage = Errors was found during parsing of comment-based help. These errors were ignored: {0}
WikiGitCloneFailMessage = Failed to clone wiki. Ensure the feature is enabled and the first page has been created.
WikiGitCloneFailMessageDebug = Wiki clone URL '{0}'
InvokeGitStandardOutputMessage = git standard output: '{0}'
InvokeGitStandardErrorMessage = git standard error: '{0}'
InvokeGitExitCodeMessage = git exit code: '{0}'
FoundCompositeFilesMessage = Found {0} composite files in path '{1}'.
UnexpectedInvokeGitReturnCode = Unexpected return code '{0}'. Run with -Debug to see details.
InvokeGitStandardOutputReturn = Git Standard Output: '{0}'
InvokeGitStandardErrorReturn = Git Standard Error: '{0}'
CommentBasedHelpBlockNotFound = A comment-based help block in source file '{0}' could not be found.
CommentBasedHelpBlockNotAtTopMessage = A comment-based help block in source file '{0}' was found, but is not at the top of the file.
CommentBasedHelpBlockNotAtTopMessage = A comment-based help block in source file '{0}' was found, but is not at the top ofthe file.
CompositeResourceMultiConfigError = {1} composite resources were found in the source file '{0}'. This is not currently supported. Please separate these into different scripts.
MacOSNotSupportedError = NotImplemented: MacOS is not supported for this operation because DSC can not be installed onto it. Please use an OS that DSC can be installed onto.
'@
8 changes: 7 additions & 1 deletion source/tasks/Publish_GitHub_Wiki_Content.build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,13 @@ task Publish_GitHub_Wiki_Content {
}
}

$remoteURL = git remote get-url origin
$gitRemoteResult = Invoke-Git -WorkingDirectory $BuildRoot `
-Arguments @( 'remote', 'get-url', 'origin' )

if ($gitRemoteResult.ExitCode -eq 0)
{
$remoteURL = $gitRemoteResult.StandardOutput
}

# Parse the URL for owner name and repository name.
if ($remoteURL -match 'github')
Expand Down
Loading

0 comments on commit e298ac3

Please sign in to comment.