3 from zlib import compress
9 from django.db import models
10 from mercurial import hg, ui
11 from south.db import db
12 from south.v2 import DataMigration
14 from django.conf import settings
15 from slughifi import slughifi
17 META_REGEX = re.compile(r'\s*<!--\s(.*?)-->', re.DOTALL | re.MULTILINE)
18 STAGE_TAGS_RE = re.compile(r'^#stage-finished: (.*)$', re.MULTILINE)
19 AUTHOR_RE = re.compile(r'\s*(.*?)\s*<(.*)>\s*')
25 # >>> urlunquote('Za%C5%BC%C3%B3%C5%82%C4%87_g%C4%99%C5%9Bl%C4%85_ja%C5%BA%C5%84')
26 # u'Za\u017c\xf3\u0142\u0107_g\u0119\u015bl\u0105 ja\u017a\u0144'
28 return unicode(urllib.unquote(url), 'utf-8', 'ignore')
32 parts = name.split('__')
36 def file_to_title(fname):
37 """ Returns a title-like version of a filename. """
38 parts = (p.replace('_', ' ').title() for p in fname.split('__'))
39 return ' / '.join(parts)
43 return re.sub(META_REGEX, '', text, 1)
46 def gallery(slug, text):
49 m = re.match(META_REGEX, text)
51 for line in m.group(1).split('\n'):
53 k, v = line.split(':', 1)
54 result[k.strip()] = v.strip()
58 gallery = result.get('gallery', slughifi(slug))
60 if gallery.startswith('/'):
61 gallery = os.path.basename(gallery)
66 def migrate_file_from_hg(orm, fname, entry):
67 fname = urlunquote(fname)
69 if fname.endswith('.xml'):
71 title = file_to_title(fname)
72 fname = slughifi(fname)
74 # create all the needed objects
75 # what if it already exists?
76 book = orm.Book.objects.create(
79 chunk = orm.Chunk.objects.create(
84 chunk.stage = orm.ChunkTag.objects.order_by('ordering')[0]
88 maxrev = entry.filerev()
91 # this will fail if directory exists
92 os.makedirs(os.path.join(settings.DVCS_REPO_PATH, str(chunk.pk)))
94 for rev in xrange(maxrev + 1):
95 fctx = entry.filectx(rev)
97 gallery_link = gallery(fname, data)
98 data = plain_text(data)
100 # get tags from description
101 description = fctx.description().decode("utf-8", 'replace')
102 tags = STAGE_TAGS_RE.findall(description)
103 tags = [orm.ChunkTag.objects.get(slug=slug.strip()) for slug in tags]
106 max_ordering = max(tags, key=lambda x: x.ordering).ordering
108 chunk.stage = orm.ChunkTag.objects.filter(ordering__gt=max_ordering).order_by('ordering')[0]
112 description = STAGE_TAGS_RE.sub('', description)
114 author = author_name = author_email = None
115 author_desc = fctx.user().decode("utf-8", 'replace')
116 m = AUTHOR_RE.match(author_desc)
119 author = orm['auth.User'].objects.get(username=m.group(1), email=m.group(2))
120 except orm['auth.User'].DoesNotExist:
121 author_name = m.group(1)
122 author_email = m.group(2)
124 author_name = author_desc
126 head = orm.ChunkChange.objects.create(
129 created_at=datetime.datetime.fromtimestamp(fctx.date()[0]),
130 description=description,
132 author_name=author_name,
133 author_email=author_email,
137 path = "%d/%d" % (chunk.pk, head.pk)
138 abs_path = os.path.join(settings.DVCS_REPO_PATH, path)
139 f = open(abs_path, 'wb')
140 f.write(compress(data))
151 book.gallery = gallery_link
155 class Migration(DataMigration):
157 def forwards(self, orm):
159 hg_path = settings.WIKI_REPOSITORY_PATH
163 print 'migrate from', hg_path
164 repo = hg.repository(ui.ui(), hg_path)
167 if fname.startswith('.') or not fname.startswith('a'):
169 migrate_file_from_hg(orm, fname, tip[fname])
172 def backwards(self, orm):
173 "Write your backwards methods here."
179 'Meta': {'object_name': 'Group'},
180 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
181 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
182 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
185 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
186 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
187 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
188 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
189 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
192 'Meta': {'object_name': 'User'},
193 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
194 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
195 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
196 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
197 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
198 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
199 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
200 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
201 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
202 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
203 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
204 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
205 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
208 'Meta': {'ordering': "['parent_number', 'title']", 'object_name': 'Book'},
209 'gallery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
210 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
211 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['catalogue.Book']"}),
212 'parent_number': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
213 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}),
214 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
216 'catalogue.bookpublishrecord': {
217 'Meta': {'ordering': "['-timestamp']", 'object_name': 'BookPublishRecord'},
218 'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Book']"}),
219 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
220 'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
221 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
224 'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk'},
225 'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.Book']"}),
226 'comment': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
227 'creator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'created_documents'", 'null': 'True', 'to': "orm['auth.User']"}),
228 'head': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': "orm['catalogue.ChunkChange']", 'null': 'True', 'blank': 'True'}),
229 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
230 'number': ('django.db.models.fields.IntegerField', [], {}),
231 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'}),
232 'stage': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.ChunkTag']", 'null': 'True', 'blank': 'True'}),
233 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'})
235 'catalogue.chunkchange': {
236 'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'ChunkChange'},
237 'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
238 'author_email': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
239 'author_name': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
240 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
241 'data': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
242 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
243 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
244 'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['catalogue.ChunkChange']"}),
245 'parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'children'", 'null': 'True', 'blank': 'True', 'to': "orm['catalogue.ChunkChange']"}),
246 'publishable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
247 'revision': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
248 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'change_set'", 'symmetrical': 'False', 'to': "orm['catalogue.ChunkTag']"}),
249 'tree': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'change_set'", 'to': "orm['catalogue.Chunk']"})
251 'catalogue.chunkpublishrecord': {
252 'Meta': {'object_name': 'ChunkPublishRecord'},
253 'book_record': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.BookPublishRecord']"}),
254 'change': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['catalogue.ChunkChange']"}),
255 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
257 'catalogue.chunktag': {
258 'Meta': {'ordering': "['ordering']", 'object_name': 'ChunkTag'},
259 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
260 'name': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
261 'ordering': ('django.db.models.fields.IntegerField', [], {}),
262 'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '64', 'unique': 'True', 'null': 'True', 'blank': 'True'})
264 'contenttypes.contenttype': {
265 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
266 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
267 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
268 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
269 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
273 complete_apps = ['catalogue']