]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - bots/json_edit.py
Better parsing for car description.
[philipp/winterrodeln/wrpylib.git] / bots / json_edit.py
1 #!/usr/bin/python
2 """
3 User script for pywikibot (https://gerrit.wikimedia.org/r/pywikibot/core.git), tested with version 6.6.1.
4 Put it in directory scripts/userscripts.
5
6 Edit JSON associated with sledruns.
7
8 The following generators and filters are supported:
9
10 &params;
11 """
12 import json
13
14 import pywikibot
15 from jsonschema import validate
16 from pywikibot import pagegenerators, Page
17 from pywikibot.bot import (
18     AutomaticTWSummaryBot,
19     ConfigParserBot,
20     ExistingPageBot,
21     NoRedirectPageBot,
22     SingleSiteBot,
23 )
24
25 from wrpylib.json_tools import order_json_keys
26 from wrpylib.wrmwmarkup import create_sledrun_wiki
27
28
29 docuReplacements = {'&params;': pagegenerators.parameterHelp}
30
31
32 class SledrunFromJsonBot(
33     SingleSiteBot,
34     ConfigParserBot,
35     ExistingPageBot,
36     NoRedirectPageBot,
37     AutomaticTWSummaryBot,
38 ):
39     def setup(self) -> None:
40         schema = Page(self.site, 'Winterrodeln:Datenschema/Rodelbahn/V1.json')
41         assert schema.content_model == 'json'
42         self.sledrun_schema = json.loads(schema.text)
43
44     def treat_page(self) -> None:
45         """Load the given page, do some changes, and save it."""
46         if self.current_page.content_model != 'json':
47             return
48         content_json = json.loads(self.current_page.text)
49
50         # *here*, content_json can be processed
51         processed_json = content_json
52
53         validate(instance=processed_json, schema=self.sledrun_schema)
54         processed_json_ordered = order_json_keys(processed_json, self.sledrun_schema)
55         assert processed_json_ordered == processed_json
56         text = json.dumps(processed_json_ordered, ensure_ascii=False, indent=4)
57
58         summary = 'JSON Daten aktualisiert.'
59         self.put_current(text, summary=summary)
60
61
62 def main(*args: str) -> None:
63     local_args = pywikibot.handle_args(args)
64     gen_factory = pagegenerators.GeneratorFactory()
65     gen_factory.handle_args(local_args)
66     gen = gen_factory.getCombinedGenerator(preload=True)
67     if gen:
68         bot = SledrunFromJsonBot(generator=gen)
69         bot.run()
70     else:
71         pywikibot.bot.suggest_help(missing_generator=True)
72
73
74 if __name__ == '__main__':
75     main()