mirror of
https://github.com/facebook/react-native.git
synced 2026-11-18 20:19:07 +00:00
Add Buck CLI override for feature flag defaults
Summary:
Here, we add a mechanism to override React Native feature flag default values via a Buck command line argument, without modifying source files.
A `genrule` in the featureflags BUCK target always interposes on `ReactNativeFeatureFlagsDefaults.h` before compilation. When `react_native.feature_flag_defaults` is set to a JSON object via `--config`, a Python script rewrites the return values in the matching method bodies. When unset, the header passes through unmodified.
The Python script matches each override against the full method signature shape (`<returnType> <flagName>() override { ... return <value>; }`) with lenient whitespace, and fails the build if any requested flag name is not found in the header.
Usage:
```
buck2 build --config 'react_native.feature_flag_defaults={"enableViewCulling":true}' //target
buck2 build --config 'react_native.feature_flag_defaults={"enableViewCulling":true,"preparedTextCacheSize":500}' //target
```
This modifies defaults only — app-level providers still take priority.
Changelog: [Internal]
Reviewed By: robhogan
Differential Revision: D101484355
fbshipit-source-id: 870b630642be4965fc18490e74487bdc0c4d221d
This commit is contained in:
1 parent
5042e58ca2
commit
fed907bf52
2 files changed
+139
No files matched your search
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env fbpython
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
#
|
||||
# This source code is licensed under the MIT license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
# pyre-strict
|
||||
|
||||
"""Rewrite default return values in ReactNativeFeatureFlagsDefaults.h.
|
||||
|
||||
Reads the header from --input, writes the transformed header to stdout.
|
||||
Overrides are passed as a JSON object via --overrides.
|
||||
Fails with a non-zero exit code if any requested flag is not found.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def cxx_literal(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, (int, float)):
|
||||
s = str(value)
|
||||
if isinstance(value, int) or "." not in s:
|
||||
s += ".0"
|
||||
return s
|
||||
raise ValueError(f"Unsupported value type {type(value).__name__} for override")
|
||||
|
||||
|
||||
def rewrite(source: bytes, overrides: dict[str, object]) -> bytes:
|
||||
text = source.decode("utf-8")
|
||||
for name, value in overrides.items():
|
||||
cxx_type = "bool" if isinstance(value, bool) else "double"
|
||||
pattern = rf"""
|
||||
( # group 1: everything up to the value
|
||||
{cxx_type} \s+ # return type
|
||||
{re.escape(name)} # method name
|
||||
\s* \( \s* \) # parameter list
|
||||
\s+ override # override specifier
|
||||
\s* \{{ # opening brace
|
||||
[^}}]*? # body before the return (non-greedy, no nested braces)
|
||||
return \s+ # return keyword
|
||||
)
|
||||
[^;]+ # the value to replace
|
||||
( \s* ; ) # group 2: semicolon
|
||||
"""
|
||||
text, n = re.subn(
|
||||
pattern,
|
||||
rf"\g<1>{cxx_literal(value)}\2",
|
||||
text,
|
||||
count=1,
|
||||
flags=re.DOTALL | re.VERBOSE,
|
||||
)
|
||||
if n != 1:
|
||||
raise ValueError(f"{name} not matched")
|
||||
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--overrides", default="{}")
|
||||
parser.add_argument("--input", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
overrides: dict[str, object] = json.loads(args.overrides)
|
||||
with open(args.input, "rb") as f:
|
||||
source = f.read()
|
||||
|
||||
sys.stdout.buffer.write(rewrite(source, overrides))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
#
|
||||
# This source code is licensed under the MIT license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
# pyre-strict
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
|
||||
from rewrite_feature_flag_defaults import cxx_literal, rewrite
|
||||
|
||||
|
||||
def _load_header() -> bytes:
|
||||
with open(os.environ["HEADER_PATH"], "rb") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
class RewriteFeatureFlagDefaultsTest(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.source = _load_header()
|
||||
|
||||
def test_empty_overrides_is_passthrough(self) -> None:
|
||||
self.assertEqual(rewrite(self.source, {}), self.source)
|
||||
|
||||
def test_override_bool_to_true(self) -> None:
|
||||
result = rewrite(self.source, {"commonTestFlag": True})
|
||||
start, end = self._method_body_range(result, "commonTestFlag")
|
||||
self.assertIn(b"return true;", result[start:end])
|
||||
|
||||
def test_override_bool_to_false(self) -> None:
|
||||
result = rewrite(self.source, {"commonTestFlag": False})
|
||||
start, end = self._method_body_range(result, "commonTestFlag")
|
||||
self.assertIn(b"return false;", result[start:end])
|
||||
|
||||
def test_cxx_literal_int_produces_double(self) -> None:
|
||||
self.assertEqual(cxx_literal(42), "42.0")
|
||||
|
||||
def test_cxx_literal_float(self) -> None:
|
||||
self.assertEqual(cxx_literal(3.14), "3.14")
|
||||
|
||||
def test_unmatched_flag_raises(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
rewrite(self.source, {"bogusFlag": True})
|
||||
|
||||
def test_only_target_method_body_changes(self) -> None:
|
||||
result = rewrite(self.source, {"commonTestFlag": True})
|
||||
src_start, src_end = self._method_body_range(self.source, "commonTestFlag")
|
||||
res_start, res_end = self._method_body_range(result, "commonTestFlag")
|
||||
self.assertEqual(self.source[:src_start], result[:res_start])
|
||||
self.assertEqual(self.source[src_end:], result[res_end:])
|
||||
|
||||
def _method_body_range(self, source: bytes, name: str) -> tuple[int, int]:
|
||||
idx = source.find(name.encode())
|
||||
self.assertNotEqual(idx, -1, f"{name} not found in output")
|
||||
open_brace = source.find(b"{", idx)
|
||||
close_brace = source.find(b"}", open_brace)
|
||||
return (open_brace, close_brace + 1)
|
||||
Reference in new issue
Block a user