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