Skip to contentSkip to conversation

clean ups, buildinfohelper fix and delete project patches

PATCH New Michael Wood 1 participant 5 messages Sep 6, 2016

lore
Share & tools
lore
#0 lore raw

cover clean ups, buildinfohelper fix and delete project patches

Couple of clean ups, fix for local layers in buildinfohelper and api and implementation of delete a project.

Michael Wood (4):
toaster: Clean up and convert to rest api project edit and get calls
toaster: move MostRecentBuildsView to its own widget
toaster: project page Implement front end feature to delete project
toaster: buildinfohelper local layer don't construct path using git
info

 bitbake/lib/bb/ui/buildinfohelper.py               |   8 +-
 bitbake/lib/toaster/toastergui/api.py              | 272 +++++++++++++--------
 .../lib/toaster/toastergui/static/js/libtoaster.js |   3 +-
 .../toaster/toastergui/static/js/projectpage.js    | 157 ++----------
 bitbake/lib/toaster/toastergui/templates/base.html |   1 +
 .../toastergui/templates/baseprojectpage.html      |   6 +
 .../lib/toaster/toastergui/templates/project.html  |  27 +-
 bitbake/lib/toaster/toastergui/urls.py             |   7 +-
 bitbake/lib/toaster/toastergui/views.py            | 131 +---------
 bitbake/lib/toaster/toastergui/widgets.py          | 141 +++++++++--
 10 files changed, 343 insertions(+), 410 deletions(-)
Signature · 1 line
2.7.4
#1 lore raw

PATCH 1/4 toaster: Clean up and convert to rest api project edit and get calls

Convert the project xhr calls into proper rest api and port the client side calls to use the new API. Fix all the pyflakes identified issues and clean up unused fields.

Also remove the api and client side code for changing release on the fly as this is no longer supported.

[YOCTO #9519]

---
 bitbake/lib/toaster/toastergui/api.py              | 161 +++++++++++++++++++++
 .../lib/toaster/toastergui/static/js/libtoaster.js |   3 +-
 .../toaster/toastergui/static/js/projectpage.js    | 147 +------------------
 bitbake/lib/toaster/toastergui/templates/base.html |   1 +
 bitbake/lib/toaster/toastergui/urls.py             |   4 +
 bitbake/lib/toaster/toastergui/views.py            | 131 +----------------
 6 files changed, 176 insertions(+), 271 deletions(-)
bitbake/lib/toaster/toastergui/api.py +161 -0
index be18090..8876409 100644
@@ -20,11 +20,13 @@
 
 import re
 import logging
+from collections import Counter
 
 from orm.models import Project, ProjectTarget, Build, Layer_Version
 from orm.models import LayerVersionDependency, LayerSource, ProjectLayer
 from orm.models import Recipe, CustomImageRecipe, CustomImagePackage
 from orm.models import Layer, Target, Package, Package_Dependency
+from orm.models import ProjectVariable
 from bldcontrol.models import BuildRequest
 from bldcontrol import bbcontroller
 
@@ -772,3 +774,162 @@ class XhrCustomRecipePackages(View):
         except CustomImageRecipe.DoesNotExist:
             return error_response("Tried to remove package that wasn't"
                                   " present")
+
+
+class XhrProject(View):
+    """ Create, delete or edit a project
+
+    Entry point: /xhr_project/<project_id>
+    """
+    def post(self, request, *args, **kwargs):
+        """
+          Edit project control
+
+          Args:
+              layerAdd = layer_version_id layer_version_id ...
+              layerDel = layer_version_id layer_version_id ...
+              projectName = new_project_name
+              machineName = new_machine_name
+
+          Returns:
+              {"error": "ok"}
+            or
+              {"error": <error message>}
+        """
+        try:
+            prj = Project.objects.get(pk=kwargs['project_id'])
+        except Project.DoesNotExist:
+            return error_response("No such project")
+
+        # Add layers
+        if 'layerAdd' in request.POST and len(request.POST['layerAdd']) > 0:
+            for layer_version_id in request.POST['layerAdd'].split(','):
+                try:
+                    lv = Layer_Version.objects.get(pk=int(layer_version_id))
+                    ProjectLayer.objects.get_or_create(project=prj,
+                                                       layercommit=lv)
+                except Layer_Version.DoesNotExist:
+                    return error_response("Layer version %s asked to add "
+                                          "doesn't exist" % layer_version_id)
+
+        # Remove layers
+        if 'layerDel' in request.POST and len(request.POST['layerDel']) > 0:
+            layer_version_ids = request.POST['layerDel'].split(',')
+            ProjectLayer.objects.filter(
+                project=prj,
+                layercommit_id__in=layer_version_ids).delete()
+
+        # Project name change
+        if 'projectName' in request.POST:
+            prj.name = request.POST['projectName']
+            prj.save()
+
+        # Machine name change
+        if 'machineName' in request.POST:
+            machinevar = prj.projectvariable_set.get(name="MACHINE")
+            machinevar.value = request.POST['machineName']
+            machinevar.save()
+
+        return JsonResponse({"error": "ok"})
+
+    def get(self, request, *args, **kwargs):
+        """
+        Returns:
+            json object representing the current project
+        or:
+            {"error": <error message>}
+        """
+
+        try:
+            project = Project.objects.get(pk=kwargs['project_id'])
+        except Project.DoesNotExist:
+            return error_response("Project %s does not exist" %
+                                  kwargs['project_id'])
+
+        # Create the frequently built targets list
+
+        freqtargets = Counter(Target.objects.filter(
+            Q(build__project=project),
+            ~Q(build__outcome=Build.IN_PROGRESS)
+        ).order_by("target").values_list("target", flat=True))
+
+        freqtargets = freqtargets.most_common(5)
+
+        # We now have the targets in order of frequency but if there are two
+        # with the same frequency then we need to make sure those are in
+        # alphabetical order without losing the frequency ordering
+
+        tmp = []
+        switch = None
+        for i, freqtartget in enumerate(freqtargets):
+            target, count = freqtartget
+            try:
+                target_next, count_next = freqtargets[i+1]
+                if count == count_next and target > target_next:
+                    switch = target
+                    continue
+            except IndexError:
+                pass
+
+            tmp.append(target)
+
+            if switch:
+                tmp.append(switch)
+                switch = None
+
+        freqtargets = tmp
+
+        layers = []
+        for layer in project.projectlayer_set.all():
+            layers.append({
+                "id": layer.layercommit.pk,
+                "name": layer.layercommit.layer.name,
+                "vcs_url": layer.layercommit.layer.vcs_url,
+                "local_source_dir": layer.layercommit.layer.local_source_dir,
+                "vcs_reference": layer.layercommit.get_vcs_reference(),
+                "url": layer.layercommit.layer.layer_index_url,
+                "layerdetailurl": layer.layercommit.get_detailspage_url(
+                    project.pk),
+                "layersource": layer.layercommit.layer_source
+            })
+
+        data = {
+            "name": project.name,
+            "layers": layers,
+            "freqtargets": freqtargets,
+        }
+
+        if project.release is not None:
+            data['release'] = {
+                "id": project.release.pk,
+                "name": project.release.name,
+                "description": project.release.description
+            }
+
+        try:
+            data["machine"] = {"name":
+                               project.projectvariable_set.get(
+                                   name="MACHINE").value}
+        except ProjectVariable.DoesNotExist:
+            data["machine"] = None
+        try:
+            data["distro"] = project.projectvariable_set.get(
+                name="DISTRO").value
+        except ProjectVariable.DoesNotExist:
+            data["distro"] = "-- not set yet"
+
+        data['error'] = "ok"
+
+        return JsonResponse(data)
+
+    def put(self, request, *args, **kwargs):
+        # TODO create new project api
+        return HttpResponse()
+
+    def delete(self, request, *args, **kwargs):
+        try:
+            Project.objects.get(kwargs['project_id']).delete()
+        except Project.DoesNotExist:
+            return error_response("Project %s does not exist" %
+                                  kwargs['project_id'])
+        return JsonResponse({"error": "ok"})
bitbake/lib/toaster/toastergui/static/js/libtoaster.js +1 -2
index f56affd..b2099a6 100644
@@ -167,7 +167,6 @@ var libtoaster = (function () {
   function _getProjectInfo(url, onsuccess, onfail){
     $.ajax({
         type: "GET",
-        data : { format: "json" },
         url: url,
         headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
         success: function (_data) {
@@ -194,7 +193,7 @@ var libtoaster = (function () {
   function _editCurrentProject(data, onSuccess, onFail){
     $.ajax({
         type: "POST",
-        url: libtoaster.ctx.projectPageUrl + "?format=json",
+        url: libtoaster.ctx.xhrProjectUrl,
         data: data,
         headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
         success: function (data) {
bitbake/lib/toaster/toastergui/static/js/projectpage.js +6 -141

170 lines not on this page · raw message

bitbake/lib/toaster/toastergui/templates/base.html +1 -0
index 58491eb..c1b1417 100644
@@ -44,6 +44,7 @@
         {% if project.id %}
         projectId : {{project.id}},
         projectPageUrl : {% url 'project' project.id as purl %}{{purl|json}},
+        xhrProjectUrl : {% url 'xhr_project' project.id as pxurl %}{{pxurl|json}},
         projectName : {{project.name|json}},
         recipesTypeAheadUrl: {% url 'xhr_recipestypeahead' project.id as paturl%}{{paturl|json}},
         layersTypeAheadUrl: {% url 'xhr_layerstypeahead' project.id as paturl%}{{paturl|json}},
bitbake/lib/toaster/toastergui/urls.py +4 -0
index 9509cd5..1232611 100644
@@ -220,6 +220,10 @@ urlpatterns = patterns('toastergui.views',
             api.XhrBuildRequest.as_view(),
             name='xhr_buildrequest'),
 
+        url(r'xhr_project/(?P<project_id>\d+)$',
+            api.XhrProject.as_view(),
+            name='xhr_project'),
+
         url(r'^mostrecentbuilds$', api.MostRecentBuildsView.as_view(),
             name='most_recent_builds'),
 
bitbake/lib/toaster/toastergui/views.py +3 -128

139 lines not on this page · raw message

Signature · 1 line
2.7.4
#2 lore raw

PATCH 2/4 toaster: move MostRecentBuildsView to its own widget

In reply to Michael Wood

This view is specific to the builds dashboard rather than gernic api so like ToasterTable and ToasterTypeAhead we class it as a widget as it has a single purpose. Also clean up some flake8 identified issues.

Original author of the code moved in this commit is Elliot Smith.

---
 bitbake/lib/toaster/toastergui/api.py     | 108 -----------------------
 bitbake/lib/toaster/toastergui/urls.py    |   3 +-
 bitbake/lib/toaster/toastergui/widgets.py | 141 ++++++++++++++++++++++++++----
 3 files changed, 127 insertions(+), 125 deletions(-)
bitbake/lib/toaster/toastergui/api.py +0 -108
index 8876409..5589118 100644
@@ -33,10 +33,8 @@ from bldcontrol import bbcontroller
 from django.http import HttpResponse, JsonResponse
 from django.views.generic import View
 from django.core.urlresolvers import reverse
-from django.utils import timezone
 from django.db.models import Q, F
 from django.db import Error
-from toastergui.templatetags.projecttags import json, sectohms, get_tasks
 from toastergui.templatetags.projecttags import filtered_filesizeformat
 
 logger = logging.getLogger("toaster")
@@ -227,112 +225,6 @@ class XhrLayer(View):
         })
 
 
-class MostRecentBuildsView(View):
-    def _was_yesterday_or_earlier(self, completed_on):
-        now = timezone.now()
-        delta = now - completed_on
-
-        if delta.days >= 1:
-            return True
-
-        return False
-
-    def get(self, request, *args, **kwargs):
-        """
-        Returns a list of builds in JSON format.
-        """
-        project = None
-
-        project_id = request.GET.get('project_id', None)
-        if project_id:
-            try:
-                project = Project.objects.get(pk=project_id)
-            except:
-                # if project lookup fails, assume no project
-                pass
-
-        recent_build_objs = Build.get_recent(project)
-        recent_builds = []
-
-        for build_obj in recent_build_objs:
-            dashboard_url = reverse('builddashboard', args=(build_obj.pk,))
-            buildtime_url = reverse('buildtime', args=(build_obj.pk,))
-            rebuild_url = \
-                reverse('xhr_buildrequest', args=(build_obj.project.pk,))
-            cancel_url = \
-                reverse('xhr_buildrequest', args=(build_obj.project.pk,))
-
-            build = {}
-            build['id'] = build_obj.pk
-            build['dashboard_url'] = dashboard_url
-
-            buildrequest_id = None
-            if hasattr(build_obj, 'buildrequest'):
-                buildrequest_id = build_obj.buildrequest.pk
-            build['buildrequest_id'] = buildrequest_id
-
-            build['recipes_parsed_percentage'] = \
-                int((build_obj.recipes_parsed /
-                     build_obj.recipes_to_parse) * 100)
-
-            tasks_complete_percentage = 0
-            if build_obj.outcome in (Build.SUCCEEDED, Build.FAILED):
-                tasks_complete_percentage = 100
-            elif build_obj.outcome == Build.IN_PROGRESS:
-                tasks_complete_percentage = build_obj.completeper()
-            build['tasks_complete_percentage'] = tasks_complete_percentage
-
-            build['state'] = build_obj.get_state()
-
-            build['errors'] = build_obj.errors.count()
-            build['dashboard_errors_url'] = dashboard_url + '#errors'
-
-            build['warnings'] = build_obj.warnings.count()
-            build['dashboard_warnings_url'] = dashboard_url + '#warnings'
-
-            build['buildtime'] = sectohms(build_obj.timespent_seconds)
-            build['buildtime_url'] = buildtime_url
-
-            build['rebuild_url'] = rebuild_url
-            build['cancel_url'] = cancel_url
-
-            build['is_default_project_build'] = build_obj.project.is_default
-
-            build['build_targets_json'] = \
-                json(get_tasks(build_obj.target_set.all()))
-
-            # convert completed_on time to user's timezone
-            completed_on = timezone.localtime(build_obj.completed_on)
-
-            completed_on_template = '%H:%M'
-            if self._was_yesterday_or_earlier(completed_on):
-                completed_on_template = '%d/%m/%Y ' + completed_on_template
-            build['completed_on'] = completed_on.strftime(
-                completed_on_template)
-
-            targets = []
-            target_objs = build_obj.get_sorted_target_list()
-            for target_obj in target_objs:
-                if target_obj.task:
-                    targets.append(target_obj.target + ':' + target_obj.task)
-                else:
-                    targets.append(target_obj.target)
-            build['targets'] = ' '.join(targets)
-
-            # abbreviated form of the full target list
-            abbreviated_targets = ''
-            num_targets = len(targets)
-            if num_targets > 0:
-                abbreviated_targets = targets[0]
-            if num_targets > 1:
-                abbreviated_targets += (' +%s' % (num_targets - 1))
-            build['targets_abbreviated'] = abbreviated_targets
-
-            recent_builds.append(build)
-
-        return JsonResponse(recent_builds, safe=False)
-
-
 class XhrCustomRecipe(View):
     """ Create a custom image recipe """
 
bitbake/lib/toaster/toastergui/urls.py +2 -1
index 1232611..0002a5a 100644
@@ -24,6 +24,7 @@ from toastergui import tables
 from toastergui import buildtables
 from toastergui import typeaheads
 from toastergui import api
+from toastergui import widgets
 
 urlpatterns = patterns('toastergui.views',
         # landing page
@@ -224,7 +225,7 @@ urlpatterns = patterns('toastergui.views',
             api.XhrProject.as_view(),
             name='xhr_project'),
 
-        url(r'^mostrecentbuilds$', api.MostRecentBuildsView.as_view(),
+        url(r'^mostrecentbuilds$', widgets.MostRecentBuildsView.as_view(),
             name='most_recent_builds'),
 
           # default redirection
bitbake/lib/toaster/toastergui/widgets.py +125 -16

202 lines not on this page · raw message

Signature · 1 line
2.7.4
#3 lore raw

PATCH 3/4 toaster: project page Implement front end feature to delete project

In reply to Michael Wood

Add confirm modal and api calls to delete a project from the project dashboard.

[YOCTO #6238]

---
 bitbake/lib/toaster/toastergui/api.py              |  7 ++++--
 .../toaster/toastergui/static/js/projectpage.js    | 18 ++++++++++++++-
 .../toastergui/templates/baseprojectpage.html      |  6 +++++
 .../lib/toaster/toastergui/templates/project.html  | 27 +++++++++++-----------
 4 files changed, 41 insertions(+), 17 deletions(-)
bitbake/lib/toaster/toastergui/api.py +5 -2
index 5589118..4fb078b 100644
@@ -820,8 +820,11 @@ class XhrProject(View):
 
     def delete(self, request, *args, **kwargs):
         try:
-            Project.objects.get(kwargs['project_id']).delete()
+            Project.objects.get(pk=kwargs['project_id']).delete()
         except Project.DoesNotExist:
             return error_response("Project %s does not exist" %
                                   kwargs['project_id'])
-        return JsonResponse({"error": "ok"})
+        return JsonResponse({
+            "error": "ok",
+            "gotoUrl": reverse("all-projects", args=[])
+        })
bitbake/lib/toaster/toastergui/static/js/projectpage.js +17 -1
index 3bf3cba..d38389c 100644
@@ -328,7 +328,23 @@ function projectPageInit(ctx) {
 
   $("#delete-project-confirmed").click(function(e){
     e.preventDefault();
-  
+
+    $.ajax({
+        type: 'DELETE',
+        url: libtoaster.ctx.xhrProjectUrl,
+        headers: { 'X-CSRFToken' : $.cookie('csrftoken')},
+        success: function (data) {
+          if (data.error !== "ok") {
+            console.warn(data.error);
+          } else {
+            window.location.replace(data.gotoUrl);
+          }
+        },
+        error: function (data) {
+          console.warn(data);
+          if (onfail) onfail(data);
+        }
+    });
   });
 
 }
bitbake/lib/toaster/toastergui/templates/baseprojectpage.html +6 -0
index b3b6f1c..8427d25 100644
@@ -34,6 +34,12 @@ $(document).ready(function(){
       <li><a href="{% url 'projectlayers' project.id %}">Layers</a></li>
       <li class="nav-header">Extra configuration</li>
       <li><a href="{% url 'projectconf' project.id %}">BitBake variables</a></li>
+
+      <li class="nav-header">Actions</li>
+      <li>
+        <a href="#delete-project-modal" role="button" class="text-danger" data-toggle="modal" data-target="#delete-project-modal">
+          <i class="icon-trash text-danger"></i> Delete project</a>
+      </li>
     </ul>
   </div>
   <div class="col-md-10">
bitbake/lib/toaster/toastergui/templates/project.html +13 -14
index ff9eab7..d932c56 100644
@@ -24,30 +24,29 @@
   });
 </script>
 
-{% comment %}
-<!-- Comment out the ability to change the project release, until we decide what to do this functionality -->
-<div id="change-release-modal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="change-release-modal" aria-hidden="false">
+<div id="delete-project-modal" class="modal fade" tabindex="-1" role="dialog">
   <div class="modal-dialog">
     <div class="modal-content">
-
       <div class="modal-header">
-	<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
-	<h3>Changing Yocto Project release to <span class="proposed-release-change-name"></span></h3>
+        <h4>Are you sure you want to delete this project?</h4>
       </div>
       <div class="modal-body">
-	<p>The following added layers do not exist for <span class="proposed-release-change-name"></span>: </p>
-	<ul id="layers-to-remove-list">
-	</ul>
-	<p>If you change the Yocto Project release to <span class="proposed-release-change-name"></span>, the above layers will be deleted from your added layers.</p>
+        <p>Deleting the <strong>A Toaster project</strong> project will remove forever:</p>
+        <ul>
+          <li>Its configuration information</li>
+          <li>Its imported layers</li>
+          <li>Its custom images</li>
+          <li>All its build information</li>
+        </ul>
       </div>
       <div class="modal-footer">
-	<button id="change-release-and-rm-layers" data-dismiss="modal" type="submit" class="btn btn-primary">Change release and delete layers</button>
-	<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
+        <button type="button" class="btn btn-primary" id="delete-project-confirmed">Delete project</button>
+        <button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button>
       </div>
     </div><!-- /.modal-content -->
   </div><!-- /.modal-dialog -->
-</div><!-- /.modal -->
-{% endcomment %}
+</div>
+
 
 <div class="row" id="project-page" style="display:none">
   <div class="col-md-6">
Signature · 1 line
2.7.4
#4 lore raw

PATCH 4/4 toaster: buildinfohelper local layer don't construct path using git info

In reply to Michael Wood

When the layer is local source don't try and work out the location of the layer by using the git information (getGitCloneDirectory)

[YOCTO #10199]

---
 bitbake/lib/bb/ui/buildinfohelper.py | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
bitbake/lib/bb/ui/buildinfohelper.py +5 -3
index 0f09b5c..6bf8278 100644
@@ -449,7 +449,11 @@ class ORMWrapper(object):
             # note that this is different
             buildrequest = BuildRequest.objects.get(pk = br_id)
             for brl in buildrequest.brlayer_set.all():
-                localdirname = os.path.join(bc.getGitCloneDirectory(brl.giturl, brl.commit), brl.dirpath)
+                if brl.local_source_dir:
+                    localdirname = os.path.join(brl.local_source_dir,
+                                                brl.dirpath)
+                else:
+                    localdirname = os.path.join(bc.getGitCloneDirectory(brl.giturl, brl.commit), brl.dirpath)
                 # we get a relative path, unless running in HEAD mode where the path is absolute
                 if not localdirname.startswith("/"):
                     localdirname = os.path.join(bc.be.sourcedir, localdirname)
@@ -979,8 +983,6 @@ class BuildInfoHelper(object):
     def _get_layer_version_for_path(self, path):
         self._ensure_build()
 
-        assert path.startswith("/")
-
         def _slkey_interactive(layer_version):
             assert isinstance(layer_version, Layer_Version)
             return len(layer_version.local_path)
Signature · 1 line
2.7.4