Fix Flickr license detection.
[redakcja.git] / apps / dvcs / models.py
1 from datetime import datetime
2 import os.path
3
4 from django.contrib.auth.models import User
5 from django.core.files.base import ContentFile
6 from django.core.files.storage import FileSystemStorage
7 from django.db import models, transaction
8 from django.db.models.base import ModelBase
9 from django.utils.translation import ugettext_lazy as _
10 from mercurial import simplemerge
11
12 from django.conf import settings
13 from dvcs.signals import post_commit, post_publishable
14 from dvcs.storage import GzipFileSystemStorage
15
16
17 class Tag(models.Model):
18     """A tag (e.g. document stage) which can be applied to a Change."""
19     name = models.CharField(_('name'), max_length=64)
20     slug = models.SlugField(_('slug'), unique=True, max_length=64, 
21             null=True, blank=True)
22     ordering = models.IntegerField(_('ordering'))
23
24     _object_cache = {}
25
26     class Meta:
27         abstract = True
28         ordering = ['ordering']
29         verbose_name = _("tag")
30         verbose_name_plural = _("tags")
31
32     def __unicode__(self):
33         return self.name
34
35     @classmethod
36     def get(cls, slug):
37         if slug in cls._object_cache:
38             return cls._object_cache[slug]
39         else:
40             obj = cls.objects.get(slug=slug)
41             cls._object_cache[slug] = obj
42             return obj
43
44     @staticmethod
45     def listener_changed(sender, instance, **kwargs):
46         sender._object_cache = {}
47
48     def get_next(self):
49         """
50             Returns the next tag - stage to work on.
51             Returns None for the last stage.
52         """
53         try:
54             return type(self).objects.filter(ordering__gt=self.ordering)[0]
55         except IndexError:
56             return None
57
58 models.signals.pre_save.connect(Tag.listener_changed, sender=Tag)
59
60
61 def data_upload_to(instance, filename):
62     return "%d/%d" % (instance.tree.pk, instance.pk)
63
64 class Change(models.Model):
65     """
66         Single document change related to previous change. The "parent"
67         argument points to the version against which this change has been 
68         recorded. Initial text will have a null parent.
69         
70         Data file contains a gzipped text of the document.
71     """
72     author = models.ForeignKey(User, null=True, blank=True, verbose_name=_('author'))
73     author_name = models.CharField(_('author name'), max_length=128,
74                         null=True, blank=True,
75                         help_text=_("Used if author is not set.")
76                         )
77     author_email = models.CharField(_('author email'), max_length=128,
78                         null=True, blank=True,
79                         help_text=_("Used if author is not set.")
80                         )
81     revision = models.IntegerField(_('revision'), db_index=True)
82
83     parent = models.ForeignKey('self',
84                         null=True, blank=True, default=None,
85                         verbose_name=_('parent'),
86                         related_name="children")
87
88     merge_parent = models.ForeignKey('self',
89                         null=True, blank=True, default=None,
90                         verbose_name=_('merge parent'),
91                         related_name="merge_children")
92
93     description = models.TextField(_('description'), blank=True, default='')
94     created_at = models.DateTimeField(editable=False, db_index=True, 
95                         default=datetime.now)
96     publishable = models.BooleanField(_('publishable'), default=False)
97
98     class Meta:
99         abstract = True
100         ordering = ('created_at',)
101         unique_together = ['tree', 'revision']
102         verbose_name = _("change")
103         verbose_name_plural = _("changes")
104
105     def __unicode__(self):
106         return u"Id: %r, Tree %r, Parent %r, Data: %s" % (self.id, self.tree_id, self.parent_id, self.data)
107
108     def author_str(self):
109         if self.author:
110             return "%s %s <%s>" % (
111                 self.author.first_name,
112                 self.author.last_name, 
113                 self.author.email)
114         else:
115             return "%s <%s>" % (
116                 self.author_name,
117                 self.author_email
118                 )
119
120
121     def save(self, *args, **kwargs):
122         """
123             take the next available revision number if none yet
124         """
125         if self.revision is None:
126             tree_rev = self.tree.revision()
127             if tree_rev is None:
128                 self.revision = 1
129             else:
130                 self.revision = tree_rev + 1
131         return super(Change, self).save(*args, **kwargs)
132
133     def materialize(self):
134         f = self.data.storage.open(self.data)
135         text = f.read()
136         f.close()
137         return unicode(text, 'utf-8')
138
139     def merge_with(self, other, author=None, 
140             author_name=None, author_email=None, 
141             description=u"Automatic merge."):
142         """Performs an automatic merge after straying commits."""
143         assert self.tree_id == other.tree_id  # same tree
144         if other.parent_id == self.pk:
145             # immediate child - fast forward
146             return other
147
148         local = self.materialize().encode('utf-8')
149         base = other.parent.materialize().encode('utf-8')
150         remote = other.materialize().encode('utf-8')
151
152         merge = simplemerge.Merge3Text(base, local, remote)
153         result = ''.join(merge.merge_lines())
154         merge_node = self.children.create(
155                     merge_parent=other, tree=self.tree,
156                     author=author,
157                     author_name=author_name,
158                     author_email=author_email,
159                     description=description)
160         merge_node.data.save('', ContentFile(result))
161         return merge_node
162
163     def revert(self, **kwargs):
164         """ commit this version of a doc as new head """
165         self.tree.commit(text=self.materialize(), **kwargs)
166
167     def set_publishable(self, publishable):
168         self.publishable = publishable
169         self.save()
170         post_publishable.send(sender=self, publishable=publishable)
171
172
173 def create_tag_model(model):
174     name = model.__name__ + 'Tag'
175
176     class Meta(Tag.Meta):
177         app_label = model._meta.app_label
178
179     attrs = {
180         '__module__': model.__module__,
181         'Meta': Meta,
182     }
183     return type(name, (Tag,), attrs)
184
185
186 def create_change_model(model):
187     name = model.__name__ + 'Change'
188     repo = GzipFileSystemStorage(location=model.REPO_PATH)
189
190     class Meta(Change.Meta):
191         app_label = model._meta.app_label
192
193     attrs = {
194         '__module__': model.__module__,
195         'tree': models.ForeignKey(model, related_name='change_set', verbose_name=_('document')),
196         'tags': models.ManyToManyField(model.tag_model, verbose_name=_('tags'), related_name='change_set'),
197         'data': models.FileField(_('data'), upload_to=data_upload_to, storage=repo),
198         'Meta': Meta,
199     }
200     return type(name, (Change,), attrs)
201
202
203 class DocumentMeta(ModelBase):
204     "Metaclass for Document models."
205     def __new__(cls, name, bases, attrs):
206
207         model = super(DocumentMeta, cls).__new__(cls, name, bases, attrs)
208         if not model._meta.abstract:
209             # create a real Tag object and `stage' fk
210             model.tag_model = create_tag_model(model)
211             models.ForeignKey(model.tag_model, verbose_name=_('stage'),
212                 null=True, blank=True).contribute_to_class(model, 'stage')
213
214             # create real Change model and `head' fk
215             model.change_model = create_change_model(model)
216
217             models.ForeignKey(model.change_model,
218                     null=True, blank=True, default=None,
219                     verbose_name=_('head'), 
220                     help_text=_("This document's current head."),
221                     editable=False).contribute_to_class(model, 'head')
222
223             models.ForeignKey(User, null=True, blank=True, editable=False,
224                 verbose_name=_('creator'), related_name="created_%s" % name.lower()
225                 ).contribute_to_class(model, 'creator')
226
227         return model
228
229
230 class Document(models.Model):
231     """File in repository. Subclass it to use version control in your app."""
232
233     __metaclass__ = DocumentMeta
234
235     # default repository path
236     REPO_PATH = os.path.join(settings.MEDIA_ROOT, 'dvcs')
237
238     user = models.ForeignKey(User, null=True, blank=True,
239         verbose_name=_('user'), help_text=_('Work assignment.'))
240
241     class Meta:
242         abstract = True
243
244     def __unicode__(self):
245         return u"{0}, HEAD: {1}".format(self.id, self.head_id)
246
247     def materialize(self, change=None):
248         if self.head is None:
249             return u''
250         if change is None:
251             change = self.head
252         elif not isinstance(change, Change):
253             change = self.change_set.get(pk=change)
254         return change.materialize()
255
256     def commit(self, text, author=None, author_name=None, author_email=None,
257             publishable=False, **kwargs):
258         """Commits a new revision.
259
260         This will automatically merge the commit into the main branch,
261         if parent is not document's head.
262
263         :param unicode text: new version of the document
264         :param parent: parent revision (head, if not specified)
265         :type parent: Change or None
266         :param User author: the commiter
267         :param unicode author_name: commiter name (if ``author`` not specified)
268         :param unicode author_email: commiter e-mail (if ``author`` not specified)
269         :param Tag[] tags: list of tags to apply to the new commit
270         :param bool publishable: set new commit as ready to publish
271         :returns: new head
272         """
273         if 'parent' not in kwargs:
274             parent = self.head
275         else:
276             parent = kwargs['parent']
277             if parent is not None and not isinstance(parent, Change):
278                 parent = self.change_set.objects.get(pk=kwargs['parent'])
279
280         tags = kwargs.get('tags', [])
281         if tags:
282             # set stage to next tag after the commited one
283             self.stage = max(tags, key=lambda t: t.ordering).get_next()
284
285         change = self.change_set.create(author=author,
286                     author_name=author_name,
287                     author_email=author_email,
288                     description=kwargs.get('description', ''),
289                     publishable=publishable,
290                     parent=parent)
291
292         change.tags = tags
293         change.data.save('', ContentFile(text.encode('utf-8')))
294         change.save()
295
296         if self.head:
297             # merge new change as new head
298             self.head = self.head.merge_with(change, author=author,
299                     author_name=author_name,
300                     author_email=author_email)
301         else:
302             self.head = change
303         self.save()
304
305         post_commit.send(sender=self.head)
306
307         return self.head
308
309     def history(self):
310         return self.change_set.all().order_by('revision')
311
312     def revision(self):
313         rev = self.change_set.aggregate(
314                 models.Max('revision'))['revision__max']
315         return rev
316
317     def at_revision(self, rev):
318         """Returns a Change with given revision number."""
319         return self.change_set.get(revision=rev)
320
321     def publishable(self):
322         changes = self.history().filter(publishable=True)
323         if changes.exists():
324             return changes.order_by('-revision')[0]
325         else:
326             return None
327
328     @transaction.commit_on_success
329     def prepend_history(self, other):
330         """Takes over the the other document's history and prepends to own."""
331
332         assert self != other
333         other_revs = other.change_set.all().count()
334         # workaround for a non-atomic UPDATE in SQLITE
335         self.change_set.all().update(revision=0-models.F('revision'))
336         self.change_set.all().update(revision=other_revs - models.F('revision'))
337         other.change_set.all().update(tree=self)
338         assert not other.change_set.exists()
339         other.delete()