author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Wed, 05 Aug 2009 09:14:34 +0200 | |
changeset 3386 | ab797c5374b7 |
parent 2615 | 1ea41b7c0836 |
child 2790 | 968108e16066 |
child 3115 | 29262ba01464 |
permissions | -rw-r--r-- |
0 | 1 |
"""some utilities for cubicweb tools |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1802
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1802
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
2397
cdedc2a32b06
[shell] move toolsutils.confirm() to logilab.common.shellutils
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2395
diff
changeset
|
10 |
# XXX move most of this in logilab.common (shellutils ?) |
cdedc2a32b06
[shell] move toolsutils.confirm() to logilab.common.shellutils
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2395
diff
changeset
|
11 |
|
0 | 12 |
import os, sys |
13 |
from os import listdir, makedirs, symlink, environ, chmod, walk, remove |
|
14 |
from os.path import exists, join, abspath, normpath |
|
15 |
||
16 |
from logilab.common.clcommands import Command as BaseCommand, \ |
|
1132 | 17 |
main_run as base_main_run |
0 | 18 |
from logilab.common.compat import any |
2615
1ea41b7c0836
F [dialog] offer to create backup. refactor to use l.c.shellutils.ASK
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2476
diff
changeset
|
19 |
from logilab.common.shellutils import ASK |
0 | 20 |
|
21 |
from cubicweb import warning |
|
22 |
from cubicweb import ConfigurationError, ExecutionError |
|
23 |
||
24 |
def iter_dir(directory, condition_file=None, ignore=()): |
|
25 |
"""iterate on a directory""" |
|
26 |
for sub in listdir(directory): |
|
27 |
if sub in ('CVS', '.svn', '.hg'): |
|
28 |
continue |
|
29 |
if condition_file is not None and \ |
|
30 |
not exists(join(directory, sub, condition_file)): |
|
31 |
continue |
|
32 |
if sub in ignore: |
|
33 |
continue |
|
34 |
yield sub |
|
35 |
||
36 |
def create_dir(directory): |
|
37 |
"""create a directory if it doesn't exist yet""" |
|
38 |
try: |
|
39 |
makedirs(directory) |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
40 |
print '-> created directory %s.' % directory |
0 | 41 |
except OSError, ex: |
42 |
import errno |
|
43 |
if ex.errno != errno.EEXIST: |
|
44 |
raise |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
45 |
print '-> directory %s already exists, no need to create it.' % directory |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
46 |
|
0 | 47 |
def create_symlink(source, target): |
48 |
"""create a symbolic link""" |
|
49 |
if exists(target): |
|
50 |
remove(target) |
|
51 |
symlink(source, target) |
|
52 |
print '[symlink] %s <-- %s' % (target, source) |
|
53 |
||
54 |
def create_copy(source, target): |
|
55 |
import shutil |
|
56 |
print '[copy] %s <-- %s' % (target, source) |
|
57 |
shutil.copy2(source, target) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
58 |
|
0 | 59 |
def rm(whatever): |
60 |
import shutil |
|
61 |
shutil.rmtree(whatever) |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
62 |
print '-> removed %s' % whatever |
0 | 63 |
|
64 |
def show_diffs(appl_file, ref_file, askconfirm=True): |
|
65 |
"""interactivly replace the old file with the new file according to |
|
66 |
user decision |
|
67 |
""" |
|
68 |
import shutil |
|
69 |
p_output = os.popen('diff -u %s %s' % (appl_file, ref_file), 'r') |
|
70 |
diffs = p_output.read() |
|
71 |
if diffs: |
|
72 |
if askconfirm: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
73 |
print |
0 | 74 |
print diffs |
2615
1ea41b7c0836
F [dialog] offer to create backup. refactor to use l.c.shellutils.ASK
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2476
diff
changeset
|
75 |
action = ASK.ask('Replace ?', ('N','y','q'), 'N') |
0 | 76 |
else: |
77 |
action = 'y' |
|
78 |
if action == 'y': |
|
79 |
try: |
|
80 |
shutil.copyfile(ref_file, appl_file) |
|
81 |
except IOError: |
|
82 |
os.system('chmod a+w %s' % appl_file) |
|
83 |
shutil.copyfile(ref_file, appl_file) |
|
84 |
print 'replaced' |
|
85 |
elif action == 'q': |
|
86 |
sys.exit(0) |
|
87 |
else: |
|
88 |
copy_file = appl_file + '.default' |
|
89 |
copy = file(copy_file, 'w') |
|
90 |
copy.write(open(ref_file).read()) |
|
91 |
copy.close() |
|
92 |
print 'keep current version, the new file has been written to', copy_file |
|
93 |
else: |
|
94 |
print 'no diff between %s and %s' % (appl_file, ref_file) |
|
95 |
||
96 |
||
97 |
def copy_skeleton(skeldir, targetdir, context, |
|
98 |
exclude=('*.py[co]', '*.orig', '*~', '*_flymake.py'), |
|
99 |
askconfirm=False): |
|
100 |
import shutil |
|
101 |
from fnmatch import fnmatch |
|
102 |
skeldir = normpath(skeldir) |
|
103 |
targetdir = normpath(targetdir) |
|
104 |
for dirpath, dirnames, filenames in walk(skeldir): |
|
105 |
tdirpath = dirpath.replace(skeldir, targetdir) |
|
106 |
create_dir(tdirpath) |
|
107 |
for fname in filenames: |
|
108 |
if any(fnmatch(fname, pat) for pat in exclude): |
|
109 |
continue |
|
110 |
fpath = join(dirpath, fname) |
|
111 |
if 'CUBENAME' in fname: |
|
112 |
tfpath = join(tdirpath, fname.replace('CUBENAME', context['cubename'])) |
|
113 |
elif 'DISTNAME' in fname: |
|
114 |
tfpath = join(tdirpath, fname.replace('DISTNAME', context['distname'])) |
|
115 |
else: |
|
116 |
tfpath = join(tdirpath, fname) |
|
117 |
if fname.endswith('.tmpl'): |
|
118 |
tfpath = tfpath[:-5] |
|
119 |
if not askconfirm or not exists(tfpath) or \ |
|
2615
1ea41b7c0836
F [dialog] offer to create backup. refactor to use l.c.shellutils.ASK
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2476
diff
changeset
|
120 |
ASK.confirm('%s exists, overwrite?' % tfpath): |
1138
22f634977c95
make pylint happy, fix some bugs on the way
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
121 |
fill_templated_file(fpath, tfpath, context) |
0 | 122 |
print '[generate] %s <-- %s' % (tfpath, fpath) |
123 |
elif exists(tfpath): |
|
124 |
show_diffs(tfpath, fpath, askconfirm) |
|
125 |
else: |
|
126 |
shutil.copyfile(fpath, tfpath) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
127 |
|
0 | 128 |
def fill_templated_file(fpath, tfpath, context): |
129 |
fobj = file(tfpath, 'w') |
|
130 |
templated = file(fpath).read() |
|
131 |
fobj.write(templated % context) |
|
132 |
fobj.close() |
|
133 |
||
134 |
def restrict_perms_to_user(filepath, log=None): |
|
135 |
"""set -rw------- permission on the given file""" |
|
136 |
if log: |
|
137 |
log('set %s permissions to 0600', filepath) |
|
138 |
else: |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
139 |
print '-> set %s permissions to 0600' % filepath |
0 | 140 |
chmod(filepath, 0600) |
141 |
||
142 |
def read_config(config_file): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2397
diff
changeset
|
143 |
"""read the instance configuration from a file and return it as a |
0 | 144 |
dictionnary |
145 |
||
146 |
:type config_file: str |
|
147 |
:param config_file: path to the configuration file |
|
148 |
||
149 |
:rtype: dict |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
150 |
:return: a dictionary with specified values associated to option names |
0 | 151 |
""" |
152 |
from logilab.common.fileutils import lines |
|
153 |
config = current = {} |
|
154 |
try: |
|
155 |
for line in lines(config_file, comments='#'): |
|
156 |
try: |
|
157 |
option, value = line.split('=', 1) |
|
158 |
except ValueError: |
|
159 |
option = line.strip().lower() |
|
160 |
if option[0] == '[': |
|
161 |
# start a section |
|
162 |
section = option[1:-1] |
|
163 |
assert not config.has_key(section), \ |
|
164 |
'Section %s is defined more than once' % section |
|
165 |
config[section] = current = {} |
|
166 |
continue |
|
167 |
print >> sys.stderr, 'ignoring malformed line\n%r' % line |
|
168 |
continue |
|
169 |
option = option.strip().replace(' ', '_') |
|
170 |
value = value.strip() |
|
171 |
current[option] = value or None |
|
172 |
except IOError, ex: |
|
173 |
warning('missing or non readable configuration file %s (%s)', |
|
174 |
config_file, ex) |
|
175 |
return config |
|
176 |
||
177 |
def env_path(env_var, default, name): |
|
178 |
"""get a path specified in a variable or using the default value and return |
|
179 |
it. |
|
180 |
||
181 |
:type env_var: str |
|
182 |
:param env_var: name of an environment variable |
|
183 |
||
184 |
:type default: str |
|
185 |
:param default: default value if the environment variable is not defined |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
186 |
|
0 | 187 |
:type name: str |
188 |
:param name: the informal name of the path, used for error message |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
189 |
|
0 | 190 |
:rtype: str |
191 |
:return: the value of the environment variable or the default value |
|
192 |
||
193 |
:raise `ConfigurationError`: if the returned path does not exist |
|
194 |
""" |
|
195 |
path = environ.get(env_var, default) |
|
196 |
if not exists(path): |
|
197 |
raise ConfigurationError('%s path %s doesn\'t exist' % (name, path)) |
|
198 |
return abspath(path) |
|
199 |
||
200 |
||
201 |
||
202 |
_HDLRS = {} |
|
203 |
||
204 |
class metacmdhandler(type): |
|
205 |
def __new__(mcs, name, bases, classdict): |
|
206 |
cls = super(metacmdhandler, mcs).__new__(mcs, name, bases, classdict) |
|
207 |
if getattr(cls, 'cfgname', None) and getattr(cls, 'cmdname', None): |
|
208 |
_HDLRS.setdefault(cls.cmdname, []).append(cls) |
|
209 |
return cls |
|
210 |
||
211 |
||
212 |
class CommandHandler(object): |
|
213 |
"""configuration specific helper for cubicweb-ctl commands""" |
|
214 |
__metaclass__ = metacmdhandler |
|
215 |
def __init__(self, config): |
|
216 |
self.config = config |
|
217 |
||
218 |
class Command(BaseCommand): |
|
219 |
"""base class for cubicweb-ctl commands""" |
|
220 |
||
221 |
def config_helper(self, config, required=True, cmdname=None): |
|
222 |
if cmdname is None: |
|
223 |
cmdname = self.name |
|
224 |
for helpercls in _HDLRS.get(cmdname, ()): |
|
225 |
if helpercls.cfgname == config.name: |
|
226 |
return helpercls(config) |
|
227 |
if config.name == 'all-in-one': |
|
228 |
for helpercls in _HDLRS.get(cmdname, ()): |
|
229 |
if helpercls.cfgname == 'repository': |
|
230 |
return helpercls(config) |
|
231 |
if required: |
|
232 |
msg = 'No helper for command %s using %s configuration' % ( |
|
233 |
cmdname, config.name) |
|
234 |
raise ConfigurationError(msg) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
235 |
|
0 | 236 |
def fail(self, reason): |
237 |
print "command failed:", reason |
|
238 |
sys.exit(1) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
239 |
|
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
240 |
|
0 | 241 |
def main_run(args, doc): |
242 |
"""command line tool""" |
|
243 |
try: |
|
244 |
base_main_run(args, doc) |
|
245 |
except ConfigurationError, err: |
|
246 |
print 'ERROR: ', err |
|
247 |
sys.exit(1) |
|
248 |
except ExecutionError, err: |
|
249 |
print err |
|
250 |
sys.exit(2) |
|
251 |
||
252 |
CONNECT_OPTIONS = ( |
|
253 |
("user", |
|
254 |
{'short': 'u', 'type' : 'string', 'metavar': '<user>', |
|
255 |
'help': 'connect as <user> instead of being prompted to give it.', |
|
256 |
} |
|
257 |
), |
|
258 |
("password", |
|
259 |
{'short': 'p', 'type' : 'password', 'metavar': '<password>', |
|
260 |
'help': 'automatically give <password> for authentication instead of \ |
|
261 |
being prompted to give it.', |
|
262 |
}), |
|
263 |
("host", |
|
264 |
{'short': 'H', 'type' : 'string', 'metavar': '<hostname>', |
|
541
0d75cfe50f83
fix default value of pyro ns host
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
0
diff
changeset
|
265 |
'default': None, |
0 | 266 |
'help': 'specify the name server\'s host name. Will be detected by \ |
267 |
broadcast if not provided.', |
|
268 |
}), |
|
269 |
) |
|
270 |
||
271 |
def config_connect(appid, optconfig): |
|
272 |
from cubicweb.dbapi import connect |
|
273 |
from getpass import getpass |
|
274 |
user = optconfig.user |
|
275 |
if not user: |
|
276 |
user = raw_input('login: ') |
|
277 |
password = optconfig.password |
|
278 |
if not password: |
|
279 |
password = getpass('password: ') |
|
2388
fddb0fd11321
[api] update dbapi.connect() calls to match new prototype (user parameter is now named login)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1977
diff
changeset
|
280 |
return connect(login=user, password=password, host=optconfig.host, database=appid) |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
281 |