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 merger.merge(cfg, application_cfg)
394 # apply overwrite from command line if needed
395 for rule in self.get_command_line_overrides(options,
397 # this cannot be factorized because of the exec
400 # default launcher name ('salome')
401 if ('profile' in cfg.APPLICATION and
402 'launcher_name' not in cfg.APPLICATION.profile):
403 cfg.APPLICATION.profile.launcher_name = 'salome'
406 cfg['open_application'] = 'yes'
408 # =====================================================================
409 # Load product config files in PRODUCTS section
410 products_cfg = src.pyconf.Config()
411 products_cfg.addMapping("PRODUCTS",
412 src.pyconf.Mapping(products_cfg),
414 if application is not None:
415 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
416 for product_name in cfg.APPLICATION.products.keys():
417 # Loop on all files that are in softsDir directory
418 # and read their config
419 product_file_name = product_name + ".pyconf"
420 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
421 if product_file_path:
422 products_dir = os.path.dirname(product_file_path)
424 prod_cfg = src.pyconf.Config(open(
425 os.path.join(products_dir,
427 PWD=("", products_dir))
428 products_cfg.PRODUCTS[product_name] = prod_cfg
429 except Exception as e:
431 "WARNING: Error in configuration file"
432 ": %(prod)s\n %(error)s" % \
433 {'prod' : product_name, 'error': str(e) })
434 sys.stdout.write(msg)
436 merger.merge(cfg, products_cfg)
438 # apply overwrite from command line if needed
439 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
440 exec('cfg.' + rule) # this cannot be factorized because of the exec
442 # =====================================================================
444 self.set_user_config_file(cfg)
445 user_cfg_file = self.get_user_config_file()
446 user_cfg = src.pyconf.Config(open(user_cfg_file))
447 merger.merge(cfg, user_cfg)
449 # apply overwrite from command line if needed
450 for rule in self.get_command_line_overrides(options, ["USER"]):
451 exec('cfg.' + rule) # this cannot be factorize because of the exec
455 def set_user_config_file(self, config):
456 '''Set the user config file name and path.
457 If necessary, build it from another one or create it from scratch.
459 :param config class 'src.pyconf.Config': The global config
460 (containing all pyconf).
462 # get the expected name and path of the file
463 self.config_file_name = 'salomeTools.pyconf'
464 self.user_config_file_path = os.path.join(config.VARS.personalDir,
465 self.config_file_name)
467 # if pyconf does not exist, create it from scratch
468 if not os.path.isfile(self.user_config_file_path):
469 self.create_config_file(config)
471 def create_config_file(self, config):
472 '''This method is called when there are no user config file.
473 It build it from scratch.
475 :param config class 'src.pyconf.Config': The global config.
476 :return: the config corresponding to the file created.
477 :rtype: config class 'src.pyconf.Config'
480 cfg_name = self.get_user_config_file()
482 user_cfg = src.pyconf.Config()
484 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
487 user_cfg.USER.addMapping('workdir', os.path.expanduser('~'),
488 "This is where salomeTools will work. "
489 "You may (and probably do) change it.\n")
490 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
491 "This is the user name used to access salome cvs base.\n")
492 user_cfg.USER.addMapping('svn_user', config.VARS.user,
493 "This is the user name used to access salome svn base.\n")
494 user_cfg.USER.addMapping('output_verbose_level', 3,
495 "This is the default output_verbose_level you want."
496 " 0=>no output, 5=>debug.\n")
497 user_cfg.USER.addMapping('publish_dir',
498 os.path.join(os.path.expanduser('~'),
502 user_cfg.USER.addMapping('editor',
504 "This is the editor used to "
505 "modify configuration files\n")
506 user_cfg.USER.addMapping('browser',
508 "This is the browser used to "
509 "read html documentation\n")
510 user_cfg.USER.addMapping('pdf_viewer',
512 "This is the pdf_viewer used "
513 "to read pdf documentation\n")
514 user_cfg.USER.addMapping("base",
515 src.pyconf.Reference(
518 'workdir + $VARS.sep + "BASE"'),
519 "The products installation base (could be "
520 "ignored if this key exists in the site.pyconf"
521 " file of salomTools).\n")
523 user_cfg.USER.addMapping("log_dir",
524 src.pyconf.Reference(
527 'workdir + $VARS.sep + "LOGS"'),
528 "The log repository\n")
531 src.ensure_path_exists(config.VARS.personalDir)
532 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
535 f = open(cfg_name, 'w')
541 def get_user_config_file(self):
542 '''Get the user config file
543 :return: path to the user config file.
546 if not self.user_config_file_path:
547 raise src.SatException(_("Error in get_user_config_file: "
548 "missing user config file path"))
549 return self.user_config_file_path
551 def check_path(path, ext=[]):
552 '''Construct a text with the input path and "not found" if it does not
555 :param path Str: the path to check.
556 :param ext List: An extension. Verify that the path extension
558 :return: The string of the path with information
561 # check if file exists
562 if not os.path.exists(path):
563 return "'%s'" % path + " " + src.printcolors.printcError(_(
568 fe = os.path.splitext(path)[1].lower()
570 return "'%s'" % path + " " + src.printcolors.printcError(_(
575 def show_product_info(config, name, logger):
576 '''Display on the terminal and logger information about a product.
578 :param config Config: the global configuration.
579 :param name Str: The name of the product
580 :param logger Logger: The logger instance to use for the display
583 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
584 pinfo = src.product.get_product_config(config, name)
586 # Type of the product
587 ptype = src.get_cfg_param(pinfo, "type", "")
588 src.printcolors.print_value(logger, "type", ptype, 2)
589 if "depend" in pinfo:
590 src.printcolors.print_value(logger,
592 ', '.join(pinfo.depend), 2)
594 if "opt_depend" in pinfo:
595 src.printcolors.print_value(logger,
597 ', '.join(pinfo.opt_depend), 2)
599 # information on prepare
600 logger.write("\n", 2)
601 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
603 is_dev = src.product.product_is_dev(pinfo)
604 method = pinfo.get_source
607 src.printcolors.print_value(logger, "get method", method, 2)
610 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
611 src.printcolors.print_value(logger, "base module",
612 pinfo.cvs_info.module_base, 2)
613 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
614 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
616 elif method == 'svn':
617 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
619 elif method == 'git':
620 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
621 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
623 elif method == 'archive':
624 src.printcolors.print_value(logger,
626 check_path(pinfo.archive_info.archive_name),
629 if 'patches' in pinfo:
630 for patch in pinfo.patches:
631 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
633 if src.product.product_is_fixed(pinfo):
634 src.printcolors.print_value(logger, "install_dir",
635 check_path(pinfo.install_dir), 2)
637 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
640 # information on compilation
641 if src.product.product_compiles(pinfo):
642 logger.write("\n", 2)
643 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
644 src.printcolors.print_value(logger,
645 "compilation method",
649 if pinfo.build_source == "script" and "compil_script" in pinfo:
650 src.printcolors.print_value(logger,
651 "Compilation script",
655 if 'nb_proc' in pinfo:
656 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
658 src.printcolors.print_value(logger,
660 check_path(pinfo.source_dir),
662 if 'install_dir' in pinfo:
663 src.printcolors.print_value(logger,
665 check_path(pinfo.build_dir),
667 src.printcolors.print_value(logger,
669 check_path(pinfo.install_dir),
673 src.printcolors.printcWarning(_("no install dir")) +
676 logger.write("\n", 2)
677 msg = _("This product does not compile")
678 logger.write("%s\n" % msg, 2)
680 # information on environment
681 logger.write("\n", 2)
682 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
683 if "environ" in pinfo and "env_script" in pinfo.environ:
684 src.printcolors.print_value(logger,
686 check_path(pinfo.environ.env_script),
689 zz = src.environment.SalomeEnviron(config,
690 src.fileEnviron.ScreenEnviron(logger),
692 zz.set_python_libdirs()
693 zz.set_a_product(name, logger)
695 def show_patchs(config, logger):
696 '''Prints all the used patchs in the application.
698 :param config Config: the global configuration.
699 :param logger Logger: The logger instance to use for the display
701 len_max = max([len(p) for p in config.APPLICATION.products]) + 2
702 for product in config.APPLICATION.products:
703 product_info = src.product.get_product_config(config, product)
704 if src.product.product_has_patches(product_info):
705 logger.write("%s: " % product, 1)
706 logger.write(src.printcolors.printcInfo(
707 " " * (len_max - len(product) -2) +
708 "%s\n" % product_info.patches[0]),
710 if len(product_info.patches) > 1:
711 for patch in product_info.patches[1:]:
712 logger.write(src.printcolors.printcInfo(len_max*" " +
714 logger.write("\n", 1)
716 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
717 '''Prints a value from the configuration. Prints recursively the values
718 under the initial path.
720 :param config class 'src.pyconf.Config': The configuration
721 from which the value is displayed.
722 :param path str : the path in the configuration of the value to print.
723 :param show_label boolean: if True, do a basic display.
724 (useful for bash completion)
725 :param logger Logger: the logger instance
726 :param level int: The number of spaces to add before display.
727 :param show_full_path :
730 # Make sure that the path does not ends with a point
731 if path.endswith('.'):
734 # display all the path or not
738 vname = path.split('.')[-1]
740 # number of spaces before the display
741 tab_level = " " * level
743 # call to the function that gets the value of the path.
745 val = config.getByPath(path)
746 except Exception as e:
747 logger.write(tab_level)
748 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
749 src.printcolors.printcError(str(e))))
752 # in this case, display only the value
754 logger.write(tab_level)
755 logger.write("%s: " % src.printcolors.printcLabel(vname))
757 # The case where the value has under values,
758 # do a recursive call to the function
759 if dir(val).__contains__('keys'):
760 if show_label: logger.write("\n")
761 for v in sorted(val.keys()):
762 print_value(config, path + '.' + v, show_label, logger, level + 1)
763 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
764 # in this case, value is a list (or a Sequence)
765 if show_label: logger.write("\n")
768 print_value(config, path + "[" + str(index) + "]",
769 show_label, logger, level + 1)
771 else: # case where val is just a str
772 logger.write("%s\n" % val)
774 def get_config_children(config, args):
775 '''Gets the names of the children of the given parameter.
776 Useful only for completion mechanism
778 :param config Config: The configuration where to read the values
779 :param args: The path in the config from which get the keys
782 rootkeys = config.keys()
785 # no parameter returns list of root keys
789 pos = parent.rfind('.')
791 # Case where there is only on key as parameter.
793 vals = [m for m in rootkeys if m.startswith(parent)]
795 # Case where there is a part from a key
796 # for example VARS.us (for VARS.user)
798 tail = parent[pos+1:]
800 a = config.getByPath(head)
801 if dir(a).__contains__('keys'):
802 vals = map(lambda x: head + '.' + x,
803 [m for m in a.keys() if m.startswith(tail)])
807 for v in sorted(vals):
808 sys.stdout.write("%s\n" % v)
811 '''method that is called when salomeTools is called with --help option.
813 :return: The text to display for the config command description.
816 return _("The config command allows manipulation "
817 "and operation on config files.\n\nexample:\nsat config "
818 "SALOME-master --info ParaView")
821 def run(args, runner, logger):
822 '''method that is called when salomeTools is called with config parameter.
825 (options, args) = parser.parse_args(args)
827 # Only useful for completion mechanism : print the keys of the config
829 get_config_children(runner.cfg, args)
832 # case : print a value of the config
834 if options.value == ".":
835 # if argument is ".", print all the config
836 for val in sorted(runner.cfg.keys()):
837 print_value(runner.cfg, val, not options.no_label, logger)
839 print_value(runner.cfg, options.value, not options.no_label, logger,
840 level=0, show_full_path=False)
842 # case : edit user pyconf file or application file
844 editor = runner.cfg.USER.editor
845 if ('APPLICATION' not in runner.cfg and
846 'open_application' not in runner.cfg): # edit user pyconf
847 usercfg = os.path.join(runner.cfg.VARS.personalDir,
848 'salomeTools.pyconf')
849 logger.write(_("Openning %s\n" % usercfg), 3)
850 src.system.show_in_editor(editor, usercfg, logger)
852 # search for file <application>.pyconf and open it
853 for path in runner.cfg.PATHS.APPLICATIONPATH:
854 pyconf_path = os.path.join(path,
855 runner.cfg.VARS.application + ".pyconf")
856 if os.path.exists(pyconf_path):
857 logger.write(_("Openning %s\n" % pyconf_path), 3)
858 src.system.show_in_editor(editor, pyconf_path, logger)
861 # case : give information about the product in parameter
863 src.check_config_has_application(runner.cfg)
864 if options.info in runner.cfg.APPLICATION.products:
865 show_product_info(runner.cfg, options.info, logger)
867 raise src.SatException(_("%(product_name)s is not a product "
868 "of %(application_name)s.") %
869 {'product_name' : options.info,
871 runner.cfg.VARS.application})
873 # case : copy an existing <application>.pyconf
874 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
876 # product is required
877 src.check_config_has_application( runner.cfg )
879 # get application file path
880 source = runner.cfg.VARS.application + '.pyconf'
881 source_full_path = ""
882 for path in runner.cfg.PATHS.APPLICATIONPATH:
883 # ignore personal directory
884 if path == runner.cfg.VARS.personalDir:
886 # loop on all directories that can have pyconf applications
887 zz = os.path.join(path, source)
888 if os.path.exists(zz):
889 source_full_path = zz
892 if len(source_full_path) == 0:
893 raise src.SatException(_(
894 "Config file for product %s not found\n") % source)
897 # a name is given as parameter, use it
899 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
901 dest = (runner.cfg.INTERNAL.config.copy_prefix
902 + runner.cfg.VARS.application)
904 # use same name as source
905 dest = runner.cfg.VARS.application
908 dest_file = os.path.join(runner.cfg.VARS.personalDir,
909 'Applications', dest + '.pyconf')
910 if os.path.exists(dest_file):
911 raise src.SatException(_("A personal application"
912 " '%s' already exists") % dest)
915 shutil.copyfile(source_full_path, dest_file)
916 logger.write(_("%s has been created.\n") % dest_file)
918 # case : display all the available pyconf applications
921 # search in all directories that can have pyconf applications
922 for path in runner.cfg.PATHS.APPLICATIONPATH:
924 if not options.no_label:
925 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
927 if not os.path.exists(path):
928 logger.write(src.printcolors.printcError(_(
929 "Directory not found")) + "\n")
931 for f in sorted(os.listdir(path)):
932 # ignore file that does not ends with .pyconf
933 if not f.endswith('.pyconf'):
936 appliname = f[:-len('.pyconf')]
937 if appliname not in lproduct:
938 lproduct.append(appliname)
939 if path.startswith(runner.cfg.VARS.personalDir) \
940 and not options.no_label:
941 logger.write("%s*\n" % appliname)
943 logger.write("%s\n" % appliname)
946 # case : give a synthetic view of all patches used in the application
947 elif options.show_patchs:
948 src.check_config_has_application(runner.cfg)
949 # Print some informations
950 logger.write(_('Show the patchs of application %s\n') %
951 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
952 logger.write("\n", 2, False)
953 show_patchs(runner.cfg, logger)
955 # case: print all the products name of the application (internal use for completion)
956 elif options.completion:
957 for product_name in runner.cfg.APPLICATION.products.keys():
958 logger.write("%s\n" % product_name)