Debian Codegraph @

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

raw
1 #!powershell
2
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 #Requires -Module Ansible.ModuleUtils.Legacy
6 #Requires -Module Ansible.ModuleUtils.Backup
7
8 function WriteLines($outlines, $path, $linesep, $encodingobj, $validate, $check_mode) {
9 Try {
10 $temppath = [System.IO.Path]::GetTempFileName()
11 }
12 Catch {
13 Fail-Json @{} "Cannot create temporary file! ($($_.Exception.Message))"
14 }
15 $joined = $outlines -join $linesep
16 [System.IO.File]::WriteAllText($temppath, $joined, $encodingobj)
17
18 If ($validate) {
19
20 If (-not ($validate -like "*%s*")) {
21 Fail-Json @{} "validate must contain %s: $validate"
22 }
23
24 $validate = $validate.Replace("%s", $temppath)
25
26 $parts = [System.Collections.ArrayList] $validate.Split(" ")
27 $cmdname = $parts[0]
28
29 $cmdargs = $validate.Substring($cmdname.Length + 1)
30
31 $process = [Diagnostics.Process]::Start($cmdname, $cmdargs)
32 $process.WaitForExit()
33
34 If ($process.ExitCode -ne 0) {
35 [string] $output = $process.StandardOutput.ReadToEnd()
36 [string] $error = $process.StandardError.ReadToEnd()
37 Remove-Item -LiteralPath $temppath -Force
38 Fail-Json @{} "failed to validate $cmdname $cmdargs with error: $output $error"
39 }
40
41 }
42
43 # Commit changes to the path
44 $cleanpath = $path.Replace("/", "\")
45 Try {
46 Copy-Item -LiteralPath $temppath -Destination $cleanpath -Force -WhatIf:$check_mode
47 }
48 Catch {
49 Fail-Json @{} "Cannot write to: $cleanpath ($($_.Exception.Message))"
50 }
51
52 Try {
53 Remove-Item -LiteralPath $temppath -Force -WhatIf:$check_mode
54 }
55 Catch {
56 Fail-Json @{} "Cannot remove temporary file: $temppath ($($_.Exception.Message))"
57 }
58
59 return $joined
60
61 }
62
63
64 # Implement the functionality for state == 'present'
65 function Present {
66 param (
67 $path,
68 $regex,
69 $line,
70 $insertafter,
71 $insertbefore,
72 $create,
73 $backup,
74 $backrefs,
75 $validate,
76 $encodingobj,
77 $linesep,
78 $check_mode,
79 $diff_support
80 )
81
82 # Note that we have to clean up the path because ansible wants to treat / and \ as
83 # interchangeable in windows pathnames, but .NET framework internals do not support that.
84 $cleanpath = $path.Replace("/", "\")
85 $endswithnewline = $null
86
87 # Check if path exists. If it does not exist, either create it if create == "yes"
88 # was specified or fail with a reasonable error message.
89 If (-not (Test-Path -LiteralPath $path)) {
90 If (-not $create) {
91 Fail-Json @{} "Path $path does not exist !"
92 }
93 # Create new empty file, using the specified encoding to write correct BOM
94 [System.IO.File]::WriteAllLines($cleanpath, "", $encodingobj)
95 $endswithnewline = $false
96 }
97
98 # Initialize result information
99 $result = @{
100 backup = ""
101 changed = $false
102 msg = ""
103 }
104
105 If ($insertbefore -and $insertafter) {
106 Add-Warning $result "Both insertbefore and insertafter parameters found, ignoring `"insertafter=$insertafter`""
107 }
108
109 # Read the dest file lines using the indicated encoding into a mutable ArrayList.
110 $before = [System.IO.File]::ReadAllLines($cleanpath, $encodingobj)
111 If ($null -eq $before) {
112 $lines = New-Object System.Collections.ArrayList
113 }
114 Else {
115 $lines = [System.Collections.ArrayList] $before
116 If ($null -eq $endswithnewline ) {
117 $alltext = [System.IO.File]::ReadAllText($cleanpath, $encodingobj)
118 $endswithnewline = (($alltext[-1] -eq "`n") -or ($alltext[-1] -eq "`r"))
119 }
120 }
121
122 if ($diff_support) {
123 if ($endswithnewline) {
124 $before += ""
125 }
126 $result.diff = @{
127 before = $before -join $linesep
128 }
129 }
130
131 # Compile the regex specified, if provided
132 $mre = $null
133 If ($regex) {
134 $mre = New-Object Regex $regex, 'Compiled'
135 }
136
137 # Compile the regex for insertafter or insertbefore, if provided
138 $insre = $null
139 If ($insertafter -and $insertafter -ne "BOF" -and $insertafter -ne "EOF") {
140 $insre = New-Object Regex $insertafter, 'Compiled'
141 }
142 ElseIf ($insertbefore -and $insertbefore -ne "BOF") {
143 $insre = New-Object Regex $insertbefore, 'Compiled'
144 }
145
146 # index[0] is the line num where regex has been found
147 # index[1] is the line num where insertafter/insertbefore has been found
148 $index = -1, -1
149 $lineno = 0
150
151 # The latest match object and matched line
152 $matched_line = ""
153
154 # Iterate through the lines in the file looking for matches
155 Foreach ($cur_line in $lines) {
156 If ($regex) {
157 $m = $mre.Match($cur_line)
158 $match_found = $m.Success
159 If ($match_found) {
160 $matched_line = $cur_line
161 }
162 }
163 Else {
164 $match_found = $line -ceq $cur_line
165 }
166 If ($match_found) {
167 $index[0] = $lineno
168 }
169 ElseIf ($insre -and $insre.Match($cur_line).Success) {
170 If ($insertafter) {
171 $index[1] = $lineno + 1
172 }
173 If ($insertbefore) {
174 $index[1] = $lineno
175 }
176 }
177 $lineno = $lineno + 1
178 }
179
180 If ($index[0] -ne -1) {
181 If ($backrefs) {
182 $new_line = [regex]::Replace($matched_line, $regex, $line)
183 }
184 Else {
185 $new_line = $line
186 }
187 If ($lines[$index[0]] -cne $new_line) {
188 $lines[$index[0]] = $new_line
189 $result.changed = $true
190 $result.msg = "line replaced"
191 }
192 }
193 ElseIf ($backrefs) {
194 # No matches - no-op
195 }
196 ElseIf ($insertbefore -eq "BOF" -or $insertafter -eq "BOF") {
197 $lines.Insert(0, $line)
198 $result.changed = $true
199 $result.msg = "line added"
200 }
201 ElseIf ($insertafter -eq "EOF" -or $index[1] -eq -1) {
202 $lines.Add($line) > $null
203 $result.changed = $true
204 $result.msg = "line added"
205 }
206 Else {
207 $lines.Insert($index[1], $line)
208 $result.changed = $true
209 $result.msg = "line added"
210 }
211
212 # Write changes to the path if changes were made
213 If ($result.changed) {
214
215 # Write backup file if backup == "yes"
216 If ($backup) {
217 $result.backup_file = Backup-File -path $path -WhatIf:$check_mode
218 }
219
220 if ($endswithnewline) {
221 $lines.Add("")
222 }
223
224 $writelines_params = @{
225 outlines = $lines
226 path = $path
227 linesep = $linesep
228 encodingobj = $encodingobj
229 validate = $validate
230 check_mode = $check_mode
231 }
232 $after = WriteLines @writelines_params
233
234 if ($diff_support) {
235 $result.diff.after = $after
236 }
237 }
238
239 $result.encoding = $encodingobj.WebName
240
241 Exit-Json $result
242 }
243
244
245 # Implement the functionality for state == 'absent'
246 function Absent($path, $regex, $line, $backup, $validate, $encodingobj, $linesep, $check_mode, $diff_support) {
247
248 # Check if path exists. If it does not exist, fail with a reasonable error message.
249 If (-not (Test-Path -LiteralPath $path)) {
250 Fail-Json @{} "Path $path does not exist !"
251 }
252
253 # Initialize result information
254 $result = @{
255 backup = ""
256 changed = $false
257 msg = ""
258 }
259
260 # Read the dest file lines using the indicated encoding into a mutable ArrayList. Note
261 # that we have to clean up the path because ansible wants to treat / and \ as
262 # interchangeable in windows pathnames, but .NET framework internals do not support that.
263 $cleanpath = $path.Replace("/", "\")
264 $before = [System.IO.File]::ReadAllLines($cleanpath, $encodingobj)
265 If ($null -eq $before) {
266 $lines = New-Object System.Collections.ArrayList
267 }
268 Else {
269 $lines = [System.Collections.ArrayList] $before
270 $alltext = [System.IO.File]::ReadAllText($cleanpath, $encodingobj)
271 If (($alltext[-1] -eq "`n") -or ($alltext[-1] -eq "`r")) {
272 $lines.Add("")
273 $before += ""
274 }
275 }
276
277 if ($diff_support) {
278 $result.diff = @{
279 before = $before -join $linesep
280 }
281 }
282
283 # Compile the regex specified, if provided
284 $cre = $null
285 If ($regex) {
286 $cre = New-Object Regex $regex, 'Compiled'
287 }
288
289 $found = New-Object System.Collections.ArrayList
290 $left = New-Object System.Collections.ArrayList
291
292 Foreach ($cur_line in $lines) {
293 If ($regex) {
294 $m = $cre.Match($cur_line)
295 $match_found = $m.Success
296 }
297 Else {
298 $match_found = $line -ceq $cur_line
299 }
300 If ($match_found) {
301 $found.Add($cur_line) > $null
302 $result.changed = $true
303 }
304 Else {
305 $left.Add($cur_line) > $null
306 }
307 }
308
309 # Write changes to the path if changes were made
310 If ($result.changed) {
311
312 # Write backup file if backup == "yes"
313 If ($backup) {
314 $result.backup_file = Backup-File -path $path -WhatIf:$check_mode
315 }
316
317 $writelines_params = @{
318 outlines = $left
319 path = $path
320 linesep = $linesep
321 encodingobj = $encodingobj
322 validate = $validate
323 check_mode = $check_mode
324 }
325 $after = WriteLines @writelines_params
326
327 if ($diff_support) {
328 $result.diff.after = $after
329 }
330 }
331
332 $result.encoding = $encodingobj.WebName
333 $result.found = $found.Count
334 $result.msg = "$($found.Count) line(s) removed"
335
336 Exit-Json $result
337 }
338
339
340 # Parse the parameters file dropped by the Ansible machinery
341 $params = Parse-Args $args -supports_check_mode $true
342 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
343 $diff_support = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false
344
345 # Initialize defaults for input parameters.
346 $path = Get-AnsibleParam -obj $params -name "path" -type "path" -failifempty $true -aliases "dest", "destfile", "name"
347 $regex = Get-AnsibleParam -obj $params -name "regex" -type "str" -aliases "regexp"
348 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present", "absent"
349 $line = Get-AnsibleParam -obj $params -name "line" -type "str"
350 $backrefs = Get-AnsibleParam -obj $params -name "backrefs" -type "bool" -default $false
351 $insertafter = Get-AnsibleParam -obj $params -name "insertafter" -type "str"
352 $insertbefore = Get-AnsibleParam -obj $params -name "insertbefore" -type "str"
353 $create = Get-AnsibleParam -obj $params -name "create" -type "bool" -default $false
354 $backup = Get-AnsibleParam -obj $params -name "backup" -type "bool" -default $false
355 $validate = Get-AnsibleParam -obj $params -name "validate" -type "str"
356 $encoding = Get-AnsibleParam -obj $params -name "encoding" -type "str" -default "auto"
357 $newline = Get-AnsibleParam -obj $params -name "newline" -type "str" -default "windows" -validateset "unix", "windows"
358
359 # Fail if the path is not a file
360 If (Test-Path -LiteralPath $path -PathType "container") {
361 Fail-Json @{} "Path $path is a directory"
362 }
363
364 # Default to windows line separator - probably most common
365 $linesep = "`r`n"
366 If ($newline -eq "unix") {
367 $linesep = "`n"
368 }
369
370 # Figure out the proper encoding to use for reading / writing the target file.
371
372 # The default encoding is UTF-8 without BOM
373 $encodingobj = [System.Text.UTF8Encoding] $false
374
375 # If an explicit encoding is specified, use that instead
376 If ($encoding -ne "auto") {
377 $encodingobj = [System.Text.Encoding]::GetEncoding($encoding)
378 }
379
380 # Otherwise see if we can determine the current encoding of the target file.
381 # If the file doesn't exist yet (create == 'yes') we use the default or
382 # explicitly specified encoding set above.
383 ElseIf (Test-Path -LiteralPath $path) {
384
385 # Get a sorted list of encodings with preambles, longest first
386 $max_preamble_len = 0
387 $sortedlist = New-Object System.Collections.SortedList
388 Foreach ($encodinginfo in [System.Text.Encoding]::GetEncodings()) {
389 $encoding = $encodinginfo.GetEncoding()
390 $plen = $encoding.GetPreamble().Length
391 If ($plen -gt $max_preamble_len) {
392 $max_preamble_len = $plen
393 }
394 If ($plen -gt 0) {
395 $sortedlist.Add( - ($plen * 1000000 + $encoding.CodePage), $encoding) > $null
396 }
397 }
398
399 # Get the first N bytes from the file, where N is the max preamble length we saw
400 [Byte[]]$bom = Get-Content -Encoding Byte -ReadCount $max_preamble_len -TotalCount $max_preamble_len -LiteralPath $path
401
402 # Iterate through the sorted encodings, looking for a full match.
403 $found = $false
404 Foreach ($encoding in $sortedlist.GetValueList()) {
405 $preamble = $encoding.GetPreamble()
406 If ($preamble -and $bom) {
407 Foreach ($i in 0..($preamble.Length - 1)) {
408 If ($i -ge $bom.Length) {
409 break
410 }
411 If ($preamble[$i] -ne $bom[$i]) {
412 break
413 }
414 ElseIf ($i + 1 -eq $preamble.Length) {
415 $encodingobj = $encoding
416 $found = $true
417 }
418 }
419 If ($found) {
420 break
421 }
422 }
423 }
424 }
425
426
427 # Main dispatch - based on the value of 'state', perform argument validation and
428 # call the appropriate handler function.
429 If ($state -eq "present") {
430
431 If ($backrefs -and -not $regex) {
432 Fail-Json @{} "regexp= is required with backrefs=true"
433 }
434
435 If (-not $line) {
436 Fail-Json @{} "line= is required with state=present"
437 }
438
439 If (-not $insertbefore -and -not $insertafter) {
440 $insertafter = "EOF"
441 }
442
443 $present_params = @{
444 path = $path
445 regex = $regex
446 line = $line
447 insertafter = $insertafter
448 insertbefore = $insertbefore
449 create = $create
450 backup = $backup
451 backrefs = $backrefs
452 validate = $validate
453 encodingobj = $encodingobj
454 linesep = $linesep
455 check_mode = $check_mode
456 diff_support = $diff_support
457 }
458 Present @present_params
459
460 }
461 ElseIf ($state -eq "absent") {
462
463 If (-not $regex -and -not $line) {
464 Fail-Json @{} "one of line= or regexp= is required with state=absent"
465 }
466
467 $absent_params = @{
468 path = $path
469 regex = $regex
470 line = $line
471 backup = $backup
472 validate = $validate
473 encodingobj = $encodingobj
474 linesep = $linesep
475 check_mode = $check_mode
476 diff_support = $diff_support
477 }
478 Absent @absent_params
479 }