From 9754a15374428b87724281710358ec2b2cdbb688 Mon Sep 17 00:00:00 2001 From: Rob Reynolds Date: Tue, 18 Apr 2017 18:11:03 -0500 Subject: [PATCH 01/10] (GH-72) PowerShell scripts in format for signing PowerShell can not validate authenticode signatures for files that are UTF8 without BOM, nor can they for files with LF line endings as signatures end up creating mixed mode files. For those reasons, the files need to be UTF-8 with a BOM and Windows line endings (CRLF). --- .../cChocoInstaller/cChocoInstaller.psm1 | 390 ++++++------ .../cChocoPackageInstall.psm1 | 582 +++++++++--------- .../cChocoPackageInstallerSet.schema.psm1 | 86 +-- DSCResources/cChocoSource/cChocoSource.psm1 | 344 +++++------ cChoco.psd1 | 2 +- 5 files changed, 702 insertions(+), 702 deletions(-) diff --git a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 index 1ca852a..3ddf918 100644 --- a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 +++ b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 @@ -1,195 +1,195 @@ -function Get-TargetResource -{ - [OutputType([hashtable])] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $InstallDir, - [parameter()] - [string] - $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' - ) - Write-Verbose 'Start Get-TargetResource' - - #Needs to return a hashtable that returns the current status of the configuration component - $Configuration = @{ - InstallDir = $env:ChocolateyInstall - ChocoInstallScriptUrl = $ChocoInstallScriptUrl - } - - Return $Configuration -} - -function Set-TargetResource -{ - [CmdletBinding(SupportsShouldProcess)] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $InstallDir, - - [parameter()] - [string] - $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' - ) - Write-Verbose 'Start Set-TargetResource' - $whatIfShouldProcess = $pscmdlet.ShouldProcess('Chocolatey', 'Download and Install') - if ($whatIfShouldProcess) { - Install-Chocolatey @PSBoundParameters - } -} - -function Test-TargetResource -{ - [OutputType([bool])] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $InstallDir, - [parameter()] - [string] - $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' - ) - - Write-Verbose 'Test-TargetResource' - if (-not (Test-ChocoInstalled)) - { - Write-Verbose 'Choco is not installed, calling set' - Return $false - } - - ##Test to see if the Install Directory is correct. - $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') - if(-not ($InstallDir -eq $env:ChocolateyInstall)) - { - Write-Verbose "Choco should be installed in $InstallDir but is installed to $env:ChocolateyInstall calling set" - Return $false - } - - Return $true -} - -function Test-ChocoInstalled -{ - Write-Verbose 'Test-ChocoInstalled' - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - - Write-Verbose "Env:Path contains: $env:Path" - if (Test-Command -command choco) - { - Write-Verbose 'YES - Choco is Installed' - return $true - } - - Write-Verbose "NO - Choco is not Installed" - return $false -} - -Function Test-Command -{ - Param ( - [string]$command = 'choco' - ) - Write-Verbose "Test-Command $command" - if (Get-Command -Name $command -ErrorAction SilentlyContinue) { - Write-Verbose "$command exists" - return $true - } else { - Write-Verbose "$command does NOT exist" - return $false - } -} - -#region - chocolately installer work arounds. Main issue is use of write-host -function global:Write-Host -{ - Param( - [Parameter(Mandatory,Position = 0)] - $Object, - [Switch] - $NoNewLine, - [ConsoleColor] - $ForegroundColor, - [ConsoleColor] - $BackgroundColor - ) - #Redirecting Write-Host -> Write-Verbose. - Write-Verbose $Object -} -#endregion - -function Get-FileDownload { - param ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string]$url, - - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string]$file - ) - # Set security protocol preference to avoid the download error if the machine has disabled TLS 1.0 and SSLv3 - # See: https://chocolatey.org/install (Installing With Restricted TLS section) - # Since cChoco requires at least PowerShell 4.0, we have .NET 4.5 available, so we can use [System.Net.SecurityProtocolType] enum values by name. - $securityProtocolSettingsOriginal = [System.Net.ServicePointManager]::SecurityProtocol - [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls -bor [System.Net.SecurityProtocolType]::Ssl3 - - Write-Verbose "Downloading $url to $file" - $downloader = new-object -TypeName System.Net.WebClient - $downloader.DownloadFile($url, $file) - - [System.Net.ServicePointManager]::SecurityProtocol = $securityProtocolSettingsOriginal -} - -Function Install-Chocolatey { - [CmdletBinding()] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $InstallDir, - - [parameter()] - [string] - $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' - ) - Write-Verbose 'Install-Chocolatey' - - #Create install directory if it does not exist - If(-not (Test-Path -Path $InstallDir)) { - Write-Verbose "[ChocoInstaller] Creating $InstallDir" - New-Item -Path $InstallDir -ItemType Directory - } - - #Set permanent EnvironmentVariable - Write-Verbose 'Setting ChocolateyInstall environment variables' - [Environment]::SetEnvironmentVariable('ChocolateyInstall', $InstallDir, [EnvironmentVariableTarget]::Machine) - $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') - Write-Verbose "Env:ChocolateyInstall has $env:ChocolateyInstall" - - #Download an execute install script - $file = Join-Path -Path $InstallDir -ChildPath 'install.ps1' - Get-FileDownload -url $ChocoInstallScriptUrl -file $file - . $file - - #refresh after install - Write-Verbose 'Adding Choco to path' - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - if ($env:path -notlike "*$InstallDir*") { - $env:Path += ";$InstallDir" - } - - Write-Verbose "Env:Path has $env:path" - #InstallChoco $InstallDir - $Null = Choco - Write-Verbose 'Finish InstallChoco' -} - -Export-ModuleMember -Function *-TargetResource +function Get-TargetResource +{ + [OutputType([hashtable])] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $InstallDir, + [parameter()] + [string] + $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' + ) + Write-Verbose 'Start Get-TargetResource' + + #Needs to return a hashtable that returns the current status of the configuration component + $Configuration = @{ + InstallDir = $env:ChocolateyInstall + ChocoInstallScriptUrl = $ChocoInstallScriptUrl + } + + Return $Configuration +} + +function Set-TargetResource +{ + [CmdletBinding(SupportsShouldProcess)] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $InstallDir, + + [parameter()] + [string] + $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' + ) + Write-Verbose 'Start Set-TargetResource' + $whatIfShouldProcess = $pscmdlet.ShouldProcess('Chocolatey', 'Download and Install') + if ($whatIfShouldProcess) { + Install-Chocolatey @PSBoundParameters + } +} + +function Test-TargetResource +{ + [OutputType([bool])] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $InstallDir, + [parameter()] + [string] + $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' + ) + + Write-Verbose 'Test-TargetResource' + if (-not (Test-ChocoInstalled)) + { + Write-Verbose 'Choco is not installed, calling set' + Return $false + } + + ##Test to see if the Install Directory is correct. + $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') + if(-not ($InstallDir -eq $env:ChocolateyInstall)) + { + Write-Verbose "Choco should be installed in $InstallDir but is installed to $env:ChocolateyInstall calling set" + Return $false + } + + Return $true +} + +function Test-ChocoInstalled +{ + Write-Verbose 'Test-ChocoInstalled' + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + + Write-Verbose "Env:Path contains: $env:Path" + if (Test-Command -command choco) + { + Write-Verbose 'YES - Choco is Installed' + return $true + } + + Write-Verbose "NO - Choco is not Installed" + return $false +} + +Function Test-Command +{ + Param ( + [string]$command = 'choco' + ) + Write-Verbose "Test-Command $command" + if (Get-Command -Name $command -ErrorAction SilentlyContinue) { + Write-Verbose "$command exists" + return $true + } else { + Write-Verbose "$command does NOT exist" + return $false + } +} + +#region - chocolately installer work arounds. Main issue is use of write-host +function global:Write-Host +{ + Param( + [Parameter(Mandatory,Position = 0)] + $Object, + [Switch] + $NoNewLine, + [ConsoleColor] + $ForegroundColor, + [ConsoleColor] + $BackgroundColor + ) + #Redirecting Write-Host -> Write-Verbose. + Write-Verbose $Object +} +#endregion + +function Get-FileDownload { + param ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$url, + + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string]$file + ) + # Set security protocol preference to avoid the download error if the machine has disabled TLS 1.0 and SSLv3 + # See: https://chocolatey.org/install (Installing With Restricted TLS section) + # Since cChoco requires at least PowerShell 4.0, we have .NET 4.5 available, so we can use [System.Net.SecurityProtocolType] enum values by name. + $securityProtocolSettingsOriginal = [System.Net.ServicePointManager]::SecurityProtocol + [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls -bor [System.Net.SecurityProtocolType]::Ssl3 + + Write-Verbose "Downloading $url to $file" + $downloader = new-object -TypeName System.Net.WebClient + $downloader.DownloadFile($url, $file) + + [System.Net.ServicePointManager]::SecurityProtocol = $securityProtocolSettingsOriginal +} + +Function Install-Chocolatey { + [CmdletBinding()] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $InstallDir, + + [parameter()] + [string] + $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' + ) + Write-Verbose 'Install-Chocolatey' + + #Create install directory if it does not exist + If(-not (Test-Path -Path $InstallDir)) { + Write-Verbose "[ChocoInstaller] Creating $InstallDir" + New-Item -Path $InstallDir -ItemType Directory + } + + #Set permanent EnvironmentVariable + Write-Verbose 'Setting ChocolateyInstall environment variables' + [Environment]::SetEnvironmentVariable('ChocolateyInstall', $InstallDir, [EnvironmentVariableTarget]::Machine) + $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') + Write-Verbose "Env:ChocolateyInstall has $env:ChocolateyInstall" + + #Download an execute install script + $file = Join-Path -Path $InstallDir -ChildPath 'install.ps1' + Get-FileDownload -url $ChocoInstallScriptUrl -file $file + . $file + + #refresh after install + Write-Verbose 'Adding Choco to path' + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + if ($env:path -notlike "*$InstallDir*") { + $env:Path += ";$InstallDir" + } + + Write-Verbose "Env:Path has $env:path" + #InstallChoco $InstallDir + $Null = Choco + Write-Verbose 'Finish InstallChoco' +} + +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 index faab8ba..85b0363 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -1,198 +1,198 @@ -function Get-TargetResource -{ - [OutputType([hashtable])] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $Name, - [ValidateNotNullOrEmpty()] - [string] - $Params, - [ValidateNotNullOrEmpty()] - [string] - $Version, - [ValidateNotNullOrEmpty()] - [string] - $Source - ) - - Write-Verbose -Message 'Start Get-TargetResource' - - if (-Not (Test-ChocoInstalled)) { - throw "cChocoPackageInstall requires Chocolatey to be installed, consider using cChocoInstaller with 'dependson' in dsc config" - } - - #Needs to return a hashtable that returns the current - #status of the configuration component - $Configuration = @{ - Name = $Name - Params = $Params - Version = $Version - Source = $Source - } - - return $Configuration -} - -function Set-TargetResource -{ - [CmdletBinding(SupportsShouldProcess)] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $Name, - [ValidateSet('Present','Absent')] - [string] - $Ensure='Present', - [ValidateNotNullOrEmpty()] - [string] - $Params, - [ValidateNotNullOrEmpty()] - [string] - $Version, - [ValidateNotNullOrEmpty()] - [string] +function Get-TargetResource +{ + [OutputType([hashtable])] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $Name, + [ValidateNotNullOrEmpty()] + [string] + $Params, + [ValidateNotNullOrEmpty()] + [string] + $Version, + [ValidateNotNullOrEmpty()] + [string] + $Source + ) + + Write-Verbose -Message 'Start Get-TargetResource' + + if (-Not (Test-ChocoInstalled)) { + throw "cChocoPackageInstall requires Chocolatey to be installed, consider using cChocoInstaller with 'dependson' in dsc config" + } + + #Needs to return a hashtable that returns the current + #status of the configuration component + $Configuration = @{ + Name = $Name + Params = $Params + Version = $Version + Source = $Source + } + + return $Configuration +} + +function Set-TargetResource +{ + [CmdletBinding(SupportsShouldProcess)] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $Name, + [ValidateSet('Present','Absent')] + [string] + $Ensure='Present', + [ValidateNotNullOrEmpty()] + [string] + $Params, + [ValidateNotNullOrEmpty()] + [string] + $Version, + [ValidateNotNullOrEmpty()] + [string] $Source, [String] - $chocoParams, + $chocoParams, [bool] - $AutoUpgrade = $false - ) - Write-Verbose -Message 'Start Set-TargetResource' - - if (-Not (Test-ChocoInstalled)) { - throw "cChocoPackageInstall requires Chocolatey to be installed, consider using cChocoInstaller with 'dependson' in dsc config" - } - - $isInstalled = IsPackageInstalled -pName $Name - - #Uninstall if Ensure is set to absent and the package is installed - if ($isInstalled) { - if ($Ensure -eq 'Absent') { - $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Remove Chocolatey package') - if ($whatIfShouldProcess) { - Write-Verbose -Message "Removing $Name as ensure is set to absent" - UninstallPackage -pName $Name -pParams $Params - } - } else { - $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Installing / upgrading package from Chocolatey') - if ($whatIfShouldProcess) { - if ($Version) { - Write-Verbose -Message "Uninstalling $Name due to version mis-match" - UninstallPackage -pName $Name -pParams $Params - Write-Verbose -Message "Re-Installing $Name with correct version $version" - InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams - } elseif ($AutoUpgrade) { - Write-Verbose -Message "Upgrading $Name due to version mis-match" - Upgrade-Package -pName $Name -pParams $Params - } - } - } - } else { - $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Install package from Chocolatey') - if ($whatIfShouldProcess) { - InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams - } - } -} - -function Test-TargetResource -{ - [CmdletBinding(SupportsShouldProcess)] - [OutputType([bool])] - param - ( - [parameter(Mandatory)] - [ValidateNotNullOrEmpty()] - [string] - $Name, - [ValidateSet('Present','Absent')] - [string] - $Ensure='Present', - [ValidateNotNullOrEmpty()] - [string] - $Params, - [ValidateNotNullOrEmpty()] - [string] - $Version, - [ValidateNotNullOrEmpty()] - [string] + $AutoUpgrade = $false + ) + Write-Verbose -Message 'Start Set-TargetResource' + + if (-Not (Test-ChocoInstalled)) { + throw "cChocoPackageInstall requires Chocolatey to be installed, consider using cChocoInstaller with 'dependson' in dsc config" + } + + $isInstalled = IsPackageInstalled -pName $Name + + #Uninstall if Ensure is set to absent and the package is installed + if ($isInstalled) { + if ($Ensure -eq 'Absent') { + $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Remove Chocolatey package') + if ($whatIfShouldProcess) { + Write-Verbose -Message "Removing $Name as ensure is set to absent" + UninstallPackage -pName $Name -pParams $Params + } + } else { + $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Installing / upgrading package from Chocolatey') + if ($whatIfShouldProcess) { + if ($Version) { + Write-Verbose -Message "Uninstalling $Name due to version mis-match" + UninstallPackage -pName $Name -pParams $Params + Write-Verbose -Message "Re-Installing $Name with correct version $version" + InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams + } elseif ($AutoUpgrade) { + Write-Verbose -Message "Upgrading $Name due to version mis-match" + Upgrade-Package -pName $Name -pParams $Params + } + } + } + } else { + $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Install package from Chocolatey') + if ($whatIfShouldProcess) { + InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams + } + } +} + +function Test-TargetResource +{ + [CmdletBinding(SupportsShouldProcess)] + [OutputType([bool])] + param + ( + [parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] + $Name, + [ValidateSet('Present','Absent')] + [string] + $Ensure='Present', + [ValidateNotNullOrEmpty()] + [string] + $Params, + [ValidateNotNullOrEmpty()] + [string] + $Version, + [ValidateNotNullOrEmpty()] + [string] $Source, [ValidateNotNullOrEmpty()] [String] - $chocoParams, + $chocoParams, [bool] - $AutoUpgrade = $false - ) - - Write-Verbose -Message 'Start Test-TargetResource' - - if (-Not (Test-ChocoInstalled)) { - return $false - } - - $isInstalled = IsPackageInstalled -pName $Name - - if ($ensure -eq 'Absent') { - if ($isInstalled -eq $false) { - return $true - } else { - return $false - } - } - - if ($version) { - Write-Verbose -Message "Checking if $Name is installed and if version matches $version" - $result = IsPackageInstalled -pName $Name -pVersion $Version - } else { - Write-Verbose -Message "Checking if $Name is installed" - - if ($AutoUpgrade -and $isInstalled) { - $result = Test-LatestVersionInstalled -pName $Name - } else { - $result = $isInstalled - } + $AutoUpgrade = $false + ) + + Write-Verbose -Message 'Start Test-TargetResource' + + if (-Not (Test-ChocoInstalled)) { + return $false + } + + $isInstalled = IsPackageInstalled -pName $Name + + if ($ensure -eq 'Absent') { + if ($isInstalled -eq $false) { + return $true + } else { + return $false + } + } + + if ($version) { + Write-Verbose -Message "Checking if $Name is installed and if version matches $version" + $result = IsPackageInstalled -pName $Name -pVersion $Version + } else { + Write-Verbose -Message "Checking if $Name is installed" + + if ($AutoUpgrade -and $isInstalled) { + $result = Test-LatestVersionInstalled -pName $Name + } else { + $result = $isInstalled + } } - - Return $result -} -function Test-ChocoInstalled -{ - Write-Verbose -Message 'Test-ChocoInstalled' - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - - Write-Verbose -Message "Env:Path contains: $env:Path" - if (Test-Command -command choco) - { - Write-Verbose -Message 'YES - Choco is Installed' - return $true - } - - Write-Verbose -Message 'NO - Choco is not Installed' - return $false -} - -Function Test-Command -{ + + Return $result +} +function Test-ChocoInstalled +{ + Write-Verbose -Message 'Test-ChocoInstalled' + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + + Write-Verbose -Message "Env:Path contains: $env:Path" + if (Test-Command -command choco) + { + Write-Verbose -Message 'YES - Choco is Installed' + return $true + } + + Write-Verbose -Message 'NO - Choco is not Installed' + return $false +} + +Function Test-Command +{ [CmdletBinding()] - [OutputType([bool])] - Param ( - [string]$command = 'choco' - ) - Write-Verbose -Message "Test-Command $command" - if (Get-Command -Name $command -ErrorAction SilentlyContinue) { - Write-Verbose -Message "$command exists" - return $true - } else { - Write-Verbose -Message "$command does NOT exist" - return $false - } -} - + [OutputType([bool])] + Param ( + [string]$command = 'choco' + ) + Write-Verbose -Message "Test-Command $command" + if (Get-Command -Name $command -ErrorAction SilentlyContinue) { + Write-Verbose -Message "$command exists" + return $true + } else { + Write-Verbose -Message "$command does NOT exist" + return $false + } +} + function InstallPackage { [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingInvokeExpression','')] @@ -226,108 +226,108 @@ function InstallPackage #refresh path varaible in powershell, as choco doesn"t, to pull in git $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') -} - -function UninstallPackage -{ - param( - [Parameter(Position=0,Mandatory)] - [string]$pName, - [Parameter(Position=1)] - [string]$pParams - ) - - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - - #Todo: Refactor - if (-not ($pParams)) - { - Write-Verbose -Message 'Uninstalling Package Standard' - $packageUninstallOuput = choco uninstall $pName -y - } - elseif ($pParams) - { - Write-Verbose -Message "Uninstalling Package with params $pParams" - $packageUninstallOuput = choco uninstall $pName --params="$pParams" -y - } - - - Write-Verbose -Message "Package uninstall output $packageUninstallOuput " - - #refresh path varaible in powershell, as choco doesn"t, to pull in git - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') -} - - -function IsPackageInstalled -{ - param( - [Parameter(Position=0,Mandatory)][string]$pName, - [Parameter(Position=1)][string]$pVersion - ) - Write-Verbose -Message "Start IsPackageInstalled $pName" - - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - Write-Verbose -Message "Path variables: $env:Path" - - $installedPackages = Get-ChocoInstalledPackage - - if ($pVersion) { - Write-Verbose 'Comparing version' - $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName -and $_.Version -eq $pVersion} - } else { - Write-Verbose "Finding packages -eq $pName" - $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName} - } - - $count = @($installedPackages).Count - Write-Verbose "Found $Count matching packages" - if ($Count -gt 0) - { - $installedPackages | ForEach-Object {Write-Verbose -Message "Found: $($_.Name) with version $($_.Version)"} - return $true - } - - return $false -} - -Function Test-LatestVersionInstalled { - param( - [Parameter(Position=0,Mandatory)] - [string]$pName - ) - Write-Verbose -Message "Testing if $pName can be upgraded" - - $queryres = choco upgrade $pName --noop | Select-String -Pattern $pName - $queryres | ForEach-Object {Write-Verbose -Message $_} - - if ($queryres -match "$pName.*is the latest version available based on your source") { - return $true - } - return $false -} - -##region - chocolately installer work arounds. Main issue is use of write-host -##attempting to work around the issues with Chocolatey calling Write-host in its scripts. -function global:Write-Host -{ - Param( - [Parameter(Mandatory, Position = 0)] - [Object] - $Object, - [Switch] - $NoNewLine, - [ConsoleColor] - $ForegroundColor, - [ConsoleColor] - $BackgroundColor - - ) - - #Override default Write-Host... - Write-Verbose -Message $Object -} - +} + +function UninstallPackage +{ + param( + [Parameter(Position=0,Mandatory)] + [string]$pName, + [Parameter(Position=1)] + [string]$pParams + ) + + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + + #Todo: Refactor + if (-not ($pParams)) + { + Write-Verbose -Message 'Uninstalling Package Standard' + $packageUninstallOuput = choco uninstall $pName -y + } + elseif ($pParams) + { + Write-Verbose -Message "Uninstalling Package with params $pParams" + $packageUninstallOuput = choco uninstall $pName --params="$pParams" -y + } + + + Write-Verbose -Message "Package uninstall output $packageUninstallOuput " + + #refresh path varaible in powershell, as choco doesn"t, to pull in git + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') +} + + +function IsPackageInstalled +{ + param( + [Parameter(Position=0,Mandatory)][string]$pName, + [Parameter(Position=1)][string]$pVersion + ) + Write-Verbose -Message "Start IsPackageInstalled $pName" + + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + Write-Verbose -Message "Path variables: $env:Path" + + $installedPackages = Get-ChocoInstalledPackage + + if ($pVersion) { + Write-Verbose 'Comparing version' + $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName -and $_.Version -eq $pVersion} + } else { + Write-Verbose "Finding packages -eq $pName" + $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName} + } + + $count = @($installedPackages).Count + Write-Verbose "Found $Count matching packages" + if ($Count -gt 0) + { + $installedPackages | ForEach-Object {Write-Verbose -Message "Found: $($_.Name) with version $($_.Version)"} + return $true + } + + return $false +} + +Function Test-LatestVersionInstalled { + param( + [Parameter(Position=0,Mandatory)] + [string]$pName + ) + Write-Verbose -Message "Testing if $pName can be upgraded" + + $queryres = choco upgrade $pName --noop | Select-String -Pattern $pName + $queryres | ForEach-Object {Write-Verbose -Message $_} + + if ($queryres -match "$pName.*is the latest version available based on your source") { + return $true + } + return $false +} + +##region - chocolately installer work arounds. Main issue is use of write-host +##attempting to work around the issues with Chocolatey calling Write-host in its scripts. +function global:Write-Host +{ + Param( + [Parameter(Mandatory, Position = 0)] + [Object] + $Object, + [Switch] + $NoNewLine, + [ConsoleColor] + $ForegroundColor, + [ConsoleColor] + $BackgroundColor + + ) + + #Override default Write-Host... + Write-Verbose -Message $Object +} + Function Upgrade-Package { [Diagnostics.CodeAnalysis.SuppressMessage('PSUseApprovedVerbs','')] [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingInvokeExpression','')] @@ -361,7 +361,7 @@ Function Upgrade-Package { $packageUpgradeOuput = Invoke-Expression -Command $cmd $packageUpgradeOuput | ForEach-Object { Write-Verbose -Message $_ } } - + function Get-ChocoInstalledPackage { $res = choco list -lo | ForEach-Object { $Obj = $_ -split '\s' @@ -371,6 +371,6 @@ function Get-ChocoInstalledPackage { } } Return $res -} - +} + Export-ModuleMember -Function *-TargetResource \ No newline at end of file diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 index a70d55e..f160a71 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 @@ -1,43 +1,43 @@ -Configuration cChocoPackageInstallerSet -{ -<# -.SYNOPSIS -Composite DSC Resource allowing you to specify multiple choco packages in a single resource block. -#> - [CmdletBinding(SupportsShouldProcess=$true)] - param - ( - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String[]] - $Name, - [ValidateSet('Present','Absent')] - [System.String] - $Ensure='Present', - [parameter(Mandatory = $false)] - [ValidateNotNullOrEmpty()] - [System.String] - $Source - ) - - $addSource = $Source - - foreach ($pName in $Name) { - ## We only need to specify the source one time, - ## so we do it only with the first package - if ($addSource) { - cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { - Ensure = $Ensure - Name = $pName - Source = $Source - } - $addSource = $null - } - else { - cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { - Ensure = $Ensure - Name = $pName - } - } - } -} +Configuration cChocoPackageInstallerSet +{ +<# +.SYNOPSIS +Composite DSC Resource allowing you to specify multiple choco packages in a single resource block. +#> + [CmdletBinding(SupportsShouldProcess=$true)] + param + ( + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String[]] + $Name, + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present', + [parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [System.String] + $Source + ) + + $addSource = $Source + + foreach ($pName in $Name) { + ## We only need to specify the source one time, + ## so we do it only with the first package + if ($addSource) { + cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { + Ensure = $Ensure + Name = $pName + Source = $Source + } + $addSource = $null + } + else { + cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { + Ensure = $Ensure + Name = $pName + } + } + } +} diff --git a/DSCResources/cChocoSource/cChocoSource.psm1 b/DSCResources/cChocoSource/cChocoSource.psm1 index 7d0d90b..127d216 100644 --- a/DSCResources/cChocoSource/cChocoSource.psm1 +++ b/DSCResources/cChocoSource/cChocoSource.psm1 @@ -1,172 +1,172 @@ -function Get-TargetResource -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Name, - [ValidateSet('Present','Absent')] - [System.String] - $Ensure='Present', - [parameter(Mandatory = $false)] - [UInt32] - $Priority, - [parameter(Mandatory = $false)] - [PSCredential] - $Credentials, - [parameter(Mandatory = $false)] - [System.String] - $Source - ) - - Write-Verbose "Start Get-TargetResource" - - #Needs to return a hashtable that returns the current - #status of the configuration component - $Configuration = @{ - Name = $Name - Priority = $Priority - Source = $Source - } - - return $Configuration -} - -function Set-TargetResource -{ - [CmdletBinding()] - param - ( - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Name, - [ValidateSet('Present','Absent')] - [System.String] - $Ensure='Present', - [parameter(Mandatory = $false)] - [UInt32] - $Priority, - [parameter(Mandatory = $false)] - [PSCredential] - $Credentials, - [parameter(Mandatory = $false)] - [System.String] - $Source - ) - Write-Verbose "Start Set-TargetResource" - - if($Ensure -eq "Present") - { - if($Credentials -eq $null) - { - if($priority -eq $null) - { - choco sources add -n"$name" -s"$source" - } - else - { - choco sources add -n"$name" -s"$source" --priority=$priority - } - } - else - { - $username = $Credentials.UserName - $password = $Credentials.GetNetworkCredential().Password - - if($priority -eq $null) - { - choco sources add -n"$name" -s"$source" -u="$username" -p="$password" - } - else - { - choco sources add -n"$name" -s"$source" -u="$username" -p="$password" --priority=$priority - } - } - } - else - { - choco sources remove -n"$name" - } -} - -function Test-TargetResource -{ - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [parameter(Mandatory = $true)] - [ValidateNotNullOrEmpty()] - [System.String] - $Name, - [ValidateSet('Present','Absent')] - [System.String] - $Ensure='Present', - [parameter(Mandatory = $false)] - [UInt32] - $Priority, - [parameter(Mandatory = $false)] - [PSCredential] - $Credentials, - [parameter(Mandatory = $false)] - [System.String] - $Source - ) - - Write-Verbose "Start Test-TargetResource" - - if($env:ChocolateyInstall -eq "" -or $env:ChocolateyInstall -eq $null) - { - $exe = (get-command choco).Source - $chocofolder = $exe.Substring(0,$exe.LastIndexOf("\")) - - if( $chocofolder.EndsWith("bin") ) - { - $chocofolder = $chocofolder.Substring(0,$chocofolder.LastIndexOf("\")) - } - } - else - { - $chocofolder = $env:ChocolateyInstall - } - $configfolder = "$chocofolder\config" - $configfile = Get-ChildItem $configfolder | Where-Object {$_.Name -match "chocolatey.config$"} - - $xml = [xml](Get-Content $configfile.FullName) - $sources = $xml.chocolatey.sources.source - - foreach($chocosource in $sources) - { - if($chocosource.id -eq $name -and $ensure -eq 'Present') - { - if ($chocosource.priority -eq $Priority) - { - return $true - } - else - { - return $false - } - } - elseif($chocosource.id -eq $name -and $ensure -eq 'Absent') - { - return $false - } - } - - if($Ensure -eq 'Present') - { - return $false - } - else - { - return $true - } -} - - -Export-ModuleMember -Function *-TargetResource +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $Name, + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present', + [parameter(Mandatory = $false)] + [UInt32] + $Priority, + [parameter(Mandatory = $false)] + [PSCredential] + $Credentials, + [parameter(Mandatory = $false)] + [System.String] + $Source + ) + + Write-Verbose "Start Get-TargetResource" + + #Needs to return a hashtable that returns the current + #status of the configuration component + $Configuration = @{ + Name = $Name + Priority = $Priority + Source = $Source + } + + return $Configuration +} + +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $Name, + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present', + [parameter(Mandatory = $false)] + [UInt32] + $Priority, + [parameter(Mandatory = $false)] + [PSCredential] + $Credentials, + [parameter(Mandatory = $false)] + [System.String] + $Source + ) + Write-Verbose "Start Set-TargetResource" + + if($Ensure -eq "Present") + { + if($Credentials -eq $null) + { + if($priority -eq $null) + { + choco sources add -n"$name" -s"$source" + } + else + { + choco sources add -n"$name" -s"$source" --priority=$priority + } + } + else + { + $username = $Credentials.UserName + $password = $Credentials.GetNetworkCredential().Password + + if($priority -eq $null) + { + choco sources add -n"$name" -s"$source" -u="$username" -p="$password" + } + else + { + choco sources add -n"$name" -s"$source" -u="$username" -p="$password" --priority=$priority + } + } + } + else + { + choco sources remove -n"$name" + } +} + +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [System.String] + $Name, + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present', + [parameter(Mandatory = $false)] + [UInt32] + $Priority, + [parameter(Mandatory = $false)] + [PSCredential] + $Credentials, + [parameter(Mandatory = $false)] + [System.String] + $Source + ) + + Write-Verbose "Start Test-TargetResource" + + if($env:ChocolateyInstall -eq "" -or $env:ChocolateyInstall -eq $null) + { + $exe = (get-command choco).Source + $chocofolder = $exe.Substring(0,$exe.LastIndexOf("\")) + + if( $chocofolder.EndsWith("bin") ) + { + $chocofolder = $chocofolder.Substring(0,$chocofolder.LastIndexOf("\")) + } + } + else + { + $chocofolder = $env:ChocolateyInstall + } + $configfolder = "$chocofolder\config" + $configfile = Get-ChildItem $configfolder | Where-Object {$_.Name -match "chocolatey.config$"} + + $xml = [xml](Get-Content $configfile.FullName) + $sources = $xml.chocolatey.sources.source + + foreach($chocosource in $sources) + { + if($chocosource.id -eq $name -and $ensure -eq 'Present') + { + if ($chocosource.priority -eq $Priority) + { + return $true + } + else + { + return $false + } + } + elseif($chocosource.id -eq $name -and $ensure -eq 'Absent') + { + return $false + } + } + + if($Ensure -eq 'Present') + { + return $false + } + else + { + return $true + } +} + + +Export-ModuleMember -Function *-TargetResource diff --git a/cChoco.psd1 b/cChoco.psd1 index 3e5ceff..d5af58e 100644 --- a/cChoco.psd1 +++ b/cChoco.psd1 @@ -1,4 +1,4 @@ -@{ +@{ Copyright = "(c) 2017 Chocolatey Software, (c) 2013-2017 Lawrence Gripper, All rights reserved."; Description = "Chocolatey DSC Resources for use with internal packages and the community package repository. Learn more at http://chocolatey.org/"; CompanyName = "Chocolatey Software"; From 1ba231a8e9341f073960f42acf0e9cd85dc7c64a Mon Sep 17 00:00:00 2001 From: Rob Reynolds Date: Wed, 19 Apr 2017 11:23:27 -0500 Subject: [PATCH 02/10] (maint) formatting --- AppVeyor/AppVeyorDeploy.ps1 | 18 +++++++++--------- readme.md | 30 +++++++++++++++--------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/AppVeyor/AppVeyorDeploy.ps1 b/AppVeyor/AppVeyorDeploy.ps1 index 16d66b1..da2a4da 100644 --- a/AppVeyor/AppVeyorDeploy.ps1 +++ b/AppVeyor/AppVeyorDeploy.ps1 @@ -1,11 +1,11 @@ -#---------------------------------# -# Header # -#---------------------------------# +#---------------------------------# +# Header # +#---------------------------------# Write-Host 'Running AppVeyor deploy script' -ForegroundColor Yellow -#---------------------------------# -# Update module manifest # -#---------------------------------# +#---------------------------------# +# Update module manifest # +#---------------------------------# Write-Host 'Creating new module manifest' $ModuleManifestPath = Join-Path -path "$pwd" -ChildPath ("$env:ModuleName"+'.psd1') @@ -14,9 +14,9 @@ $ModuleManifest = Get-Content $ModuleManifestPath -Raw Write-Host "Updating module manifest to version: $env:APPVEYOR_BUILD_VERSION" [regex]::replace($ModuleManifest,'(ModuleVersion = )(.*)',"`$1'$env:APPVEYOR_BUILD_VERSION'") | Out-File -LiteralPath $ModuleManifestPath -#---------------------------------# -# Publish to PS Gallery # -#---------------------------------# +#---------------------------------# +# Publish to PS Gallery # +#---------------------------------# if ( ($env:APPVEYOR_REPO_NAME -notmatch 'chocolatey') -or ($env:APPVEYOR_REPO_BRANCH -notmatch 'master') ) { diff --git a/readme.md b/readme.md index 2d0e131..5678b05 100644 --- a/readme.md +++ b/readme.md @@ -10,7 +10,7 @@ Community Chocolatey DSC Resource This resource is aimed at getting and installing packages from the choco gallery. -The resource takes the name of the package and will then install that package. +The resource takes the name of the package and will then install that package. See [ExampleConfig.ps1](ExampleConfig.ps1) for example usage. @@ -19,23 +19,23 @@ See list of packages here: https://chocolatey.org/packages Contributing ============================= -Happy to accept new features and fixes. Outstanding issues which can be worked on tagged HelpedWanted under issues. +Happy to accept new features and fixes. Outstanding issues which can be worked on tagged HelpedWanted under issues. Submitting a PR ============================= -Here's the general process of fixing an issue in the DSC Resource Kit: -1. Fork the repository. -3. Clone your fork to your machine. -4. It's preferred to create a non-master working branch where you store updates. -5. Make changes. -6. Write pester tests to ensure that the issue is fixed. -7. Submit a pull request to the development branch. -8. Make sure all tests are passing in AppVeyor for your pull request. -9. Make sure your code does not contain merge conflicts. -10. Address comments (if any). - -Build and Publishing +Here's the general process of fixing an issue in the DSC Resource Kit: +1. Fork the repository. +3. Clone your fork to your machine. +4. It's preferred to create a non-master working branch where you store updates. +5. Make changes. +6. Write pester tests to ensure that the issue is fixed. +7. Submit a pull request to the development branch. +8. Make sure all tests are passing in AppVeyor for your pull request. +9. Make sure your code does not contain merge conflicts. +10. Address comments (if any). + +Build and Publishing ============================ AppVeyor is used to package up the resource and publish to the Powershell Gallery (on successful build from master branch only). @@ -45,4 +45,4 @@ The AppVeyor scripts do the following: - Verify best practises using 'PSScriptAnalyzer' - Update the version in the manifest file - Publish the module to the powershell gallery -- Checkin updated manifest file to github \ No newline at end of file +- Checkin updated manifest file to github From 44d4f522a80954fe570574c9afb625e79634ccc9 Mon Sep 17 00:00:00 2001 From: Rob Reynolds Date: Wed, 19 Apr 2017 11:25:47 -0500 Subject: [PATCH 03/10] (GH-77) Push to gallery on new tags Instead of pushing on merges to master, push to the PowerShell gallery on new tags being added. We want to use tagging for versioning and getting to version history in the repository, so it's good to just set that up appropriately. --- AppVeyor/AppVeyorDeploy.ps1 | 2 +- readme.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AppVeyor/AppVeyorDeploy.ps1 b/AppVeyor/AppVeyorDeploy.ps1 index da2a4da..0447fab 100644 --- a/AppVeyor/AppVeyorDeploy.ps1 +++ b/AppVeyor/AppVeyorDeploy.ps1 @@ -18,7 +18,7 @@ Write-Host "Updating module manifest to version: $env:APPVEYOR_BUILD_VERSION" # Publish to PS Gallery # #---------------------------------# -if ( ($env:APPVEYOR_REPO_NAME -notmatch 'chocolatey') -or ($env:APPVEYOR_REPO_BRANCH -notmatch 'master') ) +if ( ($env:APPVEYOR_REPO_NAME -notmatch 'chocolatey') -or (!$env:APPVEYOR_REPO_TAG_NAME) ) { Write-Host "Finished testing of branch: $env:APPVEYOR_REPO_BRANCH - Exiting" exit; diff --git a/readme.md b/readme.md index 5678b05..4f26d20 100644 --- a/readme.md +++ b/readme.md @@ -38,7 +38,7 @@ Here's the general process of fixing an issue in the DSC Resource Kit: Build and Publishing ============================ -AppVeyor is used to package up the resource and publish to the Powershell Gallery (on successful build from master branch only). +AppVeyor is used to package up the resource and publish to the Powershell Gallery (on successful build from a newly pushed tag only). The AppVeyor scripts do the following: - Test the resources using 'xDSCResourceDesigner' From 8e36b1fca012b560928686c4bde1b3e32ae71a4e Mon Sep 17 00:00:00 2001 From: Neil Date: Thu, 27 Apr 2017 15:35:44 -0700 Subject: [PATCH 04/10] Added version to example --- Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 index 53b26e3..a5b4f66 100644 --- a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 +++ b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 @@ -8,10 +8,11 @@ Name = 'skype' Ensure = 'Present' AutoUpgrade = $True + Version = 7.35.0.101 } } } $config = InstallChoco -Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force \ No newline at end of file +Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force From 58bd11e7127057503544adaffb6bfca90f0bfbdf Mon Sep 17 00:00:00 2001 From: Jark Reijerink Date: Wed, 21 Jun 2017 14:15:41 +0100 Subject: [PATCH 05/10] (GH-44) Pass the Source to choco correctly The Source parameter for the cChocoPackageInstaller DSC Resource is not used by the choco install and choco upgrade commands so packages get installed and upgraded from the central chocolatey repository instead of the url specified in the Source parameter. This commit rectifies this issue. --- .../cChocoPackageInstall.psm1 | 42 +++++++++++++------ 1 file changed, 30 insertions(+), 12 deletions(-) diff --git a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 index 85b0363..2502a4c 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -85,17 +85,17 @@ function Set-TargetResource Write-Verbose -Message "Uninstalling $Name due to version mis-match" UninstallPackage -pName $Name -pParams $Params Write-Verbose -Message "Re-Installing $Name with correct version $version" - InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams + InstallPackage -pName $Name -pParams $Params -pVersion $Version -pSource $Source -cParams $chocoParams } elseif ($AutoUpgrade) { Write-Verbose -Message "Upgrading $Name due to version mis-match" - Upgrade-Package -pName $Name -pParams $Params + Upgrade-Package -pName $Name -pParams $Params -pSource $Source } } } } else { $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Install package from Chocolatey') if ($whatIfShouldProcess) { - InstallPackage -pName $Name -pParams $Params -pVersion $Version -cParams $chocoParams + InstallPackage -pName $Name -pParams $Params -pVersion $Version -pSource $Source -cParams $chocoParams } } } @@ -152,7 +152,7 @@ function Test-TargetResource Write-Verbose -Message "Checking if $Name is installed" if ($AutoUpgrade -and $isInstalled) { - $result = Test-LatestVersionInstalled -pName $Name + $result = Test-LatestVersionInstalled -pName $Name -pSource $Source } else { $result = $isInstalled } @@ -204,6 +204,8 @@ function InstallPackage [Parameter(Position=2)] [string]$pVersion, [Parameter(Position=3)] + [string]$pSource, + [Parameter(Position=4)] [string]$cParams ) @@ -216,6 +218,9 @@ function InstallPackage if ($pVersion) { $chocoinstallparams += " --version=`"$pVersion`"" } + if ($pSource) { + $chocoinstallparams += " --source=`"$pSource`"" + } if ($cParams) { $chocoinstallparams += " $cParams" } @@ -251,14 +256,12 @@ function UninstallPackage $packageUninstallOuput = choco uninstall $pName --params="$pParams" -y } - Write-Verbose -Message "Package uninstall output $packageUninstallOuput " #refresh path varaible in powershell, as choco doesn"t, to pull in git $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') } - function IsPackageInstalled { param( @@ -292,16 +295,26 @@ function IsPackageInstalled } Function Test-LatestVersionInstalled { + [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingInvokeExpression','')] param( - [Parameter(Position=0,Mandatory)] - [string]$pName + [Parameter(Mandatory)] + [string]$pName, + [Parameter(Mandatory)] + [string]$pSource ) Write-Verbose -Message "Testing if $pName can be upgraded" - $queryres = choco upgrade $pName --noop | Select-String -Pattern $pName - $queryres | ForEach-Object {Write-Verbose -Message $_} + [string]$chocoupgradeparams = '--noop' + if ($pSource) { + $chocoupgradeparams += " --source=`"$pSource`"" + } + + Write-Verbose -Message "Testing if $pName can be upgraded: 'choco upgrade $pName $chocoupgradeparams'" + + $packageUpgradeOuput = Invoke-Expression -Command "choco upgrade $pName $chocoupgradeparams" + $packageUpgradeOuput | ForEach-Object {Write-Verbose -Message $_} - if ($queryres -match "$pName.*is the latest version available based on your source") { + if ($packageUpgradeOuput -match "$pName.*is the latest version available based on your source") { return $true } return $false @@ -337,6 +350,8 @@ Function Upgrade-Package { [Parameter(Position=1)] [string]$pParams, [Parameter(Position=2)] + [string]$pSource, + [Parameter(Position=3)] [string]$cParams ) @@ -347,10 +362,13 @@ Function Upgrade-Package { if ($pParams) { $chocoupgradeparams += " --params=`"$pParams`"" } + if ($pSource) { + $chocoupgradeparams += " --source=`"$pSource`"" + } if ($cParams) { $chocoupgradeparams += " $cParams" } - $cmd = "choco upgrade -dv -y $pName $chocoupgradeparams" + $cmd = "choco upgrade $pName $chocoupgradeparams" Write-Verbose -Message "Upgrade command: '$cmd'" if (-not (IsPackageInstalled -pName $pName)) From 2ed30be9d0bd22d6deaa60cca873823eb245b999 Mon Sep 17 00:00:00 2001 From: Jark Reijerink Date: Thu, 22 Jun 2017 22:11:13 +0100 Subject: [PATCH 06/10] (GH-85) Pass the source to cChocoPackageInstallerSet correctly The cChocoPackageInstallerSet resource only provides the Source parameter to the first package being installed. This occurred due to historical reasons where the Source would be added to the system rather than being specified. This commit will pass the Source in for every package. --- .../cChocoPackageInstallerSet.schema.psm1 | 21 ++++--------------- 1 file changed, 4 insertions(+), 17 deletions(-) diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 index f160a71..f084920 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 @@ -20,24 +20,11 @@ Composite DSC Resource allowing you to specify multiple choco packages in a sing $Source ) - $addSource = $Source - foreach ($pName in $Name) { - ## We only need to specify the source one time, - ## so we do it only with the first package - if ($addSource) { - cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { - Ensure = $Ensure - Name = $pName - Source = $Source - } - $addSource = $null - } - else { - cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { - Ensure = $Ensure - Name = $pName - } + cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { + Ensure = $Ensure + Name = $pName + Source = $Source } } } From 1161e86a044d9bf52b1b4711a470323e07f9c08f Mon Sep 17 00:00:00 2001 From: Rob Reynolds Date: Thu, 13 Jul 2017 20:05:10 -0500 Subject: [PATCH 07/10] (GH-70) Apply Apache v2 Licensing Apply Apache v2 licensing to the repository - received sign off from all current contributors. --- AppVeyor/AppVeyorBuild.ps1 | 21 ++- AppVeyor/AppVeyorDeploy.ps1 | 17 +- AppVeyor/AppVeyorInstall.ps1 | 21 ++- AppVeyor/AppVeyorTest.ps1 | 21 ++- .../cChocoInstaller/cChocoInstaller.psm1 | 17 +- .../cChocoPackageInstall.psm1 | 17 +- .../cChocoPackageInstallerSet.psd1 | 6 +- .../cChocoPackageInstallerSet.schema.psm1 | 17 +- DSCResources/cChocoSource/cChocoSource.psm1 | 17 +- ExampleConfig.ps1 | 143 +++++++------- ...cChocoInstaller_cChocoInstallerExample.ps1 | 17 +- ...oInstaller_cChocoPackageInstallExample.ps1 | 17 +- LICENSE | 174 ++++++++++++++++++ NOTICE | 14 ++ Tests/cChocoInstaller_Tests.ps1 | 19 +- Tests/cChocoPackageInstall_Tests.ps1 | 21 ++- Tests/cChoco_ScriptAnalyzerTests.ps1 | 21 ++- Tests/cChoco_xDscResourceTests.ps1 | 19 +- cChoco.psd1 | 2 +- 19 files changed, 507 insertions(+), 94 deletions(-) create mode 100644 LICENSE create mode 100644 NOTICE diff --git a/AppVeyor/AppVeyorBuild.ps1 b/AppVeyor/AppVeyorBuild.ps1 index 6fb7f23..a5eed85 100644 --- a/AppVeyor/AppVeyorBuild.ps1 +++ b/AppVeyor/AppVeyorBuild.ps1 @@ -1,6 +1,21 @@ -#---------------------------------# -# Header # -#---------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# Header # +#---------------------------------# Write-Host 'Running AppVeyor build script' -ForegroundColor Yellow Write-Host "ModuleName : $env:ModuleName" Write-Host "Build version : $env:APPVEYOR_BUILD_VERSION" diff --git a/AppVeyor/AppVeyorDeploy.ps1 b/AppVeyor/AppVeyorDeploy.ps1 index 0447fab..df684d5 100644 --- a/AppVeyor/AppVeyorDeploy.ps1 +++ b/AppVeyor/AppVeyorDeploy.ps1 @@ -1,4 +1,19 @@ -#---------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# # Header # #---------------------------------# Write-Host 'Running AppVeyor deploy script' -ForegroundColor Yellow diff --git a/AppVeyor/AppVeyorInstall.ps1 b/AppVeyor/AppVeyorInstall.ps1 index ca8603c..1d802be 100644 --- a/AppVeyor/AppVeyorInstall.ps1 +++ b/AppVeyor/AppVeyorInstall.ps1 @@ -1,6 +1,21 @@ -#---------------------------------# -# Header # -#---------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# Header # +#---------------------------------# Write-Host 'Running AppVeyor install script' -ForegroundColor Yellow #---------------------------------# diff --git a/AppVeyor/AppVeyorTest.ps1 b/AppVeyor/AppVeyorTest.ps1 index 1729ab5..ed6eb5b 100644 --- a/AppVeyor/AppVeyorTest.ps1 +++ b/AppVeyor/AppVeyorTest.ps1 @@ -1,6 +1,21 @@ -#---------------------------------# -# Header # -#---------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# Header # +#---------------------------------# Write-Host 'Running AppVeyor test script' -ForegroundColor Yellow Write-Host "Current working directory: $pwd" diff --git a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 index 3ddf918..ef2b354 100644 --- a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 +++ b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 @@ -1,4 +1,19 @@ -function Get-TargetResource +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +function Get-TargetResource { [OutputType([hashtable])] param diff --git a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 index 2502a4c..acb88bf 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -1,4 +1,19 @@ -function Get-TargetResource +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +function Get-TargetResource { [OutputType([hashtable])] param diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 index a5a963f..2697046 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 @@ -16,13 +16,13 @@ ModuleVersion = '2.1.0.0' GUID = '028ba992-9429-4a6b-9c99-17eb4999cb23' # Author of this module -Author = 'Lawrence Gripper' +Author = 'Chocolatey Software, Lawrence Gripper, Javy de Koning' # Company or vendor of this module -CompanyName = 'Lawrence Gripper' +CompanyName = 'Chocolatey Software, Inc' # Copyright statement for this module -Copyright = '(c) 2013-2016 Lawrence Gripper. All rights reserved.' +Copyright = '(c) 2017 Chocolatey Software, Inc (c) 2013-2017 Lawrence Gripper, All rights reserved.' # Description of the functionality provided by this module # Description = 'Allows install/uninstall of a group of choco packages.' diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 index f084920..f5fbab7 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 @@ -1,4 +1,19 @@ -Configuration cChocoPackageInstallerSet +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Configuration cChocoPackageInstallerSet { <# .SYNOPSIS diff --git a/DSCResources/cChocoSource/cChocoSource.psm1 b/DSCResources/cChocoSource/cChocoSource.psm1 index 127d216..792fcc8 100644 --- a/DSCResources/cChocoSource/cChocoSource.psm1 +++ b/DSCResources/cChocoSource/cChocoSource.psm1 @@ -1,4 +1,19 @@ -function Get-TargetResource +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +function Get-TargetResource { [CmdletBinding()] [OutputType([System.Collections.Hashtable])] diff --git a/ExampleConfig.ps1 b/ExampleConfig.ps1 index c36e69a..1da2a8f 100644 --- a/ExampleConfig.ps1 +++ b/ExampleConfig.ps1 @@ -1,65 +1,80 @@ -Configuration myChocoConfig -{ - Import-DscResource -Module cChoco - Node "localhost" - { - LocalConfigurationManager - { - DebugMode = 'ForceModuleImport' - } - cChocoInstaller installChoco - { - InstallDir = "c:\choco" - } - cChocoPackageInstaller installChrome - { - Name = "googlechrome" - DependsOn = "[cChocoInstaller]installChoco" - #This will automatically try to upgrade if available, only if a version is not explicitly specified. - AutoUpgrade = $True - } - cChocoPackageInstaller installAtomSpecificVersion - { - Name = "atom" - Version = "0.155.0" - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstaller installGit - { - Ensure = 'Present' - Name = "git" - Params = "/Someparam " - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstaller noFlashAllowed - { - Ensure = 'Absent' - Name = "flashplayerplugin" - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstallerSet installSomeStuff - { - Ensure = 'Present' - Name = @( - "git" - "skype" - "7zip" - ) - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstallerSet stuffToBeRemoved - { - Ensure = 'Absent' - Name = @( - "vlc" - "ruby" - "adobeair" - ) - DependsOn = "[cChocoInstaller]installChoco" - } - } -} - -myChocoConfig - +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Configuration myChocoConfig +{ + Import-DscResource -Module cChoco + Node "localhost" + { + LocalConfigurationManager + { + DebugMode = 'ForceModuleImport' + } + cChocoInstaller installChoco + { + InstallDir = "c:\choco" + } + cChocoPackageInstaller installChrome + { + Name = "googlechrome" + DependsOn = "[cChocoInstaller]installChoco" + #This will automatically try to upgrade if available, only if a version is not explicitly specified. + AutoUpgrade = $True + } + cChocoPackageInstaller installAtomSpecificVersion + { + Name = "atom" + Version = "0.155.0" + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstaller installGit + { + Ensure = 'Present' + Name = "git" + Params = "/Someparam " + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstaller noFlashAllowed + { + Ensure = 'Absent' + Name = "flashplayerplugin" + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstallerSet installSomeStuff + { + Ensure = 'Present' + Name = @( + "git" + "skype" + "7zip" + ) + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstallerSet stuffToBeRemoved + { + Ensure = 'Absent' + Name = @( + "vlc" + "ruby" + "adobeair" + ) + DependsOn = "[cChocoInstaller]installChoco" + } + } +} + +myChocoConfig + Start-DscConfiguration .\myChocoConfig -wait -Verbose -force \ No newline at end of file diff --git a/Examples/cChocoInstaller_cChocoInstallerExample.ps1 b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 index 37a28bf..15bdd18 100644 --- a/Examples/cChocoInstaller_cChocoInstallerExample.ps1 +++ b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 @@ -1,4 +1,19 @@ -Configuration InstallChoco +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Configuration InstallChoco { Import-DscResource -Module cChoco Node "localhost" diff --git a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 index a5b4f66..4792666 100644 --- a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 +++ b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 @@ -1,4 +1,19 @@ -Configuration InstallChoco +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Configuration InstallChoco { Import-DscResource -Module cChoco Node "localhost" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..338979d --- /dev/null +++ b/LICENSE @@ -0,0 +1,174 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..f322b27 --- /dev/null +++ b/NOTICE @@ -0,0 +1,14 @@ + Copyright (c) 2017 Chocolatey Software, Inc. + Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Tests/cChocoInstaller_Tests.ps1 b/Tests/cChocoInstaller_Tests.ps1 index 48f32ff..d884ce9 100644 --- a/Tests/cChocoInstaller_Tests.ps1 +++ b/Tests/cChocoInstaller_Tests.ps1 @@ -1,5 +1,20 @@ -#---------------------------------# -# Pester tests for cChocoInstall # +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# Pester tests for cChocoInstall # #---------------------------------# $ResourceName = ((Split-Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0] $ResourceFile = (Get-DscResource -Name $ResourceName).Path diff --git a/Tests/cChocoPackageInstall_Tests.ps1 b/Tests/cChocoPackageInstall_Tests.ps1 index a9c6f63..90f2f5d 100644 --- a/Tests/cChocoPackageInstall_Tests.ps1 +++ b/Tests/cChocoPackageInstall_Tests.ps1 @@ -1,6 +1,21 @@ -#----------------------------------------# -# Pester tests for cChocoPackageInstall # -#----------------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#----------------------------------------# +# Pester tests for cChocoPackageInstall # +#----------------------------------------# $ResourceName = ((Split-Path -Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0] $ResourceFile = (Get-DscResource -Name $ResourceName).Path diff --git a/Tests/cChoco_ScriptAnalyzerTests.ps1 b/Tests/cChoco_ScriptAnalyzerTests.ps1 index 462fdfe..43aaf20 100644 --- a/Tests/cChoco_ScriptAnalyzerTests.ps1 +++ b/Tests/cChoco_ScriptAnalyzerTests.ps1 @@ -1,6 +1,21 @@ -#---------------------------------# -# PSScriptAnalyzer tests # -#---------------------------------# +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# PSScriptAnalyzer tests # +#---------------------------------# $Rules = Get-ScriptAnalyzerRule #Only run on cChocoInstaller.psm1 for now as this is the only resource that has had code adjustments for PSScriptAnalyzer rules. diff --git a/Tests/cChoco_xDscResourceTests.ps1 b/Tests/cChoco_xDscResourceTests.ps1 index 397737a..6ec484b 100644 --- a/Tests/cChoco_xDscResourceTests.ps1 +++ b/Tests/cChoco_xDscResourceTests.ps1 @@ -1,5 +1,20 @@ -#---------------------------------# -# xDscResourceTests Pester # +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +#---------------------------------# +# xDscResourceTests Pester # #---------------------------------# $DSC = Get-DscResource | Where-Object {$_.Module.Name -eq 'cChoco'} diff --git a/cChoco.psd1 b/cChoco.psd1 index d5af58e..e224e3f 100644 --- a/cChoco.psd1 +++ b/cChoco.psd1 @@ -1,5 +1,5 @@ @{ - Copyright = "(c) 2017 Chocolatey Software, (c) 2013-2017 Lawrence Gripper, All rights reserved."; + Copyright = "(c) 2017 Chocolatey Software, Inc (c) 2013-2017 Lawrence Gripper, All rights reserved."; Description = "Chocolatey DSC Resources for use with internal packages and the community package repository. Learn more at http://chocolatey.org/"; CompanyName = "Chocolatey Software"; GUID = "4857229F-8C2D-41BB-A068-9E3C0C8ED63D"; From 1bcd95d01ef8b144db7e6eb4597232bf16a11054 Mon Sep 17 00:00:00 2001 From: Rob Reynolds Date: Thu, 13 Jul 2017 20:15:54 -0500 Subject: [PATCH 08/10] (maint) formatting --- AppVeyor/AppVeyorBuild.ps1 | 8 +- AppVeyor/AppVeyorInstall.ps1 | 30 ++-- AppVeyor/AppVeyorTest.ps1 | 16 +- .../cChocoInstaller/cChocoInstaller.psm1 | 30 ++-- .../cChocoPackageInstall.psm1 | 78 ++++----- .../cChocoPackageInstallerSet.psd1 | 3 +- DSCResources/cChocoSource/cChocoSource.psm1 | 18 +- ExampleConfig.ps1 | 160 +++++++++--------- ...cChocoInstaller_cChocoInstallerExample.ps1 | 6 +- ...oInstaller_cChocoPackageInstallExample.ps1 | 6 +- Tests/cChocoInstaller_Tests.ps1 | 8 +- Tests/cChocoPackageInstall_Tests.ps1 | 26 +-- Tests/cChoco_ScriptAnalyzerTests.ps1 | 8 +- Tests/cChoco_xDscResourceTests.ps1 | 18 +- 14 files changed, 208 insertions(+), 207 deletions(-) diff --git a/AppVeyor/AppVeyorBuild.ps1 b/AppVeyor/AppVeyorBuild.ps1 index a5eed85..287df2d 100644 --- a/AppVeyor/AppVeyorBuild.ps1 +++ b/AppVeyor/AppVeyorBuild.ps1 @@ -26,7 +26,7 @@ Write-Host "PSModulePath :" $env:PSModulePath -split ';' -#---------------------------------# -# BuildScript # -#---------------------------------# -Write-Host 'Nothing to build, skipping.....' \ No newline at end of file +#---------------------------------# +# BuildScript # +#---------------------------------# +Write-Host 'Nothing to build, skipping.....' diff --git a/AppVeyor/AppVeyorInstall.ps1 b/AppVeyor/AppVeyorInstall.ps1 index 1d802be..0375f61 100644 --- a/AppVeyor/AppVeyorInstall.ps1 +++ b/AppVeyor/AppVeyorInstall.ps1 @@ -18,33 +18,33 @@ #---------------------------------# Write-Host 'Running AppVeyor install script' -ForegroundColor Yellow -#---------------------------------# -# Install NuGet # -#---------------------------------# +#---------------------------------# +# Install NuGet # +#---------------------------------# Write-Host 'Installing NuGet PackageProvide' $pkg = Install-PackageProvider -Name NuGet -Force -ErrorAction Stop -Write-Host "Installed NuGet version '$($pkg.version)'" +Write-Host "Installed NuGet version '$($pkg.version)'" -#---------------------------------# -# Install Modules # -#---------------------------------# +#---------------------------------# +# Install Modules # +#---------------------------------# [version]$ScriptAnalyzerVersion = '1.8.1' Install-Module -Name 'PSScriptAnalyzer' -Repository PSGallery -Force -ErrorAction Stop -MaximumVersion $ScriptAnalyzerVersion Install-Module -Name 'Pester','xDSCResourceDesigner' -Repository PSGallery -Force -ErrorAction Stop -#---------------------------------# -# Update PSModulePath # -#---------------------------------# +#---------------------------------# +# Update PSModulePath # +#---------------------------------# Write-Host 'Updating PSModulePath for DSC resource testing' $env:PSModulePath = $env:PSModulePath + ";" + "C:\projects" -#---------------------------------# -# Validate # -#---------------------------------# +#---------------------------------# +# Validate # +#---------------------------------# $RequiredModules = 'PSScriptAnalyzer','Pester','xDSCResourceDesigner' $InstalledModules = Get-Module -Name $RequiredModules -ListAvailable -if ( ($InstalledModules.count -lt $RequiredModules.Count) -or ($Null -eq $InstalledModules)) { +if ( ($InstalledModules.count -lt $RequiredModules.Count) -or ($Null -eq $InstalledModules)) { throw "Required modules are missing." } else { Write-Host 'All modules required found' -ForegroundColor Green -} \ No newline at end of file +} diff --git a/AppVeyor/AppVeyorTest.ps1 b/AppVeyor/AppVeyorTest.ps1 index ed6eb5b..5186183 100644 --- a/AppVeyor/AppVeyorTest.ps1 +++ b/AppVeyor/AppVeyorTest.ps1 @@ -19,9 +19,9 @@ Write-Host 'Running AppVeyor test script' -ForegroundColor Yellow Write-Host "Current working directory: $pwd" -#---------------------------------# -# Run Pester Tests # -#---------------------------------# +#---------------------------------# +# Run Pester Tests # +#---------------------------------# $resultsFile = '.\TestsResults.xml' $testFiles = Get-ChildItem "$pwd\tests" | Where-Object {$_.FullName -match 'Tests.ps1$'} | Select-Object -ExpandProperty FullName $results = Invoke-Pester -Script $testFiles -OutputFormat NUnitXml -OutputFile $resultsFile -PassThru @@ -33,11 +33,11 @@ try { throw "Upload failed." } -#---------------------------------# -# Validate # -#---------------------------------# -if (($results.FailedCount -gt 0) -or ($results.PassedCount -eq 0) -or ($null -eq $results)) { +#---------------------------------# +# Validate # +#---------------------------------# +if (($results.FailedCount -gt 0) -or ($results.PassedCount -eq 0) -or ($null -eq $results)) { throw "$($results.FailedCount) tests failed." } else { Write-Host 'All tests passed' -ForegroundColor Green -} \ No newline at end of file +} diff --git a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 index ef2b354..e4e096c 100644 --- a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 +++ b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 @@ -78,10 +78,10 @@ function Test-TargetResource Write-Verbose 'Choco is not installed, calling set' Return $false } - + ##Test to see if the Install Directory is correct. $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') - if(-not ($InstallDir -eq $env:ChocolateyInstall)) + if(-not ($InstallDir -eq $env:ChocolateyInstall)) { Write-Verbose "Choco should be installed in $InstallDir but is installed to $env:ChocolateyInstall calling set" Return $false @@ -109,7 +109,7 @@ function Test-ChocoInstalled Function Test-Command { Param ( - [string]$command = 'choco' + [string]$command = 'choco' ) Write-Verbose "Test-Command $command" if (Get-Command -Name $command -ErrorAction SilentlyContinue) { @@ -118,8 +118,8 @@ Function Test-Command } else { Write-Verbose "$command does NOT exist" return $false - } -} + } +} #region - chocolately installer work arounds. Main issue is use of write-host function global:Write-Host @@ -134,7 +134,7 @@ function global:Write-Host [ConsoleColor] $BackgroundColor ) - #Redirecting Write-Host -> Write-Verbose. + #Redirecting Write-Host -> Write-Verbose. Write-Verbose $Object } #endregion @@ -144,7 +144,7 @@ function Get-FileDownload { [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$url, - + [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$file @@ -174,7 +174,7 @@ Function Install-Chocolatey { [parameter()] [string] $ChocoInstallScriptUrl = 'https://chocolatey.org/install.ps1' - ) + ) Write-Verbose 'Install-Chocolatey' #Create install directory if it does not exist @@ -186,22 +186,22 @@ Function Install-Chocolatey { #Set permanent EnvironmentVariable Write-Verbose 'Setting ChocolateyInstall environment variables' [Environment]::SetEnvironmentVariable('ChocolateyInstall', $InstallDir, [EnvironmentVariableTarget]::Machine) - $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') - Write-Verbose "Env:ChocolateyInstall has $env:ChocolateyInstall" - - #Download an execute install script + $env:ChocolateyInstall = [Environment]::GetEnvironmentVariable('ChocolateyInstall','Machine') + Write-Verbose "Env:ChocolateyInstall has $env:ChocolateyInstall" + + #Download an execute install script $file = Join-Path -Path $InstallDir -ChildPath 'install.ps1' Get-FileDownload -url $ChocoInstallScriptUrl -file $file . $file #refresh after install Write-Verbose 'Adding Choco to path' - $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') + $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') if ($env:path -notlike "*$InstallDir*") { $env:Path += ";$InstallDir" } - - Write-Verbose "Env:Path has $env:path" + + Write-Verbose "Env:Path has $env:path" #InstallChoco $InstallDir $Null = Choco Write-Verbose 'Finish InstallChoco' diff --git a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 index acb88bf..1807a19 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -24,7 +24,7 @@ function Get-TargetResource $Name, [ValidateNotNullOrEmpty()] [string] - $Params, + $Params, [ValidateNotNullOrEmpty()] [string] $Version, @@ -59,16 +59,16 @@ function Set-TargetResource [parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string] - $Name, + $Name, [ValidateSet('Present','Absent')] [string] $Ensure='Present', [ValidateNotNullOrEmpty()] [string] - $Params, + $Params, [ValidateNotNullOrEmpty()] [string] - $Version, + $Version, [ValidateNotNullOrEmpty()] [string] $Source, @@ -78,7 +78,7 @@ function Set-TargetResource $AutoUpgrade = $false ) Write-Verbose -Message 'Start Set-TargetResource' - + if (-Not (Test-ChocoInstalled)) { throw "cChocoPackageInstall requires Chocolatey to be installed, consider using cChocoInstaller with 'dependson' in dsc config" } @@ -87,12 +87,12 @@ function Set-TargetResource #Uninstall if Ensure is set to absent and the package is installed if ($isInstalled) { - if ($Ensure -eq 'Absent') { + if ($Ensure -eq 'Absent') { $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Remove Chocolatey package') if ($whatIfShouldProcess) { Write-Verbose -Message "Removing $Name as ensure is set to absent" UninstallPackage -pName $Name -pParams $Params - } + } } else { $whatIfShouldProcess = $pscmdlet.ShouldProcess("$Name", 'Installing / upgrading package from Chocolatey') if ($whatIfShouldProcess) { @@ -130,7 +130,7 @@ function Test-TargetResource $Ensure='Present', [ValidateNotNullOrEmpty()] [string] - $Params, + $Params, [ValidateNotNullOrEmpty()] [string] $Version, @@ -148,10 +148,10 @@ function Test-TargetResource if (-Not (Test-ChocoInstalled)) { return $false - } - + } + $isInstalled = IsPackageInstalled -pName $Name - + if ($ensure -eq 'Absent') { if ($isInstalled -eq $false) { return $true @@ -159,7 +159,7 @@ function Test-TargetResource return $false } } - + if ($version) { Write-Verbose -Message "Checking if $Name is installed and if version matches $version" $result = IsPackageInstalled -pName $Name -pVersion $Version @@ -172,7 +172,7 @@ function Test-TargetResource $result = $isInstalled } } - + Return $result } function Test-ChocoInstalled @@ -196,7 +196,7 @@ Function Test-Command [CmdletBinding()] [OutputType([bool])] Param ( - [string]$command = 'choco' + [string]$command = 'choco' ) Write-Verbose -Message "Test-Command $command" if (Get-Command -Name $command -ErrorAction SilentlyContinue) { @@ -205,8 +205,8 @@ Function Test-Command } else { Write-Verbose -Message "$command does NOT exist" return $false - } -} + } +} function InstallPackage { @@ -222,10 +222,10 @@ function InstallPackage [string]$pSource, [Parameter(Position=4)] [string]$cParams - ) + ) $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - + [string]$chocoinstallparams = '-y' if ($pParams) { $chocoinstallparams += " --params=`"$pParams`"" @@ -240,7 +240,7 @@ function InstallPackage $chocoinstallparams += " $cParams" } Write-Verbose -Message "Install command: 'choco install $pName $chocoinstallparams'" - + $packageInstallOuput = Invoke-Expression -Command "choco install $pName $chocoinstallparams" Write-Verbose -Message "Package output $packageInstallOuput " @@ -248,7 +248,7 @@ function InstallPackage $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') } -function UninstallPackage +function UninstallPackage { param( [Parameter(Position=0,Mandatory)] @@ -258,7 +258,7 @@ function UninstallPackage ) $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - + #Todo: Refactor if (-not ($pParams)) { @@ -268,9 +268,9 @@ function UninstallPackage elseif ($pParams) { Write-Verbose -Message "Uninstalling Package with params $pParams" - $packageUninstallOuput = choco uninstall $pName --params="$pParams" -y + $packageUninstallOuput = choco uninstall $pName --params="$pParams" -y } - + Write-Verbose -Message "Package uninstall output $packageUninstallOuput " #refresh path varaible in powershell, as choco doesn"t, to pull in git @@ -282,14 +282,14 @@ function IsPackageInstalled param( [Parameter(Position=0,Mandatory)][string]$pName, [Parameter(Position=1)][string]$pVersion - ) + ) Write-Verbose -Message "Start IsPackageInstalled $pName" $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') Write-Verbose -Message "Path variables: $env:Path" - + $installedPackages = Get-ChocoInstalledPackage - + if ($pVersion) { Write-Verbose 'Comparing version' $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName -and $_.Version -eq $pVersion} @@ -297,7 +297,7 @@ function IsPackageInstalled Write-Verbose "Finding packages -eq $pName" $installedPackages = $installedPackages | Where-object { $_.Name -eq $pName} } - + $count = @($installedPackages).Count Write-Verbose "Found $Count matching packages" if ($Count -gt 0) @@ -316,7 +316,7 @@ Function Test-LatestVersionInstalled { [string]$pName, [Parameter(Mandatory)] [string]$pSource - ) + ) Write-Verbose -Message "Testing if $pName can be upgraded" [string]$chocoupgradeparams = '--noop' @@ -325,18 +325,18 @@ Function Test-LatestVersionInstalled { } Write-Verbose -Message "Testing if $pName can be upgraded: 'choco upgrade $pName $chocoupgradeparams'" - + $packageUpgradeOuput = Invoke-Expression -Command "choco upgrade $pName $chocoupgradeparams" - $packageUpgradeOuput | ForEach-Object {Write-Verbose -Message $_} - + $packageUpgradeOuput | ForEach-Object {Write-Verbose -Message $_} + if ($packageUpgradeOuput -match "$pName.*is the latest version available based on your source") { return $true - } + } return $false } ##region - chocolately installer work arounds. Main issue is use of write-host -##attempting to work around the issues with Chocolatey calling Write-host in its scripts. +##attempting to work around the issues with Chocolatey calling Write-host in its scripts. function global:Write-Host { Param( @@ -368,11 +368,11 @@ Function Upgrade-Package { [string]$pSource, [Parameter(Position=3)] [string]$cParams - ) + ) $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') Write-Verbose -Message "Path variables: $env:Path" - + [string]$chocoupgradeparams = '-dv -y' if ($pParams) { $chocoupgradeparams += " --params=`"$pParams`"" @@ -389,8 +389,8 @@ Function Upgrade-Package { if (-not (IsPackageInstalled -pName $pName)) { throw "$pName is not installed, you cannot upgrade" - } - + } + $packageUpgradeOuput = Invoke-Expression -Command $cmd $packageUpgradeOuput | ForEach-Object { Write-Verbose -Message $_ } } @@ -400,10 +400,10 @@ function Get-ChocoInstalledPackage { $Obj = $_ -split '\s' [pscustomobject]@{ 'Name' = $Obj[0] - 'Version' = $Obj[1] + 'Version' = $Obj[1] } } Return $res } -Export-ModuleMember -Function *-TargetResource \ No newline at end of file +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 index 2697046..758af2d 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 @@ -1,4 +1,5 @@ -# + +# # Module manifest for module 'cChocoPackageInstallerSet' # # Generated on: 2016/05/11 diff --git a/DSCResources/cChocoSource/cChocoSource.psm1 b/DSCResources/cChocoSource/cChocoSource.psm1 index 792fcc8..441053f 100644 --- a/DSCResources/cChocoSource/cChocoSource.psm1 +++ b/DSCResources/cChocoSource/cChocoSource.psm1 @@ -15,14 +15,14 @@ function Get-TargetResource { - [CmdletBinding()] + [CmdletBinding()] [OutputType([System.Collections.Hashtable])] param ( [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] - $Name, + $Name, [ValidateSet('Present','Absent')] [System.String] $Ensure='Present', @@ -52,13 +52,13 @@ function Get-TargetResource function Set-TargetResource { - [CmdletBinding()] + [CmdletBinding()] param ( [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] - $Name, + $Name, [ValidateSet('Present','Absent')] [System.String] $Ensure='Present', @@ -91,7 +91,7 @@ function Set-TargetResource { $username = $Credentials.UserName $password = $Credentials.GetNetworkCredential().Password - + if($priority -eq $null) { choco sources add -n"$name" -s"$source" -u="$username" -p="$password" @@ -117,7 +117,7 @@ function Test-TargetResource [parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] [System.String] - $Name, + $Name, [ValidateSet('Present','Absent')] [System.String] $Ensure='Present', @@ -133,9 +133,9 @@ function Test-TargetResource ) Write-Verbose "Start Test-TargetResource" - + if($env:ChocolateyInstall -eq "" -or $env:ChocolateyInstall -eq $null) - { + { $exe = (get-command choco).Source $chocofolder = $exe.Substring(0,$exe.LastIndexOf("\")) @@ -172,7 +172,7 @@ function Test-TargetResource return $false } } - + if($Ensure -eq 'Present') { return $false diff --git a/ExampleConfig.ps1 b/ExampleConfig.ps1 index 1da2a8f..505e479 100644 --- a/ExampleConfig.ps1 +++ b/ExampleConfig.ps1 @@ -1,80 +1,80 @@ -# Copyright (c) 2017 Chocolatey Software, Inc. -# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -Configuration myChocoConfig -{ - Import-DscResource -Module cChoco - Node "localhost" - { - LocalConfigurationManager - { - DebugMode = 'ForceModuleImport' - } - cChocoInstaller installChoco - { - InstallDir = "c:\choco" - } - cChocoPackageInstaller installChrome - { - Name = "googlechrome" - DependsOn = "[cChocoInstaller]installChoco" - #This will automatically try to upgrade if available, only if a version is not explicitly specified. - AutoUpgrade = $True - } - cChocoPackageInstaller installAtomSpecificVersion - { - Name = "atom" - Version = "0.155.0" - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstaller installGit - { - Ensure = 'Present' - Name = "git" - Params = "/Someparam " - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstaller noFlashAllowed - { - Ensure = 'Absent' - Name = "flashplayerplugin" - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstallerSet installSomeStuff - { - Ensure = 'Present' - Name = @( - "git" - "skype" - "7zip" - ) - DependsOn = "[cChocoInstaller]installChoco" - } - cChocoPackageInstallerSet stuffToBeRemoved - { - Ensure = 'Absent' - Name = @( - "vlc" - "ruby" - "adobeair" - ) - DependsOn = "[cChocoInstaller]installChoco" - } - } -} - -myChocoConfig - -Start-DscConfiguration .\myChocoConfig -wait -Verbose -force \ No newline at end of file +# Copyright (c) 2017 Chocolatey Software, Inc. +# Copyright (c) 2013 - 2017 Lawrence Gripper & original authors/contributors from https://github.com/chocolatey/cChoco +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +Configuration myChocoConfig +{ + Import-DscResource -Module cChoco + Node "localhost" + { + LocalConfigurationManager + { + DebugMode = 'ForceModuleImport' + } + cChocoInstaller installChoco + { + InstallDir = "c:\choco" + } + cChocoPackageInstaller installChrome + { + Name = "googlechrome" + DependsOn = "[cChocoInstaller]installChoco" + #This will automatically try to upgrade if available, only if a version is not explicitly specified. + AutoUpgrade = $True + } + cChocoPackageInstaller installAtomSpecificVersion + { + Name = "atom" + Version = "0.155.0" + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstaller installGit + { + Ensure = 'Present' + Name = "git" + Params = "/Someparam " + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstaller noFlashAllowed + { + Ensure = 'Absent' + Name = "flashplayerplugin" + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstallerSet installSomeStuff + { + Ensure = 'Present' + Name = @( + "git" + "skype" + "7zip" + ) + DependsOn = "[cChocoInstaller]installChoco" + } + cChocoPackageInstallerSet stuffToBeRemoved + { + Ensure = 'Absent' + Name = @( + "vlc" + "ruby" + "adobeair" + ) + DependsOn = "[cChocoInstaller]installChoco" + } + } +} + +myChocoConfig + +Start-DscConfiguration .\myChocoConfig -wait -Verbose -force diff --git a/Examples/cChocoInstaller_cChocoInstallerExample.ps1 b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 index 15bdd18..7457162 100644 --- a/Examples/cChocoInstaller_cChocoInstallerExample.ps1 +++ b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 @@ -15,7 +15,7 @@ Configuration InstallChoco { - Import-DscResource -Module cChoco + Import-DscResource -Module cChoco Node "localhost" { cChocoInstaller InstallChoco @@ -29,8 +29,8 @@ Configuration InstallChoco DependsOn = '[cChocoInstaller]installChoco' } } -} +} $config = InstallChoco -Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force \ No newline at end of file +Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force diff --git a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 index 4792666..96f3633 100644 --- a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 +++ b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 @@ -15,18 +15,18 @@ Configuration InstallChoco { - Import-DscResource -Module cChoco + Import-DscResource -Module cChoco Node "localhost" { cChocoPackageInstaller installSkypeWithChocoParams { Name = 'skype' Ensure = 'Present' - AutoUpgrade = $True + AutoUpgrade = $True Version = 7.35.0.101 } } -} +} $config = InstallChoco diff --git a/Tests/cChocoInstaller_Tests.ps1 b/Tests/cChocoInstaller_Tests.ps1 index d884ce9..77fc1f2 100644 --- a/Tests/cChocoInstaller_Tests.ps1 +++ b/Tests/cChocoInstaller_Tests.ps1 @@ -17,12 +17,12 @@ # Pester tests for cChocoInstall # #---------------------------------# $ResourceName = ((Split-Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0] -$ResourceFile = (Get-DscResource -Name $ResourceName).Path - +$ResourceFile = (Get-DscResource -Name $ResourceName).Path + Describe "Testing $ResourceName loaded from $ResourceFile" { Context “Testing 'Get-TargetResource'” { It 'DummyTest $true should be $true' { $true | Should Be $true - } + } } -} \ No newline at end of file +} diff --git a/Tests/cChocoPackageInstall_Tests.ps1 b/Tests/cChocoPackageInstall_Tests.ps1 index 90f2f5d..e522f64 100644 --- a/Tests/cChocoPackageInstall_Tests.ps1 +++ b/Tests/cChocoPackageInstall_Tests.ps1 @@ -17,22 +17,22 @@ # Pester tests for cChocoPackageInstall # #----------------------------------------# $ResourceName = ((Split-Path -Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0] -$ResourceFile = (Get-DscResource -Name $ResourceName).Path - -$TestsPath = (split-path -path $MyInvocation.MyCommand.Path -Parent) -$ResourceFile = Get-ChildItem -Recurse $TestsPath\.. -File | Where-Object {$_.name -eq "$ResourceName.psm1"} - +$ResourceFile = (Get-DscResource -Name $ResourceName).Path + +$TestsPath = (split-path -path $MyInvocation.MyCommand.Path -Parent) +$ResourceFile = Get-ChildItem -Recurse $TestsPath\.. -File | Where-Object {$_.name -eq "$ResourceName.psm1"} + Import-Module -Name $ResourceFile.FullName Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { Context -Name "Package is not installed" -Fixture { - Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith { + Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith { return [pscustomobject]@{ 'Name' = 'NotGoogleChrome' 'Version' = '1.0.0' } } - + $Scenario1 = @{ Name = 'GoogleChrome' Ensure = 'Present' @@ -48,12 +48,12 @@ Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { It -name "Test-TargetResource -ensure 'Absent' should return True" -test { Test-TargetResource @Scenario2 | Should Be $True } - + $Scenario3 = @{ Name = 'GoogleChrome' Ensure = 'Absent' Version = '1.0.0' - } + } It -name "Test-TargetResource -ensure 'Absent' -version '1.0.0' should return True" -test { Test-TargetResource @Scenario3 | Should Be $True } @@ -79,7 +79,7 @@ Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { } Context -Name "Package is installed with version 1.0.0" -Fixture { - Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith { + Mock -CommandName 'Get-ChocoInstalledPackage' -ModuleName 'cChocoPackageInstall' -MockWith { return [pscustomobject]@{ 'Name' = 'GoogleChrome' 'Version' = '1.0.0' @@ -107,7 +107,7 @@ Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { Ensure = 'Present' Version = '1.0.0' } - + It -name "Test-TargetResource -ensure 'Present' -version '1.0.0' should return True" -test { Test-TargetResource @Scenario3 | Should Be $True } @@ -117,7 +117,7 @@ Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { Ensure = 'Present' Version = '1.0.1' } - + It -name "Test-TargetResource -ensure 'Present' -version '1.0.1' should return False" -test { Test-TargetResource @Scenario4 | Should Be $False } @@ -125,4 +125,4 @@ Describe -Name "Testing $ResourceName loaded from $ResourceFile" -Fixture { } #Clean-up -Remove-Module cChocoPackageInstall \ No newline at end of file +Remove-Module cChocoPackageInstall diff --git a/Tests/cChoco_ScriptAnalyzerTests.ps1 b/Tests/cChoco_ScriptAnalyzerTests.ps1 index 43aaf20..89c3441 100644 --- a/Tests/cChoco_ScriptAnalyzerTests.ps1 +++ b/Tests/cChoco_ScriptAnalyzerTests.ps1 @@ -21,9 +21,9 @@ $Rules = Get-ScriptAnalyzerRule #Only run on cChocoInstaller.psm1 for now as this is the only resource that has had code adjustments for PSScriptAnalyzer rules. $Modules = Get-ChildItem “$PSScriptRoot\..\” -Filter ‘*.psm1’ -Recurse | Where-Object {$_.FullName -match '(cChocoInstaller|cChocoPackageInstall)\.psm1$'} -#---------------------------------# -# Run Module tests (psm1) # -#---------------------------------# +#---------------------------------# +# Run Module tests (psm1) # +#---------------------------------# if ($Modules.count -gt 0) { Describe ‘Testing all Modules against default PSScriptAnalyzer rule-set’ { foreach ($module in $modules) { @@ -36,4 +36,4 @@ if ($Modules.count -gt 0) { } } } -} \ No newline at end of file +} diff --git a/Tests/cChoco_xDscResourceTests.ps1 b/Tests/cChoco_xDscResourceTests.ps1 index 6ec484b..4c061e5 100644 --- a/Tests/cChoco_xDscResourceTests.ps1 +++ b/Tests/cChoco_xDscResourceTests.ps1 @@ -17,25 +17,25 @@ # xDscResourceTests Pester # #---------------------------------# $DSC = Get-DscResource | Where-Object {$_.Module.Name -eq 'cChoco'} - -Describe 'Testing all DSC resources using xDscResource designer.' { + +Describe 'Testing all DSC resources using xDscResource designer.' { foreach ($Resource in $DSC) - { + { if (-not ($Resource.ImplementedAs -eq 'Composite') ) { $ResourceName = $Resource.ResourceType - $Mof = Get-ChildItem “$PSScriptRoot\..\” -Filter "$resourcename.schema.mof" -Recurse - + $Mof = Get-ChildItem “$PSScriptRoot\..\” -Filter "$resourcename.schema.mof" -Recurse + Context “Testing DscResource '$ResourceName' using Test-xDscResource” { It 'Test-xDscResource should return $true' { Test-xDscResource -Name $ResourceName | Should Be $true - } + } } Context “Testing DscSchema '$ResourceName' using Test-xDscSchema” { It 'Test-xDscSchema should return true' { Test-xDscSchema -Path $Mof.FullName | Should Be $true - } + } } } - } -} \ No newline at end of file + } +} From 7dd92e078a4c9dacb185ed8170717a789ec1a215 Mon Sep 17 00:00:00 2001 From: lukemgriffith Date: Mon, 10 Jul 2017 21:43:32 +0100 Subject: [PATCH 09/10] (GH-87) Moved to using reduced output The old implementation caused promotional message, and chocolatey banner to get mixed into the works. If upgrading Chocolatey, cause problems as the version caught is a string with "vX.X.X" and in the where clause is attempted to be converted to a .NET version type. Limiting the output reduces it to only the packages, leaving out any banners. --- .../cChocoPackageInstall/cChocoPackageInstall.psm1 | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 index 1807a19..91acfae 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -396,14 +396,7 @@ Function Upgrade-Package { } function Get-ChocoInstalledPackage { - $res = choco list -lo | ForEach-Object { - $Obj = $_ -split '\s' - [pscustomobject]@{ - 'Name' = $Obj[0] - 'Version' = $Obj[1] - } - } - Return $res + Return (choco list -lo -r | ConvertFrom-Csv -Header 'Name', 'Version' -Delimiter "|") } Export-ModuleMember -Function *-TargetResource From 5b57ef464822737679702b07e32897f108e52b37 Mon Sep 17 00:00:00 2001 From: lukemgriffith Date: Tue, 18 Jul 2017 20:35:26 +0100 Subject: [PATCH 10/10] (GH-71) Implemented cChocoFeature Implemented cChocoFeature to provide an interface for DSC to configure choco client features. --- .gitIgnore | 3 +- DSCResources/cChocoFeature/cChocoFeature.psm1 | 148 ++++++++++++++++++ .../cChocoFeature/cChocoFeature.schema.mof | 8 + Examples/cChocoFeatureExample.ps1 | 41 +++++ Tests/cChocoFeature_Tests.ps1 | 87 ++++++++++ Tests/cChoco_ScriptAnalyzerTests.ps1 | 2 +- 6 files changed, 287 insertions(+), 2 deletions(-) create mode 100644 DSCResources/cChocoFeature/cChocoFeature.psm1 create mode 100644 DSCResources/cChocoFeature/cChocoFeature.schema.mof create mode 100644 Examples/cChocoFeatureExample.ps1 create mode 100644 Tests/cChocoFeature_Tests.ps1 diff --git a/.gitIgnore b/.gitIgnore index 75853ff..47fc7c9 100644 --- a/.gitIgnore +++ b/.gitIgnore @@ -1,2 +1,3 @@ *.mof -!*.schema.mof \ No newline at end of file +!*.schema.mof +TestsResults.xml \ No newline at end of file diff --git a/DSCResources/cChocoFeature/cChocoFeature.psm1 b/DSCResources/cChocoFeature/cChocoFeature.psm1 new file mode 100644 index 0000000..21513ba --- /dev/null +++ b/DSCResources/cChocoFeature/cChocoFeature.psm1 @@ -0,0 +1,148 @@ +# Copyright (c) 2017 Chocolatey Software, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +<# +.Description +Returns the configuration for cChocoFeature. + +.Example +Get-TargetResource -FeatureName allowGlobalConfirmation -Ensure 'Present' +#> +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $FeatureName, + + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present' + ) + + Write-Verbose "Starting cChocoFeature Get-TargetResource - Feature Name: $FeatureName, Ensure: $Ensure" + + $returnValue = @{ + FeatureName = $FeatureName + Ensure = $Ensure + } + + $returnValue + +} + +<# +.Description +Performs the set for the cChocoFeature resource. + +.Example +Get-TargetResource -FeatureName allowGlobalConfirmation -Ensure 'Present' + +#> +function Set-TargetResource +{ + [CmdletBinding(SupportsShouldProcess=$true)] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $FeatureName, + + [ValidateSet('Present','Absent')] + [string] + $Ensure='Present' + ) + + + Write-Verbose "Starting cChocoFeature Set-TargetResource - Feature Name: $FeatureName, Ensure: $Ensure." + + if ($pscmdlet.ShouldProcess("Choco feature $FeatureName will be ensured $Ensure.")) + { + if ($Ensure -eq 'Present') + { + Write-Verbose "Enabling choco feature $FeatureName." + choco feature enable -n $FeatureName + } + else + { + Write-Verbose "Disabling choco feature $FeatureName." + choco feature disable -n $FeatureName + } + } + +} + +<# +.Description +Performs the test for cChocoFeature. + +.Example +Test-TargetResource -FeatureName allowGlobalConfirmation -Ensure 'Present' +#> +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [parameter(Mandatory = $true)] + [System.String] + $FeatureName, + + [ValidateSet('Present','Absent')] + [System.String] + $Ensure='Present' + ) + + Write-Verbose "Starting cChocoFeature Test-TargetResource - Feature Name: $FeatureName, Ensure: $Ensure." + + $result = $false + $feature = Get-ChocoFeature -FeatureName $FeatureName | Where-Object {$_.State -eq "Enabled"} + + if (($Ensure -eq 'Present' -and ([bool]$feature)) -or ($Ensure -eq 'Absent' -and !([bool]$feature))) + { + Write-Verbose "Test-TargetResource is true, $FeatureName is $Ensure." + $result = $true + } + else + { + Write-Verbose "Test-TargetResource is false, $FeatureName is not $Ensure." + } + + return $result + +} + +<# +.Description +Query chocolatey features. +#> +function Get-ChocoFeature +{ + [OutputType([PSCustomObject])] + param( + [string] + $FeatureName + ) + choco feature -r | ConvertFrom-Csv -Delimiter "|" -Header Name, State, Description | Where-Object {$_.Name -eq $FeatureName} +} + + + + +Export-ModuleMember -Function *-TargetResource + diff --git a/DSCResources/cChocoFeature/cChocoFeature.schema.mof b/DSCResources/cChocoFeature/cChocoFeature.schema.mof new file mode 100644 index 0000000..6b1c53a --- /dev/null +++ b/DSCResources/cChocoFeature/cChocoFeature.schema.mof @@ -0,0 +1,8 @@ + +[ClassVersion("1.0.0.0"), FriendlyName("cChocoFeature")] +class cChocoFeature : OMI_BaseResource +{ + [Key] String FeatureName; + [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure; +}; + diff --git a/Examples/cChocoFeatureExample.ps1 b/Examples/cChocoFeatureExample.ps1 new file mode 100644 index 0000000..8cd1b70 --- /dev/null +++ b/Examples/cChocoFeatureExample.ps1 @@ -0,0 +1,41 @@ +# Copyright (c) 2017 Chocolatey Software, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +configuration ChocoFeatures { + + Import-DscResource -ModuleName cChoco + + Node 'localhost' { + + cChocoFeature allowGlobalConfirmation { + + FeatureName = "allowGlobalConfirmation" + Ensure = 'Present' + + } + + cChocoFeature powershellHost { + + FeatureName = "powershellHost" + Ensure = 'Absent' + } + } + +} + + +$config = ChocoFeatures + +Start-DscConfiguration -Path $config.psparentpath -Wait -Verbose -Force diff --git a/Tests/cChocoFeature_Tests.ps1 b/Tests/cChocoFeature_Tests.ps1 new file mode 100644 index 0000000..4c67253 --- /dev/null +++ b/Tests/cChocoFeature_Tests.ps1 @@ -0,0 +1,87 @@ +# Copyright (c) 2017 Chocolatey Software, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +$ResourceName = ((Split-Path $MyInvocation.MyCommand.Path -Leaf) -split '_')[0] +$ResourceFile = (Get-DscResource -Name $ResourceName).Path + +$TestsPath = (split-path -path $MyInvocation.MyCommand.Path -Parent) +$ResourceFile = Get-ChildItem -Recurse $TestsPath\.. -File | Where-Object {$_.name -eq "$ResourceName.psm1"} + +Import-Module -Name $ResourceFile.FullName + + +#---------------------------------# +# Pester tests for cChocoInstall # +#---------------------------------# +Describe "Testing cChocoFeature" { + + Context "Test-TargetResource" { + + mock -ModuleName cChocoFeature -CommandName Get-ChocoFeature -MockWith { + @([pscustomobject]@{ + Name = "allowGlobalConfirmation" + State = "Enabled" + Description = "blah" + }, + [pscustomobject]@{ + Name = "powershellhost" + State = "Disabled" + Description = "blah" + } )| Where-Object { $_.Name -eq $FeatureName } + } -Verifiable + + + it 'Test-TargetResource returns true when Present and Enabled.' { + Test-TargetResource -FeatureName 'allowGlobalConfirmation' -Ensure 'Present' | should be $true + } + + it 'Test-TargetResource returns false when Present and Disabled' { + Test-TargetResource -FeatureName 'powershellhost' -Ensure 'Present' | should be $false + } + + it 'Test-TargetResource returns false when Absent and Enabled' { + Test-TargetResource -FeatureName 'allowGlobalConfirmation' -Ensure 'Absent' | Should be $false + } + + it 'Test-TargetResource returns true when Absent and Disabled' { + Test-TargetResource -FeatureName 'powershellhost' -Ensure 'Absent' | should be $true + } + + } + + Context "Set-TargetResource" { + + InModuleScope -ModuleName cChocoFeature -ScriptBlock { + function choco {} + mock choco {} + } + + Set-TargetResource -FeatureName "TestFeature" -Ensure "Present" + + it "Present - Should have called choco, with enable" { + Assert-MockCalled -CommandName choco -ModuleName cChocoFeature -ParameterFilter { + $args -contains "enable" + } + } + + Set-TargetResource -FeatureName "TestFeature" -Ensure "Absent" + + it "Absent - Should have called choco, with disable" { + Assert-MockCalled -CommandName choco -ModuleName cChocoFeature -ParameterFilter { + $args -contains "disable" + } + } + } +} \ No newline at end of file diff --git a/Tests/cChoco_ScriptAnalyzerTests.ps1 b/Tests/cChoco_ScriptAnalyzerTests.ps1 index 89c3441..699758b 100644 --- a/Tests/cChoco_ScriptAnalyzerTests.ps1 +++ b/Tests/cChoco_ScriptAnalyzerTests.ps1 @@ -19,7 +19,7 @@ $Rules = Get-ScriptAnalyzerRule #Only run on cChocoInstaller.psm1 for now as this is the only resource that has had code adjustments for PSScriptAnalyzer rules. -$Modules = Get-ChildItem “$PSScriptRoot\..\” -Filter ‘*.psm1’ -Recurse | Where-Object {$_.FullName -match '(cChocoInstaller|cChocoPackageInstall)\.psm1$'} +$Modules = Get-ChildItem “$PSScriptRoot\..\” -Filter ‘*.psm1’ -Recurse | Where-Object {$_.FullName -match '(cChocoInstaller|cChocoPackageInstall|cChocoFeature)\.psm1$'} #---------------------------------# # Run Module tests (psm1) #