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