Skip to content
This repository was archived by the owner on Jun 13, 2024. It is now read-only.

Refactor Nuget operations out of Publish-PSArtifactUtility function #444

Merged
merged 8 commits into from
Mar 22, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions src/PowerShellGet/private/functions/New-NugetPackage.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
function New-NugetPackage {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$NuspecPath,

[Parameter(Mandatory = $true)]
[string]$NugetPackageRoot,

[Parameter()]
[string]$OutputPath = $NugetPackageRoot,

[Parameter(Mandatory = $true, ParameterSetName = "UseNuget")]
[string]$NugetExePath,

[Parameter(ParameterSetName = "UseDotnetCli")]
[switch]$UseDotnetCli

)
Set-StrictMode -Off

if (-Not(Test-Path -Path $NuspecPath -PathType Leaf)) {
throw "A nuspec file does not exist at $NuspecPath, provide valid path to a .nuspec"
}

if (-Not(Test-Path -Path $NugetPackageRoot)) {
throw "NugetPackageRoot $NugetPackageRoot does not exist"
}


if ($PSCmdlet.ParameterSetName -eq "UseNuget") {
if (-Not(Test-Path -Path $NuGetExePath)) {
throw "Nuget.exe does not exist at $NugetExePath, provide a valid path to nuget.exe"
}

$ArgumentList = @("pack")
$ArgumentList += "`"$NuspecPath`""
$ArgumentList += "-outputdirectory `"$OutputPath`""

$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = $NugetExePath
$processStartInfo.RedirectStandardError = $true
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$processStartInfo.Arguments = $ArgumentList

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processStartInfo
$process.Start() | Out-Null
$process.WaitForExit()

if (-Not ($process.ExitCode -eq 0 )) {
$stdErr = $process.StandardError.ReadToEnd()
throw "nuget.exe failed to pack $stdErr"
}
}

if ($PSCmdlet.ParameterSetName -eq "UseDotnetCli") {
#perform dotnet pack using a temporary project file.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@edyoung @Benny1007 Extract this into it's own function. Replace the comment with a function name. Use a PowerShell approved verb.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what are the benefits of abstracting this further. Don't want to get into similar situation of Register-PSRepository and Resolve-Location, Get-LocationString, Get-EscapedString etc... This function has a single responsibility - to create a nuget package, having all the code at hand in one file to perform that was the reason for abstracting it in the first place. Personally not a fan of splitting out to multiple functions for the sake of it.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not for the sake of it. It's for building reusable abstractions. Why is it out fault that the Process API is not designed for consuming a quick task's exit code and standard output and error streams? We just wrap that and clearly express we care about those 3 things. See my comment here which when I replied by email 2 days ago somehow got stuck at the bottom of the review: https://github.com/PowerShell/PowerShellGet/pull/444#issuecomment-477119239

$dotnetCliPath = (Get-Command -Name "dotnet").Source

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Create Verbose Preference to log which Get-Command is retrieved. This would be useful in submitting bug reports. It could even verbose the version of the exe found.

$tempPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.Guid]::NewGuid()).Guid
New-Item -ItemType Directory -Path $tempPath -Force | Out-Null

$CsprojContent = @"
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>NotUsed</AssemblyName>
<Description>Temp project used for creating nupkg file.</Description>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>true</IsPackable>
</PropertyGroup>
</Project>
"@
$projectFile = New-Item -ItemType File -Path $tempPath -Name "Temp.csproj"
Set-Content -Value $CsprojContent -Path $projectFile

#execution

$ArgumentList = @("pack")
$ArgumentList += "`"$projectFile`""
$ArgumentList += "/p:NuspecFile=`"$NuspecPath`""
$ArgumentList += "--output `"$OutputPath`""

$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = $dotnetCliPath
$processStartInfo.RedirectStandardError = $true
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$processStartInfo.Arguments = $ArgumentList

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processStartInfo
$process.Start() | Out-Null
$process.WaitForExit()

if (Test-Path -Path $tempPath) {
Remove-Item -Path $tempPath -Force -Recurse
}

if (-Not ($process.ExitCode -eq 0 )) {
$stdOut = $process.StandardOutput.ReadToEnd()
throw "dotnet cli failed to pack $stdOut"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still does not allow inspecting the temporary created project file. This makes it a bit magical when trying to understand what got uploaded to a repository as part of the publish process.

@Benny1007 @edyoung

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overwrite the outputpath variable and then you would know where the artifact resides.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry, was missing a question mark off the last comment! would need to pass this through from the public function.

}

}

$stdOut = $process.StandardOutput.ReadToEnd()
$stdOut -match "Successfully created package '(.*.nupkg)'" | Out-Null
$nupkgFullFile = $matches[1]

$stdOut = $process.StandardOutput.ReadToEnd()

Write-Verbose -Message $stdOut
Write-Output $nupkgFullFile
}
129 changes: 129 additions & 0 deletions src/PowerShellGet/private/functions/New-NuspecFile.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
function New-NuspecFile {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$OutputPath,

[Parameter(Mandatory = $true)]
[string]$Id,

[Parameter(Mandatory = $true)]
[version]$Version,

[Parameter(Mandatory = $true)]
[string]$Description,

[Parameter(Mandatory = $true)]
[string[]]$Authors,

[Parameter()]
[string[]]$Owners,

[Parameter()]
[string]$ReleaseNotes,

[Parameter()]
[bool]$RequireLicenseAcceptance,

[Parameter()]
[string]$Copyright,

[Parameter()]
[string[]]$Tags,

[Parameter()]
[string]$LicenseUrl,

[Parameter()]
[string]$ProjectUrl,

[Parameter()]
[string]$IconUrl,

[Parameter()]
[PSObject[]]$Dependencies,

[Parameter()]
[PSObject[]]$Files

)
Set-StrictMode -Off

$nameSpaceUri = "http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"
[xml]$xml = New-Object System.Xml.XmlDocument

$xmlDeclaration = $xml.CreateXmlDeclaration("1.0", "utf-8", $null)
$xml.AppendChild($xmlDeclaration) | Out-Null

#create top-level elements
$packageElement = $xml.CreateElement("package", $nameSpaceUri)
$metaDataElement = $xml.CreateElement("metadata", $nameSpaceUri)

#truncate tags if they exceed nuspec specifications for size.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're destructively messing with parameters, create a Process block attached to the params block.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain this further?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In PowerShell v1, the only way to validate parameters was in a Process block and to throw an exception. In PowerShell v2, you can use ValidateScript.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this comment was in reference to the truncation of tags?, which is now NOT happening but I seem to have left the comment in the code.

$Tags = $Tags -Join " "

if ($Tags.Length -gt 4000) {
Write-Warning -Message "Tag list exceeded 4000 characters and may not be accepted by some Nuget feeds."
}

$metaDataElementsHash = [ordered]@{
id = $Id
version = $Version
description = $Description
authors = $Authors -Join ","
owners = $Owners -Join ","
releaseNotes = $ReleaseNotes
requireLicenseAcceptance = $RequireLicenseAcceptance.ToString().ToLower()
copyright = $Copyright
tags = $Tags
}

if ($LicenseUrl) { $metaDataElementsHash.Add("licenseUrl", $LicenseUrl) }
if ($ProjectUrl) { $metaDataElementsHash.Add("projectUrl", $ProjectUrl) }
if ($IconUrl) { $metaDataElementsHash.Add("iconUrl", $IconUrl) }

foreach ($key in $metaDataElementsHash.Keys) {
$element = $xml.CreateElement($key, $nameSpaceUri)
$elementInnerText = $metaDataElementsHash.item($key)
$element.InnerText = $elementInnerText

$metaDataElement.AppendChild($element) | Out-Null
}


if ($Dependencies) {
$dependenciesElement = $xml.CreateElement("dependencies", $nameSpaceUri)

foreach ($dependency in $Dependencies) {
$element = $xml.CreateElement("dependency", $nameSpaceUri)
$element.SetAttribute("id", $dependency.id)
if ($dependency.version) { $element.SetAttribute("version", $dependency.version) }

$dependenciesElement.AppendChild($element) | Out-Null
}
$metaDataElement.AppendChild($dependenciesElement) | Out-Null
}

if ($Files) {
$filesElement = $xml.CreateElement("files", $nameSpaceUri)

foreach ($file in $Files) {
$element = $xml.CreateElement("file", $nameSpaceUri)
$element.SetAttribute("src", $file.src)
if ($file.target) { $element.SetAttribute("target", $file.target) }
if ($file.exclude) { $element.SetAttribute("exclude", $file.exclude) }

$filesElement.AppendChild($element) | Out-Null
}
}

$packageElement.AppendChild($metaDataElement) | Out-Null
if ($filesElement) { $packageElement.AppendChild($filesElement) | Out-Null }

$xml.AppendChild($packageElement) | Out-Null

$nuspecFullName = Join-Path -Path $OutputPath -ChildPath "$Id.nuspec"
$xml.save($nuspecFullName)

Write-Output $nuspecFullName
}
80 changes: 80 additions & 0 deletions src/PowerShellGet/private/functions/Publish-NugetPackage.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
function Publish-NugetPackage {
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true)]
[string]$NupkgPath,

[Parameter(Mandatory = $true)]
[string]$Destination,

[Parameter(Mandatory = $true)]
[string]$NugetApiKey,

[Parameter(ParameterSetName = "UseNuget")]
[string]$NugetExePath,

[Parameter(ParameterSetName = "UseDotnetCli")]
[switch]$UseDotnetCli
)
Set-StrictMode -Off

$Destination = $Destination.TrimEnd("\")

if ($PSCmdlet.ParameterSetName -eq "UseNuget") {
$ArgumentList = @('push')
$ArgumentList += "`"$NupkgPath`""
$ArgumentList += @('-source', "`"$Destination`"")
$ArgumentList += @('-apikey', "`"$NugetApiKey`"")
$ArgumentList += '-NonInteractive'

#use processstartinfo and process objects here as it allows stderr redirection in memory rather than file.
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = $NugetExePath
$processStartInfo.RedirectStandardError = $true
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$processStartInfo.Arguments = $ArgumentList

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processStartInfo
$process.Start() | Out-Null
$process.WaitForExit()

if (-Not ($process.ExitCode -eq 0 )) {
$stdErr = $process.StandardError.ReadToEnd()
throw "nuget.exe failed to push $stdErr"
}
}

if ($PSCmdlet.ParameterSetName -eq "UseDotnetCli") {
#perform dotnet pack using a temporary project file.
$dotnetCliPath = (Get-Command -Name "dotnet").Source

$ArgumentList = @('nuget')
$ArgumentList += 'push'
$ArgumentList += "`"$NupkgPath`""
$ArgumentList += @('--source', "`"$Destination`"")
$ArgumentList += @('--api-key', "`"$NugetApiKey`"")

#use processstartinfo and process objects here as it allows stdout redirection in memory rather than file.
$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo
$processStartInfo.FileName = $dotnetCliPath
$processStartInfo.RedirectStandardError = $true
$processStartInfo.RedirectStandardOutput = $true
$processStartInfo.UseShellExecute = $false
$processStartInfo.Arguments = $ArgumentList

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processStartInfo
$process.Start() | Out-Null
$process.WaitForExit()

if (-Not ($process.ExitCode -eq 0)) {
$stdOut = $process.StandardOutput.ReadToEnd()
throw "dotnet cli failed to nuget push $stdOut"
}
}

$stdOut = $process.StandardOutput.ReadToEnd()
Write-Verbose -Message $stdOut
}
Loading