-
Notifications
You must be signed in to change notification settings - Fork 1
/
converter.py
executable file
·81 lines (65 loc) · 2.52 KB
/
converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
import argparse
import textwrap
import xml.sax
import xml.sax.handler
class DeckException(Exception):
pass
class DeckHandler(xml.sax.handler.ContentHandler):
"""Enumeration of different card zones."""
ZONE_NONE = 0 # no zone
ZONE_MAIN = 1 # maindeck
ZONE_SIDE = 2 # sideboard
def __init__(self, output):
self.output = output
self._zone = self.ZONE_NONE
self._chars = ""
def error(self, msg):
self._file.close()
raise DeckException("error on line {}: {}".format(
self._locator.getLineNumber(), msg))
def _card(self, attrs):
if "number" not in attrs:
self.error("card tag without number attribute")
if "name" not in attrs:
self.error("card tag without name attribute")
return "{} {}\n".format(attrs["number"], attrs["name"])
def startDocument(self):
self._file = open(self.output, "w")
def endDocument(self):
self._file.close()
def startElement(self, name, attrs):
if name == "zone":
if "name" not in attrs:
self.error("zone tag without name attribute")
zone = attrs["name"]
if zone == "main":
self._zone = self.ZONE_MAIN
elif zone == "side":
self._zone = self.ZONE_SIDE
else:
self.error("unknown zone name \"{}\"".format(zone))
elif name == "card":
if self._zone == self.ZONE_MAIN:
self._file.write(self._card(attrs))
elif self._zone == self.ZONE_SIDE:
self._file.write("SB: " + self._card(attrs))
else:
self.error("card tag not in a valid zone")
def characters(self, content):
"""Handle all text contents as comments."""
for line in textwrap.wrap(content):
self._file.write("// {}\n".format(line))
def endElement(self, name):
if name == "zone":
self._zone = self.ZONE_NONE
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert Cockatrice " \
"decklists from XML format to plaintext format.")
parser.add_argument("deck", type=str, nargs="+", help="a XML format deck")
parser.add_argument("--suffix", type=str, default=".plain",
help="suffix to add to filename for plaintext decks")
args = parser.parse_args()
for filename in args.deck:
xml.sax.parse(filename, DeckHandler(filename + args.suffix))
# vim: set ts=4 sw=4 et :