document stages on import,
[redakcja.git] / apps / wiki / migrations / 0003_auto__add_book__add_chunk__add_unique_chunk_book_number__add_unique_ch.py
1 # encoding: utf-8
2 import datetime
3 import os.path
4 import cPickle
5 import re
6 import urllib
7
8 from django.conf import settings
9 from django.db import models
10 from mercurial import mdiff, hg, ui
11 from south.db import db
12 from south.v2 import SchemaMigration
13
14 from slughifi import slughifi
15
16 META_REGEX = re.compile(r'\s*<!--\s(.*?)-->', re.DOTALL | re.MULTILINE)
17 STAGE_TAGS_RE = re.compile(r'^#stage-finished: (.*)$', re.MULTILINE)
18
19
20 def urlunquote(url):
21     """Unqotes URL
22
23     # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
24     # u'Za\u017c\xf3\u0142\u0107_g\u0119\u015bl\u0105 ja\u017a\u0144'
25     """
26     return unicode(urllib.unquote(url), 'utf-8', 'ignore')
27
28
29 def split_name(name):
30     parts = name.split('__')
31     return parts
32
33
34 def file_to_title(fname):
35     """ Returns a title-like version of a filename. """
36     parts = (p.replace('_', ' ').title() for p in fname.split('__'))
37     return ' / '.join(parts)
38
39
40 def make_patch(src, dst):
41     if isinstance(src, unicode):
42         src = src.encode('utf-8')
43     if isinstance(dst, unicode):
44         dst = dst.encode('utf-8')
45     return cPickle.dumps(mdiff.textdiff(src, dst))
46
47
48 def plain_text(text):
49     return re.sub(META_REGEX, '', text, 1)
50
51
52 def gallery(slug, text):
53     result = {}
54
55     m = re.match(META_REGEX, text)
56     if m:
57         for line in m.group(1).split('\n'):
58             try:
59                 k, v = line.split(':', 1)
60                 result[k.strip()] = v.strip()
61             except ValueError:
62                 continue
63
64     gallery = result.get('gallery', slughifi(slug))
65
66     if gallery.startswith('/'):
67         gallery = os.path.basename(gallery)
68
69     return gallery
70
71
72 def migrate_file_from_hg(orm, fname, entry):
73     fname = urlunquote(fname)
74     print fname
75     if fname.endswith('.xml'):
76         fname = fname[:-4]
77     title = file_to_title(fname)
78     fname = slughifi(fname)
79     # create all the needed objects
80     # what if it already exists?
81     book = orm.Book.objects.create(
82         title=title,
83         slug=fname)
84     chunk = orm.Chunk.objects.create(
85         book=book,
86         number=1,
87         slug='1',
88         comment='cz. 1')
89     head = orm['dvcs.Change'].objects.create(
90         tree=chunk,
91         revision=-1,
92         patch=make_patch('', ''),
93         created_at=datetime.datetime.fromtimestamp(entry.filectx(0).date()[0]),
94         description=''
95         )
96     chunk.head = head
97     try:
98         chunk.stage = orm['dvcs.Tag'].objects.order_by('ordering')[0]
99     except IndexError:
100         chunk.stage = None
101     old_data = ''
102
103     maxrev = entry.filerev()
104     gallery_link = None
105     
106     for rev in xrange(maxrev + 1):
107         fctx = entry.filectx(rev)
108         data = fctx.data()
109         gallery_link = gallery(fname, data)
110         data = plain_text(data)
111
112         # get tags from description
113         description = fctx.description().decode("utf-8", 'replace')
114         tags = STAGE_TAGS_RE.findall(description)
115         tags = [orm['dvcs.Tag'].objects.get(slug=slug.strip()) for slug in tags]
116
117         if tags:
118             max_ordering = max(tags, key=lambda x: x.ordering).ordering
119             try:
120                 chunk.stage = orm['dvcs.Tag'].objects.filter(ordering__gt=max_ordering).order_by('ordering')[0]
121             except IndexError:
122                 chunk.stage = None
123
124         description = STAGE_TAGS_RE.sub('', description)
125
126         head = orm['dvcs.Change'].objects.create(
127             tree=chunk,
128             revision=rev + 1,
129             patch=make_patch(old_data, data),
130             created_at=datetime.datetime.fromtimestamp(fctx.date()[0]),
131             description=description,
132             author_desc=fctx.user().decode("utf-8", 'replace'),
133             parent=chunk.head
134             )
135         head.tags = tags
136         chunk.head = head
137         old_data = data
138
139     chunk.save()
140     if gallery_link:
141         book.gallery = gallery_link
142         book.save()
143
144
145 def migrate_from_hg(orm):
146     try:
147         hg_path = settings.WIKI_REPOSITORY_PATH
148     except:
149         pass
150
151     print 'migrate from', hg_path
152     repo = hg.repository(ui.ui(), hg_path)
153     tip = repo['tip']
154     for fname in tip:
155         if fname.startswith('.'):
156             continue
157         migrate_file_from_hg(orm, fname, tip[fname])
158
159
160 class Migration(SchemaMigration):
161
162     depends_on = [
163         ('dvcs', '0001_initial'),
164     ]
165
166     def forwards(self, orm):
167         
168         # Adding model 'Book'
169         db.create_table('wiki_book', (
170             ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
171             ('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
172             ('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=128, db_index=True)),
173             ('gallery', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
174             ('parent', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='children', null=True, to=orm['wiki.Book'])),
175             ('parent_number', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
176             ('last_published', self.gf('django.db.models.fields.DateTimeField')(null=True)),
177             ('_list_html', self.gf('django.db.models.fields.TextField')(null=True)),
178         ))
179         db.send_create_signal('wiki', ['Book'])
180
181         # Adding model 'Chunk'
182         db.create_table('wiki_chunk', (
183             ('document_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['dvcs.Document'], unique=True, primary_key=True)),
184             ('book', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.Book'])),
185             ('number', self.gf('django.db.models.fields.IntegerField')()),
186             ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
187             ('comment', self.gf('django.db.models.fields.CharField')(max_length=255)),
188         ))
189         db.send_create_signal('wiki', ['Chunk'])
190
191         # Adding unique constraint on 'Chunk', fields ['book', 'number']
192         db.create_unique('wiki_chunk', ['book_id', 'number'])
193
194         # Adding unique constraint on 'Chunk', fields ['book', 'slug']
195         db.create_unique('wiki_chunk', ['book_id', 'slug'])
196
197         if not db.dry_run:
198             migrate_from_hg(orm)
199
200     def backwards(self, orm):
201         
202         # Removing unique constraint on 'Chunk', fields ['book', 'slug']
203         db.delete_unique('wiki_chunk', ['book_id', 'slug'])
204
205         # Removing unique constraint on 'Chunk', fields ['book', 'number']
206         db.delete_unique('wiki_chunk', ['book_id', 'number'])
207
208         # Deleting model 'Book'
209         db.delete_table('wiki_book')
210
211         # Deleting model 'Chunk'
212         db.delete_table('wiki_chunk')
213
214
215     models = {
216         'auth.group': {
217             'Meta': {'object_name': 'Group'},
218             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
219             'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
220             'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
221         },
222         'auth.permission': {
223             'Meta': {'ordering': "('content_type__app_label', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
224             'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
225             'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
226             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
227             'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
228         },
229         'auth.user': {
230             'Meta': {'object_name': 'User'},
231             'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
232             'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
233             'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
234             'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
235             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
236             'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
237             'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
238             'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
239             'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
240             'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
241             'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
242             'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
243             'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
244         },
245         'contenttypes.contenttype': {
246             'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
247             'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
248             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
249             'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
250             'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
251         },
252         'dvcs.change': {
253             'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'Change'},
254             'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
255             'author_desc': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
256             'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
257             'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
258             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
259             'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['dvcs.Change']"}),
260             'parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'children'", 'null': 'True', 'blank': 'True', 'to': "orm['dvcs.Change']"}),
261             'patch': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
262             'publishable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
263             'revision': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
264             'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['dvcs.Tag']", 'symmetrical': 'False'}),
265             'tree': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['dvcs.Document']"})
266         },
267         'dvcs.document': {
268             'Meta': {'object_name': 'Document'},
269             'creator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
270             'head': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['dvcs.Change']", 'null': 'True', 'blank': 'True'}),
271             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
272             'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['dvcs.Tag']", 'null': 'True'}),
273             'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True'})
274         },
275         'dvcs.tag': {
276             'Meta': {'ordering': "['ordering']", 'object_name': 'Tag'},
277             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
278             'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
279             'ordering': ('django.db.models.fields.IntegerField', [], {}),
280             'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'})
281         },
282         'wiki.book': {
283             'Meta': {'ordering': "['parent_number', 'title']", 'object_name': 'Book'},
284             '_list_html': ('django.db.models.fields.TextField', [], {'null': 'True'}),
285             'gallery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
286             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
287             'last_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
288             'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['wiki.Book']"}),
289             'parent_number': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
290             'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}),
291             'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
292         },
293         'wiki.chunk': {
294             'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk', '_ormbases': ['dvcs.Document']},
295             'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Book']"}),
296             'comment': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
297             'document_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['dvcs.Document']", 'unique': 'True', 'primary_key': 'True'}),
298             'number': ('django.db.models.fields.IntegerField', [], {}),
299             'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})
300         },
301         'wiki.theme': {
302             'Meta': {'ordering': "('name',)", 'object_name': 'Theme'},
303             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
304             'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
305         }
306     }
307
308     complete_apps = ['wiki']