Path: blob/trunk/dotnet/private/generate_resources_tool.py
4502 views
#!/usr/bin/env python31"""Generate C# ResourceUtilities partial class with embedded JS resources.23Usage:4generate_resources_tool.py --output path/to/ResourceUtilities.g.cs \5--input Ident1=path/to/file1.js \6--input Ident2=path/to/file2.js ...78Each identifier becomes a const string in ResourceUtilities class.9The content is emitted as a C# raw string literal using 5-quotes.1011Todo:12It would be nice to convert this small single-file utility to .NET10/C#,13so it would work like `dotnet run generate_resources.cs -- <args>`.14Meaning .NET developers can easily support it.15"""1617import argparse18import os19import sys202122def parse_args(argv: list[str]) -> argparse.Namespace:23parser = argparse.ArgumentParser()24parser.add_argument("--output", required=True)25parser.add_argument("--input", action="append", default=[], help="IDENT=path")26return parser.parse_args(argv)272829def parse_input_spec(spec: str) -> tuple[str, str]:30if "=" not in spec:31raise ValueError(f"Invalid --input value, expected IDENT=path, got: {spec}")32ident, path = spec.split("=", 1)33ident = ident.strip()34path = path.strip()35if not ident:36raise ValueError(f"Empty identifier in --input value: {spec}")37if not path:38raise ValueError(f"Empty path in --input value: {spec}")39return ident, path404142def generate(output: str, inputs: list[tuple[str, str]]) -> None:43props: list[str] = []44for prop_name, path in inputs:45with open(path, encoding="utf-8") as f:46content = f.read()47# Use a C# raw string literal with five quotes. For a valid raw48# literal, the content must start on a new line and the closing49# quotes must be on their own line as well. We assume the content50# does not contain a sequence of five consecutive double quotes.51#52# Resulting C# will look like:53# """""54# <content>55# """""56literal = '"""""\n' + content + '\n"""""'57props.append(f" internal const string {prop_name} = {literal};")5859lines: list[str] = []60lines.append("// <auto-generated />")61lines.append("namespace OpenQA.Selenium.Internal;")62lines.append("")63lines.append("internal static partial class ResourceUtilities")64lines.append("{")65for p in props:66lines.append(p)67lines.append("}")68lines.append("")6970os.makedirs(os.path.dirname(output), exist_ok=True)71with open(output, "w", encoding="utf-8", newline="\n") as f:72f.write("\n".join(lines))737475def main(argv: list[str]) -> int:76args = parse_args(argv)77inputs: list[tuple[str, str]] = []78for spec in args.input:79ident, path = parse_input_spec(spec)80inputs.append((ident, path))81generate(args.output, inputs)82return 0838485if __name__ == "__main__":86raise SystemExit(main(sys.argv[1:]))878889