master xml making script
[redakcja.git] / scripts / fix_something.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 import sys
7 sys.path.append('.')
8 sys.path.append('./apps')
9 sys.path.append('./lib')
10
11 from django.core.management import setup_environ
12 from redakcja import settings
13 from lxml import etree
14
15 setup_environ(settings)
16
17 from catalogue.models import Book, Chunk
18 import re
19
20 fixed = {}
21
22 tag_with_name = r"<([^>]+)name=\"([^>]+)>"
23
24 def fix(book, author, dry_run=True):
25     fc = book[0]
26     txt = fc.materialize()
27
28     newtxt, cnt = re.subn(tag_with_name, r'<\1nazwa="\2>', txt)
29     if cnt == 0:
30         print "%s ==> nothing changed" % book.slug
31         return
32     
33     if not dry_run:
34         print "%s ==> changing" % book.slug
35         fc.commit(newtxt, author=author, description=u"Automatyczna zmiana atrybutu name na nazwa")
36     else:
37         print "%s ==> i would change this" % book.slug
38
39 def fix_empty_opis(book, author, dry_run=True):
40     fc = book[0]
41     txt = fc.materialize()
42     try:
43         t = etree.fromstring(txt)
44         empty_opis = t.xpath('//opis[not(node())]')
45         empty_cwiczenie = t.xpath('//cwiczenie[not(node())]')
46         
47         if empty_opis:
48             print "%s: opis/ x %d" % (book.slug, len(empty_opis))
49
50         if empty_cwiczenie:
51             print "%s: cwiczenie/ x %d" % (book.slug, len(empty_cwiczenie))
52
53     except:
54         print "%s didn't parse" % b.slug
55         return
56
57     
58
59 import sys
60 import getopt
61 from django.contrib.auth.models import User
62 opts, oth_ = getopt.getopt(sys.argv[1:],
63     [],
64     [ "seriously"])
65 dry_run = not (("--seriously",'') in opts)
66 me = User.objects.get(username='marcinkoziej')
67 if dry_run:
68     print "This is a dry run, to really fix something, run with --seriously"
69 for b in Book.objects.all():
70     if len(b) == 0:
71         print "%s ==> does not contain chunks" % b.slug
72         continue
73     fix_empty_opis(b, me, dry_run)
74
75     
76