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 LOCAL config file
251 # search only in the data directory
252 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
254 local_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir,
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") % \
261 except IOError as error:
263 raise src.SatException( e );
264 merger.merge(cfg, local_cfg)
266 # When the key is "default", put the default value
267 if cfg.LOCAL.base == "default":
268 cfg.LOCAL.base = os.path.abspath(
269 os.path.join(cfg.VARS.salometoolsway,
272 if cfg.LOCAL.workdir == "default":
273 cfg.LOCAL.workdir = os.path.abspath(
274 os.path.join(cfg.VARS.salometoolsway,
276 if cfg.LOCAL.log_dir == "default":
277 cfg.LOCAL.log_dir = os.path.abspath(
278 os.path.join(cfg.VARS.salometoolsway,
282 if cfg.LOCAL.archive_dir == "default":
283 cfg.LOCAL.archive_dir = os.path.abspath(
284 os.path.join(cfg.VARS.salometoolsway,
288 # apply overwrite from command line if needed
289 for rule in self.get_command_line_overrides(options, ["LOCAL"]):
290 exec('cfg.' + rule) # this cannot be factorized because of the exec
292 # =====================================================================
294 projects_cfg = src.pyconf.Config()
295 projects_cfg.addMapping("PROJECTS",
296 src.pyconf.Mapping(projects_cfg),
298 projects_cfg.PROJECTS.addMapping("projects",
299 src.pyconf.Mapping(cfg.PROJECTS),
300 "The projects definition\n")
302 for project_pyconf_path in cfg.PROJECTS.project_file_paths:
303 if not os.path.exists(project_pyconf_path):
304 msg = _("WARNING: The project file %s cannot be found. "
305 "It will be ignored\n" % project_pyconf_path)
306 sys.stdout.write(msg)
308 project_name = os.path.basename(
309 project_pyconf_path)[:-len(".pyconf")]
311 project_pyconf_dir = os.path.dirname(project_pyconf_path)
312 project_cfg = src.pyconf.Config(open(project_pyconf_path),
313 PWD=("", project_pyconf_dir))
314 except Exception as e:
315 msg = _("ERROR: Error in configuration file: "
316 "%(file_path)s\n %(error)s\n") % \
317 {'file_path' : project_pyconf_path, 'error': str(e) }
318 sys.stdout.write(msg)
320 projects_cfg.PROJECTS.projects.addMapping(project_name,
321 src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
322 "The %s project\n" % project_name)
323 projects_cfg.PROJECTS.projects[project_name]=project_cfg
324 projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
327 merger.merge(cfg, projects_cfg)
329 # apply overwrite from command line if needed
330 for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
331 exec('cfg.' + rule) # this cannot be factorized because of the exec
333 # =====================================================================
334 # Create the paths where to search the application configurations,
335 # the product configurations, the products archives,
336 # the jobs configurations and the machines configurations
337 cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
338 cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
339 cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
341 cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
342 cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
343 cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
344 cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
345 cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
346 cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
347 cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
348 cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
350 # initialise the path with local directory
351 cfg.PATHS["ARCHIVEPATH"].append(cfg.LOCAL.archive_dir, "")
353 # Loop over the projects in order to complete the PATHS variables
354 for project in cfg.PROJECTS.projects:
355 for PATH in ["APPLICATIONPATH",
360 if PATH not in cfg.PROJECTS.projects[project]:
362 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
364 # apply overwrite from command line if needed
365 for rule in self.get_command_line_overrides(options, ["PATHS"]):
366 exec('cfg.' + rule) # this cannot be factorized because of the exec
368 # =====================================================================
369 # Load APPLICATION config file
370 if application is not None:
371 # search APPLICATION file in all directories in configPath
372 cp = cfg.PATHS.APPLICATIONPATH
373 src.pyconf.streamOpener = ConfigOpener(cp)
376 application_cfg = src.pyconf.Config(application + '.pyconf')
378 raise src.SatException(_("%s, use 'config --list' to get the"
379 " list of available applications.") %e)
380 except src.pyconf.ConfigError as e:
381 if (not ('-e' in parser.parse_args()[1])
382 or ('--edit' in parser.parse_args()[1])
383 and command == 'config'):
384 raise src.SatException(_("Error in configuration file: "
385 "%(application)s.pyconf\n "
387 { 'application': application, 'error': str(e) } )
389 sys.stdout.write(src.printcolors.printcWarning(
390 "There is an error in the file"
391 " %s.pyconf.\n" % cfg.VARS.application))
393 except Exception as e:
394 if (not ('-e' in parser.parse_args()[1])
395 or ('--edit' in parser.parse_args()[1])
396 and command == 'config'):
397 sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
398 raise src.SatException(_("Error in configuration file:"
399 " %(application)s.pyconf\n") % \
400 { 'application': application} )
402 sys.stdout.write(src.printcolors.printcWarning(
403 "There is an error in the file"
404 " %s.pyconf. Opening the file with the"
405 " default viewer\n" % cfg.VARS.application))
406 sys.stdout.write("The error:"
407 " %s\n" % src.printcolors.printcWarning(
412 cfg['open_application'] = 'yes'
414 # =====================================================================
415 # Load product config files in PRODUCTS section
416 products_cfg = src.pyconf.Config()
417 products_cfg.addMapping("PRODUCTS",
418 src.pyconf.Mapping(products_cfg),
420 if application is not None:
421 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
422 for product_name in application_cfg.APPLICATION.products.keys():
423 # Loop on all files that are in softsDir directory
424 # and read their config
425 product_file_name = product_name + ".pyconf"
426 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
427 if product_file_path:
428 products_dir = os.path.dirname(product_file_path)
430 prod_cfg = src.pyconf.Config(open(product_file_path),
431 PWD=("", products_dir))
432 prod_cfg.from_file = product_file_path
433 products_cfg.PRODUCTS[product_name] = prod_cfg
434 except Exception as e:
436 "WARNING: Error in configuration file"
437 ": %(prod)s\n %(error)s" % \
438 {'prod' : product_name, 'error': str(e) })
439 sys.stdout.write(msg)
441 merger.merge(cfg, products_cfg)
443 # apply overwrite from command line if needed
444 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
445 exec('cfg.' + rule) # this cannot be factorized because of the exec
448 merger.merge(cfg, application_cfg)
450 # default launcher name ('salome')
451 if ('profile' in cfg.APPLICATION and
452 'launcher_name' not in cfg.APPLICATION.profile):
453 cfg.APPLICATION.profile.launcher_name = 'salome'
455 # apply overwrite from command line if needed
456 for rule in self.get_command_line_overrides(options,
458 # this cannot be factorized because of the exec
461 # =====================================================================
463 self.set_user_config_file(cfg)
464 user_cfg_file = self.get_user_config_file()
465 user_cfg = src.pyconf.Config(open(user_cfg_file))
466 merger.merge(cfg, user_cfg)
468 # apply overwrite from command line if needed
469 for rule in self.get_command_line_overrides(options, ["USER"]):
470 exec('cfg.' + rule) # this cannot be factorize because of the exec
474 def set_user_config_file(self, config):
475 '''Set the user config file name and path.
476 If necessary, build it from another one or create it from scratch.
478 :param config class 'src.pyconf.Config': The global config
479 (containing all pyconf).
481 # get the expected name and path of the file
482 self.config_file_name = 'SAT.pyconf'
483 self.user_config_file_path = os.path.join(config.VARS.personalDir,
484 self.config_file_name)
486 # if pyconf does not exist, create it from scratch
487 if not os.path.isfile(self.user_config_file_path):
488 self.create_config_file(config)
490 def create_config_file(self, config):
491 '''This method is called when there are no user config file.
492 It build it from scratch.
494 :param config class 'src.pyconf.Config': The global config.
495 :return: the config corresponding to the file created.
496 :rtype: config class 'src.pyconf.Config'
499 cfg_name = self.get_user_config_file()
501 user_cfg = src.pyconf.Config()
503 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
505 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
506 "This is the user name used to access salome cvs base.\n")
507 user_cfg.USER.addMapping('svn_user', config.VARS.user,
508 "This is the user name used to access salome svn base.\n")
509 user_cfg.USER.addMapping('output_verbose_level', 3,
510 "This is the default output_verbose_level you want."
511 " 0=>no output, 5=>debug.\n")
512 user_cfg.USER.addMapping('publish_dir',
513 os.path.join(os.path.expanduser('~'),
517 user_cfg.USER.addMapping('editor',
519 "This is the editor used to "
520 "modify configuration files\n")
521 user_cfg.USER.addMapping('browser',
523 "This is the browser used to "
524 "read html documentation\n")
525 user_cfg.USER.addMapping('pdf_viewer',
527 "This is the pdf_viewer used "
528 "to read pdf documentation\n")
529 # CNC 25/10/17 : plus nécessaire a priori
530 # user_cfg.USER.addMapping("base",
531 # src.pyconf.Reference(
534 # 'workdir + $VARS.sep + "BASE"'),
535 # "The products installation base (could be "
536 # "ignored if this key exists in the local.pyconf"
537 # " file of salomTools).\n")
540 src.ensure_path_exists(config.VARS.personalDir)
541 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
544 f = open(cfg_name, 'w')
550 def get_user_config_file(self):
551 '''Get the user config file
552 :return: path to the user config file.
555 if not self.user_config_file_path:
556 raise src.SatException(_("Error in get_user_config_file: "
557 "missing user config file path"))
558 return self.user_config_file_path
560 def check_path(path, ext=[]):
561 '''Construct a text with the input path and "not found" if it does not
564 :param path Str: the path to check.
565 :param ext List: An extension. Verify that the path extension
567 :return: The string of the path with information
570 # check if file exists
571 if not os.path.exists(path):
572 return "'%s'" % path + " " + src.printcolors.printcError(_(
577 fe = os.path.splitext(path)[1].lower()
579 return "'%s'" % path + " " + src.printcolors.printcError(_(
584 def show_product_info(config, name, logger):
585 '''Display on the terminal and logger information about a product.
587 :param config Config: the global configuration.
588 :param name Str: The name of the product
589 :param logger Logger: The logger instance to use for the display
592 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
593 pinfo = src.product.get_product_config(config, name)
595 if "depend" in pinfo:
596 src.printcolors.print_value(logger,
598 ', '.join(pinfo.depend), 2)
600 if "opt_depend" in pinfo:
601 src.printcolors.print_value(logger,
603 ', '.join(pinfo.opt_depend), 2)
605 # information on pyconf
606 logger.write("\n", 2)
607 logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
608 if "from_file" in pinfo:
609 src.printcolors.print_value(logger,
613 if "section" in pinfo:
614 src.printcolors.print_value(logger,
619 # information on prepare
620 logger.write("\n", 2)
621 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
623 is_dev = src.product.product_is_dev(pinfo)
624 method = pinfo.get_source
627 src.printcolors.print_value(logger, "get method", method, 2)
630 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
631 src.printcolors.print_value(logger, "base module",
632 pinfo.cvs_info.module_base, 2)
633 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
634 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
636 elif method == 'svn':
637 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
639 elif method == 'git':
640 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
641 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
643 elif method == 'archive':
644 src.printcolors.print_value(logger,
646 check_path(pinfo.archive_info.archive_name),
649 if 'patches' in pinfo:
650 for patch in pinfo.patches:
651 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
653 if src.product.product_is_fixed(pinfo):
654 src.printcolors.print_value(logger, "install_dir",
655 check_path(pinfo.install_dir), 2)
657 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
660 # information on compilation
661 if src.product.product_compiles(pinfo):
662 logger.write("\n", 2)
663 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
664 src.printcolors.print_value(logger,
665 "compilation method",
669 if pinfo.build_source == "script" and "compil_script" in pinfo:
670 src.printcolors.print_value(logger,
671 "Compilation script",
675 if 'nb_proc' in pinfo:
676 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
678 src.printcolors.print_value(logger,
680 check_path(pinfo.source_dir),
682 if 'install_dir' in pinfo:
683 src.printcolors.print_value(logger,
685 check_path(pinfo.build_dir),
687 src.printcolors.print_value(logger,
689 check_path(pinfo.install_dir),
693 src.printcolors.printcWarning(_("no install dir")) +
696 logger.write("\n", 2)
697 msg = _("This product does not compile")
698 logger.write("%s\n" % msg, 2)
700 # information on environment
701 logger.write("\n", 2)
702 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
703 if "environ" in pinfo and "env_script" in pinfo.environ:
704 src.printcolors.print_value(logger,
706 check_path(pinfo.environ.env_script),
709 zz = src.environment.SalomeEnviron(config,
710 src.fileEnviron.ScreenEnviron(logger),
712 zz.set_python_libdirs()
713 zz.set_a_product(name, logger)
715 def show_patchs(config, logger):
716 '''Prints all the used patchs in the application.
718 :param config Config: the global configuration.
719 :param logger Logger: The logger instance to use for the display
721 len_max = max([len(p) for p in config.APPLICATION.products]) + 2
722 for product in config.APPLICATION.products:
723 product_info = src.product.get_product_config(config, product)
724 if src.product.product_has_patches(product_info):
725 logger.write("%s: " % product, 1)
726 logger.write(src.printcolors.printcInfo(
727 " " * (len_max - len(product) -2) +
728 "%s\n" % product_info.patches[0]),
730 if len(product_info.patches) > 1:
731 for patch in product_info.patches[1:]:
732 logger.write(src.printcolors.printcInfo(len_max*" " +
734 logger.write("\n", 1)
736 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
737 '''Prints a value from the configuration. Prints recursively the values
738 under the initial path.
740 :param config class 'src.pyconf.Config': The configuration
741 from which the value is displayed.
742 :param path str : the path in the configuration of the value to print.
743 :param show_label boolean: if True, do a basic display.
744 (useful for bash completion)
745 :param logger Logger: the logger instance
746 :param level int: The number of spaces to add before display.
747 :param show_full_path :
750 # Make sure that the path does not ends with a point
751 if path.endswith('.'):
754 # display all the path or not
758 vname = path.split('.')[-1]
760 # number of spaces before the display
761 tab_level = " " * level
763 # call to the function that gets the value of the path.
765 val = config.getByPath(path)
766 except Exception as e:
767 logger.write(tab_level)
768 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
769 src.printcolors.printcError(str(e))))
772 # in this case, display only the value
774 logger.write(tab_level)
775 logger.write("%s: " % src.printcolors.printcLabel(vname))
777 # The case where the value has under values,
778 # do a recursive call to the function
779 if dir(val).__contains__('keys'):
780 if show_label: logger.write("\n")
781 for v in sorted(val.keys()):
782 print_value(config, path + '.' + v, show_label, logger, level + 1)
783 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
784 # in this case, value is a list (or a Sequence)
785 if show_label: logger.write("\n")
788 print_value(config, path + "[" + str(index) + "]",
789 show_label, logger, level + 1)
791 else: # case where val is just a str
792 logger.write("%s\n" % val)
794 def get_config_children(config, args):
795 '''Gets the names of the children of the given parameter.
796 Useful only for completion mechanism
798 :param config Config: The configuration where to read the values
799 :param args: The path in the config from which get the keys
802 rootkeys = config.keys()
805 # no parameter returns list of root keys
809 pos = parent.rfind('.')
811 # Case where there is only on key as parameter.
813 vals = [m for m in rootkeys if m.startswith(parent)]
815 # Case where there is a part from a key
816 # for example VARS.us (for VARS.user)
818 tail = parent[pos+1:]
820 a = config.getByPath(head)
821 if dir(a).__contains__('keys'):
822 vals = map(lambda x: head + '.' + x,
823 [m for m in a.keys() if m.startswith(tail)])
827 for v in sorted(vals):
828 sys.stdout.write("%s\n" % v)
831 '''method that is called when salomeTools is called with --help option.
833 :return: The text to display for the config command description.
836 return _("The config command allows manipulation "
837 "and operation on config files.\n\nexample:\nsat config "
838 "SALOME-master --info ParaView")
841 def run(args, runner, logger):
842 '''method that is called when salomeTools is called with config parameter.
845 (options, args) = parser.parse_args(args)
847 # Only useful for completion mechanism : print the keys of the config
849 get_config_children(runner.cfg, args)
852 # case : print a value of the config
854 if options.value == ".":
855 # if argument is ".", print all the config
856 for val in sorted(runner.cfg.keys()):
857 print_value(runner.cfg, val, not options.no_label, logger)
859 print_value(runner.cfg, options.value, not options.no_label, logger,
860 level=0, show_full_path=False)
862 # case : edit user pyconf file or application file
864 editor = runner.cfg.USER.editor
865 if ('APPLICATION' not in runner.cfg and
866 'open_application' not in runner.cfg): # edit user pyconf
867 usercfg = os.path.join(runner.cfg.VARS.personalDir,
869 logger.write(_("Openning %s\n" % usercfg), 3)
870 src.system.show_in_editor(editor, usercfg, logger)
872 # search for file <application>.pyconf and open it
873 for path in runner.cfg.PATHS.APPLICATIONPATH:
874 pyconf_path = os.path.join(path,
875 runner.cfg.VARS.application + ".pyconf")
876 if os.path.exists(pyconf_path):
877 logger.write(_("Openning %s\n" % pyconf_path), 3)
878 src.system.show_in_editor(editor, pyconf_path, logger)
881 # case : give information about the product in parameter
883 src.check_config_has_application(runner.cfg)
884 if options.info in runner.cfg.APPLICATION.products:
885 show_product_info(runner.cfg, options.info, logger)
887 raise src.SatException(_("%(product_name)s is not a product "
888 "of %(application_name)s.") %
889 {'product_name' : options.info,
891 runner.cfg.VARS.application})
893 # case : copy an existing <application>.pyconf
894 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
896 # product is required
897 src.check_config_has_application( runner.cfg )
899 # get application file path
900 source = runner.cfg.VARS.application + '.pyconf'
901 source_full_path = ""
902 for path in runner.cfg.PATHS.APPLICATIONPATH:
903 # ignore personal directory
904 if path == runner.cfg.VARS.personalDir:
906 # loop on all directories that can have pyconf applications
907 zz = os.path.join(path, source)
908 if os.path.exists(zz):
909 source_full_path = zz
912 if len(source_full_path) == 0:
913 raise src.SatException(_(
914 "Config file for product %s not found\n") % source)
917 # a name is given as parameter, use it
919 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
921 dest = (runner.cfg.INTERNAL.config.copy_prefix
922 + runner.cfg.VARS.application)
924 # use same name as source
925 dest = runner.cfg.VARS.application
928 dest_file = os.path.join(runner.cfg.VARS.personalDir,
929 'Applications', dest + '.pyconf')
930 if os.path.exists(dest_file):
931 raise src.SatException(_("A personal application"
932 " '%s' already exists") % dest)
935 shutil.copyfile(source_full_path, dest_file)
936 logger.write(_("%s has been created.\n") % dest_file)
938 # case : display all the available pyconf applications
941 # search in all directories that can have pyconf applications
942 for path in runner.cfg.PATHS.APPLICATIONPATH:
944 if not options.no_label:
945 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
947 if not os.path.exists(path):
948 logger.write(src.printcolors.printcError(_(
949 "Directory not found")) + "\n")
951 for f in sorted(os.listdir(path)):
952 # ignore file that does not ends with .pyconf
953 if not f.endswith('.pyconf'):
956 appliname = f[:-len('.pyconf')]
957 if appliname not in lproduct:
958 lproduct.append(appliname)
959 if path.startswith(runner.cfg.VARS.personalDir) \
960 and not options.no_label:
961 logger.write("%s*\n" % appliname)
963 logger.write("%s\n" % appliname)
966 # case : give a synthetic view of all patches used in the application
967 elif options.show_patchs:
968 src.check_config_has_application(runner.cfg)
969 # Print some informations
970 logger.write(_('Show the patchs of application %s\n') %
971 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
972 logger.write("\n", 2, False)
973 show_patchs(runner.cfg, logger)
975 # case: print all the products name of the application (internal use for completion)
976 elif options.completion:
977 for product_name in runner.cfg.APPLICATION.products.keys():
978 logger.write("%s\n" % product_name)