xref: /aosp_15_r20/external/bazelbuild-rules_cc/tools/migration/convert_crosstool_to_starlark.go (revision eed53cd41c5909d05eedc7ad9720bb158fd93452)
1/*
2The convert_crosstool_to_starlark script takes in a CROSSTOOL file and
3generates a Starlark rule.
4
5See https://github.com/bazelbuild/bazel/issues/5380
6
7Example usage:
8bazel run \
9@rules_cc//tools/migration:convert_crosstool_to_starlark -- \
10--crosstool=/path/to/CROSSTOOL \
11--output_location=/path/to/cc_config.bzl
12*/
13package main
14
15import (
16	"flag"
17	"fmt"
18	"io/ioutil"
19	"os"
20	"os/user"
21	"path"
22	"strings"
23
24	// Google internal base/go package, commented out by copybara
25	"log"
26	crosstoolpb "third_party/com/github/bazelbuild/bazel/src/main/protobuf/crosstool_config_go_proto"
27	"github.com/golang/protobuf/proto"
28
29	"tools/migration/crosstooltostarlarklib"
30)
31
32var (
33	crosstoolLocation = flag.String(
34		"crosstool", "", "Location of the CROSSTOOL file")
35	outputLocation = flag.String(
36		"output_location", "", "Location of the output .bzl file")
37)
38
39func toAbsolutePath(pathString string) (string, error) {
40	usr, err := user.Current()
41	if err != nil {
42		return "", err
43	}
44	homeDir := usr.HomeDir
45
46	if strings.HasPrefix(pathString, "~") {
47		return path.Join(homeDir, pathString[1:]), nil
48	}
49
50	if path.IsAbs(pathString) {
51		return pathString, nil
52	}
53
54	workingDirectory := os.Getenv("BUILD_WORKING_DIRECTORY")
55	return path.Join(workingDirectory, pathString), nil
56}
57
58func main() {
59	flag.Parse()
60
61	if *crosstoolLocation == "" {
62		log.Fatalf("Missing mandatory argument 'crosstool'")
63	}
64	crosstoolPath, err := toAbsolutePath(*crosstoolLocation)
65	if err != nil {
66		log.Fatalf("Error while resolving CROSSTOOL location:", err)
67	}
68
69	if *outputLocation == "" {
70		log.Fatalf("Missing mandatory argument 'output_location'")
71	}
72	outputPath, err := toAbsolutePath(*outputLocation)
73	if err != nil {
74		log.Fatalf("Error resolving output location:", err)
75	}
76
77	in, err := ioutil.ReadFile(crosstoolPath)
78	if err != nil {
79		log.Fatalf("Error reading CROSSTOOL file:", err)
80	}
81	crosstool := &crosstoolpb.CrosstoolRelease{}
82	if err := proto.UnmarshalText(string(in), crosstool); err != nil {
83		log.Fatalf("Failed to parse CROSSTOOL:", err)
84	}
85
86	file, err := os.Create(outputPath)
87	if err != nil {
88		log.Fatalf("Error creating output file:", err)
89	}
90	defer file.Close()
91
92	rule, err := crosstooltostarlarklib.Transform(crosstool)
93	if err != nil {
94		log.Fatalf("Error converting CROSSTOOL to a Starlark rule:", err)
95	}
96
97	if _, err := file.WriteString(rule); err != nil {
98		log.Fatalf("Error converting CROSSTOOL to a Starlark rule:", err)
99	}
100	fmt.Println("Success!")
101}
102