2 """XML Virtual FileSystem for Midnight Commander
4 The script requires Midnight Commander 3.1+
5 (http://www.midnight-commander.org/), Python 2.4+ (http://www.python.org/).
7 For mc 4.7+ just put the script in $HOME/[.local/share/].mc/extfs.d.
8 For older versions put it in /usr/[local/][lib|share]/mc/extfs
9 and add a line "xml" to the /usr/[local/][lib|share]/mc/extfs/extfs.ini.
10 Make the script executable.
12 For mc 4.7+ run this "cd" command in the Midnight Commander (in the "bindings"
13 file the command is "%cd"): cd file/xml://; in older versions it is
14 cd file#xml, where "file" is the name of your XML file.
16 The VFS represents tags as directories; the directories are numbered to
17 distinguish tags with the same name; also numbering helps to sort tags by their
18 order in XML instead of sorting them by name. Attributes, text nodes and
19 comments are represented as text files; attributes are shown in a file named
20 "attributes", attributes are listed in the file as name=value lines (I
21 deliberately ignore a small chance of newline characters in values); names and
22 values are reencoded to the console encoding. Text nodes and comments are
23 collected in a file named "text", stripped and reencoded. The filesystem is
26 Implementation based on minidom doesn't understand namespaces, it just shows
27 them among other attributes. ElementTree-based implementation doesn't show
28 namespaces at all. Implementation based on lxml.etree shows namespaces in a
29 separate file "namespaces"; every child tag includes its parent's namespaces.
31 It is useful to have a top-down view on an XML structure but it's especially
32 convenient to extract text values from tags. One can get, for example, a
33 base64-encoded image - just walk down the VFS to the tag's directory and copy
34 its text file to a real file.
36 The VFS was inspired by a FUSE xmlfs: https://github.com/halhen/xmlfs
41 __author__ = "Oleg Broytman <phd@phdru.name>"
42 __copyright__ = "Copyright (C) 2013 PhiloSoft Design"
45 force_implementation = None # Can be None for default choice,
46 # 'lxml', 'elementtree' or 'minidom'
49 use_elementtree = False
54 import xml.dom.minidom
57 import xml.etree.ElementTree as ET
61 use_elementtree = True
64 import lxml.etree as etree
77 # Get the default charset.
79 lcAll = locale.getdefaultlocale()
80 except locale.Error, err:
81 print >>sys.stderr, "WARNING:", err
85 default_encoding = lcAll[1]
88 default_encoding = locale.getpreferredencoding()
89 except locale.Error, err:
90 print >>sys.stderr, "WARNING:", err
91 default_encoding = sys.getdefaultencoding()
93 default_encoding = sys.getdefaultencoding()
96 logger = logging.getLogger('xml-mcextfs')
97 log_err_handler = logging.StreamHandler(sys.stderr)
98 logger.addHandler(log_err_handler)
99 logger.setLevel(logging.INFO)
101 if len(sys.argv) < 3:
103 XML Virtual FileSystem for Midnight Commander version %s
107 This is not a program. Put the script in $HOME/[.local/share/].mc/extfs.d or
108 /usr/[local/][lib|share]/mc/extfs. For more information read the source!""",
109 __version__, __author__, __copyright__
114 locale.setlocale(locale.LC_ALL, '')
117 class XmlVfs(object):
118 """Abstract base class"""
120 supports_namespaces = False
126 self._list(self.getroot())
128 def _list(self, node, path=''):
129 n = len(self.getchildren(node))
131 width = int(math.log10(n)) + 1
132 template = "%%0%dd" % width
136 for element in self.getchildren(node):
137 if not self.istag(element):
140 tag = self.getlocalname(self.gettag(element))
142 subpath = '%s/%s %s' % (path, template % n, tag)
144 subpath = '%s %s' % (template % n, tag)
145 subpath_encoded = subpath.encode(default_encoding, "replace")
146 print "dr-xr-xr-x 1 user group 0 Jan 1 00:00 %s" % subpath_encoded
147 if self.hasattrs(element):
148 attr_text = self.attrs2text(element)
149 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/attributes" % (
150 len(attr_text), subpath_encoded)
151 if self.supports_namespaces and self.has_ns(element):
152 ns_text = self.ns2text(element)
153 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/namespaces" % (
154 len(ns_text), subpath_encoded)
155 text = self.collect_text(element)
157 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/text" % (
158 len(text), subpath_encoded)
159 self._list(element, subpath)
161 def has_ns(self, node):
164 def get_child_node(self, node, i):
166 for element in self.getchildren(node):
167 if self.istag(element):
171 xml_error('There are less than %d nodes' % i)
174 class MiniDOMXmlVfs(XmlVfs):
176 self.document = xml.dom.minidom.parse(sys.argv[2])
178 def hasattrs(self, node):
179 return bool(node.attributes)
181 def attrs2text(self, node):
182 attrs = node.attributes
183 attrs = [attrs.item(i) for i in range(attrs.length)]
184 return '\n'.join(["%s=%s" %
185 (a.name.encode(default_encoding, "replace"),
186 a.value.encode(default_encoding, "replace"))
189 def collect_text(self, node):
190 text_accumulator = []
191 for element in node.childNodes:
192 if element.localName:
194 elif element.nodeType == element.COMMENT_NODE:
195 text = u"<!--%s-->" % element.nodeValue
196 elif element.nodeType == element.TEXT_NODE:
197 text = element.nodeValue.strip()
199 xml_error("Unknown node type %d" % element.nodeType)
200 if text: text_accumulator.append(text)
201 return '\n'.join(text_accumulator).encode(default_encoding, "replace")
206 def getchildren(self, node):
207 return node.childNodes
209 def gettag(self, node):
210 return node.localName
212 def istag(self, node):
213 return bool(node.localName)
215 def getlocalname(self, name):
219 if use_elementtree or use_lxml:
220 class CommonEtreeXmlVfs(XmlVfs):
221 def hasattrs(self, node):
222 return bool(node.attrib)
224 def collect_text(self, node):
225 text_accumulator = []
227 text = node.text.strip()
228 if text: text_accumulator.append(text)
230 if not self.istag(element):
231 text = u"<!--%s-->" % element.text
232 text_accumulator.append(text)
234 text = node.tail.strip()
235 if text: text_accumulator.append(text)
236 return '\n'.join(text_accumulator).encode(default_encoding, "replace")
239 return self.document.getroot()
241 def getchildren(self, node):
244 def gettag(self, node):
247 def istag(self, node):
248 return isinstance(node.tag, basestring)
252 class ElementTreeXmlVfs(CommonEtreeXmlVfs):
254 # Copied from http://effbot.org/zone/element-pi.ht
256 class PIParser(ET.XMLTreeBuilder):
259 ET.XMLTreeBuilder.__init__(self)
260 # assumes ElementTree 1.2.X
261 self._parser.CommentHandler = self.handle_comment
262 self._parser.ProcessingInstructionHandler = self.handle_pi
263 self._target.start("document", {})
266 self._target.end("document")
267 return ET.XMLTreeBuilder.close(self)
269 def handle_comment(self, data):
270 self._target.start(ET.Comment, {})
271 self._target.data(data)
272 self._target.end(ET.Comment)
274 def handle_pi(self, target, data):
275 self._target.start(ET.PI, {})
276 self._target.data(target + " " + data)
277 self._target.end(ET.PI)
279 self.document = ET.parse(sys.argv[2], PIParser())
281 def attrs2text(self, node):
282 attr_accumulator = []
283 for name, value in node.attrib.items():
284 name = name.encode(default_encoding, "replace")
285 value = value.encode(default_encoding, "replace")
286 if name.startswith('{'):
287 name = name.split('}', 1)[1] # Remove XML namespace
288 attr_accumulator.append("%s=%s" % (name, value))
289 return '\n'.join(attr_accumulator)
291 def getlocalname(self, name):
292 if name.startswith('{'):
293 name = name.split('}', 1)[1] # Remove XML namespace
298 class LxmlEtreeXmlVfs(CommonEtreeXmlVfs):
299 supports_namespaces = True
302 self.document = etree.parse(sys.argv[2])
304 def attrs2text(self, node):
305 attr_accumulator = []
306 for name, value in node.attrib.items():
307 name = etree.QName(name).localname.encode(default_encoding, "replace")
308 value = value.encode(default_encoding, "replace")
309 attr_accumulator.append("%s=%s" % (name, value))
310 return '\n'.join(attr_accumulator)
312 def has_ns(self, node):
313 return bool(node.nsmap)
315 def ns2text(self, node):
317 for name, value in node.nsmap.items():
318 name = name.encode(default_encoding, "replace")
319 value = value.encode(default_encoding, "replace")
320 ns_accumulator.append("%s=%s" % (name, value))
321 return '\n'.join(ns_accumulator)
324 return [self.document.getroot()]
326 def getlocalname(self, name):
327 return etree.QName(name).localname
331 if force_implementation is None:
333 return LxmlEtreeXmlVfs()
334 elif use_elementtree:
335 return ElementTreeXmlVfs()
337 return MiniDOMXmlVfs()
338 elif force_implementation == 'minidom':
339 return MiniDOMXmlVfs()
340 elif force_implementation == 'elementtree':
341 return ElementTreeXmlVfs()
342 elif force_implementation == 'lxml':
343 return LxmlEtreeXmlVfs()
345 raise ValueError('Unknown implementation "%s", expected "minidom", "elementtree" or "lxml"' % force_implementation)
349 """List the entire VFS"""
351 xmlvfs = build_xmlvfs()
356 """Extract a file from the VFS"""
358 xmlvfs = build_xmlvfs()
359 xml_filename = sys.argv[3]
360 real_filename = sys.argv[4]
362 node = xmlvfs.getroot()
363 for path_comp in xml_filename.split('/'):
365 i = int(path_comp.split(' ', 1)[0])
366 node = xmlvfs.get_child_node(node, i)
367 elif path_comp in ('attributes', 'namespaces', 'text'):
370 xml_error('Unknown file')
372 if path_comp == 'attributes':
373 if xmlvfs.hasattrs(node):
374 text = xmlvfs.attrs2text(node)
376 xml_error('There are no attributes')
378 elif path_comp == 'namespaces':
379 if xmlvfs.has_ns(node):
380 text = xmlvfs.ns2text(node)
382 xml_error('There are no attributes')
384 elif path_comp == 'text':
385 text = xmlvfs.collect_text(node)
388 xml_error('Unknown file')
390 outfile = open(real_filename, 'w')
396 """Put a file to the VFS"""
397 sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
400 """Remove a file from the VFS"""
401 sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
403 mcxml_rmdir = mcxml_rm
406 """Create a directory in the VFS"""
407 sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
410 def xml_error(error_str):
411 logger.critical("Error walking XML file: %s", error_str)
414 command = sys.argv[1]
415 procname = "mcxml_" + command
418 if not g.has_key(procname):
419 logger.critical("Unknown command %s", command)
427 logger.exception("Error during run")