3 # Copyright (C) 2010-2012 CEA/DEN
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.
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.
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
28 # internationalization
29 satdir = os.path.dirname(os.path.realpath(__file__))
30 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
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',
56 '''Class that helps to find an application pyconf
57 in all the possible directories (pathList)
59 def __init__(self, pathList):
62 :param pathList list: The list of paths where to search a pyconf.
64 self.pathList = pathList
66 def __call__(self, name):
67 if os.path.isabs(name):
68 return src.pyconf.ConfigInputStream(open(name, 'rb'))
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)
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.
78 for path in self.pathList:
79 if os.path.exists(os.path.join(path, name)):
81 raise IOError(_("Configuration file '%s' not found") % name)
84 '''Class that manages the read of all the configuration files of salomeTools
86 def __init__(self, datadir=None):
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...
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
97 :return: The dictionary that stores all information.
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
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
113 var['personalDir'] = os.path.join(os.path.expanduser('~'),
115 src.ensure_path_exists(var['personalDir'])
117 var['personal_applications_dir'] = os.path.join(var['personalDir'],
119 src.ensure_path_exists(var['personal_applications_dir'])
121 var['personal_products_dir'] = os.path.join(var['personalDir'],
123 src.ensure_path_exists(var['personal_products_dir'])
125 var['personal_archives_dir'] = os.path.join(var['personalDir'],
127 src.ensure_path_exists(var['personal_archives_dir'])
129 var['personal_jobs_dir'] = os.path.join(var['personalDir'],
131 src.ensure_path_exists(var['personal_jobs_dir'])
133 var['personal_machines_dir'] = os.path.join(var['personalDir'],
135 src.ensure_path_exists(var['personal_machines_dir'])
137 # read linux distributions dictionary
138 distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
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
149 var['dist_name'] = dist_name
150 var['dist_version'] = dist_version
152 var['python'] = src.architecture.get_python_version()
154 var['nb_proc'] = src.architecture.get_nb_proc()
155 node_name = platform.node()
156 var['node'] = node_name
157 var['hostname'] = node_name
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')
165 var['command'] = str(command)
166 var['application'] = str(application)
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'
176 def get_command_line_overrides(self, options, sections):
177 '''get all the overwrites that are in the command line
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.
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:
191 for section in sections:
192 # only overwrite the sections that correspond to the option
193 over.extend(filter(lambda l: l.startswith(section + "."),
197 def get_config(self, application=None, options=None, command=None,
199 '''get the config from all the configuration files.
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'
211 # create a ConfigMerger to handle merge
212 merger = src.pyconf.ConfigMerger()#MergeHandler())
214 # create the configuration instance
215 cfg = src.pyconf.Config()
217 # =====================================================================
218 # create VARS section
219 var = self._create_vars(application=application, command=command,
222 cfg.VARS = src.pyconf.Mapping(cfg)
224 cfg.VARS[variable] = var[variable]
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
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')])
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") % \
243 merger.merge(cfg, internal_cfg)
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
249 # =====================================================================
250 # Load SITE config file
251 # search only in the data directory
252 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
254 site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir,
256 PWD = ('SITE', cfg.VARS.datadir) )
257 except src.pyconf.ConfigError as e:
258 raise src.SatException(_("Error in configuration file: "
259 "site.pyconf\n %(error)s") % \
261 except IOError as error:
263 if "site.pyconf" in e :
264 e += ("\nYou can copy data"
266 + "site.template.pyconf to data"
268 + "site.pyconf and edit the file")
269 raise src.SatException( e );
270 merger.merge(cfg, site_cfg)
272 # apply overwrite from command line if needed
273 for rule in self.get_command_line_overrides(options, ["SITE"]):
274 exec('cfg.' + rule) # this cannot be factorized because of the exec
276 # =====================================================================
278 projects_cfg = src.pyconf.Config()
279 projects_cfg.addMapping("PROJECTS",
280 src.pyconf.Mapping(projects_cfg),
282 projects_cfg.PROJECTS.addMapping("projects",
283 src.pyconf.Mapping(cfg.PROJECTS),
284 "The projects definition\n")
286 for project_pyconf_path in cfg.PROJECTS.project_file_paths:
287 if not os.path.exists(project_pyconf_path):
288 msg = _("WARNING: The project file %s cannot be found. "
289 "It will be ignored\n" % project_pyconf_path)
290 sys.stdout.write(msg)
292 project_name = os.path.basename(
293 project_pyconf_path)[:-len(".pyconf")]
295 project_pyconf_dir = os.path.dirname(project_pyconf_path)
296 project_cfg = src.pyconf.Config(open(project_pyconf_path),
297 PWD=("", project_pyconf_dir))
298 except Exception as e:
299 msg = _("ERROR: Error in configuration file: "
300 "%(file_path)s\n %(error)s\n") % \
301 {'file_path' : project_pyconf_path, 'error': str(e) }
302 sys.stdout.write(msg)
304 projects_cfg.PROJECTS.projects.addMapping(project_name,
305 src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
306 "The %s project\n" % project_name)
307 projects_cfg.PROJECTS.projects[project_name]=project_cfg
308 projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
311 merger.merge(cfg, projects_cfg)
313 # apply overwrite from command line if needed
314 for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
315 exec('cfg.' + rule) # this cannot be factorized because of the exec
317 # =====================================================================
318 # Create the paths where to search the application configurations,
319 # the product configurations, the products archives,
320 # the jobs configurations and the machines configurations
321 cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
322 cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
323 cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
325 cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
326 cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
327 cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
328 cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
329 cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
330 cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
331 cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
332 cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
333 # Loop over the projects in order to complete the PATHS variables
334 for project in cfg.PROJECTS.projects:
335 for PATH in ["APPLICATIONPATH",
340 if PATH not in cfg.PROJECTS.projects[project]:
342 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
344 # apply overwrite from command line if needed
345 for rule in self.get_command_line_overrides(options, ["PATHS"]):
346 exec('cfg.' + rule) # this cannot be factorized because of the exec
348 # =====================================================================
349 # Load APPLICATION config file
350 if application is not None:
351 # search APPLICATION file in all directories in configPath
352 cp = cfg.PATHS.APPLICATIONPATH
353 src.pyconf.streamOpener = ConfigOpener(cp)
356 application_cfg = src.pyconf.Config(application + '.pyconf')
358 raise src.SatException(_("%s, use 'config --list' to get the"
359 " list of available applications.") %e)
360 except src.pyconf.ConfigError as e:
361 if (not ('-e' in parser.parse_args()[1])
362 or ('--edit' in parser.parse_args()[1])
363 and command == 'config'):
364 raise src.SatException(_("Error in configuration file: "
365 "%(application)s.pyconf\n "
367 { 'application': application, 'error': str(e) } )
369 sys.stdout.write(src.printcolors.printcWarning(
370 "There is an error in the file"
371 " %s.pyconf.\n" % cfg.VARS.application))
373 except Exception as e:
374 if (not ('-e' in parser.parse_args()[1])
375 or ('--edit' in parser.parse_args()[1])
376 and command == 'config'):
377 sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
378 raise src.SatException(_("Error in configuration file:"
379 " %(application)s.pyconf\n") % \
380 { 'application': application} )
382 sys.stdout.write(src.printcolors.printcWarning(
383 "There is an error in the file"
384 " %s.pyconf. Opening the file with the"
385 " default viewer\n" % cfg.VARS.application))
386 sys.stdout.write("The error:"
387 " %s\n" % src.printcolors.printcWarning(
392 cfg['open_application'] = 'yes'
394 # =====================================================================
395 # Load product config files in PRODUCTS section
396 products_cfg = src.pyconf.Config()
397 products_cfg.addMapping("PRODUCTS",
398 src.pyconf.Mapping(products_cfg),
400 if application is not None:
401 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
402 for product_name in application_cfg.APPLICATION.products.keys():
403 # Loop on all files that are in softsDir directory
404 # and read their config
405 product_file_name = product_name + ".pyconf"
406 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
407 if product_file_path:
408 products_dir = os.path.dirname(product_file_path)
410 prod_cfg = src.pyconf.Config(open(product_file_path),
411 PWD=("", products_dir))
412 prod_cfg.from_file = product_file_path
413 products_cfg.PRODUCTS[product_name] = prod_cfg
414 except Exception as e:
416 "WARNING: Error in configuration file"
417 ": %(prod)s\n %(error)s" % \
418 {'prod' : product_name, 'error': str(e) })
419 sys.stdout.write(msg)
421 merger.merge(cfg, products_cfg)
423 # apply overwrite from command line if needed
424 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
425 exec('cfg.' + rule) # this cannot be factorized because of the exec
428 merger.merge(cfg, application_cfg)
430 # default launcher name ('salome')
431 if ('profile' in cfg.APPLICATION and
432 'launcher_name' not in cfg.APPLICATION.profile):
433 cfg.APPLICATION.profile.launcher_name = 'salome'
435 # apply overwrite from command line if needed
436 for rule in self.get_command_line_overrides(options,
438 # this cannot be factorized because of the exec
441 # =====================================================================
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)
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
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.
458 :param config class 'src.pyconf.Config': The global config
459 (containing all pyconf).
461 # get the expected name and path of the file
462 self.config_file_name = 'SAT.pyconf'
463 self.user_config_file_path = os.path.join(config.VARS.personalDir,
464 self.config_file_name)
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)
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.
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'
479 cfg_name = self.get_user_config_file()
481 user_cfg = src.pyconf.Config()
483 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
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('~'),
501 user_cfg.USER.addMapping('editor',
503 "This is the editor used to "
504 "modify configuration files\n")
505 user_cfg.USER.addMapping('browser',
507 "This is the browser used to "
508 "read html documentation\n")
509 user_cfg.USER.addMapping('pdf_viewer',
511 "This is the pdf_viewer used "
512 "to read pdf documentation\n")
513 user_cfg.USER.addMapping("base",
514 src.pyconf.Reference(
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")
522 user_cfg.USER.addMapping("log_dir",
523 src.pyconf.Reference(
526 'workdir + $VARS.sep + "LOGS"'),
527 "The log repository\n")
530 src.ensure_path_exists(config.VARS.personalDir)
531 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
534 f = open(cfg_name, 'w')
540 def get_user_config_file(self):
541 '''Get the user config file
542 :return: path to the user config file.
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
550 def check_path(path, ext=[]):
551 '''Construct a text with the input path and "not found" if it does not
554 :param path Str: the path to check.
555 :param ext List: An extension. Verify that the path extension
557 :return: The string of the path with information
560 # check if file exists
561 if not os.path.exists(path):
562 return "'%s'" % path + " " + src.printcolors.printcError(_(
567 fe = os.path.splitext(path)[1].lower()
569 return "'%s'" % path + " " + src.printcolors.printcError(_(
574 def show_product_info(config, name, logger):
575 '''Display on the terminal and logger information about a product.
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
582 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
583 pinfo = src.product.get_product_config(config, name)
585 if "depend" in pinfo:
586 src.printcolors.print_value(logger,
588 ', '.join(pinfo.depend), 2)
590 if "opt_depend" in pinfo:
591 src.printcolors.print_value(logger,
593 ', '.join(pinfo.opt_depend), 2)
595 # information on pyconf
596 logger.write("\n", 2)
597 logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
598 if "from_file" in pinfo:
599 src.printcolors.print_value(logger,
603 if "section" in pinfo:
604 src.printcolors.print_value(logger,
609 # information on prepare
610 logger.write("\n", 2)
611 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
613 is_dev = src.product.product_is_dev(pinfo)
614 method = pinfo.get_source
617 src.printcolors.print_value(logger, "get method", method, 2)
620 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
621 src.printcolors.print_value(logger, "base module",
622 pinfo.cvs_info.module_base, 2)
623 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
624 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
626 elif method == 'svn':
627 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
629 elif method == 'git':
630 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
631 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
633 elif method == 'archive':
634 src.printcolors.print_value(logger,
636 check_path(pinfo.archive_info.archive_name),
639 if 'patches' in pinfo:
640 for patch in pinfo.patches:
641 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
643 if src.product.product_is_fixed(pinfo):
644 src.printcolors.print_value(logger, "install_dir",
645 check_path(pinfo.install_dir), 2)
647 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
650 # information on compilation
651 if src.product.product_compiles(pinfo):
652 logger.write("\n", 2)
653 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
654 src.printcolors.print_value(logger,
655 "compilation method",
659 if pinfo.build_source == "script" and "compil_script" in pinfo:
660 src.printcolors.print_value(logger,
661 "Compilation script",
665 if 'nb_proc' in pinfo:
666 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
668 src.printcolors.print_value(logger,
670 check_path(pinfo.source_dir),
672 if 'install_dir' in pinfo:
673 src.printcolors.print_value(logger,
675 check_path(pinfo.build_dir),
677 src.printcolors.print_value(logger,
679 check_path(pinfo.install_dir),
683 src.printcolors.printcWarning(_("no install dir")) +
686 logger.write("\n", 2)
687 msg = _("This product does not compile")
688 logger.write("%s\n" % msg, 2)
690 # information on environment
691 logger.write("\n", 2)
692 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
693 if "environ" in pinfo and "env_script" in pinfo.environ:
694 src.printcolors.print_value(logger,
696 check_path(pinfo.environ.env_script),
699 zz = src.environment.SalomeEnviron(config,
700 src.fileEnviron.ScreenEnviron(logger),
702 zz.set_python_libdirs()
703 zz.set_a_product(name, logger)
705 def show_patchs(config, logger):
706 '''Prints all the used patchs in the application.
708 :param config Config: the global configuration.
709 :param logger Logger: The logger instance to use for the display
711 len_max = max([len(p) for p in config.APPLICATION.products]) + 2
712 for product in config.APPLICATION.products:
713 product_info = src.product.get_product_config(config, product)
714 if src.product.product_has_patches(product_info):
715 logger.write("%s: " % product, 1)
716 logger.write(src.printcolors.printcInfo(
717 " " * (len_max - len(product) -2) +
718 "%s\n" % product_info.patches[0]),
720 if len(product_info.patches) > 1:
721 for patch in product_info.patches[1:]:
722 logger.write(src.printcolors.printcInfo(len_max*" " +
724 logger.write("\n", 1)
726 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
727 '''Prints a value from the configuration. Prints recursively the values
728 under the initial path.
730 :param config class 'src.pyconf.Config': The configuration
731 from which the value is displayed.
732 :param path str : the path in the configuration of the value to print.
733 :param show_label boolean: if True, do a basic display.
734 (useful for bash completion)
735 :param logger Logger: the logger instance
736 :param level int: The number of spaces to add before display.
737 :param show_full_path :
740 # Make sure that the path does not ends with a point
741 if path.endswith('.'):
744 # display all the path or not
748 vname = path.split('.')[-1]
750 # number of spaces before the display
751 tab_level = " " * level
753 # call to the function that gets the value of the path.
755 val = config.getByPath(path)
756 except Exception as e:
757 logger.write(tab_level)
758 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
759 src.printcolors.printcError(str(e))))
762 # in this case, display only the value
764 logger.write(tab_level)
765 logger.write("%s: " % src.printcolors.printcLabel(vname))
767 # The case where the value has under values,
768 # do a recursive call to the function
769 if dir(val).__contains__('keys'):
770 if show_label: logger.write("\n")
771 for v in sorted(val.keys()):
772 print_value(config, path + '.' + v, show_label, logger, level + 1)
773 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
774 # in this case, value is a list (or a Sequence)
775 if show_label: logger.write("\n")
778 print_value(config, path + "[" + str(index) + "]",
779 show_label, logger, level + 1)
781 else: # case where val is just a str
782 logger.write("%s\n" % val)
784 def get_config_children(config, args):
785 '''Gets the names of the children of the given parameter.
786 Useful only for completion mechanism
788 :param config Config: The configuration where to read the values
789 :param args: The path in the config from which get the keys
792 rootkeys = config.keys()
795 # no parameter returns list of root keys
799 pos = parent.rfind('.')
801 # Case where there is only on key as parameter.
803 vals = [m for m in rootkeys if m.startswith(parent)]
805 # Case where there is a part from a key
806 # for example VARS.us (for VARS.user)
808 tail = parent[pos+1:]
810 a = config.getByPath(head)
811 if dir(a).__contains__('keys'):
812 vals = map(lambda x: head + '.' + x,
813 [m for m in a.keys() if m.startswith(tail)])
817 for v in sorted(vals):
818 sys.stdout.write("%s\n" % v)
821 '''method that is called when salomeTools is called with --help option.
823 :return: The text to display for the config command description.
826 return _("The config command allows manipulation "
827 "and operation on config files.\n\nexample:\nsat config "
828 "SALOME-master --info ParaView")
831 def run(args, runner, logger):
832 '''method that is called when salomeTools is called with config parameter.
835 (options, args) = parser.parse_args(args)
837 # Only useful for completion mechanism : print the keys of the config
839 get_config_children(runner.cfg, args)
842 # case : print a value of the config
844 if options.value == ".":
845 # if argument is ".", print all the config
846 for val in sorted(runner.cfg.keys()):
847 print_value(runner.cfg, val, not options.no_label, logger)
849 print_value(runner.cfg, options.value, not options.no_label, logger,
850 level=0, show_full_path=False)
852 # case : edit user pyconf file or application file
854 editor = runner.cfg.USER.editor
855 if ('APPLICATION' not in runner.cfg and
856 'open_application' not in runner.cfg): # edit user pyconf
857 usercfg = os.path.join(runner.cfg.VARS.personalDir,
859 logger.write(_("Openning %s\n" % usercfg), 3)
860 src.system.show_in_editor(editor, usercfg, logger)
862 # search for file <application>.pyconf and open it
863 for path in runner.cfg.PATHS.APPLICATIONPATH:
864 pyconf_path = os.path.join(path,
865 runner.cfg.VARS.application + ".pyconf")
866 if os.path.exists(pyconf_path):
867 logger.write(_("Openning %s\n" % pyconf_path), 3)
868 src.system.show_in_editor(editor, pyconf_path, logger)
871 # case : give information about the product in parameter
873 src.check_config_has_application(runner.cfg)
874 if options.info in runner.cfg.APPLICATION.products:
875 show_product_info(runner.cfg, options.info, logger)
877 raise src.SatException(_("%(product_name)s is not a product "
878 "of %(application_name)s.") %
879 {'product_name' : options.info,
881 runner.cfg.VARS.application})
883 # case : copy an existing <application>.pyconf
884 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
886 # product is required
887 src.check_config_has_application( runner.cfg )
889 # get application file path
890 source = runner.cfg.VARS.application + '.pyconf'
891 source_full_path = ""
892 for path in runner.cfg.PATHS.APPLICATIONPATH:
893 # ignore personal directory
894 if path == runner.cfg.VARS.personalDir:
896 # loop on all directories that can have pyconf applications
897 zz = os.path.join(path, source)
898 if os.path.exists(zz):
899 source_full_path = zz
902 if len(source_full_path) == 0:
903 raise src.SatException(_(
904 "Config file for product %s not found\n") % source)
907 # a name is given as parameter, use it
909 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
911 dest = (runner.cfg.INTERNAL.config.copy_prefix
912 + runner.cfg.VARS.application)
914 # use same name as source
915 dest = runner.cfg.VARS.application
918 dest_file = os.path.join(runner.cfg.VARS.personalDir,
919 'Applications', dest + '.pyconf')
920 if os.path.exists(dest_file):
921 raise src.SatException(_("A personal application"
922 " '%s' already exists") % dest)
925 shutil.copyfile(source_full_path, dest_file)
926 logger.write(_("%s has been created.\n") % dest_file)
928 # case : display all the available pyconf applications
931 # search in all directories that can have pyconf applications
932 for path in runner.cfg.PATHS.APPLICATIONPATH:
934 if not options.no_label:
935 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
937 if not os.path.exists(path):
938 logger.write(src.printcolors.printcError(_(
939 "Directory not found")) + "\n")
941 for f in sorted(os.listdir(path)):
942 # ignore file that does not ends with .pyconf
943 if not f.endswith('.pyconf'):
946 appliname = f[:-len('.pyconf')]
947 if appliname not in lproduct:
948 lproduct.append(appliname)
949 if path.startswith(runner.cfg.VARS.personalDir) \
950 and not options.no_label:
951 logger.write("%s*\n" % appliname)
953 logger.write("%s\n" % appliname)
956 # case : give a synthetic view of all patches used in the application
957 elif options.show_patchs:
958 src.check_config_has_application(runner.cfg)
959 # Print some informations
960 logger.write(_('Show the patchs of application %s\n') %
961 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
962 logger.write("\n", 2, False)
963 show_patchs(runner.cfg, logger)
965 # case: print all the products name of the application (internal use for completion)
966 elif options.completion:
967 for product_name in runner.cfg.APPLICATION.products.keys():
968 logger.write("%s\n" % product_name)