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
5 # http://www.apache.org/licenses/LICENSE-2.0
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.
21 from contextlib import closing
24 def is_archive(source):
25 return tarfile.is_tarfile(source) or zipfile.is_zipfile(source)
28 def extract_archive(source):
29 if tarfile.is_tarfile(source):
31 elif zipfile.is_zipfile(source):
34 'Unsupported archive type provided or archive is not valid: {0}.'.format(source))
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))
42 def untar(archive, destination=None):
44 destination = tempfile.mkdtemp()
45 with closing(tarfile.open(name=archive)) as tar_archive:
46 tar_archive.extractall(path=destination, members=tar_archive.getmembers())
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)
57 file_path, os.path.relpath(file_path, source_dir))
61 def unzip(archive, destination=None):
63 destination = tempfile.mkdtemp()
64 with closing(zipfile.ZipFile(archive, 'r')) as zip_file:
65 zip_file.extractall(destination)