go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucicfg/starlark/stdlib/internal/io.star (about) 1 # Copyright 2019 The LUCI Authors. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """API for reading files.""" 16 17 def _read_file(path): 18 """Reads a file and returns its contents as a string. 19 20 Useful for rules that accept large chunks of free form text. By using 21 `io.read_file` such text can be kept in a separate file. 22 23 Args: 24 path: either a path relative to the currently executing Starlark script, 25 or (if starts with `//`) an absolute path within the currently executing 26 package. If it is a relative path, it must point somewhere inside the 27 current package directory. Required. 28 29 Returns: 30 The contents of the file as a string. Fails if there's no such file, it 31 can't be read, or it is outside of the current package directory. 32 """ 33 return __native__.read_file(path) 34 35 def _read_proto(ctor, path, encoding = None): 36 """Reads a serialized proto message from a file, deserializes and returns it. 37 38 Args: 39 ctor: a constructor function that defines the message type. Required. 40 path: either a path relative to the currently executing Starlark script, 41 or (if starts with `//`) an absolute path within the currently executing 42 package. If it is a relative path, it must point somewhere inside the 43 current package directory. Required. 44 encoding: either `jsonpb` or `textpb` or `auto` to detect based on the 45 file extension. Default is `auto`. 46 47 Returns: 48 Deserialized proto message constructed via `ctor`. 49 """ 50 if encoding == None or encoding == "auto": 51 ext = path[path.rfind(".") + 1:].lower() 52 encoding = "jsonpb" if ext in ["json", "jsonpb"] else "textpb" 53 if encoding == "jsonpb": 54 return proto.from_jsonpb(ctor, _read_file(path)) 55 if encoding == "textpb": 56 return proto.from_textpb(ctor, _read_file(path)) 57 fail("unknown proto encoding %r" % (encoding,)) 58 59 io = struct( 60 read_file = _read_file, 61 read_proto = _read_proto, 62 )