move-chunk script
[redakcja.git] / scripts / move-chunk.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
14 setup_environ(settings)
15
16 from catalogue.models import Book, Chunk
17 import re
18
19 from django.db import transaction
20
21 if len(sys.argv) != 4:
22     print "dump-book slug-part chunk-no to-position"
23     sys.exit(-1)
24
25 term = sys.argv[1]
26 chunk_idx = int(sys.argv[2])
27 new_position = int(sys.argv[3])
28
29 with transaction.commit_on_success():
30     books = Book.objects.filter(slug__contains=term)
31     if len(books) > 1:
32         for b in range(len(books)):
33             print "%d) %s" % (b+1, books[b].slug)
34         print "Which one? "
35         ch = int(raw_input())
36         book = books[ch-1]
37     else:
38         book = books[0]
39
40     chunks_total = len(book)
41     max_number = max(c.number for c in book)
42     moving_chunk = next(c for c in book if c.number == chunk_idx)
43
44     moving_chunk.number = max_number+2
45     moving_chunk.save()
46
47     adjust = 1
48     for i in range(chunks_total-1, -1, -1):
49         chunk = book[i]
50         chunk.number = i + 1 + adjust
51         chunk.save()
52         if i + 1 == new_position:
53             adjust = 0
54
55
56     moving_chunk.number = new_position
57     moving_chunk.save()
58
59     book = Book.objects.get(pk=book.pk)
60     for c in book:
61         print c
62     while True:
63         print "is this ok (y/n)? "
64         resp = raw_input()
65         if resp[0] == 'y':
66             break
67         elif resp[0] == 'n':
68             raise Exception("Aborting")
69     
70