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