1#! /usr/bin/env python3
2#
3# Copyright (C) 2021 Richard Purdie
4#
5# SPDX-License-Identifier: GPL-2.0-only
6#
7
8import argparse
9import io
10import os
11import sys
12import warnings
13warnings.simplefilter("default")
14
15bindir = os.path.dirname(__file__)
16topdir = os.path.dirname(bindir)
17sys.path[0:0] = [os.path.join(topdir, 'lib')]
18
19import bb.tinfoil
20
21if __name__ == "__main__":
22    parser = argparse.ArgumentParser(description="Bitbake Query Variable")
23    parser.add_argument("variable", help="variable name to query")
24    parser.add_argument("-r", "--recipe", help="Recipe name to query", default=None, required=False)
25    parser.add_argument('-u', '--unexpand', help='Do not expand the value (with --value)', action="store_true")
26    parser.add_argument('-f', '--flag', help='Specify a variable flag to query (with --value)', default=None)
27    parser.add_argument('--value', help='Only report the value, no history and no variable name', action="store_true")
28    parser.add_argument('-q', '--quiet', help='Silence bitbake server logging', action="store_true")
29    parser.add_argument('--ignore-undefined', help='Suppress any errors related to undefined variables', action="store_true")
30    args = parser.parse_args()
31
32    if not args.value:
33        if args.unexpand:
34            sys.exit("--unexpand only makes sense with --value")
35
36        if args.flag:
37            sys.exit("--flag only makes sense with --value")
38
39    quiet = args.quiet or args.value
40    with bb.tinfoil.Tinfoil(tracking=True, setup_logging=not quiet) as tinfoil:
41        if args.recipe:
42            tinfoil.prepare(quiet=3 if quiet else 2)
43            d = tinfoil.parse_recipe(args.recipe)
44        else:
45            tinfoil.prepare(quiet=2, config_only=True)
46            d = tinfoil.config_data
47
48        value = None
49        if args.flag:
50            value = d.getVarFlag(args.variable, args.flag, expand=not args.unexpand)
51            if value is None and not args.ignore_undefined:
52                sys.exit(f"The flag '{args.flag}' is not defined for variable '{args.variable}'")
53        else:
54            value = d.getVar(args.variable, expand=not args.unexpand)
55            if value is None and not args.ignore_undefined:
56                sys.exit(f"The variable '{args.variable}' is not defined")
57        if args.value:
58            print(str(value if value is not None else ""))
59        else:
60            bb.data.emit_var(args.variable, d=d, all=True)
61