vFW and vDNS support added to azure-plugin
[multicloud/azure.git] / azure / aria / aria-extension-cloudify / src / aria / aria / utils / archive.py
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 # See the License for the specific language governing permissions and
11 # limitations under the License.
12
13 """
14 Archive utilities.
15 """
16
17 import os
18 import tarfile
19 import zipfile
20 import tempfile
21 from contextlib import closing
22
23
24 def is_archive(source):
25     return tarfile.is_tarfile(source) or zipfile.is_zipfile(source)
26
27
28 def extract_archive(source):
29     if tarfile.is_tarfile(source):
30         return untar(source)
31     elif zipfile.is_zipfile(source):
32         return unzip(source)
33     raise ValueError(
34         'Unsupported archive type provided or archive is not valid: {0}.'.format(source))
35
36
37 def tar(source, destination):
38     with closing(tarfile.open(destination, 'w:gz')) as tar_archive:
39         tar_archive.add(source, arcname=os.path.basename(source))
40
41
42 def untar(archive, destination=None):
43     if not destination:
44         destination = tempfile.mkdtemp()
45     with closing(tarfile.open(name=archive)) as tar_archive:
46         tar_archive.extractall(path=destination, members=tar_archive.getmembers())
47     return destination
48
49
50 def zip(source, destination):
51     with closing(zipfile.ZipFile(destination, 'w')) as zip_file:
52         for root, _, files in os.walk(source):
53             for filename in files:
54                 file_path = os.path.join(root, filename)
55                 source_dir = os.path.dirname(source)
56                 zip_file.write(
57                     file_path, os.path.relpath(file_path, source_dir))
58     return destination
59
60
61 def unzip(archive, destination=None):
62     if not destination:
63         destination = tempfile.mkdtemp()
64     with closing(zipfile.ZipFile(archive, 'r')) as zip_file:
65         zip_file.extractall(destination)
66     return destination