2 Created on Jun 27, 2011
8 from time
import gmtime, strftime
12 '''object to hold settings of environment'''
14 def __init__(self, loadFromSystem=True, useAsWriter=False, reportLevel=1, searchPath=None):
15 '''Initial variables to be pushed and setup
17 append switch between append and prepend for initial variables.
18 loadFromSystem causes variable`s system value to be loaded on first encounter.
19 If useAsWriter == True than every change to variables is recorded to XML file.
20 reportLevel sets the level of messaging.
28 if searchPath
is not None:
29 self.searchPath.extend(searchPath)
31 self.searchPath.extend(os.environ[
'ENVXMLPATH'].split(os.pathsep))
40 self.
actions[
'set'] =
lambda n, v, _: self.
set(n, v)
62 dot.expandVars =
False
67 def _locate(self, filename, caller=None, hints=None):
69 Find 'filename' in the internal search path.
71 from os.path
import isabs, isfile, join, dirname, normpath, abspath
77 elif type(hints)
is str:
82 localfile = join(calldir, filename)
86 hints = [join(calldir, hint)
for hint
in hints]
90 for f
in [normpath(join(d, filename))
94 from errno
import ENOENT
95 raise OSError(ENOENT,
'cannot find file in %r' % self.
searchPath, filename)
97 def vars(self, strings=True):
98 '''returns dictionary of all variables optionally converted to string'''
100 return dict([(n, v.value(
True))
for n, v
in self.variables.items()])
105 '''Gets a single variable. If not available then tries to load from system.'''
109 return os.environ[name]
111 def search(self, varName, expr, regExp=False):
112 '''Searches in a variable for a value.'''
117 Guess the type of the variable from its name: if the name contains
118 'PATH' or 'DIRS', then the variable is a list, otherwise it is a scalar.
120 varname = varname.upper()
121 if 'PATH' in varname
or 'DIRS' in varname:
127 '''Creates an instance of new variable. It loads values from the OS if the variable is not local.'''
131 if not isinstance(local, bool):
132 if str(local).lower() ==
'true':
137 if name
in self.variables.keys():
141 if vartype.lower() ==
"list":
148 if vartype.lower() ==
"list":
155 a.set(os.environ[name], os.pathsep, environment=self.
variables)
161 '''Appends to an existing variable.'''
170 '''Prepends to an existing variable, or create a new one.'''
178 def set(self, name, value):
179 '''Sets a single variable - overrides any previous value!'''
189 '''Sets a single variable only if it is not already set!'''
203 v.set(os.environ[name], os.pathsep, environment=self.
variables)
213 '''Unsets a single variable to an empty value - overrides any previous value!'''
220 def remove(self, name, value, regexp=False):
221 '''Remove value from variable.'''
230 self.
remove(name, value,
True)
234 '''Searches for appearance of variable in a file.'''
236 variable = XMLFile.variable(filename, name=varName)
239 def loadXML(self, fileName=None, namespace='EnvSchema'):
240 '''Loads XML file for input variables.'''
242 fileName = self.
_locate(fileName)
245 self.loadedFiles.add(fileName)
248 self._fileDirStack.append(dot.value())
250 dot.set(os.path.dirname(fileName))
251 variables = XMLfile.variable(fileName, namespace=namespace)
252 for i, (action, args)
in enumerate(variables):
254 self.report.addError(
'Node {0}: No action taken with var "{1}". Probably wrong action argument: "{2}".'.
format(i, args[0], action))
258 dot.set(self._fileDirStack.pop())
263 '''Renew writer for new input.'''
264 self.writer.resetWriter()
268 '''Finishes input of XML file and closes the file.'''
269 self.writer.writeToFile(outputFile)
273 '''Creates an output file with a specified name to be used for setting variables by sourcing this file'''
274 f = open(fileName,
'w')
276 f.write(
'#!/bin/bash\n')
278 if not self[variable].local:
279 f.write(
'export ' +variable+
'='+self[variable].value(
True, os.pathsep)+
'\n')
281 f.write(
'#!/bin/csh\n')
283 if not self[variable].local:
284 f.write(
'setenv ' +variable+
' '+self[variable].value(
True, os.pathsep)+
'\n')
287 f.write(
'REM This is an enviroment settings file generated on '+strftime(
"%a, %d %b %Y %H:%M:%S\n", gmtime()))
289 if not self[variable].local:
290 f.write(
'set '+variable+
'='+self[variable].value(
True, os.pathsep)+
'\n')
296 '''Writes the current state of environment to a XML file.
298 NOTE: There is no trace of actions taken, variables are written with a set action only.
305 writer.writeToFile(fileName)
309 '''Loads all variables from the current system settings.'''
310 for k, v
in os.environ.items():
316 Call the variable processors on all the variables.
318 for v
in self.variables.values():
322 '''Returns a variable string with separator separator from the values list'''
326 stri = stri[0:len(stri)-1]
331 '''Writes single variable to XML file.'''
332 if isinstance(value, list):
334 self.writer.writeVar(name, action, value, vartype, local)
341 if key
in self.variables.keys():
342 self.report.addWarn(
'Addition canceled because of duplicate entry. Var: "' + key +
'" value: "' + value +
'".')
354 return item
in self.variables.keys()
357 return len(self.variables.keys())