-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzip_util.py
More file actions
214 lines (158 loc) · 6.8 KB
/
Copy pathzip_util.py
File metadata and controls
214 lines (158 loc) · 6.8 KB
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
###########################################################
#
# Copyright (c) 2011, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
import zipfile, os, codecs, datetime
class ZipUtil(object):
def zip_dir(cls, dir, zip_path=None, ignore_dirs=[], include_dirs=[]):
if not zip_path:
zip_path = "./%s.zip" % os.path.basename(dir)
if os.path.exists(zip_path):
os.unlink(zip_path)
# check if the folder exists
dirname = os.path.dirname(zip_path)
if not os.path.exists(dirname):
os.makedirs(dirname)
f = codecs.open(zip_path, 'wb')
zip = zipfile.ZipFile(f, 'w', compression=zipfile.ZIP_DEFLATED)
# Probably not, this may work better in windows without compression
#zip = zipfile.ZipFile(f, 'w', compression=zipfile.ZIP_STORED)
try:
count = 0
for root, dirs, files in os.walk(dir):
for ignore_dir in ignore_dirs:
if ignore_dir in dirs:
dirs.remove(ignore_dir)
if root == dir and include_dirs:
del dirs[:]
dirs.extend(include_dirs)
continue
for file in files:
path = "%s/%s" % (root, file)
relpath = path.replace("%s/" % os.path.dirname(dir), "")
#relpath = "%s/%s" % (os.path.basename(root), file)
if os.path.islink(path):
zip_info = zipfile.ZipInfo(root)
zip_info.create_system = 3
zip_info.external_attr = 271663808L
zip_info.filename = relpath
zip.writestr(zip_info, os.readlink(path) )
else:
zip.write(path, relpath)
count += 1
finally:
zip.close()
if not count and os.path.exists(zip_path):
os.unlink(zip_path)
zip_dir = classmethod(zip_dir)
# take from: https://gist.github.com/610907
def zip_dir2(cls, dir, zip_path=None):
'''Zip up a directory and preserve symlinks and empty directories'''
if not os.path.exists(dir):
return
if not zip_path:
zip_path = "./%s.zip" % os.path.basename(dir)
if os.path.exists(zip_path):
os.unlink(zip_path)
inputDir = dir
outputZip = zip_path
zipOut = zipfile.ZipFile(outputZip, 'w', compression=zipfile.ZIP_DEFLATED)
rootLen = len(os.path.dirname(inputDir))
def _ArchiveDirectory(parentDirectory):
contents = os.listdir(parentDirectory)
#store empty directories
if not contents:
#http://www.velocityreviews.com/forums/t318840-add-empty-directory-using-zipfile.html
archiveRoot = parentDirectory[rootLen:].replace('\\', '/').lstrip('/')
zipInfo = zipfile.ZipInfo(archiveRoot+'/')
zipOut.writestr(zipInfo, '')
for item in contents:
fullPath = os.path.join(parentDirectory, item)
if os.path.isdir(fullPath) and not os.path.islink(fullPath):
_ArchiveDirectory(fullPath)
else:
archiveRoot = fullPath[rootLen:].replace('\\', '/').lstrip('/')
if os.path.islink(fullPath):
# http://www.mail-archive.com/python-list@python.org/msg34223.html
zipInfo = zipfile.ZipInfo(archiveRoot)
zipInfo.create_system = 3
# long type of hex val of '0xA1ED0000L',
# say, symlink attr magic...
zipInfo.external_attr = 2716663808L
zipOut.writestr(zipInfo, os.readlink(fullPath))
else:
zipOut.write(fullPath, archiveRoot, zipfile.ZIP_DEFLATED)
_ArchiveDirectory(inputDir)
zipOut.close()
zip_dir2 = classmethod(zip_dir2)
def extract(cls, zip_path, base_dir=None):
# first check if this is a zip file
if not os.path.exists(zip_path):
raise Exception("Path [%s] does not exist" % zip_path)
is_zip = zipfile.is_zipfile(zip_path)
if not is_zip:
raise Exception("Path [%s] is not a zip file" % zip_path)
# TODO: make sure all paths are relative
if not base_dir:
base_dir = os.path.dirname(zip_path)
paths = []
f = codecs.open(zip_path, 'rb')
zf = zipfile.ZipFile(f, 'r')
if hasattr(zf, 'extractall'):
try:
zf.extractall(path=base_dir)
except Exception, e:
print "WARNING extracting zip: ", e
return paths # This does not fill in the paths
name_list = zf.namelist()
for file_path in name_list:
try:
data = zf.read(file_path)
except KeyError:
print 'ERROR: Did not find %s in zip file' % filename
else:
new_path = "%s/%s" % (base_dir, file_path)
new_dir = os.path.dirname(new_path)
if not os.path.exists(new_dir):
os.makedirs(new_dir)
nf = codecs.open(new_path, 'wb')
nf.write(data)
nf.close()
paths.append(new_path)
return paths
extract = classmethod(extract)
def get_file_paths(cls, path):
paths = []
zf = zipfile.ZipFile(path)
for info in zf.infolist():
paths.append( info.filename )
return paths
get_file_paths = classmethod(get_file_paths)
def print_info(cls, path):
zf = zipfile.ZipFile(path)
for info in zf.infolist():
print info.filename
print '\tComment:\t', info.comment
print '\tModified:\t', datetime.datetime(*info.date_time)
print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)'
print '\tZIP version:\t', info.create_version
print '\tCompressed:\t', info.compress_size, 'bytes'
print '\tUncompressed:\t', info.file_size, 'bytes'
print
print_info = classmethod(print_info)
if __name__ == '__main__':
zip = ZipUtil()
zip.zip_dir("C:/test/mp3", "C:/test/mp3.zip")
zip.extract("C:/test/mp3.zip", base_dir = "C:/test/output")
"""
zip.zip_dir("zip_this", "/home/apache/test/cow.zip")
zip.print_info("/home/apache/test/cow.zip")
zip.extract("/home/apache/test/cow.zip", "/home/apache/test2")
"""