|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (C) 2019-2024 Intel Corporation |
| 3 | +# SPDX-License-Identifier: BSD-3-Clause |
| 4 | + |
| 5 | +import argparse |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import sys |
| 9 | + |
| 10 | +from codebasin import CodeBase, config, finder, report, util |
| 11 | + |
| 12 | +# TODO: Refactor to avoid imports from __main__ |
| 13 | +from codebasin.__main__ import Formatter, _help_string, version |
| 14 | + |
| 15 | +log = logging.getLogger("codebasin") |
| 16 | + |
| 17 | + |
| 18 | +def _build_parser() -> argparse.ArgumentParser: |
| 19 | + """ |
| 20 | + Build argument parser. |
| 21 | + """ |
| 22 | + parser = argparse.ArgumentParser( |
| 23 | + description="CBI Tree Tool " + version, |
| 24 | + formatter_class=argparse.RawTextHelpFormatter, |
| 25 | + add_help=False, |
| 26 | + ) |
| 27 | + parser.add_argument( |
| 28 | + "-h", |
| 29 | + "--help", |
| 30 | + action="help", |
| 31 | + help=_help_string("Display help message and exit."), |
| 32 | + ) |
| 33 | + parser.add_argument( |
| 34 | + "--version", |
| 35 | + action="version", |
| 36 | + version=f"CBI Coverage Tool {version}", |
| 37 | + help=_help_string("Display version information and exit."), |
| 38 | + ) |
| 39 | + parser.add_argument( |
| 40 | + "-x", |
| 41 | + "--exclude", |
| 42 | + dest="excludes", |
| 43 | + metavar="<pattern>", |
| 44 | + action="append", |
| 45 | + default=[], |
| 46 | + help=_help_string( |
| 47 | + "Exclude files matching this pattern from the code base.", |
| 48 | + "May be specified multiple times.", |
| 49 | + is_long=True, |
| 50 | + ), |
| 51 | + ) |
| 52 | + parser.add_argument( |
| 53 | + "-p", |
| 54 | + "--platform", |
| 55 | + dest="platforms", |
| 56 | + metavar="<platform>", |
| 57 | + action="append", |
| 58 | + default=[], |
| 59 | + help=_help_string( |
| 60 | + "Include the specified platform in the analysis.", |
| 61 | + "May be specified multiple times.", |
| 62 | + "If not specified, all platforms will be included.", |
| 63 | + is_long=True, |
| 64 | + ), |
| 65 | + ) |
| 66 | + parser.add_argument( |
| 67 | + "--prune", |
| 68 | + dest="prune", |
| 69 | + action="store_true", |
| 70 | + help=_help_string( |
| 71 | + "Prune unused files from the tree.", |
| 72 | + ), |
| 73 | + ) |
| 74 | + parser.add_argument( |
| 75 | + "-L", |
| 76 | + "--levels", |
| 77 | + dest="levels", |
| 78 | + metavar="<level>", |
| 79 | + type=int, |
| 80 | + help=_help_string( |
| 81 | + "Print only the specified number of levels.", |
| 82 | + is_long=True, |
| 83 | + is_last=True, |
| 84 | + ), |
| 85 | + ) |
| 86 | + |
| 87 | + parser.add_argument( |
| 88 | + "analysis_file", |
| 89 | + metavar="<analysis-file>", |
| 90 | + help=_help_string( |
| 91 | + "TOML file describing the analysis to be performed, " |
| 92 | + + "including the codebase and platform descriptions.", |
| 93 | + is_last=True, |
| 94 | + ), |
| 95 | + ) |
| 96 | + |
| 97 | + return parser |
| 98 | + |
| 99 | + |
| 100 | +def _tree(args: argparse.Namespace): |
| 101 | + # Refuse to print a tree with no levels, consistent with tree utility. |
| 102 | + if args.levels is not None and args.levels <= 0: |
| 103 | + raise ValueError("Number of levels must be greater than 0.") |
| 104 | + |
| 105 | + # TODO: Refactor this to avoid duplication in __main__ |
| 106 | + # Determine the root directory based on where codebasin is run. |
| 107 | + rootdir = os.path.abspath(os.getcwd()) |
| 108 | + |
| 109 | + # Set up a default configuration object. |
| 110 | + configuration = {} |
| 111 | + |
| 112 | + # Load the analysis file if it exists. |
| 113 | + if args.analysis_file is not None: |
| 114 | + path = os.path.abspath(args.analysis_file) |
| 115 | + if os.path.exists(path): |
| 116 | + if not os.path.splitext(path)[1] == ".toml": |
| 117 | + raise RuntimeError(f"Analysis file {path} must end in .toml.") |
| 118 | + |
| 119 | + with open(path, "rb") as f: |
| 120 | + analysis_toml = util._load_toml(f, "analysis") |
| 121 | + |
| 122 | + if "codebase" in analysis_toml: |
| 123 | + if "exclude" in analysis_toml["codebase"]: |
| 124 | + args.excludes += analysis_toml["codebase"]["exclude"] |
| 125 | + |
| 126 | + for name in args.platforms: |
| 127 | + if name not in analysis_toml["platform"].keys(): |
| 128 | + raise KeyError( |
| 129 | + f"Platform {name} requested on the command line " |
| 130 | + + "does not exist in the configuration file.", |
| 131 | + ) |
| 132 | + |
| 133 | + cmd_platforms = args.platforms.copy() |
| 134 | + for name in analysis_toml["platform"].keys(): |
| 135 | + if cmd_platforms and name not in cmd_platforms: |
| 136 | + continue |
| 137 | + if "commands" not in analysis_toml["platform"][name]: |
| 138 | + raise ValueError(f"Missing 'commands' for platform {name}") |
| 139 | + p = analysis_toml["platform"][name]["commands"] |
| 140 | + db = config.load_database(p, rootdir) |
| 141 | + args.platforms.append(name) |
| 142 | + configuration.update({name: db}) |
| 143 | + |
| 144 | + # Construct a codebase object associated with the root directory. |
| 145 | + codebase = CodeBase(rootdir, exclude_patterns=args.excludes) |
| 146 | + |
| 147 | + # Parse the source tree, and determine source line associations. |
| 148 | + # The trees and associations are housed in state. |
| 149 | + state = finder.find( |
| 150 | + rootdir, |
| 151 | + codebase, |
| 152 | + configuration, |
| 153 | + show_progress=True, |
| 154 | + ) |
| 155 | + |
| 156 | + # Print the file tree. |
| 157 | + report.files(codebase, state, prune=args.prune, levels=args.levels) |
| 158 | + sys.exit(0) |
| 159 | + |
| 160 | + |
| 161 | +def cli(argv: list[str]) -> int: |
| 162 | + parser = _build_parser() |
| 163 | + args = parser.parse_args(argv) |
| 164 | + |
| 165 | + # Configure logging such that: |
| 166 | + # - Only errors are written to the terminal |
| 167 | + log.setLevel(logging.DEBUG) |
| 168 | + |
| 169 | + stderr_handler = logging.StreamHandler(sys.stderr) |
| 170 | + stderr_handler.setLevel(logging.ERROR) |
| 171 | + stderr_handler.setFormatter(Formatter(colors=sys.stderr.isatty())) |
| 172 | + log.addHandler(stderr_handler) |
| 173 | + |
| 174 | + return _tree(args) |
| 175 | + |
| 176 | + |
| 177 | +def main(): |
| 178 | + try: |
| 179 | + cli(sys.argv[1:]) |
| 180 | + except Exception as e: |
| 181 | + log.error(str(e)) |
| 182 | + sys.exit(1) |
| 183 | + |
| 184 | + |
| 185 | +if __name__ == "__main__": |
| 186 | + sys.argv[0] = "codebasin.tree" |
| 187 | + main() |
0 commit comments