author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 19 Feb 2010 09:34:14 +0100 | |
branch | stable |
changeset 4643 | 921737d2e3a8 |
parent 4556 | 43c14e0e8972 |
child 4721 | 8f63691ccb7f |
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 |
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
|
85 |
action = ASK.ask('Replace ?', ('N','y','q'), 'N') |
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 |
||
106 |
||
107 |
def copy_skeleton(skeldir, targetdir, context, |
|
108 |
exclude=('*.py[co]', '*.orig', '*~', '*_flymake.py'), |
|
109 |
askconfirm=False): |
|
110 |
import shutil |
|
111 |
from fnmatch import fnmatch |
|
112 |
skeldir = normpath(skeldir) |
|
113 |
targetdir = normpath(targetdir) |
|
114 |
for dirpath, dirnames, filenames in walk(skeldir): |
|
115 |
tdirpath = dirpath.replace(skeldir, targetdir) |
|
116 |
create_dir(tdirpath) |
|
117 |
for fname in filenames: |
|
118 |
if any(fnmatch(fname, pat) for pat in exclude): |
|
119 |
continue |
|
120 |
fpath = join(dirpath, fname) |
|
121 |
if 'CUBENAME' in fname: |
|
122 |
tfpath = join(tdirpath, fname.replace('CUBENAME', context['cubename'])) |
|
123 |
elif 'DISTNAME' in fname: |
|
124 |
tfpath = join(tdirpath, fname.replace('DISTNAME', context['distname'])) |
|
125 |
else: |
|
126 |
tfpath = join(tdirpath, fname) |
|
127 |
if fname.endswith('.tmpl'): |
|
128 |
tfpath = tfpath[:-5] |
|
129 |
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
|
130 |
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
|
131 |
fill_templated_file(fpath, tfpath, context) |
0 | 132 |
print '[generate] %s <-- %s' % (tfpath, fpath) |
133 |
elif exists(tfpath): |
|
134 |
show_diffs(tfpath, fpath, askconfirm) |
|
135 |
else: |
|
136 |
shutil.copyfile(fpath, tfpath) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
137 |
|
0 | 138 |
def fill_templated_file(fpath, tfpath, context): |
139 |
fobj = file(tfpath, 'w') |
|
140 |
templated = file(fpath).read() |
|
141 |
fobj.write(templated % context) |
|
142 |
fobj.close() |
|
143 |
||
144 |
def restrict_perms_to_user(filepath, log=None): |
|
145 |
"""set -rw------- permission on the given file""" |
|
146 |
if log: |
|
147 |
log('set %s permissions to 0600', filepath) |
|
148 |
else: |
|
2395
e3093fc12a00
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2388
diff
changeset
|
149 |
print '-> set %s permissions to 0600' % filepath |
0 | 150 |
chmod(filepath, 0600) |
151 |
||
152 |
def read_config(config_file): |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2397
diff
changeset
|
153 |
"""read the instance configuration from a file and return it as a |
0 | 154 |
dictionnary |
155 |
||
156 |
:type config_file: str |
|
157 |
:param config_file: path to the configuration file |
|
158 |
||
159 |
:rtype: dict |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
160 |
:return: a dictionary with specified values associated to option names |
0 | 161 |
""" |
162 |
from logilab.common.fileutils import lines |
|
163 |
config = current = {} |
|
164 |
try: |
|
165 |
for line in lines(config_file, comments='#'): |
|
166 |
try: |
|
167 |
option, value = line.split('=', 1) |
|
168 |
except ValueError: |
|
169 |
option = line.strip().lower() |
|
170 |
if option[0] == '[': |
|
171 |
# start a section |
|
172 |
section = option[1:-1] |
|
173 |
assert not config.has_key(section), \ |
|
174 |
'Section %s is defined more than once' % section |
|
175 |
config[section] = current = {} |
|
176 |
continue |
|
177 |
print >> sys.stderr, 'ignoring malformed line\n%r' % line |
|
178 |
continue |
|
179 |
option = option.strip().replace(' ', '_') |
|
180 |
value = value.strip() |
|
181 |
current[option] = value or None |
|
182 |
except IOError, ex: |
|
183 |
warning('missing or non readable configuration file %s (%s)', |
|
184 |
config_file, ex) |
|
185 |
return config |
|
186 |
||
187 |
def env_path(env_var, default, name): |
|
188 |
"""get a path specified in a variable or using the default value and return |
|
189 |
it. |
|
190 |
||
191 |
:type env_var: str |
|
192 |
:param env_var: name of an environment variable |
|
193 |
||
194 |
:type default: str |
|
195 |
: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
|
196 |
|
0 | 197 |
:type name: str |
198 |
: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
|
199 |
|
0 | 200 |
:rtype: str |
201 |
:return: the value of the environment variable or the default value |
|
202 |
||
203 |
:raise `ConfigurationError`: if the returned path does not exist |
|
204 |
""" |
|
205 |
path = environ.get(env_var, default) |
|
206 |
if not exists(path): |
|
207 |
raise ConfigurationError('%s path %s doesn\'t exist' % (name, path)) |
|
208 |
return abspath(path) |
|
209 |
||
210 |
||
211 |
||
212 |
_HDLRS = {} |
|
213 |
||
214 |
class metacmdhandler(type): |
|
215 |
def __new__(mcs, name, bases, classdict): |
|
216 |
cls = super(metacmdhandler, mcs).__new__(mcs, name, bases, classdict) |
|
217 |
if getattr(cls, 'cfgname', None) and getattr(cls, 'cmdname', None): |
|
218 |
_HDLRS.setdefault(cls.cmdname, []).append(cls) |
|
219 |
return cls |
|
220 |
||
221 |
||
222 |
class CommandHandler(object): |
|
223 |
"""configuration specific helper for cubicweb-ctl commands""" |
|
224 |
__metaclass__ = metacmdhandler |
|
225 |
def __init__(self, config): |
|
226 |
self.config = config |
|
227 |
||
228 |
class Command(BaseCommand): |
|
229 |
"""base class for cubicweb-ctl commands""" |
|
230 |
||
231 |
def config_helper(self, config, required=True, cmdname=None): |
|
232 |
if cmdname is None: |
|
233 |
cmdname = self.name |
|
234 |
for helpercls in _HDLRS.get(cmdname, ()): |
|
235 |
if helpercls.cfgname == config.name: |
|
236 |
return helpercls(config) |
|
237 |
if config.name == 'all-in-one': |
|
238 |
for helpercls in _HDLRS.get(cmdname, ()): |
|
239 |
if helpercls.cfgname == 'repository': |
|
240 |
return helpercls(config) |
|
241 |
if required: |
|
242 |
msg = 'No helper for command %s using %s configuration' % ( |
|
243 |
cmdname, config.name) |
|
244 |
raise ConfigurationError(msg) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
245 |
|
0 | 246 |
def fail(self, reason): |
247 |
print "command failed:", reason |
|
248 |
sys.exit(1) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
249 |
|
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1138
diff
changeset
|
250 |
|
0 | 251 |
def main_run(args, doc): |
252 |
"""command line tool""" |
|
253 |
try: |
|
4352
afe1f9bc308a
nicer usage for cubicweb-ctl
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
254 |
base_main_run(args, doc, copyright=None) |
0 | 255 |
except ConfigurationError, err: |
256 |
print 'ERROR: ', err |
|
257 |
sys.exit(1) |
|
258 |
except ExecutionError, err: |
|
259 |
print err |
|
260 |
sys.exit(2) |
|
261 |
||
262 |
CONNECT_OPTIONS = ( |
|
263 |
("user", |
|
264 |
{'short': 'u', 'type' : 'string', 'metavar': '<user>', |
|
265 |
'help': 'connect as <user> instead of being prompted to give it.', |
|
266 |
} |
|
267 |
), |
|
268 |
("password", |
|
269 |
{'short': 'p', 'type' : 'password', 'metavar': '<password>', |
|
270 |
'help': 'automatically give <password> for authentication instead of \ |
|
271 |
being prompted to give it.', |
|
272 |
}), |
|
273 |
("host", |
|
274 |
{'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
|
275 |
'default': None, |
0 | 276 |
'help': 'specify the name server\'s host name. Will be detected by \ |
277 |
broadcast if not provided.', |
|
278 |
}), |
|
279 |
) |
|
280 |
||
281 |
def config_connect(appid, optconfig): |
|
282 |
from cubicweb.dbapi import connect |
|
283 |
from getpass import getpass |
|
284 |
user = optconfig.user |
|
285 |
if not user: |
|
286 |
user = raw_input('login: ') |
|
287 |
password = optconfig.password |
|
288 |
if not password: |
|
289 |
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
|
290 |
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
|
291 |