Salome HOME
New command sait init. USER.workdir is replaced by LOCAL.workdir. Idem for USER.base...
[tools/sat.git] / commands / config.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  CEA/DEN
4 #
5 #  This library is free software; you can redistribute it and/or
6 #  modify it under the terms of the GNU Lesser General Public
7 #  License as published by the Free Software Foundation; either
8 #  version 2.1 of the License.
9 #
10 #  This library is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 #  Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public
16 #  License along with this library; if not, write to the Free Software
17 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18
19 import os
20 import platform
21 import datetime
22 import shutil
23 import gettext
24 import sys
25
26 import src
27
28 # internationalization
29 satdir  = os.path.dirname(os.path.realpath(__file__))
30 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
31
32 # Define all possible option for config command :  sat config <options>
33 parser = src.options.Options()
34 parser.add_option('v', 'value', 'string', 'value',
35     _("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 "unknown", put the default value
267         if cfg.LOCAL.base == "unknown":
268             cfg.LOCAL.base = os.path.abspath(
269                                         os.path.join(cfg.VARS.salometoolsway,
270                                                      "..",
271                                                      "BASE"))
272         if cfg.LOCAL.workdir == "unknown":
273             cfg.LOCAL.workdir = os.path.abspath(
274                                         os.path.join(cfg.VARS.salometoolsway,
275                                                      ".."))
276         if cfg.LOCAL.log_dir == "unknown":
277             cfg.LOCAL.log_dir = os.path.abspath(
278                                         os.path.join(cfg.VARS.salometoolsway,
279                                                      "..",
280                                                      "LOGS"))
281
282         # apply overwrite from command line if needed
283         for rule in self.get_command_line_overrides(options, ["LOCAL"]):
284             exec('cfg.' + rule) # this cannot be factorized because of the exec
285         
286         # =====================================================================
287         # Load the PROJECTS
288         projects_cfg = src.pyconf.Config()
289         projects_cfg.addMapping("PROJECTS",
290                                 src.pyconf.Mapping(projects_cfg),
291                                 "The projects\n")
292         projects_cfg.PROJECTS.addMapping("projects",
293                                 src.pyconf.Mapping(cfg.PROJECTS),
294                                 "The projects definition\n")
295         
296         for project_pyconf_path in cfg.PROJECTS.project_file_paths:
297             if not os.path.exists(project_pyconf_path):
298                 msg = _("WARNING: The project file %s cannot be found. "
299                         "It will be ignored\n" % project_pyconf_path)
300                 sys.stdout.write(msg)
301                 continue
302             project_name = os.path.basename(
303                                     project_pyconf_path)[:-len(".pyconf")]
304             try:
305                 project_pyconf_dir = os.path.dirname(project_pyconf_path)
306                 project_cfg = src.pyconf.Config(open(project_pyconf_path),
307                                                 PWD=("", project_pyconf_dir))
308             except Exception as e:
309                 msg = _("ERROR: Error in configuration file: "
310                                  "%(file_path)s\n  %(error)s\n") % \
311                             {'file_path' : project_pyconf_path, 'error': str(e) }
312                 sys.stdout.write(msg)
313                 continue
314             projects_cfg.PROJECTS.projects.addMapping(project_name,
315                              src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
316                              "The %s project\n" % project_name)
317             projects_cfg.PROJECTS.projects[project_name]=project_cfg
318             projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
319                                                         project_pyconf_path
320                    
321         merger.merge(cfg, projects_cfg)
322
323         # apply overwrite from command line if needed
324         for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
325             exec('cfg.' + rule) # this cannot be factorized because of the exec
326         
327         # =====================================================================
328         # Create the paths where to search the application configurations, 
329         # the product configurations, the products archives, 
330         # the jobs configurations and the machines configurations
331         cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
332         cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
333         cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
334         
335         cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
336         cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
337         cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
338         cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
339         cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
340         cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
341         cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
342         cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
343         # Loop over the projects in order to complete the PATHS variables
344         for project in cfg.PROJECTS.projects:
345             for PATH in ["APPLICATIONPATH",
346                          "PRODUCTPATH",
347                          "ARCHIVEPATH",
348                          "JOBPATH",
349                          "MACHINEPATH"]:
350                 if PATH not in cfg.PROJECTS.projects[project]:
351                     continue
352                 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
353         
354         # apply overwrite from command line if needed
355         for rule in self.get_command_line_overrides(options, ["PATHS"]):
356             exec('cfg.' + rule) # this cannot be factorized because of the exec
357
358         # =====================================================================
359         # Load APPLICATION config file
360         if application is not None:
361             # search APPLICATION file in all directories in configPath
362             cp = cfg.PATHS.APPLICATIONPATH
363             src.pyconf.streamOpener = ConfigOpener(cp)
364             do_merge = True
365             try:
366                 application_cfg = src.pyconf.Config(application + '.pyconf')
367             except IOError as e:
368                 raise src.SatException(_("%s, use 'config --list' to get the"
369                                          " list of available applications.") %e)
370             except src.pyconf.ConfigError as e:
371                 if (not ('-e' in parser.parse_args()[1]) 
372                                          or ('--edit' in parser.parse_args()[1]) 
373                                          and command == 'config'):
374                     raise src.SatException(_("Error in configuration file: "
375                                              "%(application)s.pyconf\n "
376                                              " %(error)s") % \
377                         { 'application': application, 'error': str(e) } )
378                 else:
379                     sys.stdout.write(src.printcolors.printcWarning(
380                                         "There is an error in the file"
381                                         " %s.pyconf.\n" % cfg.VARS.application))
382                     do_merge = False
383             except Exception as e:
384                 if (not ('-e' in parser.parse_args()[1]) 
385                                         or ('--edit' in parser.parse_args()[1]) 
386                                         and command == 'config'):
387                     sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
388                     raise src.SatException(_("Error in configuration file:"
389                                              " %(application)s.pyconf\n") % \
390                         { 'application': application} )
391                 else:
392                     sys.stdout.write(src.printcolors.printcWarning(
393                                 "There is an error in the file"
394                                 " %s.pyconf. Opening the file with the"
395                                 " default viewer\n" % cfg.VARS.application))
396                     sys.stdout.write("The error:"
397                                  " %s\n" % src.printcolors.printcWarning(
398                                                                       str(e)))
399                     do_merge = False
400         
401             else:
402                 cfg['open_application'] = 'yes'
403
404         # =====================================================================
405         # Load product config files in PRODUCTS section
406         products_cfg = src.pyconf.Config()
407         products_cfg.addMapping("PRODUCTS",
408                                 src.pyconf.Mapping(products_cfg),
409                                 "The products\n")
410         if application is not None:
411             src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
412             for product_name in application_cfg.APPLICATION.products.keys():
413                 # Loop on all files that are in softsDir directory
414                 # and read their config
415                 product_file_name = product_name + ".pyconf"
416                 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
417                 if product_file_path:
418                     products_dir = os.path.dirname(product_file_path)
419                     try:
420                         prod_cfg = src.pyconf.Config(open(product_file_path),
421                                                      PWD=("", products_dir))
422                         prod_cfg.from_file = product_file_path
423                         products_cfg.PRODUCTS[product_name] = prod_cfg
424                     except Exception as e:
425                         msg = _(
426                             "WARNING: Error in configuration file"
427                             ": %(prod)s\n  %(error)s" % \
428                             {'prod' :  product_name, 'error': str(e) })
429                         sys.stdout.write(msg)
430             
431             merger.merge(cfg, products_cfg)
432             
433             # apply overwrite from command line if needed
434             for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
435                 exec('cfg.' + rule) # this cannot be factorized because of the exec
436             
437             if do_merge:
438                 merger.merge(cfg, application_cfg)
439
440                 # default launcher name ('salome')
441                 if ('profile' in cfg.APPLICATION and 
442                     'launcher_name' not in cfg.APPLICATION.profile):
443                     cfg.APPLICATION.profile.launcher_name = 'salome'
444
445                 # apply overwrite from command line if needed
446                 for rule in self.get_command_line_overrides(options,
447                                                              ["APPLICATION"]):
448                     # this cannot be factorized because of the exec
449                     exec('cfg.' + rule)
450             
451         # =====================================================================
452         # load USER config
453         self.set_user_config_file(cfg)
454         user_cfg_file = self.get_user_config_file()
455         user_cfg = src.pyconf.Config(open(user_cfg_file))
456         merger.merge(cfg, user_cfg)
457
458         # apply overwrite from command line if needed
459         for rule in self.get_command_line_overrides(options, ["USER"]):
460             exec('cfg.' + rule) # this cannot be factorize because of the exec
461         
462         return cfg
463
464     def set_user_config_file(self, config):
465         '''Set the user config file name and path.
466         If necessary, build it from another one or create it from scratch.
467         
468         :param config class 'src.pyconf.Config': The global config 
469                                                  (containing all pyconf).
470         '''
471         # get the expected name and path of the file
472         self.config_file_name = 'SAT.pyconf'
473         self.user_config_file_path = os.path.join(config.VARS.personalDir,
474                                                    self.config_file_name)
475         
476         # if pyconf does not exist, create it from scratch
477         if not os.path.isfile(self.user_config_file_path): 
478             self.create_config_file(config)
479     
480     def create_config_file(self, config):
481         '''This method is called when there are no user config file. 
482            It build it from scratch.
483         
484         :param config class 'src.pyconf.Config': The global config.
485         :return: the config corresponding to the file created.
486         :rtype: config class 'src.pyconf.Config'
487         '''
488         
489         cfg_name = self.get_user_config_file()
490
491         user_cfg = src.pyconf.Config()
492         #
493         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
494
495         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
496             "This is the user name used to access salome cvs base.\n")
497         user_cfg.USER.addMapping('svn_user', config.VARS.user,
498             "This is the user name used to access salome svn base.\n")
499         user_cfg.USER.addMapping('output_verbose_level', 3,
500             "This is the default output_verbose_level you want."
501             " 0=>no output, 5=>debug.\n")
502         user_cfg.USER.addMapping('publish_dir', 
503                                  os.path.join(os.path.expanduser('~'),
504                                  'websupport', 
505                                  'satreport'), 
506                                  "")
507         user_cfg.USER.addMapping('editor',
508                                  'vi', 
509                                  "This is the editor used to "
510                                  "modify configuration files\n")
511         user_cfg.USER.addMapping('browser', 
512                                  'firefox', 
513                                  "This is the browser used to "
514                                  "read html documentation\n")
515         user_cfg.USER.addMapping('pdf_viewer', 
516                                  'evince', 
517                                  "This is the pdf_viewer used "
518                                  "to read pdf documentation\n")
519         user_cfg.USER.addMapping("base",
520                                  src.pyconf.Reference(
521                                             user_cfg,
522                                             src.pyconf.DOLLAR,
523                                             'workdir  + $VARS.sep + "BASE"'),
524                                  "The products installation base (could be "
525                                  "ignored if this key exists in the local.pyconf"
526                                  " file of salomTools).\n")
527                
528         # 
529         src.ensure_path_exists(config.VARS.personalDir)
530         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
531                                             'Applications'))
532
533         f = open(cfg_name, 'w')
534         user_cfg.__save__(f)
535         f.close()
536
537         return user_cfg   
538
539     def get_user_config_file(self):
540         '''Get the user config file
541         :return: path to the user config file.
542         :rtype: str
543         '''
544         if not self.user_config_file_path:
545             raise src.SatException(_("Error in get_user_config_file: "
546                                      "missing user config file path"))
547         return self.user_config_file_path     
548
549 def check_path(path, ext=[]):
550     '''Construct a text with the input path and "not found" if it does not
551        exist.
552     
553     :param path Str: the path to check.
554     :param ext List: An extension. Verify that the path extension 
555                      is in the list
556     :return: The string of the path with information
557     :rtype: Str
558     '''
559     # check if file exists
560     if not os.path.exists(path):
561         return "'%s'" % path + " " + src.printcolors.printcError(_(
562                                                             "** not found"))
563
564     # check extension
565     if len(ext) > 0:
566         fe = os.path.splitext(path)[1].lower()
567         if fe not in ext:
568             return "'%s'" % path + " " + src.printcolors.printcError(_(
569                                                         "** bad extension"))
570
571     return path
572
573 def show_product_info(config, name, logger):
574     '''Display on the terminal and logger information about a product.
575     
576     :param config Config: the global configuration.
577     :param name Str: The name of the product
578     :param logger Logger: The logger instance to use for the display
579     '''
580     
581     logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
582     pinfo = src.product.get_product_config(config, name)
583     
584     if "depend" in pinfo:
585         src.printcolors.print_value(logger, 
586                                     "depends on", 
587                                     ', '.join(pinfo.depend), 2)
588
589     if "opt_depend" in pinfo:
590         src.printcolors.print_value(logger, 
591                                     "optional", 
592                                     ', '.join(pinfo.opt_depend), 2)
593
594     # information on pyconf
595     logger.write("\n", 2)
596     logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
597     if "from_file" in pinfo:
598         src.printcolors.print_value(logger, 
599                                     "pyconf file path", 
600                                     pinfo.from_file, 
601                                     2)
602     if "section" in pinfo:
603         src.printcolors.print_value(logger, 
604                                     "section", 
605                                     pinfo.section, 
606                                     2)
607
608     # information on prepare
609     logger.write("\n", 2)
610     logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
611
612     is_dev = src.product.product_is_dev(pinfo)
613     method = pinfo.get_source
614     if is_dev:
615         method += " (dev)"
616     src.printcolors.print_value(logger, "get method", method, 2)
617
618     if method == 'cvs':
619         src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
620         src.printcolors.print_value(logger, "base module",
621                                     pinfo.cvs_info.module_base, 2)
622         src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
623         src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
624
625     elif method == 'svn':
626         src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
627
628     elif method == 'git':
629         src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
630         src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
631
632     elif method == 'archive':
633         src.printcolors.print_value(logger, 
634                                     "get from", 
635                                     check_path(pinfo.archive_info.archive_name), 
636                                     2)
637
638     if 'patches' in pinfo:
639         for patch in pinfo.patches:
640             src.printcolors.print_value(logger, "patch", check_path(patch), 2)
641
642     if src.product.product_is_fixed(pinfo):
643         src.printcolors.print_value(logger, "install_dir", 
644                                     check_path(pinfo.install_dir), 2)
645
646     if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
647         return
648     
649     # information on compilation
650     if src.product.product_compiles(pinfo):
651         logger.write("\n", 2)
652         logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
653         src.printcolors.print_value(logger, 
654                                     "compilation method", 
655                                     pinfo.build_source, 
656                                     2)
657         
658         if pinfo.build_source == "script" and "compil_script" in pinfo:
659             src.printcolors.print_value(logger, 
660                                         "Compilation script", 
661                                         pinfo.compil_script, 
662                                         2)
663         
664         if 'nb_proc' in pinfo:
665             src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
666     
667         src.printcolors.print_value(logger, 
668                                     "source dir", 
669                                     check_path(pinfo.source_dir), 
670                                     2)
671         if 'install_dir' in pinfo:
672             src.printcolors.print_value(logger, 
673                                         "build dir", 
674                                         check_path(pinfo.build_dir), 
675                                         2)
676             src.printcolors.print_value(logger, 
677                                         "install dir", 
678                                         check_path(pinfo.install_dir), 
679                                         2)
680         else:
681             logger.write("  " + 
682                          src.printcolors.printcWarning(_("no install dir")) + 
683                          "\n", 2)
684     else:
685         logger.write("\n", 2)
686         msg = _("This product does not compile")
687         logger.write("%s\n" % msg, 2)
688
689     # information on environment
690     logger.write("\n", 2)
691     logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
692     if "environ" in pinfo and "env_script" in pinfo.environ:
693         src.printcolors.print_value(logger, 
694                                     "script", 
695                                     check_path(pinfo.environ.env_script), 
696                                     2)
697
698     zz = src.environment.SalomeEnviron(config, 
699                                        src.fileEnviron.ScreenEnviron(logger), 
700                                        False)
701     zz.set_python_libdirs()
702     zz.set_a_product(name, logger)
703         
704 def show_patchs(config, logger):
705     '''Prints all the used patchs in the application.
706     
707     :param config Config: the global configuration.
708     :param logger Logger: The logger instance to use for the display
709     '''
710     len_max = max([len(p) for p in config.APPLICATION.products]) + 2
711     for product in config.APPLICATION.products:
712         product_info = src.product.get_product_config(config, product)
713         if src.product.product_has_patches(product_info):
714             logger.write("%s: " % product, 1)
715             logger.write(src.printcolors.printcInfo(
716                                             " " * (len_max - len(product) -2) +
717                                             "%s\n" % product_info.patches[0]),
718                          1)
719             if len(product_info.patches) > 1:
720                 for patch in product_info.patches[1:]:
721                     logger.write(src.printcolors.printcInfo(len_max*" " +
722                                                             "%s\n" % patch), 1)
723             logger.write("\n", 1)
724
725 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
726     '''Prints a value from the configuration. Prints recursively the values 
727        under the initial path.
728     
729     :param config class 'src.pyconf.Config': The configuration 
730                                              from which the value is displayed.
731     :param path str : the path in the configuration of the value to print.
732     :param show_label boolean: if True, do a basic display. 
733                                (useful for bash completion)
734     :param logger Logger: the logger instance
735     :param level int: The number of spaces to add before display.
736     :param show_full_path :
737     '''            
738     
739     # Make sure that the path does not ends with a point
740     if path.endswith('.'):
741         path = path[:-1]
742     
743     # display all the path or not
744     if show_full_path:
745         vname = path
746     else:
747         vname = path.split('.')[-1]
748
749     # number of spaces before the display
750     tab_level = "  " * level
751     
752     # call to the function that gets the value of the path.
753     try:
754         val = config.getByPath(path)
755     except Exception as e:
756         logger.write(tab_level)
757         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
758                                          src.printcolors.printcError(str(e))))
759         return
760
761     # in this case, display only the value
762     if show_label:
763         logger.write(tab_level)
764         logger.write("%s: " % src.printcolors.printcLabel(vname))
765
766     # The case where the value has under values, 
767     # do a recursive call to the function
768     if dir(val).__contains__('keys'):
769         if show_label: logger.write("\n")
770         for v in sorted(val.keys()):
771             print_value(config, path + '.' + v, show_label, logger, level + 1)
772     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
773         # in this case, value is a list (or a Sequence)
774         if show_label: logger.write("\n")
775         index = 0
776         for v in val:
777             print_value(config, path + "[" + str(index) + "]", 
778                         show_label, logger, level + 1)
779             index = index + 1
780     else: # case where val is just a str
781         logger.write("%s\n" % val)
782
783 def get_config_children(config, args):
784     '''Gets the names of the children of the given parameter.
785        Useful only for completion mechanism
786     
787     :param config Config: The configuration where to read the values
788     :param args: The path in the config from which get the keys
789     '''
790     vals = []
791     rootkeys = config.keys()
792     
793     if len(args) == 0:
794         # no parameter returns list of root keys
795         vals = rootkeys
796     else:
797         parent = args[0]
798         pos = parent.rfind('.')
799         if pos < 0:
800             # Case where there is only on key as parameter.
801             # For example VARS
802             vals = [m for m in rootkeys if m.startswith(parent)]
803         else:
804             # Case where there is a part from a key
805             # for example VARS.us  (for VARS.user)
806             head = parent[0:pos]
807             tail = parent[pos+1:]
808             try:
809                 a = config.getByPath(head)
810                 if dir(a).__contains__('keys'):
811                     vals = map(lambda x: head + '.' + x,
812                                [m for m in a.keys() if m.startswith(tail)])
813             except:
814                 pass
815
816     for v in sorted(vals):
817         sys.stdout.write("%s\n" % v)
818
819 def description():
820     '''method that is called when salomeTools is called with --help option.
821     
822     :return: The text to display for the config command description.
823     :rtype: str
824     '''
825     return _("The config command allows manipulation "
826              "and operation on config files.\n\nexample:\nsat config "
827              "SALOME-master --info ParaView")
828     
829
830 def run(args, runner, logger):
831     '''method that is called when salomeTools is called with config parameter.
832     '''
833     # Parse the options
834     (options, args) = parser.parse_args(args)
835
836     # Only useful for completion mechanism : print the keys of the config
837     if options.schema:
838         get_config_children(runner.cfg, args)
839         return
840     
841     # case : print a value of the config
842     if options.value:
843         if options.value == ".":
844             # if argument is ".", print all the config
845             for val in sorted(runner.cfg.keys()):
846                 print_value(runner.cfg, val, not options.no_label, logger)
847         else:
848             print_value(runner.cfg, options.value, not options.no_label, logger, 
849                         level=0, show_full_path=False)
850     
851     # case : edit user pyconf file or application file
852     elif options.edit:
853         editor = runner.cfg.USER.editor
854         if ('APPLICATION' not in runner.cfg and
855                        'open_application' not in runner.cfg): # edit user pyconf
856             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
857                                    'SAT.pyconf')
858             logger.write(_("Openning %s\n" % usercfg), 3)
859             src.system.show_in_editor(editor, usercfg, logger)
860         else:
861             # search for file <application>.pyconf and open it
862             for path in runner.cfg.PATHS.APPLICATIONPATH:
863                 pyconf_path = os.path.join(path, 
864                                     runner.cfg.VARS.application + ".pyconf")
865                 if os.path.exists(pyconf_path):
866                     logger.write(_("Openning %s\n" % pyconf_path), 3)
867                     src.system.show_in_editor(editor, pyconf_path, logger)
868                     break
869     
870     # case : give information about the product in parameter
871     elif options.info:
872         src.check_config_has_application(runner.cfg)
873         if options.info in runner.cfg.APPLICATION.products:
874             show_product_info(runner.cfg, options.info, logger)
875             return
876         raise src.SatException(_("%(product_name)s is not a product "
877                                  "of %(application_name)s.") % 
878                                {'product_name' : options.info,
879                                 'application_name' : 
880                                 runner.cfg.VARS.application})
881     
882     # case : copy an existing <application>.pyconf 
883     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
884     elif options.copy:
885         # product is required
886         src.check_config_has_application( runner.cfg )
887
888         # get application file path 
889         source = runner.cfg.VARS.application + '.pyconf'
890         source_full_path = ""
891         for path in runner.cfg.PATHS.APPLICATIONPATH:
892             # ignore personal directory
893             if path == runner.cfg.VARS.personalDir:
894                 continue
895             # loop on all directories that can have pyconf applications
896             zz = os.path.join(path, source)
897             if os.path.exists(zz):
898                 source_full_path = zz
899                 break
900
901         if len(source_full_path) == 0:
902             raise src.SatException(_(
903                         "Config file for product %s not found\n") % source)
904         else:
905             if len(args) > 0:
906                 # a name is given as parameter, use it
907                 dest = args[0]
908             elif 'copy_prefix' in runner.cfg.INTERNAL.config:
909                 # use prefix
910                 dest = (runner.cfg.INTERNAL.config.copy_prefix 
911                         + runner.cfg.VARS.application)
912             else:
913                 # use same name as source
914                 dest = runner.cfg.VARS.application
915                 
916             # the full path
917             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
918                                      'Applications', dest + '.pyconf')
919             if os.path.exists(dest_file):
920                 raise src.SatException(_("A personal application"
921                                          " '%s' already exists") % dest)
922             
923             # perform the copy
924             shutil.copyfile(source_full_path, dest_file)
925             logger.write(_("%s has been created.\n") % dest_file)
926     
927     # case : display all the available pyconf applications
928     elif options.list:
929         lproduct = list()
930         # search in all directories that can have pyconf applications
931         for path in runner.cfg.PATHS.APPLICATIONPATH:
932             # print a header
933             if not options.no_label:
934                 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
935
936             if not os.path.exists(path):
937                 logger.write(src.printcolors.printcError(_(
938                                             "Directory not found")) + "\n")
939             else:
940                 for f in sorted(os.listdir(path)):
941                     # ignore file that does not ends with .pyconf
942                     if not f.endswith('.pyconf'):
943                         continue
944
945                     appliname = f[:-len('.pyconf')]
946                     if appliname not in lproduct:
947                         lproduct.append(appliname)
948                         if path.startswith(runner.cfg.VARS.personalDir) \
949                                     and not options.no_label:
950                             logger.write("%s*\n" % appliname)
951                         else:
952                             logger.write("%s\n" % appliname)
953                             
954             logger.write("\n")
955     # case : give a synthetic view of all patches used in the application
956     elif options.show_patchs:
957         src.check_config_has_application(runner.cfg)
958         # Print some informations
959         logger.write(_('Show the patchs of application %s\n') % 
960                     src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
961         logger.write("\n", 2, False)
962         show_patchs(runner.cfg, logger)
963     
964     # case: print all the products name of the application (internal use for completion)
965     elif options.completion:
966         for product_name in runner.cfg.APPLICATION.products.keys():
967             logger.write("%s\n" % product_name)
968         
969