summaryrefslogtreecommitdiff
path: root/framework/grouptools.py
blob: fb7e6c207675dab1584ece4c73f993381ff79e66 (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
# coding=utf-8
# Copyright (c) 2014-2016, 2019 Intel Corporation

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Module providing utility functions to work with piglit groups.

Instead of using posixpath (or the generic os.path) for working with tests this
module should be preferred.

Piglit groups look much like posix paths, they are '/' delimited with each
element representing a group, and the final element being the test name. Unlike
posix paths they may not start with a leading '/'.

"""

__all__ = [
    'SEPARATOR',
    'commonprefix',
    'format',
    'from_path',
    'groupname',
    'join',
    'split',
    'splitname',
    'testname',
]

SEPARATOR = '@'


def testname(group):
    """Return the last element of a group name.

    Provided the value 'group1|group2|test1' will provide 'test1', this
    does not enforce any rules that the final element is a test name, and can
    be used to shaved down groups.

    Analogous to os.path.basename

    """
    return splitname(group)[1]


def groupname(group):
    """Return all groups except the last.

    Provided the value 'group1/group2/test1' will provide 'group1/group2', this
    does not enforce any rules that the final element is a test name, and can
    be used to shaved down groups.

    Analogous to os.path.dirname

    """
    return splitname(group)[0]


def splitname(group):
    """Split a group name, Returns tuple "(group, test)"."""
    i = group.rfind(SEPARATOR) + 1
    head, tail = group[:i], group[i:]
    head = head.rstrip(SEPARATOR)

    return head, tail


def commonprefix(args):
    """Given a list of groups, returns the longest common leading component."""
    if len(args) == 1:
        return args[0]
    elif any(e == '' for e in args):
        return ''

    common = []

    for elems in zip(*[split(a) for a in args]):
        iter_ = iter(elems)
        first = next(iter_)
        if all(first == r for r in iter_):
            common.append(first)
        else:
            break

    # Join needs at least one element to join
    if common:
        return join(*common)
    else:
        return ''


def join(first, *args):
    """Join multiple groups together.

    This function is implemented via string concatenation, while most
    pythonistas would use list joining, because it is accepted as better.  I
    wrote a number of implementations and timed them with timeit.  I found for
    small number of joins (2-10) that str concatenation was quite a bit faster,
    at around 100 elements list joining became faster. Since most of piglit's
    use of join is for 2-10 elements I used string concatenation, which is
    coincidentally very similar to the way posixpath.join is implemented.

    """
    # If first happens to be a non-existent value, walk through args until we
    # find a real value and use that.
    args = (a for a in args)
    if not first:
        for group in args:
            if group:
                first = group
                break

    for group in args:
        # Only append things if the group is not empty, otherwise we'll get
        # extra SEPARATORs where we don't want them
        if group:
            if not first.endswith(SEPARATOR):
                first += SEPARATOR
            first += group

    return first


def split(group):
    """Split the group into a list of elements.

    If input is '' return an empty list

    """
    if group == '':
        return []
    return group.split(SEPARATOR)


def from_path(path):
    """Create a group from a path.

    This function takes a path, and creates a group out of it.

    This safely handles both Windows and Unix style paths.

    """
    assert isinstance(path, str), 'Type must be str'

    if '\\' in path:
        path = path.replace('\\', SEPARATOR)
    if '/' in path:
        path = path.replace('/', SEPARATOR)
    if '.' == path:
        return ''
    return path


def format(name):
    """Format an internal name for printing.

    It doesn't matter how the name is stored internally, presenting a
    consistence, clean interface on the command line that doesn't contain any
    ugly or problematic characters is important.

    This replaces SEPARATOR with '/', which is what most devs are used to and
    want to see.

    """
    assert isinstance(name, str)
    return name.replace(SEPARATOR, '/')