All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
xmlModule.py
Go to the documentation of this file.
1 '''
2 Created on Jul 2, 2011
3 
4 @author: mplajner
5 '''
6 
7 import logging
8 
9 from cPickle import load, dump
10 from hashlib import md5 # pylint: disable=E0611
11 
12 from xml.dom import minidom
13 from xml.parsers.expat import ExpatError
14 
15 class XMLFile(object):
16  '''Takes care of XML file operations such as reading and writing.'''
17 
18  def __init__(self):
19  self.xmlResult = '<?xml version="1.0" encoding="UTF-8"?><env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">\n'
20  self.declaredVars = []
21  self.log = logging.getLogger('XMLFile')
22 
23  def variable(self, path, namespace='EnvSchema', name=None):
24  '''Returns list containing name of variable, action and value.
25 
26  @param path: a file name or a file-like object
27 
28  If no name given, returns list of lists of all variables and locals(instead of action 'local' is filled).
29  '''
30  isFilename = type(path) is str
31  if isFilename:
32  checksum = md5()
33  checksum.update(open(path, 'rb').read())
34  checksum = checksum.digest()
35 
36  cpath = path + "c" # preparsed file
37  try:
38  f = open(cpath, 'rb')
39  oldsum, data = load(f)
40  if oldsum == checksum:
41  return data
42  except IOError:
43  pass
44  except EOFError:
45  pass
46 
47  caller = path
48  else:
49  caller = None
50 
51  # Get file
52  try:
53  doc = minidom.parse(path)
54  except ExpatError, exc:
55  self.log.fatal('Failed to parse %s: %s', path, exc)
56  self.log.fatal(list(open(path))[exc.lineno-1].rstrip())
57  self.log.fatal(' ' * exc.offset + '^')
58  raise SystemExit(1)
59 
60  if namespace == '':
61  namespace = None
62 
63  ELEMENT_NODE = minidom.Node.ELEMENT_NODE
64  # Get all variables
65  nodes = doc.getElementsByTagNameNS(namespace, "config")[0].childNodes
66  variables = []
67  for node in nodes:
68  # if it is an element node
69  if node.nodeType == ELEMENT_NODE:
70  action = str(node.localName)
71 
72  if action == 'include':
73  if node.childNodes:
74  value = str(node.childNodes[0].data)
75  else:
76  value = ''
77  variables.append((action, (value, caller, str(node.getAttribute('hints')))))
78 
79  elif action == 'search_path':
80  if node.childNodes:
81  value = str(node.childNodes[0].data)
82  else:
83  value = ''
84  variables.append((action, (value, None, None)))
85 
86  else:
87  varname = str(node.getAttribute('variable'))
88  if name and varname != name:
89  continue
90 
91  if action == 'declare':
92  variables.append((action, (varname, str(node.getAttribute('type')), str(node.getAttribute('local')))))
93  else:
94  if node.childNodes:
95  value = str(node.childNodes[0].data)
96  else:
97  value = ''
98  variables.append((action, (varname, value, None)))
99 
100  if isFilename:
101  try:
102  f = open(cpath, 'wb')
103  dump((checksum, variables), f, protocol=2)
104  f.close()
105  except IOError:
106  pass
107  return variables
108 
109 
110  def resetWriter(self):
111  '''resets the buffer of writer'''
112  self.xmlResult = '<?xml version="1.0" encoding="UTF-8"?><env:config xmlns:env="EnvSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="EnvSchema ./EnvSchema.xsd ">\n'
113  self.declaredVars = []
114 
115  def writeToFile(self, outputFile=None):
116  '''Finishes the XML input and writes XML to file.'''
117  if outputFile is None:
118  raise IOError("No output file given")
119  self.xmlResult += '</env:config>'
120 
121  doc = minidom.parseString(self.xmlResult)
122  with open(outputFile, "w") as f:
123  f.write( doc.toxml() )
124 
125  return outputFile
126 
127  def writeVar(self, varName, action, value, vartype='list', local=False):
128  '''Writes a action to a file. Declare undeclared elements (non-local list is default type).'''
129  if action == 'declare':
130  self.xmlResult += '<env:declare variable="'+varName+'" type="'+ vartype.lower() +'" local="'+(str(local)).lower()+'" />\n'
131  self.declaredVars.append(varName)
132  return
133 
134  if varName not in self.declaredVars:
135  self.xmlResult += '<env:declare variable="'+varName+'" type="'+ vartype +'" local="'+(str(local)).lower()+'" />\n'
136  self.declaredVars.append(varName)
137  self.xmlResult += '<env:'+action+' variable="'+ varName +'">'+value+'</env:'+action+'>\n'
string type
Definition: gaudirun.py:151