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 _("print the value of CONFIG_VARIABLE."))
36 parser.add_option('e', 'edit', 'boolean', 'edit',
37 _("edit the product configuration file."))
38 parser.add_option('l', 'list', 'boolean', 'list',
39 _("list all available applications."))
40 parser.add_option('c', 'copy', 'boolean', 'copy',
41 _("""copy a config file to the personnal config files directory.
42 \tWARNING the included files are not copied.
43 \tIf a name is given the new config file takes the given name."""))
44 parser.add_option('n', 'no_label', 'boolean', 'no_label',
45 _("do not print labels, Works only with --value and --list."))
46 parser.add_option('s', 'schema', 'boolean', 'schema',
50 '''Class that helps to find an application pyconf
51 in all the possible directories (pathList)
53 def __init__(self, pathList):
56 :param pathList list: The list of paths where to serach a pyconf.
58 self.pathList = pathList
60 def __call__(self, name):
61 if os.path.isabs(name):
62 return src.pyconf.ConfigInputStream(open(name, 'rb'))
64 return src.pyconf.ConfigInputStream(
65 open(os.path.join( self.get_path(name), name ), 'rb') )
66 raise IOError(_("Configuration file '%s' not found") % name)
68 def get_path( self, name ):
69 '''The method that returns the entire path of the pyconf searched
70 :param name str: The name of the searched pyconf.
72 for path in self.pathList:
73 if os.path.exists(os.path.join(path, name)):
75 raise IOError(_("Configuration file '%s' not found") % name)
78 '''Class that manages the read of all the configuration files of salomeTools
80 def __init__(self, dataDir=None):
83 def _create_vars(self, application=None, command=None, dataDir=None):
84 '''Create a dictionary that stores all information about machine,
85 user, date, repositories, etc...
87 :param application str: The application for which salomeTools is called.
88 :param command str: The command that is called.
89 :param dataDir str: The repository that contain external data
91 :return: The dictionary that stores all information.
95 var['user'] = src.architecture.get_user()
96 var['salometoolsway'] = os.path.dirname(
97 os.path.dirname(os.path.abspath(__file__)))
98 var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
99 var['sep']= os.path.sep
101 # dataDir has a default location
102 var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
103 if dataDir is not None:
104 var['dataDir'] = dataDir
106 var['personalDir'] = os.path.join(os.path.expanduser('~'),
109 # read linux distributions dictionary
110 distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
114 # set platform parameters
115 dist_name = src.architecture.get_distribution(
116 codes=distrib_cfg.DISTRIBUTIONS)
117 dist_version = src.architecture.get_distrib_version(dist_name,
118 codes=distrib_cfg.VERSIONS)
119 dist = dist_name + dist_version
121 var['dist_name'] = dist_name
122 var['dist_version'] = dist_version
124 var['python'] = src.architecture.get_python_version()
126 var['nb_proc'] = src.architecture.get_nb_proc()
127 node_name = platform.node()
128 var['node'] = node_name
129 var['hostname'] = node_name
131 # set date parameters
132 dt = datetime.datetime.now()
133 var['date'] = dt.strftime('%Y%m%d')
134 var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
135 var['hour'] = dt.strftime('%H%M%S')
137 var['command'] = str(command)
138 var['application'] = str(application)
140 # Root dir for temporary files
141 var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
142 # particular win case
143 if src.architecture.is_windows() :
144 var['tmp_root'] = os.path.expanduser('~') + os.sep + 'tmp'
148 def get_command_line_overrides(self, options, sections):
149 '''get all the overwrites that are in the command line
151 :param options: the options from salomeTools class
152 initialization (like -l5 or --overwrite)
153 :param sections str: The config section to overwrite.
154 :return: The list of all the overwrites to apply.
157 # when there are no options or not the overwrite option,
158 # return an empty list
159 if options is None or options.overwrite is None:
163 for section in sections:
164 # only overwrite the sections that correspond to the option
165 over.extend(filter(lambda l: l.startswith(section + "."),
169 def get_config(self, application=None, options=None, command=None,
171 '''get the config from all the configuration files.
173 :param application str: The application for which salomeTools is called.
174 :param options class Options: The general salomeToos
175 options (--overwrite or -l5, for example)
176 :param command str: The command that is called.
177 :param dataDir str: The repository that contain
178 external data for salomeTools.
179 :return: The final config.
180 :rtype: class 'src.pyconf.Config'
183 # create a ConfigMerger to handle merge
184 merger = src.pyconf.ConfigMerger()#MergeHandler())
186 # create the configuration instance
187 cfg = src.pyconf.Config()
189 # =====================================================================
190 # create VARS section
191 var = self._create_vars(application=application, command=command,
194 cfg.VARS = src.pyconf.Mapping(cfg)
196 cfg.VARS[variable] = var[variable]
198 # apply overwrite from command line if needed
199 for rule in self.get_command_line_overrides(options, ["VARS"]):
200 exec('cfg.' + rule) # this cannot be factorized because of the exec
202 # =====================================================================
203 # Load INTERNAL config
204 # read src/internal_config/salomeTools.pyconf
205 src.pyconf.streamOpener = ConfigOpener([
206 os.path.join(cfg.VARS.srcDir, 'internal_config')])
208 internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir,
209 'internal_config', 'salomeTools.pyconf')))
210 except src.pyconf.ConfigError as e:
211 raise src.SatException(_("Error in configuration file:"
212 " salomeTools.pyconf\n %(error)s") % \
215 merger.merge(cfg, internal_cfg)
217 # apply overwrite from command line if needed
218 for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
219 exec('cfg.' + rule) # this cannot be factorized because of the exec
221 # =====================================================================
222 # Load SITE config file
223 # search only in the data directory
224 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
226 site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.dataDir,
228 except src.pyconf.ConfigError as e:
229 raise src.SatException(_("Error in configuration file: "
230 "site.pyconf\n %(error)s") % \
232 except IOError as error:
234 if "site.pyconf" in e :
235 e += ("\nYou can copy data"
237 + "site.template.pyconf to data"
239 + "site.pyconf and edit the file")
240 raise src.SatException( e );
242 # add user local path for configPath
243 site_cfg.SITE.config.config_path.append(
244 os.path.join(cfg.VARS.personalDir, 'Applications'),
245 "User applications path")
247 merger.merge(cfg, site_cfg)
249 # apply overwrite from command line if needed
250 for rule in self.get_command_line_overrides(options, ["SITE"]):
251 exec('cfg.' + rule) # this cannot be factorized because of the exec
254 # =====================================================================
255 # Load APPLICATION config file
256 if application is not None:
257 # search APPLICATION file in all directories in configPath
258 cp = cfg.SITE.config.config_path
259 src.pyconf.streamOpener = ConfigOpener(cp)
261 application_cfg = src.pyconf.Config(application + '.pyconf')
263 raise src.SatException(_("%s, use 'config --list' to get the"
264 " list of available applications.") %e)
265 except src.pyconf.ConfigError as e:
266 raise src.SatException(_("Error in configuration file:"
267 " %(application)s.pyconf\n %(error)s") % \
268 { 'application': application, 'error': str(e) } )
270 merger.merge(cfg, application_cfg)
272 # apply overwrite from command line if needed
273 for rule in self.get_command_line_overrides(options,
275 # this cannot be factorized because of the exec
278 # =====================================================================
279 # Load modules config files in MODULES section
281 # The directory containing the softwares definition
282 modules_dir = os.path.join(cfg.VARS.dataDir, 'modules')
284 # Loop on all files that are in softsDir directory
285 # and read their config
286 for fName in os.listdir(modules_dir):
287 if fName.endswith(".pyconf"):
288 src.pyconf.streamOpener = ConfigOpener([modules_dir])
290 mod_cfg = src.pyconf.Config(open(
291 os.path.join(modules_dir, fName)))
292 except src.pyconf.ConfigError as e:
293 raise src.SatException(_(
294 "Error in configuration file: %(soft)s\n %(error)s") % \
295 {'soft' : fName, 'error': str(e) })
296 except IOError as error:
298 raise src.SatException( e );
300 merger.merge(cfg.MODULES, mod_cfg)
302 # apply overwrite from command line if needed
303 for rule in self.get_command_line_overrides(options, ["MODULES"]):
304 exec('cfg.' + rule) # this cannot be factorized because of the exec
307 # =====================================================================
309 self.set_user_config_file(cfg)
310 user_cfg_file = self.get_user_config_file()
311 user_cfg = src.pyconf.Config(open(user_cfg_file))
312 merger.merge(cfg, user_cfg)
314 # apply overwrite from command line if needed
315 for rule in self.get_command_line_overrides(options, ["USER"]):
316 exec('cfg.' + rule) # this cannot be factorize because of the exec
320 def set_user_config_file(self, config):
321 '''Set the user config file name and path.
322 If necessary, build it from another one or create it from scratch.
324 :param config class 'src.pyconf.Config': The global config
325 (containing all pyconf).
327 # get the expected name and path of the file
328 self.config_file_name = 'salomeTools.pyconf'
329 self.user_config_file_path = os.path.join(config.VARS.personalDir,
330 self.config_file_name)
332 # if pyconf does not exist, create it from scratch
333 if not os.path.isfile(self.user_config_file_path):
334 self.create_config_file(config)
336 def create_config_file(self, config):
337 '''This method is called when there are no user config file.
338 It build it from scratch.
340 :param config class 'src.pyconf.Config': The global config.
341 :return: the config corresponding to the file created.
342 :rtype: config class 'src.pyconf.Config'
345 cfg_name = self.get_user_config_file()
347 user_cfg = src.pyconf.Config()
349 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
352 user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
353 "This is where salomeTools will work. "
354 "You may (and probably do) change it.\n")
355 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
356 "This is the user name used to access salome cvs base.\n")
357 user_cfg.USER.addMapping('svn_user', config.VARS.user,
358 "This is the user name used to access salome svn base.\n")
359 user_cfg.USER.addMapping('output_level', 3,
360 "This is the default output_level you want."
361 " 0=>no output, 5=>debug.\n")
362 user_cfg.USER.addMapping('publish_dir',
363 os.path.join(os.path.expanduser('~'),
367 user_cfg.USER.addMapping('editor',
369 "This is the editor used to "
370 "modify configuration files\n")
371 user_cfg.USER.addMapping('browser',
373 "This is the browser used to "
374 "read html documentation\n")
375 user_cfg.USER.addMapping('pdf_viewer',
377 "This is the pdf_viewer used "
378 "to read pdf documentation\n")
380 src.ensure_path_exists(config.VARS.personalDir)
381 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
384 f = open(cfg_name, 'w')
387 print(_("You can edit it to configure salomeTools "
388 "(use: sat config --edit).\n"))
392 def get_user_config_file(self):
393 '''Get the user config file
394 :return: path to the user config file.
397 if not self.user_config_file_path:
398 raise src.SatException(_("Error in get_user_config_file: "
399 "missing user config file path"))
400 return self.user_config_file_path
403 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
404 '''Prints a value from the configuration. Prints recursively the values
405 under the initial path.
407 :param config class 'src.pyconf.Config': The configuration
408 from which the value is displayed.
409 :param path str : the path in the configuration of the value to print.
410 :param show_label boolean: if True, do a basic display.
411 (useful for bash completion)
412 :param logger Logger: the logger instance
413 :param level int: The number of spaces to add before display.
414 :param show_full_path :
417 # Make sure that the path does not ends with a point
418 if path.endswith('.'):
421 # display all the path or not
425 vname = path.split('.')[-1]
427 # number of spaces before the display
428 tab_level = " " * level
430 # call to the function that gets the value of the path.
432 val = config.getByPath(path)
433 except Exception as e:
434 logger.write(tab_level)
435 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
436 src.printcolors.printcError(str(e))))
439 # in this case, display only the value
441 logger.write(tab_level)
442 logger.write("%s: " % src.printcolors.printcLabel(vname))
444 # The case where the value has under values,
445 # do a recursive call to the function
446 if dir(val).__contains__('keys'):
447 if show_label: logger.write("\n")
448 for v in sorted(val.keys()):
449 print_value(config, path + '.' + v, show_label, logger, level + 1)
450 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
451 # in this case, value is a list (or a Sequence)
452 if show_label: logger.write("\n")
455 print_value(config, path + "[" + str(index) + "]",
456 show_label, logger, level + 1)
458 else: # case where val is just a str
459 logger.write("%s\n" % val)
461 def get_config_children(config, args):
462 '''Gets the names of the children of the given parameter.
463 Useful only for completion mechanism
465 :param config Config: The configuration where to read the values
466 :param args: The path in the config from which get the keys
469 rootkeys = config.keys()
472 # no parameter returns list of root keys
476 pos = parent.rfind('.')
478 # Case where there is only on key as parameter.
480 vals = [m for m in rootkeys if m.startswith(parent)]
482 # Case where there is a part from a key
483 # for example VARS.us (for VARS.user)
485 tail = parent[pos+1:]
487 a = config.getByPath(head)
488 if dir(a).__contains__('keys'):
489 vals = map(lambda x: head + '.' + x, [m for m in a.keys() if m.startswith(tail)])
493 for v in sorted(vals):
494 sys.stdout.write("%s\n" % v)
497 '''method that is called when salomeTools is called with --help option.
499 :return: The text to display for the config command description.
502 return _("The config command allows manipulation "
503 "and operation on config files.")
506 def run(args, runner, logger):
507 '''method that is called when salomeTools is called with config parameter.
510 (options, args) = parser.parse_args(args)
512 # Only useful for completion mechanism : print the keys of the config
514 get_config_children(runner.cfg, args)
517 # case : print a value of the config
519 if options.value == ".":
520 # if argument is ".", print all the config
521 for val in sorted(runner.cfg.keys()):
522 print_value(runner.cfg, val, not options.no_label, logger)
524 print_value(runner.cfg, options.value, not options.no_label, logger,
525 level=0, show_full_path=False)
527 # case : edit user pyconf file or application file
529 editor = runner.cfg.USER.editor
530 if 'APPLICATION' not in runner.cfg: # edit user pyconf
531 usercfg = os.path.join(runner.cfg.VARS.personalDir,
532 'salomeTools.pyconf')
533 src.system.show_in_editor(editor, usercfg, logger)
535 # search for file <application>.pyconf and open it
536 for path in runner.cfg.SITE.config.config_path:
537 pyconf_path = os.path.join(path,
538 runner.cfg.VARS.application + ".pyconf")
539 if os.path.exists(pyconf_path):
540 src.system.show_in_editor(editor, pyconf_path, logger)
543 # case : copy an existing <application>.pyconf
544 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
546 # product is required
547 src.check_config_has_application( runner.cfg )
549 # get application file path
550 source = runner.cfg.VARS.application + '.pyconf'
551 source_full_path = ""
552 for path in runner.cfg.SITE.config.config_path:
553 # ignore personal directory
554 if path == runner.cfg.VARS.personalDir:
556 # loop on all directories that can have pyconf applications
557 zz = os.path.join(path, source)
558 if os.path.exists(zz):
559 source_full_path = zz
562 if len(source_full_path) == 0:
563 raise src.SatException(_(
564 "Config file for product %s not found\n") % source)
567 # a name is given as parameter, use it
569 elif 'copy_prefix' in runner.cfg.SITE.config:
571 dest = (runner.cfg.SITE.config.copy_prefix
572 + runner.cfg.VARS.application)
574 # use same name as source
575 dest = runner.cfg.VARS.application
578 dest_file = os.path.join(runner.cfg.VARS.personalDir,
579 'Applications', dest + '.pyconf')
580 if os.path.exists(dest_file):
581 raise src.SatException(_("A personal application"
582 " '%s' already exists") % dest)
585 shutil.copyfile(source_full_path, dest_file)
586 logger.write(_("%s has been created.\n") % dest_file)
588 # case : display all the available pyconf applications
591 # search in all directories that can have pyconf applications
592 for path in runner.cfg.SITE.config.config_path:
594 if not options.no_label:
595 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
597 if not os.path.exists(path):
598 logger.write(src.printcolors.printcError(_(
599 "Directory not found")) + "\n")
601 for f in sorted(os.listdir(path)):
602 # ignore file that does not ends with .pyconf
603 if not f.endswith('.pyconf'):
606 appliname = f[:-len('.pyconf')]
607 if appliname not in lproduct:
608 lproduct.append(appliname)
609 if path.startswith(runner.cfg.VARS.personalDir) \
610 and not options.no_label:
611 logger.write("%s*\n" % appliname)
613 logger.write("%s\n" % appliname)