Debian Codegraph @

mallard/ducktype/extensions/csv.py

raw
1 # Copyright (c) 2019 Shaun McCance <[email protected]>
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 # THE SOFTWARE.
20
21 import mallard.ducktype
22
23 # FIXME:
24 # * Copy over attributes from ext node to table node
25 # * Except maybe we want some ext attrs:
26 # * Ext attr to change separator char? (csv:sep=tab)
27 # * Ext attr to control row and col headers?
28 # * Ext attr to parse lines inline? Or should that be default?
29 # * Set inner indent to allow newlines?
30
31 class CsvExtension(mallard.ducktype.parser.ParserExtension):
32 def __init__(self, parser, prefix, version):
33 if version == 'experimental':
34 self.version = version
35 else:
36 raise mallard.ducktype.parser.SyntaxError(
37 'Unsupported csv extension version: ' + version,
38 parser)
39 self.parser = parser
40 self.prefix = prefix
41 self.version = version
42 self.table = None
43
44 def take_block_node(self, node):
45 if node.name != 'csv:table':
46 return False
47 self.table = mallard.ducktype.parser.Block('table')
48 # Normally table elements are "greedy", meaning they have special
49 # rules that allow them to consume more stuff at the same indent
50 # level. These tables, however, are different. Turn off greedy to
51 # let the parser do its job.
52 self.table.is_greedy = False
53 self.parser.current.add_child(self.table)
54 self.parser.current = self.table
55 return True
56
57 def parse_line_block(self, line):
58 if self.table is None:
59 return False
60 else:
61 if self.table is not self.parser.current:
62 self.table = None
63 return False
64 tr = mallard.ducktype.parser.Block('tr')
65 self.parser.current.add_child(tr)
66 cells = line.split(',')
67 for cell in cells:
68 td = mallard.ducktype.parser.Block('td')
69 tr.add_child(td)
70 tdp = mallard.ducktype.parser.Block('p')
71 td.add_child(tdp)
72 tdp.add_text(cell)
73 return True