1#!/usr/bin/env python3 2 3# Copyright 2024 gRPC authors. 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17# Uses trace_flags.yaml to auto-generate code for trace flags in gRPC-core, as 18# well as the trace flag piece of doc/environment_variables.md. 19 20from io import StringIO 21import os 22import subprocess 23 24from absl import app 25from absl import flags 26from mako.lookup import TemplateLookup 27from mako.runtime import Context 28from mako.template import Template 29import yaml 30 31_CHECK = flags.DEFINE_bool( 32 "check", default=False, help="Format and compare output using git diff." 33) 34 35_FORMAT = flags.DEFINE_bool( 36 "format", default=False, help="Format the trace code after generating it." 37) 38 39tmpl_dir_ = TemplateLookup(directories=["tools/codegen/core/templates/"]) 40 41 42def render_source_file(tmpl_name, trace_flags): 43 header_template = tmpl_dir_.get_template(tmpl_name) 44 buf = StringIO() 45 ctx = Context(buf, trace_flags=trace_flags, absl_prefix="") 46 header_template.render_context(ctx) 47 return buf.getvalue() 48 49 50def main(args): 51 with open("src/core/lib/debug/trace_flags.yaml") as f: 52 trace_flags = yaml.safe_load(f.read()) 53 with open("src/core/lib/debug/trace_flags.h", "w") as f: 54 f.write(render_source_file("trace_flags.h.mako", trace_flags)) 55 with open("src/core/lib/debug/trace_flags.cc", "w") as f: 56 f.write(render_source_file("trace_flags.cc.mako", trace_flags)) 57 with open("doc/trace_flags.md", "w") as f: 58 f.write(render_source_file("trace_flags.md.mako", trace_flags)) 59 if _CHECK.value or _FORMAT.value: 60 env = os.environ.copy() 61 env["CHANGED_FILES"] = "src/core/lib/debug/*" 62 env["TEST"] = "" 63 format_result = subprocess.run( 64 ["tools/distrib/clang_format_code.sh"], env=env, capture_output=True 65 ) 66 if format_result.returncode != 0: 67 raise app.Error("Format failed") 68 if _CHECK.value: 69 diff_result = subprocess.run(["git", "diff"], capture_output=True) 70 if len(diff_result.stdout) > 0 or len(diff_result.stderr) > 0: 71 print( 72 "Trace flags need to be generated. Please run tools/codegen/core/gen_trace_flags.py" 73 ) 74 print(diff_result.stdout.decode("utf-8")) 75 raise app.Error("diff found") 76 77 78if __name__ == "__main__": 79 app.run(main) 80