]> ToastFreeware Gitweb - philipp/winterrodeln/wrpylib.git/blob - bots/json_validate.py
4dbccfdb1472d9ea11f8aa4313226e69492e8c4b
[philipp/winterrodeln/wrpylib.git] / bots / 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         content_json = json.loads(self.current_page.text)
46         try:
47             validate(instance=content_json, schema=self.sledrun_schema)
48
49             content_json_ordered = order_json_keys(content_json, self.sledrun_schema)
50             assert content_json_ordered == content_json
51             text = json.dumps(content_json_ordered, ensure_ascii=False, indent=4)
52
53         except jsonschema.exceptions.ValidationError as e:
54             text = str(e)
55
56         summary = 'JSON Daten aktualisiert.'
57         self.put_current(text, summary=summary)
58
59
60 def main(*args: str) -> None:
61     local_args = pywikibot.handle_args(args)
62     gen_factory = pagegenerators.GeneratorFactory()
63     gen_factory.handle_args(local_args)
64     gen = gen_factory.getCombinedGenerator(preload=True)
65     if gen:
66         bot = SledrunFromJsonBot(generator=gen)
67         bot.run()
68     else:
69         pywikibot.bot.suggest_help(missing_generator=True)
70
71
72 if __name__ == '__main__':
73     main()