]> SALOME platform Git repositories - tools/sat.git/blob - commands/config.py
Salome HOME
Add the profile command
[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(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             do_merge = True
391             try:
392                 application_cfg = src.pyconf.Config(application + '.pyconf')
393             except IOError as e:
394                 raise src.SatException(_("%s, use 'config --list' to get the"
395                                          " list of available applications.") %e)
396             except src.pyconf.ConfigError as e:
397                 if (not ('-e' in parser.parse_args()[1]) 
398                                          or ('--edit' in parser.parse_args()[1]) 
399                                          and command == 'config'):
400                     raise src.SatException(_("Error in configuration file: "
401                                              "%(application)s.pyconf\n "
402                                              " %(error)s") % \
403                         { 'application': application, 'error': str(e) } )
404                 else:
405                     sys.stdout.write(src.printcolors.printcWarning(
406                                         "There is an error in the file"
407                                         " %s.pyconf.\n" % cfg.VARS.application))
408                     do_merge = False
409             except:
410                 if (not ('-e' in parser.parse_args()[1]) 
411                                         or ('--edit' in parser.parse_args()[1]) 
412                                         and command == 'config'):
413                     raise src.SatException(_("Error in configuration file:"
414                                              " %(application)s.pyconf\n") % \
415                         { 'application': application} )
416                 else:
417                     sys.stdout.write(src.printcolors.printcWarning(
418                                     "There is an error in the file"
419                                     " %s.pyconf. Opening the file with the"
420                                     " default viewer\n" % cfg.VARS.application))
421                     do_merge = False
422
423             if do_merge:
424                 merger.merge(cfg, application_cfg)
425             
426                 # apply overwrite from command line if needed
427                 for rule in self.get_command_line_overrides(options,
428                                                              ["APPLICATION"]):
429                     # this cannot be factorized because of the exec
430                     exec('cfg.' + rule)
431                     
432                 # default launcher name ('salome')
433                 if ('profile' in cfg.APPLICATION and 
434                     'launcher_name' not in cfg.APPLICATION.profile):
435                     cfg.APPLICATION.profile.launcher_name = 'salome'
436         
437             else:
438                 cfg['open_application'] = 'yes'
439                 
440             
441         # =====================================================================
442         # load USER config
443         self.set_user_config_file(cfg)
444         user_cfg_file = self.get_user_config_file()
445         user_cfg = src.pyconf.Config(open(user_cfg_file))
446         merger.merge(cfg, user_cfg)
447
448         # apply overwrite from command line if needed
449         for rule in self.get_command_line_overrides(options, ["USER"]):
450             exec('cfg.' + rule) # this cannot be factorize because of the exec
451         
452         return cfg
453
454     def set_user_config_file(self, config):
455         '''Set the user config file name and path.
456         If necessary, build it from another one or create it from scratch.
457         
458         :param config class 'src.pyconf.Config': The global config 
459                                                  (containing all pyconf).
460         '''
461         # get the expected name and path of the file
462         self.config_file_name = 'salomeTools.pyconf'
463         self.user_config_file_path = os.path.join(config.VARS.personalDir,
464                                                    self.config_file_name)
465         
466         # if pyconf does not exist, create it from scratch
467         if not os.path.isfile(self.user_config_file_path): 
468             self.create_config_file(config)
469     
470     def create_config_file(self, config):
471         '''This method is called when there are no user config file. 
472            It build it from scratch.
473         
474         :param config class 'src.pyconf.Config': The global config.
475         :return: the config corresponding to the file created.
476         :rtype: config class 'src.pyconf.Config'
477         '''
478         
479         cfg_name = self.get_user_config_file()
480
481         user_cfg = src.pyconf.Config()
482         #
483         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
484
485         #
486         user_cfg.USER.addMapping('workdir', os.path.expanduser('~'),
487             "This is where salomeTools will work. "
488             "You may (and probably do) change it.\n")
489         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
490             "This is the user name used to access salome cvs base.\n")
491         user_cfg.USER.addMapping('svn_user', config.VARS.user,
492             "This is the user name used to access salome svn base.\n")
493         user_cfg.USER.addMapping('output_verbose_level', 3,
494             "This is the default output_verbose_level you want."
495             " 0=>no output, 5=>debug.\n")
496         user_cfg.USER.addMapping('publish_dir', 
497                                  os.path.join(os.path.expanduser('~'),
498                                  'websupport', 
499                                  'satreport'), 
500                                  "")
501         user_cfg.USER.addMapping('editor',
502                                  'vi', 
503                                  "This is the editor used to "
504                                  "modify configuration files\n")
505         user_cfg.USER.addMapping('browser', 
506                                  'firefox', 
507                                  "This is the browser used to "
508                                  "read html documentation\n")
509         user_cfg.USER.addMapping('pdf_viewer', 
510                                  'evince', 
511                                  "This is the pdf_viewer used "
512                                  "to read pdf documentation\n")
513         user_cfg.USER.addMapping("base",
514                                  src.pyconf.Reference(
515                                             user_cfg,
516                                             src.pyconf.DOLLAR,
517                                             'workdir  + $VARS.sep + "BASE"'),
518                                  "The products installation base (could be "
519                                  "ignored if this key exists in the site.pyconf"
520                                  " file of salomTools).\n")
521         
522         user_cfg.USER.addMapping("log_dir",
523                                  src.pyconf.Reference(
524                                             user_cfg,
525                                             src.pyconf.DOLLAR,
526                                             'workdir  + $VARS.sep + "LOGS"'),
527                                  "The log repository\n")
528         
529         # 
530         src.ensure_path_exists(config.VARS.personalDir)
531         src.ensure_path_exists(os.path.join(config.VARS.personalDir, 
532                                             'Applications'))
533
534         f = open(cfg_name, 'w')
535         user_cfg.__save__(f)
536         f.close()
537
538         return user_cfg   
539
540     def get_user_config_file(self):
541         '''Get the user config file
542         :return: path to the user config file.
543         :rtype: str
544         '''
545         if not self.user_config_file_path:
546             raise src.SatException(_("Error in get_user_config_file: "
547                                      "missing user config file path"))
548         return self.user_config_file_path     
549
550 def check_path(path, ext=[]):
551     '''Construct a text with the input path and "not found" if it does not
552        exist.
553     
554     :param path Str: the path to check.
555     :param ext List: An extension. Verify that the path extension 
556                      is in the list
557     :return: The string of the path with information
558     :rtype: Str
559     '''
560     # check if file exists
561     if not os.path.exists(path):
562         return "'%s'" % path + " " + src.printcolors.printcError(_(
563                                                             "** not found"))
564
565     # check extension
566     if len(ext) > 0:
567         fe = os.path.splitext(path)[1].lower()
568         if fe not in ext:
569             return "'%s'" % path + " " + src.printcolors.printcError(_(
570                                                         "** bad extension"))
571
572     return path
573
574 def show_product_info(config, name, logger):
575     '''Display on the terminal and logger information about a product.
576     
577     :param config Config: the global configuration.
578     :param name Str: The name of the product
579     :param logger Logger: The logger instance to use for the display
580     '''
581     
582     logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
583     pinfo = src.product.get_product_config(config, name)
584     
585     # Type of the product
586     ptype = src.get_cfg_param(pinfo, "type", "")
587     src.printcolors.print_value(logger, "type", ptype, 2)
588     if "depend" in pinfo:
589         src.printcolors.print_value(logger, 
590                                     "depends on", 
591                                     ', '.join(pinfo.depend), 2)
592
593     if "opt_depend" in pinfo:
594         src.printcolors.print_value(logger, 
595                                     "optional", 
596                                     ', '.join(pinfo.opt_depend), 2)
597
598     # information on prepare
599     logger.write("\n", 2)
600     logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
601
602     is_dev = src.product.product_is_dev(pinfo)
603     method = pinfo.get_source
604     if is_dev:
605         method += " (dev)"
606     src.printcolors.print_value(logger, "get method", method, 2)
607
608     if method == 'cvs':
609         src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
610         src.printcolors.print_value(logger, "base module",
611                                     pinfo.cvs_info.module_base, 2)
612         src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
613         src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
614
615     elif method == 'svn':
616         src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
617
618     elif method == 'git':
619         src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
620         src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
621
622     elif method == 'archive':
623         src.printcolors.print_value(logger, 
624                                     "get from", 
625                                     check_path(pinfo.archive_info.archive_name), 
626                                     2)
627
628     if 'patches' in pinfo:
629         for patch in pinfo.patches:
630             src.printcolors.print_value(logger, "patch", check_path(patch), 2)
631
632     if src.product.product_is_fixed(pinfo):
633         src.printcolors.print_value(logger, "install_dir", 
634                                     check_path(pinfo.install_dir), 2)
635
636     if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
637         return
638     
639     # information on compilation
640     if src.product.product_compiles(pinfo):
641         logger.write("\n", 2)
642         logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
643         src.printcolors.print_value(logger, 
644                                     "compilation method", 
645                                     pinfo.build_source, 
646                                     2)
647         
648         if pinfo.build_source == "script" and "compil_script" in pinfo:
649             src.printcolors.print_value(logger, 
650                                         "Compilation script", 
651                                         pinfo.compil_script, 
652                                         2)
653         
654         if 'nb_proc' in pinfo:
655             src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
656     
657         src.printcolors.print_value(logger, 
658                                     "source dir", 
659                                     check_path(pinfo.source_dir), 
660                                     2)
661         if 'install_dir' in pinfo:
662             src.printcolors.print_value(logger, 
663                                         "build dir", 
664                                         check_path(pinfo.build_dir), 
665                                         2)
666             src.printcolors.print_value(logger, 
667                                         "install dir", 
668                                         check_path(pinfo.install_dir), 
669                                         2)
670         else:
671             logger.write("  " + 
672                          src.printcolors.printcWarning(_("no install dir")) + 
673                          "\n", 2)
674     else:
675         logger.write("\n", 2)
676         msg = _("This product does not compile")
677         logger.write("%s\n" % msg, 2)
678
679     # information on environment
680     logger.write("\n", 2)
681     logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
682     if "environ" in pinfo and "env_script" in pinfo.environ:
683         src.printcolors.print_value(logger, 
684                                     "script", 
685                                     check_path(pinfo.environ.env_script), 
686                                     2)
687
688     zz = src.environment.SalomeEnviron(config, 
689                                        src.fileEnviron.ScreenEnviron(logger), 
690                                        False)
691     zz.set_python_libdirs()
692     zz.set_a_product(name, logger)
693         
694 def show_patchs(config, logger):
695     '''Prints all the used patchs in the application.
696     
697     :param config Config: the global configuration.
698     :param logger Logger: The logger instance to use for the display
699     '''
700     len_max = max([len(p) for p in config.APPLICATION.products]) + 2
701     for product in config.APPLICATION.products:
702         product_info = src.product.get_product_config(config, product)
703         if src.product.product_has_patches(product_info):
704             logger.write("%s: " % product, 1)
705             logger.write(src.printcolors.printcInfo(
706                                             " " * (len_max - len(product) -2) +
707                                             "%s\n" % product_info.patches[0]),
708                          1)
709             if len(product_info.patches) > 1:
710                 for patch in product_info.patches[1:]:
711                     logger.write(src.printcolors.printcInfo(len_max*" " +
712                                                             "%s\n" % patch), 1)
713             logger.write("\n", 1)
714
715 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
716     '''Prints a value from the configuration. Prints recursively the values 
717        under the initial path.
718     
719     :param config class 'src.pyconf.Config': The configuration 
720                                              from which the value is displayed.
721     :param path str : the path in the configuration of the value to print.
722     :param show_label boolean: if True, do a basic display. 
723                                (useful for bash completion)
724     :param logger Logger: the logger instance
725     :param level int: The number of spaces to add before display.
726     :param show_full_path :
727     '''            
728     
729     # Make sure that the path does not ends with a point
730     if path.endswith('.'):
731         path = path[:-1]
732     
733     # display all the path or not
734     if show_full_path:
735         vname = path
736     else:
737         vname = path.split('.')[-1]
738
739     # number of spaces before the display
740     tab_level = "  " * level
741     
742     # call to the function that gets the value of the path.
743     try:
744         val = config.getByPath(path)
745     except Exception as e:
746         logger.write(tab_level)
747         logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname), 
748                                          src.printcolors.printcError(str(e))))
749         return
750
751     # in this case, display only the value
752     if show_label:
753         logger.write(tab_level)
754         logger.write("%s: " % src.printcolors.printcLabel(vname))
755
756     # The case where the value has under values, 
757     # do a recursive call to the function
758     if dir(val).__contains__('keys'):
759         if show_label: logger.write("\n")
760         for v in sorted(val.keys()):
761             print_value(config, path + '.' + v, show_label, logger, level + 1)
762     elif val.__class__ == src.pyconf.Sequence or isinstance(val, list): 
763         # in this case, value is a list (or a Sequence)
764         if show_label: logger.write("\n")
765         index = 0
766         for v in val:
767             print_value(config, path + "[" + str(index) + "]", 
768                         show_label, logger, level + 1)
769             index = index + 1
770     else: # case where val is just a str
771         logger.write("%s\n" % val)
772
773 def get_config_children(config, args):
774     '''Gets the names of the children of the given parameter.
775        Useful only for completion mechanism
776     
777     :param config Config: The configuration where to read the values
778     :param args: The path in the config from which get the keys
779     '''
780     vals = []
781     rootkeys = config.keys()
782     
783     if len(args) == 0:
784         # no parameter returns list of root keys
785         vals = rootkeys
786     else:
787         parent = args[0]
788         pos = parent.rfind('.')
789         if pos < 0:
790             # Case where there is only on key as parameter.
791             # For example VARS
792             vals = [m for m in rootkeys if m.startswith(parent)]
793         else:
794             # Case where there is a part from a key
795             # for example VARS.us  (for VARS.user)
796             head = parent[0:pos]
797             tail = parent[pos+1:]
798             try:
799                 a = config.getByPath(head)
800                 if dir(a).__contains__('keys'):
801                     vals = map(lambda x: head + '.' + x,
802                                [m for m in a.keys() if m.startswith(tail)])
803             except:
804                 pass
805
806     for v in sorted(vals):
807         sys.stdout.write("%s\n" % v)
808
809 def description():
810     '''method that is called when salomeTools is called with --help option.
811     
812     :return: The text to display for the config command description.
813     :rtype: str
814     '''
815     return _("The config command allows manipulation "
816              "and operation on config files.\n\nexample:\nsat config "
817              "SALOME-master --info ParaView")
818     
819
820 def run(args, runner, logger):
821     '''method that is called when salomeTools is called with config parameter.
822     '''
823     # Parse the options
824     (options, args) = parser.parse_args(args)
825
826     # Only useful for completion mechanism : print the keys of the config
827     if options.schema:
828         get_config_children(runner.cfg, args)
829         return
830     
831     # case : print a value of the config
832     if options.value:
833         if options.value == ".":
834             # if argument is ".", print all the config
835             for val in sorted(runner.cfg.keys()):
836                 print_value(runner.cfg, val, not options.no_label, logger)
837         else:
838             print_value(runner.cfg, options.value, not options.no_label, logger, 
839                         level=0, show_full_path=False)
840     
841     # case : edit user pyconf file or application file
842     elif options.edit:
843         editor = runner.cfg.USER.editor
844         if ('APPLICATION' not in runner.cfg and
845                        'open_application' not in runner.cfg): # edit user pyconf
846             usercfg = os.path.join(runner.cfg.VARS.personalDir, 
847                                    'salomeTools.pyconf')
848             logger.write(_("Openning %s\n" % usercfg), 3)
849             src.system.show_in_editor(editor, usercfg, logger)
850         else:
851             # search for file <application>.pyconf and open it
852             for path in runner.cfg.PATHS.APPLICATIONPATH:
853                 pyconf_path = os.path.join(path, 
854                                     runner.cfg.VARS.application + ".pyconf")
855                 if os.path.exists(pyconf_path):
856                     logger.write(_("Openning %s\n" % pyconf_path), 3)
857                     src.system.show_in_editor(editor, pyconf_path, logger)
858                     break
859     
860     # case : give information about the product in parameter
861     elif options.info:
862         src.check_config_has_application(runner.cfg)
863         if options.info in runner.cfg.APPLICATION.products:
864             show_product_info(runner.cfg, options.info, logger)
865             return
866         raise src.SatException(_("%(product_name)s is not a product "
867                                  "of %(application_name)s.") % 
868                                {'product_name' : options.info,
869                                 'application_name' : 
870                                 runner.cfg.VARS.application})
871     
872     # case : copy an existing <application>.pyconf 
873     # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
874     elif options.copy:
875         # product is required
876         src.check_config_has_application( runner.cfg )
877
878         # get application file path 
879         source = runner.cfg.VARS.application + '.pyconf'
880         source_full_path = ""
881         for path in runner.cfg.PATHS.APPLICATIONPATH:
882             # ignore personal directory
883             if path == runner.cfg.VARS.personalDir:
884                 continue
885             # loop on all directories that can have pyconf applications
886             zz = os.path.join(path, source)
887             if os.path.exists(zz):
888                 source_full_path = zz
889                 break
890
891         if len(source_full_path) == 0:
892             raise src.SatException(_(
893                         "Config file for product %s not found\n") % source)
894         else:
895             if len(args) > 0:
896                 # a name is given as parameter, use it
897                 dest = args[0]
898             elif 'copy_prefix' in runner.cfg.INTERNAL.config:
899                 # use prefix
900                 dest = (runner.cfg.INTERNAL.config.copy_prefix 
901                         + runner.cfg.VARS.application)
902             else:
903                 # use same name as source
904                 dest = runner.cfg.VARS.application
905                 
906             # the full path
907             dest_file = os.path.join(runner.cfg.VARS.personalDir, 
908                                      'Applications', dest + '.pyconf')
909             if os.path.exists(dest_file):
910                 raise src.SatException(_("A personal application"
911                                          " '%s' already exists") % dest)
912             
913             # perform the copy
914             shutil.copyfile(source_full_path, dest_file)
915             logger.write(_("%s has been created.\n") % dest_file)
916     
917     # case : display all the available pyconf applications
918     elif options.list:
919         lproduct = list()
920         # search in all directories that can have pyconf applications
921         for path in runner.cfg.PATHS.APPLICATIONPATH:
922             # print a header
923             if not options.no_label:
924                 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
925
926             if not os.path.exists(path):
927                 logger.write(src.printcolors.printcError(_(
928                                             "Directory not found")) + "\n")
929             else:
930                 for f in sorted(os.listdir(path)):
931                     # ignore file that does not ends with .pyconf
932                     if not f.endswith('.pyconf'):
933                         continue
934
935                     appliname = f[:-len('.pyconf')]
936                     if appliname not in lproduct:
937                         lproduct.append(appliname)
938                         if path.startswith(runner.cfg.VARS.personalDir) \
939                                     and not options.no_label:
940                             logger.write("%s*\n" % appliname)
941                         else:
942                             logger.write("%s\n" % appliname)
943                             
944             logger.write("\n")
945     # case : give a synthetic view of all patches used in the application
946     elif options.show_patchs:
947         src.check_config_has_application(runner.cfg)
948         # Print some informations
949         logger.write(_('Show the patchs of application %s\n') % 
950                     src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
951         logger.write("\n", 2, False)
952         show_patchs(runner.cfg, logger)
953         
954