Repository navigation
Expand file tree
/
Copy pathcommon.py
More file actions
570 lines (493 loc) · 15.8 KB
/
Copy pathcommon.py
File metadata and controls
570 lines (493 loc) · 15.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import os, sys
import re
import logging
from six.moves.urllib.parse import urlencode
from six.moves import cPickle
import inspect
import six
import types
log = logging
def safe_import(path):
module = path.split('.')
mod = g = __import__(module[0], fromlist=['*'])
s = [module[0]]
for i in module[1:]:
if isinstance(g, types.ModuleType):
mod = g
if hasattr(g, i):
g = getattr(g, i)
else:
s.append(i)
g = __import__('.'.join(s), fromlist=['*'])
return mod, g
def import_handler(path):
"""
Will return module, class, function
"""
module = path.split('.')
mod = g = __import__(module[0], fromlist=['*'])
s = [module[0]]
cls = None
for i in module[1:]:
if isinstance(g, types.ModuleType):
mod = g
if hasattr(g, i):
g = getattr(g, i)
if inspect.isclass(g):
cls = g
else:
s.append(i)
g = __import__('.'.join(s), fromlist=['*'])
return mod, cls, g
def import_mod_attr(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, six.string_types):
module, func = path.rsplit('.', 1)
mod = __import__(module, fromlist=['*'])
f = getattr(mod, func)
else:
f = path
mod = inspect.getmodule(path)
return mod, f
def import_attr(func):
mod, f = import_mod_attr(func)
return f
def myimport(module):
mod = __import__(module, fromlist=['*'])
return mod
def install(packages):
from pkg_resources import load_entry_point
load = load_entry_point('setuptools', 'console_scripts', 'easy_install')
load(packages)
class MyPkg(object):
@staticmethod
def resource_filename(module, path):
mod = myimport(module)
p = os.path.dirname(mod.__file__)
if path:
return os.path.join(p, path)
else:
return p
@staticmethod
def resource_listdir(module, path):
d = MyPkg.resource_filename(module, path)
return os.listdir(d)
@staticmethod
def resource_isdir(module, path):
d = MyPkg.resource_filename(module, path)
return os.path.isdir(d)
try:
import pkg_resources as pkg
except:
pkg = MyPkg
def extract_file(module, path, dist, verbose=False, replace=True):
outf = os.path.join(dist, os.path.basename(path))
# d = pkg.get_distribution(module)
# if d.has_metadata('zip-safe'):
# f = open(outf, 'wb')
# f.write(pkg.resource_string(module, path))
# f.close()
# if verbose:
# print 'Info : Extract %s/%s to %s' % (module, path, outf)
# else:
import shutil
inf = pkg.resource_filename(module, path)
sfile = os.path.basename(inf)
if os.path.isdir(dist):
dfile = os.path.join(dist, sfile)
else:
dfile = dist
f = os.path.exists(dfile)
if replace or not f:
shutil.copy2(inf, dist)
if verbose:
six.print_('Copy %s to %s' % (inf, dist))
def extract_dirs(mod, path, dst, verbose=False, exclude=None, exclude_ext=None, recursion=True, replace=True):
"""
mod name
path mod path
dst output directory
resursion True will extract all sub module of mod
"""
default_exclude = ['.svn', '_svn', '.git']
default_exclude_ext = ['.pyc', '.pyo', '.bak', '.tmp']
exclude = exclude or []
exclude_ext = exclude_ext or []
# log = logging.getLogger('uliweb')
if not os.path.exists(dst):
os.makedirs(dst)
if verbose:
six.print_('Make directory %s' % dst)
for r in pkg.resource_listdir(mod, path):
if r in exclude or r in default_exclude:
continue
fpath = os.path.join(path, r)
if pkg.resource_isdir(mod, fpath):
if recursion:
extract_dirs(mod, fpath, os.path.join(dst, r), verbose, exclude, exclude_ext, recursion, replace)
else:
ext = os.path.splitext(fpath)[1]
if ext in exclude_ext or ext in default_exclude_ext:
continue
extract_file(mod, fpath, dst, verbose, replace)
def copy_dir(src, dst, verbose=False, check=False, processor=None):
import shutil
# log = logging.getLogger('uliweb')
def _md5(filename):
try:
import hashlib
a = hashlib.md5()
except ImportError:
import md5
a = md5.new()
a.update(file(filename, 'rb').read())
return a.digest()
if not os.path.exists(dst):
os.makedirs(dst)
if verbose:
six.print_("Processing %s" % src)
for r in os.listdir(src):
if r in ['.svn', '_svn', '.git']:
continue
fpath = os.path.join(src, r)
if os.path.isdir(fpath):
copy_dir(fpath, os.path.join(dst, r), verbose, check, processor)
else:
ext = os.path.splitext(fpath)[1]
if ext in ['.pyc', '.pyo', '.bak', '.tmp']:
continue
df = os.path.join(dst, r)
if check:
if os.path.exists(df):
a = _md5(fpath)
b = _md5(df)
if a != b:
six.print_(("Error: Target file %s is already existed, and "
"it not same as source one %s, so copy failed" % (fpath, dst)))
else:
if processor:
if processor(fpath, dst, df):
continue
shutil.copy2(fpath, dst)
if verbose:
six.print_("Copy %s to %s" % (fpath, dst))
else:
if processor:
if processor(fpath, dst, df):
continue
shutil.copy2(fpath, dst)
if verbose:
six.print_("Copy %s to %s" % (fpath, dst))
def copy_dir_with_check(dirs, dst, verbose=False, check=True, processor=None):
# log = logging.getLogger('uliweb')
for d in dirs:
if not os.path.exists(d):
continue
copy_dir(d, dst, verbose, check, processor)
def check_apps_dir(apps_dir):
log = logging
if not os.path.exists(apps_dir):
six.print_("[Error] Can't find the apps_dir [%s], please check it out" % apps_dir, file=sys.stderr)
sys.exit(1)
def is_pyfile_exist(dir, pymodule):
path = os.path.join(dir, '%s.py' % pymodule)
if not os.path.exists(path):
path = os.path.join(dir, '%s.pyc' % pymodule)
if not os.path.exists(path):
path = os.path.join(dir, '%s.pyo' % pymodule)
if not os.path.exists(path):
return False
return True
def wraps(src):
def _f(des):
def f(*args, **kwargs):
from uliweb import application
if application:
env = application.get_view_env()
for k, v in six.iteritems(env):
six.get_function_globals(src)[k] = v
six.get_function_globals(src)['env'] = env
return des(*args, **kwargs)
f.__name__ = src.__name__
six.get_function_globals(f).update(six.get_function_globals(src))
f.__doc__ = src.__doc__
f.__module__ = src.__module__
f.__dict__.update(src.__dict__)
return f
return _f
def timeit(func):
log = logging.getLogger('uliweb.app')
import time
@wraps(func)
def f(*args, **kwargs):
begin = time.time()
ret = func(*args, **kwargs)
end = time.time()
six.print_(("%s.%s [%s]s" % (func.__module__, func.__name__, end-begin)))
return ret
return f
def safe_unicode(s, encoding='utf-8'):
from uliweb.i18n.lazystr import LazyString
if isinstance(s, six.text_type):
return s
elif isinstance(s, LazyString):
return six.text_type(s)
else:
return six.text_type(str(s), encoding)
def safe_str(s, encoding='utf-8'):
from uliweb.i18n.lazystr import LazyString
if isinstance(s, six.text_type):
return s.encode(encoding)
elif isinstance(s, LazyString):
return six.text_type(s).encode(encoding)
else:
return str(s)
def get_var(key):
def f():
from uliweb import settings
return settings.get_var(key)
return f
def get_choice(choices, value, default=None):
if six.callable(choices):
choices = choices()
return dict(choices).get(value, default)
def simple_value(v, encoding='utf-8', none=False):
import datetime
import decimal
if six.callable(v):
v = v()
if isinstance(v, datetime.datetime):
return v.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(v, datetime.date):
return v.strftime('%Y-%m-%d')
elif isinstance(v, datetime.time):
return v.strftime('%H:%M:%S')
elif isinstance(v, decimal.Decimal):
return str(v)
elif isinstance(v, six.text_type):
return v.encode(encoding)
elif isinstance(v, (tuple, list)):
s = []
for x in v:
s.append(simple_value(x, encoding, none))
return s
elif isinstance(v, dict):
d = {}
for k, v in six.iteritems(v):
d[simple_value(k)] = simple_value(v, encoding, none)
return d
elif v is None:
if none:
return v
else:
return ''
else:
return v
def str_value(v, encoding='utf-8', bool_int=True, none='NULL'):
import datetime
import decimal
if six.callable(v):
v = v()
if isinstance(v, datetime.datetime):
return v.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(v, datetime.date):
return v.strftime('%Y-%m-%d')
elif isinstance(v, datetime.time):
return v.strftime('%H:%M:%S')
elif isinstance(v, decimal.Decimal):
return str(v)
elif isinstance(v, six.text_type):
return v.encode(encoding)
elif v is None:
return none
elif isinstance(v, bool):
if bool_int:
if v:
return '1'
else:
return '0'
else:
return str(v)
else:
return str(v)
def norm_path(path):
return os.path.normcase(os.path.abspath(path))
r_expand_path = re.compile('\$\{(\w+)\}')
def expand_path(path):
"""
Auto search some variables defined in path string, such as:
${PROJECT}/files
${app_name}/files
for ${PROJECT} will be replaced with uliweb application apps_dir directory
and others will be treated as a normal python package, so uliweb will
use pkg_resources to get the path of the package
"""
from uliweb import application
def replace(m):
txt = m.groups()[0]
if txt == 'PROJECT':
return application.apps_dir
else:
return pkg.resource_filename(txt, '')
return re.sub(r_expand_path, replace, path)
def date_in(d, dates):
"""
compare if d in dates. dates should be a tuple or a list, for example:
date_in(d, [d1, d2])
and this function will execute:
d1 <= d <= d2
and if d is None, then return False
"""
if not d:
return False
return dates[0] <= d <= dates[1]
class Serial(object):
@classmethod
def load(cls, s):
return cPickle.loads(s)
@classmethod
def dump(cls, v):
return cPickle.dumps(v, cPickle.HIGHEST_PROTOCOL)
from six.moves.urllib import parse
class QueryString(object):
def __init__(self, url):
self.url = str(url)
self.scheme, self.netloc, self.script_root, qs, self.anchor = self.parse()
self.qs = parse.parse_qs(qs, True)
def parse(self):
return parse.urlsplit(self.url)
def __getitem__(self, name):
return self.qs.get(name, [])
def __setitem__(self, name, value):
self.qs[name] = [value]
def set(self, name, value, replace=False):
v = self.qs.setdefault(name, [])
if replace:
self.qs[name] = [value]
else:
v.append(value)
return self
def __str__(self):
qs = urlencode(self.qs, True)
return urlparse.urlunsplit((self.scheme, self.netloc, self.script_root, qs, self.anchor))
def query_string(url, replace=True, **kwargs):
q = QueryString(url)
for k, v in kwargs.items():
q.set(k, v, replace)
return str(q)
def camel_to_(s):
"""
Convert CamelCase to camel_case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', s)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def application_path(path):
"""
Join application project_dir and path
"""
from uliweb import application
return os.path.join(application.project_dir, path)
def get_uuid(type=4):
"""
Get uuid value
"""
import uuid
name = 'uuid'+str(type)
u = getattr(uuid, name)
return u().hex
def pretty_dict(d, leading=' ', newline='\n', indent=0, tabstop=4, process=None):
"""
Output pretty formatted dict, for example:
d = {"a":"b",
"c":{
"d":"e",
"f":"g",
}
}
will output:
a : 'b'
c :
d : 'e'
f : 'g'
"""
for k, v in d.items():
if process:
k, v = process(k, v)
if isinstance(v, dict):
yield '%s%s : %s' % (indent*tabstop*leading, k, newline)
for x in pretty_dict(v, leading=leading, newline=newline, indent=indent+1, tabstop=tabstop):
yield x
continue
yield '%s%s : %s%s' % (indent*tabstop*leading, k, simple_value(v), newline)
def request_url():
from uliweb import request
if request.query_string:
return request.path + '?' + request.query_string
else:
return request.path
def flat_list(*alist):
"""
Flat a tuple, list, single value or list of list to flat list
e.g.
>>> flat_list(1,2,3)
[1, 2, 3]
>>> flat_list(1)
[1]
>>> flat_list([1,2,3])
[1, 2, 3]
>>> flat_list([None])
[]
"""
a = []
for x in alist:
if x is None:
continue
if isinstance(x, (tuple, list)):
a.extend([i for i in x if i is not None])
else:
a.append(x)
return a
def compare_dict(da, db):
"""
Compare differencs from two dicts
"""
sa = set(da.items())
sb = set(db.items())
diff = sa & sb
return dict(sa - diff), dict(sb - diff)
def get_caller(skip=None):
"""
Get the caller information, it'll return: module, filename, line_no
"""
import inspect
from fnmatch import fnmatch
stack = inspect.stack()
if len(stack) > 1:
stack.pop(0)
if not isinstance(skip, (list, tuple)):
skip = [skip]
ptn = [os.path.splitext(s.replace('\\', '/'))[0] for s in skip]
for frame in stack:
#see doc: inspect
#the frame object, the filename, the line number of the current line,
#the function name, a list of lines of context from the source code,
#and the index of the current line within that list
filename, funcname, lineno = frame[1], frame[3], frame[2]
del frame
found = False
for k in ptn:
filename = os.path.splitext(filename.replace('\\', '/'))[0]
if fnmatch(filename, k):
found = True
break
if not found:
return filename, lineno, funcname
#if __name__ == '__main__':
# log.info('Info: info')
# try:
# 1/0
# except:
# log.exception('1/0')