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