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 # internationalization
28 satdir = os.path.dirname(os.path.realpath(__file__))
29 gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
31 # Define all possible option for config command : sat config <options>
32 parser = src.options.Options()
33 parser.add_option('v', 'value', 'string', 'value',
34 _("print the value of CONFIG_VARIABLE."))
35 parser.add_option('e', 'edit', 'boolean', 'edit',
36 _("edit the product configuration file."))
37 parser.add_option('l', 'list', 'boolean', 'list',
38 _("list all available applications."))
39 parser.add_option('c', 'copy', 'boolean', 'copy',
40 _("""copy a config file to the personnal config files directory.
41 \tWARNING the included files are not copied.
42 \tIf a name is given the new config file takes the given name."""))
45 '''Class that helps to find an application pyconf
46 in all the possible directories (pathList)
48 def __init__(self, pathList):
51 :param pathList list: The list of paths where to serach a pyconf.
53 self.pathList = pathList
55 def __call__(self, name):
56 if os.path.isabs(name):
57 return src.pyconf.ConfigInputStream(open(name, 'rb'))
59 return src.pyconf.ConfigInputStream(
60 open(os.path.join( self.get_path(name), name ), 'rb') )
61 raise IOError(_("Configuration file '%s' not found") % name)
63 def get_path( self, name ):
64 '''The method that returns the entire path of the pyconf searched
65 :param name str: The name of the searched pyconf.
67 for path in self.pathList:
68 if os.path.exists(os.path.join(path, name)):
70 raise IOError(_("Configuration file '%s' not found") % name)
73 '''Class that manages the read of all the configuration files of salomeTools
75 def __init__(self, dataDir=None):
78 def _create_vars(self, application=None, command=None, dataDir=None):
79 '''Create a dictionary that stores all information about machine,
80 user, date, repositories, etc...
82 :param application str: The application for which salomeTools is called.
83 :param command str: The command that is called.
84 :param dataDir str: The repository that contain external data
86 :return: The dictionary that stores all information.
90 var['user'] = src.architecture.get_user()
91 var['salometoolsway'] = os.path.dirname(
92 os.path.dirname(os.path.abspath(__file__)))
93 var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
94 var['sep']= os.path.sep
96 # dataDir has a default location
97 var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
98 if dataDir is not None:
99 var['dataDir'] = dataDir
101 var['personalDir'] = os.path.join(os.path.expanduser('~'),
104 # read linux distributions dictionary
105 distrib_cfg = src.pyconf.Config(os.path.join(var['srcDir'],
109 # set platform parameters
110 dist_name = src.architecture.get_distribution(
111 codes=distrib_cfg.DISTRIBUTIONS)
112 dist_version = src.architecture.get_distrib_version(dist_name,
113 codes=distrib_cfg.VERSIONS)
114 dist = dist_name + dist_version
116 var['dist_name'] = dist_name
117 var['dist_version'] = dist_version
119 var['python'] = src.architecture.get_python_version()
121 var['nb_proc'] = src.architecture.get_nb_proc()
122 node_name = platform.node()
123 var['node'] = node_name
124 var['hostname'] = node_name
126 # set date parameters
127 dt = datetime.datetime.now()
128 var['date'] = dt.strftime('%Y%m%d')
129 var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
130 var['hour'] = dt.strftime('%H%M%S')
132 var['command'] = str(command)
133 var['application'] = str(application)
135 # Root dir for temporary files
136 var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
137 # particular win case
138 if src.architecture.is_windows() :
139 var['tmp_root'] = os.path.expanduser('~') + os.sep + 'tmp'
143 def get_command_line_overrides(self, options, sections):
144 '''get all the overwrites that are in the command line
146 :param options: the options from salomeTools class
147 initialization (like -l5 or --overwrite)
148 :param sections str: The config section to overwrite.
149 :return: The list of all the overwrites to apply.
152 # when there are no options or not the overwrite option,
153 # return an empty list
154 if options is None or options.overwrite is None:
158 for section in sections:
159 # only overwrite the sections that correspond to the option
160 over.extend(filter(lambda l: l.startswith(section + "."),
164 def get_config(self, application=None, options=None, command=None,
166 '''get the config from all the configuration files.
168 :param application str: The application for which salomeTools is called.
169 :param options class Options: The general salomeToos
170 options (--overwrite or -l5, for example)
171 :param command str: The command that is called.
172 :param dataDir str: The repository that contain
173 external data for salomeTools.
174 :return: The final config.
175 :rtype: class 'src.pyconf.Config'
178 # create a ConfigMerger to handle merge
179 merger = src.pyconf.ConfigMerger()#MergeHandler())
181 # create the configuration instance
182 cfg = src.pyconf.Config()
184 # =====================================================================
185 # create VARS section
186 var = self._create_vars(application=application, command=command,
189 cfg.VARS = src.pyconf.Mapping(cfg)
191 cfg.VARS[variable] = var[variable]
193 # apply overwrite from command line if needed
194 for rule in self.get_command_line_overrides(options, ["VARS"]):
195 exec('cfg.' + rule) # this cannot be factorized because of the exec
197 # =====================================================================
198 # Load INTERNAL config
199 # read src/internal_config/salomeTools.pyconf
200 src.pyconf.streamOpener = ConfigOpener([
201 os.path.join(cfg.VARS.srcDir, 'internal_config')])
203 internal_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.srcDir,
204 'internal_config', 'salomeTools.pyconf')))
205 except src.pyconf.ConfigError as e:
206 raise src.SatException(_("Error in configuration file:"
207 " salomeTools.pyconf\n %(error)s") % \
210 merger.merge(cfg, internal_cfg)
212 # apply overwrite from command line if needed
213 for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
214 exec('cfg.' + rule) # this cannot be factorized because of the exec
216 # =====================================================================
217 # Load SITE config file
218 # search only in the data directory
219 src.pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
221 site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.dataDir,
223 except src.pyconf.ConfigError as e:
224 raise src.SatException(_("Error in configuration file: "
225 "site.pyconf\n %(error)s") % \
227 except IOError as error:
229 if "site.pyconf" in e :
230 e += ("\nYou can copy data"
232 + "site.template.pyconf to data"
234 + "site.pyconf and edit the file")
235 raise src.SatException( e );
237 # add user local path for configPath
238 site_cfg.SITE.config.config_path.append(
239 os.path.join(cfg.VARS.personalDir, 'Applications'),
240 "User applications path")
242 merger.merge(cfg, site_cfg)
244 # apply overwrite from command line if needed
245 for rule in self.get_command_line_overrides(options, ["SITE"]):
246 exec('cfg.' + rule) # this cannot be factorized because of the exec
249 # =====================================================================
250 # Load APPLICATION config file
251 if application is not None:
252 # search APPLICATION file in all directories in configPath
253 cp = cfg.SITE.config.config_path
254 src.pyconf.streamOpener = ConfigOpener(cp)
256 application_cfg = src.pyconf.Config(application + '.pyconf')
258 raise src.SatException(_("%s, use 'config --list' to get the"
259 " list of available applications.") %e)
260 except src.pyconf.ConfigError as e:
261 raise src.SatException(_("Error in configuration file:"
262 " %(application)s.pyconf\n %(error)s") % \
263 { 'application': application, 'error': str(e) } )
265 merger.merge(cfg, application_cfg)
267 # apply overwrite from command line if needed
268 for rule in self.get_command_line_overrides(options,
270 # this cannot be factorized because of the exec
273 # =====================================================================
274 # Load softwares config files in SOFTWARE section
276 # The directory containing the softwares definition
277 softsDir = os.path.join(cfg.VARS.dataDir, 'softwares')
279 # Loop on all files that are in softsDir directory
280 # and read their config
281 for fName in os.listdir(softsDir):
282 if fName.endswith(".pyconf"):
283 src.pyconf.streamOpener = ConfigOpener([softsDir])
285 soft_cfg = src.pyconf.Config(open(
286 os.path.join(softsDir, fName)))
287 except src.pyconf.ConfigError as e:
288 raise src.SatException(_(
289 "Error in configuration file: %(soft)s\n %(error)s") % \
290 {'soft' : fName, 'error': str(e) })
291 except IOError as error:
293 raise src.SatException( e );
295 merger.merge(cfg, soft_cfg)
297 # apply overwrite from command line if needed
298 for rule in self.get_command_line_overrides(options, ["SOFTWARE"]):
299 exec('cfg.' + rule) # this cannot be factorized because of the exec
302 # =====================================================================
304 self.set_user_config_file(cfg)
305 user_cfg_file = self.get_user_config_file()
306 user_cfg = src.pyconf.Config(open(user_cfg_file))
307 merger.merge(cfg, user_cfg)
309 # apply overwrite from command line if needed
310 for rule in self.get_command_line_overrides(options, ["USER"]):
311 exec('cfg.' + rule) # this cannot be factorize because of the exec
315 def set_user_config_file(self, config):
316 '''Set the user config file name and path.
317 If necessary, build it from another one or create it from scratch.
319 :param config class 'src.pyconf.Config': The global config
320 (containing all pyconf).
322 # get the expected name and path of the file
323 self.config_file_name = 'salomeTools.pyconf'
324 self.user_config_file_path = os.path.join(config.VARS.personalDir,
325 self.config_file_name)
327 # if pyconf does not exist, create it from scratch
328 if not os.path.isfile(self.user_config_file_path):
329 self.create_config_file(config)
331 def create_config_file(self, config):
332 '''This method is called when there are no user config file.
333 It build it from scratch.
335 :param config class 'src.pyconf.Config': The global config.
336 :return: the config corresponding to the file created.
337 :rtype: config class 'src.pyconf.Config'
340 cfg_name = self.get_user_config_file()
342 user_cfg = src.pyconf.Config()
344 user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
347 user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
348 "This is where salomeTools will work. "
349 "You may (and probably do) change it.\n")
350 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
351 "This is the user name used to access salome cvs base.\n")
352 user_cfg.USER.addMapping('svn_user', config.VARS.user,
353 "This is the user name used to access salome svn base.\n")
354 user_cfg.USER.addMapping('output_level', 3,
355 "This is the default output_level you want."
356 " 0=>no output, 5=>debug.\n")
357 user_cfg.USER.addMapping('publish_dir',
358 os.path.join(os.path.expanduser('~'),
362 user_cfg.USER.addMapping('editor',
364 "This is the editor used to "
365 "modify configuration files\n")
366 user_cfg.USER.addMapping('browser',
368 "This is the browser used to "
369 "read html documentation\n")
370 user_cfg.USER.addMapping('pdf_viewer',
372 "This is the pdf_viewer used "
373 "to read pdf documentation\n")
375 src.ensure_path_exists(config.VARS.personalDir)
376 src.ensure_path_exists(os.path.join(config.VARS.personalDir,
379 f = open(cfg_name, 'w')
382 print(_("You can edit it to configure salomeTools "
383 "(use: sat config --edit).\n"))
387 def get_user_config_file(self):
388 '''Get the user config file
389 :return: path to the user config file.
392 if not self.user_config_file_path:
393 raise src.SatException(_("Error in get_user_config_file: "
394 "missing user config file path"))
395 return self.user_config_file_path
398 def print_value(config, path, show_label, logger, level=0, show_full_path=False):
399 '''Prints a value from the configuration. Prints recursively the values
400 under the initial path.
402 :param config class 'src.pyconf.Config': The configuration
403 from which the value is displayed.
404 :param path str : the path in the configuration of the value to print.
405 :param show_label boolean: if True, do a basic display.
406 (useful for bash completion)
407 :param logger Logger: the logger instance
408 :param level int: The number of spaces to add before display.
409 :param show_full_path :
412 # display all the path or not
416 vname = path.split('.')[-1]
418 # number of spaces before the display
419 tab_level = " " * level
421 # call to the function that gets the value of the path.
423 val = config.getByPath(path)
424 except Exception as e:
425 logger.write(tab_level)
426 logger.write("%s: ERROR %s\n" % (src.printcolors.printcLabel(vname),
427 src.printcolors.printcError(str(e))))
430 # in this case, display only the value
432 logger.write(tab_level)
433 logger.write("%s: " % src.printcolors.printcLabel(vname))
435 # The case where the value has under values,
436 # do a recursive call to the function
437 if dir(val).__contains__('keys'):
438 if show_label: logger.write("\n")
439 for v in sorted(val.keys()):
440 print_value(config, path + '.' + v, show_label, logger, level + 1)
441 elif val.__class__ == src.pyconf.Sequence or isinstance(val, list):
442 # in this case, value is a list (or a Sequence)
443 if show_label: logger.write("\n")
446 print_value(config, path + "[" + str(index) + "]",
447 show_label, logger, level + 1)
449 else: # case where val is just a str
450 logger.write("%s\n" % val)
453 '''method that is called when salomeTools is called with --help option.
455 :return: The text to display for the config command description.
458 return _("The config command allows manipulation "
459 "and operation on config files.")
462 def run(args, runner, logger):
463 '''method that is called when salomeTools is called with config parameter.
466 (options, args) = parser.parse_args(args)
468 # case : print a value of the config
470 if options.value == ".":
471 # if argument is ".", print all the config
472 for val in sorted(runner.cfg.keys()):
473 print_value(runner.cfg, val, True, logger)
475 print_value(runner.cfg, options.value, True, logger,
476 level=0, show_full_path=False)
478 # case : edit user pyconf file or application file
480 editor = runner.cfg.USER.editor
481 if 'APPLICATION' not in runner.cfg: # edit user pyconf
482 usercfg = os.path.join(runner.cfg.VARS.personalDir,
483 'salomeTools.pyconf')
484 src.system.show_in_editor(editor, usercfg, logger)
486 # search for file <application>.pyconf and open it
487 for path in runner.cfg.SITE.config.config_path:
488 pyconf_path = os.path.join(path,
489 runner.cfg.VARS.application + ".pyconf")
490 if os.path.exists(pyconf_path):
491 src.system.show_in_editor(editor, pyconf_path, logger)
494 # case : copy an existing <application>.pyconf
495 # to ~/.salomeTools/Applications/LOCAL_<application>.pyconf
497 # product is required
498 src.check_config_has_application( runner.cfg )
500 # get application file path
501 source = runner.cfg.VARS.application + '.pyconf'
502 source_full_path = ""
503 for path in runner.cfg.SITE.config.config_path:
504 # ignore personal directory
505 if path == runner.cfg.VARS.personalDir:
507 # loop on all directories that can have pyconf applications
508 zz = os.path.join(path, source)
509 if os.path.exists(zz):
510 source_full_path = zz
513 if len(source_full_path) == 0:
514 raise src.SatException(_(
515 "Config file for product %s not found\n") % source)
518 # a name is given as parameter, use it
520 elif 'copy_prefix' in runner.cfg.SITE.config:
522 dest = (runner.cfg.SITE.config.copy_prefix
523 + runner.cfg.VARS.application)
525 # use same name as source
526 dest = runner.cfg.VARS.application
529 dest_file = os.path.join(runner.cfg.VARS.personalDir,
530 'Applications', dest + '.pyconf')
531 if os.path.exists(dest_file):
532 raise src.SatException(_("A personal application"
533 " '%s' already exists") % dest)
536 shutil.copyfile(source_full_path, dest_file)
537 logger.write(_("%s has been created.\n") % dest_file)
539 # case : display all the available pyconf applications
542 # search in all directories that can have pyconf applications
543 for path in runner.cfg.SITE.config.config_path:
545 logger.write("------ %s\n" % src.printcolors.printcHeader(path))
547 if not os.path.exists(path):
548 logger.write(src.printcolors.printcError(_(
549 "Directory not found")) + "\n")
551 for f in sorted(os.listdir(path)):
552 # ignore file that does not ends with .pyconf
553 if not f.endswith('.pyconf'):
556 appliname = f[:-len('.pyconf')]
557 if appliname not in lproduct:
558 lproduct.append(appliname)
559 if path.startswith(runner.cfg.VARS.personalDir):
560 logger.write("%s*\n" % appliname)
562 logger.write("%s\n" % appliname)