diff --git a/Build/psake.ps1 b/Build/psake.ps1 index 1ea1a9f..707331c 100644 --- a/Build/psake.ps1 +++ b/Build/psake.ps1 @@ -60,12 +60,12 @@ Task Build -Depends Test { $lines # Load the module, read the exported functions, update the psd1 FunctionsToExport - Set-ModuleFunctions + Set-ModuleFunction # Bump the module version if we didn't already Try { - [version]$GalleryVersion = Get-NextPSGalleryVersion -Name $env:BHProjectName -ErrorAction Stop + [version]$GalleryVersion = Get-NextNugetPackageVersion -Name $env:BHProjectName -ErrorAction Stop [version]$GithubVersion = Get-MetaData -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -ErrorAction Stop if($GalleryVersion -ge $GithubVersion) { Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value $GalleryVersion -ErrorAction stop @@ -86,4 +86,4 @@ Task Deploy -Depends Build { Recurse = $false # We keep psdeploy artifacts, avoid deploying those : ) } Invoke-PSDeploy @Verbose @Params -} \ No newline at end of file +} diff --git a/BuildHelpers/BuildHelpers.psd1 b/BuildHelpers/BuildHelpers.psd1 index 38db851..17484d8 100644 --- a/BuildHelpers/BuildHelpers.psd1 +++ b/BuildHelpers/BuildHelpers.psd1 @@ -4,7 +4,7 @@ RootModule = 'BuildHelpers.psm1' # Version number of this module. -ModuleVersion = '1.1.0' +ModuleVersion = '2.0.0' # ID used to uniquely identify this module GUID = 'ec079170-28b7-40b4-aaae-f8ebf76850ab' @@ -67,7 +67,7 @@ CmdletsToExport = '*' VariablesToExport = '*' # Aliases to export from this module -AliasesToExport = 'Set-BuildVariable' +AliasesToExport = @('Set-BuildVariable', 'Get-NextPSGalleryVersion') # DSC resources to export from this module # DscResourcesToExport = @() @@ -96,7 +96,7 @@ PrivateData = @{ # IconUri = '' # ReleaseNotes of this module - # ReleaseNotes = '' + ReleaseNotes = "This release will load an external copy of Joel Bennett's Configuration module if we find one on your system, and it is newer than the embedded Configuration module" } # End of PSData hashtable diff --git a/BuildHelpers/BuildHelpers.psm1 b/BuildHelpers/BuildHelpers.psm1 index e4bbd03..d70cdf0 100755 --- a/BuildHelpers/BuildHelpers.psm1 +++ b/BuildHelpers/BuildHelpers.psm1 @@ -1,29 +1,64 @@ #Get public and private function definition files. - $Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue ) - $Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue ) - $ModuleRoot = $PSScriptRoot +$Public = @( Get-ChildItem -Path $PSScriptRoot\Public\*.ps1 -ErrorAction SilentlyContinue ) +$Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue ) +# $ModuleRoot = $PSScriptRoot #Dot source the files - Foreach($import in @($Public + $Private)) +Foreach($import in @($Public + $Private)) +{ + Try { - Try - { - . $import.fullname - } - Catch - { - Write-Error -Message "Failed to import function $($import.fullname): $_" - } + . $import.fullname } + Catch + { + Write-Error -Message "Failed to import function $($import.fullname): $_" + } +} # Load dependencies. TODO: Move to module dependency once the bug that # causes this is fixed: https://ci.appveyor.com/project/RamblingCookieMonster/buildhelpers/build/1.0.22 # Thanks to Joel Bennett for this! - Import-Module $PSScriptRoot\Private\Modules\Configuration +$fallbackModule = Get-Module -Name $PSScriptRoot\Private\Modules\Configuration -ListAvailable +if ($configModule = Get-Module $fallbackModule.Name -ListAvailable) +{ + $configModule | + Where-Object { $_.Version -gt $fallbackModule.Version} | + Sort-Object -Property Version -Descending | + Select-Object -First 1 | + Import-Module -Force +} +if (-not (Get-Module $fallbackModule.Name | Where-Object { $_.Version -gt $fallbackModule.Version})) +{ + $fallbackModule | Import-Module -Force +} Export-ModuleMember -Function $Public.Basename Export-ModuleMember -Function Get-Metadata, Update-Metadata, Export-Metadata # Set aliases (#10) Set-Alias -Name Set-BuildVariable -Value $PSScriptRoot\Scripts\Set-BuildVariable.ps1 -Export-ModuleMember -Alias Set-BuildVariable +Set-Alias -Name Get-NextPSGalleryVersion -Value Get-NextNugetPackageVersion +# Backwards compatibilty to command names prior to #72 +Set-Alias -Name Get-BuildVariables -Value Get-BuildVariable +Set-Alias -Name Get-ModuleAliases -Value Get-ModuleAlias +Set-Alias -Name Get-ModuleFunctions -Value Get-ModuleFunction +Set-Alias -Name Set-ModuleAliases -Value Set-ModuleAlias +Set-Alias -Name Set-ModuleFormats -Value Set-ModuleFormat +Set-Alias -Name Set-ModuleFunctions -Value Set-ModuleFunction +Set-Alias -Name Set-ModuleTypes -Value Set-ModuleType + +$exportModuleMemberSplat = @{ + Alias = @( + 'Set-BuildVariable' + 'Get-NextPSGalleryVersion' + 'Get-BuildVariables' + 'Get-ModuleAliases' + 'Get-ModuleFunctions' + 'Set-ModuleAliases' + 'Set-ModuleFormats' + 'Set-ModuleFunctions' + 'Set-ModuleTypes' + ) +} +Export-ModuleMember @exportModuleMemberSplat diff --git a/BuildHelpers/Private/Get-InstalledSoftware.ps1 b/BuildHelpers/Private/Get-InstalledSoftware.ps1 index a7ccf8f..8ea219f 100644 --- a/BuildHelpers/Private/Get-InstalledSoftware.ps1 +++ b/BuildHelpers/Private/Get-InstalledSoftware.ps1 @@ -38,15 +38,15 @@ [Parameter( Position = 0, ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, + ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [ValidateNotNullOrEmpty()] [Alias('CN','__SERVER','Server','Computer')] [string[]]$ComputerName = $env:computername, - + [string]$DisplayName = $null, - + [string]$Publisher = $null ) @@ -58,7 +58,7 @@ "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall" - function Get-SoftwareKeys { + function Get-SoftwareKey { [cmdletbinding()] param( $Reg, @@ -89,7 +89,7 @@ foreach($key in $subkeys) { #Build the full path to the key for this software - $thisKey = $UninstallKey+"\\"+$key + $thisKey = $UninstallKey+"\\"+$key #Open the subkey for this software $thisSubKey = $null @@ -101,7 +101,7 @@ { #Get the display name. If this is not empty we know there is information to show $dispName = $thisSubKey.GetValue("DisplayName") - + #Get the publisher name ahead of time to allow filtering using Publisher parameter $pubName = $thisSubKey.GetValue("Publisher") @@ -119,11 +119,11 @@ DisplayName = $dispname Publisher = $pubName Version = $thisSubKey.GetValue("DisplayVersion") - UninstallString = $thisSubKey.GetValue("UninstallString") + UninstallString = $thisSubKey.GetValue("UninstallString") InstallDate = $thisSubKey.GetValue("InstallDate") Hive = $Hive Arch = $Arch - } | select ComputerName, DisplayName, Publisher, Version, Hive, Arch, UninstallString, InstallDate + } | Select-Object ComputerName, DisplayName, Publisher, Version, Hive, Arch, UninstallString, InstallDate } } Catch @@ -171,7 +171,7 @@ foreach($uninstallKey in $UninstallKeys) { Write-Verbose "Checking [LocalMachine] [$uninstallKey] on [$computer]" - Get-SoftwareKeys -Reg $Reg -UninstallKey $uninstallKey -Hive 'HKLM' + Get-SoftwareKey -Reg $Reg -UninstallKey $uninstallKey -Hive 'HKLM' } Try @@ -191,8 +191,8 @@ foreach($uninstallKey in $UninstallKeys) { Write-Verbose "Checking [CurrentUser] [$uninstallKey] on [$computer]" - Get-SoftwareKeys -Reg $Reg -UninstallKey $uninstallKey -Hive HKCU + Get-SoftwareKey -Reg $Reg -UninstallKey $uninstallKey -Hive HKCU } } } -} \ No newline at end of file +} diff --git a/BuildHelpers/Private/Get-TeamCityProperties.ps1 b/BuildHelpers/Private/Get-TeamCityProperty.ps1 similarity index 78% rename from BuildHelpers/Private/Get-TeamCityProperties.ps1 rename to BuildHelpers/Private/Get-TeamCityProperty.ps1 index a2aeed4..9f9198b 100644 --- a/BuildHelpers/Private/Get-TeamCityProperties.ps1 +++ b/BuildHelpers/Private/Get-TeamCityProperty.ps1 @@ -1,4 +1,4 @@ -function Get-TeamCityProperties +function Get-TeamCityProperty { <# .SYNOPSIS @@ -6,26 +6,26 @@ Doesn't do anything if not running under TeamCity .DESCRIPTION - Teamcity generates a build properties file and stores the location in the environent - variable TEAMCITY_BUILD_PROPERTIES_FILE. + Teamcity generates a build properties file and stores the location in the environent + variable TEAMCITY_BUILD_PROPERTIES_FILE. Loads the TeamCity system build properties into a hashtable. .PARAMETER propertiesfile - Path to properties xml file. Defaults to environent - variable TEAMCITY_BUILD_PROPERTIES_FILE. + Path to properties xml file. Defaults to environent + variable TEAMCITY_BUILD_PROPERTIES_FILE. .NOTES We assume you are in the project root, for several of the fallback options .EXAMPLE - Get-TeamCityProperties + Get-TeamCityProperty .LINK https://gist.github.com/piers7/6432985 .LINK - Get-BuildVariables + Get-BuildVariable #> [OutputType([hashtable])] param( @@ -46,7 +46,7 @@ { $buildProperties[$entry.Key] = $entry.'#text' } - + Write-Output -InputObject $buildProperties } } diff --git a/BuildHelpers/Private/Invoke-LikeFilter.ps1 b/BuildHelpers/Private/Invoke-LikeFilter.ps1 index f69b7e6..09d66b2 100644 --- a/BuildHelpers/Private/Invoke-LikeFilter.ps1 +++ b/BuildHelpers/Private/Invoke-LikeFilter.ps1 @@ -8,11 +8,11 @@ function Invoke-LikeFilter { [string[]]$FilterArray, # Array of strings to filter on with a -like operator [switch]$Not # return items that are not -like... ) - + if($FilterArray.count -gt 0) { Write-Verbose "Running FilterArray [$FilterArray] against [$($Collection.count)] items" - $Collection | Where { + $Collection | Where-Object { $Status = $False foreach($item in $FilterArray) { @@ -25,8 +25,8 @@ function Invoke-LikeFilter { } elseif($NestedPropertyName) { - # Code injection, beware... - $Value = Invoke-Expression "`$_.$($NestedPropertyName -join '.')" + $dump = $_ + $Value = $NestedPropertyName | Foreach-Object -process {$dump = $dump.$_} -end {$dump} if($Value -like $item) { $Status = $True @@ -54,4 +54,4 @@ function Invoke-LikeFilter { { $Collection } -} \ No newline at end of file +} diff --git a/BuildHelpers/Private/Join-Parts.ps1 b/BuildHelpers/Private/Join-Part.ps1 similarity index 74% rename from BuildHelpers/Private/Join-Parts.ps1 rename to BuildHelpers/Private/Join-Part.ps1 index 7ff7c5c..0f7aab8 100644 --- a/BuildHelpers/Private/Join-Parts.ps1 +++ b/BuildHelpers/Private/Join-Part.ps1 @@ -1,4 +1,4 @@ -function Join-Parts { +function Join-Part { <# .SYNOPSIS Join strings with a specified separator. @@ -17,24 +17,24 @@ function Join-Parts { Strings to join .EXAMPLE - Join-Parts -Separator "/" this //should $Null /work/ /well + Join-Part -Separator "/" this //should $Null /work/ /well # Output: this/should/work/well .EXAMPLE - Join-Parts -Parts http://this.com, should, /work/, /wel + Join-Part -Parts http://this.com, should, /work/, /wel # Output: http://this.com/should/work/wel .EXAMPLE - Join-Parts -Separator "?" this ?should work ???well + Join-Part -Separator "?" this ?should work ???well # Output: this?should?work?well .EXAMPLE $CouldBeOneOrMore = @( "JustOne" ) - Join-Parts -Separator ? -Parts CouldBeOneOrMore + Join-Part -Separator ? -Parts CouldBeOneOrMore # Output JustOne @@ -43,8 +43,8 @@ function Join-Parts { .NOTES Credit to Rob C. and Michael S. from this post: - http://stackoverflow.com/questions/9593535/best-way-to-join-parts-with-a-separator-in-powershell - + http://stackoverflow.com/questions/9593535/best-way-to-Join-Part-with-a-separator-in-powershell + #> [cmdletbinding()] param @@ -60,4 +60,4 @@ function Join-Parts { Foreach-Object { ( [string]$_ ).trim($Separator) } | Where-Object { $_ } ) -join $Separator -} \ No newline at end of file +} diff --git a/BuildHelpers/Public/Find-NugetPackage.ps1 b/BuildHelpers/Public/Find-NugetPackage.ps1 index 953b7c0..079524c 100644 --- a/BuildHelpers/Public/Find-NugetPackage.ps1 +++ b/BuildHelpers/Public/Find-NugetPackage.ps1 @@ -74,34 +74,30 @@ function Find-NugetPackage if($IsLatest) { Write-Verbose "Searching for latest [$name] module" - $URI = Join-Parts -Separator / -Parts $PackageSourceUrl, "Packages?`$filter=Id eq '$name' and IsLatestVersion" + $URI = Join-Part -Separator / -Parts $PackageSourceUrl, "Packages?`$filter=Id eq '$name' and IsLatestVersion" } elseif($PSBoundParameters.ContainsKey($Version)) { Write-Verbose "Searching for version [$version] of [$name]" - $URI = Join-Parts -Separator / -Parts $PackageSourceUrl, "Packages?`$filter=Id eq '$name' and Version eq '$Version'" + $URI = Join-Part -Separator / -Parts $PackageSourceUrl, "Packages?`$filter=Id eq '$name' and Version eq '$Version'" } else { Write-Verbose "Searching for all versions of [$name] module" - $URI = Join-Parts -Separator / -Parts $PackageSourceUrl ,"Packages?`$filter=Id eq '$name'" + $URI = Join-Part -Separator / -Parts $PackageSourceUrl ,"Packages?`$filter=Id eq '$name'" } - Invoke-RestMethod $URI | - Select-Object @{n='Name';ex={$_.title.('#text')}}, - @{n='Author';ex={$_.author.name}}, - @{n='Version';ex={ - if($_.properties.NormalizedVersion) - { - $_.properties.NormalizedVersion - } - else - { - $_.properties.Version - } - } - }, - @{n='Uri';ex={$_.Content.src}}, - @{n='Description';ex={$_.properties.Description}}, - @{n='Properties';ex={$_.properties}} + Invoke-RestMethod $URI | + Select-Object @{n='Name';ex={$_.title.('#text')}}, + @{n='Author';ex={$_.author.name}}, + @{n='Version';ex={ + if($_.properties.NormalizedVersion){ + $_.properties.NormalizedVersion + }else{ + $_.properties.Version + } + }}, + @{n='Uri';ex={$_.Content.src}}, + @{n='Description';ex={$_.properties.Description}}, + @{n='Properties';ex={$_.properties}} } diff --git a/BuildHelpers/Public/Get-BuildEnvironment.ps1 b/BuildHelpers/Public/Get-BuildEnvironment.ps1 index 9c69a7c..3df33dd 100644 --- a/BuildHelpers/Public/Get-BuildEnvironment.ps1 +++ b/BuildHelpers/Public/Get-BuildEnvironment.ps1 @@ -10,10 +10,10 @@ function Get-BuildEnvironment { Get normalized build system and project details Returns the following details: - ProjectPath via Get-BuildVariables - BranchName via Get-BuildVariables - CommitMessage via Get-BuildVariables - BuildNumber via Get-BuildVariables + ProjectPath via Get-BuildVariable + BranchName via Get-BuildVariable + CommitMessage via Get-BuildVariable + BuildNumber via Get-BuildVariable ProjectName via Get-ProjectName PSModuleManifest via Get-PSModuleManifest ModulePath via Split-Path on PSModuleManifest @@ -51,7 +51,7 @@ function Get-BuildEnvironment { https://github.com/RamblingCookieMonster/BuildHelpers .LINK - Get-BuildVariables + Get-BuildVariable .LINK Set-BuildEnvironment @@ -87,7 +87,7 @@ function Get-BuildEnvironment { { $GBVParams.add('GitPath', $GitPath) } - ${Build.Vars} = Get-BuildVariables @GBVParams + ${Build.Vars} = Get-BuildVariable @GBVParams ${Build.ProjectName} = Get-ProjectName -Path $Path ${Build.ManifestPath} = Get-PSModuleManifest -Path $Path if( ${Build.ManifestPath} ) { diff --git a/BuildHelpers/Public/Get-BuildEnvironmentDetail.ps1 b/BuildHelpers/Public/Get-BuildEnvironmentDetail.ps1 index 142a405..d85a805 100644 --- a/BuildHelpers/Public/Get-BuildEnvironmentDetail.ps1 +++ b/BuildHelpers/Public/Get-BuildEnvironmentDetail.ps1 @@ -41,6 +41,7 @@ about_BuildHelpers #> [cmdletbinding()] + [OutputType( [String], [Hashtable])] param( [validateset('*', 'OperatingSystem', @@ -80,39 +81,38 @@ { 'PSVersionTable' { $Details.set_item($_, $PSVersionTable)} 'PSModulePath' { $Details.set_item($_, ($ENV:PSModulePath -split ';'))} - 'ModulesLoaded' { $Details.set_item($_, ( + 'ModulesLoaded' { $Details.set_item($_, ( Get-Module | - Select Name, Version, Path | - Sort Name + Select-Object Name, Version, Path | + Sort-Object Name )) } 'ModulesAvailable' { $Details.set_item($_, ( Get-Module -ListAvailable | - Select Name, Version, Path | - Sort Name - + Select-Object Name, Version, Path | + Sort-Object Name + )) } 'Path' { $Details.set_item($_, ( $ENV:Path -split ';'))} - 'Variables' { $Details.set_item($_, ( Get-Variable | Select Name, Value ))} + 'Variables' { $Details.set_item($_, ( Get-Variable | Select-Object Name, Value ))} 'Software' { $Details.set_item($_, ( Get-InstalledSoftware | - Select DisplayName, Publisher, Version, Hive, Arch))} + Select-Object DisplayName, Publisher, Version, Hive, Arch))} 'Hotfixes' { $Details.set_item($_, ( Get-Hotfix ))} 'OperatingSystem' { $Details.set_item($_, ( - Get-WMIObject win32_operatingsystem | - Select Caption, - Version + Get-CimInstance -classname win32_operatingsystem | + Select-Object Caption, Version ))} 'Location' { $Details.set_item($_, ( Get-Location ).Path )} 'PackageProvider' { $Details.set_item($_, $( if(Get-Module PackageManagement -ListAvailable) { - Get-PackageProvider | Select Name, Version + Get-PackageProvider | Select-Object Name, Version } ))} 'PackageSource' { $Details.set_item($_, $( if(Get-Module PackageManagement -ListAvailable) { - Get-PackageSource | Select Name, ProviderName, Location + Get-PackageSource | Select-Object Name, ProviderName, Location } ))} } @@ -130,4 +130,4 @@ { $Details } -} \ No newline at end of file +} diff --git a/BuildHelpers/Public/Get-BuildVariables.ps1 b/BuildHelpers/Public/Get-BuildVariable.ps1 similarity index 89% rename from BuildHelpers/Public/Get-BuildVariables.ps1 rename to BuildHelpers/Public/Get-BuildVariable.ps1 index 4cd4974..c37aecd 100644 --- a/BuildHelpers/Public/Get-BuildVariables.ps1 +++ b/BuildHelpers/Public/Get-BuildVariable.ps1 @@ -1,5 +1,4 @@ -function Get-BuildVariables -{ +function Get-BuildVariable { <# .SYNOPSIS Normalize build system variables @@ -46,7 +45,7 @@ function Get-BuildVariables We assume you are in the project root, for several of the fallback options .EXAMPLE - Get-BuildVariables + Get-BuildVariable .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -62,23 +61,20 @@ function Get-BuildVariables #> [cmdletbinding()] param( - [ValidateNotNullOrEmpty()] $Path = $PWD.Path, - [validatescript({ - if(-not (Get-Command $_ -ErrorAction SilentlyContinue)) - { - throw "Could not find command at GitPath [$_]" - } - $true - })] + if(-not (Get-Command $_ -ErrorAction SilentlyContinue)) + { + throw "Could not find command at GitPath [$_]" + } + $true + })] $GitPath = 'git' ) $Path = Get-FullPath $Path $Environment = Get-Item ENV: - if(!$PSboundParameters.ContainsKey('GitPath')) - { + if(!$PSboundParameters.ContainsKey('GitPath')) { $GitPath = (Get-Command $GitPath -ErrorAction SilentlyContinue)[0].Path } @@ -90,7 +86,7 @@ function Get-BuildVariables GitPath = $GitPath } } - $tcProperties = Get-TeamCityProperties # Teamcity has limited ENV: values but dumps the build configuration in a properties file. + $tcProperties = Get-TeamCityProperty # Teamcity has limited ENV: values but dumps the build configuration in a properties file. # Determine the build system: $BuildSystem = switch ($Environment.Name) @@ -121,12 +117,9 @@ function Get-BuildVariables } if(-not $BuildRoot) { - if ($BuildSystem -eq 'Teamcity') - { + if ($BuildSystem -eq 'Teamcity') { $BuildRoot = $tcProperties['teamcity.build.checkoutDir'] - } - else - { + } else { # Assumption: this function is defined in a file at the root of the build folder $BuildRoot = $Path } @@ -156,61 +149,53 @@ function Get-BuildVariables # Find the git commit message $CommitMessage = switch ($Environment.Name) { - 'APPVEYOR_REPO_COMMIT_MESSAGE' - { + 'APPVEYOR_REPO_COMMIT_MESSAGE' { "$env:APPVEYOR_REPO_COMMIT_MESSAGE $env:APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED".TrimEnd() break } - 'CI_COMMIT_SHA' - { + 'CI_COMMIT_SHA' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # Gitlab 9.0+ - thanks to mipadi http://stackoverflow.com/a/3357357/3067642 } - 'CI_BUILD_REF' - { + 'CI_BUILD_REF' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # Gitlab 8.x - thanks to mipadi http://stackoverflow.com/a/3357357/3067642 } - 'GIT_COMMIT' - { + 'GIT_COMMIT' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # Jenkins - thanks to mipadi http://stackoverflow.com/a/3357357/3067642 } - 'BUILD_SOURCEVERSION' - { + 'BUILD_SOURCEVERSION' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # VSTS (https://www.visualstudio.com/en-us/docs/build/define/variables#) } - 'BUILD_VCS_NUMBER' - { + 'BUILD_VCS_NUMBER' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # Teamcity https://confluence.jetbrains.com/display/TCD10/Predefined+Build+Parameters } - 'BAMBOO_REPOSITORY_REVISION_NUMBER' - { + 'BAMBOO_REPOSITORY_REVISION_NUMBER' { if($WeCanGit) { Invoke-Git @IGParams -Arguments "log --format=%B -n 1 $( (Get-Item -Path "ENV:$_").Value )" break } # Bamboo https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html } - 'TRAVIS_COMMIT_MESSAGE' - { + 'TRAVIS_COMMIT_MESSAGE' { "$env:TRAVIS_COMMIT_MESSAGE" break } diff --git a/BuildHelpers/Public/Get-GitChangedFile.ps1 b/BuildHelpers/Public/Get-GitChangedFile.ps1 index 1d2f028..7536ae3 100644 --- a/BuildHelpers/Public/Get-GitChangedFile.ps1 +++ b/BuildHelpers/Public/Get-GitChangedFile.ps1 @@ -65,7 +65,7 @@ function Get-GitChangedFile { $Path = Get-FullPath $Path $GitPathRaw = Invoke-Git rev-parse --show-toplevel -Path $Path Write-Verbose "Found git root [$GitPathRaw]" - $GitPath = Resolve-Path $GitPathRaw + $GitPath = Get-FullPath $GitPathRaw if(Test-Path $GitPath) { Write-Verbose "Using [$GitPath] as repo root" @@ -88,7 +88,7 @@ function Get-GitChangedFile { if($Files.Count -gt 0) { $Params = @{Collection = $Files} - Write-Verbose "Found [$($Files.Count)] files with raw values:`n$($Files | Foreach {"'$_'"} | Out-String)" + Write-Verbose "Found [$($Files.Count)] files with raw values:`n$($Files | Foreach-Object {"'$_'"} | Out-String)" if($Include) { $Files = Invoke-LikeFilter @params -FilterArray $Include diff --git a/BuildHelpers/Public/Get-ModuleAliases.ps1 b/BuildHelpers/Public/Get-ModuleAlias.ps1 similarity index 79% rename from BuildHelpers/Public/Get-ModuleAliases.ps1 rename to BuildHelpers/Public/Get-ModuleAlias.ps1 index 5b5e225..81260e8 100644 --- a/BuildHelpers/Public/Get-ModuleAliases.ps1 +++ b/BuildHelpers/Public/Get-ModuleAlias.ps1 @@ -1,5 +1,4 @@ -function Get-ModuleAliases -{ +function Get-ModuleAlias { <# .SYNOPSIS List aliases imported by a module @@ -17,7 +16,7 @@ function Get-ModuleAliases We assume you are in the project root, for several of the fallback options .EXAMPLE - Get-ModuleAliases + Get-ModuleAlias .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -28,7 +27,6 @@ function Get-ModuleAliases [cmdletbinding()] param( [parameter(ValueFromPipeline = $True)] - [ValidateNotNullOrEmpty()] [Alias('Path')] [string]$Name ) @@ -36,7 +34,7 @@ function Get-ModuleAliases { if(-not $Name) { - $BuildDetails = Get-BuildVariables + $BuildDetails = Get-BuildVariable $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) } @@ -49,10 +47,10 @@ function Get-ModuleAliases # Create a runspace, add script to run $PowerShell = [Powershell]::Create() [void]$PowerShell.AddScript({ - Param ($Force, $Passthru, $Name) - Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + Param ($Force, $Passthru, $Name) + Import-Module -Name $Name -PassThru:$Passthru -Force:$Force - }).AddParameters($Params) + }).AddParameters($Params) ( $PowerShell.Invoke() ).ExportedAliases.Keys diff --git a/BuildHelpers/Public/Get-ModuleFunctions.ps1 b/BuildHelpers/Public/Get-ModuleFunction.ps1 similarity index 79% rename from BuildHelpers/Public/Get-ModuleFunctions.ps1 rename to BuildHelpers/Public/Get-ModuleFunction.ps1 index 54f8055..e341f37 100644 --- a/BuildHelpers/Public/Get-ModuleFunctions.ps1 +++ b/BuildHelpers/Public/Get-ModuleFunction.ps1 @@ -1,5 +1,4 @@ -function Get-ModuleFunctions -{ +function Get-ModuleFunction { <# .SYNOPSIS List functions imported by a module @@ -17,7 +16,7 @@ function Get-ModuleFunctions We assume you are in the project root, for several of the fallback options .EXAMPLE - Get-ModuleFunctions + Get-ModuleFunction .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -28,7 +27,6 @@ function Get-ModuleFunctions [cmdletbinding()] param( [parameter(ValueFromPipeline = $True)] - [ValidateNotNullOrEmpty()] [Alias('Path')] [string]$Name ) @@ -36,7 +34,7 @@ function Get-ModuleFunctions { if(-not $Name) { - $BuildDetails = Get-BuildVariables + $BuildDetails = Get-BuildVariable $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) } @@ -49,10 +47,10 @@ function Get-ModuleFunctions # Create a runspace, add script to run $PowerShell = [Powershell]::Create() [void]$PowerShell.AddScript({ - Param ($Force, $Passthru, $Name) - Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + Param ($Force, $Passthru, $Name) + Import-Module -Name $Name -PassThru:$Passthru -Force:$Force - }).AddParameters($Params) + }).AddParameters($Params) ( $PowerShell.Invoke() ).ExportedFunctions.Keys diff --git a/BuildHelpers/Public/Get-NextNugetPackageVersion.ps1 b/BuildHelpers/Public/Get-NextNugetPackageVersion.ps1 index a4a247c..e28c8a1 100644 --- a/BuildHelpers/Public/Get-NextNugetPackageVersion.ps1 +++ b/BuildHelpers/Public/Get-NextNugetPackageVersion.ps1 @@ -12,7 +12,7 @@ Uses the versioning scheme adopted by the user Where possible, users should stick to semver: http://semver.org/ (Major.Minor.Patch, given restrictions .NET Version class) - + If no existing module is found, we return 0.0.1 .PARAMETER Name diff --git a/BuildHelpers/Public/Get-NextPSGalleryVersion.ps1 b/BuildHelpers/Public/Get-NextPowerShellGetVersion.ps1 similarity index 94% rename from BuildHelpers/Public/Get-NextPSGalleryVersion.ps1 rename to BuildHelpers/Public/Get-NextPowerShellGetVersion.ps1 index b72da28..b7a1835 100644 --- a/BuildHelpers/Public/Get-NextPSGalleryVersion.ps1 +++ b/BuildHelpers/Public/Get-NextPowerShellGetVersion.ps1 @@ -1,8 +1,8 @@ -function Get-NextPSGalleryVersion { +function Get-NextPowerShellGetVersion { <# .SYNOPSIS DEPRECATED: Please use Get-NextNugetPackageVersion - + Get the next version for a module or script in the PowerShell Gallery .FUNCTIONALITY @@ -18,7 +18,7 @@ Where possible, users should stick to semver: http://semver.org/ (Major.Minor.Patch, given restrictions .NET Version class) This requires the PowerShellGet module - + If no existing module is found, we return 0.0.1 .PARAMETER Name @@ -28,10 +28,10 @@ Module or script. Defaults to module. .EXAMPLE - Get-NextPSGalleryVersion PSDeploy + Get-NextPowerShellGetVersion PSDeploy .EXAMPLE - Get-NextPSGalleryVersion Open-ISEFunction -Type Script + Get-NextPowerShellGetVersion Open-ISEFunction -Type Script .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -60,7 +60,7 @@ if ($Type -eq 'Module') { $Existing = Find-Module -Name $Item -Repository $Repository -ErrorAction Stop } - else { + else { # Script $Existing = Find-Script -Name $Item -Repository $Repository -ErrorAction Stop } @@ -108,6 +108,6 @@ else { New-Object System.Version ($Version.Major + 1, 0) } - } + } } } diff --git a/BuildHelpers/Public/Get-PSModuleManifest.ps1 b/BuildHelpers/Public/Get-PSModuleManifest.ps1 index d032a04..409e881 100644 --- a/BuildHelpers/Public/Get-PSModuleManifest.ps1 +++ b/BuildHelpers/Public/Get-PSModuleManifest.ps1 @@ -31,7 +31,7 @@ https://github.com/RamblingCookieMonster/BuildHelpers .LINK - Get-BuildVariables + Get-BuildVariable .LINK Set-BuildEnvironment @@ -40,6 +40,7 @@ about_BuildHelpers #> [cmdletbinding()] + [OutputType( [String] )] param( [ValidateNotNullOrEmpty()] $Path = $PWD.Path @@ -57,7 +58,7 @@ else { # Look for properly organized modules - $ProjectPaths = Get-ChildItem $Path -Directory | + $ProjectPaths = Get-ChildItem $Path -Directory | ForEach-Object { $ThisFolder = $_ $ExpectedManifest = Join-Path $ThisFolder.FullName "$($ThisFolder.Name).psd1" diff --git a/BuildHelpers/Public/Get-ProjectName.ps1 b/BuildHelpers/Public/Get-ProjectName.ps1 index 4832b92..6399416 100644 --- a/BuildHelpers/Public/Get-ProjectName.ps1 +++ b/BuildHelpers/Public/Get-ProjectName.ps1 @@ -32,7 +32,7 @@ function Get-ProjectName https://github.com/RamblingCookieMonster/BuildHelpers .LINK - Get-BuildVariables + Get-BuildVariable .LINK Set-BuildEnvironment @@ -59,7 +59,7 @@ function Get-ProjectName Where-Object { Test-Path $(Join-Path $_.FullName "$($_.name).psd1") } | - Select -ExpandProperty Fullname + Select-Object -ExpandProperty Fullname if( @($ProjectPaths).Count -gt 1 ) { @@ -90,7 +90,7 @@ function Get-ProjectName $result = Split-Path $Path -Leaf } } - + if ($env:APPVEYOR_PROJECT_NAME -and $env:APPVEYOR_JOB_ID -and ($result -like $env:APPVEYOR_PROJECT_NAME)) { $env:APPVEYOR_PROJECT_NAME diff --git a/BuildHelpers/Public/Invoke-Git.ps1 b/BuildHelpers/Public/Invoke-Git.ps1 index 27e790d..35f7c7d 100644 --- a/BuildHelpers/Public/Invoke-Git.ps1 +++ b/BuildHelpers/Public/Invoke-Git.ps1 @@ -1,5 +1,5 @@ Function Invoke-Git { - <# +<# .SYNOPSIS Wrapper to invoke git and return streams @@ -58,92 +58,95 @@ #> [cmdletbinding()] param( - [parameter( - Position = 0, - ValueFromRemainingArguments = $true - )] - [String]$Arguments, - - [Bool]$NoWindow = $true, - [Bool]$RedirectStandardError = $true, - [Bool]$RedirectStandardOutput = $true, - [Bool]$UseShellExecute = $false, - [String]$Path = $PWD.Path, - [Switch]$Quiet, - [String]$Split = "`n", - [Switch]$Raw, - [validatescript( + [parameter(Position = 0, + ValueFromRemainingArguments = $true)] + $Arguments, + + $NoWindow = $true, + $RedirectStandardError = $true, + $RedirectStandardOutput = $true, + $UseShellExecute = $false, + $Path = $PWD.Path, + $Quiet, + $Split = "`n", + $Raw, + [validatescript({ + if(-not (Get-Command $_ -ErrorAction SilentlyContinue)) { - if (-not (Get-Command $_ -ErrorAction SilentlyContinue)) { - throw "Could not find command at GitPath [$_]" - } - $true + throw "Could not find command at GitPath [$_]" } - )] - [String]$GitPath = 'git' + $true + })] + [string]$GitPath = 'git' ) - Begin { - $Path = Get-FullPath $Path - if (!$PSBoundParameters.ContainsKey('GitPath')) { - $GitPath = (Get-Command $GitPath -ErrorAction Stop)[0].Path - } - $Command = $GitPath + $Path = Get-FullPath $Path + # http://stackoverflow.com/questions/8761888/powershell-capturing-standard-out-and-error-with-start-process + $pinfo = New-Object System.Diagnostics.ProcessStartInfo + if(!$PSBoundParameters.ContainsKey('GitPath')) { + $GitPath = (Get-Command $GitPath -ErrorAction Stop)[0].Path } - - Process { - # http://stackoverflow.com/questions/8761888/powershell-capturing-standard-out-and-error-with-start-process - $pinfo = New-Object System.Diagnostics.ProcessStartInfo - $pinfo.FileName = $GitPath - $pinfo.CreateNoWindow = $NoWindow - $pinfo.RedirectStandardError = $RedirectStandardError - $pinfo.RedirectStandardOutput = $RedirectStandardOutput - $pinfo.UseShellExecute = $UseShellExecute - $pinfo.WorkingDirectory = $Path - if ($PSBoundParameters.ContainsKey('Arguments')) { - $pinfo.Arguments = $Arguments - $Command = "$Command $Arguments" - } - $p = New-Object System.Diagnostics.Process - $p.StartInfo = $pinfo - $null = $p.Start() - $p.WaitForExit() - if ($Quiet) { - return + $pinfo.FileName = $GitPath + $Command = $GitPath + $pinfo.CreateNoWindow = $NoWindow + $pinfo.RedirectStandardError = $RedirectStandardError + $pinfo.RedirectStandardOutput = $RedirectStandardOutput + $pinfo.UseShellExecute = $UseShellExecute + $pinfo.WorkingDirectory = $Path + if($PSBoundParameters.ContainsKey('Arguments')) + { + $pinfo.Arguments = $Arguments + $Command = "$Command $Arguments" + } + $p = New-Object System.Diagnostics.Process + $p.StartInfo = $pinfo + $null = $p.Start() + $p.WaitForExit() + if($Quiet) + { + return + } + else + { + #there was a newline in output... + if($stdout = $p.StandardOutput.ReadToEnd()) + { + if($split) + { + $stdout = $stdout -split "`n" | Where-Object {$_} + } + $stdout = foreach($item in @($stdout)){ + $item.trim() + } } - else { - #there was a newline in output... - if ($stdout = $p.StandardOutput.ReadToEnd()) { - if ($split) { - $stdout = $stdout -split "`n" | Where {$_} - } - $stdout = foreach ($item in @($stdout)) { - $item.trim() - } + if($stderr = $p.StandardError.ReadToEnd()) + { + if($split) + { + $stderr = $stderr -split "`n" | Where-Object {$_} } - if ($stderr = $p.StandardError.ReadToEnd()) { - if ($split) { - $stderr = $stderr -split "`n" | Where {$_} - } - $stderr = foreach ($item in @($stderr)) { - $item.trim() - } + $stderr = foreach($item in @($stderr)){ + $item.trim() } + } - if ($Raw) { - [pscustomobject]@{ - Command = $Command - Output = $stdout - Error = $stderr - } + if($Raw) + { + [pscustomobject]@{ + Command = $Command + Output = $stdout + Error = $stderr } - else { - if ($stdout) { - $stdout - } - if ($stderr) { - Write-Error $stderr.trim() - } + } + else + { + if($stdout) + { + $stdout + } + if($stderr) + { + Write-Error $stderr.trim() } } } diff --git a/BuildHelpers/Public/Set-BuildEnvironment.ps1 b/BuildHelpers/Public/Set-BuildEnvironment.ps1 index 0471cd3..51c0968 100644 --- a/BuildHelpers/Public/Set-BuildEnvironment.ps1 +++ b/BuildHelpers/Public/Set-BuildEnvironment.ps1 @@ -10,10 +10,10 @@ function Set-BuildEnvironment { Normalize build system and project details into environment variables Creates the following environment variables: - $ENV:ProjectPath via Get-BuildVariables - $ENV:BranchName via Get-BuildVariables - $ENV:CommitMessage via Get-BuildVariables - $ENV:BuildNumber via Get-BuildVariables + $ENV:ProjectPath via Get-BuildVariable + $ENV:BranchName via Get-BuildVariable + $ENV:CommitMessage via Get-BuildVariable + $ENV:BuildNumber via Get-BuildVariable $ENV:ProjectName via Get-ProjectName $ENV:PSModuleManifest via Get-PSModuleManifest $ENV:ModulePath via Split-Path on PSModuleManifest @@ -70,7 +70,7 @@ function Set-BuildEnvironment { https://github.com/RamblingCookieMonster/BuildHelpers .LINK - Get-BuildVariables + Get-BuildVariable .LINK Get-BuildEnvironment @@ -81,7 +81,8 @@ function Set-BuildEnvironment { .LINK about_BuildHelpers #> - [cmdletbinding()] + [CmdLetBinding( SupportsShouldProcess = $false )] + [System.Diagnostics.CodeAnalysis.SuppressMessage('PSUseShouldProcessForStateChangingFunctions', '')] param( [validatescript({ Test-Path $_ -PathType Container })] [ValidateNotNullOrEmpty()] diff --git a/BuildHelpers/Public/Set-ModuleAliases.ps1 b/BuildHelpers/Public/Set-ModuleAlias.ps1 similarity index 74% rename from BuildHelpers/Public/Set-ModuleAliases.ps1 rename to BuildHelpers/Public/Set-ModuleAlias.ps1 index 92bcc01..dee059c 100644 --- a/BuildHelpers/Public/Set-ModuleAliases.ps1 +++ b/BuildHelpers/Public/Set-ModuleAlias.ps1 @@ -1,5 +1,4 @@ -function Set-ModuleAliases -{ +function Set-ModuleAlias { <# .SYNOPSIS EXPIRIMENTAL: Set AliasesToExport in a module manifest @@ -11,14 +10,14 @@ function Set-ModuleAliases EXPIRIMENTAL: Set AliasesToExport in a module manifest .PARAMETER Name - Name or path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariables + Name or path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariable .NOTES Major thanks to Joel Bennett for the code behind working with the psd1 Source: https://github.com/PoshCode/Configuration .EXAMPLE - Set-ModuleAliases + Set-ModuleAlias .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -26,10 +25,9 @@ function Set-ModuleAliases .LINK about_BuildHelpers #> - [cmdletbinding()] + [CmdLetBinding( SupportsShouldProcess )] param( [parameter(ValueFromPipeline = $True)] - [ValidateNotNullOrEmpty()] [Alias('Path')] [string]$Name, @@ -39,7 +37,7 @@ function Set-ModuleAliases { if(-not $Name) { - $BuildDetails = Get-BuildVariables + $BuildDetails = Get-BuildVariable $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) } @@ -52,11 +50,11 @@ function Set-ModuleAliases # Create a runspace, add script to run $PowerShell = [Powershell]::Create() [void]$PowerShell.AddScript({ - Param ($Force, $Passthru, $Name) - $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force - $module | Where-Object Path -notin $module.Scripts + Param ($Force, $Passthru, $Name) + $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + $module | Where-Object Path -notin $module.Scripts - }).AddParameters($Params) + }).AddParameters($Params) #Consider moving this to a runspace or job to keep session clean $Module = $PowerShell.Invoke() @@ -78,8 +76,10 @@ function Set-ModuleAliases Throw "Could not find expected module manifest '$ModulePSD1Path'" } - Update-MetaData -Path $ModulePSD1Path -PropertyName AliasesToExport -Value $AliasesToExport - + If ($PSCmdlet.ShouldProcess("Updating Module's exported Aliases")) { + Update-MetaData -Path $ModulePSD1Path -PropertyName AliasesToExport -Value $AliasesToExport + } + # Close down the runspace $PowerShell.Dispose() } diff --git a/BuildHelpers/Public/Set-ModuleFormats.ps1 b/BuildHelpers/Public/Set-ModuleFormat.ps1 similarity index 73% rename from BuildHelpers/Public/Set-ModuleFormats.ps1 rename to BuildHelpers/Public/Set-ModuleFormat.ps1 index a3a4606..4dfa72e 100644 --- a/BuildHelpers/Public/Set-ModuleFormats.ps1 +++ b/BuildHelpers/Public/Set-ModuleFormat.ps1 @@ -1,9 +1,8 @@ -function Set-ModuleFormats -{ +function Set-ModuleFormat { <# .SYNOPSIS EXPIRIMENTAL: Set FormatsToProcess - + [string]$FormatsPath in a module manifest .FUNCTIONALITY @@ -11,11 +10,11 @@ function Set-ModuleFormats .DESCRIPTION EXPIRIMENTAL: Set FormatsToProcess - + [string]$FormatsPath in a module manifest .PARAMETER Name - Name or path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariables + Name or path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariable .PARAMETER FormatsToProcess Array of .ps1xml files @@ -28,9 +27,9 @@ function Set-ModuleFormats Source: https://github.com/PoshCode/Configuration .EXAMPLE - Set-ModuleFormats -FormatsRelativePath '.\Format' + Set-ModuleFormat -FormatsRelativePath '.\Format' - Update module manifiest FormatsToProcess parameters with all the .ps1xml present in the .\Format folder. + Update module manifiest FormatsToProcess parameters with all the .ps1xml present in the .\Format folder. .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -38,10 +37,9 @@ function Set-ModuleFormats .LINK about_BuildHelpers #> - [cmdletbinding()] + [CmdLetBinding( SupportsShouldProcess )] param( [parameter(ValueFromPipeline = $True)] - [ValidateNotNullOrEmpty()] [Alias('Path')] [string]$Name, @@ -53,7 +51,7 @@ function Set-ModuleFormats { if(-not $Name) { - $BuildDetails = Get-BuildVariables + $BuildDetails = Get-BuildVariable $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) } @@ -68,11 +66,11 @@ function Set-ModuleFormats # Add scriptblock to the runspace [void]$PowerShell.AddScript({ - Param ($Force, $Passthru, $Name) - $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force - $module | Where-Object Path -notin $module.Scripts + Param ($Force, $Passthru, $Name) + $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + $module | Where-Object Path -notin $module.Scripts - }).AddParameters($Params) + }).AddParameters($Params) #Invoke the command $Module = $PowerShell.Invoke() @@ -93,16 +91,17 @@ function Set-ModuleFormats if(-not $FormatsToProcess) { $FormatPath = Join-Path -Path $Parent -ChildPath $FormatsRelativePath - $FormatList = Get-ChildItem -Path $FormatPath\*.ps1xml + $FormatList = Get-ChildItem -Path (Join-Path $FormatPath "*.ps1xml") $FormatsToProcess = @() - Foreach ($Item in $FormatList) - { + Foreach ($Item in $FormatList) { $FormatsToProcess += Join-Path -Path $FormatsRelativePath -ChildPath $Item.Name } } - Update-MetaData -Path $ModulePSD1Path -PropertyName FormatsToProcess -Value $FormatsToProcess + If ($PSCmdlet.ShouldProcess("Updating Module's FormatsToProcess")) { + Update-MetaData -Path $ModulePSD1Path -PropertyName FormatsToProcess -Value $FormatsToProcess + } # Close down the runspace $PowerShell.Dispose() diff --git a/BuildHelpers/Public/Set-ModuleFunctions.ps1 b/BuildHelpers/Public/Set-ModuleFunction.ps1 similarity index 74% rename from BuildHelpers/Public/Set-ModuleFunctions.ps1 rename to BuildHelpers/Public/Set-ModuleFunction.ps1 index e771c73..eb4bf2f 100644 --- a/BuildHelpers/Public/Set-ModuleFunctions.ps1 +++ b/BuildHelpers/Public/Set-ModuleFunction.ps1 @@ -1,5 +1,4 @@ -function Set-ModuleFunctions -{ +function Set-ModuleFunction { <# .SYNOPSIS Set FunctionsToExport in a module manifest @@ -11,14 +10,14 @@ function Set-ModuleFunctions Set FunctionsToExport in a module manifest .PARAMETER Name - Path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariables + Path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariable .NOTES Major thanks to Joel Bennett for the code behind working with the psd1 Source: https://github.com/PoshCode/Configuration .EXAMPLE - Set-ModuleFunctions + Set-ModuleFunction .LINK https://github.com/RamblingCookieMonster/BuildHelpers @@ -26,10 +25,9 @@ function Set-ModuleFunctions .LINK about_BuildHelpers #> - [cmdletbinding()] + [CmdLetBinding( SupportsShouldProcess )] param( [parameter(ValueFromPipeline = $True)] - [ValidateNotNullOrEmpty()] [Alias('Path')] [string]$Name, @@ -39,7 +37,7 @@ function Set-ModuleFunctions { if(-not $Name) { - $BuildDetails = Get-BuildVariables + $BuildDetails = Get-BuildVariable $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) } @@ -52,10 +50,10 @@ function Set-ModuleFunctions # Create a runspace, add script to run $PowerShell = [Powershell]::Create() [void]$PowerShell.AddScript({ - Param ($Force, $Passthru, $Name) - $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force - $module | Where-Object {$_.Path -notin $module.Scripts} - }).AddParameters($Params) + Param ($Force, $Passthru, $Name) + $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + $module | Where-Object {$_.Path -notin $module.Scripts} + }).AddParameters($Params) #Consider moving this to a runspace or job to keep session clean $Module = $PowerShell.Invoke() @@ -76,7 +74,9 @@ function Set-ModuleFunctions Throw "Could not find expected module manifest '$ModulePSD1Path'" } - Update-MetaData -Path $ModulePSD1Path -PropertyName FunctionsToExport -Value $FunctionsToExport + If ($PSCmdlet.ShouldProcess("Updating list of exported functions")) { + Update-MetaData -Path $ModulePSD1Path -PropertyName FunctionsToExport -Value $FunctionsToExport + } # Close down the runspace $PowerShell.Dispose() diff --git a/BuildHelpers/Public/Set-ModuleType.ps1 b/BuildHelpers/Public/Set-ModuleType.ps1 new file mode 100644 index 0000000..caf5677 --- /dev/null +++ b/BuildHelpers/Public/Set-ModuleType.ps1 @@ -0,0 +1,109 @@ +function Set-ModuleType { + <# + .SYNOPSIS + EXPIRIMENTAL: Set TypesToProcess + + [string]$TypesPath in a module manifest + + .FUNCTIONALITY + CI/CD + + .DESCRIPTION + EXPIRIMENTAL: Set TypesToProcess + + [string]$TypesPath in a module manifest + + .PARAMETER Name + Name or path to module to inspect. Defaults to ProjectPath\ProjectName via Get-BuildVariable + + .PARAMETER TypesToProcess + Array of .ps1xml files + + .PARAMETER TypesRelativePath + Path to the ps1xml files relatives to the root of the module (example: ".\Types") + + .NOTES + Major thanks to Joel Bennett for the code behind working with the psd1 + Source: https://github.com/PoshCode/Configuration + + .EXAMPLE + Set-ModuleType -TypesRelativePath '.\Types' + + Update module manifiest TypesToProcess parameters with all the .ps1xml present in the .\Types folder. + + .LINK + https://github.com/RamblingCookieMonster/BuildHelpers + + .LINK + about_BuildHelpers + #> + [CmdLetBinding( SupportsShouldProcess )] + param( + [parameter(ValueFromPipeline = $True)] + [Alias('Path')] + [string]$Name, + + [string[]]$TypesToProcess, + + [string]$TypesRelativePath + ) + Process + { + if(-not $Name) + { + $BuildDetails = Get-BuildVariable + $Name = Join-Path ($BuildDetails.ProjectPath) (Get-ProjectName) + } + + $params = @{ + Force = $True + Passthru = $True + Name = Get-FullPath $Name + } + + # Create a runspace + $PowerShell = [Powershell]::Create() + + # Add scriptblock to the runspace + [void]$PowerShell.AddScript({ + Param ($Force, $Passthru, $Name) + $module = Import-Module -Name $Name -PassThru:$Passthru -Force:$Force + $module | Where-Object Path -notin $module.Scripts + + }).AddParameters($Params) + + #Invoke the command + $Module = $PowerShell.Invoke() + + if(-not $Module) + { + Throw "Could not find module '$Name'" + } + + $Parent = $Module.ModuleBase + $File = "$($Module.Name).psd1" + $ModulePSD1Path = Join-Path $Parent $File + if(-not (Test-Path $ModulePSD1Path)) + { + Throw "Could not find expected module manifest '$ModulePSD1Path'" + } + + if(-not $TypesToProcess) + { + $TypesPath = Join-Path -Path $Parent -ChildPath $TypesRelativePath + $TypesList = Get-ChildItem -Path (Join-Path $TypesPath "*.ps1xml") + + $TypesToProcess = @() + Foreach ($Item in $TypesList) { + $TypesToProcess += Join-Path -Path $TypesRelativePath -ChildPath $Item.Name + } + } + + If ($PSCmdlet.ShouldProcess("Updating Module's TypesToProcess")) { + Update-MetaData -Path $ModulePSD1Path -PropertyName TypesToProcess -Value $TypesToProcess + } + + # Close down the runspace + $PowerShell.Dispose() + } +} diff --git a/BuildHelpers/Public/Set-ShieldsIoBadge.ps1 b/BuildHelpers/Public/Set-ShieldsIoBadge.ps1 new file mode 100644 index 0000000..12c4b1f --- /dev/null +++ b/BuildHelpers/Public/Set-ShieldsIoBadge.ps1 @@ -0,0 +1,90 @@ +function Set-ShieldsIoBadge { + <# + .SYNOPSIS + Modifies the link to a https://shields.io badge in a .md file. Can be used as part of a CI pipeline to update the status of + badges such as Code Coverage. + + .FUNCTIONALITY + CI/CD + + .DESCRIPTION + This cmdlet can be used to update the link to a https://shields.io badge that has been created in a file such as readme.md. + + To use this function You need to have initially added the badge to your readme.md or specified file by adding the following + string (ensuring 'Subject' matches what you specify for -Subject): + + ![Subject]() + + .PARAMETER Subject + The label to assign to the badge. Default 'Build'. + + .PARAMETER Status + The status text of value to assign to the badge. Default: 0. + + .PARAMETER Color + The color to assign to the badge. If status is set to 0 - 100 and this parameter is not specified, the color is set + automatically to either green, yellow, orange or red depending on the value, or light grey if it is not a 0 - 100 value. + + .PARAMETER AsPercentage + Switch: Use to add a percentage sign after whatever you provide for -Status. + + .PARAMETER Path + Path to the text file to update. By default this is $Env:BHProjectPath\Readme.md + + .EXAMPLE + Set-ShieldsIoBadge -Subject 'Coverage' -Status ([math]::floor(100 - (($PesterResults.CodeCoverage.NumberOfCommandsMissed / $PesterResults.CodeCoverage.NumberOfCommandsAnalyzed) * 100))) -AsPercentage + + .LINK + http://wragg.io/add-a-code-coverage-badge-to-your-powershell-deployment-pipeline/ + + .LINK + https://github.com/RamblingCookieMonster/BuildHelpers + + .LINK + about_BuildHelpers + #> + [cmdletbinding(supportsshouldprocess)] + param( + [string] + $Subject = 'Build', + + $Status = 0, + + [string] + $Color, + + [switch] + $AsPercentage, + + [string] + $Path = "$Env:BHProjectPath\Readme.md" + ) + Process + { + $Path = Get-FullPath $Path + + if (-not $Color) + { + $Color = switch ($Status) + { + {$_ -in 90..100 -or $_ -eq 'Pass'} { 'brightgreen' } + {$_ -in 75..89} { 'yellow' } + {$_ -in 60..74} { 'orange' } + {$_ -in 0..59 -or $_ -eq 'Fail'} { 'red' } + default { 'lightgrey' } + } + } + + if ($AsPercentage) + { + $Percent = '%25' + } + + if ($PSCmdlet.ShouldProcess($Path)) + { + $ReadmeContent = (Get-Content $Path) + $ReadmeContent = $ReadmeContent -replace "!\[$($Subject)\].+\)", "![$($Subject)](https://img.shields.io/badge/$Subject-$Status$Percent-$Color.svg)" + $ReadmeContent | Set-Content -Path $Path + } + } +} diff --git a/BuildHelpers/Public/Step-ModuleVersion.ps1 b/BuildHelpers/Public/Step-ModuleVersion.ps1 index 53f929d..618ec4a 100644 --- a/BuildHelpers/Public/Step-ModuleVersion.ps1 +++ b/BuildHelpers/Public/Step-ModuleVersion.ps1 @@ -5,24 +5,24 @@ Reads an existing Module Manifest file and increments the ModuleVersion property. .EXAMPLE C:\PS> Step-ModuleVersion -Path .\testmanifest.psd1 - + Will increment the Build section of the ModuleVersion .EXAMPLE C:\PS> Step-ModuleVersion -Path .\testmanifest.psd1 -By Minor - + Will increment the Minor section of the ModuleVersion and set the Build section to 0. .EXAMPLE C:\PS> Set-Location C:\source\testmanifest C:\PS> Step-ModuleVersion - + Will increment the Build section of the ModuleVersion of the manifest in the current working directory. .INPUTS String .NOTES - This function should only read the module and call Update-ModuleManifest with - the new Version, but there appears to be a bug in Update-ModuleManifest dealing - with Object[] types so this function manually de-serializes the manifest and + This function should only read the module and call Update-ModuleManifest with + the new Version, but there appears to be a bug in Update-ModuleManifest dealing + with Object[] types so this function manually de-serializes the manifest and calls New-ModuleManifest to overwrite the manifest at Path. .LINK http://semver.org/ @@ -42,7 +42,7 @@ function Step-ModuleVersion [ValidateScript({ Test-Path $_ -PathType Leaf })] [string[]] $Path, - + # Version section to step [Parameter(Position=1)] [ValidateSet("Major", "Minor", "Build","Patch")] @@ -56,9 +56,9 @@ function Step-ModuleVersion if (-not $PSBoundParameters.ContainsKey("Path")) { $Path = (Get-Item $PWD\*.psd1)[0] - } + } } - + Process { foreach ($file in $Path) @@ -68,12 +68,12 @@ function Step-ModuleVersion $manifest = Import-PowerShellDataFile -Path $file $newVersion = Step-Version $manifest.ModuleVersion $By $manifest.Remove("ModuleVersion") - + $manifest.FunctionsToExport = $manifest.FunctionsToExport | ForEach-Object {$_} $manifest.NestedModules = $manifest.NestedModules | ForEach-Object {$_} $manifest.RequiredModules = $manifest.RequiredModules | ForEach-Object {$_} $manifest.ModuleList = $manifest.ModuleList | ForEach-Object {$_} - + if ($manifest.ContainsKey("PrivateData") -and $manifest.PrivateData.ContainsKey("PSData")) { foreach ($node in $manifest.PrivateData["PSData"].GetEnumerator()) @@ -83,17 +83,17 @@ function Step-ModuleVersion { $value = $node.Value | ForEach-Object {$_} } - else + else { - $value = $node.Value + $value = $node.Value } - + $manifest[$key] = $value } $manifest.Remove("PrivateData") } - + New-ModuleManifest -Path $file -ModuleVersion $newVersion @manifest - } - } + } + } } diff --git a/BuildHelpers/Public/Step-Version.ps1 b/BuildHelpers/Public/Step-Version.ps1 index 06f6ab4..e98f462 100644 --- a/BuildHelpers/Public/Step-Version.ps1 +++ b/BuildHelpers/Public/Step-Version.ps1 @@ -7,18 +7,18 @@ .EXAMPLE C:\PS> Step-Version 1.1.1 1.1.2 - + Will increment the Patch/Build section of the Version .EXAMPLE C:\PS> Step-Version 1.1.1 Minor 1.2.0 - + Will increment the Minor section of the Version .EXAMPLE C:\PS> Step-Version 1.1.1 Major 2.0.0 - - Will increment the Major section of the Version + + Will increment the Major section of the Version .EXAMPLE C:\PS> $v = [version]"1.1.1" C:\PS> $v | Step-Version -Type Minor @@ -26,7 +26,7 @@ .INPUTS String .OUTPUTS - String + String .NOTES This function operates on strings. #> @@ -40,7 +40,7 @@ function Step-Version { Position=0)] [String] $Version, - + # Version section to step [Parameter(Position=1)] [ValidateSet("Major", "Minor", "Build","Patch")] @@ -52,11 +52,11 @@ function Step-Version { Process { $currentVersion = [version]$Version - + $major = $currentVersion.Major $minor = $currentVersion.Minor $build = $currentVersion.Build - + switch ($By) { "Major" { $major++ $minor = 0 @@ -68,10 +68,10 @@ function Step-Version { Default { $build++ break } } - + $newVersion = New-Object Version -ArgumentList $major, $minor, $build Write-Output -InputObject $newVersion.ToString() - } + } } diff --git a/BuildHelpers/Scripts/Set-BuildVariable.ps1 b/BuildHelpers/Scripts/Set-BuildVariable.ps1 index a3b6dc2..387a7b1 100644 --- a/BuildHelpers/Scripts/Set-BuildVariable.ps1 +++ b/BuildHelpers/Scripts/Set-BuildVariable.ps1 @@ -9,10 +9,10 @@ Normalize build system and project details into variables Creates the following variables: - BHProjectPath via Get-BuildVariables - BHBranchName via Get-BuildVariables - BHCommitMessage via Get-BuildVariables - BHBuildNumber via Get-BuildVariables + BHProjectPath via Get-BuildVariable + BHBranchName via Get-BuildVariable + BHCommitMessage via Get-BuildVariable + BHBuildNumber via Get-BuildVariable BHProjectName via Get-ProjectName BHPSModuleManifest via Get-PSModuleManifest BHModulePath via Split-Path on BHPSModuleManifest @@ -57,7 +57,7 @@ https://github.com/RamblingCookieMonster/BuildHelpers .LINK - Get-BuildVariables + Get-BuildVariable .LINK Get-ProjectName @@ -103,7 +103,7 @@ else } } -${Build.Vars} = Get-BuildVariables -Path $Path +${Build.Vars} = Get-BuildVariable -Path $Path ${Build.ProjectName} = Get-ProjectName -Path $Path ${Build.ManifestPath} = Get-PSModuleManifest -Path $Path $BuildHelpersVariables = @{ @@ -118,4 +118,4 @@ $BuildHelpersVariables = @{ } foreach ($VarName in $BuildHelpersVariables.Keys) { Set-Variable -Scope $Scope -Name ('{0}{1}' -f $VariableNamePrefix,$VarName) -Value $BuildHelpersVariables[$VarName] -} \ No newline at end of file +} diff --git a/BuildHelpers/en-US/about_BuildHelpers.help.txt b/BuildHelpers/en-US/about_BuildHelpers.help.txt index f2ed3e3..bb815ca 100755 --- a/BuildHelpers/en-US/about_BuildHelpers.help.txt +++ b/BuildHelpers/en-US/about_BuildHelpers.help.txt @@ -13,7 +13,7 @@ LONG DESCRIPTION DETAILED DESCRIPTION There are a few functions: - Get-BuildVariables: This looks at your current environment variables, and returns details on what build system you're using, the git branch, commit message, and more. + Get-BuildVariable: This looks at your current environment variables, and returns details on what build system you're using, the git branch, commit message, and more. Get-ProjectName: This looks at the current path, and tries to guess your project / module name based on common conventions. Set-BuildEnvironment: This calls other BuildHelper functions, and sets environment variables that you can use in your scripts. Set-BuildVariable: This calls other BuildHelper functions, and sets PowerShell variables in the calling or specified scope. diff --git a/README.md b/README.md index abea32a..b663199 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Pull requests and other contributions welcome! Get-Command -Module BuildHelpers # Get help - Get-Help Get-BuildVariables -Full + Get-Help Get-BuildVariable -Full Get-Help about_BuildHelpers ``` @@ -38,10 +38,10 @@ Pull requests and other contributions welcome! ### Get Normalized Build Variables ```powershell -Get-BuildVariables +Get-BuildVariable # We assume you're in the project root. If not, specify a path: -Get-BuildVariables -Path C:\MyProjectRoot +Get-BuildVariable -Path C:\MyProjectRoot ``` ### Get Project Name @@ -111,7 +111,7 @@ Here's an example, having run Set-BuildEnvironment in an AppVeyor project: During the module authoring process, updating FunctionsToExport can be tedious, so many folks leave this set to '*', missing out on module auto-loading and other benefits. -To get the best of both worlds, use FunctionsToExport='*', and use Set-ModuleFunctions in your build before deployment: +To get the best of both worlds, use FunctionsToExport='*', and use Set-ModuleFunction in your build before deployment: ```powershell # Set your build environment (we use this to get psd1 path) @@ -122,8 +122,8 @@ Select-String -Path .\PSSlack\PSSlack.psd1 -Pattern FunctionsToExport # PSSlack\PSSlack.psd1:61:FunctionsToExport = '*' -# Update the psd1 with Set-ModuleFunctions: -Set-ModuleFunctions +# Update the psd1 with Set-ModuleFunction: +Set-ModuleFunction # Check FunctionsToExport again: Select-String -Path .\PSSlack\PSSlack.psd1 -Pattern FunctionsToExport @@ -137,7 +137,7 @@ Typical examples take an existing PSD1 file and bump the module version from tha ```powershell # Get the latest version for a project -$Version = Get-NextPSGalleryVersion -Name $env:BHProjectName +$Version = Get-NextNugetPackageVersion -Name $env:BHProjectName # Update the module metadata with the new version - thanks to Joel Bennett for this function! Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value $Version @@ -145,4 +145,4 @@ Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value ## Notes -Thanks to Joel Bennett for the ConvertTo-Metadata function that we use in Set-ModuleFunctions! \ No newline at end of file +Thanks to Joel Bennett for the ConvertTo-Metadata function that we use in Set-ModuleFunction! diff --git a/Tests/BuildHelpers.Tests.ps1 b/Tests/BuildHelpers.Tests.ps1 index ad4e992..14b3ca8 100644 --- a/Tests/BuildHelpers.Tests.ps1 +++ b/Tests/BuildHelpers.Tests.ps1 @@ -11,6 +11,7 @@ $ModuleName = $ENV:BHProjectName } Import-Module $PSScriptRoot\..\$ModuleName -Force +Import-Module $PSScriptRoot\..\$ModuleName\Private\Modules\Configuration -Force Describe "$ModuleName PS$PSVersion" { Context 'Strict mode' { @@ -21,7 +22,7 @@ Describe "$ModuleName PS$PSVersion" { $Module = @( Get-Module $ModuleName ) $Module.Name -contains $ModuleName | Should be $True $Commands = $Module.ExportedCommands.Keys - $Commands -contains 'Get-BuildVariables' | Should Be $True + $Commands -contains 'Get-BuildVariable' | Should Be $True } } } @@ -51,142 +52,142 @@ Describe "Get-ProjectName PS$PSVersion" { } Describe 'Step-Version' { - Context 'By Param' { + Context 'By Param' { It 'Should increment the Patch level' { $result = Step-Version @Verbose 1.1.1 $result | Should Be 1.1.2 } - + It 'Should increment the Minor level and set Patch level to 0' { $result = Step-Version @Verbose 1.1.1 Minor $result | Should Be 1.2.0 - } - + } + It 'Should increment the Major level and set the Minor and Patch level to 0' { $result = Step-Version @Verbose 1.1.1 Major $result | Should Be 2.0.0 - } + } } - + Context 'By Pipeline' { It 'Should increment the Patch level' { $result = [version]"1.1.1" | Step-Version @Verbose $result | Should Be 1.1.2 } - + It 'Should increment the Minor level and set Patch level to 0' { $result = $result = [version]"1.1.1" | Step-Version @Verbose -By Minor $result | Should Be 1.2.0 - } - + } + It 'Should increment the Major level and set the Minor and Patch level to 0' { $result = $result = [version]"1.1.1" | Step-Version @Verbose -By Major $result | Should Be 2.0.0 - } + } } } Describe 'Step-ModuleVersion' { Context 'Basic Manifest' { - + New-Item -Path TestDrive:\ -Name testmanifest -ItemType Directory New-Item -Path TestDrive:\testmanifest -Name testmanifest.psm1 -ItemType File - + $manifestParams = @{Guid = New-Guid Author = "Name" RootModule = "testmanifest.psm1" ModuleVersion = "1.1.1" - Description = "A test module" + Description = "A test module" } - + New-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 @manifestParams Step-ModuleVersion @Verbose -Path TestDrive:\testmanifest\testmanifest.psd1 - $newManifest = Import-PowerShellDataFile @Verbose -Path TestDrive:\testmanifest\testmanifest.psd1 - + $newManifest = Import-PowerShellDataFile @Verbose -Path TestDrive:\testmanifest\testmanifest.psd1 + It 'Passes Test-ModuleManifest' { Test-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 $? | Should Be $true } - + It 'Should be at version 1.1.2' { $newManifest.ModuleVersion | Should Be 1.1.2 } - + It 'The other properties should be the same' { $newManifest.Guid | Should Be $manifestParams.Guid $newManifest.Author | Should Be $manifestParams.Author $newManifest.RootModule | Should Be $manifestParams.RootModule - $newManifest.Description | Should Be $manifestParams.Description + $newManifest.Description | Should Be $manifestParams.Description } } - + Context 'Basic Manifest in PWD' { - + New-Item -Path TestDrive:\ -Name testmanifest -ItemType Directory New-Item -Path TestDrive:\ -Name notamanifest.txt -ItemType File New-Item -Path TestDrive:\testmanifest -Name testmanifest.psm1 -ItemType File - + $manifestParams = @{Guid = New-Guid Author = "Name" RootModule = "testmanifest.psm1" ModuleVersion = "1.1.1" - Description = "A test module" + Description = "A test module" } - + New-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 @manifestParams Push-Location - Set-Location -Path TestDrive:\testmanifest\ - + Set-Location -Path TestDrive:\testmanifest\ + It 'Should be at version 1.1.2' { Step-ModuleVersion @Verbose - $newManifest = Import-PowerShellDataFile -Path TestDrive:\testmanifest\testmanifest.psd1 + $newManifest = Import-PowerShellDataFile -Path TestDrive:\testmanifest\testmanifest.psd1 $newManifest.ModuleVersion | Should Be 1.1.2 } Pop-Location - } - + } + Context 'Basic Manifest with Minor step' { - + New-Item -Path TestDrive:\ -Name testmanifest -ItemType Directory New-Item -Path TestDrive:\testmanifest -Name testmanifest.psm1 -ItemType File - + $manifestParams = @{Guid = New-Guid Author = "Name" RootModule = "testmanifest.psm1" ModuleVersion = "1.1.1" - Description = "A test module" + Description = "A test module" } - + New-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 @manifestParams Step-ModuleVersion @Verbose -Path TestDrive:\testmanifest\testmanifest.psd1 -By Minor - $newManifest = Import-PowerShellDataFile -Path TestDrive:\testmanifest\testmanifest.psd1 - + $newManifest = Import-PowerShellDataFile -Path TestDrive:\testmanifest\testmanifest.psd1 + It 'Passes Test-ModuleManifest' { Test-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 $? | Should Be $true } - + It 'Should be at version 1.2.0' { $newManifest.ModuleVersion | Should Be 1.2.0 } - + It 'The other properties should be the same' { $newManifest.Guid | Should Be $manifestParams.Guid $newManifest.Author | Should Be $manifestParams.Author $newManifest.RootModule | Should Be $manifestParams.RootModule - $newManifest.Description | Should Be $manifestParams.Description + $newManifest.Description | Should Be $manifestParams.Description } - } + } Context 'Complex Manifest' { - + New-Item -Path TestDrive:\ -Name testmanifest -ItemType Directory New-Item -Path TestDrive:\testmanifest -Name testmanifest.psm1 -ItemType File - + $manifestParams = @{Guid = New-Guid Author = "Name" RootModule = "testmanifest.psm1" @@ -201,40 +202,40 @@ Describe 'Step-ModuleVersion' { RequiredModules = @("ModuleA","ModuleB") ModuleList = @("ModuleX","ModuleY") } - + New-ModuleManifest -Path TestDrive:\testmanifest\testmanifest.psd1 @manifestParams Step-ModuleVersion @Verbose -Path TestDrive:\testmanifest\testmanifest.psd1 $newManifest = Import-PowerShellDataFile -Path TestDrive:\testmanifest\testmanifest.psd1 - + It 'Should be at version 1.1.2' { $newManifest.ModuleVersion | Should Be 1.1.2 } - + It 'Should have an properly formatted array for "FunctionsToExport"' { - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatchExactly "FunctionsToExport = 'Get-MyFunction', 'Set-MyFunction'" + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatchExactly "FunctionsToExport = 'Get-MyFunction', 'Set-MyFunction'" } - + It 'Should have an properly formatted array for "Tags"' { - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatchExactly "Tags = 'one', 'two', 'three'" - } + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatchExactly "Tags = 'one', 'two', 'three'" + } - It 'Should have an properly formatted array for "NestedModules"' { - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('NestedModules = @(''Module1'',')) - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape(" 'Module2')")) - } + It 'Should have an properly formatted array for "NestedModules"' { + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('NestedModules = @(''Module1'',')) + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape(" 'Module2')")) + } It 'Should have an properly formatted array for "RequiredModules"' { - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('RequiredModules = @(''ModuleA'',')) + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('RequiredModules = @(''ModuleA'',')) 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape(" 'ModuleB')")) - } - + } + It 'Should have an properly formatted array for "ModuleList"' { - 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('ModuleList = @(''ModuleX'',')) + 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape('ModuleList = @(''ModuleX'',')) 'TestDrive:\testmanifest\testmanifest.psd1' | Should -FileContentMatch ([regex]::Escape(" 'ModuleY')")) - } - + } + It 'The other properties should be the same' { $newManifest.Guid | Should Be $manifestParams.Guid $newManifest.Author | Should Be $manifestParams.Author @@ -256,7 +257,7 @@ Describe 'Get-GitChangedFile' { # @($Output).count | Should BeGreaterThan 0 # Test-Path @($Output)[0] | Should Be $true # } - + It 'Should find files changed in a specified commit in this repo' { $Output = Get-GitChangedFile -Commit 01b3931e6ed5d3d16cbcae25fcf98d185c1375b7 -ErrorAction SilentlyContinue -Include README* @($Output).count | Should Be 1 @@ -285,8 +286,15 @@ Describe 'Invoke-Git' { } } -Describe 'Get-ModuleFunctions' { +Describe 'Get-ModuleFunction' { Context 'dummymodule' { + It 'Should return the functions output by a module' { + $Functions = Get-ModuleFunction -Name $PSScriptRoot\TestData\dummymodule + $Functions.Count | Should be 3 + 'a', 'b', 'c' | Foreach { + $Functions -contains $_ | Should Be $True + } + } It 'Should return the functions output by a module' { $Functions = Get-ModuleFunctions -Name $PSScriptRoot\TestData\dummymodule $Functions.Count | Should be 3 @@ -297,13 +305,13 @@ Describe 'Get-ModuleFunctions' { } } -Describe 'Set-ModuleFunctions' { +Describe 'Set-ModuleFunction' { Context 'dummymodule' { $dummydir = ( mkdir $PSScriptRoot\TestData\dummymodule ).FullName Copy-item $PSScriptRoot\TestData\dummymodule.psd1 $dummydir -Confirm:$False Copy-item $PSScriptRoot\TestData\dummymodule.psm1 $dummydir -Confirm:$False It 'Should update the module manifest with exported functions' { - Set-ModuleFunctions -Name $dummydir + Set-ModuleFunction -Name $dummydir $Functions = Get-Metadata $dummydir\dummymodule.psd1 -PropertyName FunctionsToExport $Functions.Count | Should be 3 'a', 'b', 'c' | Foreach { @@ -313,3 +321,113 @@ Describe 'Set-ModuleFunctions' { Remove-Item $dummydir -Force -Confirm:$False -Recurse } } + +Describe 'Set-ModuleFormat' { + Context 'Can set FormatsToProcess with an array of *.ps1xml files' { + $dummydir = ( mkdir $PSScriptRoot\TestData\dummymodule ).FullName + Copy-item $PSScriptRoot\TestData\dummymodule.psd1 $dummydir -Confirm:$False + Copy-item $PSScriptRoot\TestData\dummymodule.psm1 $dummydir -Confirm:$False + + $dummyFormatsDir = Join-Path $dummydir Formats + New-Item $dummyFormatsDir -ItemType Directory + New-Item (Join-Path $dummyFormatsDir dummymodule-format1.format.ps1xml) -ItemType File | Out-Null + New-Item (Join-Path $dummyFormatsDir dummymodule-format2.format.ps1xml) -ItemType File | Out-Null + + It 'Should update the module manifest with formats to process' { + $FormatsToProcessFiles = Get-ChildItem $dummyFormatsDir\*.ps1xml | Foreach { + Join-Path .\Formats $_.Name + } + Set-ModuleFormat -Name $dummydir -FormatsToProcess $FormatsToProcessFiles + $FormatsToProcess = Get-Metadata $dummydir\dummymodule.psd1 -PropertyName FormatsToProcess + $FormatsToProcess.Count | Should be 2 + ".\Formats\dummymodule-format1.format.ps1xml", ".\Formats\dummymodule-format2.format.ps1xml" | Foreach { + $FormatsToProcess -contains $_ | Should Be $True + } + } + + Remove-Item $dummydir -Force -Confirm:$False -Recurse + } + + Context 'Can set FormatsToProcess using a relative path containing *.ps1xml type files' { + $dummydir = ( mkdir $PSScriptRoot\TestData\dummymodule ).FullName + Copy-item $PSScriptRoot\TestData\dummymodule.psd1 $dummydir -Confirm:$False + Copy-item $PSScriptRoot\TestData\dummymodule.psm1 $dummydir -Confirm:$False + + $dummyFormatsDir = Join-Path $dummydir Formats + New-Item $dummyFormatsDir -ItemType Directory + New-Item (Join-Path $dummyFormatsDir dummymodule-format1.format.ps1xml) -ItemType File | Out-Null + New-Item (Join-Path $dummyFormatsDir dummymodule-format2.format.ps1xml) -ItemType File | Out-Null + + It 'Should update the module manifest with formats to process' { + Set-ModuleFormat -Name $dummydir -FormatsRelativePath .\Formats + $FormatsToProcess = Get-Metadata $dummydir\dummymodule.psd1 -PropertyName FormatsToProcess + $FormatsToProcess.Count | Should be 2 + ".\Formats\dummymodule-format1.format.ps1xml", ".\Formats\dummymodule-format2.format.ps1xml" | Foreach { + $FormatsToProcess -contains $_ | Should Be $True + } + } + + Remove-Item $dummydir -Force -Confirm:$False -Recurse + } +} + +Describe 'Set-ModuleType' { + Context 'Can set TypesToProcess with an array of *.ps1xml files' { + $dummydir = ( mkdir $PSScriptRoot\TestData\dummymodule ).FullName + Copy-item $PSScriptRoot\TestData\dummymodule.psd1 $dummydir -Confirm:$False + Copy-item $PSScriptRoot\TestData\dummymodule.psm1 $dummydir -Confirm:$False + + $dummyTypesDir = Join-Path $dummydir Types + New-Item $dummyTypesDir -ItemType Directory + New-Item (Join-Path $dummyTypesDir dummymodule-types1.types.ps1xml) -ItemType File | Out-Null + New-Item (Join-Path $dummyTypesDir dummymodule-types2.types.ps1xml) -ItemType File | Out-Null + + It 'Should update the module manifest with types to process' { + $TypesToProcessFiles = Get-ChildItem $dummyTypesDir\*.ps1xml | Foreach { + Join-Path .\Types $_.Name + } + Set-ModuleType -Name $dummydir -TypesToProcess $TypesToProcessFiles + $TypesToProcess = Get-Metadata $dummydir\dummymodule.psd1 -PropertyName TypesToProcess + $TypesToProcess.Count | Should be 2 + ".\Types\dummymodule-types1.types.ps1xml", ".\Types\dummymodule-types1.types.ps1xml" | Foreach { + $TypesToProcess -contains $_ | Should Be $True + } + } + + Remove-Item $dummydir -Force -Confirm:$False -Recurse + } + + Context 'Can set TypesToProcess using a relative path containing *.ps1xml type files' { + $dummydir = ( mkdir $PSScriptRoot\TestData\dummymodule ).FullName + Copy-item $PSScriptRoot\TestData\dummymodule.psd1 $dummydir -Confirm:$False + Copy-item $PSScriptRoot\TestData\dummymodule.psm1 $dummydir -Confirm:$False + + $dummyTypesDir = Join-Path $dummydir Types + New-Item $dummyTypesDir -ItemType Directory + New-Item (Join-Path $dummyTypesDir dummymodule-types1.types.ps1xml) -ItemType File | Out-Null + New-Item (Join-Path $dummyTypesDir dummymodule-types2.types.ps1xml) -ItemType File | Out-Null + + It 'Should update the module manifest with types to process' { + Set-ModuleType -Name $dummydir -TypesRelativePath .\Types + $TypesToProcess = Get-Metadata $dummydir\dummymodule.psd1 -PropertyName TypesToProcess + $TypesToProcess.Count | Should be 2 + ".\Types\dummymodule-types1.types.ps1xml", ".\Types\dummymodule-types1.types.ps1xml" | Foreach { + $TypesToProcess -contains $_ | Should Be $True + } + } + + Remove-Item $dummydir -Force -Confirm:$False -Recurse + } +} + +Describe 'Set-ShieldsIoBadge' { + Context 'dummy readme.md' { + Set-Content -Path TestDrive:\readme.md -Value '![coverage]()' + + Set-ShieldsIoBadge -Subject 'coverage' -Status 75 -AsPercentage -Path TestDrive:\readme.md + + It 'Should update the dummy readme.md with code coverage' { + Get-Content TestDrive:\readme.md | Should Be '![coverage](https://img.shields.io/badge/coverage-75%25-yellow.svg)' + } + } +} diff --git a/Tests/TestData/dummymodule.psd1 b/Tests/TestData/dummymodule.psd1 index 0db89d6..c7f16c4 100644 --- a/Tests/TestData/dummymodule.psd1 +++ b/Tests/TestData/dummymodule.psd1 @@ -49,10 +49,10 @@ PowerShellVersion = '3.0' # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module -# TypesToProcess = @() +TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module -#FormatsToProcess = '.Format.ps1xml' +FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @()