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 = [l.strip() for l in ldic["ignore_filters"].split(',')]
128 def has_pyconf(self):
129 return len(self.pyconf) > 0
131 def get_pyconf_parameters(self):
132 if len(self.pyconf) == 0:
134 return re.findall("%\((?P<name>\S[^\)]*)", self.pyconf)
137 # Check if the file needs to be parsed.
138 def check_file_for_substitution(self, file_):
139 for filter_ in self.ignore_filters:
140 if fnmatch.fnmatchcase(file_, filter_):
144 def check_user_values(self, values):
148 # create a list of all parameters (pyconf + list))
149 pnames = self.get_pyconf_parameters()
150 for p in self.parameters:
151 tp = TParam(p, self.compo_name)
152 pnames.append(tp.name)
155 pnames = list(set(pnames)) # remove duplicates
157 known_values = ["name", "Name", "NAME", "target", self.file_subst]
158 known_values.extend(values.keys())
161 if p not in known_values:
165 raise src.SatException(_(
166 "Missing parameters: %s") % ", ".join(missing))
168 def get_parameters(self, conf_values=None):
169 if self.dico is not None:
172 self.check_user_values(conf_values)
174 # create dictionary with default values
176 dico["name"] = self.compo_name.lower()
177 dico["Name"] = self.compo_name.capitalize()
178 dico["NAME"] = self.compo_name
179 dico["target"] = self.target
180 dico[self.file_subst] = self.compo_name
181 # add user values if any
182 if conf_values is not None:
183 for p in conf_values.keys():
184 dico[p] = conf_values[p]
186 # ask user for values
187 for p in self.parameters:
188 tp = TParam(p, self.compo_name, dico)
193 while not tp.check_value(val):
194 val = input(tp.prompt)
195 if len(val) == 0 and len(tp.default) > 0:
199 # ask for missing value for pyconf
200 pyconfparam = self.get_pyconf_parameters()
201 for p in filter(lambda l: not (l in dico), pyconfparam):
204 rep = input("%s? " % p)
210 def search_template(config, template):
212 template_src_dir = ""
213 if os.path.isabs(template):
214 if os.path.exists(template):
215 template_src_dir = template
217 # look in template directory
218 for td in [os.path.join(config.VARS.datadir, "templates")]:
219 zz = os.path.join(td, template)
220 if os.path.exists(zz):
221 template_src_dir = zz
224 if len(template_src_dir) == 0:
225 raise src.SatException(_("Template not found: %s") % template)
227 return template_src_dir
229 # Prepares a module from a template.
230 def prepare_from_template(config,
236 template_src_dir = search_template(config, template)
240 if os.path.isfile(template_src_dir):
241 logger.write(" " + _(
242 "Extract template %s\n") % src.printcolors.printcInfo(
244 src.system.archive_extract(template_src_dir, target_dir)
246 logger.write(" " + _(
247 "Copy template %s\n") % src.printcolors.printcInfo(
249 shutil.copytree(template_src_dir, target_dir)
250 logger.write("\n", 5)
253 if name.endswith("CPP"):
254 compo_name = name[:-3]
257 settings_file = os.path.join(target_dir, "template.info")
258 if not os.path.exists(settings_file):
259 raise src.SatException(_("Settings file not found"))
260 tsettings = TemplateSettings(compo_name, settings_file, target_dir)
262 # first rename the files
263 logger.write(" " + src.printcolors.printcLabel(_("Rename files\n")), 4)
264 for root, dirs, files in os.walk(target_dir):
266 ff = fic.replace(tsettings.file_subst, compo_name)
268 if os.path.exists(os.path.join(root, ff)):
269 raise src.SatException(_(
270 "Destination file already exists: %s") % os.path.join(
272 logger.write(" %s -> %s\n" % (fic, ff), 5)
273 os.rename(os.path.join(root, fic), os.path.join(root, ff))
275 # rename the directories
276 logger.write("\n", 5)
277 logger.write(" " + src.printcolors.printcLabel(_("Rename directories\n")),
279 for root, dirs, files in os.walk(target_dir, topdown=False):
281 dd = rep.replace(tsettings.file_subst, compo_name)
283 if os.path.exists(os.path.join(root, dd)):
284 raise src.SatException(_(
285 "Destination directory "
286 "already exists: %s") % os.path.join(root, dd))
287 logger.write(" %s -> %s\n" % (rep, dd), 5)
288 os.rename(os.path.join(root, rep), os.path.join(root, dd))
290 # ask for missing parameters
291 logger.write("\n", 5)
292 logger.write(" " + src.printcolors.printcLabel(
293 _("Make substitution in files\n")), 4)
294 logger.write(" " + _("Delimiter =") + " %s\n" % tsettings.delimiter_char,
296 logger.write(" " + _("Ignore Filters =") + " %s\n" % ', '.join(
297 tsettings.ignore_filters), 5)
298 dico = tsettings.get_parameters(conf_values)
299 logger.write("\n", 3)
301 # override standard string.Template class to use the desire delimiter
302 class CompoTemplate(string.Template):
303 delimiter = tsettings.delimiter_char
306 logger.write("\n", 5, True)
307 pathlen = len(target_dir) + 1
308 for root, dirs, files in os.walk(target_dir):
310 fpath = os.path.join(root, fic)
311 if not tsettings.check_file_for_substitution(fpath[pathlen:]):
312 logger.write(" - %s\n" % fpath[pathlen:], 5)
315 with open(fpath, 'r') as f:
317 # make the substitution
318 template = CompoTemplate(m)
319 d = template.safe_substitute(dico)
324 with open(fpath, 'w') as f:
326 logger.write(" %s %s\n" % (changed, fpath[pathlen:]), 5)
328 if not tsettings.has_pyconf:
329 logger.write(src.printcolors.printcWarning(_(
330 "Definition for sat not found in settings file.")) + "\n", 2)
332 definition = tsettings.pyconf % dico
333 pyconf_file = os.path.join(target_dir, name + '.pyconf')
334 f = open(pyconf_file, 'w')
338 "Create configuration file: ") + src.printcolors.printcInfo(
339 pyconf_file) + "\n", 2)
341 if len(tsettings.post_command) > 0:
342 cmd = tsettings.post_command % dico
343 logger.write("\n", 5, True)
345 "Run post command: ") + src.printcolors.printcInfo(cmd) + "\n", 3)
347 p = subprocess.Popen(cmd, shell=True, cwd=target_dir)
353 def get_template_info(config, template_name, logger):
354 sources = search_template(config, template_name)
355 src.printcolors.print_value(logger, _("Template"), sources)
358 tmpdir = os.path.join(config.VARS.tmp_root, "tmp_template")
359 settings_file = os.path.join(tmpdir, "template.info")
360 if os.path.exists(tmpdir):
361 shutil.rmtree(tmpdir)
362 if os.path.isdir(sources):
363 shutil.copytree(sources, tmpdir)
365 src.system.archive_extract(sources, tmpdir)
366 settings_file = os.path.join(tmpdir, "template.info")
368 if not os.path.exists(settings_file):
369 raise src.SatException(_("Settings file not found"))
370 tsettings = TemplateSettings("NAME", settings_file, "target")
372 logger.write("\n", 3)
373 if len(tsettings.info) == 0:
374 logger.write(src.printcolors.printcWarning(_(
375 "No information for this template.")), 3)
377 logger.write(tsettings.info, 3)
379 logger.write("\n", 3)
380 logger.write("= Configuration", 3)
381 src.printcolors.print_value(logger,
382 "file substitution key",
383 tsettings.file_subst)
384 src.printcolors.print_value(logger,
386 tsettings.delimiter_char)
387 if len(tsettings.ignore_filters) > 0:
388 src.printcolors.print_value(logger,
390 ', '.join(tsettings.ignore_filters))
392 logger.write("\n", 3)
393 logger.write("= Parameters", 3)
395 for pp in tsettings.parameters:
396 tt = TParam(pp, "NAME")
397 pnames.append(tt.name)
398 src.printcolors.print_value(logger, "Name", tt.name)
399 src.printcolors.print_value(logger, "Prompt", tt.raw_prompt)
400 src.printcolors.print_value(logger, "Default value", tt.default)
401 logger.write("\n", 3)
404 logger.write("= Verification\n", 3)
405 if tsettings.file_subst not in pnames:
407 "file substitution key not defined as a "
408 "parameter: %s" % tsettings.file_subst, 3)
411 reexp = tsettings.delimiter_char.replace("$", "\$") + "{(?P<name>\S[^}]*)"
412 pathlen = len(tmpdir) + 1
413 for root, __, files in os.walk(tmpdir):
415 fpath = os.path.join(root, fic)
416 if not tsettings.check_file_for_substitution(fpath[pathlen:]):
419 with open(fpath, 'r') as f:
421 zz = re.findall(reexp, m)
422 zz = list(set(zz)) # reduce
423 zz = filter(lambda l: l not in pnames, zz)
425 logger.write("Missing definition in %s: %s" % (
426 src.printcolors.printcLabel(
427 fpath[pathlen:]), ", ".join(zz)), 3)
431 logger.write(src.printcolors.printc("OK"), 3)
433 logger.write(src.printcolors.printc("KO"), 3)
435 logger.write("\n", 3)
438 shutil.rmtree(tmpdir)
443 # Describes the command
445 return _("The template command creates the sources for a SALOME "
446 "module from a template.\n\nexample\nsat template "
447 "--name my_product_name --template PythonComponent --target /tmp")
449 def run(args, runner, logger):
450 '''method that is called when salomeTools is called with template parameter.
452 (options, args) = parser.parse_args(args)
454 if options.template is None:
455 msg = _("Error: the --%s argument is required\n") % "template"
456 logger.write(src.printcolors.printcError(msg), 1)
457 logger.write("\n", 1)
460 if options.target is None and options.info is None:
461 msg = _("Error: the --%s argument is required\n") % "target"
462 logger.write(src.printcolors.printcError(msg), 1)
463 logger.write("\n", 1)
466 # if "APPLICATION" in runner.cfg:
467 # msg = _("Error: this command does not use a product.")
468 # logger.write(src.printcolors.printcError(msg), 1)
469 # logger.write("\n", 1)
473 return get_template_info(runner.cfg, options.template, logger)
475 if options.name is None:
476 msg = _("Error: the --%s argument is required\n") % "name"
477 logger.write(src.printcolors.printcError(msg), 1)
478 logger.write("\n", 1)
481 if not options.name.replace('_', '').isalnum():
482 msg = _("Error: component name must contains only alphanumeric "
483 "characters and no spaces\n")
484 logger.write(src.printcolors.printcError(msg), 1)
485 logger.write("\n", 1)
488 if options.target is None:
489 msg = _("Error: the --%s argument is required\n") % "target"
490 logger.write(src.printcolors.printcError(msg), 1)
491 logger.write("\n", 1)
494 target_dir = os.path.join(options.target, options.name)
495 if os.path.exists(target_dir):
496 msg = _("Error: the target already exists: %s") % target_dir
497 logger.write(src.printcolors.printcError(msg), 1)
498 logger.write("\n", 1)
502 logger.write(_('Create sources from template\n'), 1)
503 src.printcolors.print_value(logger, 'destination', target_dir, 2)
504 src.printcolors.print_value(logger, 'name', options.name, 2)
505 src.printcolors.print_value(logger, 'template', options.template, 2)
506 logger.write("\n", 3, False)
509 if options.param is not None:
511 for elt in options.param.split(","):
512 param_def = elt.strip().split('=')
513 if len(param_def) != 2:
514 msg = _("Error: bad parameter definition")
515 logger.write(src.printcolors.printcError(msg), 1)
516 logger.write("\n", 1)
518 conf_values[param_def[0].strip()] = param_def[1].strip()
520 retcode = prepare_from_template(runner.cfg, options.name, options.template,
521 target_dir, conf_values, logger)
525 "The sources were created in %s") % src.printcolors.printcInfo(
527 logger.write(src.printcolors.printcWarning(_("\nDo not forget to put "
528 "them in your version control system.")), 3)
530 logger.write("\n", 3)