-
Notifications
You must be signed in to change notification settings - Fork 26
/
dirtools.py
390 lines (302 loc) · 12.4 KB
/
dirtools.py
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# -*- coding: utf-8 -*-
import logging
import os
import hashlib
from contextlib import closing # for Python2.6 compatibility
import tarfile
import tempfile
from datetime import datetime
import json
from globster import Globster
log = logging.getLogger("dirtools")
# TODO abs=True args for .files(), .subdirs() ?
def load_patterns(exclude_file=".exclude"):
""" Load patterns to exclude file from `exclude_file',
and return a list of pattern.
:type exclude_file: str
:param exclude_file: File containing exclude patterns
:rtype: list
:return: List a patterns
"""
return filter(None, open(exclude_file).read().split("\n"))
def _filehash(filepath, blocksize=4096):
""" Return the hash object for the file `filepath', processing the file
by chunk of `blocksize'.
:type filepath: str
:param filepath: Path to file
:type blocksize: int
:param blocksize: Size of the chunk when processing the file
"""
sha = hashlib.sha256()
with open(filepath, 'rb') as fp:
while 1:
data = fp.read(blocksize)
if data:
sha.update(data)
else:
break
return sha
def filehash(filepath, blocksize=4096):
""" Return the hash hexdigest() for the file `filepath', processing the file
by chunk of `blocksize'.
:type filepath: str
:param filepath: Path to file
:type blocksize: int
:param blocksize: Size of the chunk when processing the file
"""
sha = _filehash(filepath, blocksize)
return sha.hexdigest()
class File(object):
def __init__(self, path):
self.file = os.path.basename(path)
self.path = os.path.abspath(path)
def _hash(self):
""" Return the hash object. """
return _filehash(self.path)
def hash(self):
""" Return the hash hexdigest. """
return filehash(self.path)
def compress_to(self, archive_path=None):
""" Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created
"""
if archive_path is None:
archive = tempfile.NamedTemporaryFile(delete=False)
tar_args = ()
tar_kwargs = {'fileobj': archive}
_return = archive.name
else:
tar_args = (archive_path)
tar_kwargs = {}
_return = archive_path
tar_kwargs.update({'mode': 'w:gz'})
with closing(tarfile.open(*tar_args, **tar_kwargs)) as tar:
tar.add(self.path, arcname=self.file)
return _return
class Dir(object):
""" Wrapper for dirtools arround a path.
Try to load a .exclude file, ready to compute hashdir,
:type directory: str
:param directory: Root directory for initialization
:type exclude_file: str
:param exclude_file: File containing exclusion pattern,
.exclude by default, you can also load .gitignore files.
:type excludes: list
:param excludes: List of additionals patterns for exclusion,
by default: ['.git/', '.hg/', '.svn/']
"""
def __init__(self, directory=".", exclude_file=".exclude",
excludes=['.git/', '.hg/', '.svn/']):
if not os.path.isdir(directory):
raise TypeError("Directory must be a directory.")
self.directory = os.path.basename(directory)
self.path = os.path.abspath(directory)
self.parent = os.path.dirname(self.path)
self.exclude_file = os.path.join(self.path, exclude_file)
self.patterns = excludes
if os.path.isfile(self.exclude_file):
self.patterns.extend(load_patterns(self.exclude_file))
self.globster = Globster(self.patterns)
def hash(self, index_func=os.path.getmtime):
""" Hash for the entire directory (except excluded files) recursively.
Use mtime instead of sha256 by default for a faster hash.
>>> dir.hash(index_func=dirtools.filehash)
"""
# TODO alternative to filehash => mtime as a faster alternative
shadir = hashlib.sha256()
for f in self.files():
try:
shadir.update(str(index_func(os.path.join(self.path, f))))
except (IOError, OSError):
pass
return shadir.hexdigest()
def iterfiles(self, pattern=None, abspath=False):
""" Generator for all the files not excluded recursively.
Return relative path.
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
"""
if pattern is not None:
globster = Globster([pattern])
for root, dirs, files in self.walk():
for f in files:
if pattern is None or (pattern is not None and globster.match(f)):
if abspath:
yield os.path.join(root, f)
else:
yield self.relpath(os.path.join(root, f))
def files(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False):
""" Return a sorted list containing relative path of all files (recursively).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
:param sort_key: key argument for sorted
:param sort_reverse: reverse argument for sorted
:rtype: list
:return: List of all relative files paths.
"""
return sorted(self.iterfiles(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse)
def get(self, pattern, sort_key=lambda k: k, sort_reverse=False, abspath=False):
res = self.files(pattern, sort_key=sort_key, sort_reverse=sort_reverse, abspath=abspath)
if res:
return res[0]
def itersubdirs(self, pattern=None, abspath=False):
""" Generator for all subdirs (except excluded).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
"""
if pattern is not None:
globster = Globster([pattern])
for root, dirs, files in self.walk():
for d in dirs:
if pattern is None or (pattern is not None and globster.match(d)):
if abspath:
yield os.path.join(root, d)
else:
yield self.relpath(os.path.join(root, d))
def subdirs(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False):
""" Return a sorted list containing relative path of all subdirs (recursively).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
:param sort_key: key argument for sorted
:param sort_reverse: reverse argument for sorted
:rtype: list
:return: List of all relative files paths.
"""
return sorted(self.itersubdirs(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse)
def size(self):
""" Return directory size in bytes.
:rtype: int
:return: Total directory size in bytes.
"""
dir_size = 0
for f in self.iterfiles(abspath=True):
dir_size += os.path.getsize(f)
return dir_size
def is_excluded(self, path):
""" Return True if `path' should be excluded
given patterns in the `exclude_file'. """
match = self.globster.match(self.relpath(path))
if match:
log.debug("{0} matched {1} for exclusion".format(path, match))
return True
return False
def walk(self):
""" Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly. """
for root, dirs, files in os.walk(self.path, topdown=True):
# TODO relative walk, recursive call if root excluder found???
#root_excluder = get_root_excluder(root)
ndirs = []
# First we exclude directories
for d in list(dirs):
if self.is_excluded(os.path.join(root, d)):
dirs.remove(d)
elif not os.path.islink(os.path.join(root, d)):
ndirs.append(d)
nfiles = []
for fpath in (os.path.join(root, f) for f in files):
if not self.is_excluded(fpath) and not os.path.islink(fpath):
nfiles.append(os.path.relpath(fpath, root))
yield root, ndirs, nfiles
def find_projects(self, file_identifier=".project"):
""" Search all directory recursively for subdirs
with `file_identifier' in it.
:type file_identifier: str
:param file_identifier: File identier, .project by default.
:rtype: list
:return: The list of subdirs with a `file_identifier' in it.
"""
projects = []
for d in self.subdirs():
project_file = os.path.join(self.directory, d, file_identifier)
if os.path.isfile(project_file):
projects.append(d)
return projects
def relpath(self, path):
""" Return a relative filepath to path from Dir path. """
return os.path.relpath(path, start=self.path)
def compress_to(self, archive_path=None):
""" Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created
"""
if archive_path is None:
archive = tempfile.NamedTemporaryFile(delete=False)
tar_args = []
tar_kwargs = {'fileobj': archive}
_return = archive.name
else:
tar_args = [archive_path]
tar_kwargs = {}
_return = archive_path
tar_kwargs.update({'mode': 'w:gz'})
with closing(tarfile.open(*tar_args, **tar_kwargs)) as tar:
tar.add(self.path, arcname='', exclude=self.is_excluded)
return _return
class DirState(object):
""" Hold a directory state / snapshot meta-data for later comparison. """
def __init__(self, _dir=None, state=None, index_cmp=os.path.getmtime):
self._dir = _dir
self.index_cmp = index_cmp
self.state = state or self.compute_state()
def compute_state(self):
""" Generate the index. """
data = {}
data['directory'] = self._dir.path
data['files'] = list(self._dir.files())
data['subdirs'] = list(self._dir.subdirs())
data['index'] = self.index()
return data
def index(self):
index = {}
for f in self._dir.iterfiles():
try:
index[f] = self.index_cmp(os.path.join(self._dir.path, f))
except Exception as exc:
print(f, exc)
return index
def __sub__(self, other):
""" Compute diff with operator overloading.
>>> path = DirState(Dir('/path'))
>>> path_copy = DirState(Dir('/path_copy'))
>>> diff = path_copy - path
>>> # Equals to
>>> diff = compute_diff(path_copy.state, path.state)
"""
if self.index_cmp != other.index_cmp:
raise Exception('Both DirState instance must have the same index_cmp.')
return compute_diff(self.state, other.state)
def to_json(self, base_path='.', dt=None, fmt=None):
if fmt is None:
fmt = '{0}@{1}.json'
if dt is None:
dt = datetime.utcnow()
path = fmt.format(self._dir.path.strip('/').split('/')[-1],
dt.isoformat())
path = os.path.join(base_path, path)
with open(path, 'wb') as f:
f.write(json.dumps(self.state))
return path
@classmethod
def from_json(cls, path):
with open(path, 'rb') as f:
return cls(state=json.loads(f.read()))
def compute_diff(dir_base, dir_cmp):
""" Compare `dir_base' and `dir_cmp' and returns a list with
the following keys:
- deleted files `deleted'
- created files `created'
- updated files `updated'
- deleted directories `deleted_dirs'
"""
data = {}
data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files']))
data['created'] = list(set(dir_base['files']) - set(dir_cmp['files']))
data['updated'] = []
data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs']))
for f in set(dir_cmp['files']).intersection(set(dir_base['files'])):
if dir_base['index'][f] != dir_cmp['index'][f]:
data['updated'].append(f)
return data