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