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