Salome HOME
e4ddc59677672ec65b8130cd0f57eff046c6248d
[tools/sat.git] / commands / template.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 import os
20 import string
21 import shutil
22 import subprocess
23 import fnmatch
24 import re
25
26 import src
27
28 # Compatibility python 2/3 for input function
29 # input stays input for python 3 and input = raw_input for python 2
30 try: 
31     input = raw_input
32 except NameError: 
33     pass
34
35 # Python 2/3 compatibility for execfile function
36 try:
37     execfile
38 except:
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)
43
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)
61
62 class TParam:
63     def __init__(self, param_def, compo_name, dico=None):
64         self.default = ""
65         self.prompt = ""
66         self.check_method = None
67         
68         if isinstance(param_def, str):
69             self.name = param_def
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]
77         else:
78             raise src.SatException(_("ERROR in template parameter definition"))
79
80         self.raw_prompt = self.prompt
81         if len(self.prompt) == 0:
82             self.prompt = _("value for '%s'") % self.name
83         self.prompt += "? "
84         if len(self.default) > 0:
85             self.prompt += "[%s] " % self.default
86
87     def check_value(self, val):
88         if self.check_method is None:
89             return len(val) > 0
90         return len(val) > 0 and self.check_method(val)
91
92 def get_dico_param(dico, key, default):
93     if key in dico:
94         return dico[key]
95     return default
96
97 class TemplateSettings:
98     def __init__(self, compo_name, settings_file, target):
99         self.compo_name = compo_name
100         self.dico = None
101         self.target = target
102
103         # read the settings
104         gdic, ldic = {}, {}
105         execfile(settings_file, gdic, ldic)
106
107         # check required parameters in template.info
108         missing = []
109         for pp in ["file_subst", "parameters"]:
110             if not (pp in ldic): missing.append("'%s'" % pp)
111         if len(missing) > 0:
112             raise src.SatException(_(
113                 "Bad format in settings file! %s not defined.") % ", ".join(
114                                                                        missing))
115         
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", "")
121
122         # get the delimiter for the template
123         self.delimiter_char = get_dico_param(ldic, "delimiter", ":sat:")
124
125         # get the ignore filter
126         self.ignore_filters = [l.strip() for l in ldic["ignore_filters"].split(',')]
127
128     def has_pyconf(self):
129         return len(self.pyconf) > 0
130
131     def get_pyconf_parameters(self):
132         if len(self.pyconf) == 0:
133             return []
134         return re.findall("%\((?P<name>\S[^\)]*)", self.pyconf)
135
136     ##
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_):
141                 return False
142         return True
143
144     def check_user_values(self, values):
145         if values is None:
146             return
147         
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)
153         
154         # reduce the list
155         pnames = list(set(pnames)) # remove duplicates
156
157         known_values = ["name", "Name", "NAME", "target", self.file_subst]
158         known_values.extend(values.keys())
159         missing = []
160         for p in pnames:
161             if p not in known_values:
162                 missing.append(p)
163         
164         if len(missing) > 0:
165             raise src.SatException(_(
166                                  "Missing parameters: %s") % ", ".join(missing))
167
168     def get_parameters(self, conf_values=None):
169         if self.dico is not None:
170             return self.dico
171
172         self.check_user_values(conf_values)
173
174         # create dictionary with default values
175         dico = {}
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]
185
186         # ask user for values
187         for p in self.parameters:
188             tp = TParam(p, self.compo_name, dico)
189             if tp.name in dico:
190                 continue
191             
192             val = ""
193             while not tp.check_value(val):
194                 val = input(tp.prompt)
195                 if len(val) == 0 and len(tp.default) > 0:
196                     val = tp.default
197             dico[tp.name] = val
198
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):
202             rep = ""
203             while len(rep) == 0:
204                 rep = input("%s? " % p)
205             dico[p] = rep
206
207         self.dico = dico
208         return self.dico
209
210 def search_template(config, template):
211     # search template
212     template_src_dir = ""
213     if os.path.isabs(template):
214         if os.path.exists(template):
215             template_src_dir = template
216     else:
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
222                 break
223
224     if len(template_src_dir) == 0:
225         raise src.SatException(_("Template not found: %s") % template)
226
227     return template_src_dir
228 ##
229 # Prepares a module from a template.
230 def prepare_from_template(config,
231                           name,
232                           template,
233                           target_dir,
234                           conf_values,
235                           logger):
236     template_src_dir = search_template(config, template)
237     res = 0
238
239     # copy the template
240     if os.path.isfile(template_src_dir):
241         logger.write("  " + _(
242                         "Extract template %s\n") % src.printcolors.printcInfo(
243                                                                    template), 4)
244         src.system.archive_extract(template_src_dir, target_dir)
245     else:
246         logger.write("  " + _(
247                         "Copy template %s\n") % src.printcolors.printcInfo(
248                                                                    template), 4)
249         shutil.copytree(template_src_dir, target_dir)
250     logger.write("\n", 5)
251
252     compo_name = name
253     if name.endswith("CPP"):
254         compo_name = name[:-3]
255
256     # read settings
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)
261
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):
265         for fic in files:
266             ff = fic.replace(tsettings.file_subst, compo_name)
267             if ff != fic:
268                 if os.path.exists(os.path.join(root, ff)):
269                     raise src.SatException(_(
270                         "Destination file already exists: %s") % os.path.join(
271                                                                       root, ff))
272                 logger.write("    %s -> %s\n" % (fic, ff), 5)
273                 os.rename(os.path.join(root, fic), os.path.join(root, ff))
274
275     # rename the directories
276     logger.write("\n", 5)
277     logger.write("  " + src.printcolors.printcLabel(_("Rename directories\n")),
278                  4)
279     for root, dirs, files in os.walk(target_dir, topdown=False):
280         for rep in dirs:
281             dd = rep.replace(tsettings.file_subst, compo_name)
282             if dd != rep:
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))
289
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,
295                  5)
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)
300
301     # override standard string.Template class to use the desire delimiter
302     class CompoTemplate(string.Template):
303         delimiter = tsettings.delimiter_char
304
305     # do substitution
306     logger.write("\n", 5, True)
307     pathlen = len(target_dir) + 1
308     for root, dirs, files in os.walk(target_dir):
309         for fic in files:
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)
313                 continue
314             # read the file
315             with open(fpath, 'r') as f:
316                 m = f.read()
317                 # make the substitution
318                 template = CompoTemplate(m)
319                 d = template.safe_substitute(dico)
320                         
321             changed = " "
322             if d != m:
323                 changed = "*"
324                 with open(fpath, 'w') as f:
325                     f.write(d)
326             logger.write("  %s %s\n" % (changed, fpath[pathlen:]), 5)
327
328     if not tsettings.has_pyconf:
329         logger.write(src.printcolors.printcWarning(_(
330                    "Definition for sat not found in settings file.")) + "\n", 2)
331     else:
332         definition = tsettings.pyconf % dico
333         pyconf_file = os.path.join(target_dir, name + '.pyconf')
334         f = open(pyconf_file, 'w')
335         f.write(definition)
336         f.close
337         logger.write(_(
338             "Create configuration file: ") + src.printcolors.printcInfo(
339                                                          pyconf_file) + "\n", 2)
340
341     if len(tsettings.post_command) > 0:
342         cmd = tsettings.post_command % dico
343         logger.write("\n", 5, True)
344         logger.write(_(
345               "Run post command: ") + src.printcolors.printcInfo(cmd) + "\n", 3)
346         
347         p = subprocess.Popen(cmd, shell=True, cwd=target_dir)
348         p.wait()
349         res = p.returncode
350
351     return res
352
353 def get_template_info(config, template_name, logger):
354     sources = search_template(config, template_name)
355     src.printcolors.print_value(logger, _("Template"), sources)
356
357     # read settings
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)
364     else:
365         src.system.archive_extract(sources, tmpdir)
366         settings_file = os.path.join(tmpdir, "template.info")
367
368     if not os.path.exists(settings_file):
369         raise src.SatException(_("Settings file not found"))
370     tsettings = TemplateSettings("NAME", settings_file, "target")
371     
372     logger.write("\n", 3)
373     if len(tsettings.info) == 0:
374         logger.write(src.printcolors.printcWarning(_(
375                                        "No information for this template.")), 3)
376     else:
377         logger.write(tsettings.info, 3)
378
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,
385                                 "subsitution key",
386                                 tsettings.delimiter_char)
387     if len(tsettings.ignore_filters) > 0:
388         src.printcolors.print_value(logger,
389                                     "Ignore Filter",
390                                     ', '.join(tsettings.ignore_filters))
391
392     logger.write("\n", 3)
393     logger.write("= Parameters", 3)
394     pnames = []
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)
402
403     retcode = 0
404     logger.write("= Verification\n", 3)
405     if tsettings.file_subst not in pnames:
406         logger.write(
407                      "file substitution key not defined as a "
408                      "parameter: %s" % tsettings.file_subst, 3)
409         retcode = 1
410     
411     reexp = tsettings.delimiter_char.replace("$", "\$") + "{(?P<name>\S[^}]*)"
412     pathlen = len(tmpdir) + 1
413     for root, __, files in os.walk(tmpdir):
414         for fic in files:
415             fpath = os.path.join(root, fic)
416             if not tsettings.check_file_for_substitution(fpath[pathlen:]):
417                 continue
418             # read the file
419             with open(fpath, 'r') as f:
420                 m = f.read()
421                 zz = re.findall(reexp, m)
422                 zz = list(set(zz)) # reduce
423                 zz = filter(lambda l: l not in pnames, zz)
424                 if len(zz) > 0:
425                     logger.write("Missing definition in %s: %s" % (
426                         src.printcolors.printcLabel(
427                                                 fpath[pathlen:]), ", ".join(zz)), 3)
428                     retcode = 1
429
430     if retcode == 0:
431         logger.write(src.printcolors.printc("OK"), 3)
432     else:
433         logger.write(src.printcolors.printc("KO"), 3)
434
435     logger.write("\n", 3)
436
437     # clean up tmp file
438     shutil.rmtree(tmpdir)
439
440     return retcode
441
442 ##
443 # Describes the command
444 def description():
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")
448
449 def run(args, runner, logger):
450     '''method that is called when salomeTools is called with template parameter.
451     '''
452     (options, args) = parser.parse_args(args)
453
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)
458         return 1
459
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)
464         return 1
465
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)
470     #     return 1
471
472     if options.info:
473         return get_template_info(runner.cfg, options.template, logger)
474
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)
479         return 1
480
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)
486         return 1
487
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)
492         return 1
493
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)
499         return 1
500
501
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)
507     
508     conf_values = None
509     if options.param is not None:
510         conf_values = {}
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)
517                 return 1
518             conf_values[param_def[0].strip()] = param_def[1].strip()
519     
520     retcode = prepare_from_template(runner.cfg, options.name, options.template,
521         target_dir, conf_values, logger)
522
523     if retcode == 0:
524         logger.write(_(
525                  "The sources were created in %s") % src.printcolors.printcInfo(
526                                                                  target_dir), 3)
527         logger.write(src.printcolors.printcWarning(_("\nDo not forget to put "
528                                    "them in your version control system.")), 3)
529         
530     logger.write("\n", 3)
531     
532     return retcode