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