Debian Codegraph @

tools/xpathgrep.py

raw
1 #!/usr/bin/env python
2
3 import sys
4 import os.path
5
6 def error(message, *args):
7 if args:
8 message = message % args
9 sys.stderr.write('ERROR: %s\n' % message)
10
11 try:
12 import lxml.etree as et
13 except ImportError:
14 error(sys.exc_info()[1])
15 sys.exit(5)
16
17 try:
18 basestring
19 except NameError:
20 basestring = (str, bytes)
21
22 try:
23 unicode
24 except NameError:
25 unicode = str
26
27 SHORT_DESCRIPTION = "An XPath file finder for XML files."
28
29 __doc__ = SHORT_DESCRIPTION + '''
30
31 Evaluates an XPath expression against a series of files and prints the
32 matching subtrees to stdout.
33
34 Examples::
35
36 $ cat test.xml
37 <root>
38 <a num="1234" notnum="1234abc"/>
39 <b text="abc"/>
40 <c text="aBc"/>
41 <d xmlns="http://www.example.org/ns/example" num="2"/>
42 <d xmlns="http://www.example.org/ns/example" num="4"/>
43 </root>
44
45 # find all leaf elements:
46 $ SCRIPT '//*[not(*)]' test.xml
47 <a num="1234" notnum="1234abc"/>
48 <b text="abc"/>
49 <c text="aBc"/>
50
51 # find all elements with attribute values containing "abc" ignoring case:
52 $ SCRIPT '//*[@*[contains(py:lower(.), "abc")]]' test.xml
53 <a num="1234" notnum="1234abc"/>
54 <b text="abc"/>
55 <c text="aBc"/>
56
57 # find all numeric attribute values:
58 $ SCRIPT '//@*[re:match(., "^[0-9]+$")]' test.xml
59 1234
60
61 * find all elements with numeric attribute values:
62 $ SCRIPT '//*[@*[re:match(., "^[0-9]+$")]]' test.xml
63 <a num="1234" notnum="1234abc"/>
64
65 * find all elements with numeric attribute values in more than one file:
66 $ SCRIPT '//*[@*[re:match(., "^[0-9]+$")]]' test.xml test.xml test.xml
67 >> test.xml
68 <a num="1234" notnum="1234abc"/>
69 >> test.xml
70 <a num="1234" notnum="1234abc"/>
71 >> test.xml
72 <a num="1234" notnum="1234abc"/>
73
74 * find XML files that have non-empty root nodes:
75 $ SCRIPT -q '*' test.xml test.xml test.xml
76 >> test.xml
77 >> test.xml
78 >> test.xml
79
80 * find out if an XML file has at most depth three:
81 $ SCRIPT 'not(/*/*/*)' test.xml
82 True
83
84 * find all elements that belong to a specific namespace and have @num=2
85 $ SCRIPT --ns e=http://www.example.org/ns/example '//e:*[@num="2"]' test.xml
86 <d xmlns="http://www.example.org/ns/example" num="2"/>
87
88 By default, all Python builtins and string methods are available as
89 XPath functions through the ``py`` prefix. There is also a string
90 comparison function ``py:within(x, a, b)`` that tests the string x for
91 being lexicographically within the interval ``a <= x <= b``.
92 '''.replace('SCRIPT', os.path.basename(sys.argv[0]))
93
94 REGEXP_NS = "http://exslt.org/regular-expressions"
95 PYTHON_BUILTINS_NS = "PYTHON-BUILTINS"
96
97 def make_parser(remove_blank_text=True, **kwargs):
98 return et.XMLParser(remove_blank_text=remove_blank_text, **kwargs)
99
100 def print_result(result, pretty_print, encoding=None, _is_py3=sys.version_info[0] >= 3):
101 stdout = sys.stdout
102 if not stdout.isatty() and not encoding:
103 encoding = 'utf8'
104 if et.iselement(result):
105 result = et.tostring(result, xml_declaration=False, with_tail=False,
106 pretty_print=pretty_print, encoding=encoding)
107 if not pretty_print:
108 # pretty printing appends newline, otherwise we do it
109 if isinstance(result, unicode):
110 result += '\n'
111 else:
112 result += '\n'.encode('ascii')
113 elif isinstance(result, basestring):
114 result += '\n'
115 else:
116 result = '%r\n' % result # '%r' for better number formatting
117
118 if encoding and encoding != 'unicode' and isinstance(result, unicode):
119 result = result.encode(encoding)
120
121 if _is_py3 and not isinstance(result, unicode):
122 stdout.buffer.write(result)
123 else:
124 stdout.write(result)
125
126 def print_results(results, pretty_print):
127 if isinstance(results, list):
128 for result in results:
129 print_result(result, pretty_print)
130 else:
131 print_result(results, pretty_print)
132
133 def iter_input(input, filename, parser, line_by_line):
134 if isinstance(input, basestring):
135 with open(input, 'rb') as f:
136 for tree in iter_input(f, filename, parser, line_by_line):
137 yield tree
138 else:
139 try:
140 if line_by_line:
141 for line in input:
142 if line:
143 yield et.ElementTree(et.fromstring(line, parser))
144 else:
145 yield et.parse(input, parser)
146 except IOError:
147 e = sys.exc_info()[1]
148 error("parsing %r failed: %s: %s",
149 filename, e.__class__.__name__, e)
150
151 def find_in_file(f, xpath, print_name=True, xinclude=False, pretty_print=True, line_by_line=False,
152 encoding=None, verbose=True):
153 try:
154 filename = f.name
155 except AttributeError:
156 filename = f
157
158 xml_parser = et.XMLParser(encoding=encoding)
159
160 try:
161 if not callable(xpath):
162 xpath = et.XPath(xpath)
163
164 found = False
165 for tree in iter_input(f, filename, xml_parser, line_by_line):
166 try:
167 if xinclude:
168 tree.xinclude()
169 except IOError:
170 e = sys.exc_info()[1]
171 error("XInclude for %r failed: %s: %s",
172 filename, e.__class__.__name__, e)
173
174 results = xpath(tree)
175 if results is not None and results != []:
176 found = True
177 if verbose:
178 print_results(results, pretty_print)
179
180 if not found:
181 return False
182 if not verbose and print_name:
183 print(filename)
184 return True
185 except Exception:
186 e = sys.exc_info()[1]
187 error("%r: %s: %s",
188 filename, e.__class__.__name__, e)
189 return False
190
191 def register_builtins():
192 ns = et.FunctionNamespace(PYTHON_BUILTINS_NS)
193 tostring = et.tostring
194
195 def make_string(s):
196 if isinstance(s, list):
197 if not s:
198 return ''
199 s = s[0]
200 if not isinstance(s, unicode):
201 if et.iselement(s):
202 s = tostring(s, method="text", encoding='unicode')
203 else:
204 s = unicode(s)
205 return s
206
207 def wrap_builtin(b):
208 def wrapped_builtin(_, *args):
209 return b(*args)
210 return wrapped_builtin
211
212 for (name, builtin) in vars(__builtins__).items():
213 if callable(builtin):
214 if not name.startswith('_') and name == name.lower():
215 ns[name] = wrap_builtin(builtin)
216
217 def wrap_str_method(b):
218 def wrapped_method(_, *args):
219 args = tuple(map(make_string, args))
220 return b(*args)
221 return wrapped_method
222
223 for (name, method) in vars(unicode).items():
224 if callable(method):
225 if not name.startswith('_'):
226 ns[name] = wrap_str_method(method)
227
228 def within(_, s, a, b):
229 return make_string(a) <= make_string(s) <= make_string(b)
230 ns["within"] = within
231
232
233 def parse_options():
234 from optparse import OptionParser
235
236 usage = "usage: %prog [options] XPATH [FILE ...]"
237
238 parser = OptionParser(
239 usage = usage,
240 version = "%prog using lxml.etree " + et.__version__,
241 description = SHORT_DESCRIPTION)
242 parser.add_option("-H", "--long-help",
243 action="store_true", dest="long_help", default=False,
244 help="a longer help text including usage examples")
245 parser.add_option("-i", "--xinclude",
246 action="store_true", dest="xinclude", default=False,
247 help="run XInclude on the file before XPath")
248 parser.add_option("--no-python",
249 action="store_false", dest="python", default=True,
250 help="disable Python builtins and functions (prefix 'py')")
251 parser.add_option("--no-regexp",
252 action="store_false", dest="regexp", default=True,
253 help="disable regular expressions (prefix 're')")
254 parser.add_option("-q", "--quiet",
255 action="store_false", dest="verbose", default=True,
256 help="don't print status messages to stdout")
257 parser.add_option("-t", "--root-tag",
258 dest="root_tag", metavar="TAG",
259 help="surround output with <TAG>...</TAG> to produce a well-formed XML document")
260 parser.add_option("-p", "--plain",
261 action="store_false", dest="pretty_print", default=True,
262 help="do not pretty-print the output")
263 parser.add_option("-l", "--lines",
264 action="store_true", dest="line_by_line", default=False,
265 help="parse each line of input separately (e.g. grep output)")
266 parser.add_option("-e", "--encoding",
267 dest="encoding",
268 help="use a specific encoding for parsing (may be required with --lines)")
269 parser.add_option("-N", "--ns", metavar="PREFIX=NS",
270 action="append", dest="namespaces", default=[],
271 help="add a namespace declaration")
272
273 options, args = parser.parse_args()
274
275 if options.long_help:
276 parser.print_help()
277 print(__doc__[__doc__.find('\n\n')+1:])
278 sys.exit(0)
279
280 if len(args) < 1:
281 parser.error("first argument must be an XPath expression")
282
283 return options, args
284
285
286 def main(options, args):
287 namespaces = {}
288 if options.regexp:
289 namespaces["re"] = REGEXP_NS
290 if options.python:
291 register_builtins()
292 namespaces["py"] = PYTHON_BUILTINS_NS
293
294 for ns in options.namespaces:
295 prefix, NS = ns.split("=", 1)
296 namespaces[prefix.strip()] = NS.strip()
297
298 xpath = et.XPath(args[0], namespaces=namespaces)
299 files = args[1:] or [sys.stdin]
300
301 if options.root_tag and options.verbose:
302 print('<%s>' % options.root_tag)
303
304 found = False
305 print_name = len(files) > 1 and not options.root_tag
306 for input in files:
307 found |= find_in_file(
308 input, xpath,
309 print_name=print_name,
310 xinclude=options.xinclude,
311 pretty_print=options.pretty_print,
312 line_by_line=options.line_by_line,
313 encoding=options.encoding,
314 verbose=options.verbose,
315 )
316
317 if options.root_tag and options.verbose:
318 print('</%s>' % options.root_tag)
319
320 return found
321
322 if __name__ == "__main__":
323 try:
324 options, args = parse_options()
325 found = main(options, args)
326 if found:
327 sys.exit(0)
328 else:
329 sys.exit(1)
330 except et.XPathSyntaxError:
331 error(sys.exc_info()[1])
332 sys.exit(4)
333 except KeyboardInterrupt:
334 pass