]> git.phdru.name Git - extfs.d.git/blob - xml-minidom
f3e8ff76878d01979399a88156c6f3417f9f4023
[extfs.d.git] / xml-minidom
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+ 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 It is useful to have a top-down view on an XML structure but it's especially
27 convenient to extract text values from tags. One can get, for example, a
28 base64-encoded image - just walk down the VFS to the tag's directory and copy
29 its text file to a real file.
30
31 The VFS was inspired by a FUSE xmlfs: https://github.com/halhen/xmlfs
32
33 """
34
35 __version__ = "0.4.0"
36 __author__ = "Oleg Broytman <phd@phdru.name>"
37 __copyright__ = "Copyright (C) 2013 PhiloSoft Design"
38 __license__ = "GPL"
39
40 import math
41 import sys
42 import xml.dom.minidom
43
44 try:
45    import locale
46    use_locale = True
47 except ImportError:
48    use_locale = False
49
50 if use_locale:
51    # Get the default charset.
52    try:
53       lcAll = locale.getdefaultlocale()
54    except locale.Error, err:
55       print >>sys.stderr, "WARNING:", err
56       lcAll = []
57
58    if len(lcAll) == 2:
59       default_encoding = lcAll[1]
60    else:
61       try:
62          default_encoding = locale.getpreferredencoding()
63       except locale.Error, err:
64          print >>sys.stderr, "WARNING:", err
65          default_encoding = sys.getdefaultencoding()
66 else:
67    default_encoding = sys.getdefaultencoding()
68
69 import logging
70 logger = logging.getLogger('xml-mcextfs')
71 log_err_handler = logging.StreamHandler(sys.stderr)
72 logger.addHandler(log_err_handler)
73 logger.setLevel(logging.INFO)
74
75 if len(sys.argv) < 3:
76     logger.critical("""\
77 XML Virtual FileSystem for Midnight Commander version %s
78 Author: %s
79 %s
80
81 This is not a program. Put the script in $HOME/[.local/share/].mc/extfs.d or
82 /usr/[local/][lib|share]/mc/extfs. For more information read the source!""",
83    __version__, __author__, __copyright__
84 )
85     sys.exit(1)
86
87
88 locale.setlocale(locale.LC_ALL, '')
89
90 class XmlVfs(object):
91     def __init__(self):
92         self.parse()
93
94 class MiniDOM(XmlVfs):
95     def parse(self):
96         self.document = xml.dom.minidom.parse(sys.argv[2])
97
98     def hasattrs(self, node):
99         return bool(node.attributes)
100
101     def attrs2text(self, node):
102         attrs = node.attributes
103         attrs = [attrs.item(i) for i in range (attrs.length)]
104         return '\n'.join(["%s=%s" %
105             (a.name.encode(default_encoding, "replace"),
106             a.value.encode(default_encoding, "replace"))
107             for a in attrs])
108
109     def collect_text(self, node):
110         text_accumulator = []
111         for element in node.childNodes:
112             if element.localName:
113                 continue
114             elif element.nodeType == element.COMMENT_NODE:
115                 text = u"<!--%s-->" % element.nodeValue
116             elif element.nodeType == element.TEXT_NODE:
117                 text = element.nodeValue.strip()
118             else:
119                 xml_error("Unknown node type %d" % element.nodeType)
120             if text: text_accumulator.append(text)
121         return '\n'.join(text_accumulator).encode(default_encoding, "replace")
122
123     def list(self):
124         self._list(self.document)
125
126     def _list(self, node, path=''):
127         childNodes = node.childNodes
128         n = 0
129         for element in childNodes:
130             if element.localName:
131                 n += 1
132         if n:
133             width = int(math.log10(n))+1
134             template = "%%0%dd" % width
135         else:
136             template = "%d"
137         n = 0
138         for element in childNodes:
139             if element.localName:
140                 n += 1
141                 if path:
142                     subpath = '%s/%s %s' % (path, template % n, element.localName)
143                 else:
144                     subpath = '%s %s' % (template % n, element.localName)
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                 text = self.collect_text(element)
152                 if text:
153                     print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/text" % (
154                         len(text), subpath_encoded)
155                 self._list(element, subpath)
156
157     def getroot(self):
158         return self.document
159
160     def get_child_node(self, node, i):
161         n = 0
162         for element in node.childNodes:
163             if element.localName:
164                 n += 1
165                 if n == i:
166                     return element
167         xml_error('There are less than %d nodes' % i)
168
169
170 def mcxml_list():
171     """List the entire VFS"""
172
173     xmlvfs = MiniDOM()
174     xmlvfs.list()
175
176
177 def mcxml_copyout():
178     """Extract a file from the VFS"""
179
180     xmlvfs = MiniDOM()
181     xml_filename = sys.argv[3]
182     real_filename = sys.argv[4]
183
184     node = xmlvfs.getroot()
185     for path_comp in xml_filename.split('/'):
186         if ' ' in path_comp:
187             i = int(path_comp.split(' ', 1)[0])
188             node = xmlvfs.get_child_node(node, i)
189         elif path_comp in ('attributes', 'text'):
190             break
191         else:
192             xml_error('Unknown file')
193
194     if path_comp == 'attributes':
195         if xmlvfs.hasattrs(node):
196             text = xmlvfs.attrs2text(node)
197         else:
198             xml_error('There are no attributes')
199
200     if path_comp == 'text':
201         text = xmlvfs.collect_text(node)
202
203     outfile = open(real_filename, 'w')
204     outfile.write(text)
205     outfile.close()
206
207
208 def mcxml_copyin():
209     """Put a file to the VFS"""
210     sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
211
212 def mcxml_rm():
213     """Remove a file from the VFS"""
214     sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
215
216 mcxml_rmdir = mcxml_rm
217
218 def mcxml_mkdir():
219     """Create a directory in the VFS"""
220     sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
221
222
223 def xml_error(error_str):
224     logger.critical("Error walking XML file: %s", error_str)
225     sys.exit(1)
226
227 command = sys.argv[1]
228 procname = "mcxml_" + command
229
230 g = globals()
231 if not g.has_key(procname):
232     logger.critical("Unknown command %s", command)
233     sys.exit(1)
234
235 try:
236     g[procname]()
237 except SystemExit:
238     raise
239 except:
240     logger.exception("Error during run")