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