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('s', 'schema', 'boolean', 'schema',
54 '''Class that helps to find an application pyconf
55 in all the possible directories (pathList)
57 def __init__(self, pathList):
60 :param pathList list: The list of paths where to search a pyconf.
62 self.pathList = pathList
64 def __call__(self, name):
65 if os.path.isabs(name):
66 return src.pyconf.ConfigInputStream(open(name, 'rb'))
68 return src.pyconf.ConfigInputStream(
69 open(os.path.join( self.get_path(name), name ), 'rb') )
70 raise IOError(_("Configuration file '%s' not found") % name)
72 def get_path( self, name ):
73 '''The method that returns the entire path of the pyconf searched
74 :param name str: The name of the searched pyconf.
76 for path in self.pathList:
77 if os.path.exists(os.path.join(path, name)):
79 raise IOError(_("Configuration file '%s' not found") % name)
82 '''Class that manages the read of all the configuration files of salomeTools
84 def __init__(self, datadir=None):
87 def _create_vars(self, application=None, command=None, datadir=None):
88 '''Create a dictionary that stores all information about machine,
89 user, date, repositories, etc...
91 :param application str: The application for which salomeTools is called.
92 :param command str: The command that is called.
93 :param datadir str: The repository that contain external data
95 :return: The dictionary that stores all information.
99 var['user'] = src.architecture.get_user()
100 var['salometoolsway'] = os.path.dirname(
101 os.path.dirname(os.path.abspath(__file__)))
102 var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
103 var['internal_dir'] = os.path.join(var['srcDir'], 'internal_config')
104 var['sep']= os.path.sep
106 # datadir has a default location
107 var['datadir'] = os.path.join(var['salometoolsway'], 'data')
108 if datadir is not None:
109 var['datadir'] = datadir
111 var['personalDir'] = os.path.join(os.path.expanduser('~'),
113 src.ensure_path_exists(var['personalDir'])
115 var['personal_applications_dir'] = os.path.join(var['personalDir'],
117 src.ensure_path_exists(var['personal_applications_dir'])
119 var['personal_products_dir'] = os.path.join(var['personalDir'],
121 src.ensure_path_exists(var['personal_products_dir'])
123 var['personal_archives_dir'] = os.path.join(var['personalDir'],
125 src.ensure_path_exists(var['personal_archives_dir'])
127 var['personal_jobs_dir'] = os.path.join(var['personalDir'],
129 src.ensure_path_exists(var['personal_jobs_dir'])
131 var['personal_machines_dir'] = os.path.join(var['personalDir'],
133 src.ensure_path_exists(var['personal_machines_dir'])
135 # read linux distributions dictionary
136 distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
140 # set platform parameters
141 dist_name = src.architecture.get_distribution(
142 codes=distrib_cfg.DISTRIBUTIONS)
143 dist_version = src.architecture.get_distrib_version(dist_name,
144 codes=distrib_cfg.VERSIONS)
145 dist = dist_name + dist_version
147 var['dist_name'] = dist_name
148 var['dist_version'] = dist_version
150 var['python'] = src.architecture.get_python_version()
152 var['nb_proc'] = src.architecture.get_nb_proc()
153 node_name = platform.node()
154 var['node'] = node_name
155 var['hostname'] = node_name
157 # set date parameters
158 dt = datetime.datetime.now()
159 var['date'] = dt.strftime('%Y%m%d')
160 var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
161 var['hour'] = dt.strftime('%H%M%S')
163 var['command'] = str(command)
164 var['application'] = str(application)
166 # Root dir for temporary files
167 var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
168 # particular win case
169 if src.architecture.is_windows() :
170 var['tmp_root'] = os.path.expanduser('~') + os.sep + 'tmp'
174 def get_command_line_overrides(self, options, sections):
175 '''get all the overwrites that are in the command line
177 :param options: the options from salomeTools class
178 initialization (like -l5 or --overwrite)
179 :param sections str: The config section to overwrite.
180 :return: The list of all the overwrites to apply.
183 # when there are no options or not the overwrite option,
184 # return an empty list
185 if options is None or options.overwrite is None:
189 for section in sections:
190 # only overwrite the sections that correspond to the option
191 over.extend(filter(lambda l: l.startswith(section + "."),
195 def get_config(self, application=None, options=None, command=None,
197 '''get the config from all the configuration files.
199 :param application str: The application for which salomeTools is called.
200 :param options class Options: The general salomeToos
201 options (--overwrite or -l5, for example)
202 :param command str: The command that is called.
203 :param datadir str: The repository that contain
204 external data for salomeTools.
205 :return: The final config.
206 :rtype: class 'src.pyconf.Config'
209 # create a ConfigMerger to handle merge
210 merger = src.pyconf.ConfigMerger()#MergeHandler())
212 # create the configuration instance
213 cfg = src.pyconf.Config()
215 # =====================================================================
216 # create VARS section
217 var = self._create_vars(application=application, command=command,
220 cfg.VARS = src.pyconf.Mapping(cfg)
222 cfg.VARS[variable] = var[variable]
224 # apply overwrite from command line if needed
225 for rule in self.get_command_line_overrides(options, ["VARS"]):
226 exec('cfg.' + rule) # this cannot be factorized because of the exec
228 # =====================================================================
229 # Load INTERNAL config
230 # read src/internal_config/salomeTools.pyconf
231 src.pyconf.streamOpener = ConfigOpener([
232 os.path.join(cfg.VARS.srcDir, 'internal_config')])
234 internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir,
235 'internal_config', 'salomeTools.pyconf')))
236 except src.pyconf.ConfigError as e:
237 raise src.SatException(_("Error in configuration file:"
238 " salomeTools.pyconf\n %(error)s") % \
241 merger.merge(cfg, internal_cfg)
243 # apply overwrite from command line if needed
244 for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
245 exec('cfg.' + rule) # this cannot be factorized because of the exec
247 # =====================================================================
248 # Load SITE config file
249 # search only in the data directory
250 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
252 site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir,
254 PWD = ('SITE', cfg.VARS.datadir) )
255 except src.pyconf.ConfigError as e:
256 raise src.SatException(_("Error in configuration file: "
257 "site.pyconf\n %(error)s") % \
259 except IOError as error:
261 if "site.pyconf" in e :
262 e += ("\nYou can copy data"
264 + "site.template.pyconf to data"
266 + "site.pyconf and edit the file")
267 raise src.SatException( e );
268 merger.merge(cfg, site_cfg)
270 # apply overwrite from command line if needed
271 for rule in self.get_command_line_overrides(options, ["SITE"]):
272 exec('cfg.' + rule) # this cannot be factorized because of the exec
274 # =====================================================================
276 projects_cfg = src.pyconf.Config()
277 projects_cfg.addMapping("PROJECTS",
278 src.pyconf.Mapping(projects_cfg),
280 projects_cfg.PROJECTS.addMapping("projects",
281 src.pyconf.Mapping(cfg.PROJECTS),
282 "The projects definition\n")
284 for project_pyconf_path in cfg.PROJECTS.project_file_paths:
285 if not os.path.exists(project_pyconf_path):
286 msg = _("WARNING: The project file %s cannot be found. "
287 "It will be ignored\n" % project_pyconf_path)
288 sys.stdout.write(msg)
290 project_name = os.path.basename(
291 project_pyconf_path)[:-len(".pyconf")]
293 project_pyconf_dir = os.path.dirname(project_pyconf_path)
294 project_cfg = src.pyconf.Config(open(project_pyconf_path),
295 PWD=("", project_pyconf_dir))
296 except Exception as e:
297 raise src.SatException(_("Error in configuration file: "
298 "%(file_path)s\n %(error)s") % \
299 {'file_path' : project_pyconf_path, 'error': str(e) })
300 projects_cfg.PROJECTS.projects.addMapping(project_name,
301 src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
302 "The %s project\n" % project_name)
303 projects_cfg.PROJECTS.projects[project_name]=project_cfg
304 projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
307 merger.merge(cfg, projects_cfg)
309 # apply overwrite from command line if needed
310 for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
311 exec('cfg.' + rule) # this cannot be factorized because of the exec
313 # =====================================================================
314 # Create the paths where to search the application configurations,
315 # the product configurations, the products archives,
316 # the jobs configurations and the machines configurations
317 cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
318 cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
319 cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
321 cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
322 cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
323 cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
324 cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
325 cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
326 cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
327 cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
328 cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
329 # Loop over the projects in order to complete the PATHS variables
330 for project in cfg.PROJECTS.projects:
331 for PATH in ["APPLICATIONPATH",
336 if PATH not in cfg.PROJECTS.projects[project]:
338 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
340 # apply overwrite from command line if needed
341 for rule in self.get_command_line_overrides(options, ["PATHS"]):
342 exec('cfg.' + rule) # this cannot be factorized because of the exec
344 # =====================================================================
345 # Load product config files in PRODUCTS section
346 products_cfg = src.pyconf.Config()
347 products_cfg.addMapping("PRODUCTS",
348 src.pyconf.Mapping(products_cfg),
350 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
351 for products_dir in cfg.PATHS.PRODUCTPATH:
352 # Loop on all files that are in softsDir directory
353 # and read their config
354 for fName in os.listdir(products_dir):
355 if fName.endswith(".pyconf"):
356 pName = fName[:-len(".pyconf")]
357 if pName in products_cfg.PRODUCTS:
360 prod_cfg = src.pyconf.Config(open(
361 os.path.join(products_dir,
363 PWD=("", products_dir))
364 except src.pyconf.ConfigError as e:
365 raise src.SatException(_(
366 "Error in configuration file: %(prod)s\n %(error)s") % \
367 {'prod' : fName, 'error': str(e) })
368 except IOError as error:
370 raise src.SatException( e );
371 except Exception as e:
372 raise src.SatException(_(
373 "Error in configuration file: %(prod)s\n %(error)s") % \
374 {'prod' : fName, 'error': str(e) })
376 products_cfg.PRODUCTS[pName] = prod_cfg
378 merger.merge(cfg, products_cfg)
380 # apply overwrite from command line if needed
381 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
382 exec('cfg.' + rule) # this cannot be factorized because of the exec
384 # =====================================================================
385 # Load APPLICATION config file
386 if application is not None:
387 # search APPLICATION file in all directories in configPath
388 cp = cfg.PATHS.APPLICATIONPATH
389 src.pyconf.streamOpener = ConfigOpener(cp)
392 application_cfg = src.pyconf.Config(application + '.pyconf')
394 raise src.SatException(_("%s, use 'config --list' to get the"
395 " list of available applications.") %e)
396 except src.pyconf.ConfigError as e:
397 if (not ('-e' in parser.parse_args()[1])
398 or ('--edit' in parser.parse_args()[1])
399 and command == 'config'):
400 raise src.SatException(_("Error in configuration file: "
401 "%(application)s.pyconf\n "
403 { 'application': application, 'error': str(e) } )
405 sys.stdout.write(src.printcolors.printcWarning(
406 "There is an error in the file"
407 " %s.pyconf.\n" % cfg.VARS.application))
409 except Exception as e:
410 if (not ('-e' in parser.parse_args()[1])
411 or ('--edit' in parser.parse_args()[1])
412 and command == 'config'):
413 sys.stdout.write(src.printcolors.printcWarning("%s\n" % str(e)))
414 raise src.SatException(_("Error in configuration file:"
415 " %(application)s.pyconf\n") % \
416 { 'application': application} )
418 sys.stdout.write(src.printcolors.printcWarning(
419 "There is an error in the file"
420 " %s.pyconf. Opening the file with the"
421 " default viewer\n" % cfg.VARS.application))
422 sys.stdout.write("The error:"
423 " %s\n" % src.printcolors.printcWarning(
428 merger.merge(cfg, application_cfg)
430 # apply overwrite from command line if needed
431 for rule in self.get_command_line_overrides(options,
433 # this cannot be factorized because of the exec
436 # default launcher name ('salome')
437 if ('profile' in cfg.APPLICATION and
438 'launcher_name' not in cfg.APPLICATION.profile):
439 cfg.APPLICATION.profile.launcher_name = 'salome'
442 cfg['open_application'] = 'yes'
445 # =====================================================================
447 self.set_user_config_file(cfg)
448 user_cfg_file = self.get_user_config_file()
449 user_cfg = src.pyconf.Config(open(user_cfg_file))
450 merger.merge(cfg, user_cfg)
452 # apply overwrite from command line if needed
453 for rule in self.get_command_line_overrides(options, ["USER"]):
454 exec('cfg.' + rule) # this cannot be factorize because of the exec
458 def set_user_config_file(self, config):
459 '''Set the user config file name and path.
460 If necessary, build it from another one or create it from scratch.
462 :param config class 'src.pyconf.Config': The global config
463 (containing all pyconf).
465 # get the expected name and path of the file
466 self.config_file_name = 'salomeTools.pyconf'
467 self.user_config_file_path = os.path.join(config.VARS.personalDir,
468 self.config_file_name)
470 # if pyconf does not exist, create it from scratch
471 if not os.path.isfile(self.user_config_file_path):
472 self.create_config_file(config)
474 def create_config_file(self, config):
475 '''This method is called when there are no user config file.
476 It build it from scratch.
478 :param config class 'src.pyconf.Config': The global config.
479 :return: the config corresponding to the file created.
480 :rtype: config class 'src.pyconf.Config'
483 cfg_name = self.get_user_config_file()
485 user_cfg = src.pyconf.Config()
487 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
490 user_cfg.USER.addMapping('workdir', os.path.expanduser('~'),
491 "This is where salomeTools will work. "
492 "You may (and probably do) change it.\n")
493 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
494 "This is the user name used to access salome cvs base.\n")
495 user_cfg.USER.addMapping('svn_user', config.VARS.user,
496 "This is the user name used to access salome svn base.\n")
497 user_cfg.USER.addMapping('output_verbose_level', 3,
498 "This is the default output_verbose_level you want."
499 " 0=>no output, 5=>debug.\n")
500 user_cfg.USER.addMapping('publish_dir',
501 os.path.join(os.path.expanduser('~'),
505 user_cfg.USER.addMapping('editor',
507 "This is the editor used to "
508 "modify configuration files\n")
509 user_cfg.USER.addMapping('browser',
511 "This is the browser used to "
512 "read html documentation\n")
513 user_cfg.USER.addMapping('pdf_viewer',
515 "This is the pdf_viewer used "
516 "to read pdf documentation\n")
517 user_cfg.USER.addMapping("base",
518 src.pyconf.Reference(
521 'workdir + $VARS.sep + "BASE"'),
522 "The products installation base (could be "
523 "ignored if this key exists in the site.pyconf"
524 " file of salomTools).\n")
526 user_cfg.USER.addMapping("log_dir",
527 src.pyconf.Reference(
530 'workdir + $VARS.sep + "LOGS"'),
531 "The log repository\n")
534 src.ensure_path_exists(config.VARS.personalDir)
535 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
538 f = open(cfg_name, 'w')
544 def get_user_config_file(self):
545 '''Get the user config file
546 :return: path to the user config file.
549 if not self.user_config_file_path:
550 raise src.SatException(_("Error in get_user_config_file: "
551 "missing user config file path"))
552 return self.user_config_file_path
554 def check_path(path, ext=[]):
555 '''Construct a text with the input path and "not found" if it does not
558 :param path Str: the path to check.
559 :param ext List: An extension. Verify that the path extension
561 :return: The string of the path with information
564 # check if file exists
565 if not os.path.exists(path):
566 return "'%s'" % path + " " + src.printcolors.printcError(_(
571 fe = os.path.splitext(path)[1].lower()
573 return "'%s'" % path + " " + src.printcolors.printcError(_(
578 def show_product_info(config, name, logger):
579 '''Display on the terminal and logger information about a product.
581 :param config Config: the global configuration.
582 :param name Str: The name of the product
583 :param logger Logger: The logger instance to use for the display
586 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
587 pinfo = src.product.get_product_config(config, name)
589 # Type of the product
590 ptype = src.get_cfg_param(pinfo, "type", "")
591 src.printcolors.print_value(logger, "type", ptype, 2)
592 if "depend" in pinfo:
593 src.printcolors.print_value(logger,
595 ', '.join(pinfo.depend), 2)
597 if "opt_depend" in pinfo:
598 src.printcolors.print_value(logger,
600 ', '.join(pinfo.opt_depend), 2)
602 # information on prepare
603 logger.write("\n", 2)
604 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
606 is_dev = src.product.product_is_dev(pinfo)
607 method = pinfo.get_source
610 src.printcolors.print_value(logger, "get method", method, 2)
613 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
614 src.printcolors.print_value(logger, "base module",
615 pinfo.cvs_info.module_base, 2)
616 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
617 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
619 elif method == 'svn':
620 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
622 elif method == 'git':
623 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
624 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
626 elif method == 'archive':
627 src.printcolors.print_value(logger,
629 check_path(pinfo.archive_info.archive_name),
632 if 'patches' in pinfo:
633 for patch in pinfo.patches:
634 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
636 if src.product.product_is_fixed(pinfo):
637 src.printcolors.print_value(logger, "install_dir",
638 check_path(pinfo.install_dir), 2)
640 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
643 # information on compilation
644 if src.product.product_compiles(pinfo):
645 logger.write("\n", 2)
646 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
647 src.printcolors.print_value(logger,
648 "compilation method",
652 if pinfo.build_source == "script" and "compil_script" in pinfo:
653 src.printcolors.print_value(logger,
654 "Compilation script",
658 if 'nb_proc' in pinfo:
659 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
661 src.printcolors.print_value(logger,
663 check_path(pinfo.source_dir),
665 if 'install_dir' in pinfo:
666 src.printcolors.print_value(logger,
668 check_path(pinfo.build_dir),
670 src.printcolors.print_value(logger,
672 check_path(pinfo.install_dir),
676 src.printcolors.printcWarning(_("no install dir")) +
679 logger.write("\n", 2)
680 msg = _("This product does not compile")
681 logger.write("%s\n" % msg, 2)
683 # information on environment
684 logger.write("\n", 2)
685 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
686 if "environ" in pinfo and "env_script" in pinfo.environ:
687 src.printcolors.print_value(logger,
689 check_path(pinfo.environ.env_script),
692 zz = src.environment.SalomeEnviron(config,
693 src.fileEnviron.ScreenEnviron(logger),
695 zz.set_python_libdirs()
696 zz.set_a_product(name, logger)
698 def show_patchs(config, logger):
699 '''Prints all the used patchs in the application.
701 :param config Config: the global configuration.
702 :param logger Logger: The logger instance to use for the display
704 len_max = max([len(p) for p in config.APPLICATION.products]) + 2
705 for product in config.APPLICATION.products:
706 product_info = src.product.get_product_config(config, product)
707 if src.product.product_has_patches(product_info):
708 logger.write("%s: " % product, 1)
709 logger.write(src.printcolors.printcInfo(
710 " " * (len_max - len(product) -2) +
711 "%s\n" % product_info.patches[0]),
713 if len(product_info.patches) > 1:
714 for patch in product_info.patches[1:]:
715 logger.write(src.printcolors.printcInfo(len_max*" " +
717 logger.write("\n", 1)
719 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
720 '''Prints a value from the configuration. Prints recursively the values
721 under the initial path.
723 :param config class 'src.pyconf.Config': The configuration
724 from which the value is displayed.
725 :param path str : the path in the configuration of the value to print.
726 :param show_label boolean: if True, do a basic display.
727 (useful for bash completion)
728 :param logger Logger: the logger instance
729 :param level int: The number of spaces to add before display.
730 :param show_full_path :
733 # Make sure that the path does not ends with a point
734 if path.endswith('.'):
737 # display all the path or not
741 vname = path.split('.')[-1]
743 # number of spaces before the display
744 tab_level = " " * level
746 # call to the function that gets the value of the path.
748 val = config.getByPath(path)
749 except Exception as e:
750 logger.write(tab_level)
751 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
752 src.printcolors.printcError(str(e))))
755 # in this case, display only the value
757 logger.write(tab_level)
758 logger.write("%s: " % src.printcolors.printcLabel(vname))
760 # The case where the value has under values,
761 # do a recursive call to the function
762 if dir(val).__contains__('keys'):
763 if show_label: logger.write("\n")
764 for v in sorted(val.keys()):
765 print_value(config, path + '.' + v, show_label, logger, level + 1)
766 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
767 # in this case, value is a list (or a Sequence)
768 if show_label: logger.write("\n")
771 print_value(config, path + "[" + str(index) + "]",
772 show_label, logger, level + 1)
774 else: # case where val is just a str
775 logger.write("%s\n" % val)
777 def get_config_children(config, args):
778 '''Gets the names of the children of the given parameter.
779 Useful only for completion mechanism
781 :param config Config: The configuration where to read the values
782 :param args: The path in the config from which get the keys
785 rootkeys = config.keys()
788 # no parameter returns list of root keys
792 pos = parent.rfind('.')
794 # Case where there is only on key as parameter.
796 vals = [m for m in rootkeys if m.startswith(parent)]
798 # Case where there is a part from a key
799 # for example VARS.us (for VARS.user)
801 tail = parent[pos+1:]
803 a = config.getByPath(head)
804 if dir(a).__contains__('keys'):
805 vals = map(lambda x: head + '.' + x,
806 [m for m in a.keys() if m.startswith(tail)])
810 for v in sorted(vals):
811 sys.stdout.write("%s\n" % v)
814 '''method that is called when salomeTools is called with --help option.
816 :return: The text to display for the config command description.
819 return _("The config command allows manipulation "
820 "and operation on config files.\n\nexample:\nsat config "
821 "SALOME-master --info ParaView")
824 def run(args, runner, logger):
825 '''method that is called when salomeTools is called with config parameter.
828 (options, args) = parser.parse_args(args)
830 # Only useful for completion mechanism : print the keys of the config
832 get_config_children(runner.cfg, args)
835 # case : print a value of the config
837 if options.value == ".":
838 # if argument is ".", print all the config
839 for val in sorted(runner.cfg.keys()):
840 print_value(runner.cfg, val, not options.no_label, logger)
842 print_value(runner.cfg, options.value, not options.no_label, logger,
843 level=0, show_full_path=False)
845 # case : edit user pyconf file or application file
847 editor = runner.cfg.USER.editor
848 if ('APPLICATION' not in runner.cfg and
849 'open_application' not in runner.cfg): # edit user pyconf
850 usercfg = os.path.join(runner.cfg.VARS.personalDir,
851 'salomeTools.pyconf')
852 logger.write(_("Openning %s\n" % usercfg), 3)
853 src.system.show_in_editor(editor, usercfg, logger)
855 # search for file <application>.pyconf and open it
856 for path in runner.cfg.PATHS.APPLICATIONPATH:
857 pyconf_path = os.path.join(path,
858 runner.cfg.VARS.application + ".pyconf")
859 if os.path.exists(pyconf_path):
860 logger.write(_("Openning %s\n" % pyconf_path), 3)
861 src.system.show_in_editor(editor, pyconf_path, logger)
864 # case : give information about the product in parameter
866 src.check_config_has_application(runner.cfg)
867 if options.info in runner.cfg.APPLICATION.products:
868 show_product_info(runner.cfg, options.info, logger)
870 raise src.SatException(_("%(product_name)s is not a product "
871 "of %(application_name)s.") %
872 {'product_name' : options.info,
874 runner.cfg.VARS.application})
876 # case : copy an existing <application>.pyconf
877 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
879 # product is required
880 src.check_config_has_application( runner.cfg )
882 # get application file path
883 source = runner.cfg.VARS.application + '.pyconf'
884 source_full_path = ""
885 for path in runner.cfg.PATHS.APPLICATIONPATH:
886 # ignore personal directory
887 if path == runner.cfg.VARS.personalDir:
889 # loop on all directories that can have pyconf applications
890 zz = os.path.join(path, source)
891 if os.path.exists(zz):
892 source_full_path = zz
895 if len(source_full_path) == 0:
896 raise src.SatException(_(
897 "Config file for product %s not found\n") % source)
900 # a name is given as parameter, use it
902 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
904 dest = (runner.cfg.INTERNAL.config.copy_prefix
905 + runner.cfg.VARS.application)
907 # use same name as source
908 dest = runner.cfg.VARS.application
911 dest_file = os.path.join(runner.cfg.VARS.personalDir,
912 'Applications', dest + '.pyconf')
913 if os.path.exists(dest_file):
914 raise src.SatException(_("A personal application"
915 " '%s' already exists") % dest)
918 shutil.copyfile(source_full_path, dest_file)
919 logger.write(_("%s has been created.\n") % dest_file)
921 # case : display all the available pyconf applications
924 # search in all directories that can have pyconf applications
925 for path in runner.cfg.PATHS.APPLICATIONPATH:
927 if not options.no_label:
928 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
930 if not os.path.exists(path):
931 logger.write(src.printcolors.printcError(_(
932 "Directory not found")) + "\n")
934 for f in sorted(os.listdir(path)):
935 # ignore file that does not ends with .pyconf
936 if not f.endswith('.pyconf'):
939 appliname = f[:-len('.pyconf')]
940 if appliname not in lproduct:
941 lproduct.append(appliname)
942 if path.startswith(runner.cfg.VARS.personalDir) \
943 and not options.no_label:
944 logger.write("%s*\n" % appliname)
946 logger.write("%s\n" % appliname)
949 # case : give a synthetic view of all patches used in the application
950 elif options.show_patchs:
951 src.check_config_has_application(runner.cfg)
952 # Print some informations
953 logger.write(_('Show the patchs of application %s\n') %
954 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
955 logger.write("\n", 2, False)
956 show_patchs(runner.cfg, logger)