xref: /aosp_15_r20/external/bazelbuild-rules_cc/tools/migration/legacy_fields_migrator.py (revision eed53cd41c5909d05eedc7ad9720bb158fd93452)
1"""Script migrating legacy CROSSTOOL fields into features.
2
3This script migrates the CROSSTOOL to use only the features to describe C++
4command lines. It is intended to be added as a last step of CROSSTOOL generation
5pipeline. Since it doesn't retain comments, we assume CROSSTOOL owners will want
6to migrate their pipeline manually.
7"""
8
9# Tracking issue: https://github.com/bazelbuild/bazel/issues/5187
10#
11# Since C++ rules team is working on migrating CROSSTOOL from text proto into
12# Starlark, we advise CROSSTOOL owners to wait for the CROSSTOOL -> Starlark
13# migrator before they invest too much time into fixing their pipeline. Tracking
14# issue for the Starlark effort is
15# https://github.com/bazelbuild/bazel/issues/5380.
16
17from absl import app
18from absl import flags
19from google.protobuf import text_format
20from third_party.com.github.bazelbuild.bazel.src.main.protobuf import crosstool_config_pb2
21from tools.migration.legacy_fields_migration_lib import migrate_legacy_fields
22import os
23
24flags.DEFINE_string("input", None, "Input CROSSTOOL file to be migrated")
25flags.DEFINE_string("output", None,
26                    "Output path where to write migrated CROSSTOOL.")
27flags.DEFINE_boolean("inline", None, "Overwrite --input file")
28
29
30def main(unused_argv):
31  crosstool = crosstool_config_pb2.CrosstoolRelease()
32
33  input_filename = flags.FLAGS.input
34  output_filename = flags.FLAGS.output
35  inline = flags.FLAGS.inline
36
37  if not input_filename:
38    raise app.UsageError("ERROR --input unspecified")
39  if not output_filename and not inline:
40    raise app.UsageError("ERROR --output unspecified and --inline not passed")
41  if output_filename and inline:
42    raise app.UsageError("ERROR both --output and --inline passed")
43
44  with open(to_absolute_path(input_filename), "r") as f:
45    input_text = f.read()
46
47  text_format.Merge(input_text, crosstool)
48
49  migrate_legacy_fields(crosstool)
50  output_text = text_format.MessageToString(crosstool)
51
52  resolved_output_filename = to_absolute_path(
53      input_filename if inline else output_filename)
54  with open(resolved_output_filename, "w") as f:
55    f.write(output_text)
56
57def to_absolute_path(path):
58  path = os.path.expanduser(path)
59  if os.path.isabs(path):
60    return path
61  else:
62    if "BUILD_WORKING_DIRECTORY" in os.environ:
63      return os.path.join(os.environ["BUILD_WORKING_DIRECTORY"], path)
64    else:
65      return path
66
67
68if __name__ == "__main__":
69  app.run(main)
70