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
27 import src.debug as DBG
29 # internationalization
30 satdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
31 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
33 # Define all possible option for config command : sat config <options>
34 parser = src.options.Options()
35 parser.add_option('v', 'value', 'string', 'value',
36 _("Optional: print the value of CONFIG_VARIABLE."))
37 parser.add_option('g', 'debug', 'string', 'debug',
38 _("Optional: print the debugging mode value of CONFIG_VARIABLE."))
39 parser.add_option('e', 'edit', 'boolean', 'edit',
40 _("Optional: edit the product configuration file."))
41 parser.add_option('i', 'info', 'list2', 'info',
42 _("Optional: get information on product(s). This option accepts a comma separated list."))
43 parser.add_option('p', 'products', 'list2', 'products',
44 _("Optional: same as --info, for convenience."))
45 parser.add_option('l', 'list', 'boolean', 'list',
46 _("Optional: list all available applications."))
47 parser.add_option('', 'show_patchs', 'boolean', 'show_patchs',
48 _("Optional: synthetic list of all patches used in the application"))
49 parser.add_option('', 'show_properties', 'boolean', 'show_properties',
50 _("Optional: synthetic list of all properties used in the application"))
51 parser.add_option('c', 'copy', 'boolean', 'copy',
52 _("""Optional: copy a config file to the personal config files directory.
53 \tWARNING the included files are not copied.
54 \tIf a name is given the new config file takes the given name."""))
55 parser.add_option('n', 'no_label', 'boolean', 'no_label',
56 _("Internal use: do not print labels, Works only with --value and --list."))
57 parser.add_option('', 'completion', 'boolean', 'completion',
58 _("Internal use: print only keys, works only with --value."))
59 parser.add_option('s', 'schema', 'boolean', 'schema',
63 '''Class that helps to find an application pyconf
64 in all the possible directories (pathList)
66 def __init__(self, pathList):
69 :param pathList list: The list of paths where to search a pyconf.
71 self.pathList = pathList
73 def __call__(self, name):
74 if os.path.isabs(name):
75 return src.pyconf.ConfigInputStream(open(name, 'rb'))
77 return src.pyconf.ConfigInputStream(
78 open(os.path.join( self.get_path(name), name ), 'rb') )
79 raise IOError(_("Configuration file '%s' not found") % name)
81 def get_path( self, name ):
82 '''The method that returns the entire path of the pyconf searched
83 :param name str: The name of the searched pyconf.
85 for path in self.pathList:
86 if os.path.exists(os.path.join(path, name)):
88 raise IOError(_("Configuration file '%s' not found") % name)
91 '''Class that manages the read of all the configuration files of salomeTools
93 def __init__(self, datadir=None):
96 def _create_vars(self, application=None, command=None, datadir=None):
97 '''Create a dictionary that stores all information about machine,
98 user, date, repositories, etc...
100 :param application str: The application for which salomeTools is called.
101 :param command str: The command that is called.
102 :param datadir str: The repository that contain external data
104 :return: The dictionary that stores all information.
108 var['user'] = src.architecture.get_user()
109 var['salometoolsway'] = os.path.dirname(
110 os.path.dirname(os.path.abspath(__file__)))
111 var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
112 var['internal_dir'] = os.path.join(var['srcDir'], 'internal_config')
113 var['sep']= os.path.sep
115 # datadir has a default location
116 var['datadir'] = os.path.join(var['salometoolsway'], 'data')
117 if datadir is not None:
118 var['datadir'] = datadir
120 var['personalDir'] = os.path.join(os.path.expanduser('~'),
122 src.ensure_path_exists(var['personalDir'])
124 var['personal_applications_dir'] = os.path.join(var['personalDir'],
126 src.ensure_path_exists(var['personal_applications_dir'])
128 var['personal_products_dir'] = os.path.join(var['personalDir'],
130 src.ensure_path_exists(var['personal_products_dir'])
132 var['personal_archives_dir'] = os.path.join(var['personalDir'],
134 src.ensure_path_exists(var['personal_archives_dir'])
136 var['personal_jobs_dir'] = os.path.join(var['personalDir'],
138 src.ensure_path_exists(var['personal_jobs_dir'])
140 var['personal_machines_dir'] = os.path.join(var['personalDir'],
142 src.ensure_path_exists(var['personal_machines_dir'])
144 # read linux distributions dictionary
145 distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
149 # set platform parameters
150 dist_name = src.architecture.get_distribution(
151 codes=distrib_cfg.DISTRIBUTIONS)
152 dist_version = src.architecture.get_distrib_version(dist_name,
153 codes=distrib_cfg.VERSIONS)
154 dist = dist_name + dist_version
156 var['dist_name'] = dist_name
157 var['dist_version'] = dist_version
159 var['python'] = src.architecture.get_python_version()
161 var['nb_proc'] = src.architecture.get_nb_proc()
162 node_name = platform.node()
163 var['node'] = node_name
164 var['hostname'] = node_name
166 # set date parameters
167 dt = datetime.datetime.now()
168 var['date'] = dt.strftime('%Y%m%d')
169 var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
170 var['hour'] = dt.strftime('%H%M%S')
172 var['command'] = str(command)
173 var['application'] = str(application)
175 # Root dir for temporary files
176 var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
177 # particular win case
178 if src.architecture.is_windows() :
179 var['tmp_root'] = os.path.expanduser('~') + os.sep + 'tmp'
183 def get_command_line_overrides(self, options, sections):
184 '''get all the overwrites that are in the command line
186 :param options: the options from salomeTools class
187 initialization (like -l5 or --overwrite)
188 :param sections str: The config section to overwrite.
189 :return: The list of all the overwrites to apply.
192 # when there are no options or not the overwrite option,
193 # return an empty list
194 if options is None or options.overwrite is None:
198 for section in sections:
199 # only overwrite the sections that correspond to the option
200 over.extend(filter(lambda l: l.startswith(section + "."),
204 def get_config(self, application=None, options=None, command=None,
206 '''get the config from all the configuration files.
208 :param application str: The application for which salomeTools is called.
209 :param options class Options: The general salomeToos
210 options (--overwrite or -l5, for example)
211 :param command str: The command that is called.
212 :param datadir str: The repository that contain
213 external data for salomeTools.
214 :return: The final config.
215 :rtype: class 'src.pyconf.Config'
218 # create a ConfigMerger to handle merge
219 merger = src.pyconf.ConfigMerger()#MergeHandler())
221 # create the configuration instance
222 cfg = src.pyconf.Config()
224 # =====================================================================
225 # create VARS section
226 var = self._create_vars(application=application, command=command,
229 cfg.VARS = src.pyconf.Mapping(cfg)
231 cfg.VARS[variable] = var[variable]
233 # apply overwrite from command line if needed
234 for rule in self.get_command_line_overrides(options, ["VARS"]):
235 exec('cfg.' + rule) # this cannot be factorized because of the exec
237 # =====================================================================
238 # Load INTERNAL config
239 # read src/internal_config/salomeTools.pyconf
240 src.pyconf.streamOpener = ConfigOpener([
241 os.path.join(cfg.VARS.srcDir, 'internal_config')])
243 internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir,
244 'internal_config', 'salomeTools.pyconf')))
245 except src.pyconf.ConfigError as e:
246 raise src.SatException(_("Error in configuration file:"
247 " salomeTools.pyconf\n %(error)s") % \
250 merger.merge(cfg, internal_cfg)
252 # apply overwrite from command line if needed
253 for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
254 exec('cfg.' + rule) # this cannot be factorized because of the exec
256 # =====================================================================
257 # Load LOCAL config file
258 # search only in the data directory
259 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
261 local_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir,
263 PWD = ('LOCAL', cfg.VARS.datadir) )
264 except src.pyconf.ConfigError as e:
265 raise src.SatException(_("Error in configuration file: "
266 "local.pyconf\n %(error)s") % \
268 except IOError as error:
270 raise src.SatException( e );
271 merger.merge(cfg, local_cfg)
273 # When the key is "default", put the default value
274 if cfg.LOCAL.base == "default":
275 cfg.LOCAL.base = os.path.abspath(
276 os.path.join(cfg.VARS.salometoolsway,
279 if cfg.LOCAL.workdir == "default":
280 cfg.LOCAL.workdir = os.path.abspath(
281 os.path.join(cfg.VARS.salometoolsway,
283 if cfg.LOCAL.log_dir == "default":
284 cfg.LOCAL.log_dir = os.path.abspath(
285 os.path.join(cfg.VARS.salometoolsway,
289 if cfg.LOCAL.archive_dir == "default":
290 cfg.LOCAL.archive_dir = os.path.abspath(
291 os.path.join(cfg.VARS.salometoolsway,
295 # apply overwrite from command line if needed
296 for rule in self.get_command_line_overrides(options, ["LOCAL"]):
297 exec('cfg.' + rule) # this cannot be factorized because of the exec
299 # =====================================================================
301 projects_cfg = src.pyconf.Config()
302 projects_cfg.addMapping("PROJECTS",
303 src.pyconf.Mapping(projects_cfg),
305 projects_cfg.PROJECTS.addMapping("projects",
306 src.pyconf.Mapping(cfg.PROJECTS),
307 "The projects definition\n")
309 for project_pyconf_path in cfg.PROJECTS.project_file_paths:
310 if not os.path.exists(project_pyconf_path):
311 msg = _("WARNING: The project file %s cannot be found. "
312 "It will be ignored\n" % project_pyconf_path)
313 sys.stdout.write(msg)
315 project_name = os.path.basename(
316 project_pyconf_path)[:-len(".pyconf")]
318 project_pyconf_dir = os.path.dirname(project_pyconf_path)
319 project_cfg = src.pyconf.Config(open(project_pyconf_path),
320 PWD=("", project_pyconf_dir))
321 except Exception as e:
322 msg = _("ERROR: Error in configuration file: "
323 "%(file_path)s\n %(error)s\n") % \
324 {'file_path' : project_pyconf_path, 'error': str(e) }
325 sys.stdout.write(msg)
327 projects_cfg.PROJECTS.projects.addMapping(project_name,
328 src.pyconf.Mapping(projects_cfg.PROJECTS.projects),
329 "The %s project\n" % project_name)
330 projects_cfg.PROJECTS.projects[project_name]=project_cfg
331 projects_cfg.PROJECTS.projects[project_name]["file_path"] = \
334 merger.merge(cfg, projects_cfg)
336 # apply overwrite from command line if needed
337 for rule in self.get_command_line_overrides(options, ["PROJECTS"]):
338 exec('cfg.' + rule) # this cannot be factorized because of the exec
340 # =====================================================================
341 # Create the paths where to search the application configurations,
342 # the product configurations, the products archives,
343 # the jobs configurations and the machines configurations
344 cfg.addMapping("PATHS", src.pyconf.Mapping(cfg), "The paths\n")
345 cfg.PATHS["APPLICATIONPATH"] = src.pyconf.Sequence(cfg.PATHS)
346 cfg.PATHS.APPLICATIONPATH.append(cfg.VARS.personal_applications_dir, "")
349 cfg.PATHS["PRODUCTPATH"] = src.pyconf.Sequence(cfg.PATHS)
350 cfg.PATHS.PRODUCTPATH.append(cfg.VARS.personal_products_dir, "")
351 cfg.PATHS["ARCHIVEPATH"] = src.pyconf.Sequence(cfg.PATHS)
352 cfg.PATHS.ARCHIVEPATH.append(cfg.VARS.personal_archives_dir, "")
353 cfg.PATHS["ARCHIVEFTP"] = src.pyconf.Sequence(cfg.PATHS)
354 cfg.PATHS["JOBPATH"] = src.pyconf.Sequence(cfg.PATHS)
355 cfg.PATHS.JOBPATH.append(cfg.VARS.personal_jobs_dir, "")
356 cfg.PATHS["MACHINEPATH"] = src.pyconf.Sequence(cfg.PATHS)
357 cfg.PATHS.MACHINEPATH.append(cfg.VARS.personal_machines_dir, "")
359 # initialise the path with local directory
360 cfg.PATHS["ARCHIVEPATH"].append(cfg.LOCAL.archive_dir, "")
362 # Loop over the projects in order to complete the PATHS variables
363 # as /data/tmpsalome/salome/prerequis/archives for example ARCHIVEPATH
364 for project in cfg.PROJECTS.projects:
365 for PATH in ["APPLICATIONPATH",
367 "ARCHIVEPATH", #comment this for default archive #8646
371 if PATH not in cfg.PROJECTS.projects[project]:
373 cfg.PATHS[PATH].append(cfg.PROJECTS.projects[project][PATH], "")
375 # apply overwrite from command line if needed
376 for rule in self.get_command_line_overrides(options, ["PATHS"]):
377 exec('cfg.' + rule) # this cannot be factorized because of the exec
379 # AT END append APPLI_TEST directory in APPLICATIONPATH, for unittest
380 appli_test_dir = os.path.join(satdir, "test", "APPLI_TEST")
381 if appli_test_dir not in cfg.PATHS.APPLICATIONPATH:
382 cfg.PATHS.APPLICATIONPATH.append(appli_test_dir, "unittest APPLI_TEST path")
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(
395 _("%s, use 'config --list' to get the 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 cfg['open_application'] = 'yes'
430 # =====================================================================
431 # Load product config files in PRODUCTS section
432 products_cfg = src.pyconf.Config()
433 products_cfg.addMapping("PRODUCTS",
434 src.pyconf.Mapping(products_cfg),
436 if application is not None:
437 src.pyconf.streamOpener = ConfigOpener(cfg.PATHS.PRODUCTPATH)
438 for product_name in application_cfg.APPLICATION.products.keys():
439 # Loop on all files that are in softsDir directory
440 # and read their config
441 product_file_name = product_name + ".pyconf"
442 product_file_path = src.find_file_in_lpath(product_file_name, cfg.PATHS.PRODUCTPATH)
443 if product_file_path:
444 products_dir = os.path.dirname(product_file_path)
446 prod_cfg = src.pyconf.Config(open(product_file_path),
447 PWD=("", products_dir))
448 prod_cfg.from_file = product_file_path
449 products_cfg.PRODUCTS[product_name] = prod_cfg
450 except Exception as e:
452 "WARNING: Error in configuration file"
453 ": %(prod)s\n %(error)s" % \
454 {'prod' : product_name, 'error': str(e) })
455 sys.stdout.write(msg)
457 merger.merge(cfg, products_cfg)
459 # apply overwrite from command line if needed
460 for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
461 exec('cfg.' + rule) # this cannot be factorized because of the exec
464 merger.merge(cfg, application_cfg)
466 # default launcher name ('salome')
467 if ('profile' in cfg.APPLICATION and
468 'launcher_name' not in cfg.APPLICATION.profile):
469 cfg.APPLICATION.profile.launcher_name = 'salome'
471 # apply overwrite from command line if needed
472 for rule in self.get_command_line_overrides(options,
474 # this cannot be factorized because of the exec
477 # =====================================================================
479 self.set_user_config_file(cfg)
480 user_cfg_file = self.get_user_config_file()
481 user_cfg = src.pyconf.Config(open(user_cfg_file))
482 merger.merge(cfg, user_cfg)
484 # apply overwrite from command line if needed
485 for rule in self.get_command_line_overrides(options, ["USER"]):
486 exec('cfg.' + rule) # this cannot be factorize because of the exec
490 def set_user_config_file(self, config):
491 '''Set the user config file name and path.
492 If necessary, build it from another one or create it from scratch.
494 :param config class 'src.pyconf.Config': The global config
495 (containing all pyconf).
497 # get the expected name and path of the file
498 self.config_file_name = 'SAT.pyconf'
499 self.user_config_file_path = os.path.join(config.VARS.personalDir,
500 self.config_file_name)
502 # if pyconf does not exist, create it from scratch
503 if not os.path.isfile(self.user_config_file_path):
504 self.create_config_file(config)
506 def create_config_file(self, config):
507 '''This method is called when there are no user config file.
508 It build it from scratch.
510 :param config class 'src.pyconf.Config': The global config.
511 :return: the config corresponding to the file created.
512 :rtype: config class 'src.pyconf.Config'
515 cfg_name = self.get_user_config_file()
517 user_cfg = src.pyconf.Config()
519 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
521 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
522 "This is the user name used to access salome cvs base.\n")
523 user_cfg.USER.addMapping('svn_user', config.VARS.user,
524 "This is the user name used to access salome svn base.\n")
525 user_cfg.USER.addMapping('output_verbose_level', 3,
526 "This is the default output_verbose_level you want."
527 " 0=>no output, 5=>debug.\n")
528 user_cfg.USER.addMapping('publish_dir',
529 os.path.join(os.path.expanduser('~'),
533 user_cfg.USER.addMapping('editor',
535 "This is the editor used to "
536 "modify configuration files\n")
537 user_cfg.USER.addMapping('browser',
539 "This is the browser used to "
540 "read html documentation\n")
541 user_cfg.USER.addMapping('pdf_viewer',
543 "This is the pdf_viewer used "
544 "to read pdf documentation\n")
545 # CNC 25/10/17 : plus nécessaire a priori
546 # user_cfg.USER.addMapping("base",
547 # src.pyconf.Reference(
550 # 'workdir + $VARS.sep + "BASE"'),
551 # "The products installation base (could be "
552 # "ignored if this key exists in the local.pyconf"
553 # " file of salomTools).\n")
556 src.ensure_path_exists(config.VARS.personalDir)
557 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
560 f = open(cfg_name, 'w')
566 def get_user_config_file(self):
567 '''Get the user config file
568 :return: path to the user config file.
571 if not self.user_config_file_path:
572 raise src.SatException(_("Error in get_user_config_file: "
573 "missing user config file path"))
574 return self.user_config_file_path
576 def check_path(path, ext=[]):
577 '''Construct a text with the input path and "not found" if it does not
580 :param path Str: the path to check.
581 :param ext List: An extension. Verify that the path extension
583 :return: The string of the path with information
586 # check if file exists
587 if not os.path.exists(path):
588 return "'%s'" % path + " " + src.printcolors.printcError(_(
593 fe = os.path.splitext(path)[1].lower()
595 return "'%s'" % path + " " + src.printcolors.printcError(_(
600 def show_product_info(config, name, logger):
601 '''Display on the terminal and logger information about a product.
603 :param config Config: the global configuration.
604 :param name Str: The name of the product
605 :param logger Logger: The logger instance to use for the display
608 logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
609 pinfo = src.product.get_product_config(config, name)
611 if "depend" in pinfo:
612 src.printcolors.print_value(logger,
614 ', '.join(pinfo.depend), 2)
616 if "opt_depend" in pinfo:
617 src.printcolors.print_value(logger,
619 ', '.join(pinfo.opt_depend), 2)
621 # information on pyconf
622 logger.write("\n", 2)
623 logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
624 if "from_file" in pinfo:
625 src.printcolors.print_value(logger,
629 if "section" in pinfo:
630 src.printcolors.print_value(logger,
635 # information on prepare
636 logger.write("\n", 2)
637 logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
639 is_dev = src.product.product_is_dev(pinfo)
640 method = pinfo.get_source
643 src.printcolors.print_value(logger, "get method", method, 2)
646 src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
647 src.printcolors.print_value(logger, "base module",
648 pinfo.cvs_info.module_base, 2)
649 src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
650 src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
652 elif method == 'svn':
653 src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
655 elif method == 'git':
656 src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
657 src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
659 elif method == 'archive':
660 src.printcolors.print_value(logger,
662 check_path(pinfo.archive_info.archive_name),
665 if 'patches' in pinfo:
666 for patch in pinfo.patches:
667 src.printcolors.print_value(logger, "patch", check_path(patch), 2)
669 if src.product.product_is_fixed(pinfo):
670 src.printcolors.print_value(logger, "install_dir",
671 check_path(pinfo.install_dir), 2)
673 if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
676 # information on compilation
677 if src.product.product_compiles(pinfo):
678 logger.write("\n", 2)
679 logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
680 src.printcolors.print_value(logger,
681 "compilation method",
685 if pinfo.build_source == "script" and "compil_script" in pinfo:
686 src.printcolors.print_value(logger,
687 "Compilation script",
691 if 'nb_proc' in pinfo:
692 src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
694 src.printcolors.print_value(logger,
696 check_path(pinfo.source_dir),
698 if 'install_dir' in pinfo:
699 src.printcolors.print_value(logger,
701 check_path(pinfo.build_dir),
703 src.printcolors.print_value(logger,
705 check_path(pinfo.install_dir),
709 src.printcolors.printcWarning(_("no install dir")) +
712 logger.write("\n", 2)
713 msg = _("This product does not compile")
714 logger.write("%s\n" % msg, 2)
716 # information on environment
717 logger.write("\n", 2)
718 logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
719 if "environ" in pinfo and "env_script" in pinfo.environ:
720 src.printcolors.print_value(logger,
722 check_path(pinfo.environ.env_script),
725 zz = src.environment.SalomeEnviron(config,
726 src.fileEnviron.ScreenEnviron(logger),
728 zz.set_python_libdirs()
729 zz.set_a_product(name, logger)
730 logger.write("\n", 2)
733 def show_patchs(config, logger):
734 '''Prints all the used patchs in the application.
736 :param config Config: the global configuration.
737 :param logger Logger: The logger instance to use for the display
740 for product in sorted(config.APPLICATION.products):
742 product_info = src.product.get_product_config(config, product)
743 if src.product.product_has_patches(product_info):
745 logger.write("%s:\n" % product, 1)
746 for i in product_info.patches:
747 logger.write(src.printcolors.printcInfo(" %s\n" % i), 1)
748 except Exception as e:
749 msg = "problem on product %s\n%s\n" % (product, str(e))
753 logger.write("\n", 1)
755 logger.write("No patchs found\n", 1)
758 def show_properties(config, logger):
759 '''Prints all the used properties in the application.
761 :param config Config: the global configuration.
762 :param logger Logger: The logger instance to use for the display
765 for product in sorted(config.APPLICATION.products):
767 product_info = src.product.get_product_config(config, product)
770 for i in product_info.properties:
772 logger.write("%s:\n" % product, 1)
775 logger.write(src.printcolors.printcInfo(" %s\n" % i), 1)
776 except Exception as e:
778 except Exception as e:
779 # logger.write(src.printcolors.printcInfo(" %s\n" % "no properties"), 1)
780 msg = "problem on product %s\n%s\n" % (product, e)
784 logger.write("\n", 1)
786 logger.write("No properties found\n", 1)
788 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
789 '''Prints a value from the configuration. Prints recursively the values
790 under the initial path.
792 :param config class 'src.pyconf.Config': The configuration
793 from which the value is displayed.
794 :param path str : the path in the configuration of the value to print.
795 :param show_label boolean: if True, do a basic display.
796 (useful for bash completion)
797 :param logger Logger: the logger instance
798 :param level int: The number of spaces to add before display.
799 :param show_full_path :
802 # Make sure that the path does not ends with a point
803 if path.endswith('.'):
806 # display all the path or not
810 vname = path.split('.')[-1]
812 # number of spaces before the display
813 tab_level = " " * level
815 # call to the function that gets the value of the path.
817 val = config.getByPath(path)
818 except Exception as e:
819 logger.write(tab_level)
820 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
821 src.printcolors.printcError(str(e))))
824 # in this case, display only the value
826 logger.write(tab_level)
827 logger.write("%s: " % src.printcolors.printcLabel(vname))
829 # The case where the value has under values,
830 # do a recursive call to the function
831 if dir(val).__contains__('keys'):
832 if show_label: logger.write("\n")
833 for v in sorted(val.keys()):
834 print_value(config, path + '.' + v, show_label, logger, level + 1)
835 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
836 # in this case, value is a list (or a Sequence)
837 if show_label: logger.write("\n")
840 print_value(config, path + "[" + str(index) + "]",
841 show_label, logger, level + 1)
843 else: # case where val is just a str
844 logger.write("%s\n" % val)
846 def get_config_children(config, args):
847 '''Gets the names of the children of the given parameter.
848 Useful only for completion mechanism
850 :param config Config: The configuration where to read the values
851 :param args: The path in the config from which get the keys
854 rootkeys = config.keys()
857 # no parameter returns list of root keys
861 pos = parent.rfind('.')
863 # Case where there is only on key as parameter.
865 vals = [m for m in rootkeys if m.startswith(parent)]
867 # Case where there is a part from a key
868 # for example VARS.us (for VARS.user)
870 tail = parent[pos+1:]
872 a = config.getByPath(head)
873 if dir(a).__contains__('keys'):
874 vals = map(lambda x: head + '.' + x,
875 [m for m in a.keys() if m.startswith(tail)])
879 for v in sorted(vals):
880 sys.stdout.write("%s\n" % v)
883 '''method that is called when salomeTools is called with --help option.
885 :return: The text to display for the config command description.
888 return _("The config command allows manipulation "
889 "and operation on config files.\n\nexample:\nsat config "
890 "SALOME-master --info ParaView")
893 def run(args, runner, logger):
894 '''method that is called when salomeTools is called with config parameter.
897 (options, args) = parser.parse_args(args)
899 # Only useful for completion mechanism : print the keys of the config
901 get_config_children(runner.cfg, args)
904 # case : print a value of the config
906 if options.value == ".":
907 # if argument is ".", print all the config
908 for val in sorted(runner.cfg.keys()):
909 print_value(runner.cfg, val, not options.no_label, logger)
911 print_value(runner.cfg, options.value, not options.no_label, logger,
912 level=0, show_full_path=False)
914 # case : print a debug value of the config
916 if options.debug == ".":
917 # if argument is ".", print all the config
918 res = DBG.indent(DBG.getStrConfigDbg(runner.cfg))
919 logger.write("\nConfig of application %s:\n\n%s\n" % (runner.cfg.VARS.application, res))
921 if options.debug[0] == ".": # accept ".PRODUCT.etc" as "PRODUCT.etc"
922 od = options.debug[1:]
925 exec("a = runner.cfg.%s" % od)
926 res = DBG.indent(DBG.getStrConfigDbg(a))
927 logger.write("\nConfig.%s of application %s:\n\n%s\n" % (od, runner.cfg.VARS.application, res))
930 # case : edit user pyconf file or application file
932 editor = runner.cfg.USER.editor
933 if ('APPLICATION' not in runner.cfg and
934 'open_application' not in runner.cfg): # edit user pyconf
935 usercfg = os.path.join(runner.cfg.VARS.personalDir,
937 logger.write(_("Opening %s\n" % usercfg), 3)
938 src.system.show_in_editor(editor, usercfg, logger)
940 # search for file <application>.pyconf and open it
941 for path in runner.cfg.PATHS.APPLICATIONPATH:
942 pyconf_path = os.path.join(path,
943 runner.cfg.VARS.application + ".pyconf")
944 if os.path.exists(pyconf_path):
945 logger.write(_("Opening %s\n" % pyconf_path), 3)
946 src.system.show_in_editor(editor, pyconf_path, logger)
949 # case : give information about the product(s) in parameter
951 if options.info is not None:
952 logger.warning('options.products %s overrides options.info %s' % (options.products, options.info))
953 options.info = options.products
956 # DBG.write("products", sorted(runner.cfg.APPLICATION.products.keys()), True)
957 src.check_config_has_application(runner.cfg)
958 taggedProducts = src.getProductNames(runner.cfg, options.info, logger)
959 DBG.write("tagged products", sorted(taggedProducts))
960 for prod in sorted(taggedProducts):
961 if prod in runner.cfg.APPLICATION.products:
963 if len(taggedProducts) > 1:
964 logger.write("#################### ", 2)
965 show_product_info(runner.cfg, prod, logger)
966 except Exception as e:
967 msg = "problem on product %s\n%s\n" % (prod, str(e))
971 msg = _("%s is not a product of %s.\n") % \
972 (prod, runner.cfg.VARS.application)
974 #raise Exception(msg)
976 # case : copy an existing <application>.pyconf
977 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
979 # product is required
980 src.check_config_has_application( runner.cfg )
982 # get application file path
983 source = runner.cfg.VARS.application + '.pyconf'
984 source_full_path = ""
985 for path in runner.cfg.PATHS.APPLICATIONPATH:
986 # ignore personal directory
987 if path == runner.cfg.VARS.personalDir:
989 # loop on all directories that can have pyconf applications
990 zz = os.path.join(path, source)
991 if os.path.exists(zz):
992 source_full_path = zz
995 if len(source_full_path) == 0:
996 raise src.SatException(_(
997 "Config file for product %s not found\n") % source)
1000 # a name is given as parameter, use it
1002 elif 'copy_prefix' in runner.cfg.INTERNAL.config:
1004 dest = (runner.cfg.INTERNAL.config.copy_prefix
1005 + runner.cfg.VARS.application)
1007 # use same name as source
1008 dest = runner.cfg.VARS.application
1011 dest_file = os.path.join(runner.cfg.VARS.personalDir,
1012 'Applications', dest + '.pyconf')
1013 if os.path.exists(dest_file):
1014 raise src.SatException(_("A personal application"
1015 " '%s' already exists") % dest)
1018 shutil.copyfile(source_full_path, dest_file)
1019 logger.write(_("%s has been created.\n") % dest_file)
1021 # case : display all the available pyconf applications
1024 # search in all directories that can have pyconf applications
1025 for path in runner.cfg.PATHS.APPLICATIONPATH:
1027 if not options.no_label:
1028 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
1030 if not os.path.exists(path):
1031 logger.write(src.printcolors.printcError(_(
1032 "Directory not found")) + "\n")
1034 for f in sorted(os.listdir(path)):
1035 # ignore file that does not ends with .pyconf
1036 if not f.endswith('.pyconf'):
1039 appliname = f[:-len('.pyconf')]
1040 if appliname not in lproduct:
1041 lproduct.append(appliname)
1042 if path.startswith(runner.cfg.VARS.personalDir) \
1043 and not options.no_label:
1044 logger.write("%s*\n" % appliname)
1046 logger.write("%s\n" % appliname)
1050 # case: print all the products name of the application (internal use for completion)
1051 if options.completion:
1052 for product_name in runner.cfg.APPLICATION.products.keys():
1053 logger.write("%s\n" % product_name)
1055 # case : give a synthetic view of all patches used in the application
1056 if options.show_patchs:
1057 src.check_config_has_application(runner.cfg)
1058 # Print some informations
1059 logger.write(_('Patchs of application %s\n') %
1060 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
1061 logger.write("\n", 2, False)
1062 show_patchs(runner.cfg, logger)
1064 # case : give a synthetic view of all patches used in the application
1065 if options.show_properties:
1066 src.check_config_has_application(runner.cfg)
1067 # Print some informations
1068 logger.write(_('Properties of application %s\n') %
1069 src.printcolors.printcLabel(runner.cfg.VARS.application), 3)
1070 logger.write("\n", 2, False)
1071 show_properties(runner.cfg, logger)