-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththronescli.py
More file actions
executable file
·472 lines (408 loc) · 14.9 KB
/
Copy paththronescli.py
File metadata and controls
executable file
·472 lines (408 loc) · 14.9 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#!/usr/bin/env python
from __future__ import annotations
import contextlib
import json
import os
import os.path
import typing
import urllib.request
import click
from clicksearch import (
Choice,
Count,
DelimitedText,
FieldBase,
Flag,
JsonLineReader,
MarkupText,
MissingField,
ModelBase,
Text,
fieldfilter,
)
if typing.TYPE_CHECKING:
from typing import Any, Iterable, Mapping
import collections
__version__ = "3.5.0"
CARDS_URL = "https://thronesdb.com/api/public/cards/"
CARDS_ENV = "THRONESCLI_DATA"
class ThronesReader(JsonLineReader):
def __init__(self, options: dict):
if options["update"]:
self.update_cards()
click.echo("Card database updated. Thank you thronesdb.com!")
raise SystemExit(0)
@property
def filenames(self):
cards_file = self.get_cards_file()
if not os.path.exists(cards_file):
self.update_cards()
yield cards_file
@classmethod
def get_cards_file(cls):
"""Return the path of the card database file."""
if CARDS_ENV in os.environ:
return os.environ[CARDS_ENV]
with contextlib.suppress(OSError):
os.mkdir(click.get_app_dir("thronescli"))
return os.path.join(click.get_app_dir("thronescli"), "cards-v3.json")
@classmethod
def update_cards(cls):
"""Fetch a new card database and write it to file."""
try:
cards_file = cls.get_cards_file()
input_file = cards_file + ".input"
output_file = cards_file + ".output"
urllib.request.urlretrieve(CARDS_URL, input_file)
with open(input_file) as inp, open(output_file, "w") as out:
for item in json.load(inp):
# Detect X values
xvalues = [
("cost", {"Character", "Attachment", "Location", "Event"}),
("strength", {"Character"}),
("claim", {"Plot"}),
("reserve", {"Plot"}),
("initiative", {"Plot"}),
("income", {"Plot"}),
]
for fieldname, typenames in xvalues:
if (
item[fieldname] is None
and "X" in item["text"]
and item["type_name"] in typenames
):
item[fieldname] = "X"
# Write item one per line
out.write(json.dumps(item))
out.write("\n")
os.remove(input_file)
with contextlib.suppress(FileNotFoundError):
os.remove(cards_file)
os.rename(output_file, cards_file)
except Exception as exc:
msg = f"Failed to update card database: {exc}"
raise click.ClickException(msg) from exc
@classmethod
def make_params(cls) -> Iterable[click.Parameter]:
"""Yields all options offered by the reader."""
yield click.Option(["--update"], is_flag=True, help="Update card database")
class Keyword(MarkupText, DelimitedText):
KEYWORDS = {
"Ambush": True,
"Assault": False,
"Bestow": True,
"Insight": False,
"Intimidate": False,
"Limited": False,
"No attachments": True,
"Pillage": False,
"Renown": False,
"Shadow": True,
"Stealth": False,
"Terminal": False,
}
def parse_keywords(self, value: str, short: bool = False) -> Iterable[str]:
"""
Yield all keywords listed in `value`. If `short` is true,
any additional keyword parameters is excluded.
"""
for part in value.split("."):
part = part.strip()
for keyword, can_have_info in self.KEYWORDS.items():
if can_have_info:
if part.startswith(keyword):
yield keyword if short else part
break
elif part == keyword:
yield keyword
def fetch(self, item: Mapping, default: Any | type = MissingField) -> Any:
"""Return a list of all keywords defined by `item`."""
return sorted(
self.parse_keywords(super(Keyword, self).fetch(item, default=default))
)
def parts(self, value: Any) -> Iterable[str]:
"""Parts have already been split."""
return value
def format_value(self, value: Any) -> str | None:
"""Return a string representation of `value`."""
if value:
return (
". ".join(
super(Keyword, self).format_value(keyword) for keyword in value
)
+ "."
)
return "No keyword"
def count(self, item: Mapping, counts: collections.Counter):
"""
Increments the count of each part in the `DelimitedText`
individually.
"""
try:
for keyword in self.parse_keywords(super(Keyword, self).fetch(item), True):
counts[keyword] += 1
except MissingField:
pass
@classmethod
def strip_value(cls, value: Any) -> Any:
"""Return a version of `value` without HTML tags."""
return [MarkupText.strip_value(keyword) for keyword in value]
class ChallengeIcons(FieldBase):
name = "ICON"
icons = {
"military": click.style("M", fg="red"),
"intrigue": click.style("I", fg="green"),
"power": click.style("P", fg="blue"),
}
iconsortkeys = {
"military": 2,
"intrigue": 3,
"power": 4,
}
iconkeys = {icon: f"is_{icon}" for icon in icons}
def fetch(
self, item: Mapping, default: Any | type = MissingField
) -> dict[str, bool]:
"""Returns all icon values in `item` as a dict."""
if item["type_name"] != "Character":
raise MissingField("Not a character")
return {icon: bool(item.get(key)) for icon, key in self.iconkeys.items()}
def convert(
self, optarg: str, param: click.Parameter | None, ctx: click.Context | None
) -> list[str]:
"""
Converts the option argument `optarg` to a list of matching icons. If
no choice matches, then print an error message and exit.
"""
optarg = optarg.lower()
if all(c in "mip" for c in optarg):
optarg = [c for c in optarg]
else:
optarg = [optarg]
icons = []
for arg in optarg:
for icon in self.icons:
if icon.startswith(arg):
icons.append(icon)
break
else:
self.fail(
(
f"Valid choices are: {', '.join(self.icons)}. A combination of "
"the letters 'MIP' can be used to define multiple respective icons."
),
param=param,
ctx=ctx,
)
return icons
def sortkey(self, item: Mapping) -> Any:
"""
Returns a comparable-type version of this field's value in `item`,
used for sorting.
"""
return (
sum(
self.iconsortkeys[icon]
for icon, state in self.fetch(item).items()
if state
)
or 0
)
@fieldfilter("--icon")
def filter_icon(self, arg: list[str], value: dict, options: dict) -> bool:
"""Filter on having given icon."""
return all(value[icon] for icon in arg)
@fieldfilter("--icon-isnt")
def filter_icon_isnt(self, arg: list[str], value: dict, options: dict) -> bool:
"""Filter on not having given icon."""
return all(not value[icon] for icon in arg)
def format_value(self, value: dict) -> str:
"""Return a string representation of `value`."""
return (
" ".join(self.icons[icon] for icon, state in value.items() if state)
or "No Icons"
)
def count(self, item: Mapping, counts: collections.Counter):
"""Increments the `counts` of each individual icon."""
try:
for icon, value in self.fetch(item).items():
counts[icon.title()] += value
except MissingField:
pass
def get_metavar_help(self):
"""
Return a longer description of the option argument for this field used
in `--help`.
"""
return (
f"One of: {', '.join(self.icons)}. A combination of the letters "
"'MIP' can be used to define multiple respective icons."
)
class Loyal(Flag):
"""
Field class for card loyalty. Non-Loyal is by default not shown in brief
format.
Examples:
>>> ThronesModel.cli('--trait Recruit', reader=ThronesReader)
Arry: Unique. Loyal. The Night's Watch. Character. 4 Cost. 3 STR. M I.
Recruit from the Dungeons: The Night's Watch. Character. 3 Cost. 2 STR. No Icons.
Highborn Recruit: The Night's Watch. Character. 1 Cost. 1 STR. P.
<BLANKLINE>
Total count: 3
>>> ThronesModel.cli('--trait Recruit --show loyal', reader=ThronesReader)
Arry: Loyal.
Recruit from the Dungeons: Non-Loyal.
Highborn Recruit: Non-Loyal.
<BLANKLINE>
Total count: 3
"""
def fetch(self, item: Mapping, default: Any | type = MissingField) -> Any:
if item["faction_code"] == "neutral":
raise MissingField("Irrelevant for neutral")
return super().fetch(item, default)
def format_brief(self, value: Any, show: bool = False) -> str:
return super().format_brief(value, show=show) if value or show else ""
class Unique(Flag):
"""
Field class for card uniqueness. Non-Unique is by default not shown in
brief format.
Examples:
>>> ThronesModel.cli('--trait Recruit', reader=ThronesReader)
Arry: Unique. Loyal. The Night's Watch. Character. 4 Cost. 3 STR. M I.
Recruit from the Dungeons: The Night's Watch. Character. 3 Cost. 2 STR. No Icons.
Highborn Recruit: The Night's Watch. Character. 1 Cost. 1 STR. P.
<BLANKLINE>
Total count: 3
>>> ThronesModel.cli('--trait Recruit --show unique', reader=ThronesReader)
Arry: Unique.
Recruit from the Dungeons: Non-Unique.
Highborn Recruit: Non-Unique.
<BLANKLINE>
Total count: 3
"""
def fetch(self, item: Mapping, default: Any | type = MissingField) -> Any:
if item["type_name"] not in {"Character", "Location", "Attachment"}:
raise MissingField("Irrelevant for type")
return super().fetch(item, default)
def format_brief(self, value: Any, show: bool = False) -> str:
return super().format_brief(value, show=show) if value or show else ""
class Cost(Count):
def is_missing(self, value: Any) -> bool:
"""Don't report `None` as a missing value."""
return False
def fetch(self, item: Mapping, default: Any | type = MissingField) -> Any:
"""Report as missing based on card type."""
if item["type_name"] not in {"Character", "Location", "Event", "Attachment"}:
raise MissingField("Irrelevant for card type")
return super().fetch(item, default=default)
def sortkey(self, item: Mapping) -> Any:
"""
Returns a comparable-type version of this field's value in `item`, used
for sorting. For `Number` objects this is guaranteed to be an `int`
or `float`.
"""
try:
value = self.fetch(item)
except MissingField:
return -3
if value is None:
return -2
if value == "X":
return -1
return value
class KeywordValue(Cost):
def __init__(self, *args, keyword: str, **kwargs):
super().__init__(*args, **kwargs)
self.keyword = keyword
def fetch(self, item: Mapping, default: Any | type = MissingField) -> Any:
"""Fetch the keyword value."""
for part in item[self.keyname].split("."):
part = part.strip()
if part.startswith(self.keyword):
return self.validate(part.removeprefix(self.keyword).strip(" ()"))
raise MissingField("Missing keyword")
class ThronesModel(ModelBase):
__version__ = __version__
# Basic card properties
name = Text(optalias="-n", redirect_args=True)
traits = DelimitedText(
optname="trait",
delimiter=".",
verbosity=1,
unlabeled=True,
styles={"fg": "magenta"},
)
text = MarkupText(
optalias="-x", verbosity=1, unlabeled=True, styles={"fg": "white"}
)
keywords = Keyword(
keyname="text", optname="keyword", verbosity=None, autofilter=True
)
unique = Unique(keyname="is_unique")
loyal = Loyal(keyname="is_loyal")
faction = Choice(
{
"Baratheon": "House Baratheon",
"Greyjoy": "House Greyjoy",
"GJ": "House Greyjoy",
"Lannister": "House Lannister",
"Martell": "House Martell",
"Neutral": "Neutral",
"Stark": "House Stark",
"Targaryen": "House Targaryen",
"Night's Watch": "The Night's Watch",
"The Night's Watch": "The Night's Watch",
"NW": "The Night's Watch",
"Tyrell": "House Tyrell",
},
keyname="faction_name",
optalias="-f",
autofilter=True,
inclusive=True,
)
type_name = Choice(
["Agenda", "Attachment", "Character", "Event", "Location", "Plot", "Title"],
realname="Type",
optalias="-t",
inclusive=True,
)
cost = Cost(specials=["X"], autofilter=True, inclusive=True)
ambush = KeywordValue(
keyname="text",
keyword="Ambush",
realname="Ambush Cost",
specials=["X"],
autofilter=True,
verbosity=None,
)
bestow = KeywordValue(
keyname="text",
keyword="Bestow",
realname="Bestow Limit",
specials=["X"],
autofilter=True,
verbosity=None,
)
shadow = KeywordValue(
keyname="text",
keyword="Shadow",
realname="Shadow Cost",
specials=["X"],
autofilter=True,
verbosity=None,
)
# Characters
strength = Count(specials=["X"], realname="STR", autofilter=True, inclusive=True)
icons = ChallengeIcons(autofilter=True)
# Plots
claim = Count(specials=["X"], autofilter=True, inclusive=True)
income = Count(specials=["X"], autofilter=True, inclusive=True)
initiative = Count(specials=["X"], autofilter=True, inclusive=True)
reserve = Count(specials=["X"], autofilter=True, inclusive=True)
# Non-default fields
illustrator = Text(inclusive=True, verbosity=2)
pack_name = Text(realname="Set", inclusive=True, verbosity=2)
def main():
ThronesModel.cli(reader=ThronesReader)
if __name__ == "__main__":
main()