Debian Codegraph @

gavo/grammars/uniongrammar.py

raw
1 """
2 A grammar switching between subordinate grammars by file name patterns.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re
12
13 from gavo import base
14 from gavo.grammars import common
15 from gavo.rscdef import builtingrammars
16
17
18 class HandlesDeclaration(base.Structure):
19 """A declaration of what grammar to use within a UnionGrammar.
20
21 Each handler has a (full, python) regular expression defining what
22 file names the grammar is responsible in the filePattern attribute;
23 note that the pattern is matched against the full file name using search
24 so you can match path parts, but you must take care not to overmatch.
25 The other child is a normal DaCHS grammar.
26 """
27 name_ = "handles"
28
29 _pattern = base.UnicodeAttribute("pattern",
30 default=base.Undefined,
31 copyable=True)
32 _grammar = base.MultiStructAttribute("grammar",
33 default=None,
34 childFactory=builtingrammars.getGrammar,
35 childNames=list(builtingrammars.GRAMMAR_REGISTRY.keys()),
36 description="Grammar used to handle these kinds of files",
37 copyable=True)
38
39 def completeElement(self, ctx):
40 super().completeElement(ctx)
41 try:
42 self.matcher = re.compile(self.pattern)
43 except re.error as ex:
44 raise base.StructureError(
45 f"Bad handles pattern: '{self.pattern}' ({ex})")
46
47
48 class UnionGrammar(common.Grammar):
49 """A grammar using one of a sequence of grammars to parse its sources.
50
51 (since version 2.7.2)
52
53 Use this if you have differing input formats eventually processible
54 by the same row maker (of course, you can make the row maker flexible
55 enough to cope with different grammar outputs). To do that, use
56 two or more handles definitions, each giving a regular expression
57 against the full file name (but matched with re.search) and a grammar
58 to use for such files.
59
60 Handles definitions will be tried in sequence; you can hence have
61 special cases early and catch-alls later.
62
63 The basic idea is that you write something like::
64
65 <unionGrammar>
66 <handles pattern=".*\\.txt$">
67 <reGrammar...>
68 </handles>
69 <handles pattern=".*\\.csv$">
70 <csvGrammar...>
71 </handles>
72 </unionGrammar>
73 """
74 name_ = "unionGrammar"
75
76 _handles = base.StructListAttribute("handles",
77 childFactory=HandlesDeclaration,
78 copyable=True,
79 description="Recipe for what grammar to use for what sort of file.")
80
81 def parse(self, sourceToken:str, targetData=None):
82 for handler in self.handles:
83 if handler.matcher.search(sourceToken):
84 return handler.grammar.parse(sourceToken, targetData)
85 else:
86 raise base.DataError(f"No handler grammar for '{sourceToken}'")