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 # Define all possible option for config command : sat config <options>
29 parser = common.options.Options()
30 parser.add_option('v', 'value', 'string', 'value', "print the value of CONFIG_VARIABLE.")
37 def __call__(self, map1, map2, key):
38 if '__overwrite__' in map2 and key in map2.__overwrite__:
41 return common.config_pyconf.overwriteMergeResolve(map1, map2, key)
45 def __init__(self, pathList):
46 self.pathList = pathList
48 def __call__(self, name):
49 if os.path.isabs(name):
50 return common.config_pyconf.ConfigInputStream(open(name, 'rb'))
52 return common.config_pyconf.ConfigInputStream( open(os.path.join( self.getPath(name), name ), 'rb') )
53 raise IOError(_("Configuration file '%s' not found") % name)
55 def getPath( self, name ):
56 for path in self.pathList:
57 if os.path.exists(os.path.join(path, name)):
59 raise IOError(_("Configuration file '%s' not found") % name)
62 '''Class that manages the read of all the configuration files of salomeTools
64 def __init__(self, dataDir=None):
67 def _create_vars(self, application=None, command=None, dataDir=None):
68 '''Create a dictionary that stores all information about machine, user, date, repositories, etc...
69 :param application str: The application for which salomeTools is called.
70 :param command str: The command that is called.
71 :param dataDir str: The repository that contain external data for salomeTools.
72 :return: The dictionary that stores all information.
76 var['user'] = common.architecture.get_user()
77 var['salometoolsway'] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
78 var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
79 var['sep']= os.path.sep
81 # dataDir has a default location
82 var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
83 if dataDir is not None:
84 var['dataDir'] = dataDir
86 var['personalDir'] = os.path.join(os.path.expanduser('~'), '.salomeTools')
88 # read linux distributions dictionary
89 distrib_cfg = common.config_pyconf.Config(os.path.join(var['dataDir'], "distrib.pyconf"))
91 # set platform parameters
92 dist_name = common.architecture.get_distribution(codes=distrib_cfg.DISTRIBUTIONS)
93 dist_version = common.architecture.get_distrib_version(dist_name, codes=distrib_cfg.VERSIONS)
94 dist = dist_name + dist_version
96 # Forcing architecture with env variable ARCH on Windows
97 if common.architecture.is_windows() and "ARCH" in os.environ :
98 bitsdict={"Win32":"32","Win64":"64"}
99 nb_bits = bitsdict[os.environ["ARCH"]]
101 nb_bits = common.architecture.get_nb_bit()
103 var['dist_name'] = dist_name
104 var['dist_version'] = dist_version
106 var['arch'] = dist + '_' + nb_bits
107 var['bits'] = nb_bits
108 var['python'] = common.architecture.get_python_version()
110 var['nb_proc'] = common.architecture.get_nb_proc()
111 node_name = platform.node()
112 var['node'] = node_name
113 var['hostname'] = node_name
114 # particular win case
115 if common.architecture.is_windows() :
116 var['hostname'] = node_name+'-'+nb_bits
118 # set date parameters
119 dt = datetime.datetime.now()
120 var['date'] = dt.strftime('%Y%m%d')
121 var['datehour'] = dt.strftime('%Y%m%d_%H%M%S')
122 var['hour'] = dt.strftime('%H%M%S')
124 var['command'] = str(command)
125 var['application'] = str(application)
127 # Root dir for temporary files
128 var['tmp_root'] = os.sep + 'tmp' + os.sep + var['user']
129 # particular win case
130 if common.architecture.is_windows() :
131 var['tmp_root'] = os.path.expanduser('~') + os.sep + 'tmp'
135 def get_command_line_overrides(self, options, sections):
136 '''get all the overwrites that are in the command line
137 :param options : TO DO
138 :param sections str: The command that is called.
139 :return: The list of all the overwrites of the command line.
142 # when there are no options or not the overwrite option, return an empty list
143 if options is None or options.overwrite is None:
147 for section in sections:
148 over.extend(filter(lambda l: l.startswith(section + "."), options.overwrite))
151 def getConfig(self, application=None, options=None, command=None, dataDir=None):
152 '''get the config from all the configuration files.
153 :param application str: The application for which salomeTools is called.
155 :param command str: The command that is called.
156 :param dataDir str: The repository that contain external data for salomeTools.
157 :return: The final config.
158 :rtype: class 'common.config_pyconf.Config'
161 # create a ConfigMerger to handle merge
162 merger = common.config_pyconf.ConfigMerger()#MergeHandler())
164 # create the configuration instance
165 cfg = common.config_pyconf.Config()
167 # =======================================================================================
168 # create VARS section
169 var = self._create_vars(application=application, command=command, dataDir=dataDir)
171 cfg.VARS = common.config_pyconf.Mapping(cfg)
173 cfg.VARS[variable] = var[variable]
175 for rule in self.get_command_line_overrides(options, ["VARS"]):
176 exec('cfg.' + rule) # this cannot be factorized because of the exec
178 # =======================================================================================
179 # Load INTERNAL config
180 # read src/common/internal_config/salomeTools.pyconf
181 common.config_pyconf.streamOpener = ConfigOpener([os.path.join(cfg.VARS.srcDir, 'common', 'internal_config')])
183 internal_cfg = common.config_pyconf.Config(open(os.path.join(cfg.VARS.srcDir, 'common', 'internal_config', 'salomeTools.pyconf')))
184 except common.config_pyconf.ConfigError as e:
185 raise common.SatException(_("Error in configuration file: salomeTools.pyconf\n %(error)s") % \
188 merger.merge(cfg, internal_cfg)
190 for rule in self.get_command_line_overrides(options, ["INTERNAL"]):
191 exec('cfg.' + rule) # this cannot be factorized because of the exec
193 # =======================================================================================
194 # Load SITE config file
195 # search only in the data directory
196 common.config_pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
198 site_cfg = common.config_pyconf.Config(open(os.path.join(cfg.VARS.dataDir, 'site.pyconf')))
199 except common.config_pyconf.ConfigError as e:
200 raise common.SatException(_("Error in configuration file: site.pyconf\n %(error)s") % \
202 except IOError as error:
204 if "site.pyconf" in e :
205 e += "\nYou can copy data" + cfg.VARS.sep + "site.template.pyconf to data" + cfg.VARS.sep + "site.pyconf and edit the file"
206 raise common.SatException( e );
208 merger.merge(cfg, site_cfg)
210 for rule in self.get_command_line_overrides(options, ["SITE"]):
211 exec('cfg.' + rule) # this cannot be factorized because of the exec
213 # =======================================================================================
214 # Load APPLICATION config file
215 if application is not None:
216 # search APPLICATION file in all directories in configPath
217 cp = cfg.SITE.config.configPath
218 common.config_pyconf.streamOpener = ConfigOpener(cp)
220 application_cfg = common.config_pyconf.Config(application + '.pyconf')
222 raise common.SatException(_("%s, use 'config --list' to get the list of available applications.") %e)
223 except common.config_pyconf.ConfigError as e:
224 raise common.SatException(_("Error in configuration file: %(application)s.pyconf\n %(error)s") % \
225 { 'application': application, 'error': str(e) } )
227 merger.merge(cfg, application_cfg)
229 for rule in self.get_command_line_overrides(options, ["APPLICATION"]):
230 exec('cfg.' + rule) # this cannot be factorized because of the exec
232 # =======================================================================================
234 self.setUserConfigFile(cfg)
235 user_cfg_file = self.getUserConfigFile()
236 user_cfg = common.config_pyconf.Config(open(user_cfg_file))
237 merger.merge(cfg, user_cfg)
239 for rule in self.get_command_line_overrides(options, ["USER"]):
240 exec('cfg.' + rule) # this cannot be factorize because of the exec
244 def setUserConfigFile(self, config):
245 '''Set the user config file name and path.
246 If necessary, build it from another one or create it from scratch.
249 raise common.SatException(_("Error in setUserConfigFile: config is None"))
250 sat_version = config.INTERNAL.sat_version
251 self.config_file_name = 'salomeTools-%s.pyconf'%sat_version
252 self.user_config_file_path = os.path.join(config.VARS.personalDir, self.config_file_name)
253 if not os.path.isfile(self.user_config_file_path):
254 # if pyconf does not exist,
255 # Make a copy of an existing salomeTools-<sat_version>.pyconf
256 # or at least a copy of salomeTools.pyconf
257 # If there is no pyconf file at all, create it from scratch
258 already_exisiting_pyconf_file = self.getAlreadyExistingUserPyconf( config.VARS.personalDir, sat_version )
259 if already_exisiting_pyconf_file:
261 shutil.copyfile( already_exisiting_pyconf_file, self.user_config_file_path )
262 cfg = common.config_pyconf.Config(open(self.user_config_file_path))
263 else: # create from scratch
264 self.createConfigFile(config)
266 def getAlreadyExistingUserPyconf(self, dir, sat_version ):
267 '''Get a pyconf file younger than the given sat version in the given directory
268 The file basename can be one of salometools-<younger version>.pyconf or salomeTools.pyconf
269 Returns the file path or None if no file has been found.
272 # Get a younger pyconf version
273 pyconfFiles = glob.glob( os.path.join(dir, 'salomeTools-*.pyconf') )
274 sExpr = "^salomeTools-(.*)\.pyconf$"
275 oExpr = re.compile(sExpr)
276 younger_version = None
277 for s in pyconfFiles:
278 oSreMatch = oExpr.search( os.path.basename(s) )
280 pyconf_version = oSreMatch.group(1)
281 if pyconf_version < sat_version:
282 younger_version = pyconf_version
284 # Build the pyconf filepath
286 file_path = os.path.join( dir, 'salomeTools-%s.pyconf'%younger_version )
287 elif os.path.isfile( os.path.join(dir, 'salomeTools.pyconf') ):
288 file_path = os.path.join( dir, 'salomeTools.pyconf' )
292 def createConfigFile(self, config):
294 cfg_name = self.getUserConfigFile()
296 user_cfg = common.config_pyconf.Config()
298 user_cfg.addMapping('USER', common.config_pyconf.Mapping(user_cfg), "")
301 user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
302 "This is where salomeTools will work. You may (and probably do) change it.\n")
303 user_cfg.USER.addMapping('cvs_user', config.VARS.user,
304 "This is the user name used to access salome cvs base.\n")
305 user_cfg.USER.addMapping('svn_user', config.VARS.user,
306 "This is the user name used to access salome svn base.\n")
307 user_cfg.USER.addMapping('output_level', 3,
308 "This is the default output_level you want. 0=>no output, 5=>debug.\n")
309 user_cfg.USER.addMapping('publish_dir', os.path.join(os.path.expanduser('~'), 'websupport', 'satreport'), "")
310 user_cfg.USER.addMapping('editor', 'vi', "This is the editor used to modify configuration files\n")
311 user_cfg.USER.addMapping('browser', 'firefox', "This is the browser used to read html documentation\n")
312 user_cfg.USER.addMapping('pdf_viewer', 'evince', "This is the pdf_viewer used to read pdf documentation\n")
314 common.ensure_path_exists(config.VARS.personalDir)
315 common.ensure_path_exists(os.path.join(config.VARS.personalDir, 'Applications'))
317 f = open(cfg_name, 'w')
320 print(_("You can edit it to configure salomeTools (use: sat config --edit).\n"))
324 def getUserConfigFile(self):
325 '''Get the user config file
327 if not self.user_config_file_path:
328 raise common.SatException(_("Error in getUserConfigFile: missing user config file path"))
329 return self.user_config_file_path
332 def print_value(config, path, show_label, level=0, show_full_path=False):
333 '''Prints a value from the configuration. Prints recursively the values under the initial path.
334 :param config class 'common.config_pyconf.Config': The configuration from which the value is displayed.
335 :param path str : the path in the configuration of the value to print.
336 :param show_label boolean: if True, do a basic display. (useful for bash completion)
337 :param level int: The number of spaces to add before display.
338 :param show_full_path :
339 :return: The final config.
340 :rtype: class 'common.config_pyconf.Config'
343 # display all the path or not
347 vname = path.split('.')[-1]
349 # number of spaces before the display
350 tab_level = " " * level
352 # call to the function that gets the value of the path.
354 val = config.getByPath(path)
355 except Exception as e:
356 sys.stdout.write(tab_level)
357 sys.stdout.write("%s: ERROR %s\n" % (common.printcolors.printcLabel(vname), common.printcolors.printcError(str(e))))
360 # in this case, display only the value
362 sys.stdout.write(tab_level)
363 sys.stdout.write("%s: " % common.printcolors.printcLabel(vname))
365 # The case where the value has under values, do a recursive call to the function
366 if dir(val).__contains__('keys'):
367 if show_label: sys.stdout.write("\n")
368 for v in sorted(val.keys()):
369 print_value(config, path + '.' + v, show_label, level + 1)
370 elif val.__class__ == common.config_pyconf.Sequence or isinstance(val, list): # in this case, value is a list (or a Sequence)
371 if show_label: sys.stdout.write("\n")
374 print_value(config, path + "[" + str(index) + "]", show_label, level + 1)
376 else: # case where val is just a str
377 sys.stdout.write("%s\n" % val)
380 return _("The config command allows manipulation and operation on config files.")
383 def run(args, runner):
384 (options, args) = parser.parse_args(args)
385 print('Je suis dans la commande config ! Bien joué ! COUCOU')
387 print_value(runner.cfg, options.value, True, level=0, show_full_path=False)