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