Debian Codegraph @

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

raw
1 #!powershell
2
3 # Copyright: (c) 2021, Kento Yagisawa <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #AnsibleRequires -CSharpUtil Ansible.Basic
7
8 $spec = @{
9 options = @{
10 # Need to support \* which type='path' does not, the path is expanded further down.
11 src = @{ type = 'str'; required = $true }
12 dest = @{ type = 'path'; required = $true }
13 }
14 supports_check_mode = $true
15 }
16 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
17
18 $src = [Environment]::ExpandEnvironmentVariables($module.Params.src)
19 $dest = $module.Params.dest
20
21 $srcFile = [System.IO.Path]::GetFileName($src)
22 $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
23 $encoding = New-Object -TypeName System.Text.UTF8Encoding -ArgumentList $false
24 $srcWildcard = $false
25
26 # If the path ends with '\*' we want to include the dir contents and not the dir itself
27 If ($src -match '\\\*$') {
28 $srcWildcard = $true
29 $src = $src.Substring(0, $src.Length - 2)
30 }
31
32 If (-not (Test-Path -LiteralPath $src)) {
33 $module.FailJson("The source file or directory '$src' does not exist.")
34 }
35
36 If ($dest -notlike "*.zip") {
37 $module.FailJson("The destination zip file path '$dest' need to be zip file path.")
38 }
39
40 If (Test-Path -LiteralPath $dest) {
41 $module.Result.msg = "The destination zip file '$dest' already exists."
42 $module.ExitJson()
43 }
44
45 # Check .NET v4.5 or later version exists or not
46 try {
47 Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Stop
48 }
49 catch {
50 $module.FailJson(".NET Framework 4.5 or later version needs to be installed.", $_)
51 }
52
53 Function Compress-Zip($src, $dest) {
54 # Disable using backslash for Zip path. This works for .NET 4.6.1 or later
55 if ([object].Assembly.GetType("System.AppContext")) {
56 [System.AppContext]::SetSwitch('Switch.System.IO.Compression.ZipFile.UseBackslash', $false)
57 }
58
59 If (-not $module.CheckMode) {
60 If (Test-Path -LiteralPath $src -PathType Container) {
61 [System.IO.Compression.ZipFile]::CreateFromDirectory($src, $dest, $compressionLevel, (-not $srcWildcard), $encoding)
62 }
63 Else {
64 $zip = [System.IO.Compression.ZipFile]::Open($dest, 'Update')
65 try {
66 [void][System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $src, $srcFile, $compressionLevel)
67 }
68 finally {
69 $zip.Dispose()
70 }
71 }
72 }
73 $module.Result.changed = $true
74 }
75
76 Compress-Zip -src $src -dest $dest
77
78 $module.ExitJson()