Skip to contentSkip to conversation

toaster: typeaheads widgets Fix flake8 issues and remove redundant code

PATCH New Michael Wood 1 participant 3 messages Dec 1, 2016

lore
Share & tools
lore
#0 lore raw

PATCH 1/3 toaster: typeaheads widgets Fix flake8 issues and remove redundant code

Fix flake8 issues and remove redundant __init__ function definitions from typeaheads (likely a copy and paste error).

---
 bitbake/lib/toaster/toastergui/typeaheads.py | 80 ++++++++++++++--------------
 bitbake/lib/toaster/toastergui/widgets.py    |  8 +--
 2 files changed, 45 insertions(+), 43 deletions(-)
bitbake/lib/toaster/toastergui/typeaheads.py +41 -39
index 4ded9ac..2c6c145 100644
@@ -23,8 +23,6 @@ from django.core.urlresolvers import reverse
 class LayersTypeAhead(ToasterTypeAhead):
     """ Typeahead for layers available and not added in the current project's
     configuration """
-    def __init__(self):
-      super(LayersTypeAhead, self).__init__()
 
     def apply_search(self, search_term, prj, request):
         layers = prj.get_all_compatible_layer_versions()
@@ -33,13 +31,15 @@ class LayersTypeAhead(ToasterTypeAhead):
         # Unlike the other typeaheads we also don't want to show suggestions
         # for layers already in the project unless required such as when adding
         # layerdeps to a new layer.
-        if ("include_added" in request.GET and
-                request.GET['include_added'] != "true"):
+        if "include_added" in request.GET and \
+           request.GET['include_added'] != "true":
             layers = layers.exclude(
                 pk__in=prj.get_project_layer_versions(pk=True))
 
         primary_results = layers.filter(layer__name__istartswith=search_term)
-        secondary_results = layers.filter(layer__name__icontains=search_term).exclude(pk__in=primary_results)
+        secondary_results = layers.filter(
+            layer__name__icontains=search_term).exclude(
+                pk__in=primary_results)
 
         results = []
 
@@ -49,97 +49,99 @@ class LayersTypeAhead(ToasterTypeAhead):
             detail = "[ %s | %s ]" % (layer_version.layer.vcs_url,
                                       vcs_reference)
             needed_fields = {
-                'id' : layer_version.pk,
-                'name' : layer_version.layer.name,
-                'layerdetailurl' : layer_version.get_detailspage_url(prj.pk),
-                'vcs_url' : layer_version.layer.vcs_url,
-                'vcs_reference' : vcs_reference,
-                'detail' : detail,
-                'local_source_dir' : layer_version.layer.local_source_dir,
+                'id': layer_version.pk,
+                'name': layer_version.layer.name,
+                'layerdetailurl': layer_version.get_detailspage_url(prj.pk),
+                'vcs_url': layer_version.layer.vcs_url,
+                'vcs_reference': vcs_reference,
+                'detail': detail,
+                'local_source_dir': layer_version.layer.local_source_dir,
             }
 
             results.append(needed_fields)
 
         return results
 
+
 class MachinesTypeAhead(ToasterTypeAhead):
     """ Typeahead for all the machines available in the current project's
     configuration """
-    def __init__(self):
-        super(MachinesTypeAhead, self).__init__()
 
     def apply_search(self, search_term, prj, request):
         machines = prj.get_available_machines()
         machines = machines.order_by("name")
 
         primary_results = machines.filter(name__istartswith=search_term)
-        secondary_results = machines.filter(name__icontains=search_term).exclude(pk__in=primary_results)
-        tertiary_results = machines.filter(layer_version__layer__name__icontains=search_term).exclude(pk__in=primary_results).exclude(pk__in=secondary_results)
+        secondary_results = machines.filter(
+            name__icontains=search_term).exclude(pk__in=primary_results)
+        tertiary_results = machines.filter(
+            layer_version__layer__name__icontains=search_term).exclude(
+                pk__in=primary_results).exclude(pk__in=secondary_results)
 
         results = []
 
-        for machine in list(primary_results) + list(secondary_results) + list(tertiary_results):
+        for machine in list(primary_results) + list(secondary_results) + \
+                list(tertiary_results):
 
             detail = "[ %s ]" % (machine.layer_version.layer.name)
             needed_fields = {
-                'id' : machine.pk,
-                'name' : machine.name,
-                'detail' : detail,
+                'id': machine.pk,
+                'name': machine.name,
+                'detail': detail,
             }
 
             results.append(needed_fields)
-
         return results
 
+
 class RecipesTypeAhead(ToasterTypeAhead):
     """ Typeahead for all the recipes available in the current project's
     configuration """
-    def __init__(self):
-        super(RecipesTypeAhead, self).__init__()
-
     def apply_search(self, search_term, prj, request):
         recipes = prj.get_available_recipes()
         recipes = recipes.order_by("name")
 
-
         primary_results = recipes.filter(name__istartswith=search_term)
-        secondary_results = recipes.filter(name__icontains=search_term).exclude(pk__in=primary_results)
-        tertiary_results = recipes.filter(layer_version__layer__name__icontains=search_term).exclude(pk__in=primary_results).exclude(pk__in=secondary_results)
+        secondary_results = recipes.filter(
+            name__icontains=search_term).exclude(pk__in=primary_results)
+        tertiary_results = recipes.filter(
+            layer_version__layer__name__icontains=search_term).exclude(
+                pk__in=primary_results).exclude(pk__in=secondary_results)
 
         results = []
 
-        for recipe in list(primary_results) + list(secondary_results) + list(tertiary_results):
+        for recipe in list(primary_results) + list(secondary_results) + \
+                list(tertiary_results):
 
             detail = "[ %s ]" % (recipe.layer_version.layer.name)
             needed_fields = {
-                'id' : recipe.pk,
-                'name' : recipe.name,
-                'detail' : detail,
+                'id': recipe.pk,
+                'name': recipe.name,
+                'detail': detail,
             }
 
             results.append(needed_fields)
 
         return results
 
+
 class ProjectsTypeAhead(ToasterTypeAhead):
     """ Typeahead for all the projects, except for command line builds """
-    def __init__(self):
-        super(ProjectsTypeAhead, self).__init__()
-
     def apply_search(self, search_term, prj, request):
         projects = Project.objects.exclude(is_default=True).order_by("name")
 
         primary_results = projects.filter(name__istartswith=search_term)
-        secondary_results = projects.filter(name__icontains=search_term).exclude(pk__in=primary_results)
+        secondary_results = projects.filter(
+            name__icontains=search_term).exclude(pk__in=primary_results)
 
         results = []
 
         for project in list(primary_results) + list(secondary_results):
             needed_fields = {
-                'id' : project.pk,
-                'name' : project.name,
-                'detail' : "",
-                'projectPageUrl' : reverse('project', args=(project.pk,))
+                'id': project.pk,
+                'name': project.name,
+                'detail': "",
+                'projectPageUrl': reverse('project', args=(project.pk,))
             }
 
             results.append(needed_fields)
bitbake/lib/toaster/toastergui/widgets.py +4 -4
index 026903d..6b7b981 100644
@@ -42,6 +42,8 @@ import json
 import collections
 import re
 
+from toastergui.tablefilter import TableFilterMap
+
 try:
     from urllib import unquote_plus
 except ImportError:
@@ -50,8 +52,6 @@ except ImportError:
 import logging
 logger = logging.getLogger("toaster")
 
-from toastergui.tablefilter import TableFilterMap
-
 
 class NoFieldOrDataName(Exception):
     pass
@@ -259,9 +259,9 @@ class ToasterTable(TemplateView):
                     queries = query
 
             if search_queries:
-               search_queries &= queries
+                search_queries &= queries
             else:
-               search_queries = queries
+                search_queries = queries
 
         self.queryset = self.queryset.filter(search_queries)
 
Signature · 1 line
2.7.4
#1 lore raw

PATCH 2/3 toaster: typeaheads Add a git revisions suggestions

When we're importing a layer it's useful to suggest available git revisions of the layers. This uses git ls-remote to fetch the revisions and then filter on this. Caching is added for this typeahead to avoid having to fetch this information multiple times in a single session.

[YOCTO #8429]

---
 bitbake/lib/toaster/toastergui/typeaheads.py | 29 ++++++++++++++++++++++++++++
 bitbake/lib/toaster/toastergui/urls.py       |  5 +++--
 2 files changed, 32 insertions(+), 2 deletions(-)
bitbake/lib/toaster/toastergui/typeaheads.py +29 -0
index 2c6c145..5316000 100644
@@ -16,9 +16,12 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
+import subprocess
+
 from toastergui.widgets import ToasterTypeAhead
 from orm.models import Project
 from django.core.urlresolvers import reverse
+from django.core.cache import cache
 
 class LayersTypeAhead(ToasterTypeAhead):
     """ Typeahead for layers available and not added in the current project's
@@ -147,3 +150,29 @@ class ProjectsTypeAhead(ToasterTypeAhead):
             results.append(needed_fields)
 
         return results
+
+
+class GitRevisionTypeAhead(ToasterTypeAhead):
+    def apply_search(self, search_term, prj, request):
+        results = []
+        git_url = request.GET.get('git_url')
+        ls_remote = cache.get(git_url)
+
+        if ls_remote is None:
+            ls_remote = subprocess.check_output(['git', 'ls-remote', git_url],
+                                                universal_newlines=True)
+            ls_remote = ls_remote.splitlines()
+            # Avoid fetching the list of git refs on each new input
+            cache.set(git_url, ls_remote, 120)
+
+        for rev in ls_remote:
+            git_rev = str(rev).split("/")[-1:][0]
+            # "HEAD" has a special meaning in Toaster...  YOCTO #9924
+            if "HEAD" in git_rev:
+                continue
+
+            if git_rev.startswith(search_term):
+                results.append({'name': git_rev,
+                                'detail': '[ %s ]' % str(rev)})
+
+        return results
bitbake/lib/toaster/toastergui/urls.py +3 -2
index 29f0d96..d92f190 100644
@@ -182,8 +182,9 @@ urlpatterns = patterns('toastergui.views',
             typeaheads.RecipesTypeAhead.as_view(), name='xhr_recipestypeahead'),
         url(r'^xhr_typeahead/projects$',
             typeaheads.ProjectsTypeAhead.as_view(), name='xhr_projectstypeahead'),
-
-
+        url(r'^xhr_typeahead/gitrev$',
+            typeaheads.GitRevisionTypeAhead.as_view(),
+            name='xhr_gitrevtypeahead'),
 
         url(r'^xhr_testreleasechange/(?P<pid>\d+)$', 'xhr_testreleasechange',
             name='xhr_testreleasechange'),
Signature · 1 line
2.7.4
#2 lore raw

PATCH 3/3 toaster: importlayer Add git revision typeahead to that input field

In reply to Michael Wood

Add the front end mechanism to load the typeahead for the git revision field on importing a layer.
Also fix one indentation issue and update the js test.

---
 .../lib/toaster/toastergui/static/css/default.css  |  1 -
 .../toaster/toastergui/static/js/importlayer.js    | 29 +++++++++++++++++-----
 .../lib/toaster/toastergui/static/js/tests/test.js |  2 +-
 .../toaster/toastergui/templates/importlayer.html  |  5 +++-
 4 files changed, 28 insertions(+), 9 deletions(-)
bitbake/lib/toaster/toastergui/static/css/default.css +0 -1
index ff24e8c..5cd7e21 100644
@@ -210,7 +210,6 @@ fieldset.fields-apart-from-layer-name { margin-top: 20px; }
 #import-layer-name,
 #layer-subdir { width: 20%; }
 #layer-git-repo-url { width: 40%; }
-#layer-git-ref { width: 32%; }
 #local-dir-path { width: 45%; }
 #layer-dependency { width: 16em; }
 #layer-deps-list { margin-top: 0; }
bitbake/lib/toaster/toastergui/static/js/importlayer.js +23 -6
index 4784c65..b3f094e 100644
@@ -45,7 +45,7 @@ function importLayerPageInit (ctx) {
     function(layer) {
     if (layer.results.length > 0) {
       currentLayerDepSelection = layer.results[0];
-      layerDepBtn.click();
+        layerDepBtn.click();
     }
   });
 
@@ -333,19 +333,36 @@ function importLayerPageInit (ctx) {
     check_form();
   });
 
-  /* Have a guess at the layer name */
+  /* Setup 'blank' typeahead */
+  libtoaster.makeTypeahead(gitRefInput,
+                           ctx.xhrGitRevTypeAheadUrl,
+                           { git_url: null }, function(){});
+
+
   vcsURLInput.focusout(function (){
+    if (!$(this).val())
+      return;
+
     /* If we a layer name specified don't overwrite it or if there isn't a
      * url typed in yet return
      */
-    if (layerNameInput.val() || !$(this).val())
-      return;
-
-    if ($(this).val().search("/")){
+    if (!layerNameInput.val() && $(this).val().search("/")){
       var urlPts = $(this).val().split("/");
+      /* Add a suggestion of the layer name */
       var suggestion = urlPts[urlPts.length-1].replace(".git","");
       layerNameInput.val(suggestion);
     }
+
+    /* Now actually setup the typeahead properly with the git url entered */
+    gitRefInput._typeahead('destroy');
+
+    libtoaster.makeTypeahead(gitRefInput,
+                             ctx.xhrGitRevTypeAheadUrl,
+                             { git_url: $(this).val() },
+                             function(selected){
+                               gitRefInput._typeahead("close");
+                             });
+
   });
 
   function radioDisplay() {
bitbake/lib/toaster/toastergui/static/js/tests/test.js +1 -1
index d7953de..f3bf8d7 100644
@@ -144,7 +144,7 @@ QUnit.test("Make typeaheads", function(assert){
 /* Page init functions */
 
 QUnit.test("Import layer page init", function(assert){
-  assert.throws(importLayerPageInit());
+  assert.throws(importLayerPageInit({ xhrGitRevTypeAheadUrl: "url" }));
 });
 
 QUnit.test("Project page init", function(assert){
bitbake/lib/toaster/toastergui/templates/importlayer.html +4 -1
index bd507b5..afbeb94 100644
@@ -14,6 +14,7 @@
   $(document).ready(function (){
     var ctx = {
       xhrLayerUrl : "{% url 'xhr_layer' project.id %}",
+      xhrGitRevTypeAheadUrl : "{% url 'xhr_gitrevtypeahead' %}",
     };
 
     try {
@@ -112,8 +113,10 @@
           Git revision
           <span class="glyphicon glyphicon-question-sign get-help" title="You can provide a Git branch, a tag or a commit SHA as the revision"></span>
         </label>
-        <input type="text" class="form-control" id="layer-git-ref" required>
+        <span style="display: block">
+        <input type="text" class="form-control" id="layer-git-ref" autocomplete="off" data-minLength="1" data-autocomplete="off" data-provide="typeahead" required>
         <span class="help-inline" style="display:none;" id="invalid-layer-revision-hint"></span>
+        </span>
       </div>
     </fieldset>
 
Signature · 1 line
2.7.4