]> git.phdru.name Git - extfs.d.git/blob - xml
Extended regular expression
[extfs.d.git] / xml
1 #! /usr/bin/env python
2 """XML Virtual FileSystem for Midnight Commander
3
4 The script requires Midnight Commander 3.1+
5 (http://www.midnight-commander.org/), Python 2.4+ (http://www.python.org/).
6
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.
11
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.
15
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
24 read-only.
25
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".
30
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.
35
36 The VFS was inspired by a FUSE xmlfs: https://github.com/halhen/xmlfs
37
38 """
39
40 __version__ = "1.0.1"
41 __author__ = "Oleg Broytman <phd@phdru.name>"
42 __copyright__ = "Copyright (C) 2013 PhiloSoft Design"
43 __license__ = "GPL"
44
45 force_implementation = None  # Can be None for default choice,
46                              # 'lxml', 'elementtree' or 'minidom'
47
48 use_minidom = True
49 use_elementtree = False
50 use_lxml = False
51
52 import math
53 import sys
54 import xml.dom.minidom
55
56 try:
57     import xml.etree.ElementTree as ET
58 except ImportError:
59     pass
60 else:
61     use_elementtree = True
62
63 try:
64     import lxml.etree as etree
65 except ImportError:
66     pass
67 else:
68     use_lxml = True
69
70 try:
71    import locale
72    use_locale = True
73 except ImportError:
74    use_locale = False
75
76 if use_locale:
77    # Get the default charset.
78    try:
79       lcAll = locale.getdefaultlocale()
80    except locale.Error, err:
81       print >>sys.stderr, "WARNING:", err
82       lcAll = []
83
84    if len(lcAll) == 2:
85       default_encoding = lcAll[1]
86    else:
87       try:
88          default_encoding = locale.getpreferredencoding()
89       except locale.Error, err:
90          print >>sys.stderr, "WARNING:", err
91          default_encoding = sys.getdefaultencoding()
92 else:
93    default_encoding = sys.getdefaultencoding()
94
95 import logging
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)
100
101 if len(sys.argv) < 3:
102     logger.critical("""\
103 XML Virtual FileSystem for Midnight Commander version %s
104 Author: %s
105 %s
106
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__
110 )
111     sys.exit(1)
112
113
114 locale.setlocale(locale.LC_ALL, '')
115
116
117 class XmlVfs(object):
118     """Abstract base class"""
119
120     supports_namespaces = False
121
122     def __init__(self):
123         self.parse()
124
125     def list(self):
126         self._list(self.getroot())
127
128     def _list(self, node, path=''):
129         n = len(self.getchildren(node))
130         if n:
131             width = int(math.log10(n)) + 1
132             template = "%%0%dd" % width
133         else:
134             template = "%d"
135         n = 0
136         for element in self.getchildren(node):
137             if not self.istag(element):
138                 continue
139             n += 1
140             tag = self.getlocalname(self.gettag(element))
141             if path:
142                 subpath = '%s/%s %s' % (path, template % n, tag)
143             else:
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)
156             if text:
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)
160
161     def get_tag_node(self, node, i):
162         n = 0
163         for element in self.getchildren(node):
164             if self.istag(element):
165                 n += 1
166                 if n == i:
167                     return element
168         xml_error('There are less than %d nodes' % i)
169
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)
177
178     def has_ns(self, node):
179         return False
180
181
182 class MiniDOMXmlVfs(XmlVfs):
183     def parse(self):
184         self.document = xml.dom.minidom.parse(sys.argv[2])
185
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]
190
191     def collect_text(self, node):
192         text_accumulator = []
193         for element in node.childNodes:
194             if element.localName:
195                 continue
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()
200             else:
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")
204
205     def getroot(self):
206         return self.document
207
208     def getchildren(self, node):
209         return node.childNodes
210
211     def gettag(self, node):
212         return node.localName
213
214     def istag(self, node):
215         return bool(node.localName)
216
217     def getlocalname(self, name):
218         return name
219
220
221 if use_elementtree or use_lxml:
222     class CommonEtreeXmlVfs(XmlVfs):
223         def getattrs(self, node):
224             return node.attrib.items()
225
226         def collect_text(self, node):
227             text_accumulator = []
228             if node.text:
229                 text = node.text.strip()
230                 if text: text_accumulator.append(text)
231             for element in node:
232                 if not self.istag(element):
233                     text = u"<!--%s-->" % element.text
234                     text_accumulator.append(text)
235             if node.tail:
236                 text = node.tail.strip()
237                 if text: text_accumulator.append(text)
238             return '\n'.join(text_accumulator).encode(default_encoding, "replace")
239
240         def getchildren(self, node):
241             return list(node)
242
243         def gettag(self, node):
244             return node.tag
245
246         def istag(self, node):
247             return isinstance(node.tag, basestring)
248
249
250 if use_elementtree:
251     class ElementTreeXmlVfs(CommonEtreeXmlVfs):
252         def parse(self):
253             # Copied from http://effbot.org/zone/element-pi.ht
254
255             class PIParser(ET.XMLTreeBuilder):
256
257                 def __init__(self):
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", {})
263
264                 def close(self):
265                     self._target.end("document")
266                     return ET.XMLTreeBuilder.close(self)
267
268                 def handle_comment(self, data):
269                     self._target.start(ET.Comment, {})
270                     self._target.data(data)
271                     self._target.end(ET.Comment)
272
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)
277
278             self.document = ET.parse(sys.argv[2], PIParser())
279
280         def getroot(self):
281             return self.document.getroot()
282
283         def getlocalname(self, name):
284             if name.startswith('{'):
285                 name = name.split('}', 1)[1]  # Remove XML namespace
286             return name
287
288
289 if use_lxml:
290     class LxmlEtreeXmlVfs(CommonEtreeXmlVfs):
291         supports_namespaces = True
292
293         def parse(self):
294             self.document = etree.parse(sys.argv[2])
295
296         def getroot(self):
297             return [self.document.getroot()]
298
299         def getlocalname(self, name):
300             return etree.QName(name).localname
301
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:
308                     del this_nsmap[key]
309             return this_nsmap
310
311         def has_ns(self, node):
312             return bool(self._get_local_ns(node))
313
314         def ns2text(self, node):
315             ns_accumulator = []
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)
322
323
324 def build_xmlvfs():
325     if force_implementation is None:
326         if use_lxml:
327             return LxmlEtreeXmlVfs()
328         elif use_elementtree:
329             return ElementTreeXmlVfs()
330         else:
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()
338     else:
339         raise ValueError('Unknown implementation "%s", expected "minidom", "elementtree" or "lxml"' % force_implementation)
340
341
342 def mcxml_list():
343     """List the entire VFS"""
344
345     xmlvfs = build_xmlvfs()
346     xmlvfs.list()
347
348
349 def mcxml_copyout():
350     """Extract a file from the VFS"""
351
352     xmlvfs = build_xmlvfs()
353     xml_filename = sys.argv[3]
354     real_filename = sys.argv[4]
355
356     node = xmlvfs.getroot()
357     for path_comp in xml_filename.split('/'):
358         if ' ' in path_comp:
359             i = int(path_comp.split(' ', 1)[0])
360             node = xmlvfs.get_tag_node(node, i)
361         elif path_comp in ('attributes', 'namespaces', 'text'):
362             break
363         else:
364             xml_error('Unknown file')
365
366     if path_comp == 'attributes':
367         if xmlvfs.getattrs(node):
368             text = xmlvfs.attrs2text(node)
369         else:
370             xml_error('There are no attributes')
371
372     elif path_comp == 'namespaces':
373         if xmlvfs.supports_namespaces and xmlvfs.has_ns(node):
374             text = xmlvfs.ns2text(node)
375         else:
376             xml_error('There are no namespaces')
377
378     elif path_comp == 'text':
379         text = xmlvfs.collect_text(node)
380
381     else:
382         xml_error('Unknown file')
383
384     outfile = open(real_filename, 'w')
385     outfile.write(text)
386     outfile.close()
387
388
389 def mcxml_copyin():
390     """Put a file to the VFS"""
391     sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
392
393 def mcxml_rm():
394     """Remove a file from the VFS"""
395     sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
396
397 mcxml_rmdir = mcxml_rm
398
399 def mcxml_mkdir():
400     """Create a directory in the VFS"""
401     sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
402
403
404 def xml_error(error_str):
405     logger.critical("Error walking XML file: %s", error_str)
406     sys.exit(1)
407
408 command = sys.argv[1]
409 procname = "mcxml_" + command
410
411 g = globals()
412 if not g.has_key(procname):
413     logger.critical("Unknown command %s", command)
414     sys.exit(1)
415
416 try:
417     g[procname]()
418 except SystemExit:
419     raise
420 except:
421     logger.exception("Error during run")