]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - bots/sledrun_json_validate.py
Select sledrun main pages to validate JSON.
[philipp/winterrodeln/wrpylib.git] / bots / sledrun_json_validate.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 import jsonschema
14 from jsonschema import validate
15
16 import pywikibot
17 from pywikibot import pagegenerators, Page
18 from pywikibot.bot import (
19     AutomaticTWSummaryBot,
20     ConfigParserBot,
21     ExistingPageBot,
22     NoRedirectPageBot,
23     SingleSiteBot,
24 )
25
26 from wrpylib.json_tools import order_json_keys
27
28 docuReplacements = {'&params;': pagegenerators.parameterHelp}
29
30
31 class SledrunFromJsonBot(
32     SingleSiteBot,
33     ConfigParserBot,
34     ExistingPageBot,
35     NoRedirectPageBot,
36     AutomaticTWSummaryBot,
37 ):
38     def setup(self) -> None:
39         schema = Page(self.site, 'Winterrodeln:Datenschema/Rodelbahn/V1.json')
40         assert schema.content_model == 'json'
41         self.sledrun_schema = json.loads(schema.text)
42
43     def treat_page(self) -> None:
44         """Load the given page, do some changes, and save it."""
45         sledrun_json_page = Page(self.site, self.current_page.title() + '/Rodelbahn.json')
46         if not sledrun_json_page.exists():
47             return
48         content_json = json.loads(sledrun_json_page.text)
49         try:
50             validate(instance=content_json, schema=self.sledrun_schema)
51
52             content_json_ordered = order_json_keys(content_json, self.sledrun_schema)
53             assert content_json_ordered == content_json
54             text = json.dumps(content_json_ordered, ensure_ascii=False, indent=4)
55
56         except jsonschema.exceptions.ValidationError as e:
57             text = str(e)
58
59         summary = 'JSON Daten aktualisiert.'
60         self.userPut(sledrun_json_page, sledrun_json_page.text, text, summary=summary, contentmodel='json')
61
62
63 def main(*args: str) -> None:
64     local_args = pywikibot.handle_args(args)
65     gen_factory = pagegenerators.GeneratorFactory()
66     gen_factory.handle_args(local_args)
67     gen = gen_factory.getCombinedGenerator(preload=True)
68     if gen:
69         bot = SledrunFromJsonBot(generator=gen)
70         bot.run()
71     else:
72         pywikibot.bot.suggest_help(missing_generator=True)
73
74
75 if __name__ == '__main__':
76     main()