go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/lucicfg/cli/base/files.go (about)

     1  // Copyright 2020 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  package base
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  
    21  	"go.chromium.org/luci/common/errors"
    22  	"go.starlark.net/starlark"
    23  )
    24  
    25  // ExpandDirectories recursively traverses directories in `paths` discovering
    26  // *.star files in them.
    27  //
    28  // If `paths` is empty, expands `.`.
    29  //
    30  // Returns the overall list of absolute paths to discovered files.
    31  func ExpandDirectories(paths []string) ([]string, error) {
    32  	if len(paths) == 0 {
    33  		paths = []string{"."}
    34  	}
    35  	var files []string
    36  	for _, p := range paths {
    37  		p, err := filepath.Abs(p)
    38  		if err != nil {
    39  			return nil, errors.Annotate(err, "could not absolutize %q", p).Err()
    40  		}
    41  
    42  		switch info, err := os.Stat(p); {
    43  		case err != nil:
    44  			return nil, err
    45  		case !info.IsDir():
    46  			files = append(files, p)
    47  		default:
    48  			err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
    49  				if err == nil && !info.IsDir() && filepath.Ext(info.Name()) == ".star" {
    50  					files = append(files, path)
    51  				}
    52  				return err
    53  			})
    54  			if err != nil {
    55  				return nil, err
    56  			}
    57  		}
    58  	}
    59  	return files, nil
    60  }
    61  
    62  // PathLoader is an interpreter.Loader that loads files using file system paths.
    63  func PathLoader(path string) (starlark.StringDict, string, error) {
    64  	body, err := os.ReadFile(path)
    65  	return nil, string(body), err
    66  }