Some housekeeping
[redakcja.git] / src / toolbar / management / commands / fixbuttons.py
1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4
5 from django.core.management.base import NoArgsCommand
6 from toolbar.models import Button, ButtonGroup
7 import json
8 import re
9
10
11 class Command(NoArgsCommand):
12
13     def handle_noargs(self, **options):
14         buttons = Button.objects.all()
15         print("Validating parameters... ")
16         for b in buttons:
17             params = b.params
18             try:
19                 v = json.loads(b.params)
20             except ValueError as e:
21                 print('Trying to fix button "%s" ...' % b.slug)
22                 if params[0] == u'(':
23                     params = params[1:]
24                 if params[-1] == u')':
25                     params = params[:-1]
26                 try:
27                     v = son.loads(re.sub(u'([\\w-]+)\\s*:', u'"\\1": ', params).encode('utf-8'))
28                 except ValueError as e:
29                     print("Unable to fix '%s' " % b.params)
30                     print("Try to fix this button manually and rerun the script.")
31                     return False
32
33             # resave
34             b.params = json.dumps(v)
35             b.save()
36
37         print("Merge duplicate buttons (if any)...")
38         hash = {}
39         for b in buttons:
40             if b.slug not in hash:
41                 hash[b.slug] = b
42                 continue
43
44             # duplicate button
45             print("Found duplicate of '%s'" % b.slug)
46             a = hash[b.slug]
47
48             remove_duplicate = True
49             if a.params != b.params:
50                 print("Conflicting params for duplicate of '%s'." % b.slug)
51                 print("Groups will be joined, but won't remove duplicates.")
52                 remove_duplicate = False
53
54             for g in b.group.all():
55                 a.group.add(g)
56
57             b.group.clear()
58
59             a.save()
60             if remove_duplicate:
61                 b.delete()
62
63         print("Searching for empty groups and orphaned buttons:")
64         for g in ButtonGroup.objects.all():
65             if len(g.button_set.all()) == 0:
66                 print("Empty group: '%s'" % g.slug)
67
68         for b in Button.objects.all():
69             if len(b.group.all()) == 0:
70                 print("orphan: '%s'" % b.slug)