Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_scoop.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2020, Jamie Magee <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #Requires -Module Ansible.ModuleUtils.ArgvParser
7 #Requires -Module Ansible.ModuleUtils.CommandUtil
8 #AnsibleRequires -CSharpUtil Ansible.Basic
9
10 $spec = @{
11 options = @{
12 architecture = @{ type = "str"; choices = "32bit", "64bit"; aliases = @(, "arch") }
13 independent = @{ type = "bool"; default = $false }
14 global = @{ type = "bool"; default = $false }
15 name = @{ type = "list"; elements = "str"; required = $true }
16 no_cache = @{ type = "bool"; default = $false }
17 purge = @{ type = "bool"; default = $false }
18 skip_checksum = @{ type = "bool"; default = $false }
19 state = @{ type = "str"; default = "present"; choices = "present", "absent" }
20 }
21 supports_check_mode = $true
22 }
23
24 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
25
26 $architecture = $module.Params.architecture
27 $independent = $module.Params.independent
28 $global = $module.Params.global
29 $name = $module.Params.name
30 $no_cache = $module.Params.no_cache
31 $purge = $module.Params.purge
32 $skip_checksum = $module.Params.skip_checksum
33 $state = $module.Params.state
34
35 $module.Result.rc = 0
36
37 function Install-Scoop {
38 [CmdletBinding()]
39 param ()
40
41 # Scoop doesn't have refreshenv like Chocolatey
42 # Let's try to update PATH first
43 $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
44
45 $scoop_app = Get-Command -Name scoop.ps1 -Type ExternalScript -ErrorAction SilentlyContinue
46 if ($module.CheckMode -and $null -eq $scoop_app) {
47 $module.Result.skipped = $true
48 $module.Result.msg = "Skipped check mode run on win_scoop as scoop.ps1 cannot be found on the system"
49 $module.ExitJson()
50 }
51 elseif ($null -eq $scoop_app) {
52 # We need to install scoop
53 # We run this in a separate process to make it easier to get the result in a failure and capture any output that
54 # might be sent to the host. We also need to enable TLS 1.2 in that process and not here so it can download the
55 # install script and other components.
56 $install_script = {
57 # Enable TLS1.2 if it's available but disabled (eg. .NET 4.5)
58 $security_protocols = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::SystemDefault
59 if ([Net.SecurityProtocolType].GetMember("Tls12").Count -gt 0) {
60 $security_protocols = $security_protcols -bor [Net.SecurityProtocolType]::Tls12
61 }
62 [Net.ServicePointManager]::SecurityProtocol = $security_protocols
63
64 $script = (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')
65 $installer = [ScriptBlock]::Create($script)
66 $params = @{}
67
68 $current_user = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
69 if ($current_user.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
70 $params.RunAsAdmin = $true
71 }
72 . $installer -RunAsAdmin
73 }
74
75 $enc_command = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($install_script.ToString()))
76 $cmd = "powershell.exe -NoProfile -NoLogo -EncodedCommand $enc_command"
77
78 # Scoops installer does weird things and the exit code will most likely be 0. Use the presence of the scoop
79 # command as the indicator as to whether it was installed or not.
80 $res = Run-Command -Command $cmd -environment $environment
81
82 # Refresh PATH
83 $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
84
85 # locate the newly installed scoop.ps1
86 $scoop_app = Get-Command -Name scoop.ps1 -Type ExternalScript -ErrorAction SilentlyContinue
87
88 if ($null -eq $scoop_app -or -not (Test-Path -LiteralPath $scoop_app.Path)) {
89 $module.Result.rc = $res.rc
90 $module.Result.stdout = $res.stdout
91 $module.Result.stderr = $res.stderr
92 $module.FailJson("Failed to bootstrap scoop.ps1")
93 }
94
95 $module.Warn("Scoop was missing from this system, so it was installed during this task run.")
96 $module.Result.changed = $true
97 }
98
99 return $scoop_app.Path
100 }
101
102 function Get-ScoopPackage {
103 param(
104 [Parameter(Mandatory = $true)] [string]$scoop_path
105 )
106
107 $command = Argv-ToString -arguments @("powershell.exe", "-File", $scoop_path, "export")
108 $res = Run-Command -Command $command
109 if ($res.rc -ne 0) {
110 $module.Result.command = $command
111 $module.Result.rc = $res.rc
112 $module.Result.stdout = $res.stdout
113 $module.Result.stderr = $res.stderr
114 $module.FailJson("Error checking installed packages")
115 }
116
117 # Scoop since 0.2.3 output as JSON, older versions use a custom format
118 # https://github.com/ScoopInstaller/Scoop/commit/c4d1b9c22f943a810bed7f9f74d7d4d5c42d9a74
119 try {
120 $exportObj = ConvertFrom-Json -InputObject $res.stdout -ErrorAction Stop
121 }
122 catch {
123 $res.stdout -split "`n" |
124 Select-String '(.*?) \(v:(.*?)\)( \*global\*)? \[(.*?)\](\{32bit\})?' |
125 ForEach-Object {
126 [PSCustomObject]@{
127 Package = $_.Matches[0].Groups[1].Value
128 Version = $_.Matches[0].Groups[2].Value
129 Global = -not ([string]::IsNullOrWhiteSpace($_.Matches[0].Groups[3].Value))
130 Bucket = $_.Matches[0].Groups[4].Value
131 x86 = -not ([string]::IsNullOrWhiteSpace($_.Matches[0].Groups[5].Value))
132 }
133 }
134 return
135 }
136
137 $exportObj.apps | ForEach-Object {
138 $options = @($_.Info -split ',' | ForEach-Object Trim | Where-Object { $_ })
139 if ('Install failed' -in $options) {
140 return
141 }
142
143 [PSCustomObject]@{
144 Package = $_.Name
145 Version = $_.Version
146 Global = 'Global install' -in $options
147 Bucket = $_.Source
148 x86 = '32bit' -in $options
149 }
150 }
151 }
152
153 function Get-InstallScoopPackageArgument {
154 $arguments = [System.Collections.Generic.List[String]]@()
155
156 if ($architecture) {
157 $arguments.Add("--arch")
158 $arguments.Add($architecture)
159 }
160 if ($global) {
161 $arguments.Add("--global")
162 }
163 if ($independent) {
164 $arguments.Add("--independent")
165 }
166 if ($no_cache) {
167 $arguments.Add("--no-cache")
168 }
169 if ($skip_checksum) {
170 $arguments.Add("--skip")
171 }
172
173 return , $arguments
174 }
175
176 function Install-ScoopPackage {
177 param(
178 [Parameter(Mandatory = $true)] [string]$scoop_path,
179 [Parameter(Mandatory = $true)] [String[]]$packages
180 )
181 $arguments = [System.Collections.Generic.List[String]]@("powershell.exe", "-File", $scoop_path, "install")
182 $arguments.AddRange($packages)
183
184 $common_args = Get-InstallScoopPackageArgument
185 $arguments.AddRange($common_args)
186
187 $command = Argv-ToString -arguments $arguments
188
189 if (-not $module.CheckMode) {
190 $res = Run-Command -Command $command
191 if ($res.rc -ne 0) {
192 $module.Result.command = $command
193 $module.Result.rc = $res.rc
194 $module.Result.stdout = $res.stdout
195 $module.Result.stderr = $res.stderr
196 $module.FailJson("Error installing $packages")
197 }
198
199 if ($module.Verbosity -gt 1) {
200 $module.Result.stdout = $res.stdout
201 }
202 }
203 $module.Result.changed = $true
204 }
205
206 function Get-UninstallScoopPackageArgument {
207 $arguments = [System.Collections.Generic.List[String]]@()
208
209 if ($global) {
210 $arguments.Add("--global")
211 }
212 if ($purge) {
213 $arguments.Add("--purge")
214 }
215
216 return , $arguments
217 }
218
219 function Uninstall-ScoopPackage {
220 param(
221 [Parameter(Mandatory = $true)] [string]$scoop_path,
222 [Parameter(Mandatory = $true)] [String[]]$packages
223 )
224
225 $arguments = [System.Collections.Generic.List[String]]@("powershell.exe", "-File", $scoop_path, "uninstall")
226 $arguments.AddRange($packages)
227
228 $common_args = Get-UninstallScoopPackageArgument
229 $arguments.AddRange($common_args)
230
231 $command = Argv-ToString -arguments $arguments
232
233 if (-not $module.CheckMode) {
234 $res = Run-Command -Command $command
235 if ($res.rc -ne 0) {
236 $module.Result.command = $command
237 $module.Result.rc = $res.rc
238 $module.Result.stdout = $res.stdout
239 $module.Result.stderr = $res.stderr
240 $module.FailJson("Error uninstalling $packages")
241 }
242
243 if ($module.Verbosity -gt 1) {
244 $module.Result.stdout = $res.stdout
245 }
246 if (-not ($res.stdout -match "ERROR '(.*?)' isn't installed.")) {
247 $module.Result.changed = $true
248 }
249 }
250 else {
251 $module.Result.changed = $true
252 }
253 }
254
255 $scoop_path = Install-Scoop
256
257 $installed_packages = @(Get-ScoopPackage -scoop_path $scoop_path)
258
259 if ($state -in @("absent")) {
260 # Always attempt uninstall
261 # Packages can be in a broken state where they don't in appear scoop export
262 Uninstall-ScoopPackage -scoop_path $scoop_path -packages $name
263 }
264
265 if ($state -in @("present")) {
266 $missing_packages = foreach ($package in $name) {
267 if (
268 ($installed_packages.Package -notcontains $package) -or
269 (($installed_packages.Package -contains $package) -and (
270 ((($installed_packages | Where-Object { $_.Package -eq $package }).Global -contains $true) -and -not $global) -or
271 ((($installed_packages | Where-Object { $_.Package -eq $package }).Global -notcontains $true) -and $global)
272 )
273 )
274 ) {
275 $package
276 }
277 }
278 }
279
280 if ($missing_packages) {
281 Install-ScoopPackage -scoop_path $scoop_path -packages $missing_packages
282 }
283
284 $module.ExitJson()