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 with open(fpath, 'r') as f:
318 # make the substitution
319 template = CompoTemplate(m)
320 d = template.safe_substitute(dico)
325 with open(fpath, 'w') as f:
327 logger.write(" %s %s\n" % (changed, fpath[pathlen:]), 5)
329 if not tsettings.has_pyconf:
330 logger.write(src.printcolors.printcWarning(_(
331 "Definition for sat not found in settings file.")) + "\n", 2)
333 definition = tsettings.pyconf % dico
334 pyconf_file = os.path.join(target_dir, name + '.pyconf')
335 f = open(pyconf_file, 'w')
339 "Create configuration file: ") + src.printcolors.printcInfo(
340 pyconf_file) + "\n", 2)
342 if len(tsettings.post_command) > 0:
343 cmd = tsettings.post_command % dico
344 logger.write("\n", 5, True)
346 "Run post command: ") + src.printcolors.printcInfo(cmd) + "\n", 3)
348 p = subprocess.Popen(cmd, shell=True, cwd=target_dir)
354 def get_template_info(config, template_name, logger):
355 sources = search_template(config, template_name)
356 src.printcolors.print_value(logger, _("Template"), sources)
359 tmpdir = os.path.join(config.VARS.tmp_root, "tmp_template")
360 settings_file = os.path.join(tmpdir, "template.info")
361 if os.path.exists(tmpdir):
362 shutil.rmtree(tmpdir)
363 if os.path.isdir(sources):
364 shutil.copytree(sources, tmpdir)
366 src.system.archive_extract(sources, tmpdir)
367 settings_file = os.path.join(tmpdir, "template.info")
369 if not os.path.exists(settings_file):
370 raise src.SatException(_("Settings file not found"))
371 tsettings = TemplateSettings("NAME", settings_file, "target")
373 logger.write("\n", 3)
374 if len(tsettings.info) == 0:
375 logger.write(src.printcolors.printcWarning(_(
376 "No information for this template.")), 3)
378 logger.write(tsettings.info, 3)
380 logger.write("\n", 3)
381 logger.write("= Configuration", 3)
382 src.printcolors.print_value(logger,
383 "file substitution key",
384 tsettings.file_subst)
385 src.printcolors.print_value(logger,
387 tsettings.delimiter_char)
388 if len(tsettings.ignore_filters) > 0:
389 src.printcolors.print_value(logger,
391 ', '.join(tsettings.ignore_filters))
393 logger.write("\n", 3)
394 logger.write("= Parameters", 3)
396 for pp in tsettings.parameters:
397 tt = TParam(pp, "NAME")
398 pnames.append(tt.name)
399 src.printcolors.print_value(logger, "Name", tt.name)
400 src.printcolors.print_value(logger, "Prompt", tt.raw_prompt)
401 src.printcolors.print_value(logger, "Default value", tt.default)
402 logger.write("\n", 3)
405 logger.write("= Verification\n", 3)
406 if tsettings.file_subst not in pnames:
408 "file substitution key not defined as a "
409 "parameter: %s" % tsettings.file_subst, 3)
412 reexp = tsettings.delimiter_char.replace("$", "\$") + "{(?P<name>\S[^}]*)"
413 pathlen = len(tmpdir) + 1
414 for root, __, files in os.walk(tmpdir):
416 fpath = os.path.join(root, fic)
417 if not tsettings.check_file_for_substitution(fpath[pathlen:]):
420 with open(fpath, 'r') as f:
422 zz = re.findall(reexp, m)
423 zz = list(set(zz)) # reduce
424 zz = filter(lambda l: l not in pnames, zz)
426 logger.write("Missing definition in %s: %s" % (
427 src.printcolors.printcLabel(
428 fpath[pathlen:]), ", ".join(zz)), 3)
432 logger.write(src.printcolors.printc("OK"), 3)
434 logger.write(src.printcolors.printc("KO"), 3)
436 logger.write("\n", 3)
439 shutil.rmtree(tmpdir)
444 # Describes the command
446 return _("The template command creates the sources for a SALOME "
447 "module from a template.\n\nexample\nsat template "
448 "--name my_product_name --template PythonComponent --target /tmp")
450 def run(args, runner, logger):
451 '''method that is called when salomeTools is called with template parameter.
453 (options, args) = parser.parse_args(args)
455 if options.template is None:
456 msg = _("Error: the --%s argument is required\n") % "template"
457 logger.write(src.printcolors.printcError(msg), 1)
458 logger.write("\n", 1)
461 if options.target is None and options.info is None:
462 msg = _("Error: the --%s argument is required\n") % "target"
463 logger.write(src.printcolors.printcError(msg), 1)
464 logger.write("\n", 1)
467 # if "APPLICATION" in runner.cfg:
468 # msg = _("Error: this command does not use a product.")
469 # logger.write(src.printcolors.printcError(msg), 1)
470 # logger.write("\n", 1)
474 return get_template_info(runner.cfg, options.template, logger)
476 if options.name is None:
477 msg = _("Error: the --%s argument is required\n") % "name"
478 logger.write(src.printcolors.printcError(msg), 1)
479 logger.write("\n", 1)
482 if not options.name.replace('_', '').isalnum():
483 msg = _("Error: component name must contains only alphanumeric "
484 "characters and no spaces\n")
485 logger.write(src.printcolors.printcError(msg), 1)
486 logger.write("\n", 1)
489 if options.target is None:
490 msg = _("Error: the --%s argument is required\n") % "target"
491 logger.write(src.printcolors.printcError(msg), 1)
492 logger.write("\n", 1)
495 target_dir = os.path.join(options.target, options.name)
496 if os.path.exists(target_dir):
497 msg = _("Error: the target already exists: %s") % target_dir
498 logger.write(src.printcolors.printcError(msg), 1)
499 logger.write("\n", 1)
503 logger.write(_('Create sources from template\n'), 1)
504 src.printcolors.print_value(logger, 'destination', target_dir, 2)
505 src.printcolors.print_value(logger, 'name', options.name, 2)
506 src.printcolors.print_value(logger, 'template', options.template, 2)
507 logger.write("\n", 3, False)
510 if options.param is not None:
512 for elt in options.param.split(","):
513 param_def = elt.strip().split('=')
514 if len(param_def) != 2:
515 msg = _("Error: bad parameter definition")
516 logger.write(src.printcolors.printcError(msg), 1)
517 logger.write("\n", 1)
519 conf_values[param_def[0].strip()] = param_def[1].strip()
521 retcode = prepare_from_template(runner.cfg, options.name, options.template,
522 target_dir, conf_values, logger)
526 "The sources were created in %s") % src.printcolors.printcInfo(
528 logger.write(src.printcolors.printcWarning(_("\nDo not forget to put "
529 "them in your version control system.")), 3)
531 logger.write("\n", 3)