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