Commits

Anonymous committed 2e8c56b

Replaced single quotes with double quotes per Pinax's style guide.

Comments (0)

Files changed (4)

apps/vcsbrowser/backends/hg/hg.py

         Returns an abbreviated representation of this revision's unique hash.
         """
         if len(self.id) > 8:
-            return str(self.id)[:8] + '...'
+            return str(self.id)[:8] + "..."
         else:
             return str(self.id)
     
         Sorts and classifies changed paths according to action
         Returns dict of added, modified, removed, renamed, and copied paths
         """
-        classified_paths = {'added':[], 'modified':[], 'removed':[], 'replaced':[], 'renamed':[], 'copied':[]}
+        classified_paths = {"added":[], "modified":[], "removed":[], "replaced":[], "renamed":[], "copied":[]}
         for (path, action) in self.changed_paths:
-            if 'oldname' in action:
-                if (action['type'] == 'rename'):
-                    classified_paths['renamed'].append(ChangedPath('renamed', path, action['oldname']['name']))
-                if (action['type'] == 'copy'):
-                    classified_paths['copied'].append(ChangedPath('copied', path, action['oldname']['name']))
+            if "oldname" in action:
+                if (action["type"] == "rename"):
+                    classified_paths["renamed"].append(ChangedPath("renamed", path, action["oldname"]["name"]))
+                if (action["type"] == "copy"):
+                    classified_paths["copied"].append(ChangedPath("copied", path, action["oldname"]["name"]))
             
             # XXX        
             # This is ugly and non-pythonic, but necessary because the nature
             # of self.changed_paths is really weird and non-standardized. 
             # Someone from the hg team should probably look into it and simplify the
             # below conditions once it's been fixed.
-            elif (action == 'creation') or (type(action)==type({}) and action['type'] == 'creation'):
-                classified_paths['added'].append(ChangedPath('added', path))
-            elif (action == 'diff') or (type(action)==type({}) and action['type'] == 'diff'):
-                classified_paths['modified'].append(ChangedPath('modified', path))
-            elif (action == 'deletion') or (type(action)==type({}) and action['type'] == 'deletion'):
-                classified_paths['removed'].append(ChangedPath('removed', path))
+            elif (action == "creation") or (type(action)==type({}) and action["type"] == "creation"):
+                classified_paths["added"].append(ChangedPath("added", path))
+            elif (action == "diff") or (type(action)==type({}) and action["type"] == "diff"):
+                classified_paths["modified"].append(ChangedPath("modified", path))
+            elif (action == "deletion") or (type(action)==type({}) and action["type"] == "deletion"):
+                classified_paths["removed"].append(ChangedPath("removed", path))
             else:
                 raise UnknownChangedPathActionError(path, action)           
                 
         self.repo_url = repo_url
         self.kiln_api = "http://" + settings.KILN_BIND_ADDRESS
         self.kiln = Kiln(slug, repo_url, self.kiln_api)
-        self.type = 'hg'
+        self.type = "hg"
         
     def get_node(self, path, rev=None):
         # TODO: Use a named constant rather than a magic string
         if rev is None: rev = "tip"
         node = self.kiln.get_file(path, rev)
-        if node["type"] == 'file':
+        if node["type"] == "file":
             return HgFile(self.slug, self.repo_url, self.kiln_api, path, rev)
-        elif node["type"] == 'files':
+        elif node["type"] == "files":
             return HgDirectory(self.slug, self.repo_url, self.kiln_api, path, rev)
         elif node["type"]:
             raise UnknownPathTypeError(node["type"], path)
             
         revs = []
 
-        if file_json.has_key('changesets'):
+        if file_json.has_key("changesets"):
             for change_set in file_json["changesets"]:
                 date = _to_datetime(change_set["date"])
                 if discover:
                     changed_path_list = []
                     diff_json = self.kiln.get_diff(path, change_set["rev"][1], None)
-                    for entry in diff_json['diffs']: 
-                        if entry.has_key('action'):
-                            action = entry['action']
-                        elif entry.has_key('type'):
-                            action = entry['type']
-                        file = entry['file']
-                        changed_path_list.append((join(file['path'], file['name']), action))
+                    for entry in diff_json["diffs"]: 
+                        if entry.has_key("action"):
+                            action = entry["action"]
+                        elif entry.has_key("type"):
+                            action = entry["type"]
+                        file = entry["file"]
+                        changed_path_list.append((join(file["path"], file["name"]), action))
                     rev = HgRevision(change_set["rev"][1], change_set["description"], change_set["user"], date, changed_path_list)
                 else:    
                     rev = HgRevision(change_set["rev"][1], change_set["description"], change_set["user"], date)
                 revs.append(rev)
             return revs
-        elif file_json.has_key('filechangesets'):
+        elif file_json.has_key("filechangesets"):
             history = []
             for change_set in file_json["filechangesets"]:
                 date = _to_datetime(change_set["date"])
         if rev is None: rev = "tip"
         revObj = (self.get_history("", rev, rev, True))
         if revObj == None:
-            raise InvalidRevisionError(rev.encode('utf-8'))
+            raise InvalidRevisionError(rev.encode("utf-8"))
         return revObj[0]
 
     def get_filter(self, revStart, revEnd, comment, dateStart, dateEnd):
         diff = ""
         
         # This is a file
-        if diff_json.has_key('diff'):
-            diff += diff_json['diff']
+        if diff_json.has_key("diff"):
+            diff += diff_json["diff"]
         
         # This is a directory
-        elif diff_json.has_key('diffs'):
-            for diffs in diff_json['diffs']:
-                if diffs['file']['path'].startswith(path):
-                    path_ = join(diffs['file']['path'], diffs['file']['name'])
+        elif diff_json.has_key("diffs"):
+            for diffs in diff_json["diffs"]:
+                if diffs["file"]["path"].startswith(path):
+                    path_ = join(diffs["file"]["path"], diffs["file"]["name"])
 #                    for line in (super(HgRepo,self).get_diff(path_, rev1, rev2)):
                     file_diff = (self.kiln.get_diff(path_, rev1, rev2))
-                    diff += '='*80 + "\n"
-                    if file_diff.has_key('diff'):
-                        for line in file_diff['diff']:
+                    diff += "="*80 + "\n"
+                    if file_diff.has_key("diff"):
+                        for line in file_diff["diff"]:
                             diff += line
         return diff
     
         self.repo_url = repo_url
         self.kiln = Kiln(slug, repo_url, kiln_api)
         if rev is None:
-            rev = 'tip'
+            rev = "tip"
         else:
             rev = rev
         super(HgPathNode, self).__init__(is_directory, path, rev, slug)
         if file_json is None:
             return None
         
-        if file_json.has_key('files'):
+        if file_json.has_key("files"):
             contents = file_json["files"]
         
         #Build the list base on type
         return latest_rev
     
     def get_absolute_url(self):
-        if self.rev == 'tip':
-            return reverse('vcs-dir_head', 
-                       kwargs={'slug':self.slug, 'path':self.path})
+        if self.rev == "tip":
+            return reverse("vcs-dir_head", 
+                       kwargs={"slug":self.slug, "path":self.path})
         else:
-            return reverse('vcs-dir_nonhead', 
-                       kwargs={'slug':self.slug, 'path':self.path, 'rev':self.rev})        
+            return reverse("vcs-dir_nonhead", 
+                       kwargs={"slug":self.slug, "path":self.path, "rev":self.rev})        
         
         
         
         if file_json is None:
             return None
         
-        if file_json.has_key('filetype'):
-            if file_json["filetype"] == 'base64':
+        if file_json.has_key("filetype"):
+            if file_json["filetype"] == "base64":
                 contents = file_json["contents"].decode("base64")
             else:
                 contents = file_json["contents"]
         mime.load()
         # XXX: This raises an exception if contents has characters outside of ASCII range!
         try:
-            contents = contents.encode('utf-8')
+            contents = contents.encode("utf-8")
         except UnicodeDecodeError:
             print "UnicodeDecodeError: " + self.path + " " + self.rev
             traceback.print_exc()
         if file_json is None:
             return None
         
-        if file_json.has_key('files'):
+        if file_json.has_key("files"):
             contents = file_json["files"]
         else:
             return None

apps/vcsbrowser/backends/hg/kiln_wrapper.py

        
     def get_file(self, path, rev):
         # Hex the path name.
-        path_hexed = path.rstrip('/').encode("hex")
+        path_hexed = path.rstrip("/").encode("hex")
         
         # Construct the API url.
         call_url  = self.api_url + "/repo/" + self.uuid + "/file/" + rev + "/"
         except urllib2.HTTPError:
             raise InvalidRevisionOrPathError(rev, path)
 
-    def get_history(self, path, rev_start=0, rev_end='tip'):
+    def get_history(self, path, rev_start=0, rev_end="tip"):
         # Hex the path name.
         if path is "":
             path_hexed = ""
         else:
-            path_hexed = "/" + path.rstrip('/').encode("hex")
+            path_hexed = "/" + path.rstrip("/").encode("hex")
         # Construct the API url.
         
         if rev_start is None:
             # Return dictionary with JSON.
             return json.loads(response)
         except urllib2.HTTPError:
-            raise InvalidRevisionOrPathError(str(rev_start) + ':' + str(rev_end), path)
+            raise InvalidRevisionOrPathError(str(rev_start) + ":" + str(rev_end), path)
 
-    def get_dir(self, path, rev='tip'):
+    def get_dir(self, path, rev="tip"):
         # Hex the path name.
-        path_hexed = path.rstrip('/').encode("hex")
+        path_hexed = path.rstrip("/").encode("hex")
         
         # Construct the API url.
         
         if path is "":
             path_hexed = ""
         else:
-            path_hexed = "/" + path.rstrip('/').encode("hex")
+            path_hexed = "/" + path.rstrip("/").encode("hex")
         
         # Construct the API url.
         if (not upto):
             # Return dictionary with JSON.
             return json.loads(response)
         except urllib2.HTTPError:
-            raise InvalidRevisionOrPathError(str(start) + ':' + str(upto), path)
+            raise InvalidRevisionOrPathError(str(start) + ":" + str(upto), path)
         

apps/vcsbrowser/models.py

     slug = models.CharField(max_length=2048, unique=True, null=False)
 
     # Repository type.
-    type = models.ForeignKey('RepoType')
+    type = models.ForeignKey("RepoType")
 
     def __unicode__(self):
         return self.path

apps/vcsbrowser/views.py

     
     for r in Repo.objects.all():
         repo = {
-                    'repo_name': r.name,
-                    'repo_slug': r.slug,
-                    'repo_url': r.path,
-                    'repo_type': RepoType.objects.get(id=r.type_id).type
+                    "repo_name": r.name,
+                    "repo_slug": r.slug,
+                    "repo_url": r.path,
+                    "repo_type": RepoType.objects.get(id=r.type_id).type
                 }
         
         repos += [repo]
 
-    return render_to_response('vcsbrowser.html',
-              {'repo_count': len(repos), 'repo_info': repos},
+    return render_to_response("vcsbrowser.html",
+              {"repo_count": len(repos), "repo_info": repos},
               context_instance=RequestContext(request))
 
 
     repo = get_repo(slug)
 
     # Trailing slashes can trip us up, but we should probably allow them in URLs
-    path = path.rstrip('/')
+    path = path.rstrip("/")
     try:          
         breadcrumbs, root = get_breadcrumbs(repo, path, rev)    
         current_node = repo.get_node(path, rev)
             else:
                 files.append(node)
             
-        return render_to_response('dir.html',
-                  {'subdirs':subdirs, 'files':files, 'breadcrumbs':breadcrumbs,
-                   'root':root, 'path':path, 'rev':rev, 'slug': slug,
-                   'repo_type':repo.type},
+        return render_to_response("dir.html",
+                  {"subdirs":subdirs, "files":files, "breadcrumbs":breadcrumbs,
+                   "root":root, "path":path, "rev":rev, "slug": slug,
+                   "repo_type":repo.type},
                    context_instance=RequestContext(request)
                   )
  
 
         # For a text file: 
         if file_type in MIME_TYPES:
-            return render_to_response('source.html',
+            return render_to_response("source.html",
             {"path" : path,
             "content" : highlight_code(file_type, file_content,
-                                       breadcrumbs[-1]['name']),
+                                       breadcrumbs[-1]["name"]),
             "root" : root,
-            'breadcrumbs':breadcrumbs,
-            'rev':rev,
-            'slug' : slug
+            "breadcrumbs":breadcrumbs,
+            "rev":rev,
+            "slug" : slug
             }, 
             context_instance=RequestContext(request))
 
     meta-data about those revisions.
     """
     repo = get_repo(slug)
-    path = path.rstrip('/')    
+    path = path.rstrip("/")    
     if rev_from == "":
         rev_from = None
     if rev_to == "":
         rev_to = None    
 
     # HG rev can be hash
-    if repo.type == 'svn':
+    if repo.type == "svn":
         if rev_from is not None:
             rev_from = int(rev_from)
         if rev_to is not None:
             rev_to = int(rev_to)
 
     try:
-        if repo.type == 'svn' : 
+        if repo.type == "svn" : 
             history_ = repo.get_history(path=str(path), start=rev_from, upto=rev_to)
         else:
             # hg only allows history of the whole repository
 
     # if page is not an int, show page #1.
     try:
-        page = int(request.GET.get('page', '1'))
+        page = int(request.GET.get("page", "1"))
     except ValueError:
         page = 1
 
         history_ = paginator.page(paginator.num_pages)
         
     return render_to_response("history.html",
-                              {'history':history_, "breadcrumbs":breadcrumbs, 
-                               'slug': slug, 'path':path, 'root':root,
-                               'rev_from':rev_from, 'rev_to':rev_to,
-                               'repo_type':repo.type},
+                              {"history":history_, "breadcrumbs":breadcrumbs, 
+                               "slug": slug, "path":path, "root":root,
+                               "rev_from":rev_from, "rev_to":rev_to,
+                               "repo_type":repo.type},
                                context_instance=RequestContext(request)
                               )
 
     repo = get_repo(slug)
     
     # HG rev can be hash
-    if repo.type == 'svn':
+    if repo.type == "svn":
         if revno is not None:
             revno = int(revno)
 
     # TODO: Most of these variables are unnecessary. If we pass in rev directly
     # the template can access its attributes as it wishes.
     return render_to_response("rev_view.html", 
-                                {'repo_type':repo.type, 'slug':slug, 
-                                'curr_rev':revno, 'author':str(rev.author),
-                                'date':str(rev.date),
-                                'comment':str(rev.comment),
-                                'changed_paths':changed_paths }, 
+                                {"repo_type":repo.type, "slug":slug, 
+                                "curr_rev":revno, "author":str(rev.author),
+                                "date":str(rev.date),
+                                "comment":str(rev.comment),
+                                "changed_paths":changed_paths }, 
                                 context_instance=RequestContext(request)
                               )
 
     repo = get_repo(slug)    
     
     # Trailing slashes can trip us up, but we should probably allow them in URLs
-    path = path.rstrip('/')
+    path = path.rstrip("/")
     try:
         current_node = repo.get_node(path, rev)
     except InvalidRevisionOrPathError:
     # Node is a directory
     if current_node.is_directory:
         zip_ = repo.get_download(path, rev)
-        response = HttpResponse(zip_, mimetype='application/zip')
-        response['Content-Disposition'] = 'attachment; filename=' + current_node.path.split('/')[-1] + ".zip"
+        response = HttpResponse(zip_, mimetype="application/zip")
+        response["Content-Disposition"] = "attachment; filename=" + current_node.path.split("/")[-1] + ".zip"
         return response
     else:
     # Node is a file
         # Process file contents
         ## XXX Currently does not work with files on the root
         (file_content, file_type) = current_node.get_contents()
-        response = HttpResponse(file_content, mimetype='application/force-download')
-        response['Content-Disposition'] = 'attachment; filename=' + current_node.path.split('/')[-1]
+        response = HttpResponse(file_content, mimetype="application/force-download")
+        response["Content-Disposition"] = "attachment; filename=" + current_node.path.split("/")[-1]
         return response
     
 def dir_diff(request, slug, path, rev_from, rev_to):
     than the current implementation.  
     """
     repo = get_repo(slug)
-    path = path.rstrip('/')
+    path = path.rstrip("/")
     breadcrumbs, root = get_breadcrumbs(repo, path, None)
-    diffs = [{'path': file_['path'], 'action': action['type'], 'diff': diff_}
+    diffs = [{"path": file_["path"], "action": action["type"], "diff": diff_}
              for (file_, action, diff_)
              in repo.get_dirdiff(path, rev_from, rev_to)]
     return render_to_response("dir_diff.html",
-                              {'diffs':diffs, 'path':path, 'rev':'NOREV',
-                               'breadcrumbs':breadcrumbs, 'root':root,
-                               'slug':slug, 'rev_from':rev_from,
-                               'rev_to':rev_to},
+                              {"diffs":diffs, "path":path, "rev":"NOREV",
+                               "breadcrumbs":breadcrumbs, "root":root,
+                               "slug":slug, "rev_from":rev_from,
+                               "rev_to":rev_to},
                               context_instance=RequestContext(request))
 
 def diff(request, slug, path, rev_from, rev_to=None):
     files contained therein, recursively.
     """
     repo = get_repo(slug)
-    path = path.rstrip('/')
+    path = path.rstrip("/")
     
     try:
         breadcrumbs, root = get_breadcrumbs(repo, path, None)
         raise Http404
 
     try:
-        line_length = int(request.GET['wrap'])
+        line_length = int(request.GET["wrap"])
         # 0 is permitted, and disables wrapping
         assert line_length >= 0
         
     
     if not node.is_directory:
         # It's a file, use the standard diff
-        f1 = repo.get_file(path, rev_from).get_contents()[0].split('\n')
-        f2 = repo.get_file(path, rev_to).get_contents()[0].split('\n')
+        f1 = repo.get_file(path, rev_from).get_contents()[0].split("\n")
+        f2 = repo.get_file(path, rev_to).get_contents()[0].split("\n")
     
         if rev_to == None:
-            rev_to = 'HEAD' # For formatting of the diff
+            rev_to = "HEAD" # For formatting of the diff
 
-        diff_ = difflib.HtmlDiff(wrapcolumn=line_length).make_table(f1, f2, fromdesc='r'+rev_from, todesc='r'+rev_to)
+        diff_ = difflib.HtmlDiff(wrapcolumn=line_length).make_table(f1, f2, fromdesc="r"+rev_from, todesc="r"+rev_to)
 
     else:
         # It's not a file, use the repo's diff function
         diff_ = "<table><tr><td><pre>" + escape(repo.get_diff(path, rev_from, rev_to)) + "</pre></tr></td></table>"
 
     return render_to_response("diff.html",
-                              {'diff':diff_, 'path':path, 'rev':'NOREV',
-                              'breadcrumbs':breadcrumbs, 'root':root,
-                              'slug':slug, 'rev_from':rev_from,
-                              'rev_to':rev_to},
+                              {"diff":diff_, "path":path, "rev":"NOREV",
+                              "breadcrumbs":breadcrumbs, "root":root,
+                              "slug":slug, "rev_from":rev_from,
+                              "rev_to":rev_to},
                               context_instance=RequestContext(request))
 
-def patch(request, slug, path, rev_from, rev_to='HEAD'):
+def patch(request, slug, path, rev_from, rev_to="HEAD"):
     """
     Initiate a transfer of a unix diff file containing the differences
     between the file at path (or files, if path is a directory) between
     revisions rev_from and rev_to.
     """ 
     repo = get_repo(slug)
-    path = path.rstrip('/')
+    path = path.rstrip("/")
 
     patch_str = repo.get_diff(path, rev_from, rev_to)
 
-    response = HttpResponse(patch_str, mimetype='application/force-download')
-    response['Content-Disposition'] = 'attachment; filename=' + path.split('/')[-1] + ".diff"
+    response = HttpResponse(patch_str, mimetype="application/force-download")
+    response["Content-Disposition"] = "attachment; filename=" + path.split("/")[-1] + ".diff"
     return response
 
 def get_breadcrumbs(repo, path, rev):
     """
     names = []
     nodes = []
-    # Path == '' is a weird corner case. We're already holding the root in
+    # Path == "" is a weird corner case. We're already holding the root in
     # a separate variable, so there's no point repeating it in breadcrumbs.
-    for crumb in path.split('/') * bool(path):
+    for crumb in path.split("/") * bool(path):
         names.append(crumb)
-        nodes.append(repo.get_node('/'.join(names), rev))
-    breadcrumbs = [{'name':name, 'node':node} for name, node in zip(names, nodes)]
-    root = repo.get_dir('', rev)
+        nodes.append(repo.get_node("/".join(names), rev))
+    breadcrumbs = [{"name":name, "node":node} for name, node in zip(names, nodes)]
+    root = repo.get_dir("", rev)
     return breadcrumbs, root
 
 def get_repo(slug):
     repo_type = RepoType.objects.get(id=repo.type_id).type
     repo_url  = repo.path
 
-    return hg.HgRepo(slug, repo_url) if repo_type == 'hg' else svn.SvnRepo(slug, repo_url)
+    return hg.HgRepo(slug, repo_url) if repo_type == "hg" else svn.SvnRepo(slug, repo_url)