make dvcs models abstract,
[redakcja.git] / apps / wiki / migrations / 0003_add_dvcs.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 AUTHOR_RE = re.compile(r'\s*(.*?)\s*<(.*)>\s*')
19
20
21 def urlunquote(url):
22     """Unqotes URL
23
24     # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
25     # u'Za\u017c\xf3\u0142\u0107_g\u0119\u015bl\u0105 ja\u017a\u0144'
26     """
27     return unicode(urllib.unquote(url), 'utf-8', 'ignore')
28
29
30 def split_name(name):
31     parts = name.split('__')
32     return parts
33
34
35 def file_to_title(fname):
36     """ Returns a title-like version of a filename. """
37     parts = (p.replace('_', ' ').title() for p in fname.split('__'))
38     return ' / '.join(parts)
39
40
41 def make_patch(src, dst):
42     if isinstance(src, unicode):
43         src = src.encode('utf-8')
44     if isinstance(dst, unicode):
45         dst = dst.encode('utf-8')
46     return cPickle.dumps(mdiff.textdiff(src, dst))
47
48
49 def plain_text(text):
50     return re.sub(META_REGEX, '', text, 1)
51
52
53 def gallery(slug, text):
54     result = {}
55
56     m = re.match(META_REGEX, text)
57     if m:
58         for line in m.group(1).split('\n'):
59             try:
60                 k, v = line.split(':', 1)
61                 result[k.strip()] = v.strip()
62             except ValueError:
63                 continue
64
65     gallery = result.get('gallery', slughifi(slug))
66
67     if gallery.startswith('/'):
68         gallery = os.path.basename(gallery)
69
70     return gallery
71
72
73 def migrate_file_from_hg(orm, fname, entry):
74     fname = urlunquote(fname)
75     print fname
76     if fname.endswith('.xml'):
77         fname = fname[:-4]
78     title = file_to_title(fname)
79     fname = slughifi(fname)
80     # create all the needed objects
81     # what if it already exists?
82     book = orm.Book.objects.create(
83         title=title,
84         slug=fname)
85     chunk = orm.Chunk.objects.create(
86         book=book,
87         number=1,
88         slug='1')
89     head = orm['wiki.ChunkChange'].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['wiki.ChunkTag'].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['wiki.ChunkTag'].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['wiki.ChunkTag'].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         author = author_name = author_email = None
127         author_desc = fctx.user().decode("utf-8", 'replace')
128         m = AUTHOR_RE.match(author_desc)
129         if m:
130             try:
131                 author = orm['auth.User'].objects.get(username=m.group(1), email=m.group(2))
132             except orm['auth.User'].DoesNotExist:
133                 author_name = m.group(1)
134                 author_email = m.group(2)
135         else:
136             author_name = author_desc
137
138         head = orm['wiki.ChunkChange'].objects.create(
139             tree=chunk,
140             revision=rev + 1,
141             patch=make_patch(old_data, data),
142             created_at=datetime.datetime.fromtimestamp(fctx.date()[0]),
143             description=description,
144             author=author,
145             author_name=author_name,
146             author_email=author_email,
147             parent=chunk.head
148             )
149         head.tags = tags
150         chunk.head = head
151         old_data = data
152
153     chunk.save()
154     if gallery_link:
155         book.gallery = gallery_link
156         book.save()
157
158
159 def migrate_from_hg(orm):
160     try:
161         hg_path = settings.WIKI_REPOSITORY_PATH
162     except:
163         pass
164
165     print 'migrate from', hg_path
166     repo = hg.repository(ui.ui(), hg_path)
167     tip = repo['tip']
168     for fname in tip:
169         if fname.startswith('.'):
170             continue
171         migrate_file_from_hg(orm, fname, tip[fname])
172
173
174 class Migration(SchemaMigration):
175
176     def forwards(self, orm):
177         
178         # Adding model 'Book'
179         db.create_table('wiki_book', (
180             ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
181             ('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
182             ('slug', self.gf('django.db.models.fields.SlugField')(unique=True, max_length=128, db_index=True)),
183             ('gallery', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
184             ('parent', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='children', null=True, to=orm['wiki.Book'])),
185             ('parent_number', self.gf('django.db.models.fields.IntegerField')(db_index=True, null=True, blank=True)),
186             ('last_published', self.gf('django.db.models.fields.DateTimeField')(null=True)),
187             ('_list_html', self.gf('django.db.models.fields.TextField')(null=True)),
188         ))
189         db.send_create_signal('wiki', ['Book'])
190
191         # Adding model 'Chunk'
192         db.create_table('wiki_chunk', (
193             ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
194             ('creator', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='created_documents', null=True, to=orm['auth.User'])),
195             ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
196             ('book', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.Book'])),
197             ('number', self.gf('django.db.models.fields.IntegerField')()),
198             ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
199             ('comment', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
200             ('stage', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.ChunkTag'], null=True, blank=True)),
201             ('head', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['wiki.ChunkChange'], null=True, blank=True)),
202         ))
203         db.send_create_signal('wiki', ['Chunk'])
204
205         # Adding unique constraint on 'Chunk', fields ['book', 'number']
206         db.create_unique('wiki_chunk', ['book_id', 'number'])
207
208         # Adding unique constraint on 'Chunk', fields ['book', 'slug']
209         db.create_unique('wiki_chunk', ['book_id', 'slug'])
210
211         # Adding model 'ChunkTag'
212         db.create_table('wiki_chunktag', (
213             ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
214             ('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
215             ('slug', self.gf('django.db.models.fields.SlugField')(db_index=True, max_length=64, unique=True, null=True, blank=True)),
216             ('ordering', self.gf('django.db.models.fields.IntegerField')()),
217         ))
218         db.send_create_signal('wiki', ['ChunkTag'])
219
220         # Adding model 'ChunkChange'
221         db.create_table('wiki_chunkchange', (
222             ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
223             ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
224             ('author_name', self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True)),
225             ('author_email', self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True)),
226             ('patch', self.gf('django.db.models.fields.TextField')(blank=True)),
227             ('revision', self.gf('django.db.models.fields.IntegerField')(db_index=True)),
228             ('parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='children', null=True, blank=True, to=orm['wiki.ChunkChange'])),
229             ('merge_parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='merge_children', null=True, blank=True, to=orm['wiki.ChunkChange'])),
230             ('description', self.gf('django.db.models.fields.TextField')(default='', blank=True)),
231             ('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
232             ('publishable', self.gf('django.db.models.fields.BooleanField')(default=False)),
233             ('tree', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.Chunk'])),
234         ))
235         db.send_create_signal('wiki', ['ChunkChange'])
236
237         # Adding unique constraint on 'ChunkChange', fields ['tree', 'revision']
238         db.create_unique('wiki_chunkchange', ['tree_id', 'revision'])
239
240         # Adding M2M table for field tags on 'ChunkChange'
241         db.create_table('wiki_chunkchange_tags', (
242             ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
243             ('chunkchange', models.ForeignKey(orm['wiki.chunkchange'], null=False)),
244             ('chunktag', models.ForeignKey(orm['wiki.chunktag'], null=False))
245         ))
246         db.create_unique('wiki_chunkchange_tags', ['chunkchange_id', 'chunktag_id'])
247
248         if not db.dry_run:
249             from django.core.management import call_command
250             call_command("loaddata", "stages.json")
251
252             migrate_from_hg(orm)
253
254     def backwards(self, orm):
255         
256         # Removing unique constraint on 'ChunkChange', fields ['tree', 'revision']
257         db.delete_unique('wiki_chunkchange', ['tree_id', 'revision'])
258
259         # Removing unique constraint on 'Chunk', fields ['book', 'slug']
260         db.delete_unique('wiki_chunk', ['book_id', 'slug'])
261
262         # Removing unique constraint on 'Chunk', fields ['book', 'number']
263         db.delete_unique('wiki_chunk', ['book_id', 'number'])
264
265         # Deleting model 'Book'
266         db.delete_table('wiki_book')
267
268         # Deleting model 'Chunk'
269         db.delete_table('wiki_chunk')
270
271         # Deleting model 'ChunkTag'
272         db.delete_table('wiki_chunktag')
273
274         # Deleting model 'ChunkChange'
275         db.delete_table('wiki_chunkchange')
276
277         # Removing M2M table for field tags on 'ChunkChange'
278         db.delete_table('wiki_chunkchange_tags')
279
280
281     models = {
282         'auth.group': {
283             'Meta': {'object_name': 'Group'},
284             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
285             'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
286             'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
287         },
288         'auth.permission': {
289             'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
290             'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
291             'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
292             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
293             'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
294         },
295         'auth.user': {
296             'Meta': {'object_name': 'User'},
297             'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
298             'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
299             'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
300             'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
301             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
302             'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
303             'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
304             'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
305             'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
306             'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
307             'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
308             'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
309             'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
310         },
311         'contenttypes.contenttype': {
312             'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
313             'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
314             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
315             'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
316             'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
317         },
318         'wiki.book': {
319             'Meta': {'ordering': "['parent_number', 'title']", 'object_name': 'Book'},
320             '_list_html': ('django.db.models.fields.TextField', [], {'null': 'True'}),
321             'gallery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
322             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
323             'last_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
324             'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['wiki.Book']"}),
325             'parent_number': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
326             'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}),
327             'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
328         },
329         'wiki.chunk': {
330             'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk'},
331             'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Book']"}),
332             'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
333             'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'created_documents'", 'null': 'True', 'to': "orm['auth.User']"}),
334             'head': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['wiki.ChunkChange']", 'null': 'True', 'blank': 'True'}),
335             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
336             'number': ('django.db.models.fields.IntegerField', [], {}),
337             'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
338             'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.ChunkTag']", 'null': 'True', 'blank': 'True'}),
339             'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
340         },
341         'wiki.chunkchange': {
342             'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'ChunkChange'},
343             'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
344             'author_email': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
345             'author_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
346             'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
347             'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
348             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
349             'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['wiki.ChunkChange']"}),
350             'parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'children'", 'null': 'True', 'blank': 'True', 'to': "orm['wiki.ChunkChange']"}),
351             'patch': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
352             'publishable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
353             'revision': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
354             'tags': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['wiki.ChunkTag']", 'symmetrical': 'False'}),
355             'tree': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Chunk']"})
356         },
357         'wiki.chunktag': {
358             'Meta': {'ordering': "['ordering']", 'object_name': 'ChunkTag'},
359             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
360             'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
361             'ordering': ('django.db.models.fields.IntegerField', [], {}),
362             'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'})
363         },
364         'wiki.theme': {
365             'Meta': {'ordering': "('name',)", 'object_name': 'Theme'},
366             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
367             'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
368         }
369     }
370
371     complete_apps = ['wiki']