xref: /aosp_15_r20/external/executorch/build/buck_util.py (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1#!/usr/bin/env python3
2# Copyright (c) Meta Platforms, Inc. and affiliates.
3# All rights reserved.
4#
5# This source code is licensed under the BSD-style license found in the
6# LICENSE file in the root directory of this source tree.
7
8import os
9import subprocess
10import sys
11
12from typing import Optional, Sequence
13
14
15# Run buck2 from the same directory (and thus repo) as this script.
16BUCK_CWD: str = os.path.dirname(os.path.realpath(__file__))
17
18
19class Buck2Runner:
20    def __init__(self, tool_path: str) -> None:
21        self._path = tool_path
22
23    def run(self, args: Sequence[str]) -> list[str]:
24        """Runs buck2 with the given args and returns its stdout as a sequence of lines."""
25        try:
26            cp: subprocess.CompletedProcess = subprocess.run(
27                [self._path] + args, capture_output=True, cwd=BUCK_CWD, check=True
28            )
29            return [line.strip().decode("utf-8") for line in cp.stdout.splitlines()]
30        except subprocess.CalledProcessError as ex:
31            raise RuntimeError(ex.stderr.decode("utf-8")) from ex
32
33
34def get_buck2_version(path: str) -> Optional[str]:
35    try:
36        runner = Buck2Runner(path)
37        output = runner.run(["--version"])
38
39        # Example output:
40        # buck2 38f7c508bf1b87bcdc816bf56d1b9f2d2411c6be <build-id>
41        #
42        # We want the second value.
43
44        return output[0].split()[1]
45
46    except Exception as e:
47        print(f"Failed to retrieve buck2 version: {e}.", file=sys.stderr)
48        return None
49