kythe.io@v0.0.68-0.20240422202219-7225dbc01741/tools/build_rules/verifier_test/unbundle.py (about) 1 # 2 # Copyright 2016 The Kythe Authors. All rights reserved. 3 # 4 # Licensed under the Apache License, Version 2.0 (the "License"); 5 # you may not use this file except in compliance with the License. 6 # You may obtain a copy of the License at 7 # 8 # http://www.apache.org/licenses/LICENSE-2.0 9 # 10 # Unless required by applicable law or agreed to in writing, software 11 # distributed under the License is distributed on an "AS IS" BASIS, 12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 # See the License for the specific language governing permissions and 14 # limitations under the License. 15 # 16 """Extract a bundled C++ indexer test into the specified directory.""" 17 import argparse 18 import contextlib 19 import errno 20 import os 21 import os.path 22 23 24 class BundleWriter(object): 25 26 def __init__(self, root): 27 self.includes = [] 28 self.root = os.path.join(root, "test_bundle") 29 self.current = None 30 self.open("test.cc") 31 32 def open(self, path): 33 make_dirs(os.path.dirname(os.path.join(self.root, path))) 34 if self.current is not None: 35 self.current.close() 36 self.current = open(os.path.join(self.root, path), "w") 37 38 def add_include(self, path): 39 self.includes.append(path) 40 41 def close(self): 42 self.current.close() 43 self.current = None 44 45 cflagspath = os.path.join(os.path.dirname(self.root), "cflags") 46 with open(cflagspath, "w") as cflags: 47 for path in self.includes: 48 cflags.write("-I") 49 cflags.write(os.path.join(self.root, path)) 50 cflags.write("\n") 51 52 def write(self, line): 53 self.current.write(line) 54 55 56 @contextlib.contextmanager 57 def open_writer(root): 58 writer = BundleWriter(root) 59 try: 60 yield writer 61 finally: 62 writer.close() 63 64 65 def make_dirs(path): 66 try: 67 os.makedirs(path) 68 except OSError as error: 69 # Suppress creation failure for even the leaf directory. 70 if error.errno != errno.EEXIST: 71 raise 72 73 74 def main(): 75 parser = argparse.ArgumentParser() 76 parser.add_argument("input", type=argparse.FileType("r")) 77 parser.add_argument("output_root") 78 79 args = parser.parse_args() 80 with open_writer(args.output_root) as writer: 81 for line in args.input: 82 if line.startswith('#example '): 83 writer.open(line.split(None, 1)[1].strip()) 84 elif line.startswith('#incdir '): 85 writer.add_include(line.split(None, 1)[1].strip()) 86 else: 87 writer.write(line) 88 89 90 if __name__ == "__main__": 91 main()