summaryrefslogtreecommitdiff
path: root/library/decompress.py
blob: e07eb949e27c34671a7199c55d0572f65bee7b3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/python
# this is based on https://github.com/socratesx/Ansible-Decompress

import zipfile
import os
import posixpath
import shutil
import xopen
from ansible.module_utils.basic import AnsibleModule
ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: decompress

short_description: This is a simple module for decompressing unarchived files

version_added: "2.4"

description:
    - "The module gets either a gz,bz2 or zip compressed file and just uncompress its content. Its purpose is to cover the case where a single file is just compressed such as a bootimage.iso.gz. but not archived. In case the file is archived, e.g. bootimage.tar.gz then the core module unarchive can handle it."

options:
    src:
        description:
            - This is the absolute path of the compressed file
        required: true
    dest:
        description:
            - The destination of the uncompressed file. This can be an absolute file path where the content will be saved as the specified filename, a directory where the filename will match the src filename without the (.gz|.bz2|.xz|.zip) extention or undefined. In the last case the file will be uncompressed in the same directory of the src with the same filename without the compress extention.
        required: false
    force:
        description:
            - Set this option to True to overwrite the extracted file in case it exists on destination.
        required: false
        default: false
    update:
        description:
            - Set this to True to overwrite the file only if it has different size/
        required: false
        default: true

extends_documentation_fragment:
    - files

author:
    - Socrates Chouridis
    - Christian Pointner
'''

EXAMPLES = '''
# This will decompress the bootimage.iso.gz and move it to ~/isos/bootimage.iso
- name: Decompress a gzipped iso image downloaded from the Internet
  decompress:
    src: '/tmp/bootimage.iso.gz'
    dest: '~/isos/'

# Setting the extracted file name explicitly
- name: Decompress a bz2 iso image downloaded from the Internet
  decompress:
    src: '/tmp/bootimage.iso.bz2'
    dest: '~/isos/newname_image.iso'

# Extract multiple images using with_items
- name: decompress multiple images
  decompress:
    src: "{{ item }}"
    dest: '/my-images/'
    force: true
  with_items: "{{ compressed_isos_list }}"

# Setting just the src will use the same name ommiting the extention, the result will be /tmp/bootimage.iso
- name: Decompress in the same folder using the same name
  decompress:
    src: '/tmp/bootimage.iso.zip'


'''

RETURN = ''':
message:
    description: An information message regarding the decompression result.
    returned: 'always'
    type: 'str'
files:
    description: A list containing the files in the compressed file.
    returned: success
    type: list
'''


def decompress_file(data={}):
    try:
        destination = data['dest']
        force = data['force']
        update = data['update']
        original_file_path = str(posixpath.abspath(data['src']))  # Original File  Absolute Path
        original_file_dir = os.path.dirname(original_file_path)
        path_list = os.path.splitext(original_file_path)  # List
        ext = path_list[1]

        if not destination:
            extracted_filename = path_list[0]
        elif not os.path.dirname(destination):
            extracted_filename = os.path.join(original_file_dir, destination)
        elif os.path.isdir(destination):
            extracted_filename = os.path.join(destination, os.path.basename(path_list[0]))

        if ext in [".gz", ".bz2", ".xz"]:
            result = use_xopen(original_file_path, extracted_filename, force)
        elif ext == ".zip":
            result = use_unzip(original_file_path, os.path.dirname(extracted_filename), force, update)
        else:
            message = "The file type " + "\"" + ext + "\"" + " is not supported by this module. Supported File Formats: .gz, .bz2, .xz, .zip"
            return True, False, message, [original_file_path]

        return result[0], result[1], result[2], result[3]

    except Exception as e:
        message = "An error occured. Decompress Failed: " + str(e)
        return True, False, message, []


def use_xopen(src, dst, force):
    dst_exists = False
    if os.path.exists(dst):
        dst_exists = True

    with xopen.xopen(src, 'rb') as f_in, open(dst, 'wb') as f_out:
        if not dst_exists:
            shutil.copyfileobj(f_in, f_out)
            message = "File Extracted Successfully: " + dst
            return False, True, message, [dst]
        else:
            if force:
                shutil.copyfileobj(f_in, f_out)
                message = "File Extracted Successfully and replaced file (Force = True): " + dst
                return False, True, message, [dst]
            else:
                message = "File Exists: skipping extraction (Use Force=True to Overwrite): " + dst
                return False, False, message, [dst]


def use_unzip(src, dst, force=False, update=True):
    filelist = []
    for root, dirs, files in os.walk(dst):
        for d in dirs:
            filelist.append(os.path.relpath(os.path.join(root, d), dst))
        for f in files:
            filelist.append(os.path.relpath(os.path.join(root, f), dst))

    extracted_files = []
    excluded_files = []
    with zipfile.ZipFile(src, 'r') as zip_file:
        for f in zip_file.namelist():
            if not os.path.relpath(f) in filelist:
                zip_file.extract(f, dst)
                extracted_files.append(f)
            else:
                if force:
                    zip_file.extract(f, dst)
                    extracted_files.append(f)
                else:
                    info = zip_file.getinfo(f)
                    if info.file_size != os.stat(dst + "/" + f).st_size:
                        if update:
                            zip_file.extract(f, dst)
                            extracted_files.append(f)
                        else:
                            excluded_files.append(f)
                    else:
                        excluded_files.append(f)
    if not excluded_files:
        message = " All files were extracted successfully"
        for file in extracted_files:
            if not force and update and file in filelist:
                message = "Files with the same name on destination were replaced as they had different size (Update=True)"
            elif force:
                message = "All files were extracted successfully replacing any files on destination with the same name (Force=True)"
        return False, True, message, [os.path.join(dst, file) for file in extracted_files]
    else:
        if not extracted_files:
            message = "All Files Exist on Destination, Skipping Extraction... Use Force=True to Overwrite"
            return False, False, message, [os.path.join(dst, file) for file in filelist]
        else:
            message = "Some Files Skipped Extraction as they Existed on destination. Use Force=True to Overwrite "
            return False, True, message, [os.path.join(dst, file) for file in filelist]


def run_module():
    module_args = dict(
        src=dict(type='str', required=True),
        dest=dict(type='str', required=False),
        force=dict(type='bool', required=False, default=False),
        update=dict(type='bool', required=False, default=True),
    )

    result = dict(
        changed=False,
        message='',
        failed=False,
        files=[],
    )

    module = AnsibleModule(argument_spec=module_args)

    (error, is_changed, message, files) = decompress_file(module.params)

    result['changed'] = is_changed
    result['message'] = message
    result['failed'] = error
    result['files'] = files

    module.exit_json(**result)


def main():
    run_module()


if __name__ == '__main__':
    main()