go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/starlark/interpreter/fs_loader.go (about)

     1  // Copyright 2021 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  //go:build go1.16
    16  // +build go1.16
    17  
    18  package interpreter
    19  
    20  import (
    21  	"errors"
    22  	"io/fs"
    23  
    24  	"go.starlark.net/starlark"
    25  )
    26  
    27  // FSLoader returns a loader that loads files from a fs.FS implementation.
    28  func FSLoader(fsys fs.FS) Loader {
    29  	return func(path string) (_ starlark.StringDict, src string, err error) {
    30  		switch body, err := fs.ReadFile(fsys, path); {
    31  		case errors.Is(err, fs.ErrNotExist):
    32  			return nil, "", ErrNoModule
    33  		case err != nil:
    34  			return nil, "", err
    35  		default:
    36  			return nil, string(body), nil
    37  		}
    38  	}
    39  }