damned-lies r1457 - in trunk: . templates/vertimus vertimus



Author: stephaner
Date: Fri Feb 27 18:08:54 2009
New Revision: 1457
URL: http://svn.gnome.org/viewvc/damned-lies?rev=1457&view=rev

Log:
2009-02-27  StÃphane Raimbault  <stephane raimbault gmail com>

	* templates/vertimus/vertimus_detail.html: Rename action to action_id.
	* vertimus/models.py: Useless import of default_storage. Add
	get_previous_action_with_po() and state in ActionAbstract. Rename
	action to action_db when it's an ActionDb instance.
	* vertimus/urls.py: action_id_1 and action_id_2.
	* vertimus/views.py: Remove useless imports. Use real action and
	state objects. Use get_object_or_404 for the action_id_2 (URL arg).
	Coding conventions details.


Modified:
   trunk/ChangeLog
   trunk/templates/vertimus/vertimus_detail.html
   trunk/vertimus/models.py
   trunk/vertimus/urls.py
   trunk/vertimus/views.py

Modified: trunk/templates/vertimus/vertimus_detail.html
==============================================================================
--- trunk/templates/vertimus/vertimus_detail.html	(original)
+++ trunk/templates/vertimus/vertimus_detail.html	Fri Feb 27 18:08:54 2009
@@ -80,7 +80,7 @@
           {% endif %}
           <div class="right_actions">{% trans "diff with:" %}
             {% for f in files %}
-                <a href="{% url vertimus-diff-view action.id,f.action %}" title="{{ f.title }}">[{{ forloop.revcounter }}]</a>
+                <a href="{% url vertimus-diff-view action.id,f.action_id %}" title="{{ f.title }}">[{{ forloop.revcounter }}]</a>
             {% endfor %}
           </div>
         {% endif %}

Modified: trunk/vertimus/models.py
==============================================================================
--- trunk/vertimus/models.py	(original)
+++ trunk/vertimus/models.py	Fri Feb 27 18:08:54 2009
@@ -26,7 +26,6 @@
 from django.core import mail, urlresolvers
 from django.contrib.sites.models import Site
 from django.conf import settings
-from django.core.files.storage import default_storage
 from django.db.models.signals import post_save, pre_delete
 
 from stats.models import Branch, Domain, Statistics
@@ -267,16 +266,19 @@
     'IC', 'TR',
     'BA', 'UNDO')
 
-def generate_upload_file_name(instance, original_filename):
-    base, ext = os.path.splitext(original_filename)
-    if os.path.splitext(base)[1] == ".tar":
+def generate_upload_file_name(instance, pathname):
+    # Extract the first extension (with the point)
+    root, ext = os.path.splitext(pathname)
+    # Check if a second extension is present
+    if os.path.splitext(root)[1] == ".tar":
         ext = ".tar" + ext
-    filename = "%s-%s-%s-%s-%s%s" % (instance.state_db.branch.module.name, 
-                                     instance.state_db.branch.name, 
-                                     instance.state_db.domain.name,
-                                     instance.state_db.language.locale,
-                                     instance.state_db.id,
-                                     ext)
+    filename = "%s-%s-%s-%s-%s%s" % (
+        instance.state_db.branch.module.name, 
+        instance.state_db.branch.name, 
+        instance.state_db.domain.name,
+        instance.state_db.language.locale,
+        instance.state_db.id,
+        ext)
     return "%s/%s" % (settings.UPLOAD_DIR, filename)
 
 class ActionDb(models.Model):
@@ -298,45 +300,53 @@
         action._action_db = self
         return action
 
-    def get_previous_action_with_po(self):
-        """ Returns the previous action with an uploaded file related to the same state """
+    def get_previous_action_db_with_po(self):
+        """
+        Return the previous ActionDb with an uploaded file related to the
+        same state.
+        """
         try:
             action_db = ActionDb.objects.filter(file__endswith=".po", state_db=self.state_db,
                 id__lt=self.id).latest('id')
-            return action_db.get_action()
+            return action_db
         except ActionDb.DoesNotExist:
             return None
 
-    def merge_file_with_pot(self, potfile):
-        """ Merge the uploaded translated file with current pot """
+    def merge_file_with_pot(self, pot_file):
+        """Merge the uploaded translated file with current pot."""
         if self.file:
-            command = "msgmerge --previous -o %(outpo)s %(pofile)s %(potfile)s" % {
-                      'outpo':   self.file.path[:-3] + ".merged.po",
-                      'pofile':  self.file.path,
-                      'potfile': potfile
-                      }
+            command = "msgmerge --previous -o %(out_po)s %(po_file)s %(pot_file)s" % {
+                'out_po': self.file.path[:-3] + ".merged.po",
+                'po_file': self.file.path,
+                'pot_file': pot_file
+            }
             run_shell_command(command)
 
     @classmethod
     def get_action_history(cls, state_db):
-        """ Return action history as a list of tuples (action, file_history)
-            File_history is a list of previous po files, used in vertimus view to generate diff links """
+        """
+        Return action history as a list of tuples (action, file_history),
+        file_history is a list of previous po files, used in vertimus view to
+        generate diff links
+        """
         history = []
         if state_db:
-            file_history = [{'action':0, 'title': ugettext("File in repository")}]
-            for va_db in ActionDb.objects.filter(state_db__id=state_db.id).order_by('id'):
-                history.append((va_db.get_action(), list(file_history)))
-                if va_db.file and va_db.file.path.endswith('.po'):
-                    file_history.insert(0, {'action':va_db.id,
-                                            'title': ugettext("Uploaded file by %(name)s on %(date)s") % { 
-                                                                'name': va_db.person.name,
-                                                                'date': va_db.created },
-                                           })
+            file_history = [{'action_id':0, 'title': ugettext("File in repository")}]
+            for action_db in ActionDb.objects.filter(state_db__id=state_db.id).order_by('id'):
+                history.append((action_db.get_action(), list(file_history)))
+                if action_db.file and action_db.file.path.endswith('.po'):
+                    # Action.id and ActionDb.id are identical (inheritance)
+                    file_history.insert(0, {
+                        'action_id': action_db.id,
+                        'title': ugettext("Uploaded file by %(name)s on %(date)s") % { 
+                            'name': action_db.person.name,
+                            'date': action_db.created },
+                        })
         return history
 
     def __unicode__(self):
         return "%s (%s)" % (self.name, self.id)
-    
+
 
 class ActionAbstract(object):
     """Abstract class"""
@@ -375,6 +385,21 @@
     def file(self):
         return self._action_db.file
 
+    @property
+    def state(self):
+        return self._action_db.state_db.get_state()
+
+    def get_previous_action_with_po(self):
+        """
+        Return the previous Action with an uploaded file related to the same
+        state.
+        """
+        action_db = self._action_db.get_previous_action_db_with_po()
+        if action_db:
+            return action_db.get_action()
+        else:
+            return None
+
     def save_action_db(self, state, person, comment=None, file=None):
         """Used by apply"""
         self._action_db = ActionDb(state_db=state._state_db,
@@ -393,7 +418,7 @@
             return None
 
     def merged_file(self):
-        """ If available, returns the merged file as a dict: {'url':'path':'filename':} """
+        """If available, returns the merged file as a dict: {'url':'path':'filename'}"""
         mfile_url = mfile_path = mfile_name = None
         if self._action_db.file:
             mfile_url = self._action_db.file.url[:-3] + ".merged.po"
@@ -674,8 +699,7 @@
         self.save_action_db(state, person, comment, file)
 
         # Exclude WC because this action is a noop on State
-        actions_db = ActionDb.objects.filter(state_db__id=state._state_db.id).exclude(
-            name='WC').order_by('-id')
+        actions_db = ActionDb.objects.filter(state_db__id=state._state_db.id).exclude(name='WC').order_by('-id')
         i = 0
         while (i < len(actions_db)):
             if actions_db[i].name == 'UNDO':
@@ -688,7 +712,7 @@
         return StateNone()
 
 def update_uploaded_files(sender, **kwargs):
-    """ Callback to handle pot_file_changed signal """
+    """Callback to handle pot_file_changed signal"""
     actions = ActionDb.objects.filter(state_db__branch=kwargs['branch'],
                                       state_db__domain=kwargs['domain'],
                                       file__endswith=".po")
@@ -697,7 +721,10 @@
 pot_has_changed.connect(update_uploaded_files)
 
 def merge_uploaded_file(sender, instance, **kwargs):
-    """ post_save callback for ActionDb that automatically merge uploaded file with latest pot file """
+    """
+    post_save callback for ActionDb that automatically merge uploaded file
+    with latest pot file.
+    """
     if instance.file and instance.file.path.endswith('.po'):
         try:
             stat = Statistics.objects.get(branch=instance.state_db.branch, domain=instance.state_db.domain, language=None)
@@ -708,10 +735,12 @@
 post_save.connect(merge_uploaded_file, sender=ActionDb)
 
 def delete_merged_file(sender, instance, **kwargs):
-    """ pre_delete callback for ActionDb that deletes the merged file from upload dir """
+    """
+    pre_delete callback for ActionDb that deletes the merged file from upload
+    directory.
+    """
     if instance.file and instance.file.path.endswith('.po'):
         merged_file = instance.file.path[:-3] + ".merged.po"
         if os.access(merged_file, os.W_OK):
              os.remove(merged_file)
 pre_delete.connect(delete_merged_file, sender=ActionDb)
-

Modified: trunk/vertimus/urls.py
==============================================================================
--- trunk/vertimus/urls.py	(original)
+++ trunk/vertimus/urls.py	Fri Feb 27 18:08:54 2009
@@ -4,5 +4,5 @@
     url(r'^(?P<stats_id>\d+)/(?P<lang_id>\d+)$', 'vertimus_by_stats_id', name='vertimus-stats-id-view'),
     url(r'^(?P<branch_id>\d+)/(?P<domain_id>\d+)/(?P<language_id>\d+)', 'vertimus_by_ids', name='vertimus-ids-view'),
     url(r'^(?P<module_name>[\w\+\-\.]+)/(?P<branch_name>[\w\-\.]+)/(?P<domain_name>[\w\-]+)/(?P<locale_name>[\w\- ]+)', 'vertimus_by_names', name='vertimus-names-view'),
-    url(r'^diff/(?P<action_id>\d+)/(?P<action_id2>\d+)?$', 'vertimus_diff', name='vertimus-diff-view')
+    url(r'^diff/(?P<action_id_1>\d+)/(?P<action_id_2>\d+)?$', 'vertimus_diff', name='vertimus-diff-view')
 )

Modified: trunk/vertimus/views.py
==============================================================================
--- trunk/vertimus/views.py	(original)
+++ trunk/vertimus/views.py	Fri Feb 27 18:08:54 2009
@@ -18,15 +18,12 @@
 # along with Damned Lies; if not, write to the Free Software Foundation, Inc.,
 # 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
-from datetime import datetime
 from django.utils.translation import ugettext as _
 from django.shortcuts import render_to_response, get_object_or_404
-from django.http import HttpResponseRedirect, Http404
+from django.http import HttpResponseRedirect
 from django.template import RequestContext
 from django.core import urlresolvers
-from django.conf import settings
 
-from people.models import Person
 from stats.models import Statistics, Module, Branch, Domain, Language
 from vertimus.models import StateDb, ActionDb, ActionAbstract
 from vertimus.forms import ActionForm
@@ -110,46 +107,50 @@
     return render_to_response('vertimus/vertimus_detail.html', context,
                               context_instance=RequestContext(request))
 
-def vertimus_diff(request, action_id, action_id2=None):
-    """ Show a diff between current action po file and previous file """
+def vertimus_diff(request, action_id_1, action_id_2=None):
+    """Show a diff between current action po file and previous file"""
     import difflib
-    action_db1 = get_object_or_404(ActionDb, pk=action_id)
-    state = action_db1.state_db
-    file_path1 = action_db1.get_action().merged_file()['path']
-    if not file_path1:
-        file_path1 = action_db1.file.path
-    content1 = [l.decode('utf-8') for l in open(file_path1, 'U').readlines()]
-    descr1 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action_db1.person.name,
-                                                            'date': action_db1.created }
-    if action_id2 not in (None, "0"):
-        # 1) id2 specified in url
-        action2 = ActionDb.objects.get(id=action_id2)
-        file_path2 = action2.get_action().merged_file()['path']
-        descr2 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action2.person.name,
-                                                                'date': action2.created }
+    action_1 = get_object_or_404(ActionDb, pk=action_id_1).get_action()
+    state = action_1.state
+
+    file_path_1 = action_1.merged_file()['path']
+    if not file_path_1:
+        # The merged file isn't availabe yet
+        file_path_1 = action_1.file.path
+
+    content_1 = [l.decode('utf-8') for l in open(file_path_1, 'U').readlines()]
+    descr_1 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action_1.person.name,
+                                                             'date': action_1.created }
+    if action_id_2 not in (None, "0"):
+        # 1) id_2 specified in URL
+        action_2 = get_object_or_404(ActionDb, pk=action_id_2).get_action()
+        file_path_2 = action_2.merged_file()['path']
+        descr_2 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action_2.person.name,
+                                                                 'date': action_2.created }
     else:        
-        action2 = None
-        if action_id2 is None:
+        action_2 = None
+        if action_id_2 is None:
             # 2) Search previous in action history
-            action2 = action_db1.get_previous_action_with_po()
-        if action2:
-            file_path2 = action2.merged_file()['path']
-            descr2 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action2.person.name,
-                                                                    'date': action2.created }
+            action_2 = action_1.get_previous_action_with_po()
+
+        if action_2:
+            file_path_2 = action_2.merged_file()['path']
+            descr_2 = _("Uploaded file by %(name)s on %(date)s") % { 'name': action_2.person.name,
+                                                                     'date': action_2.created }
         else:
              # 3) Lastly, the file should be the more recently committed file (merged)
             try:
                 stats = Statistics.objects.get(branch=state.branch, domain=state.domain, language=state.language)
-                descr2 = _("Latest committed file for %(lang)s" % {'lang': state.language.get_name()})
+                descr_2 = _("Latest committed file for %(lang)s" % {'lang': state.language.get_name()})
             except Statistics.DoesNotExist:
                 stats = get_object_or_404(Statistics, branch=state.branch, domain=state.domain, language=None)
-                descr2 = _("Latest POT file")
-            file_path2 = stats.po_path()
+                descr_2 = _("Latest POT file")
+            file_path_2 = stats.po_path()
 
-    content2 = [l.decode('utf-8') for l in open(file_path2, 'U').readlines()]
+    content_2 = [l.decode('utf-8') for l in open(file_path_2, 'U').readlines()]
     d = difflib.HtmlDiff()
-    diff_content = d.make_table(content2, content1,
-                                descr2, descr1, context=True)
+    diff_content = d.make_table(content_2, content_1,
+                                descr_2, descr_1, context=True)
 
     context = {
         'diff_content': diff_content,



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]