Salome HOME
fix bug for overwriting products in the application pyconf
[tools/sat.git] / commands / config.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  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 platform
21 import datetime
22 import shutil
23 import gettext
24 import sys
25
26 import src
27
28 # internationalization
29 satdir  = os.path.dirname(os.path.realpath(__file__))
30 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
31
32 # Define all possible option for config command :  sat config <options>
33 parser = src.options.Options()
34 parser.add_option('v', 'value', 'string', 'value',
35     _("Optional: print the value of CONFIG_VARIABLE."))
36 parser.add_option('e', 'edit', 'boolean', 'edit',
37     _("Optional: edit the product configuration file."))
38 parser.add_option('i', 'info', 'string', 'info',
39     _("Optional: get information on a product."))
40 parser.add_option('l', 'list', 'boolean', 'list',
41     _("Optional: list all available applications."))
42 parser.add_option('', 'show_patchs', 'boolean', 'show_patchs',
43     _("Optional: synthetic view of all patches used in the application"))
44 parser.add_option('c', 'copy', 'boolean', 'copy',
45     _("""Optional: copy a config file to the personal config files directory.
46 \tWARNING the included files are not copied.
47 \tIf a name is given the new config file takes the given name."""))
48 parser.add_option('n', 'no_label', 'boolean', 'no_label',
49     _("Internal use: do not print labels, Works only with --value and --list."))
50 parser.add_option('', 'completion', 'boolean', 'completion',
51     _("Internal use: print only keys, works only with --value."))
52 parser.add_option('s', 'schema', 'boolean', 'schema',
53     _("Internal use."))
54
55 class ConfigOpener:
56     '''Class that helps to find an application pyconf 
57        in all the possible directories (pathList)
58     '''
59     def __init__(self, pathList):
60         '''Initialization
61         
62         :param pathList list: The list of paths where to search a pyconf.
63         '''
64         self.pathList = pathList
65
66     def __call__(self, name):
67         if os.path.isabs(name):
68             return src.pyconf.ConfigInputStream(open(name, 'rb'))
69         else:
70             return src.pyconf.ConfigInputStream( 
71                         open(os.path.join( self.get_path(name), name ), 'rb') )
72         raise IOError(_("Configuration file '%s' not found") % name)
73
74     def get_path( self, name ):
75         '''The method that returns the entire path of the pyconf searched
76         :param name str: The name of the searched pyconf.
77         '''
78         for path in self.pathList:
79             if os.path.exists(os.path.join(path, name)):
80                 return path
81         raise IOError(_("Configuration file '%s' not found") % name)
82
83 class ConfigManager:
84     '''Class that manages the read of all the configuration files of salomeTools
85     '''
86     def __init__(self, datadir=None):
87         pass
88
89     def _create_vars(self, application=None, command=None, datadir=None):
90         '''Create a dictionary that stores all information about machine,
91            user, date, repositories, etc...
92         
93         :param application str: The application for which salomeTools is called.
94         :param command str: The command that is called.
95         :param datadir str: The repository that contain external data 
96                             for salomeTools.
97         :return: The dictionary that stores all information.
98         :rtype: dict
99         '''
100         var = {}      
101         var['user'] = src.architecture.get_user()
102         var['salometoolsway'] = os.path.dirname(
103                                     os.path.dirname(os.path.abspath(__file__)))
104         var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
105         var['internal_dir'] = os.path.join(var['srcDir'], 'internal_config')
106         var['sep']= os.path.sep
107         
108         # datadir has a default location
109         var['datadir'] = os.path.join(var['salometoolsway'], 'data')
110         if datadir is not None:
111             var['datadir'] = datadir
112
113         var['personalDir'] = os.path.join(os.path.expanduser('~'),
114                                            '.salomeTools')
115         src.ensure_path_exists(var['personalDir'])
116
117         var['personal_applications_dir'] = os.path.join(var['personalDir'],
118                                                         "Applications")
119         src.ensure_path_exists(var['personal_applications_dir'])
120         
121         var['personal_products_dir'] = os.path.join(var['personalDir'],
122                                                     "products")
123         src.ensure_path_exists(var['personal_products_dir'])
124         
125         var['personal_archives_dir'] = os.path.join(var['personalDir'],
126                                                     "Archives")
127         src.ensure_path_exists(var['personal_archives_dir'])
128
129         var['personal_jobs_dir'] = os.path.join(var['personalDir'],
130                                                 "Jobs")
131         src.ensure_path_exists(var['personal_jobs_dir'])
132
133         var['personal_machines_dir'] = os.path.join(var['personalDir'],
134                                                     "Machines")
135         src.ensure_path_exists(var['personal_machines_dir'])
136
137         # read linux distributions dictionary
138         distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
139                                                       'internal_config',
140                                                       'distrib.pyconf'))
141         
142         # set platform parameters
143         dist_name = src.architecture.get_distribution(
144                                             codes=distrib_cfg.DISTRIBUTIONS)
145         dist_version = src.architecture.get_distrib_version(dist_name, 
146                                                     codes=distrib_cfg.VERSIONS)
147         dist = dist_name + dist_version
148         
149         var['dist_name'] = dist_name
150         var['dist_version'] = dist_version
151         var['dist'] = dist
152         var['python'] = src.architecture.get_python_version()
153
154         var['nb_proc'] = src.architecture.get_nb_proc()
155         node_name = platform.node()
156         var['node'] = node_name
157         var['hostname'] = node_name
158
159         # set date parameters
160         dt = datetime.datetime.now()
161         var['date'] = dt.strftime('%Y%m%d')
162         var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
163         var['hour'] = dt.strftime('%H%M%S')
164
165         var['command'] = str(command)
166         var['application'] = str(application)
167
168         # Root dir for temporary files 
169         var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
170         # particular win case 
171         if src.architecture.is_windows() : 
172             var['tmp_root'] =  os.path.expanduser('~') + os.sep + 'tmp'
173         
174         return var
175
176     def get_command_line_overrides(self, options, sections):
177         '''get all the overwrites that are in the command line
178         
179         :param options: the options from salomeTools class 
180                         initialization (like -l5 or --overwrite)
181         :param sections str: The config section to overwrite.
182         :return: The list of all the overwrites to apply.
183         :rtype: list
184         '''
185         # when there are no options or not the overwrite option, 
186         # return an empty list
187         if options is None or options.overwrite is None:
188             return []
189         
190         over = []
191         for section in sections:
192             # only overwrite the sections that correspond to the option 
193             over.extend(filter(lambda l: l.startswith(section + "."), 
194                                options.overwrite))
195         return over
196
197     def get_config(self, application=None, options=None, command=None,
198                     datadir=None):
199         '''get the config from all the configuration files.
200         
201         :param application str: The application for which salomeTools is called.
202         :param options class Options: The general salomeToos
203                                       options (--overwrite or -l5, for example)
204         :param command str: The command that is called.
205         :param datadir str: The repository that contain 
206                             external data for salomeTools.
207         :return: The final config.
208         :rtype: class 'src.pyconf.Config'
209         '''        
210         
211         # create a ConfigMerger to handle merge
212         merger = src.pyconf.ConfigMerger()#MergeHandler())
213         
214         # create the configuration instance
215         cfg = src.pyconf.Config()
216         
217         # =====================================================================
218         # create VARS section
219         var = self._create_vars(application=application, command=command, 
220                                 datadir=datadir)
221         # add VARS to config
222         cfg.VARS = src.pyconf.Mapping(cfg)
223         for variable in var:
224             cfg.VARS[variable] = var[variable]
225         
226         # apply overwrite from command line if needed
227         for rule in self.get_command_line_overrides(options, ["VARS"]):
228             exec('cfg.' + rule) # this cannot be factorized because of the exec
229         
230         # =====================================================================
231         # Load INTERNAL config
232         # read src/internal_config/salomeTools.pyconf
233         src.pyconf.streamOpener = ConfigOpener([
234                             os.path.join(cfg.VARS.srcDir, 'internal_config')])
235         try:
236             internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir, 
237                                     'internal_config', 'salomeTools.pyconf')))
238         except src.pyconf.ConfigError as e:
239             raise src.SatException(_("Error in configuration file:"
240                                      " salomeTools.pyconf\n  %(error)s") % \
241                                    {'error': str(e) })
242         
243         merger.merge(cfg, internal_cfg)
244
245         # apply overwrite from command line if needed
246         for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
247             exec('cfg.' + rule) # this cannot be factorized because of the exec        
248                
249         # =====================================================================
250         # Load SITE config file
251         # search only in the data directory
252         src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
253         try:
254             site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir, 
255                                                            'site.pyconf')),
256                                          PWD = ('SITE', cfg.VARS.datadir) )
257         except src.pyconf.ConfigError as e:
258             raise src.SatException(_("Error in configuration file: "
259                                      "site.pyconf\n  %(error)s") % \
260                 {'error': str(e) })
261         except IOError as error:
262             e = str(error)
263             if "site.pyconf" in e :
264                 e += ("\nYou can copy data"
265                   + cfg.VARS.sep
266                   + "site.template.pyconf to data"
267                   + cfg.VARS.sep 
268                   + "site.pyconf and edit the file")
269             raise src.SatException( e );
270         merger.merge(cfg, site_cfg)
271
272         # apply overwrite from command line if needed
273         for rule in self.get_command_line_overrides(options, ["SITE"]):
274             exec('cfg.' + rule) # this cannot be factorized because of the exec
275         
276         # =====================================================================
277         # Load the PROJECTS
278         projects_cfg = src.pyconf.Config()
279         projects_cfg.addMapping("PROJECTS",
280                                 src.pyconf.Mapping(projects_cfg),
281                                 "The projects\n")
282         projects_cfg.PROJECTS.addMapping("projects",
283                                 src.pyconf.Mapping(cfg.PROJECTS),
284                                 "The projects definition\n")
285         
286         for project_pyconf_path in cfg.PROJECTS.project_file_paths:
287             if not os.path.exists(project_pyconf_path):
288                 msg = _("WARNING: The project file %s cannot be found. "
289                         "It will be ignored\n" % project_pyconf_path)
290                 sys.stdout.write(msg)
291                 continue
292             project_name = os.path.basename(
293                                     project_pyconf_path)[:-len(".pyconf")]
294             try:
295                 project_pyconf_dir = os.path.dirname(project_pyconf_path)
296                 project_cfg = src.pyconf.Config(open(project_pyconf_path),
297                                                 PWD=("", project_pyconf_dir))
298             except Exception as e:
299                 msg = _("ERROR: Error in configuration file: "
300                                  "%(file_path)s\n  %(error)s\n") % \
301                             {'file_path' : project_pyconf_path, 'error': str(e) }
302                 sys.stdout.write(msg)
303                 continue
304             projects_cfg.PROJECTS.projects.addMapping(project_name,
305                              src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
306                              "The %s project\n" % project_name)
307             projects_cfg.PROJECTS.projects[project_name]=project_cfg
308             projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
309                                                         project_pyconf_path
310                    
311         merger.merge(cfg, projects_cfg)
312
313         # apply overwrite from command line if needed
314         for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
315             exec('cfg.' + rule) # this cannot be factorized because of the exec
316         
317         # =====================================================================
318         # Create the paths where to search the application configurations, 
319         # the product configurations, the products archives, 
320         # the jobs configurations and the machines configurations
321         cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
322         cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
323         cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
324         
325         cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
326         cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
327         cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
328         cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
329         cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
330         cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
331         cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
332         cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
333         # Loop over the projects in order to complete the PATHS variables
334         for project in cfg.PROJECTS.projects:
335             for PATH in ["APPLICATIONPATH",
336                          "PRODUCTPATH",
337                          "ARCHIVEPATH",
338                          "JOBPATH",
339                          "MACHINEPATH"]:
340                 if PATH not in cfg.PROJECTS.projects[project]:
341                     continue
342                 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
343         
344         # apply overwrite from command line if needed
345         for rule in self.get_command_line_overrides(options, ["PATHS"]):
346             exec('cfg.' + rule) # this cannot be factorized because of the exec
347
348         # =====================================================================
349         # Load APPLICATION config file
350         if application is not None:
351             # search APPLICATION file in all directories in configPath
352             cp = cfg.PATHS.APPLICATIONPATH
353             src.pyconf.streamOpener = ConfigOpener(cp)
354             do_merge = True
355             try:
356                 application_cfg = src.pyconf.Config(application + '.pyconf')
357             except IOError as e:
358                 raise src.SatException(_("%s, use 'config --list' to get the"
359                                          " list of available applications.") %e)
360             except src.pyconf.ConfigError as e:
361                 if (not ('-e' in parser.parse_args()[1]) 
362                                          or ('--edit' in parser.parse_args()[1]) 
363                                          and command == 'config'):
364                     raise src.SatException(_("Error in configuration file: "
365                                              "%(application)s.pyconf\n "
366                                              " %(error)s") % \
367                         { 'application': application, 'error': str(e) } )
368                 else:
369                     sys.stdout.write(src.printcolors.printcWarning(
370                                         "There is an error in the file"
371                                         " %s.pyconf.\n" % cfg.VARS.application))
372                     do_merge = False
373             except Exception as e:
374                 if (not ('-e' in parser.parse_args()[1]) 
375                                         or ('--edit' in parser.parse_args()[1]) 
376                                         and command == 'config'):
377                     sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
378                     raise src.SatException(_("Error in configuration file:"
379                                              " %(application)s.pyconf\n") % \
380                         { 'application': application} )
381                 else:
382                     sys.stdout.write(src.printcolors.printcWarning(
383                                 "There is an error in the file"
384                                 " %s.pyconf. Opening the file with the"
385                                 " default viewer\n" % cfg.VARS.application))
386                     sys.stdout.write("The error:"
387                                  " %s\n" % src.printcolors.printcWarning(
388                                                                       str(e)))
389                     do_merge = False
390         
391             else:
392                 cfg['open_application'] = 'yes'
393
394         # =====================================================================
395         # Load product config files in PRODUCTS section
396         products_cfg = src.pyconf.Config()
397         products_cfg.addMapping("PRODUCTS",
398                                 src.pyconf.Mapping(products_cfg),
399                                 "The products\n")
400         if application is not None:
401             src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
402             for product_name in application_cfg.APPLICATION.products.keys():
403                 # Loop on all files that are in softsDir directory
404                 # and read their config
405                 product_file_name = product_name + ".pyconf"
406                 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
407                 if product_file_path:
408                     products_dir = os.path.dirname(product_file_path)
409                     try:
410                         prod_cfg = src.pyconf.Config(open(
411                                                     os.path.join(products_dir,
412                                                                  product_file_name)),
413                                                      PWD=("", products_dir))
414                         products_cfg.PRODUCTS[product_name] = prod_cfg
415                     except Exception as e:
416                         msg = _(
417                             "WARNING: Error in configuration file"
418                             ": %(prod)s\n  %(error)s" % \
419                             {'prod' :  product_name, 'error': str(e) })
420                         sys.stdout.write(msg)
421             
422             merger.merge(cfg, products_cfg)
423             
424             # apply overwrite from command line if needed
425             for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
426                 exec('cfg.' + rule) # this cannot be factorized because of the exec
427             
428             if do_merge:
429                 merger.merge(cfg, application_cfg)
430
431                 # default launcher name ('salome')
432                 if ('profile' in cfg.APPLICATION and 
433                     'launcher_name' not in cfg.APPLICATION.profile):
434                     cfg.APPLICATION.profile.launcher_name = 'salome'
435
436                 # apply overwrite from command line if needed
437                 for rule in self.get_command_line_overrides(options,
438                                                              ["APPLICATION"]):
439                     # this cannot be factorized because of the exec
440                     exec('cfg.' + rule)
441             
442         # =====================================================================
443         # load USER config
444         self.set_user_config_file(cfg)
445         user_cfg_file = self.get_user_config_file()
446         user_cfg = src.pyconf.Config(open(user_cfg_file))
447         merger.merge(cfg, user_cfg)
448
449         # apply overwrite from command line if needed
450         for rule in self.get_command_line_overrides(options, ["USER"]):
451             exec('cfg.' + rule) # this cannot be factorize because of the exec
452         
453         return cfg
454
455     def set_user_config_file(self, config):
456         '''Set the user config file name and path.
457         If necessary, build it from another one or create it from scratch.
458         
459         :param config class 'src.pyconf.Config': The global config 
460                                                  (containing all pyconf).
461         '''
462         # get the expected name and path of the file
463         self.config_file_name = 'salomeTools.pyconf'
464         self.user_config_file_path = os.path.join(config.VARS.personalDir,
465                                                    self.config_file_name)
466         
467         # if pyconf does not exist, create it from scratch
468         if not os.path.isfile(self.user_config_file_path): 
469             self.create_config_file(config)
470     
471     def create_config_file(self, config):
472         '''This method is called when there are no user config file. 
473            It build it from scratch.
474         
475         :param config class 'src.pyconf.Config': The global config.
476         :return: the config corresponding to the file created.
477         :rtype: config class 'src.pyconf.Config'
478         '''
479         
480         cfg_name = self.get_user_config_file()
481
482         user_cfg = src.pyconf.Config()
483         #
484         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
485
486         #
487         user_cfg.USER.addMapping('workdir', os.path.expanduser('~'),
488             "This is where salomeTools will work. "
489             "You may (and probably do) change it.\n")
490         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
491             "This is the user name used to access salome cvs base.\n")
492         user_cfg.USER.addMapping('svn_user', config.VARS.user,
493             "This is the user name used to access salome svn base.\n")
494         user_cfg.USER.addMapping('output_verbose_level', 3,
495             "This is the default output_verbose_level you want."
496             " 0=>no output, 5=>debug.\n")
497         user_cfg.USER.addMapping('publish_dir', 
498                                  os.path.join(os.path.expanduser('~'),
499                                  'websupport', 
500                                  'satreport'), 
501                                  "")
502         user_cfg.USER.addMapping('editor',
503                                  'vi', 
504                                  "This is the editor used to "
505                                  "modify configuration files\n")
506         user_cfg.USER.addMapping('browser', 
507                                  'firefox', 
508                                  "This is the browser used to "
509                                  "read html documentation\n")
510         user_cfg.USER.addMapping('pdf_viewer', 
511                                  'evince', 
512                                  "This is the pdf_viewer used "
513                                  "to read pdf documentation\n")
514         user_cfg.USER.addMapping("base",
515                                  src.pyconf.Reference(
516                                             user_cfg,
517                                             src.pyconf.DOLLAR,
518                                             'workdir  + $VARS.sep + "BASE"'),
519                                  "The products installation base (could be "
520                                  "ignored if this key exists in the site.pyconf"
521                                  " file of salomTools).\n")
522         
523         user_cfg.USER.addMapping("log_dir",
524                                  src.pyconf.Reference(
525                                             user_cfg,
526                                             src.pyconf.DOLLAR,
527                                             'workdir  + $VARS.sep + "LOGS"'),
528                                  "The log repository\n")
529         
530         # 
531         src.ensure_path_exists(config.VARS.personalDir)
532         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
533                                             'Applications'))
534
535         f = open(cfg_name, 'w')
536         user_cfg.__save__(f)
537         f.close()
538
539         return user_cfg   
540
541     def get_user_config_file(self):
542         '''Get the user config file
543         :return: path to the user config file.
544         :rtype: str
545         '''
546         if not self.user_config_file_path:
547             raise src.SatException(_("Error in get_user_config_file: "
548                                      "missing user config file path"))
549         return self.user_config_file_path     
550
551 def check_path(path, ext=[]):
552     '''Construct a text with the input path and "not found" if it does not
553        exist.
554     
555     :param path Str: the path to check.
556     :param ext List: An extension. Verify that the path extension 
557                      is in the list
558     :return: The string of the path with information
559     :rtype: Str
560     '''
561     # check if file exists
562     if not os.path.exists(path):
563         return "'%s'" % path + " " + src.printcolors.printcError(_(
564                                                             "** not found"))
565
566     # check extension
567     if len(ext) > 0:
568         fe = os.path.splitext(path)[1].lower()
569         if fe not in ext:
570             return "'%s'" % path + " " + src.printcolors.printcError(_(
571                                                         "** bad extension"))
572
573     return path
574
575 def show_product_info(config, name, logger):
576     '''Display on the terminal and logger information about a product.
577     
578     :param config Config: the global configuration.
579     :param name Str: The name of the product
580     :param logger Logger: The logger instance to use for the display
581     '''
582     
583     logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
584     pinfo = src.product.get_product_config(config, name)
585     
586     # Type of the product
587     ptype = src.get_cfg_param(pinfo, "type", "")
588     src.printcolors.print_value(logger, "type", ptype, 2)
589     if "depend" in pinfo:
590         src.printcolors.print_value(logger, 
591                                     "depends on", 
592                                     ', '.join(pinfo.depend), 2)
593
594     if "opt_depend" in pinfo:
595         src.printcolors.print_value(logger, 
596                                     "optional", 
597                                     ', '.join(pinfo.opt_depend), 2)
598
599     # information on prepare
600     logger.write("\n", 2)
601     logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
602
603     is_dev = src.product.product_is_dev(pinfo)
604     method = pinfo.get_source
605     if is_dev:
606         method += " (dev)"
607     src.printcolors.print_value(logger, "get method", method, 2)
608
609     if method == 'cvs':
610         src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
611         src.printcolors.print_value(logger, "base module",
612                                     pinfo.cvs_info.module_base, 2)
613         src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
614         src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
615
616     elif method == 'svn':
617         src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
618
619     elif method == 'git':
620         src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
621         src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
622
623     elif method == 'archive':
624         src.printcolors.print_value(logger, 
625                                     "get from", 
626                                     check_path(pinfo.archive_info.archive_name), 
627                                     2)
628
629     if 'patches' in pinfo:
630         for patch in pinfo.patches:
631             src.printcolors.print_value(logger, "patch", check_path(patch), 2)
632
633     if src.product.product_is_fixed(pinfo):
634         src.printcolors.print_value(logger, "install_dir", 
635                                     check_path(pinfo.install_dir), 2)
636
637     if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
638         return
639     
640     # information on compilation
641     if src.product.product_compiles(pinfo):
642         logger.write("\n", 2)
643         logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
644         src.printcolors.print_value(logger, 
645                                     "compilation method", 
646                                     pinfo.build_source, 
647                                     2)
648         
649         if pinfo.build_source == "script" and "compil_script" in pinfo:
650             src.printcolors.print_value(logger, 
651                                         "Compilation script", 
652                                         pinfo.compil_script, 
653                                         2)
654         
655         if 'nb_proc' in pinfo:
656             src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
657     
658         src.printcolors.print_value(logger, 
659                                     "source dir", 
660                                     check_path(pinfo.source_dir), 
661                                     2)
662         if 'install_dir' in pinfo:
663             src.printcolors.print_value(logger, 
664                                         "build dir", 
665                                         check_path(pinfo.build_dir), 
666                                         2)
667             src.printcolors.print_value(logger, 
668                                         "install dir", 
669                                         check_path(pinfo.install_dir), 
670                                         2)
671         else:
672             logger.write("  " + 
673                          src.printcolors.printcWarning(_("no install dir")) + 
674                          "\n", 2)
675     else:
676         logger.write("\n", 2)
677         msg = _("This product does not compile")
678         logger.write("%s\n" % msg, 2)
679
680     # information on environment
681     logger.write("\n", 2)
682     logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
683     if "environ" in pinfo and "env_script" in pinfo.environ:
684         src.printcolors.print_value(logger, 
685                                     "script", 
686                                     check_path(pinfo.environ.env_script), 
687                                     2)
688
689     zz = src.environment.SalomeEnviron(config, 
690                                        src.fileEnviron.ScreenEnviron(logger), 
691                                        False)
692     zz.set_python_libdirs()
693     zz.set_a_product(name, logger)
694         
695 def show_patchs(config, logger):
696     '''Prints all the used patchs in the application.
697     
698     :param config Config: the global configuration.
699     :param logger Logger: The logger instance to use for the display
700     '''
701     len_max = max([len(p) for p in config.APPLICATION.products]) + 2
702     for product in config.APPLICATION.products:
703         product_info = src.product.get_product_config(config, product)
704         if src.product.product_has_patches(product_info):
705             logger.write("%s: " % product, 1)
706             logger.write(src.printcolors.printcInfo(
707                                             " " * (len_max - len(product) -2) +
708                                             "%s\n" % product_info.patches[0]),
709                          1)
710             if len(product_info.patches) > 1:
711                 for patch in product_info.patches[1:]:
712                     logger.write(src.printcolors.printcInfo(len_max*" " +
713                                                             "%s\n" % patch), 1)
714             logger.write("\n", 1)
715
716 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
717     '''Prints a value from the configuration. Prints recursively the values 
718        under the initial path.
719     
720     :param config class 'src.pyconf.Config': The configuration 
721                                              from which the value is displayed.
722     :param path str : the path in the configuration of the value to print.
723     :param show_label boolean: if True, do a basic display. 
724                                (useful for bash completion)
725     :param logger Logger: the logger instance
726     :param level int: The number of spaces to add before display.
727     :param show_full_path :
728     '''            
729     
730     # Make sure that the path does not ends with a point
731     if path.endswith('.'):
732         path = path[:-1]
733     
734     # display all the path or not
735     if show_full_path:
736         vname = path
737     else:
738         vname = path.split('.')[-1]
739
740     # number of spaces before the display
741     tab_level = "  " * level
742     
743     # call to the function that gets the value of the path.
744     try:
745         val = config.getByPath(path)
746     except Exception as e:
747         logger.write(tab_level)
748         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
749                                          src.printcolors.printcError(str(e))))
750         return
751
752     # in this case, display only the value
753     if show_label:
754         logger.write(tab_level)
755         logger.write("%s: " % src.printcolors.printcLabel(vname))
756
757     # The case where the value has under values, 
758     # do a recursive call to the function
759     if dir(val).__contains__('keys'):
760         if show_label: logger.write("\n")
761         for v in sorted(val.keys()):
762             print_value(config, path + '.' + v, show_label, logger, level + 1)
763     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
764         # in this case, value is a list (or a Sequence)
765         if show_label: logger.write("\n")
766         index = 0
767         for v in val:
768             print_value(config, path + "[" + str(index) + "]", 
769                         show_label, logger, level + 1)
770             index = index + 1
771     else: # case where val is just a str
772         logger.write("%s\n" % val)
773
774 def get_config_children(config, args):
775     '''Gets the names of the children of the given parameter.
776        Useful only for completion mechanism
777     
778     :param config Config: The configuration where to read the values
779     :param args: The path in the config from which get the keys
780     '''
781     vals = []
782     rootkeys = config.keys()
783     
784     if len(args) == 0:
785         # no parameter returns list of root keys
786         vals = rootkeys
787     else:
788         parent = args[0]
789         pos = parent.rfind('.')
790         if pos < 0:
791             # Case where there is only on key as parameter.
792             # For example VARS
793             vals = [m for m in rootkeys if m.startswith(parent)]
794         else:
795             # Case where there is a part from a key
796             # for example VARS.us  (for VARS.user)
797             head = parent[0:pos]
798             tail = parent[pos+1:]
799             try:
800                 a = config.getByPath(head)
801                 if dir(a).__contains__('keys'):
802                     vals = map(lambda x: head + '.' + x,
803                                [m for m in a.keys() if m.startswith(tail)])
804             except:
805                 pass
806
807     for v in sorted(vals):
808         sys.stdout.write("%s\n" % v)
809
810 def description():
811     '''method that is called when salomeTools is called with --help option.
812     
813     :return: The text to display for the config command description.
814     :rtype: str
815     '''
816     return _("The config command allows manipulation "
817              "and operation on config files.\n\nexample:\nsat config "
818              "SALOME-master --info ParaView")
819     
820
821 def run(args, runner, logger):
822     '''method that is called when salomeTools is called with config parameter.
823     '''
824     # Parse the options
825     (options, args) = parser.parse_args(args)
826
827     # Only useful for completion mechanism : print the keys of the config
828     if options.schema:
829         get_config_children(runner.cfg, args)
830         return
831     
832     # case : print a value of the config
833     if options.value:
834         if options.value == ".":
835             # if argument is ".", print all the config
836             for val in sorted(runner.cfg.keys()):
837                 print_value(runner.cfg, val, not options.no_label, logger)
838         else:
839             print_value(runner.cfg, options.value, not options.no_label, logger, 
840                         level=0, show_full_path=False)
841     
842     # case : edit user pyconf file or application file
843     elif options.edit:
844         editor = runner.cfg.USER.editor
845         if ('APPLICATION' not in runner.cfg and
846                        'open_application' not in runner.cfg): # edit user pyconf
847             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
848                                    'salomeTools.pyconf')
849             logger.write(_("Openning %s\n" % usercfg), 3)
850             src.system.show_in_editor(editor, usercfg, logger)
851         else:
852             # search for file <application>.pyconf and open it
853             for path in runner.cfg.PATHS.APPLICATIONPATH:
854                 pyconf_path = os.path.join(path, 
855                                     runner.cfg.VARS.application + ".pyconf")
856                 if os.path.exists(pyconf_path):
857                     logger.write(_("Openning %s\n" % pyconf_path), 3)
858                     src.system.show_in_editor(editor, pyconf_path, logger)
859                     break
860     
861     # case : give information about the product in parameter
862     elif options.info:
863         src.check_config_has_application(runner.cfg)
864         if options.info in runner.cfg.APPLICATION.products:
865             show_product_info(runner.cfg, options.info, logger)
866             return
867         raise src.SatException(_("%(product_name)s is not a product "
868                                  "of %(application_name)s.") % 
869                                {'product_name' : options.info,
870                                 'application_name' : 
871                                 runner.cfg.VARS.application})
872     
873     # case : copy an existing <application>.pyconf 
874     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
875     elif options.copy:
876         # product is required
877         src.check_config_has_application( runner.cfg )
878
879         # get application file path 
880         source = runner.cfg.VARS.application + '.pyconf'
881         source_full_path = ""
882         for path in runner.cfg.PATHS.APPLICATIONPATH:
883             # ignore personal directory
884             if path == runner.cfg.VARS.personalDir:
885                 continue
886             # loop on all directories that can have pyconf applications
887             zz = os.path.join(path, source)
888             if os.path.exists(zz):
889                 source_full_path = zz
890                 break
891
892         if len(source_full_path) == 0:
893             raise src.SatException(_(
894                         "Config file for product %s not found\n") % source)
895         else:
896             if len(args) > 0:
897                 # a name is given as parameter, use it
898                 dest = args[0]
899             elif 'copy_prefix' in runner.cfg.INTERNAL.config:
900                 # use prefix
901                 dest = (runner.cfg.INTERNAL.config.copy_prefix 
902                         + runner.cfg.VARS.application)
903             else:
904                 # use same name as source
905                 dest = runner.cfg.VARS.application
906                 
907             # the full path
908             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
909                                      'Applications', dest + '.pyconf')
910             if os.path.exists(dest_file):
911                 raise src.SatException(_("A personal application"
912                                          " '%s' already exists") % dest)
913             
914             # perform the copy
915             shutil.copyfile(source_full_path, dest_file)
916             logger.write(_("%s has been created.\n") % dest_file)
917     
918     # case : display all the available pyconf applications
919     elif options.list:
920         lproduct = list()
921         # search in all directories that can have pyconf applications
922         for path in runner.cfg.PATHS.APPLICATIONPATH:
923             # print a header
924             if not options.no_label:
925                 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
926
927             if not os.path.exists(path):
928                 logger.write(src.printcolors.printcError(_(
929                                             "Directory not found")) + "\n")
930             else:
931                 for f in sorted(os.listdir(path)):
932                     # ignore file that does not ends with .pyconf
933                     if not f.endswith('.pyconf'):
934                         continue
935
936                     appliname = f[:-len('.pyconf')]
937                     if appliname not in lproduct:
938                         lproduct.append(appliname)
939                         if path.startswith(runner.cfg.VARS.personalDir) \
940                                     and not options.no_label:
941                             logger.write("%s*\n" % appliname)
942                         else:
943                             logger.write("%s\n" % appliname)
944                             
945             logger.write("\n")
946     # case : give a synthetic view of all patches used in the application
947     elif options.show_patchs:
948         src.check_config_has_application(runner.cfg)
949         # Print some informations
950         logger.write(_('Show the patchs of application %s\n') % 
951                     src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
952         logger.write("\n", 2, False)
953         show_patchs(runner.cfg, logger)
954     
955     # case: print all the products name of the application (internal use for completion)
956     elif options.completion:
957         for product_name in runner.cfg.APPLICATION.products.keys():
958             logger.write("%s\n" % product_name)
959         
960