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
14 from slughifi import slughifi
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*')
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'
27 return unicode(urllib.unquote(url), 'utf-8', 'ignore')
31 parts = name.split('__')
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)
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))
50 return re.sub(META_REGEX, '', text, 1)
53 def gallery(slug, text):
56 m = re.match(META_REGEX, text)
58 for line in m.group(1).split('\n'):
60 k, v = line.split(':', 1)
61 result[k.strip()] = v.strip()
65 gallery = result.get('gallery', slughifi(slug))
67 if gallery.startswith('/'):
68 gallery = os.path.basename(gallery)
73 def migrate_file_from_hg(orm, fname, entry):
74 fname = urlunquote(fname)
76 if fname.endswith('.xml'):
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(
85 chunk = orm.Chunk.objects.create(
89 head = orm.ChunkChange.objects.create(
92 patch=make_patch('', ''),
93 created_at=datetime.datetime.fromtimestamp(entry.filectx(0).date()[0]),
98 chunk.stage = orm.ChunkTag.objects.order_by('ordering')[0]
103 maxrev = entry.filerev()
106 for rev in xrange(maxrev + 1):
107 fctx = entry.filectx(rev)
109 gallery_link = gallery(fname, data)
110 data = plain_text(data)
112 # get tags from description
113 description = fctx.description().decode("utf-8", 'replace')
114 tags = STAGE_TAGS_RE.findall(description)
115 tags = [orm.ChunkTag.objects.get(slug=slug.strip()) for slug in tags]
118 max_ordering = max(tags, key=lambda x: x.ordering).ordering
120 chunk.stage = orm.ChunkTag.objects.filter(ordering__gt=max_ordering).order_by('ordering')[0]
124 description = STAGE_TAGS_RE.sub('', description)
126 author = author_name = author_email = None
127 author_desc = fctx.user().decode("utf-8", 'replace')
128 m = AUTHOR_RE.match(author_desc)
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)
136 author_name = author_desc
138 head = orm.ChunkChange.objects.create(
141 patch=make_patch(old_data, data),
142 created_at=datetime.datetime.fromtimestamp(fctx.date()[0]),
143 description=description,
145 author_name=author_name,
146 author_email=author_email,
155 book.gallery = gallery_link
159 def migrate_from_hg(orm):
161 hg_path = settings.WIKI_REPOSITORY_PATH
165 print 'migrate from', hg_path
166 repo = hg.repository(ui.ui(), hg_path)
169 if fname.startswith('.'):
171 migrate_file_from_hg(orm, fname, tip[fname])
174 class Migration(SchemaMigration):
176 def forwards(self, orm):
178 # Adding model 'Book'
179 db.create_table('catalogue_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, db_index=True)),
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['catalogue.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, db_index=True)),
188 db.send_create_signal('catalogue', ['Book'])
190 # Adding model 'Chunk'
191 db.create_table('catalogue_chunk', (
192 ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
193 ('creator', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='created_documents', null=True, to=orm['auth.User'])),
194 ('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
195 ('book', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['catalogue.Book'])),
196 ('number', self.gf('django.db.models.fields.IntegerField')()),
197 ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
198 ('comment', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
199 ('stage', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['catalogue.ChunkTag'], null=True, blank=True)),
200 ('head', self.gf('django.db.models.fields.related.ForeignKey')(default=None, to=orm['catalogue.ChunkChange'], null=True, blank=True)),
202 db.send_create_signal('catalogue', ['Chunk'])
204 # Adding unique constraint on 'Chunk', fields ['book', 'number']
205 db.create_unique('catalogue_chunk', ['book_id', 'number'])
207 # Adding unique constraint on 'Chunk', fields ['book', 'slug']
208 db.create_unique('catalogue_chunk', ['book_id', 'slug'])
210 # Adding model 'ChunkTag'
211 db.create_table('catalogue_chunktag', (
212 ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
213 ('name', self.gf('django.db.models.fields.CharField')(max_length=64)),
214 ('slug', self.gf('django.db.models.fields.SlugField')(db_index=True, max_length=64, unique=True, null=True, blank=True)),
215 ('ordering', self.gf('django.db.models.fields.IntegerField')()),
217 db.send_create_signal('catalogue', ['ChunkTag'])
219 # Adding model 'ChunkChange'
220 db.create_table('catalogue_chunkchange', (
221 ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
222 ('author', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
223 ('author_name', self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True)),
224 ('author_email', self.gf('django.db.models.fields.CharField')(max_length=128, null=True, blank=True)),
225 ('patch', self.gf('django.db.models.fields.TextField')(blank=True)),
226 ('revision', self.gf('django.db.models.fields.IntegerField')(db_index=True)),
227 ('parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='children', null=True, blank=True, to=orm['catalogue.ChunkChange'])),
228 ('merge_parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='merge_children', null=True, blank=True, to=orm['catalogue.ChunkChange'])),
229 ('description', self.gf('django.db.models.fields.TextField')(default='', blank=True)),
230 ('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
231 ('publishable', self.gf('django.db.models.fields.BooleanField')(default=False)),
232 ('tree', self.gf('django.db.models.fields.related.ForeignKey')(related_name='change_set', to=orm['catalogue.Chunk'])),
234 db.send_create_signal('catalogue', ['ChunkChange'])
236 # Adding unique constraint on 'ChunkChange', fields ['tree', 'revision']
237 db.create_unique('catalogue_chunkchange', ['tree_id', 'revision'])
239 # Adding M2M table for field tags on 'ChunkChange'
240 db.create_table('catalogue_chunkchange_tags', (
241 ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
242 ('chunkchange', models.ForeignKey(orm['catalogue.chunkchange'], null=False)),
243 ('chunktag', models.ForeignKey(orm['catalogue.chunktag'], null=False))
245 db.create_unique('catalogue_chunkchange_tags', ['chunkchange_id', 'chunktag_id'])
248 from django.core.management import call_command
249 call_command("loaddata", "stages.json")
254 def backwards(self, orm):
256 # Removing unique constraint on 'ChunkChange', fields ['tree', 'revision']
257 db.delete_unique('catalogue_chunkchange', ['tree_id', 'revision'])
259 # Removing unique constraint on 'Chunk', fields ['book', 'slug']
260 db.delete_unique('catalogue_chunk', ['book_id', 'slug'])
262 # Removing unique constraint on 'Chunk', fields ['book', 'number']
263 db.delete_unique('catalogue_chunk', ['book_id', 'number'])
265 # Deleting model 'Book'
266 db.delete_table('catalogue_book')
268 # Deleting model 'Chunk'
269 db.delete_table('catalogue_chunk')
271 # Deleting model 'ChunkTag'
272 db.delete_table('catalogue_chunktag')
274 # Deleting model 'ChunkChange'
275 db.delete_table('catalogue_chunkchange')
277 # Removing M2M table for field tags on 'ChunkChange'
278 db.delete_table('catalogue_chunkchange_tags')
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'})
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'})
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'})
312 'Meta': {'ordering': "['parent_number', 'title']", 'object_name': 'Book'},
313 'gallery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
314 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
315 'last_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
316 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['catalogue.Book']"}),
317 'parent_number': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
318 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}),
319 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
322 'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk'},
323 'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Book']"}),
324 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
325 'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'created_documents'", 'null': 'True', 'to': "orm['auth.User']"}),
326 'head': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['catalogue.ChunkChange']", 'null': 'True', 'blank': 'True'}),
327 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
328 'number': ('django.db.models.fields.IntegerField', [], {}),
329 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
330 'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.ChunkTag']", 'null': 'True', 'blank': 'True'}),
331 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
333 'catalogue.chunkchange': {
334 'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'ChunkChange'},
335 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
336 'author_email': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
337 'author_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
338 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
339 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
340 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
341 'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['catalogue.ChunkChange']"}),
342 'parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'children'", 'null': 'True', 'blank': 'True', 'to': "orm['catalogue.ChunkChange']"}),
343 'patch': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
344 'publishable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
345 'revision': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
346 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'change_set'", 'symmetrical': 'False', 'to': "orm['catalogue.ChunkTag']"}),
347 'tree': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'change_set'", 'to': "orm['catalogue.Chunk']"})
349 'catalogue.chunktag': {
350 'Meta': {'ordering': "['ordering']", 'object_name': 'ChunkTag'},
351 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
352 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
353 'ordering': ('django.db.models.fields.IntegerField', [], {}),
354 'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'})
356 'contenttypes.contenttype': {
357 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
358 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
359 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
360 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
361 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
365 complete_apps = ['catalogue']