]> git.phdru.name Git - extfs.d.git/blob - xml
618c65bb99a4b3a1d2be035ac85cf371d41006fd
[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+ 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.
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 there is a newline character in values).
22 Text nodes and comments are collected in a file named "text". The filesystem is
23 read-only.
24
25 The VFS was inspired by a FUSE xmlfs: https://github.com/halhen/xmlfs
26
27 """
28
29 __version__ = "0.2.0"
30 __author__ = "Oleg Broytman <phd@phdru.name>"
31 __copyright__ = "Copyright (C) 2013 PhiloSoft Design"
32 __license__ = "GPL"
33
34 import math
35 import sys
36 import xml.dom.minidom
37
38 try:
39    import locale
40    use_locale = True
41 except ImportError:
42    use_locale = False
43
44 if use_locale:
45    # Get the default charset.
46    try:
47       lcAll = locale.getdefaultlocale()
48    except locale.Error, err:
49       print >>sys.stderr, "WARNING:", err
50       lcAll = []
51
52    if len(lcAll) == 2:
53       default_encoding = lcAll[1]
54    else:
55       try:
56          default_encoding = locale.getpreferredencoding()
57       except locale.Error, err:
58          print >>sys.stderr, "WARNING:", err
59          default_encoding = sys.getdefaultencoding()
60 else:
61    default_encoding = sys.getdefaultencoding()
62
63 import logging
64 logger = logging.getLogger('xml-mcextfs')
65 log_err_handler = logging.StreamHandler(sys.stderr)
66 logger.addHandler(log_err_handler)
67 logger.setLevel(logging.INFO)
68
69 if len(sys.argv) < 3:
70     logger.critical("""\
71 XML Virtual FileSystem for Midnight Commander version %s
72 Author: %s
73 %s
74
75 This is not a program. Put the script in $HOME/.mc/extfs.d or
76 /usr/[local/][lib|share]/mc/extfs. For more information read the source!""",
77    __version__, __author__, __copyright__
78 )
79     sys.exit(1)
80
81
82 locale.setlocale(locale.LC_ALL, '')
83
84 def _attrs2text(attrs):
85     attrs = [attrs.item(i) for i in range (attrs.length)]
86     return '\n'.join(["%s=%s" %
87         (a.name.encode(default_encoding, "replace"),
88         a.value.encode(default_encoding, "replace"))
89         for a in attrs])
90
91 def _list(node, path=''):
92     childNodes = node.childNodes
93     n = 0
94     for element in childNodes:
95         if element.localName:
96             n += 1
97     if n:
98         width = int(math.log10(n))+1
99         template = "%%0%dd" % width
100     else:
101         template = "%d"
102     n = 0
103     for element in childNodes:
104         if element.localName:
105             n += 1
106             if path:
107                 subpath = '%s/%s %s' % (path, template % n, element.localName)
108             else:
109                 subpath = '%s %s' % (template % n, element.localName)
110             subpath_encoded = subpath.encode(default_encoding, "replace")
111             print "dr--r--r-- 1 user group 0 Jan 1 00:00 %s" % subpath_encoded
112             attrs = element.attributes
113             if attrs:
114                 attr_text = _attrs2text(attrs)
115                 print "-r--r--r-- 1 user group %d Jan 1 00:00 %s/attributes" % (
116                     len(attr_text), subpath_encoded)
117             _list(element, subpath)
118
119 def mcxml_list():
120     """List the entire VFS"""
121
122     dom = xml.dom.minidom.parse(sys.argv[2])
123     _list(dom)
124
125
126 def _get_child_node(node, i):
127     n = 0
128     for element in node.childNodes:
129         if element.localName:
130             n += 1
131             if n == i:
132                 return element
133     xml_error('There are less than %d nodes' % i)
134
135 def mcxml_copyout():
136     """Extract a file from the VFS"""
137
138     node = xml.dom.minidom.parse(sys.argv[2])
139     xml_filename = sys.argv[3]
140     real_filename = sys.argv[4]
141
142     for path_comp in xml_filename.split('/'):
143         if ' ' in path_comp:
144             i = int(path_comp.split(' ', 1)[0])
145             node = _get_child_node(node, i)
146         elif path_comp == 'attributes':
147             break
148         else:
149             xml_error('Unknown file')
150
151     if path_comp == 'attributes':
152         attrs = node.attributes
153         if attrs:
154             text = _attrs2text(attrs)
155         else:
156             xml_error('There are no attributes')
157
158     outfile = open(real_filename, 'w')
159     outfile.write(text)
160     outfile.close()
161
162
163 def mcxml_copyin():
164     """Put a file to the VFS"""
165     sys.exit("XML VFS doesn't support adding files (read-only filesystem)")
166
167 def mcxml_rm():
168     """Remove a file from the VFS"""
169     sys.exit("XML VFS doesn't support removing files/directories (read-only filesystem)")
170
171 mcxml_rmdir = mcxml_rm
172
173 def mcxml_mkdir():
174     """Create a directory in the VFS"""
175     sys.exit("XML VFS doesn't support creating directories (read-only filesystem)")
176
177
178 def xml_error(error_str):
179     logger.critical("Error walking XML file: %s", error_str)
180     sys.exit(1)
181
182 command = sys.argv[1]
183 procname = "mcxml_" + command
184
185 g = globals()
186 if not g.has_key(procname):
187     logger.critical("Unknown command %s", command)
188     sys.exit(1)
189
190 try:
191     g[procname]()
192 except SystemExit:
193     raise
194 except:
195     logger.exception("Error during run")