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