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".
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.getattrs(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 get_tag_node(self, node, i):
163 for element in self.getchildren(node):
164 if self.istag(element):
168 xml_error('There are less than %d nodes' % i)
170 def attrs2text(self, node):
171 attr_accumulator = []
172 for name, value in self.getattrs(node):
173 name = self.getlocalname(name).encode(default_encoding, "replace")
174 value = value.encode(default_encoding, "replace")
175 attr_accumulator.append("%s=%s" % (name, value))
176 return '\n'.join(attr_accumulator)
178 def has_ns(self, node):
182 class MiniDOMXmlVfs(XmlVfs):
184 self.document = xml.dom.minidom.parse(sys.argv[2])
186 def getattrs(self, node):
187 attrs = node.attributes
188 attrs = [attrs.item(i) for i in range(attrs.length)]
189 return [(a.name, a.value) for a in attrs]
191 def collect_text(self, node):
192 text_accumulator = []
193 for element in node.childNodes:
194 if element.localName:
196 elif element.nodeType == element.COMMENT_NODE:
197 text = u"<!--%s-->" % element.nodeValue
198 elif element.nodeType == element.TEXT_NODE:
199 text = element.nodeValue.strip()
201 xml_error("Unknown node type %d" % element.nodeType)
202 if text: text_accumulator.append(text)
203 return '\n'.join(text_accumulator).encode(default_encoding, "replace")
208 def getchildren(self, node):
209 return node.childNodes
211 def gettag(self, node):
212 return node.localName
214 def istag(self, node):
215 return bool(node.localName)
217 def getlocalname(self, name):
221 if use_elementtree or use_lxml:
222 class CommonEtreeXmlVfs(XmlVfs):
223 def getattrs(self, node):
224 return node.attrib.items()
226 def collect_text(self, node):
227 text_accumulator = []
229 text = node.text.strip()
230 if text: text_accumulator.append(text)
232 if not self.istag(element):
233 text = u"<!--%s-->" % element.text
234 text_accumulator.append(text)
236 text = node.tail.strip()
237 if text: text_accumulator.append(text)
238 return '\n'.join(text_accumulator).encode(default_encoding, "replace")
240 def getchildren(self, node):
243 def gettag(self, node):
246 def istag(self, node):
247 return isinstance(node.tag, basestring)
251 class ElementTreeXmlVfs(CommonEtreeXmlVfs):
253 # Copied from http://effbot.org/zone/element-pi.ht
255 class PIParser(ET.XMLTreeBuilder):
258 ET.XMLTreeBuilder.__init__(self)
259 # assumes ElementTree 1.2.X
260 self._parser.CommentHandler = self.handle_comment
261 self._parser.ProcessingInstructionHandler = self.handle_pi
262 self._target.start("document", {})
265 self._target.end("document")
266 return ET.XMLTreeBuilder.close(self)
268 def handle_comment(self, data):
269 self._target.start(ET.Comment, {})
270 self._target.data(data)
271 self._target.end(ET.Comment)
273 def handle_pi(self, target, data):
274 self._target.start(ET.PI, {})
275 self._target.data(target + " " + data)
276 self._target.end(ET.PI)
278 self.document = ET.parse(sys.argv[2], PIParser())
281 return self.document.getroot()
283 def getlocalname(self, name):
284 if name.startswith('{'):
285 name = name.split('}', 1)[1] # Remove XML namespace
290 class LxmlEtreeXmlVfs(CommonEtreeXmlVfs):
291 supports_namespaces = True
294 self.document = etree.parse(sys.argv[2])
297 return [self.document.getroot()]
299 def getlocalname(self, name):
300 return etree.QName(name).localname
302 def _get_local_ns(self, node):
303 this_nsmap = node.nsmap
304 parent = node.getparent()
305 if parent is not None:
306 parents_nsmap = parent.nsmap
307 for key in parents_nsmap:
311 def has_ns(self, node):
312 return bool(self._get_local_ns(node))
314 def ns2text(self, node):
316 for name, value in self._get_local_ns(node).items():
317 if name is None: name = ''
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)
325 if force_implementation is None:
327 return LxmlEtreeXmlVfs()
328 elif use_elementtree:
329 return ElementTreeXmlVfs()
331 return MiniDOMXmlVfs()
332 elif force_implementation == 'minidom':
333 return MiniDOMXmlVfs()
334 elif force_implementation == 'elementtree':
335 return ElementTreeXmlVfs()
336 elif force_implementation == 'lxml':
337 return LxmlEtreeXmlVfs()
339 raise ValueError('Unknown implementation "%s", expected "minidom", "elementtree" or "lxml"' % force_implementation)
343 """List the entire VFS"""
345 xmlvfs = build_xmlvfs()
350 """Extract a file from the VFS"""
352 xmlvfs = build_xmlvfs()
353 xml_filename = sys.argv[3]
354 real_filename = sys.argv[4]
356 node = xmlvfs.getroot()
357 for path_comp in xml_filename.split('/'):
359 i = int(path_comp.split(' ', 1)[0])
360 node = xmlvfs.get_tag_node(node, i)
361 elif path_comp in ('attributes', 'namespaces', 'text'):
364 xml_error('Unknown file')
366 if path_comp == 'attributes':
367 if xmlvfs.getattrs(node):
368 text = xmlvfs.attrs2text(node)
370 xml_error('There are no attributes')
372 elif path_comp == 'namespaces':
373 if xmlvfs.supports_namespaces and xmlvfs.has_ns(node):
374 text = xmlvfs.ns2text(node)
376 xml_error('There are no namespaces')
378 elif path_comp == 'text':
379 text = xmlvfs.collect_text(node)
382 xml_error('Unknown file')
384 outfile = open(real_filename, 'w')
390 """Put a file to the VFS"""
391 sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
394 """Remove a file from the VFS"""
395 sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
397 mcxml_rmdir = mcxml_rm
400 """Create a directory in the VFS"""
401 sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
404 def xml_error(error_str):
405 logger.critical("Error walking XML file: %s", error_str)
408 command = sys.argv[1]
409 procname = "mcxml_" + command
412 if not g.has_key(procname):
413 logger.critical("Unknown command %s", command)
421 logger.exception("Error during run")