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+ put the script in $HOME/.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 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.
31 The VFS was inspired by a FUSE xmlfs: https://github.com/halhen/xmlfs
36 __author__ = "Oleg Broytman <phd@phdru.name>"
37 __copyright__ = "Copyright (C) 2013 PhiloSoft Design"
42 import xml.dom.minidom
51 # Get the default charset.
53 lcAll = locale.getdefaultlocale()
54 except locale.Error, err:
55 print >>sys.stderr, "WARNING:", err
59 default_encoding = lcAll[1]
62 default_encoding = locale.getpreferredencoding()
63 except locale.Error, err:
64 print >>sys.stderr, "WARNING:", err
65 default_encoding = sys.getdefaultencoding()
67 default_encoding = sys.getdefaultencoding()
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)
77 XML Virtual FileSystem for Midnight Commander version %s
81 This is not a program. Put the script in $HOME/.mc/extfs.d or
82 /usr/[local/][lib|share]/mc/extfs. For more information read the source!""",
83 __version__, __author__, __copyright__
88 locale.setlocale(locale.LC_ALL, '')
90 def _attrs2text(attrs):
91 attrs = [attrs.item(i) for i in range (attrs.length)]
92 return '\n'.join(["%s=%s" %
93 (a.name.encode(default_encoding, "replace"),
94 a.value.encode(default_encoding, "replace"))
97 def _collect_text(node):
99 for element in node.childNodes:
100 if element.localName:
102 elif element.nodeType == element.COMMENT_NODE:
103 text = u"<!--%s-->" % element.nodeValue
104 elif element.nodeType == element.TEXT_NODE:
105 text = element.nodeValue.strip()
107 xml_error("Unknown node type %d" % element.nodeType)
108 if text: text_accumulator.append(text)
109 return '\n'.join(text_accumulator).encode(default_encoding, "replace")
111 def _list(node, path=''):
112 childNodes = node.childNodes
114 for element in childNodes:
115 if element.localName:
118 width = int(math.log10(n))+1
119 template = "%%0%dd" % width
123 for element in childNodes:
124 if element.localName:
127 subpath = '%s/%s %s' % (path, template % n, element.localName)
129 subpath = '%s %s' % (template % n, element.localName)
130 subpath_encoded = subpath.encode(default_encoding, "replace")
131 print "dr--r--r-- 1 user group 0 Jan 1 00:00 %s" % subpath_encoded
132 attrs = element.attributes
134 attr_text = _attrs2text(attrs)
135 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/attributes" % (
136 len(attr_text), subpath_encoded)
137 _list(element, subpath)
139 text = _collect_text(node)
141 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/text" % (
142 len(text), path.encode(default_encoding, "replace"))
145 """List the entire VFS"""
147 dom = xml.dom.minidom.parse(sys.argv[2])
151 def _get_child_node(node, i):
153 for element in node.childNodes:
154 if element.localName:
158 xml_error('There are less than %d nodes' % i)
161 """Extract a file from the VFS"""
163 node = xml.dom.minidom.parse(sys.argv[2])
164 xml_filename = sys.argv[3]
165 real_filename = sys.argv[4]
167 for path_comp in xml_filename.split('/'):
169 i = int(path_comp.split(' ', 1)[0])
170 node = _get_child_node(node, i)
171 elif path_comp in ('attributes', 'text'):
174 xml_error('Unknown file')
176 if path_comp == 'attributes':
177 attrs = node.attributes
179 text = _attrs2text(attrs)
181 xml_error('There are no attributes')
183 if path_comp == 'text':
184 text = _collect_text(node)
186 outfile = open(real_filename, 'w')
192 """Put a file to the VFS"""
193 sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
196 """Remove a file from the VFS"""
197 sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
199 mcxml_rmdir = mcxml_rm
202 """Create a directory in the VFS"""
203 sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
206 def xml_error(error_str):
207 logger.critical("Error walking XML file: %s", error_str)
210 command = sys.argv[1]
211 procname = "mcxml_" + command
214 if not g.has_key(procname):
215 logger.critical("Unknown command %s", command)
223 logger.exception("Error during run")