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/AppVeyor/AppVeyorBuild.ps1 b/AppVeyor/AppVeyorBuild.ps1 index 6fb7f23..287df2d 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" @@ -11,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/AppVeyorDeploy.ps1 b/AppVeyor/AppVeyorDeploy.ps1 index 16d66b1..df684d5 100644 --- a/AppVeyor/AppVeyorDeploy.ps1 +++ b/AppVeyor/AppVeyorDeploy.ps1 @@ -1,11 +1,26 @@ -#---------------------------------# -# 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 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,11 +29,11 @@ $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') ) +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/AppVeyor/AppVeyorInstall.ps1 b/AppVeyor/AppVeyorInstall.ps1 index ca8603c..0375f61 100644 --- a/AppVeyor/AppVeyorInstall.ps1 +++ b/AppVeyor/AppVeyorInstall.ps1 @@ -1,35 +1,50 @@ -#---------------------------------# -# 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 -#---------------------------------# -# 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 1729ab5..5186183 100644 --- a/AppVeyor/AppVeyorTest.ps1 +++ b/AppVeyor/AppVeyorTest.ps1 @@ -1,12 +1,27 @@ -#---------------------------------# -# 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" -#---------------------------------# -# 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 @@ -18,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/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/DSCResources/cChocoInstaller/cChocoInstaller.psm1 b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 index 1ca852a..e4e096c 100644 --- a/DSCResources/cChocoInstaller/cChocoInstaller.psm1 +++ b/DSCResources/cChocoInstaller/cChocoInstaller.psm1 @@ -1,195 +1,210 @@ -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 +# 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 + ( + [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..91acfae 100644 --- a/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 +++ b/DSCResources/cChocoPackageInstall/cChocoPackageInstall.psm1 @@ -1,198 +1,213 @@ -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] +# 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 + ( + [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 -pSource $Source -cParams $chocoParams + } elseif ($AutoUpgrade) { + Write-Verbose -Message "Upgrading $Name due to version mis-match" + 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 -pSource $Source -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 -pSource $Source + } 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 } - - 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 -{ + + 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','')] @@ -204,11 +219,13 @@ function InstallPackage [Parameter(Position=2)] [string]$pVersion, [Parameter(Position=3)] + [string]$pSource, + [Parameter(Position=4)] [string]$cParams - ) + ) $env:Path = [Environment]::GetEnvironmentVariable('Path','Machine') - + [string]$chocoinstallparams = '-y' if ($pParams) { $chocoinstallparams += " --params=`"$pParams`"" @@ -216,118 +233,129 @@ function InstallPackage if ($pVersion) { $chocoinstallparams += " --version=`"$pVersion`"" } + if ($pSource) { + $chocoinstallparams += " --source=`"$pSource`"" + } if ($cParams) { $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 " #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 { + [Diagnostics.CodeAnalysis.SuppressMessage('PSAvoidUsingInvokeExpression','')] + param( + [Parameter(Mandatory)] + [string]$pName, + [Parameter(Mandatory)] + [string]$pSource + ) + Write-Verbose -Message "Testing if $pName can be upgraded" + + [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 ($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. +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','')] @@ -337,40 +365,38 @@ Function Upgrade-Package { [Parameter(Position=1)] [string]$pParams, [Parameter(Position=2)] + [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`"" } + 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)) { throw "$pName is not installed, you cannot upgrade" - } - + } + $packageUpgradeOuput = Invoke-Expression -Command $cmd $packageUpgradeOuput | ForEach-Object { Write-Verbose -Message $_ } } - + function Get-ChocoInstalledPackage { - $res = choco list -lo | ForEach-Object { - $Obj = $_ -split '\s' - [pscustomobject]@{ - 'Name' = $Obj[0] - 'Version' = $Obj[1] - } - } - Return $res -} - -Export-ModuleMember -Function *-TargetResource \ No newline at end of file + Return (choco list -lo -r | ConvertFrom-Csv -Header 'Name', 'Version' -Delimiter "|") +} + +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.psd1 index a5a963f..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 @@ -16,13 +17,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 a70d55e..f5fbab7 100644 --- a/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 +++ b/DSCResources/cChocoPackageInstallerSet/cChocoPackageInstallerSet.schema.psm1 @@ -1,43 +1,45 @@ -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 - } - } - } -} +# 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 +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 + ) + + foreach ($pName in $Name) { + cChocoPackageInstaller "cChocoPackageInstaller_$($Ensure)_$($pName)" { + Ensure = $Ensure + Name = $pName + Source = $Source + } + } +} diff --git a/DSCResources/cChocoSource/cChocoSource.psm1 b/DSCResources/cChocoSource/cChocoSource.psm1 index 7d0d90b..441053f 100644 --- a/DSCResources/cChocoSource/cChocoSource.psm1 +++ b/DSCResources/cChocoSource/cChocoSource.psm1 @@ -1,172 +1,187 @@ -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 +# 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])] + 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/ExampleConfig.ps1 b/ExampleConfig.ps1 index c36e69a..505e479 100644 --- a/ExampleConfig.ps1 +++ b/ExampleConfig.ps1 @@ -1,6 +1,21 @@ +# 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 + Import-DscResource -Module cChoco Node "localhost" { LocalConfigurationManager @@ -15,7 +30,7 @@ Configuration myChocoConfig { Name = "googlechrome" DependsOn = "[cChocoInstaller]installChoco" - #This will automatically try to upgrade if available, only if a version is not explicitly specified. + #This will automatically try to upgrade if available, only if a version is not explicitly specified. AutoUpgrade = $True } cChocoPackageInstaller installAtomSpecificVersion @@ -58,8 +73,8 @@ Configuration myChocoConfig DependsOn = "[cChocoInstaller]installChoco" } } -} +} myChocoConfig -Start-DscConfiguration .\myChocoConfig -wait -Verbose -force \ No newline at end of file +Start-DscConfiguration .\myChocoConfig -wait -Verbose -force 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/Examples/cChocoInstaller_cChocoInstallerExample.ps1 b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 index 37a28bf..7457162 100644 --- a/Examples/cChocoInstaller_cChocoInstallerExample.ps1 +++ b/Examples/cChocoInstaller_cChocoInstallerExample.ps1 @@ -1,6 +1,21 @@ -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 + Import-DscResource -Module cChoco Node "localhost" { cChocoInstaller InstallChoco @@ -14,8 +29,8 @@ 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 53b26e3..96f3633 100644 --- a/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 +++ b/Examples/cChocoInstaller_cChocoPackageInstallExample.ps1 @@ -1,17 +1,33 @@ -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 + Import-DscResource -Module cChoco Node "localhost" { cChocoPackageInstaller installSkypeWithChocoParams { Name = 'skype' Ensure = 'Present' - AutoUpgrade = $True + 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 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/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/cChocoInstaller_Tests.ps1 b/Tests/cChocoInstaller_Tests.ps1 index 48f32ff..77fc1f2 100644 --- a/Tests/cChocoInstaller_Tests.ps1 +++ b/Tests/cChocoInstaller_Tests.ps1 @@ -1,13 +1,28 @@ -#---------------------------------# -# 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 - +$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 a9c6f63..e522f64 100644 --- a/Tests/cChocoPackageInstall_Tests.ps1 +++ b/Tests/cChocoPackageInstall_Tests.ps1 @@ -1,23 +1,38 @@ -#----------------------------------------# -# 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 - -$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' @@ -33,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 } @@ -64,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' @@ -92,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 } @@ -102,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 } @@ -110,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 462fdfe..699758b 100644 --- a/Tests/cChoco_ScriptAnalyzerTests.ps1 +++ b/Tests/cChoco_ScriptAnalyzerTests.ps1 @@ -1,14 +1,29 @@ -#---------------------------------# -# 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. -$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) # -#---------------------------------# +#---------------------------------# +# Run Module tests (psm1) # +#---------------------------------# if ($Modules.count -gt 0) { Describe ‘Testing all Modules against default PSScriptAnalyzer rule-set’ { foreach ($module in $modules) { @@ -21,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 397737a..4c061e5 100644 --- a/Tests/cChoco_xDscResourceTests.ps1 +++ b/Tests/cChoco_xDscResourceTests.ps1 @@ -1,26 +1,41 @@ -#---------------------------------# -# 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'} - -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 + } +} diff --git a/cChoco.psd1 b/cChoco.psd1 index 3e5ceff..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"; diff --git a/readme.md b/readme.md index 2d0e131..4f26d20 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,30 +19,30 @@ 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). +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' - 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