configure.impl.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # Copyright (c) 2023 Project CHIP Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # This file contains private utilities for use by the `configure` script.
  15. # It is self-contained and depends only on the Python 3 standard library.
  16. import collections
  17. import json
  18. import os
  19. import re
  20. import sys
  21. import urllib.request
  22. import zipfile
  23. def download_and_extract_zip(url, dest_dir, *member_names):
  24. file, *_ = urllib.request.urlretrieve(url)
  25. with zipfile.ZipFile(file) as zip:
  26. for member in zip.infolist():
  27. if member.filename in member_names:
  28. zip.extract(member, dest_dir)
  29. def process_project_args(gn_args_json_file, *params):
  30. processor = ProjectArgProcessor(gn_args_json_file)
  31. processor.process_defaults()
  32. processor.process_env()
  33. processor.process_parameters(params)
  34. for arg, value in processor.args.items():
  35. info(" - %s = %s" % (arg, value))
  36. print("%s = %s" % (arg, value))
  37. class ProjectArgProcessor:
  38. # Prefixes to try when mapping parameters to GN arguments
  39. BOOL_ARG_PREFIXES = ('is_', 'enable_', 'use_', 'chip_', 'chip_enable', 'chip_use_', 'chip_config_')
  40. GENERIC_ARG_PREFIXES = ('chip_', 'chip_config_')
  41. gn_args = {} # GN arg -> type ('s'tring, 'b'ool, 'i'integer, '[' list, '{' struct)
  42. args = collections.OrderedDict() # collected arguments
  43. def __init__(self, gn_args_json_file):
  44. # Parse `gn args --list --json` output and derive arg types from default values
  45. argtype = str.maketrans('"tf0123456789', 'sbbiiiiiiiiii')
  46. with open(gn_args_json_file) as fh:
  47. for arg in json.load(fh):
  48. self.gn_args[arg['name']] = arg['default']['value'][0].translate(argtype)
  49. def process_defaults(self):
  50. self.add_default('custom_toolchain', 'custom')
  51. def process_env(self):
  52. self.add_env_arg('target_cc', 'CC', 'cc')
  53. self.add_env_arg('target_cxx', 'CXX', 'cxx')
  54. self.add_env_arg('target_ar', 'AR', 'ar')
  55. self.add_env_arg('target_cflags', 'CPPFLAGS', list=True)
  56. self.add_env_arg('target_cflags_c', 'CFLAGS', list=True)
  57. self.add_env_arg('target_cflags_cc', 'CXXFLAGS', list=True)
  58. self.add_env_arg('target_cflags_objc', 'OBJCFLAGS', list=True)
  59. self.add_env_arg('target_ldflags', 'LDFLAGS', list=True)
  60. def add_arg(self, arg, value):
  61. # format strings and booleans as JSON, otherwise pass through as is
  62. self.args[arg] = (json.dumps(value) if self.gn_args.get(arg, 's') in 'sb' else value)
  63. def add_default(self, arg, value):
  64. """Add an argument, if supported by the GN build"""
  65. if arg in self.gn_args:
  66. self.add_arg(arg, value)
  67. def add_env_arg(self, arg, envvar, default=None, list=False):
  68. """Add an argument from an environment variable"""
  69. value = os.environ.get(envvar, default)
  70. if not value:
  71. return
  72. if not (type := self.gn_args.get(arg, None)):
  73. info("Warning: Not propagating %s, project has no build arg '%s'" % (envvar, arg))
  74. return
  75. self.args[arg] = json.dumps(value if type != '[' else value.split() if list else [value])
  76. def gn_arg(self, name, prefixes=(), type=None):
  77. """Finds the GN argument corresponding to a parameter name"""
  78. arg = name.translate(str.maketrans('-', '_'))
  79. candidates = [p + arg for p in (('',) + prefixes) if (p + arg) in self.gn_args]
  80. preferred = [c for c in candidates if self.gn_args[c] == type] if type else []
  81. if not (match := next(iter(preferred + candidates), None)):
  82. info("Warning: Project has no build arg '%s'" % arg)
  83. return match
  84. def process_triplet_parameter(self, name, value):
  85. if value is None:
  86. fail("Project option --%s requires an argument" % name)
  87. triplet = value.split('-')
  88. if len(triplet) not in (2, 3, 4):
  89. fail("Project option --%s argument must be a cpu-vendor-os[-abi] triplet" % name)
  90. prefix = 'host_' if name == 'build' else 'target_' # "host" has different meanings in GNU and GN!
  91. self.add_arg(prefix + 'cpu', triplet[0])
  92. self.add_arg(prefix + 'os', triplet[1 if len(triplet) == 2 else 2])
  93. def process_enable_parameter(self, name, value):
  94. if not (arg := self.gn_arg(name[len('enable-'):], self.BOOL_ARG_PREFIXES, 'b')):
  95. return
  96. if self.gn_args[arg] != 'b':
  97. fail("Project build arg '%s' is not a boolean" % arg)
  98. if value != 'no' and value is not None:
  99. fail("Invalid argument for --%s, must be absent or 'no'" % name)
  100. self.add_arg(arg, value is None)
  101. def process_generic_parameter(self, name, value):
  102. if not (arg := self.gn_arg(name, self.GENERIC_ARG_PREFIXES)):
  103. return
  104. if self.gn_args[arg] == 'b':
  105. fail("Project build arg '%s' is a boolean, use --enable-..." % arg)
  106. if value is None:
  107. fail("Project option --%s requires an argument" % name)
  108. self.add_arg(arg, value)
  109. def process_parameter(self, name, value):
  110. if name in ('build', 'host', 'target'):
  111. self.process_triplet_parameter(name, value)
  112. elif name.startswith('enable-'):
  113. self.process_enable_parameter(name, value)
  114. else:
  115. self.process_generic_parameter(name, value)
  116. def process_parameters(self, args):
  117. """Process GNU-style configure command line parameters"""
  118. for arg in args:
  119. if not (m := re.fullmatch(r'--([a-z][a-z0-9-]*)(?:=(.*))?', arg)):
  120. fail("Invalid argument: '%s'" % arg)
  121. self.process_parameter(m.group(1), m.group(2))
  122. def info(message):
  123. print(message, file=sys.stderr)
  124. def fail(message):
  125. info("Error: " + message)
  126. sys.exit(1)
  127. # `configure` invokes the top-level functions in this file by
  128. # passing the function name and arguments on the command line.
  129. [_, func, *args] = sys.argv
  130. globals()[func](*args)