summaryrefslogtreecommitdiffstats
path: root/bitbake/lib/toaster/toastergui/templatetags/projecttags.py
blob: 60d5dd0b7c68bc0e8688cf7bb441913085419bc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# BitBake Toaster Implementation
#
# Copyright (C) 2013        Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from datetime import datetime, timedelta
import re
from django import template
from django.utils import timezone
from django.template.defaultfilters import filesizeformat
from orm.models import Target_Installed_Package, Target_Image_File
from orm.models import Build, Target, Task, Layer, Layer_Version

register = template.Library()

@register.simple_tag
def time_difference(start_time, end_time):
    return end_time - start_time

@register.filter(name = 'sectohms')
def sectohms(time):
    try:
        tdsec = int(time)
    except ValueError:
        tdsec = 0
    hours = int(tdsec / 3600)
    return "%02d:%02d:%02d" % (hours, int((tdsec - (hours * 3600))/ 60), int(tdsec) % 60)

@register.assignment_tag
def query(qs, **kwargs):
    """ template tag which allows queryset filtering. Usage:
          {% query books author=author as mybooks %}
          {% for book in mybooks %}
            ...
          {% endfor %}
    """
    return qs.filter(**kwargs)

@register.filter
def divide(value, arg):
    if int(arg) == 0:
        return -1
    return int(value) / int(arg)

@register.filter
def multiply(value, arg):
    return int(value) * int(arg)

@register.assignment_tag
def datecompute(delta, start = timezone.now()):
    return start + timedelta(delta)


@register.filter(name = 'sortcols')
def sortcols(tablecols):
    return sorted(tablecols, key = lambda t: t['name'])

@register.filter
def task_color(task_object, show_green=False):
    """ Return css class depending on Task execution status and execution outcome.
        By default, green is not returned for executed and successful tasks;
        show_green argument should be True to get green color.
    """
    if not task_object.task_executed:
        return 'class=muted'
    elif task_object.outcome == task_object.OUTCOME_FAILED:
        return 'class=error'
    elif task_object.outcome == task_object.OUTCOME_SUCCESS and show_green:
        return 'class=green'
    else:
        return ''

@register.filter
def filtered_icon(options, filter):
    """Returns btn-primary if the filter matches one of the filter options
    """
    for option in options:
        if filter == option[1]:
            return "btn-primary"
    return ""

@register.filter
def filtered_tooltip(options, filter):
    """Returns tooltip for the filter icon if the filter matches one of the filter options
    """
    for option in options:
        if filter == option[1]:
            return "Showing only %s"%option[0]
    return ""

@register.filter
def format_none_and_zero(value):
    """Return empty string if the value is None, zero or Not Applicable
    """
    return "" if (not value) or (value == 0) or (value == "0") or (value == 'Not Applicable') else value

@register.filter
def filtered_filesizeformat(value):
    """Change output from fileformatsize to suppress trailing '.0' and change 'bytes' to 'B'
    """
    return filesizeformat(value).replace("bytes", "B").replace(".0", "")

@register.filter
def filtered_packagespec(value):
    """Strip off empty version and revision"""
    return re.sub(r'(--$)', '', value)

@register.filter
def check_filter_status(options, filter):
    """Check if the active filter is among the available options, and return 'checked'
       if filter is not active.
       Used in FilterDialog to select the first radio button if the filter is not active.
    """
    for option in options:
        if filter == option[1]:
            return ""
    return "checked"

@register.filter
def variable_parent_name(value):
    """ filter extended variable names to the parent name
    """
    value=re.sub('_\$.*', '', value)
    return re.sub('_[a-z].*', '', value)
  
@register.filter
def filter_setin_files(file_list,matchstr):
    """ filter/search the 'set in' file lists. Note
        that this output is not autoescaped to allow
        the <p> marks, but this is safe as the data
        is file paths
    """
   
    # no filters, show last file (if any)
    if matchstr == ":":
        if file_list:
            return file_list[len(file_list)-1].file_name
        else:
            return ''

    search, filter = matchstr.partition(':')[::2]
    htmlstr=""
    # match only filters
    if search == '':
        for i in range(len(file_list)):   
            if file_list[i].file_name.find(filter) >= 0:
                htmlstr += file_list[i].file_name + "<p>"
        return htmlstr
       
    # match only search string, plus always last file
    if filter == "":
        for i in range(len(file_list)-1):   
            if file_list[i].file_name.find(search) >= 0:
                htmlstr += file_list[i].file_name + "<p>"
        htmlstr += file_list[len(file_list)-1].file_name
        return htmlstr
       
    # match filter or search string
    for i in range(len(file_list)):   
        if (file_list[i].file_name.find(filter) >= 0) or (file_list[i].file_name.find(search) >= 0):
            htmlstr += file_list[i].file_name + "<p>"
    return htmlstr


@register.filter
def string_slice(strvar,slicevar):
    """ slice a string with |string_slice:'[first]:[last]'
    """
    first,last= slicevar.partition(':')[::2]
    if first=='':
        return strvar[:int(last)]
    elif last=='':
        return strvar[int(first):]
    else:
        return strvar[int(first):int(last)]

@register.filter
def get_image_extensions( build ):
    """
    This is a simple filter that returns a list (string)
    of extensions of the build-targets-image files. Note
    that each build can have multiple targets and each
    target can yield more than one image file
    """
    targets = Target.objects.filter( build_id = build.id );
    comma = "";
    extensions = "";
    for t in targets:
        if ( not t.is_image ):
            continue;
        tif = Target_Image_File.objects.filter( target_id = t.id );
        for i in tif:
            try:
                ndx = i.file_name.index( "." );
            except ValueError:
                ndx = 0;
            s = i.file_name[ ndx + 1 : ];
            extensions += comma + s;
            comma = ", ";
    return( extensions );