Files
leleka/scripts/dev/funnel_env_reads.py

89 lines
3.8 KiB
Python

"""Route every `std::env::var` / `var_os` read of a crate's production code through one `settings` module of that crate
(STRA-338 debt (b), `env-read` ratchet). The read itself, its parsing and its place in the code do not change; the crate gets
`src/settings.rs` with two inline functions that are the only readers of the process environment, so that a later step can
replace them by a parsed `Settings` value without touching the call sites again.
Usage: python scripts/dev/funnel_env_reads.py CRATE_DIR [--dry-run]
Test files and the code after the first `#[cfg(test)] mod` are not touched. Offline refactoring aid; not part of the product.
"""
import pathlib
import re
import sys
SETTINGS = '''//! The only place of this crate that reads the process environment (`env-read` ratchet of `architecture.json`).
//! The reads keep their call sites and their parsing; a later step replaces these functions by a parsed settings value.
use std::env::{self, VarError};
use std::ffi::{OsStr, OsString};
/// `std::env::var`: the text of an environment variable.
#[inline]
pub(crate) fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
env::var(key)
}
/// `std::env::var_os`: an environment variable that may not be valid text.
#[inline]
pub(crate) fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
env::var_os(key)
}
'''
READ = re.compile(r"(?<![A-Za-z0-9_:])(?:std::)?env::(var|var_os)\(")
TEST_MOD = re.compile(r"(?m)^#\[cfg\(test\)\]\s*\n\s*mod\s")
def is_test_file(path, src):
parts = path.relative_to(src).parts
return path.name == "tests.rs" or path.name.endswith("_tests.rs") or "tests" in parts[:-1]
def main():
crate = pathlib.Path(sys.argv[1]).resolve()
dry = "--dry-run" in sys.argv
src = crate / "src"
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from archcheck import measure
test_files = measure.test_only_modules(src)
existing = src / "settings.rs"
if existing.exists() and existing.read_text(encoding="utf-8") != SETTINGS:
raise SystemExit(f"{existing} exists already: merge by hand")
touched = 0
for path in sorted(src.rglob("*.rs")):
if path.name == "settings.rs" and path.parent == src:
continue
if is_test_file(path, src) or measure._under_test_module(path, test_files):
continue
text = path.read_text(encoding="utf-8")
cut = TEST_MOD.search(text)
head, tail = (text[: cut.start()], text[cut.start() :]) if cut else (text, "")
new_head, n = READ.subn(lambda m: f"crate::settings::{m.group(1)}(", head)
if not n:
continue
# `use std::env;` stays only while something else of `env` is used
if not re.search(r"(?<![A-Za-z0-9_:])env::", new_head + tail):
new_head = re.sub(r"(?m)^use std::env;\n", "", new_head)
print(f" {path.relative_to(crate).as_posix()}: {n}")
touched += n
if not dry:
with open(path, "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(new_head + tail)
if touched and not dry:
with open(src / "settings.rs", "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(SETTINGS)
entry = src / "lib.rs"
text = entry.read_text(encoding="utf-8")
if not re.search(r"(?m)^mod settings;", text):
# after the last plain `mod x;` line of the crate root, which keeps the module list in one place
lines = text.split(chr(10))
last = max(i for i, ln in enumerate(lines) if re.match(r"^(?:pub(?:\([^)]*\))? )?mod [a-z_0-9]+;$", ln))
lines.insert(last + 1, "mod settings;")
with open(entry, "w", encoding="utf-8", newline=chr(10)) as handle:
handle.write(chr(10).join(lines))
print(f"{touched} reads routed through crate::settings")
if __name__ == "__main__":
main()