48 lines
866 B
Go
48 lines
866 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"io/fs"
|
||
|
"os"
|
||
|
"slices"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
func envOr(name string, fallback func() string) string {
|
||
|
if v := os.Getenv(name); v != "" {
|
||
|
return v
|
||
|
}
|
||
|
return fallback()
|
||
|
}
|
||
|
|
||
|
func firstExistingDir(paths ...string) (string, error) {
|
||
|
var errs []error
|
||
|
for _, path := range paths {
|
||
|
stat, err := os.Stat(path)
|
||
|
switch {
|
||
|
case errors.Is(err, fs.ErrExist):
|
||
|
continue
|
||
|
case err != nil:
|
||
|
errs = append(
|
||
|
errs, fmt.Errorf("checking if path %q exists: %w", path, err),
|
||
|
)
|
||
|
case !stat.IsDir():
|
||
|
errs = append(
|
||
|
errs, fmt.Errorf("path %q exists but is not a directory", path),
|
||
|
)
|
||
|
default:
|
||
|
return path, nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
err := fmt.Errorf(
|
||
|
"no directory found at any of the following paths: %s",
|
||
|
strings.Join(paths, ", "),
|
||
|
)
|
||
|
if len(errs) > 0 {
|
||
|
err = errors.Join(slices.Insert(errs, 0, err)...)
|
||
|
}
|
||
|
return "", err
|
||
|
}
|