587
|
1 |
#============================================================================
|
|
2 |
#Name : fileutils.py
|
|
3 |
#Part of : Helium
|
|
4 |
|
|
5 |
#Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
|
|
6 |
#All rights reserved.
|
|
7 |
#This component and the accompanying materials are made available
|
|
8 |
#under the terms of the License "Eclipse Public License v1.0"
|
|
9 |
#which accompanies this distribution, and is available
|
|
10 |
#at the URL "http://www.eclipse.org/legal/epl-v10.html".
|
|
11 |
#
|
|
12 |
#Initial Contributors:
|
|
13 |
#Nokia Corporation - initial contribution.
|
|
14 |
#
|
|
15 |
#Contributors:
|
|
16 |
#
|
|
17 |
#Description:
|
|
18 |
#===============================================================================
|
|
19 |
|
|
20 |
"""
|
|
21 |
File manipulation related functionalities:
|
|
22 |
* Filescanner
|
|
23 |
* rmtree (fixed version)
|
|
24 |
* move (fixed version)
|
|
25 |
"""
|
|
26 |
import codecs
|
|
27 |
import locale
|
|
28 |
import logging
|
|
29 |
import os
|
|
30 |
import re
|
|
31 |
import sys
|
|
32 |
import shutil
|
|
33 |
import hashlib
|
|
34 |
import subprocess
|
|
35 |
import string
|
|
36 |
|
|
37 |
import pathaddition.match
|
|
38 |
import stat
|
|
39 |
|
|
40 |
if os.name == 'nt':
|
|
41 |
import win32api
|
|
42 |
|
|
43 |
LOGGER = logging.getLogger('fileutils')
|
|
44 |
LOGGER_LOCK = logging.getLogger('fileutils.lock')
|
|
45 |
#LOGGER.addHandler(logging.FileHandler('default.log'))
|
|
46 |
#logging.basicConfig(level=logging.DEBUG)
|
|
47 |
#LOGGER.setLevel(logging.DEBUG)
|
|
48 |
|
|
49 |
class AbstractScanner(object):
|
|
50 |
""" This class implements all the required infrastructure for filescanning. """
|
|
51 |
|
|
52 |
def __init__(self):
|
|
53 |
""" Initialization. """
|
|
54 |
self.includes = []
|
|
55 |
self.excludes = []
|
|
56 |
self.includes_files = []
|
|
57 |
self.excludes_files = []
|
|
58 |
self.selectors = []
|
|
59 |
self.filetypes = []
|
|
60 |
|
|
61 |
def add_include(self, include):
|
|
62 |
""" Adds an include path to the scanner. """
|
|
63 |
if include.endswith('/') or include.endswith('\\'):
|
|
64 |
include = include + '**'
|
|
65 |
|
|
66 |
self.includes.append(include)
|
|
67 |
|
|
68 |
def add_exclude(self, exclude):
|
|
69 |
""" Adds an exclude path to the scanner. """
|
|
70 |
if exclude.endswith('/') or exclude.endswith('\\'):
|
|
71 |
exclude = exclude + '**'
|
|
72 |
|
|
73 |
self.excludes.append(exclude)
|
|
74 |
|
|
75 |
def add_exclude_file(self, exclude):
|
|
76 |
""" Adds an exclude file to the scanner. """
|
|
77 |
self.excludes_files.append(exclude)
|
|
78 |
|
|
79 |
def add_selector(self, selector):
|
|
80 |
""" Add selector to the scanner. """
|
|
81 |
self.selectors.append(selector)
|
|
82 |
|
|
83 |
def add_filetype(self, filetype):
|
|
84 |
""" Adds a filetype selection to the scanner. """
|
|
85 |
self.filetypes.append(filetype)
|
|
86 |
|
|
87 |
def is_included(self, path):
|
|
88 |
""" Returns if path is included by the scanner. """
|
|
89 |
LOGGER.debug("is_included: path = " + path)
|
|
90 |
if path.replace('\\', '/') in self.includes_files or path in self.includes_files:
|
|
91 |
return True
|
|
92 |
for inc in self.includes:
|
|
93 |
if self.match(path, inc):
|
|
94 |
LOGGER.debug("Included: " + path + " by " + inc)
|
|
95 |
return True
|
|
96 |
return False
|
|
97 |
|
|
98 |
def is_excluded(self, path):
|
|
99 |
""" Returns if path is excluded by the scanner. """
|
|
100 |
LOGGER.debug("is_excluded: path = " + path)
|
|
101 |
if path.replace('\\', '/') in self.excludes_files or path in self.excludes_files:
|
|
102 |
return True
|
|
103 |
for ex in self.excludes:
|
|
104 |
if self.match(path, ex):
|
|
105 |
LOGGER.debug("Excluded: " + path + " by " + ex)
|
|
106 |
return True
|
|
107 |
return False
|
|
108 |
|
|
109 |
def is_selected(self, path):
|
|
110 |
""" Returns if path is selected by all selectors in the scanner. """
|
|
111 |
LOGGER.debug("is_selected: path = " + path)
|
|
112 |
for selector in self.selectors:
|
|
113 |
if not selector.is_selected(path):
|
|
114 |
return False
|
|
115 |
LOGGER.debug("Selected: " + path)
|
|
116 |
return True
|
|
117 |
|
|
118 |
def is_filetype(self, path):
|
|
119 |
""" Test if a file matches one filetype. """
|
|
120 |
if len(self.filetypes) == 0:
|
|
121 |
return True
|
|
122 |
LOGGER.debug("is_filetype: path = " + path)
|
|
123 |
for filetype in self.filetypes:
|
|
124 |
if self.match(path, filetype):
|
|
125 |
LOGGER.debug("Filetype: " + path + " by " + filetype)
|
|
126 |
return True
|
|
127 |
return False
|
|
128 |
|
|
129 |
def match(self, filename, pattern):
|
|
130 |
""" Is filename matching pattern? """
|
|
131 |
return pathaddition.match.ant_match(filename, pattern, casesensitive=(os.sep != '\\'))
|
|
132 |
|
|
133 |
def test_path(self, root, relpath):
|
|
134 |
""" Test if a path matches filetype, include, exclude, and selection process."""
|
|
135 |
return self.is_filetype(relpath) and self.is_included(relpath) \
|
|
136 |
and not self.is_excluded(relpath) and \
|
|
137 |
self.is_selected(os.path.join(root, relpath))
|
|
138 |
|
|
139 |
def __str__(self):
|
|
140 |
""" Returns a string representing this instance. """
|
|
141 |
content = []
|
|
142 |
for inc in self.includes:
|
|
143 |
content.append('include:' + os.path.normpath(inc))
|
|
144 |
for ex in self.excludes:
|
|
145 |
content.append('exclude:' + os.path.normpath(ex))
|
|
146 |
return ';'.join(content)
|
|
147 |
|
|
148 |
def __repr__(self):
|
|
149 |
""" Returns a string representing this instance. """
|
|
150 |
return self.__str__()
|
|
151 |
|
|
152 |
def scan(self):
|
|
153 |
""" Abstract method which much be overriden to implement the scanning process. """
|
|
154 |
raise Exception("scan method must be overriden")
|
|
155 |
|
|
156 |
|
|
157 |
class FileScanner(AbstractScanner):
|
|
158 |
"""Scans the filesystem for files that match the selection paths.
|
|
159 |
|
|
160 |
The scanner is configured with a root directory. Any number of include
|
|
161 |
and exclude paths can be added. The scan() method is a generator that
|
|
162 |
returns matching files one at a time when called as an iterator.
|
|
163 |
|
|
164 |
This is a revisited implementation of the filescanner. It now relies on
|
|
165 |
the module pathaddition.match that implements a Ant-like regular expression matcher.
|
|
166 |
|
|
167 |
Rules:
|
|
168 |
- Includes and excludes should not start with *
|
|
169 |
- Includes and excludes should not have wildcard searches ending with ** (e.g. wildcard**)
|
|
170 |
|
|
171 |
Supported includes and excludes:
|
|
172 |
- filename.txt
|
|
173 |
- filename.*
|
|
174 |
- dir/
|
|
175 |
- dir/*
|
|
176 |
- dir/**
|
|
177 |
"""
|
|
178 |
def __init__(self, root_dir):
|
|
179 |
""" Initialization. """
|
|
180 |
AbstractScanner.__init__(self)
|
|
181 |
self.root_dir = os.path.normpath(root_dir)
|
|
182 |
if not self.root_dir.endswith(os.sep):
|
|
183 |
self.root_dir = self.root_dir + os.sep
|
|
184 |
# Add 1 so the final path separator is removed
|
|
185 |
#self.root_dirLength = len(self.root_dir) + 1
|
|
186 |
|
|
187 |
def scan(self):
|
|
188 |
""" Scans the files required to zip"""
|
|
189 |
#paths_cache = []
|
|
190 |
|
|
191 |
excludescopy = self.excludes[:]
|
|
192 |
for f_file in excludescopy:
|
|
193 |
if os.path.exists(os.path.normpath(os.path.join(self.root_dir, f_file))):
|
|
194 |
self.excludes_files.append(f_file)
|
|
195 |
self.excludes.remove(f_file)
|
|
196 |
|
|
197 |
includescopy = self.includes[:]
|
|
198 |
for f_file in includescopy:
|
|
199 |
if os.path.exists(os.path.normpath(os.path.join(self.root_dir, f_file))):
|
|
200 |
self.includes_files.append(f_file)
|
|
201 |
self.includes.remove(f_file)
|
|
202 |
|
|
203 |
LOGGER.debug('Scanning sub-root directories')
|
|
204 |
for root_dir in self.find_subroots():
|
|
205 |
for dirpath, subdirs, files in os.walk(unicode(root_dir)):
|
|
206 |
# Let's save the len before it's getting modified.
|
|
207 |
subdirsLen = len(subdirs)
|
|
208 |
subroot = dirpath[len(self.root_dir):]
|
|
209 |
|
|
210 |
dirs_to_remove = []
|
|
211 |
for subdir in subdirs:
|
|
212 |
if self.is_excluded(os.path.join(subroot, subdir)):
|
|
213 |
dirs_to_remove.append(subdir)
|
|
214 |
|
|
215 |
for dir_remove in dirs_to_remove:
|
|
216 |
subdirs.remove(dir_remove)
|
|
217 |
|
|
218 |
LOGGER.debug('Scanning directory: ' + dirpath)
|
|
219 |
for file_ in files:
|
|
220 |
path = os.path.join(subroot, file_)
|
|
221 |
if self.is_filetype(path) and self.is_included(path) and \
|
|
222 |
self.is_selected(os.path.join(dirpath, file_)) and not self.is_excluded(path):
|
|
223 |
ret_path = os.path.join(dirpath, file_)
|
|
224 |
yield ret_path
|
|
225 |
|
|
226 |
LOGGER.debug('Checking for empty directory: ' + dirpath)
|
|
227 |
# Check for including empty directories
|
|
228 |
if self.is_included(subroot) and not self.is_excluded(subroot):
|
|
229 |
if len(files) == 0 and subdirsLen == 0:
|
|
230 |
LOGGER.debug('Including empty dir: ' + dirpath)
|
|
231 |
yield dirpath
|
|
232 |
|
|
233 |
|
|
234 |
def find_subroots(self):
|
|
235 |
"""Finds all the subdirectory roots based on the include paths.
|
|
236 |
|
|
237 |
Often large archive operations define a number of archives from the root
|
|
238 |
of the drive. Walking the tree from the root is very time-consuming, so
|
|
239 |
selecting more specific subdirectory roots improves performance.
|
|
240 |
"""
|
|
241 |
def splitpath(path):
|
|
242 |
""" Returns the splitted path"""
|
|
243 |
return path.split(os.sep)
|
|
244 |
|
|
245 |
root_dirs = []
|
|
246 |
|
|
247 |
# Look for includes that start with wildcards.
|
|
248 |
subdirs_not_usable = False
|
|
249 |
for inc in self.includes + self.includes_files:
|
|
250 |
first_path_segment = splitpath(os.path.normpath(inc))[0]
|
|
251 |
if first_path_segment.find('*') != -1:
|
|
252 |
subdirs_not_usable = True
|
|
253 |
|
|
254 |
# Parse all includes for sub-roots
|
|
255 |
if not subdirs_not_usable:
|
|
256 |
for inc in self.includes + self.includes_files:
|
|
257 |
include = None
|
|
258 |
LOGGER.debug("===> inc %s" % inc)
|
|
259 |
contains_globs = False
|
|
260 |
for pathcomp in splitpath(os.path.normpath(inc)):
|
|
261 |
if pathcomp.find('*') != -1:
|
|
262 |
contains_globs = True
|
|
263 |
break
|
|
264 |
else:
|
|
265 |
if include == None:
|
|
266 |
include = pathcomp
|
|
267 |
else:
|
|
268 |
include = os.path.join(include, pathcomp)
|
|
269 |
if not contains_globs:
|
|
270 |
include = os.path.dirname(include)
|
|
271 |
|
|
272 |
LOGGER.debug("include %s" % include)
|
|
273 |
if include != None:
|
|
274 |
root_dir = os.path.normpath(os.path.join(self.root_dir, include))
|
|
275 |
is_new_root = True
|
|
276 |
for root in root_dirs[:]:
|
|
277 |
if destinsrc(root, root_dir):
|
|
278 |
LOGGER.debug("root contains include, skip it")
|
|
279 |
is_new_root = False
|
|
280 |
break
|
|
281 |
if destinsrc(root_dir, root):
|
|
282 |
LOGGER.debug("include contains root, so remove root")
|
|
283 |
root_dirs.remove(root)
|
|
284 |
if is_new_root:
|
|
285 |
root_dirs.append(root_dir)
|
|
286 |
|
|
287 |
if len(root_dirs) == 0:
|
|
288 |
root_dirs = [os.path.normpath(self.root_dir)]
|
|
289 |
LOGGER.debug('Roots = ' + str(root_dirs))
|
|
290 |
return root_dirs
|
|
291 |
|
|
292 |
def __str__(self):
|
|
293 |
return os.path.normpath(self.root_dir) + ';' + AbstractScanner.__str__(self)
|
|
294 |
|
|
295 |
def __repr__(self):
|
|
296 |
return self.__str__()
|
|
297 |
|
|
298 |
|
|
299 |
def move(src, dst):
|
|
300 |
"""Recursively move a file or directory to another location.
|
|
301 |
|
|
302 |
If the destination is on our current filesystem, then simply use
|
|
303 |
rename. Otherwise, copy src to the dst and then remove src.
|
|
304 |
A lot more could be done here... A look at a mv.c shows a lot of
|
|
305 |
the issues this implementation glosses over.
|
|
306 |
|
|
307 |
"""
|
|
308 |
try:
|
|
309 |
os.rename(src, dst)
|
|
310 |
except OSError:
|
|
311 |
if os.path.isdir(src):
|
|
312 |
if destinsrc(src, dst):
|
|
313 |
raise Exception, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
|
|
314 |
shutil.copytree(src, dst, symlinks=True)
|
|
315 |
rmtree(src)
|
|
316 |
else:
|
|
317 |
shutil.copy2(src, dst)
|
|
318 |
os.unlink(src)
|
|
319 |
|
|
320 |
def rmtree(rootdir):
|
|
321 |
""" Catch shutil.rmtree failures on Windows when files are read-only. Thanks Google!"""
|
|
322 |
if sys.platform == 'win32':
|
|
323 |
rootdir = os.path.normpath(rootdir)
|
|
324 |
if not os.path.isabs(rootdir):
|
|
325 |
rootdir = os.path.join(os.path.abspath('.'), rootdir)
|
|
326 |
if not rootdir.startswith('\\\\'):
|
|
327 |
rootdir = u"\\\\?\\" + rootdir
|
|
328 |
|
|
329 |
def cb_handle_error(fcn, path, excinfo):
|
|
330 |
""" Error handler, removing readonly and deleting the file. """
|
|
331 |
os.chmod(path, 0666)
|
|
332 |
if os.path.isdir(path):
|
|
333 |
rmdir(path)
|
|
334 |
elif os.path.isfile(path):
|
|
335 |
remove(path)
|
|
336 |
else:
|
|
337 |
fcn(path)
|
|
338 |
|
|
339 |
if 'java' in sys.platform:
|
|
340 |
import java.io
|
|
341 |
import org.apache.commons.io.FileUtils
|
|
342 |
f_file = java.io.File(rootdir)
|
|
343 |
org.apache.commons.io.FileUtils.deleteDirectory(f_file)
|
|
344 |
else:
|
|
345 |
return shutil.rmtree(rootdir, onerror=cb_handle_error)
|
|
346 |
|
|
347 |
def destinsrc(src, dst):
|
|
348 |
""" Fixed version of destinscr, that doesn't match dst with same root name."""
|
|
349 |
if os.sep == '\\':
|
|
350 |
src = src.lower()
|
|
351 |
dst = dst.lower()
|
|
352 |
src = os.path.abspath(src)
|
|
353 |
dst = os.path.abspath(dst)
|
|
354 |
if not src.endswith(os.path.sep):
|
|
355 |
src += os.path.sep
|
|
356 |
if not dst.endswith(os.path.sep):
|
|
357 |
dst += os.path.sep
|
|
358 |
return dst.startswith(src)
|
|
359 |
|
|
360 |
|
|
361 |
def which(executable):
|
|
362 |
""" Search for executable in the PATH."""
|
|
363 |
pathlist = os.environ['PATH'].split(os.pathsep)
|
588
|
364 |
pathexts = ['']
|
|
365 |
if os.sep == '\\':
|
|
366 |
pathexts = os.environ['PATHEXT'].split(os.pathsep)
|
|
367 |
|
587
|
368 |
for folder in pathlist:
|
588
|
369 |
for pathext in pathexts:
|
|
370 |
exename = executable
|
|
371 |
if os.sep == '\\' and not exename.lower().endswith(pathext.lower()):
|
|
372 |
exename = exename + pathext
|
|
373 |
filename = os.path.join(folder, exename)
|
|
374 |
try:
|
|
375 |
status = os.stat(filename)
|
|
376 |
except os.error:
|
|
377 |
continue
|
|
378 |
# Check if the path is a regular file
|
|
379 |
if stat.S_ISREG(status[stat.ST_MODE]):
|
|
380 |
mode = stat.S_IMODE(status[stat.ST_MODE])
|
|
381 |
if mode & 0111:
|
|
382 |
return os.path.normpath(filename)
|
587
|
383 |
return None
|
|
384 |
|
|
385 |
|
|
386 |
def read_policy_content(filename):
|
|
387 |
""" Read the policy number from the policy file.
|
|
388 |
strict allows to activate the new policy scanning.
|
|
389 |
"""
|
|
390 |
value = None
|
|
391 |
error = ""
|
|
392 |
try:
|
|
393 |
LOGGER.debug('Opening policy file: ' + filename)
|
|
394 |
policy_data = load_policy_content(filename)
|
|
395 |
match = re.match(r'^((?:\d+)|(?:0842[0-9a-zA-Z]{3}))\s*$', policy_data, re.M|re.DOTALL)
|
|
396 |
if match != None:
|
|
397 |
value = match.group(1)
|
|
398 |
else:
|
|
399 |
error = "Content of '%s' doesn't match r'^\d+|0842[0-9a-zA-Z]{3}\s*$'." % filename
|
628
|
400 |
except IOError, exc:
|
587
|
401 |
error = str(exc)
|
|
402 |
if value is not None:
|
|
403 |
return value
|
|
404 |
# worse case....
|
628
|
405 |
raise IOError(error)
|
587
|
406 |
|
|
407 |
def load_policy_content(filename):
|
|
408 |
""" Testing policy content loading. """
|
|
409 |
data = ''
|
|
410 |
try:
|
|
411 |
fileh = codecs.open(filename, 'r', 'ascii')
|
|
412 |
data = fileh.read()
|
628
|
413 |
except ValueError:
|
|
414 |
raise IOError("Error loading '%s' as an ASCII file." % filename)
|
587
|
415 |
finally:
|
|
416 |
fileh.close()
|
|
417 |
return data
|
|
418 |
|
|
419 |
ENCODING_MATRIX = {
|
|
420 |
codecs.BOM_UTF8: 'utf_8',
|
|
421 |
codecs.BOM_UTF16: 'utf_16',
|
|
422 |
codecs.BOM_UTF16_BE: 'utf_16_be',
|
|
423 |
codecs.BOM_UTF16_LE: 'utf_16_le',
|
|
424 |
}
|
|
425 |
|
|
426 |
def guess_encoding(data):
|
|
427 |
"""Given a byte string, guess the encoding.
|
|
428 |
|
|
429 |
First it tries for UTF8/UTF16 BOM.
|
|
430 |
|
|
431 |
Next it tries the standard 'UTF8', 'ISO-8859-1', and 'cp1252' encodings,
|
|
432 |
Plus several gathered from locale information.
|
|
433 |
|
|
434 |
The calling program *must* first call locale.setlocale(locale.LC_ALL, '')
|
|
435 |
|
|
436 |
If successful it returns (decoded_unicode, successful_encoding)
|
|
437 |
If unsuccessful it raises a ``UnicodeError``.
|
|
438 |
|
|
439 |
This was taken from http://www.voidspace.org.uk/python/articles/guessing_encoding.shtml
|
|
440 |
"""
|
|
441 |
for bom, enc in ENCODING_MATRIX.items():
|
|
442 |
if data.startswith(bom):
|
|
443 |
return data.decode(enc), enc
|
|
444 |
encodings = ['ascii', 'UTF-8']
|
|
445 |
successful_encoding = None
|
|
446 |
try:
|
|
447 |
encodings.append(locale.getlocale()[1])
|
|
448 |
except (AttributeError, IndexError):
|
|
449 |
pass
|
|
450 |
try:
|
|
451 |
encodings.append(locale.getdefaultlocale()[1])
|
|
452 |
except (AttributeError, IndexError):
|
|
453 |
pass
|
|
454 |
# latin-1
|
|
455 |
encodings.append('ISO8859-1')
|
|
456 |
encodings.append('cp1252')
|
|
457 |
for enc in encodings:
|
|
458 |
if not enc:
|
|
459 |
continue
|
|
460 |
try:
|
|
461 |
decoded = unicode(data, enc)
|
|
462 |
successful_encoding = enc
|
|
463 |
break
|
|
464 |
except (UnicodeError, LookupError):
|
|
465 |
pass
|
|
466 |
if successful_encoding is None:
|
|
467 |
raise UnicodeError('Unable to decode input data. Tried the'
|
|
468 |
' following encodings: %s.' %
|
|
469 |
', '.join([repr(enc) for enc in encodings if enc]))
|
|
470 |
else:
|
|
471 |
if successful_encoding == 'ascii':
|
|
472 |
# our default ascii encoding
|
|
473 |
successful_encoding = 'ISO8859-1'
|
|
474 |
return (decoded, successful_encoding)
|
|
475 |
|
|
476 |
def getmd5(fullpath, chunk_size=2**16):
|
|
477 |
""" returns the md5 value"""
|
588
|
478 |
for trial in range(3):
|
|
479 |
try:
|
|
480 |
file_handle = open(fullpath, "rb")
|
|
481 |
md5 = hashlib.md5()
|
|
482 |
while 1:
|
|
483 |
chunk = file_handle.read(chunk_size)
|
|
484 |
if not chunk:
|
|
485 |
break
|
|
486 |
md5.update(chunk)
|
|
487 |
file_handle.close()
|
628
|
488 |
except IOError, exc:
|
588
|
489 |
LOGGER.warning("Error happened on %d trial: %s" % (trial, str(exc)))
|
587
|
490 |
return md5.hexdigest()
|
|
491 |
|
|
492 |
def read_symbian_policy_content(filename):
|
|
493 |
""" Read the policy category from the policy file. """
|
|
494 |
value = None
|
|
495 |
error = ""
|
|
496 |
try:
|
|
497 |
LOGGER.debug('Opening symbian policy file: ' + filename)
|
|
498 |
try:
|
|
499 |
fileh = codecs.open(filename, 'r', 'ascii')
|
628
|
500 |
except ValueError:
|
|
501 |
raise IOError("Error loading '%s' as an ASCII file." % filename)
|
587
|
502 |
for line in fileh:
|
|
503 |
match = re.match(r'^Category\s+([A-Z])\s*$', line, re.M|re.DOTALL)
|
|
504 |
if match != None:
|
|
505 |
value = match.group(1)
|
|
506 |
fileh.close()
|
|
507 |
return value
|
|
508 |
fileh.close()
|
|
509 |
if match == None:
|
|
510 |
error = "Content of '%s' doesn't match r'^Category\s+([A-Z])\s*$'." % filename
|
628
|
511 |
except IOError, exc:
|
587
|
512 |
error = str(exc)
|
|
513 |
if value is not None:
|
|
514 |
return value
|
|
515 |
# worse case....
|
628
|
516 |
raise IOError(error)
|
587
|
517 |
|
|
518 |
|
|
519 |
class LockFailedException(Exception):
|
|
520 |
""" This class is used to indicate the failure in obtaining a Lock. """
|
|
521 |
pass
|
|
522 |
|
|
523 |
if os.name == 'nt':
|
|
524 |
import win32file
|
|
525 |
import win32con
|
|
526 |
import winerror
|
|
527 |
import time
|
|
528 |
import win32netcon
|
|
529 |
import win32wnet
|
|
530 |
|
|
531 |
class Lock:
|
|
532 |
""" This object implement file locking for windows. """
|
|
533 |
|
|
534 |
def __init__(self, filename):
|
|
535 |
LOGGER_LOCK.debug("__init__")
|
|
536 |
self._filename = filename
|
|
537 |
self.f_desc = None
|
|
538 |
|
|
539 |
def lock(self, wait=False):
|
|
540 |
"""lock the file"""
|
|
541 |
LOGGER_LOCK.debug("lock")
|
|
542 |
# Open the file
|
|
543 |
if self.f_desc == None:
|
|
544 |
self.f_desc = open(self._filename, "w+")
|
628
|
545 |
# pylint: disable=W0212
|
587
|
546 |
wfd = win32file._get_osfhandle(self.f_desc.fileno())
|
|
547 |
if not wait:
|
|
548 |
try:
|
|
549 |
win32file.LockFile(wfd, 0, 0, 0xffff, 0)
|
|
550 |
except:
|
|
551 |
raise LockFailedException()
|
|
552 |
else:
|
|
553 |
while True:
|
|
554 |
try:
|
|
555 |
win32file.LockFile(wfd, 0, 0, 0xffff, 0)
|
|
556 |
break
|
|
557 |
except win32file.error, exc:
|
|
558 |
if exc[0] != winerror.ERROR_LOCK_VIOLATION:
|
|
559 |
raise exc
|
|
560 |
LOGGER_LOCK.debug("waiting")
|
|
561 |
time.sleep(1)
|
|
562 |
|
|
563 |
def unlock(self):
|
|
564 |
"""unlock the file"""
|
|
565 |
LOGGER_LOCK.debug("unlock")
|
|
566 |
if self.f_desc == None:
|
|
567 |
LOGGER_LOCK.debug("already unlocked")
|
|
568 |
return
|
628
|
569 |
# pylint: disable=W0212
|
587
|
570 |
wfd = win32file._get_osfhandle(self.f_desc.fileno())
|
|
571 |
try:
|
628
|
572 |
# pylint: disable=E1101
|
587
|
573 |
win32file.UnlockFile(wfd, 0 , 0, 0xffff, 0)
|
|
574 |
self.f_desc.close()
|
|
575 |
self.f_desc = None
|
|
576 |
except win32file.error, exc:
|
|
577 |
if exc[0] != 158:
|
|
578 |
raise
|
|
579 |
|
|
580 |
|
|
581 |
def __del__(self):
|
|
582 |
LOGGER_LOCK.debug("__del__")
|
|
583 |
self.unlock()
|
|
584 |
|
|
585 |
def rmdir(path):
|
|
586 |
""" Catch os.rmdir failures on Windows when path is too long (more than 256 chars)."""
|
|
587 |
path = win32api.GetShortPathName(path)
|
|
588 |
win32file.RemoveDirectory(path)
|
|
589 |
|
|
590 |
def remove(filename):
|
|
591 |
""" Catch os.rmdir failures on Windows when path is too long (more than 256 chars)."""
|
|
592 |
filename = win32api.GetShortPathName(filename)
|
|
593 |
filename = filename.lstrip("\\\\?\\")
|
|
594 |
os.remove(filename)
|
|
595 |
|
|
596 |
def mount(drive, unc, username=None, password=None, persistent=False):
|
|
597 |
""" Windows helper function to map a network drive. """
|
|
598 |
flags = 0
|
|
599 |
if persistent:
|
|
600 |
flags = win32netcon.CONNECT_UPDATE_PROFILE
|
|
601 |
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, unc, None, username, password, flags)
|
|
602 |
|
|
603 |
|
|
604 |
def umount(drive):
|
|
605 |
""" Windows helper function to map a network drive. """
|
|
606 |
drive_type = win32file.GetDriveType(drive)
|
|
607 |
if drive_type == win32con.DRIVE_REMOTE:
|
|
608 |
win32wnet.WNetCancelConnection2(drive, win32netcon.CONNECT_UPDATE_PROFILE, 1)
|
|
609 |
else:
|
|
610 |
raise Exception("%s couldn't be umount." % drive)
|
|
611 |
|
|
612 |
else:
|
|
613 |
def rmdir(path):
|
|
614 |
"""remove directory"""
|
|
615 |
return os.rmdir(path)
|
|
616 |
|
|
617 |
def remove(path):
|
|
618 |
"""remove the files and folders"""
|
|
619 |
return os.remove(path)
|
|
620 |
|
|
621 |
class Lock:
|
|
622 |
""" This class represents a dummy lock """
|
|
623 |
def __init__(self, filename):
|
|
624 |
pass
|
|
625 |
def lock(self, wait=False):
|
|
626 |
"""lock file - do nothing """
|
|
627 |
pass
|
|
628 |
def unlock(self):
|
|
629 |
"""un lock file -do nothing """
|
|
630 |
pass
|
|
631 |
|
|
632 |
if os.sep == '\\':
|
|
633 |
def get_next_free_drive():
|
|
634 |
""" Return the first free drive found else it raise an exception. """
|
|
635 |
if os.name == 'nt':
|
|
636 |
drive_labels = sorted(list(set(string.ascii_uppercase) - set(win32api.GetLogicalDriveStrings())), reverse=True)
|
|
637 |
if len(drive_labels) != 0 :
|
|
638 |
return drive_labels[0] + ":"
|
|
639 |
raise OSError("No free drive left.")
|
|
640 |
if 'java' in sys.platform:
|
|
641 |
import java.io
|
|
642 |
used = []
|
|
643 |
for _xx in java.io.File.listRoots():
|
|
644 |
used.append(str(_xx).replace(':\\', ''))
|
|
645 |
drive_labels = sorted(list(set(string.ascii_uppercase) - set(used)), reverse=True)
|
|
646 |
if len(drive_labels) != 0 :
|
|
647 |
return drive_labels[0] + ":"
|
|
648 |
raise OSError("No free drive left.")
|
|
649 |
|
|
650 |
def subst(drive, path):
|
|
651 |
""" Substing path as a drive. """
|
|
652 |
path = os.path.normpath(path)
|
|
653 |
p_subst = subprocess.Popen("subst %s %s" % (drive, path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
654 |
errmsg = p_subst.communicate()[0]
|
|
655 |
if p_subst.returncode != 0:
|
|
656 |
raise Exception("Error substing '%s' under '%s': %s" % (path, drive, errmsg))
|
|
657 |
|
|
658 |
def unsubst(drive):
|
|
659 |
""" Unsubsting the drive. """
|
|
660 |
p_subst = subprocess.Popen("subst /D %s" % (drive), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
661 |
errmsg = p_subst.communicate()[0]
|
|
662 |
if p_subst.returncode != 0:
|
|
663 |
raise Exception("Error unsubsting '%s': %s" % (drive, errmsg))
|
|
664 |
|
|
665 |
def getSubstedDrives():
|
|
666 |
"""get substituted drive"""
|
|
667 |
driveInformation = {}
|
|
668 |
subStedDriveList = []
|
|
669 |
p_subst = subprocess.Popen("subst", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
670 |
subStedDriveList = re.split('\\n', p_subst.communicate()[0])
|
|
671 |
del subStedDriveList[len(subStedDriveList)-1]
|
|
672 |
for path in subStedDriveList:
|
|
673 |
subStedDrivePath = []
|
|
674 |
if(re.search(r'UNC', path) is not None):
|
|
675 |
subStedDrivePath = re.split('=>', path)
|
|
676 |
(drive_to_unsubst, _) = os.path.splitdrive(os.path.normpath(subStedDrivePath[0]))
|
|
677 |
uncPath = re.sub('UNC', r'\\', subStedDrivePath[1].strip())
|
|
678 |
if(uncPath != subStedDrivePath[1].strip()):
|
|
679 |
driveInformation[drive_to_unsubst] = uncPath
|
|
680 |
else:
|
|
681 |
subStedDrivePath = re.split('=>', path)
|
|
682 |
(drive_to_unsubst, _) = os.path.splitdrive(os.path.normpath(subStedDrivePath[0]))
|
|
683 |
driveInformation[drive_to_unsubst] = os.path.normpath(subStedDrivePath[1].strip())
|
|
684 |
|
|
685 |
return driveInformation
|
|
686 |
|
|
687 |
def touch(srcdir):
|
|
688 |
"""
|
|
689 |
Recursively touches all the files in the source path mentioned.
|
|
690 |
It does not touch the directories.
|
|
691 |
"""
|
|
692 |
srcnames = os.listdir(srcdir)
|
|
693 |
for name in srcnames:
|
|
694 |
srcfname = os.path.join(srcdir, name)
|
|
695 |
if os.path.isdir(srcfname):
|
|
696 |
touch(srcfname)
|
|
697 |
else:
|
|
698 |
if os.path.exists(srcfname):
|
|
699 |
os.utime(srcfname, None)
|