1# This Source Code Form is subject to the terms of the Mozilla Public
2# License, v. 2.0. If a copy of the MPL was not distributed with this
3# file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5import re
6
7_JOINED_SYMBOL_RE = re.compile(r"([^(]*)\(([^)]*)\)$")
8
9
10def split_symbol(treeherder_symbol):
11    """Split a symbol expressed as grp(sym) into its two parts.  If no group is
12    given, the returned group is '?'"""
13    groupSymbol = "?"
14    symbol = treeherder_symbol
15    if "(" in symbol:
16        match = _JOINED_SYMBOL_RE.match(symbol)
17        if match:
18            groupSymbol, symbol = match.groups()
19        else:
20            raise Exception(f"`{symbol}` is not a valid treeherder symbol.")
21    return groupSymbol, symbol
22
23
24def join_symbol(group, symbol):
25    """Perform the reverse of split_symbol, combining the given group and
26    symbol.  If the group is '?', then it is omitted."""
27    if group == "?":
28        return symbol
29    return f"{group}({symbol})"
30
31
32def add_suffix(treeherder_symbol, suffix):
33    """Add a suffix to a treeherder symbol that may contain a group."""
34    group, symbol = split_symbol(treeherder_symbol)
35    symbol += str(suffix)
36    return join_symbol(group, symbol)
37
38
39def replace_group(treeherder_symbol, new_group):
40    """Add a suffix to a treeherder symbol that may contain a group."""
41    _, symbol = split_symbol(treeherder_symbol)
42    return join_symbol(new_group, symbol)
43
44
45def inherit_treeherder_from_dep(job, dep_job):
46    """Inherit treeherder defaults from dep_job"""
47    treeherder = job.get("treeherder", {})
48
49    dep_th_platform = (
50        dep_job.task.get("extra", {})
51        .get("treeherder", {})
52        .get("machine", {})
53        .get("platform", "")
54    )
55    dep_th_collection = list(
56        dep_job.task.get("extra", {}).get("treeherder", {}).get("collection", {}).keys()
57    )[0]
58    treeherder.setdefault("platform", f"{dep_th_platform}/{dep_th_collection}")
59    treeherder.setdefault(
60        "tier", dep_job.task.get("extra", {}).get("treeherder", {}).get("tier", 1)
61    )
62    # Does not set symbol
63    treeherder.setdefault("kind", "build")
64    return treeherder
65