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 "unknown", put the default value
267 if cfg.LOCAL.base == "unknown":
268 cfg.LOCAL.base = os.path.abspath(
269 os.path.join(cfg.VARS.salometoolsway,
272 if cfg.LOCAL.workdir == "unknown":
273 cfg.LOCAL.workdir = os.path.abspath(
274 os.path.join(cfg.VARS.salometoolsway,
276 if cfg.LOCAL.log_dir == "unknown":
277 cfg.LOCAL.log_dir = os.path.abspath(
278 os.path.join(cfg.VARS.salometoolsway,
282 # apply overwrite from command line if needed
283 for rule in self.get_command_line_overrides(options, ["LOCAL"]):
284 exec('cfg.' + rule) # this cannot be factorized because of the exec
286 # =====================================================================
288 projects_cfg = src.pyconf.Config()
289 projects_cfg.addMapping("PROJECTS",
290 src.pyconf.Mapping(projects_cfg),
292 projects_cfg.PROJECTS.addMapping("projects",
293 src.pyconf.Mapping(cfg.PROJECTS),
294 "The projects definition\n")
296 for project_pyconf_path in cfg.PROJECTS.project_file_paths:
297 if not os.path.exists(project_pyconf_path):
298 msg = _("WARNING: The project file %s cannot be found. "
299 "It will be ignored\n" % project_pyconf_path)
300 sys.stdout.write(msg)
302 project_name = os.path.basename(
303 project_pyconf_path)[:-len(".pyconf")]
305 project_pyconf_dir = os.path.dirname(project_pyconf_path)
306 project_cfg = src.pyconf.Config(open(project_pyconf_path),
307 PWD=("", project_pyconf_dir))
308 except Exception as e:
309 msg = _("ERROR: Error in configuration file: "
310 "%(file_path)s\n %(error)s\n") % \
311 {'file_path' : project_pyconf_path, 'error': str(e) }
312 sys.stdout.write(msg)
314 projects_cfg.PROJECTS.projects.addMapping(project_name,
315 src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
316 "The %s project\n" % project_name)
317 projects_cfg.PROJECTS.projects[project_name]=project_cfg
318 projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
321 merger.merge(cfg, projects_cfg)
323 # apply overwrite from command line if needed
324 for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
325 exec('cfg.' + rule) # this cannot be factorized because of the exec
327 # =====================================================================
328 # Create the paths where to search the application configurations,
329 # the product configurations, the products archives,
330 # the jobs configurations and the machines configurations
331 cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
332 cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
333 cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
335 cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
336 cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
337 cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
338 cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
339 cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
340 cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
341 cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
342 cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
343 # Loop over the projects in order to complete the PATHS variables
344 for project in cfg.PROJECTS.projects:
345 for PATH in ["APPLICATIONPATH",
350 if PATH not in cfg.PROJECTS.projects[project]:
352 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
354 # apply overwrite from command line if needed
355 for rule in self.get_command_line_overrides(options, ["PATHS"]):
356 exec('cfg.' + rule) # this cannot be factorized because of the exec
358 # =====================================================================
359 # Load APPLICATION config file
360 if application is not None:
361 # search APPLICATION file in all directories in configPath
362 cp = cfg.PATHS.APPLICATIONPATH
363 src.pyconf.streamOpener = ConfigOpener(cp)
366 application_cfg = src.pyconf.Config(application + '.pyconf')
368 raise src.SatException(_("%s, use 'config --list' to get the"
369 " list of available applications.") %e)
370 except src.pyconf.ConfigError as e:
371 if (not ('-e' in parser.parse_args()[1])
372 or ('--edit' in parser.parse_args()[1])
373 and command == 'config'):
374 raise src.SatException(_("Error in configuration file: "
375 "%(application)s.pyconf\n "
377 { 'application': application, 'error': str(e) } )
379 sys.stdout.write(src.printcolors.printcWarning(
380 "There is an error in the file"
381 " %s.pyconf.\n" % cfg.VARS.application))
383 except Exception as e:
384 if (not ('-e' in parser.parse_args()[1])
385 or ('--edit' in parser.parse_args()[1])
386 and command == 'config'):
387 sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
388 raise src.SatException(_("Error in configuration file:"
389 " %(application)s.pyconf\n") % \
390 { 'application': application} )
392 sys.stdout.write(src.printcolors.printcWarning(
393 "There is an error in the file"
394 " %s.pyconf. Opening the file with the"
395 " default viewer\n" % cfg.VARS.application))
396 sys.stdout.write("The error:"
397 " %s\n" % src.printcolors.printcWarning(
402 cfg['open_application'] = 'yes'
404 # =====================================================================
405 # Load product config files in PRODUCTS section
406 products_cfg = src.pyconf.Config()
407 products_cfg.addMapping("PRODUCTS",
408 src.pyconf.Mapping(products_cfg),
410 if application is not None:
411 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
412 for product_name in application_cfg.APPLICATION.products.keys():
413 # Loop on all files that are in softsDir directory
414 # and read their config
415 product_file_name = product_name + ".pyconf"
416 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
417 if product_file_path:
418 products_dir = os.path.dirname(product_file_path)
420 prod_cfg = src.pyconf.Config(open(product_file_path),
421 PWD=("", products_dir))
422 prod_cfg.from_file = product_file_path
423 products_cfg.PRODUCTS[product_name] = prod_cfg
424 except Exception as e:
426 "WARNING: Error in configuration file"
427 ": %(prod)s\n %(error)s" % \
428 {'prod' : product_name, 'error': str(e) })
429 sys.stdout.write(msg)
431 merger.merge(cfg, products_cfg)
433 # apply overwrite from command line if needed
434 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
435 exec('cfg.' + rule) # this cannot be factorized because of the exec
438 merger.merge(cfg, application_cfg)
440 # default launcher name ('salome')
441 if ('profile' in cfg.APPLICATION and
442 'launcher_name' not in cfg.APPLICATION.profile):
443 cfg.APPLICATION.profile.launcher_name = 'salome'
445 # apply overwrite from command line if needed
446 for rule in self.get_command_line_overrides(options,
448 # this cannot be factorized because of the exec
451 # =====================================================================
453 self.set_user_config_file(cfg)
454 user_cfg_file = self.get_user_config_file()
455 user_cfg = src.pyconf.Config(open(user_cfg_file))
456 merger.merge(cfg, user_cfg)
458 # apply overwrite from command line if needed
459 for rule in self.get_command_line_overrides(options, ["USER"]):
460 exec('cfg.' + rule) # this cannot be factorize because of the exec
464 def set_user_config_file(self, config):
465 '''Set the user config file name and path.
466 If necessary, build it from another one or create it from scratch.
468 :param config class 'src.pyconf.Config': The global config
469 (containing all pyconf).
471 # get the expected name and path of the file
472 self.config_file_name = 'SAT.pyconf'
473 self.user_config_file_path = os.path.join(config.VARS.personalDir,
474 self.config_file_name)
476 # if pyconf does not exist, create it from scratch
477 if not os.path.isfile(self.user_config_file_path):
478 self.create_config_file(config)
480 def create_config_file(self, config):
481 '''This method is called when there are no user config file.
482 It build it from scratch.
484 :param config class 'src.pyconf.Config': The global config.
485 :return: the config corresponding to the file created.
486 :rtype: config class 'src.pyconf.Config'
489 cfg_name = self.get_user_config_file()
491 user_cfg = src.pyconf.Config()
493 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
495 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
496 "This is the user name used to access salome cvs base.\n")
497 user_cfg.USER.addMapping('svn_user', config.VARS.user,
498 "This is the user name used to access salome svn base.\n")
499 user_cfg.USER.addMapping('output_verbose_level', 3,
500 "This is the default output_verbose_level you want."
501 " 0=>no output, 5=>debug.\n")
502 user_cfg.USER.addMapping('publish_dir',
503 os.path.join(os.path.expanduser('~'),
507 user_cfg.USER.addMapping('editor',
509 "This is the editor used to "
510 "modify configuration files\n")
511 user_cfg.USER.addMapping('browser',
513 "This is the browser used to "
514 "read html documentation\n")
515 user_cfg.USER.addMapping('pdf_viewer',
517 "This is the pdf_viewer used "
518 "to read pdf documentation\n")
519 user_cfg.USER.addMapping("base",
520 src.pyconf.Reference(
523 'workdir + $VARS.sep + "BASE"'),
524 "The products installation base (could be "
525 "ignored if this key exists in the local.pyconf"
526 " file of salomTools).\n")
529 src.ensure_path_exists(config.VARS.personalDir)
530 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
533 f = open(cfg_name, 'w')
539 def get_user_config_file(self):
540 '''Get the user config file
541 :return: path to the user config file.
544 if not self.user_config_file_path:
545 raise src.SatException(_("Error in get_user_config_file: "
546 "missing user config file path"))
547 return self.user_config_file_path
549 def check_path(path, ext=[]):
550 '''Construct a text with the input path and "not found" if it does not
553 :param path Str: the path to check.
554 :param ext List: An extension. Verify that the path extension
556 :return: The string of the path with information
559 # check if file exists
560 if not os.path.exists(path):
561 return "'%s'" % path + " " + src.printcolors.printcError(_(
566 fe = os.path.splitext(path)[1].lower()
568 return "'%s'" % path + " " + src.printcolors.printcError(_(
573 def show_product_info(config, name, logger):
574 '''Display on the terminal and logger information about a product.
576 :param config Config: the global configuration.
577 :param name Str: The name of the product
578 :param logger Logger: The logger instance to use for the display
581 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
582 pinfo = src.product.get_product_config(config, name)
584 if "depend" in pinfo:
585 src.printcolors.print_value(logger,
587 ', '.join(pinfo.depend), 2)
589 if "opt_depend" in pinfo:
590 src.printcolors.print_value(logger,
592 ', '.join(pinfo.opt_depend), 2)
594 # information on pyconf
595 logger.write("\n", 2)
596 logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
597 if "from_file" in pinfo:
598 src.printcolors.print_value(logger,
602 if "section" in pinfo:
603 src.printcolors.print_value(logger,
608 # information on prepare
609 logger.write("\n", 2)
610 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
612 is_dev = src.product.product_is_dev(pinfo)
613 method = pinfo.get_source
616 src.printcolors.print_value(logger, "get method", method, 2)
619 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
620 src.printcolors.print_value(logger, "base module",
621 pinfo.cvs_info.module_base, 2)
622 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
623 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
625 elif method == 'svn':
626 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
628 elif method == 'git':
629 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
630 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
632 elif method == 'archive':
633 src.printcolors.print_value(logger,
635 check_path(pinfo.archive_info.archive_name),
638 if 'patches' in pinfo:
639 for patch in pinfo.patches:
640 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
642 if src.product.product_is_fixed(pinfo):
643 src.printcolors.print_value(logger, "install_dir",
644 check_path(pinfo.install_dir), 2)
646 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
649 # information on compilation
650 if src.product.product_compiles(pinfo):
651 logger.write("\n", 2)
652 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
653 src.printcolors.print_value(logger,
654 "compilation method",
658 if pinfo.build_source == "script" and "compil_script" in pinfo:
659 src.printcolors.print_value(logger,
660 "Compilation script",
664 if 'nb_proc' in pinfo:
665 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
667 src.printcolors.print_value(logger,
669 check_path(pinfo.source_dir),
671 if 'install_dir' in pinfo:
672 src.printcolors.print_value(logger,
674 check_path(pinfo.build_dir),
676 src.printcolors.print_value(logger,
678 check_path(pinfo.install_dir),
682 src.printcolors.printcWarning(_("no install dir")) +
685 logger.write("\n", 2)
686 msg = _("This product does not compile")
687 logger.write("%s\n" % msg, 2)
689 # information on environment
690 logger.write("\n", 2)
691 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
692 if "environ" in pinfo and "env_script" in pinfo.environ:
693 src.printcolors.print_value(logger,
695 check_path(pinfo.environ.env_script),
698 zz = src.environment.SalomeEnviron(config,
699 src.fileEnviron.ScreenEnviron(logger),
701 zz.set_python_libdirs()
702 zz.set_a_product(name, logger)
704 def show_patchs(config, logger):
705 '''Prints all the used patchs in the application.
707 :param config Config: the global configuration.
708 :param logger Logger: The logger instance to use for the display
710 len_max = max([len(p) for p in config.APPLICATION.products]) + 2
711 for product in config.APPLICATION.products:
712 product_info = src.product.get_product_config(config, product)
713 if src.product.product_has_patches(product_info):
714 logger.write("%s: " % product, 1)
715 logger.write(src.printcolors.printcInfo(
716 " " * (len_max - len(product) -2) +
717 "%s\n" % product_info.patches[0]),
719 if len(product_info.patches) > 1:
720 for patch in product_info.patches[1:]:
721 logger.write(src.printcolors.printcInfo(len_max*" " +
723 logger.write("\n", 1)
725 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
726 '''Prints a value from the configuration. Prints recursively the values
727 under the initial path.
729 :param config class 'src.pyconf.Config': The configuration
730 from which the value is displayed.
731 :param path str : the path in the configuration of the value to print.
732 :param show_label boolean: if True, do a basic display.
733 (useful for bash completion)
734 :param logger Logger: the logger instance
735 :param level int: The number of spaces to add before display.
736 :param show_full_path :
739 # Make sure that the path does not ends with a point
740 if path.endswith('.'):
743 # display all the path or not
747 vname = path.split('.')[-1]
749 # number of spaces before the display
750 tab_level = " " * level
752 # call to the function that gets the value of the path.
754 val = config.getByPath(path)
755 except Exception as e:
756 logger.write(tab_level)
757 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
758 src.printcolors.printcError(str(e))))
761 # in this case, display only the value
763 logger.write(tab_level)
764 logger.write("%s: " % src.printcolors.printcLabel(vname))
766 # The case where the value has under values,
767 # do a recursive call to the function
768 if dir(val).__contains__('keys'):
769 if show_label: logger.write("\n")
770 for v in sorted(val.keys()):
771 print_value(config, path + '.' + v, show_label, logger, level + 1)
772 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
773 # in this case, value is a list (or a Sequence)
774 if show_label: logger.write("\n")
777 print_value(config, path + "[" + str(index) + "]",
778 show_label, logger, level + 1)
780 else: # case where val is just a str
781 logger.write("%s\n" % val)
783 def get_config_children(config, args):
784 '''Gets the names of the children of the given parameter.
785 Useful only for completion mechanism
787 :param config Config: The configuration where to read the values
788 :param args: The path in the config from which get the keys
791 rootkeys = config.keys()
794 # no parameter returns list of root keys
798 pos = parent.rfind('.')
800 # Case where there is only on key as parameter.
802 vals = [m for m in rootkeys if m.startswith(parent)]
804 # Case where there is a part from a key
805 # for example VARS.us (for VARS.user)
807 tail = parent[pos+1:]
809 a = config.getByPath(head)
810 if dir(a).__contains__('keys'):
811 vals = map(lambda x: head + '.' + x,
812 [m for m in a.keys() if m.startswith(tail)])
816 for v in sorted(vals):
817 sys.stdout.write("%s\n" % v)
820 '''method that is called when salomeTools is called with --help option.
822 :return: The text to display for the config command description.
825 return _("The config command allows manipulation "
826 "and operation on config files.\n\nexample:\nsat config "
827 "SALOME-master --info ParaView")
830 def run(args, runner, logger):
831 '''method that is called when salomeTools is called with config parameter.
834 (options, args) = parser.parse_args(args)
836 # Only useful for completion mechanism : print the keys of the config
838 get_config_children(runner.cfg, args)
841 # case : print a value of the config
843 if options.value == ".":
844 # if argument is ".", print all the config
845 for val in sorted(runner.cfg.keys()):
846 print_value(runner.cfg, val, not options.no_label, logger)
848 print_value(runner.cfg, options.value, not options.no_label, logger,
849 level=0, show_full_path=False)
851 # case : edit user pyconf file or application file
853 editor = runner.cfg.USER.editor
854 if ('APPLICATION' not in runner.cfg and
855 'open_application' not in runner.cfg): # edit user pyconf
856 usercfg = os.path.join(runner.cfg.VARS.personalDir,
858 logger.write(_("Openning %s\n" % usercfg), 3)
859 src.system.show_in_editor(editor, usercfg, logger)
861 # search for file <application>.pyconf and open it
862 for path in runner.cfg.PATHS.APPLICATIONPATH:
863 pyconf_path = os.path.join(path,
864 runner.cfg.VARS.application + ".pyconf")
865 if os.path.exists(pyconf_path):
866 logger.write(_("Openning %s\n" % pyconf_path), 3)
867 src.system.show_in_editor(editor, pyconf_path, logger)
870 # case : give information about the product in parameter
872 src.check_config_has_application(runner.cfg)
873 if options.info in runner.cfg.APPLICATION.products:
874 show_product_info(runner.cfg, options.info, logger)
876 raise src.SatException(_("%(product_name)s is not a product "
877 "of %(application_name)s.") %
878 {'product_name' : options.info,
880 runner.cfg.VARS.application})
882 # case : copy an existing <application>.pyconf
883 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
885 # product is required
886 src.check_config_has_application( runner.cfg )
888 # get application file path
889 source = runner.cfg.VARS.application + '.pyconf'
890 source_full_path = ""
891 for path in runner.cfg.PATHS.APPLICATIONPATH:
892 # ignore personal directory
893 if path == runner.cfg.VARS.personalDir:
895 # loop on all directories that can have pyconf applications
896 zz = os.path.join(path, source)
897 if os.path.exists(zz):
898 source_full_path = zz
901 if len(source_full_path) == 0:
902 raise src.SatException(_(
903 "Config file for product %s not found\n") % source)
906 # a name is given as parameter, use it
908 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
910 dest = (runner.cfg.INTERNAL.config.copy_prefix
911 + runner.cfg.VARS.application)
913 # use same name as source
914 dest = runner.cfg.VARS.application
917 dest_file = os.path.join(runner.cfg.VARS.personalDir,
918 'Applications', dest + '.pyconf')
919 if os.path.exists(dest_file):
920 raise src.SatException(_("A personal application"
921 " '%s' already exists") % dest)
924 shutil.copyfile(source_full_path, dest_file)
925 logger.write(_("%s has been created.\n") % dest_file)
927 # case : display all the available pyconf applications
930 # search in all directories that can have pyconf applications
931 for path in runner.cfg.PATHS.APPLICATIONPATH:
933 if not options.no_label:
934 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
936 if not os.path.exists(path):
937 logger.write(src.printcolors.printcError(_(
938 "Directory not found")) + "\n")
940 for f in sorted(os.listdir(path)):
941 # ignore file that does not ends with .pyconf
942 if not f.endswith('.pyconf'):
945 appliname = f[:-len('.pyconf')]
946 if appliname not in lproduct:
947 lproduct.append(appliname)
948 if path.startswith(runner.cfg.VARS.personalDir) \
949 and not options.no_label:
950 logger.write("%s*\n" % appliname)
952 logger.write("%s\n" % appliname)
955 # case : give a synthetic view of all patches used in the application
956 elif options.show_patchs:
957 src.check_config_has_application(runner.cfg)
958 # Print some informations
959 logger.write(_('Show the patchs of application %s\n') %
960 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
961 logger.write("\n", 2, False)
962 show_patchs(runner.cfg, logger)
964 # case: print all the products name of the application (internal use for completion)
965 elif options.completion:
966 for product_name in runner.cfg.APPLICATION.products.keys():
967 logger.write("%s\n" % product_name)