author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 23 Apr 2010 09:17:08 +0200 | |
changeset 5380 | a4e7e87d315f |
parent 5328 | c51e8f62652a |
child 5423 | e15abfdcce38 |
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 |
4554
2279ba039494
use subprocess instead of os.popen to run diff
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
13 |
import subprocess |
3115
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
14 |
from os import listdir, makedirs, environ, chmod, walk, remove |
0 | 15 |
from os.path import exists, join, abspath, normpath |
16 |
||
3115
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
17 |
try: |
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
18 |
from os import symlink |
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
19 |
except ImportError: |
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
20 |
def symlink(*args): |
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
21 |
raise NotImplementedError |
29262ba01464
minimal steps to have cw running on windows
Aurélien Campéas
parents:
2615
diff
changeset
|
22 |
|
0 | 23 |
from logilab.common.clcommands import Command as BaseCommand, \ |
1132 | 24 |
main_run as base_main_run |
0 | 25 |
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
|
26 |
from logilab.common.shellutils import ASK |
0 | 27 |
|
28 |
from cubicweb import warning |
|
29 |
from cubicweb import ConfigurationError, ExecutionError |
|
30 |
||
2790
968108e16066
move underline_title to toolsutils
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2615
diff
changeset
|
31 |
def underline_title(title, car='-'): |
968108e16066
move underline_title to toolsutils
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2615
diff
changeset
|
32 |
return title+'\n'+(car*len(title)) |
968108e16066
move underline_title to toolsutils
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2615
diff
changeset
|
33 |
|
0 | 34 |
def iter_dir(directory, condition_file=None, ignore=()): |
35 |
"""iterate on a directory""" |
|
36 |
for sub in listdir(directory): |
|
37 |
if sub in ('CVS', '.svn', '.hg'): |
|
38 |
continue |
|
39 |
if condition_file is not None and \ |
|
40 |
not exists(join(directory, sub, condition_file)): |
|
41 |
continue |
|
42 |
if sub in ignore: |
|
43 |
continue |
|
44 |
yield sub |
|
45 |
||
46 |
def create_dir(directory): |
|
47 |
"""create a directory if it doesn't exist yet""" |
|
48 |
try: |
|
49 |
makedirs(directory) |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
50 |
print '-> created directory %s.' % directory |
0 | 51 |
except OSError, ex: |
52 |
import errno |
|
53 |
if ex.errno != errno.EEXIST: |
|
54 |
raise |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
55 |
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
|
56 |
|
0 | 57 |
def create_symlink(source, target): |
58 |
"""create a symbolic link""" |
|
59 |
if exists(target): |
|
60 |
remove(target) |
|
61 |
symlink(source, target) |
|
62 |
print '[symlink] %s <-- %s' % (target, source) |
|
63 |
||
64 |
def create_copy(source, target): |
|
65 |
import shutil |
|
66 |
print '[copy] %s <-- %s' % (target, source) |
|
67 |
shutil.copy2(source, target) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
68 |
|
0 | 69 |
def rm(whatever): |
70 |
import shutil |
|
71 |
shutil.rmtree(whatever) |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
72 |
print '-> removed %s' % whatever |
0 | 73 |
|
74 |
def show_diffs(appl_file, ref_file, askconfirm=True): |
|
75 |
"""interactivly replace the old file with the new file according to |
|
76 |
user decision |
|
77 |
""" |
|
78 |
import shutil |
|
4554
2279ba039494
use subprocess instead of os.popen to run diff
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
79 |
pipe = subprocess.Popen(['diff', '-u', appl_file, ref_file], stdout=subprocess.PIPE) |
2279ba039494
use subprocess instead of os.popen to run diff
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
80 |
diffs = pipe.stdout.read() |
0 | 81 |
if diffs: |
82 |
if askconfirm: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
83 |
print |
0 | 84 |
print diffs |
5324
449cc4fa9c42
[migration] makes Yes the default answer to replace configuration file
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4721
diff
changeset
|
85 |
action = ASK.ask('Replace ?', ('Y', 'n', 'q'), 'Y').lower() |
0 | 86 |
else: |
87 |
action = 'y' |
|
88 |
if action == 'y': |
|
89 |
try: |
|
90 |
shutil.copyfile(ref_file, appl_file) |
|
91 |
except IOError: |
|
92 |
os.system('chmod a+w %s' % appl_file) |
|
93 |
shutil.copyfile(ref_file, appl_file) |
|
94 |
print 'replaced' |
|
95 |
elif action == 'q': |
|
96 |
sys.exit(0) |
|
97 |
else: |
|
98 |
copy_file = appl_file + '.default' |
|
99 |
copy = file(copy_file, 'w') |
|
100 |
copy.write(open(ref_file).read()) |
|
101 |
copy.close() |
|
102 |
print 'keep current version, the new file has been written to', copy_file |
|
103 |
else: |
|
104 |
print 'no diff between %s and %s' % (appl_file, ref_file) |
|
105 |
||
5184
955ee1b24756
[c-c newcube] #1192: simpler cubicweb-ctl newcube, and more
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
5021
diff
changeset
|
106 |
SKEL_EXCLUDE = ('*.py[co]', '*.orig', '*~', '*_flymake.py') |
0 | 107 |
def copy_skeleton(skeldir, targetdir, context, |
5184
955ee1b24756
[c-c newcube] #1192: simpler cubicweb-ctl newcube, and more
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
5021
diff
changeset
|
108 |
exclude=SKEL_EXCLUDE, askconfirm=False): |
0 | 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 |
||
5021
58e89f3dfbae
handle nicely typical installation other than debian package / mercurial forest
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4721
diff
changeset
|
186 |
def env_path(env_var, default, name, checkexists=True): |
0 | 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) |
|
5021
58e89f3dfbae
handle nicely typical installation other than debian package / mercurial forest
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4721
diff
changeset
|
205 |
if checkexists and not exists(path): |
58e89f3dfbae
handle nicely typical installation other than debian package / mercurial forest
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4721
diff
changeset
|
206 |
raise ConfigurationError('%s directory %s doesn\'t exist' % (name, path)) |
0 | 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: |
|
4352
afe1f9bc308a
nicer usage for cubicweb-ctl
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
253 |
base_main_run(args, doc, copyright=None) |
0 | 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 |