3 # Copyright (C) 2010-2013 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 # Compatibility python 2/3 for input function
29 # input stays input for python 3 and input = raw_input for python 2
35 # Python 2/3 compatibility for execfile function
39 def execfile(somefile, global_vars, local_vars):
40 with open(somefile) as f:
41 code = compile(f.read(), somefile, 'exec')
42 exec(code, global_vars, local_vars)
44 parser = src.options.Options()
45 parser.add_option('n', 'name', 'string', 'name',
46 _("""REQUIRED: the name of the module to create.
47 \tThe name must be a single word in upper case with only alphanumeric characters.
48 \tWhen generating a c++ component the module's """
49 """name must be suffixed with 'CPP'."""))
50 parser.add_option('t', 'template', 'string', 'template',
51 _('REQUIRED: the template to use.'))
52 parser.add_option('', 'target', 'string', 'target',
53 _('REQUIRED: where to create the module.'))
54 parser.add_option('', 'param', 'string', 'param',
55 _('''Optional: dictionary to generate the configuration for salomeTools.
56 \tFormat is: --param param1=value1,param2=value2... without spaces
57 \tNote that when using this option you must supply all the '''
58 '''values otherwise an error will be raised.'''))
59 parser.add_option('', 'info', 'boolean', 'info',
60 _('Optional: Get information on the template.'), False)
63 def __init__(self, param_def, compo_name, dico=None):
66 self.check_method = None
68 if isinstance(param_def, str):
70 elif isinstance(param_def, tuple):
71 self.name = param_def[0]
72 if len(param_def) > 1:
73 if dico is not None: self.default = param_def[1] % dico
74 else: self.default = param_def[1]
75 if len(param_def) > 2: self.prompt = param_def[2]
76 if len(param_def) > 3: self.check_method = param_def[3]
78 raise src.SatException(_("ERROR in template parameter definition"))
80 self.raw_prompt = self.prompt
81 if len(self.prompt) == 0:
82 self.prompt = _("value for '%s'") % self.name
84 if len(self.default) > 0:
85 self.prompt += "[%s] " % self.default
87 def check_value(self, val):
88 if self.check_method is None:
90 return len(val) > 0 and self.check_method(val)
92 def get_dico_param(dico, key, default):
97 class TemplateSettings:
98 def __init__(self, compo_name, settings_file, target):
99 self.compo_name = compo_name
105 execfile(settings_file, gdic, ldic)
107 # check required parameters in template.info
109 for pp in ["file_subst", "parameters"]:
110 if not (pp in ldic): missing.append("'%s'" % pp)
112 raise src.SatException(_(
113 "Bad format in settings file! %s not defined.") % ", ".join(
116 self.file_subst = ldic["file_subst"]
117 self.parameters = ldic['parameters']
118 self.info = get_dico_param(ldic, "info", "").strip()
119 self.pyconf = get_dico_param(ldic, "pyconf", "")
120 self.post_command = get_dico_param(ldic, "post_command", "")
122 # get the delimiter for the template
123 self.delimiter_char = get_dico_param(ldic, "delimiter", ":sat:")
125 # get the ignore filter
126 self.ignore_filters = map(lambda l: l.strip(),
127 ldic["ignore_filters"].split(','))
129 def has_pyconf(self):
130 return len(self.pyconf) > 0
132 def get_pyconf_parameters(self):
133 if len(self.pyconf) == 0:
135 return re.findall("%\((?P<name>\S[^\)]*)", self.pyconf)
138 # Check if the file needs to be parsed.
139 def check_file_for_substitution(self, file_):
140 for filter_ in self.ignore_filters:
141 if fnmatch.fnmatchcase(file_, filter_):
145 def check_user_values(self, values):
149 # create a list of all parameters (pyconf + list))
150 pnames = self.get_pyconf_parameters()
151 for p in self.parameters:
152 tp = TParam(p, self.compo_name)
153 pnames.append(tp.name)
156 pnames = list(set(pnames)) # remove duplicates
158 known_values = ["name", "Name", "NAME", "target", self.file_subst]
159 known_values.extend(values.keys())
162 if p not in known_values:
166 raise src.SatException(_(
167 "Missing parameters: %s") % ", ".join(missing))
169 def get_parameters(self, conf_values=None):
170 if self.dico is not None:
173 self.check_user_values(conf_values)
175 # create dictionary with default values
177 dico["name"] = self.compo_name.lower()
178 dico["Name"] = self.compo_name.capitalize()
179 dico["NAME"] = self.compo_name
180 dico["target"] = self.target
181 dico[self.file_subst] = self.compo_name
182 # add user values if any
183 if conf_values is not None:
184 for p in conf_values.keys():
185 dico[p] = conf_values[p]
187 # ask user for values
188 for p in self.parameters:
189 tp = TParam(p, self.compo_name, dico)
194 while not tp.check_value(val):
195 val = input(tp.prompt)
196 if len(val) == 0 and len(tp.default) > 0:
200 # ask for missing value for pyconf
201 pyconfparam = self.get_pyconf_parameters()
202 for p in filter(lambda l: not (l in dico), pyconfparam):
205 rep = input("%s? " % p)
211 def search_template(config, template):
213 template_src_dir = ""
214 if os.path.isabs(template):
215 if os.path.exists(template):
216 template_src_dir = template
218 # look in template directory
219 for td in [os.path.join(config.VARS.datadir, "templates")]:
220 zz = os.path.join(td, template)
221 if os.path.exists(zz):
222 template_src_dir = zz
225 if len(template_src_dir) == 0:
226 raise src.SatException(_("Template not found: %s") % template)
228 return template_src_dir
230 # Prepares a module from a template.
231 def prepare_from_template(config,
237 template_src_dir = search_template(config, template)
241 if os.path.isfile(template_src_dir):
242 logger.write(" " + _(
243 "Extract template %s\n") % src.printcolors.printcInfo(
245 src.system.archive_extract(template_src_dir, target_dir)
247 logger.write(" " + _(
248 "Copy template %s\n") % src.printcolors.printcInfo(
250 shutil.copytree(template_src_dir, target_dir)
251 logger.write("\n", 5)
254 if name.endswith("CPP"):
255 compo_name = name[:-3]
258 settings_file = os.path.join(target_dir, "template.info")
259 if not os.path.exists(settings_file):
260 raise src.SatException(_("Settings file not found"))
261 tsettings = TemplateSettings(compo_name, settings_file, target_dir)
263 # first rename the files
264 logger.write(" " + src.printcolors.printcLabel(_("Rename files\n")), 4)
265 for root, dirs, files in os.walk(target_dir):
267 ff = fic.replace(tsettings.file_subst, compo_name)
269 if os.path.exists(os.path.join(root, ff)):
270 raise src.SatException(_(
271 "Destination file already exists: %s") % os.path.join(
273 logger.write(" %s -> %s\n" % (fic, ff), 5)
274 os.rename(os.path.join(root, fic), os.path.join(root, ff))
276 # rename the directories
277 logger.write("\n", 5)
278 logger.write(" " + src.printcolors.printcLabel(_("Rename directories\n")),
280 for root, dirs, files in os.walk(target_dir, topdown=False):
282 dd = rep.replace(tsettings.file_subst, compo_name)
284 if os.path.exists(os.path.join(root, dd)):
285 raise src.SatException(_(
286 "Destination directory "
287 "already exists: %s") % os.path.join(root, dd))
288 logger.write(" %s -> %s\n" % (rep, dd), 5)
289 os.rename(os.path.join(root, rep), os.path.join(root, dd))
291 # ask for missing parameters
292 logger.write("\n", 5)
293 logger.write(" " + src.printcolors.printcLabel(
294 _("Make substitution in files\n")), 4)
295 logger.write(" " + _("Delimiter =") + " %s\n" % tsettings.delimiter_char,
297 logger.write(" " + _("Ignore Filters =") + " %s\n" % ', '.join(
298 tsettings.ignore_filters), 5)
299 dico = tsettings.get_parameters(conf_values)
300 logger.write("\n", 3)
302 # override standard string.Template class to use the desire delimiter
303 class CompoTemplate(string.Template):
304 delimiter = tsettings.delimiter_char
307 logger.write("\n", 5, True)
308 pathlen = len(target_dir) + 1
309 for root, dirs, files in os.walk(target_dir):
311 fpath = os.path.join(root, fic)
312 if not tsettings.check_file_for_substitution(fpath[pathlen:]):
313 logger.write(" - %s\n" % fpath[pathlen:], 5)
316 m = file(fpath, 'r').read()
317 # make the substitution
318 template = CompoTemplate(m)
319 d = template.safe_substitute(dico)
320 # overwrite the file with substituted content
324 file(fpath, 'w').write(d)
325 logger.write(" %s %s\n" % (changed, fpath[pathlen:]), 5)
327 if not tsettings.has_pyconf:
328 logger.write(src.printcolors.printcWarning(_(
329 "Definition for sat not found in settings file.")) + "\n", 2)
331 definition = tsettings.pyconf % dico
332 pyconf_file = os.path.join(target_dir, name + '.pyconf')
333 f = open(pyconf_file, 'w')
337 "Create configuration file: ") + src.printcolors.printcInfo(
338 pyconf_file) + "\n", 2)
340 if len(tsettings.post_command) > 0:
341 cmd = tsettings.post_command % dico
342 logger.write("\n", 5, True)
344 "Run post command: ") + src.printcolors.printcInfo(cmd) + "\n", 3)
346 p = subprocess.Popen(cmd, shell=True, cwd=target_dir)
352 def get_template_info(config, template_name, logger):
353 sources = search_template(config, template_name)
354 src.printcolors.print_value(logger, _("Template"), sources)
357 tmpdir = os.path.join(config.VARS.tmp_root, "tmp_template")
358 settings_file = os.path.join(tmpdir, "template.info")
359 if os.path.exists(tmpdir):
360 shutil.rmtree(tmpdir)
361 if os.path.isdir(sources):
362 shutil.copytree(sources, tmpdir)
364 src.system.archive_extract(sources, tmpdir)
365 settings_file = os.path.join(tmpdir, "template.info")
367 if not os.path.exists(settings_file):
368 raise src.SatException(_("Settings file not found"))
369 tsettings = TemplateSettings("NAME", settings_file, "target")
371 logger.write("\n", 3)
372 if len(tsettings.info) == 0:
373 logger.write(src.printcolors.printcWarning(_(
374 "No information for this template.")), 3)
376 logger.write(tsettings.info, 3)
378 logger.write("\n", 3)
379 logger.write("= Configuration", 3)
380 src.printcolors.print_value(logger,
381 "file substitution key",
382 tsettings.file_subst)
383 src.printcolors.print_value(logger,
385 tsettings.delimiter_char)
386 if len(tsettings.ignore_filters) > 0:
387 src.printcolors.print_value(logger,
389 ', '.join(tsettings.ignore_filters))
391 logger.write("\n", 3)
392 logger.write("= Parameters", 3)
394 for pp in tsettings.parameters:
395 tt = TParam(pp, "NAME")
396 pnames.append(tt.name)
397 src.printcolors.print_value(logger, "Name", tt.name)
398 src.printcolors.print_value(logger, "Prompt", tt.raw_prompt)
399 src.printcolors.print_value(logger, "Default value", tt.default)
400 logger.write("\n", 3)
403 logger.write("= Verification\n", 3)
404 if tsettings.file_subst not in pnames:
406 "file substitution key not defined as a "
407 "parameter: %s" % tsettings.file_subst, 3)
410 reexp = tsettings.delimiter_char.replace("$", "\$") + "{(?P<name>\S[^}]*)"
411 pathlen = len(tmpdir) + 1
412 for root, __, files in os.walk(tmpdir):
414 fpath = os.path.join(root, fic)
415 if not tsettings.check_file_for_substitution(fpath[pathlen:]):
418 m = file(fpath, 'r').read()
419 zz = re.findall(reexp, m)
420 zz = list(set(zz)) # reduce
421 zz = filter(lambda l: l not in pnames, zz)
423 logger.write("Missing definition in %s: %s" % (
424 src.printcolors.printcLabel(
425 fpath[pathlen:]), ", ".join(zz)), 3)
429 logger.write(src.printcolors.printc("OK"), 3)
431 logger.write(src.printcolors.printc("KO"), 3)
433 logger.write("\n", 3)
436 shutil.rmtree(tmpdir)
441 # Describes the command
443 return _("The template command creates the sources for a SALOME "
444 "module from a template.\n\nexample\nsat template "
445 "--name my_product_name --template PythonComponent --target /tmp")
447 def run(args, runner, logger):
448 '''method that is called when salomeTools is called with template parameter.
450 (options, args) = parser.parse_args(args)
452 if options.template is None:
453 msg = _("Error: the --%s argument is required\n") % "template"
454 logger.write(src.printcolors.printcError(msg), 1)
455 logger.write("\n", 1)
458 if options.target is None and options.info is None:
459 msg = _("Error: the --%s argument is required\n") % "target"
460 logger.write(src.printcolors.printcError(msg), 1)
461 logger.write("\n", 1)
464 # if "APPLICATION" in runner.cfg:
465 # msg = _("Error: this command does not use a product.")
466 # logger.write(src.printcolors.printcError(msg), 1)
467 # logger.write("\n", 1)
471 return get_template_info(runner.cfg, options.template, logger)
473 if options.name is None:
474 msg = _("Error: the --%s argument is required\n") % "name"
475 logger.write(src.printcolors.printcError(msg), 1)
476 logger.write("\n", 1)
479 if not options.name.replace('_', '').isalnum():
480 msg = _("Error: component name must contains only alphanumeric "
481 "characters and no spaces\n")
482 logger.write(src.printcolors.printcError(msg), 1)
483 logger.write("\n", 1)
486 if options.target is None:
487 msg = _("Error: the --%s argument is required\n") % "target"
488 logger.write(src.printcolors.printcError(msg), 1)
489 logger.write("\n", 1)
492 target_dir = os.path.join(options.target, options.name)
493 if os.path.exists(target_dir):
494 msg = _("Error: the target already exists: %s") % target_dir
495 logger.write(src.printcolors.printcError(msg), 1)
496 logger.write("\n", 1)
500 logger.write(_('Create sources from template\n'), 1)
501 src.printcolors.print_value(logger, 'destination', target_dir, 2)
502 src.printcolors.print_value(logger, 'name', options.name, 2)
503 src.printcolors.print_value(logger, 'template', options.template, 2)
504 logger.write("\n", 3, False)
507 if options.param is not None:
509 for elt in options.param.split(","):
510 param_def = elt.strip().split('=')
511 if len(param_def) != 2:
512 msg = _("Error: bad parameter definition")
513 logger.write(src.printcolors.printcError(msg), 1)
514 logger.write("\n", 1)
516 conf_values[param_def[0].strip()] = param_def[1].strip()
518 retcode = prepare_from_template(runner.cfg, options.name, options.template,
519 target_dir, conf_values, logger)
523 "The sources were created in %s") % src.printcolors.printcInfo(
525 logger.write(src.printcolors.printcWarning(_("\nDo not forget to put "
526 "them in your version control system.")), 3)
528 logger.write("\n", 3)