-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.py
98 lines (75 loc) · 2.37 KB
/
utils.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
#
# Copyright (c) 2010-2013 Liraz Siri <[email protected]>
#
# This file is part of TKLBAM (TurnKey GNU/Linux BAckup and Migration).
#
# TKLBAM is open source software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of
# the License, or (at your option) any later version.
#
import os
from os.path import *
import executil
import shutil
import stat
import datetime
from StringIO import StringIO
def remove_any(path):
"""Remove a path whether it is a file or a directory.
Return: True if removed, False if nothing to remove"""
if not lexists(path):
return False
if not islink(path) and isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
return True
class AttrDict(dict):
def __getattr__(self, name):
if name in self:
return self[name]
raise AttributeError("no such attribute '%s'" % name)
def __setattr__(self, name, val):
self[name] = val
def is_writeable(fpath):
try:
file(fpath, "w+")
return True
except IOError:
return False
# workaround for shutil.move across-filesystem bugs
def move(src, dst):
st = os.lstat(src)
is_symlink = stat.S_ISLNK(st.st_mode)
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(os.path.abspath(src)))
if is_symlink:
linkto = os.readlink(src)
os.symlink(linkto, dst)
os.unlink(src)
else:
shutil.move(src, dst)
os.lchown(dst, st.st_uid, st.st_gid)
def apply_overlay(src, dst, olist_path):
orig_cwd = os.getcwd()
os.chdir(src)
executil.getoutput("tar --create --files-from=%s | tar --extract --directory %s" %
(olist_path, executil.mkarg(dst)))
os.chdir(orig_cwd)
def fmt_title(title, c='='):
return title + "\n" + c * len(title) + "\n"
def fmt_timestamp():
fh = StringIO()
s = "### %s ###" % datetime.datetime.now().ctime()
print >> fh, "#" * len(s)
print >> fh, s
print >> fh, "#" * len(s)
return fh.getvalue()
def path_global_or_local(path_global, path_local):
"""Return global path if writeable, otherwise return local path"""
if os.access(os.path.dirname(path_global), os.W_OK):
return path_global
return path_local
def iamroot():
return os.getuid() == 0