Publish-Packages.psm1

<#
.Synopsis
   Automatic Publish Tool (APT)
.DESCRIPTION
   Publish or rewrite nugets (feed/local nuget storage)
.EXAMPLE
   Publish-Packages -Path D:\Projects\ActiveOffice.NET\ActiveOffice.NET\devops\output\ -Feed Lomtec.ActiveOffice
 .EXAMPLE
   Publish-Packages -Path D:\Projects\ActiveOffice.NET\ActiveOffice.NET\devops\output\ -ProjectPackages D:\Projects\CISSS\src\packages\ -EnableDebug
.EXAMPLE
   Publish-Packages -Path D:\Projects\ActiveOffice.NET\ActiveOffice.NET\devops\output\ -ProjectPackages D:\Projects\CISSS\src\packages\ -EnableDebug -ResetFeed
 .NOTES
   Author: Imrich Szolik
#>

function Publish-Packages {
    [CmdletBinding()]
    param (
        #Packages path
        [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$false, HelpMessage="Packages path")]
        [string]
        $Path,
        #Package feed name
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$false, HelpMessage="Packages feed name.")]
        [string]
        $Feed,
        #Disable deploy to nuget server, rewrite local packages for debug
        [switch]
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$false, HelpMessage="Disable deploy to nuget server, rewrite local packages for debug!")]
        $EnableDebug,
        #Delete global and locel feed
        [switch]
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$false, HelpMessage="Delete global and locel feed")]
        $ResetFeed,
        #Project packages path
        [string[]]
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$false, HelpMessage="Project packages path.")]
        $ProjectPackages,
        #Publish verbosity
        [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$false, HelpMessage="Verbosity")]
        $Verbosity = "quiet"
    )
    begin {
        if ($null -eq (Get-Command nuget  -ErrorAction SilentlyContinue))  { throw "Please install nuget CLI. [ Download https://www.nuget.org/downloads & add copy nuget.exe to %userprofile%\.dotnet\tools ]" }
        #
        if(-not $EnableDebug.IsPresent){
            if([string]::IsInterned($Feed)){
                throw "Feed is required!"
            }
        }
        #
    }
    process {
        $files = Get-ChildItem -Path $Path -Filter *.nupkg
        if(($files |  Measure-Object).Count -eq 0 ){
            Write-Host "#### APT NUGET deploy into $Feed aborted. Not found any packages ####"
            return
        }

        Write-Host "#### APT NUGET deploy into $Feed ####"
       
        #to local files
        if($EnableDebug.IsPresent){
            #
            $match = [regex] '(?<name>.+)\.(?<major>\d+)\.(?<minor>\d+)\.(?<revison>\d+)\.nupkg'
            $globalNuget =  Join-Path -Path (Join-Path -Path $env:USERPROFILE -ChildPath ".nuget") -ChildPath "packages"
            #
            foreach($file in $files){
                $result = $match.Match($file)
                if($result.Success){
                    #rename .nuget to zip (Expand-Archive powershell 5.0)
                    $zipFile = "$file.FullName.zip" 
                    Copy-Item $file.FullName $zipFile
                    #
                    $name = Split-Path -Path $result.Groups['name'] -Leaf
                    $version = "$($result.Groups['major']).$($result.Groups['minor']).$($result.Groups['revison'])"
                    $globalPackages = Join-Path $globalNuget -ChildPath $name
                    #
                    Write-Host "#### APT NUGET rewrite: $name.$version ####"
                    if( Test-Path -Type  Container $globalPackages){
                        $packageDirectory = Join-Path $globalPackages -ChildPath $version
                        #
                        Remove-Item -Force -Recurse $packageDirectory -ErrorAction SilentlyContinue
                        #
                        if(-not $ResetFeed.IsPresent){
                            Write-Verbose "Rewrite user-global package: $name.$version"
                            Expand-Archive -Force -Path $zipFile -DestinationPath $packageDirectory
                        }
                        else{
                            Write-Verbose "Reset user-global package: $name.$version"
                        }
                    }
                    #
                    if($null -ne $ProjectPackages -and $ProjectPackages.Length -gt 0){
                        #
                        foreach($p in $ProjectPackages){
                            #
                            $localPackage = Join-Path $p -ChildPath "$name.$version"
                            #
                            if( Test-Path -Type  Container $localPackage){
                                #
                                Remove-Item -Force -Recurse $localPackage -ErrorAction SilentlyContinue
                                #
                                if(-not $ResetFeed.IsPresent){
                                    Write-Verbose "Rewrite project package: $name.$version"
                                    Expand-Archive -Force -Path $zipFile -DestinationPath $localPackage 
                                }
                                else{
                                    Write-Verbose "Reset project package: $name.$version"
                                }
                            }
                        }
                    }
                    #
                    Remove-Item $zipFile -Force -ErrorAction SilentlyContinue
                }
            }
        }
        #to nuget server
        else{
            $exists = nuget.exe list -NonInteractive -Source $Feed | Select-Object  @{name='Item';expression={$_.Replace(" ",".")}} | Select-Object -ExpandProperty Item
            $hasPreRelease = ($files | Where-Object -Property Name -Match '(-rc|-alpha|-beta)' | Measure-Object -Line).Lines
            if($hasPreRelease -gt 0){
                $preReleaseExists = nuget.exe list -Prerelease -NonInteractive -Source $Feed | Select-Object  @{name='Item';expression={$_.Replace(" ",".")}} | Select-Object -ExpandProperty Item
                $exists     = $exists + $preReleaseExists
            }
            #
            foreach($file in $files){
                $filename = $file.Name
                $name = $filename.SubString(0,$filename.Length-6)
                #
                if($exists -notcontains $name){
                    Write-Host "#### APT NUGET deploy: $name ####"
                    nuget.exe push -Source $Feed -ApiKey az $file.FullName -Verbosity $Verbosity
                }
                else{
                    Write-Verbose "Found $name, not deployed."
                }
            }
        }
    }
    end {
    }
}
Export-ModuleMember -Function Publish-Packages
# SIG # Begin signature block
# MIIIEwYJKoZIhvcNAQcCoIIIBDCCCAACAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBkyXLwUZvjNF89
# T/NuMo+/t4zEfJt9gX2GWpyN8wiuD6CCBQ8wggULMIIC86ADAgECAgIApTANBgkq
# hkiG9w0BAQsFADCBoDELMAkGA1UEBhMCU0sxETAPBgNVBAgTCFNsb3Zha2lhMRMw
# EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpMb210ZWMuY29tMSswKQYDVQQD
# EyJMb210ZWMuY29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MScwJQYJKoZIhvcN
# AQkBFhhJbXJpY2guU3pvbGlrQGxvbXRlYy5jb20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