80 lines
1.9 KiB
Go
80 lines
1.9 KiB
Go
// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com).
|
|
// All rights reserved.
|
|
|
|
// import-utils.go
|
|
package expr
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func checkStringParamExpected(funcName string, paramValue any, paramPos int) (err error) {
|
|
if !(IsString(paramValue) /*|| isList(paramValue)*/) {
|
|
err = fmt.Errorf("%s(): param nr %d has wrong type %s, string expected", funcName, paramPos+1, typeName(paramValue))
|
|
}
|
|
return
|
|
}
|
|
|
|
func addEnvImportDirs(dirList []string) []string {
|
|
if dirSpec, exists := os.LookupEnv(ENV_EXPR_PATH); exists {
|
|
dirs := strings.Split(dirSpec, ":")
|
|
if dirList == nil {
|
|
dirList = dirs
|
|
} else {
|
|
dirList = append(dirList, dirs...)
|
|
}
|
|
}
|
|
return dirList
|
|
}
|
|
|
|
func addPresetDirs(ctx ExprContext, ctrlKey string, dirList []string) []string {
|
|
if dirSpec, exists := getControlString(ctx, ctrlKey); exists {
|
|
dirs := strings.Split(dirSpec, ":")
|
|
if dirList == nil {
|
|
dirList = dirs
|
|
} else {
|
|
dirList = append(dirList, dirs...)
|
|
}
|
|
}
|
|
return dirList
|
|
}
|
|
|
|
func isFile(filePath string) bool {
|
|
info, err := os.Stat(filePath)
|
|
return (err == nil || errors.Is(err, os.ErrExist)) && info.Mode().IsRegular()
|
|
}
|
|
|
|
func searchAmongPath(filename string, dirList []string) (filePath string) {
|
|
for _, dir := range dirList {
|
|
if fullPath := path.Join(dir, filename); isFile(fullPath) {
|
|
filePath = fullPath
|
|
break
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func isPathRelative(filePath string) bool {
|
|
unixPath := filepath.ToSlash(filePath)
|
|
return strings.HasPrefix(unixPath, "./") || strings.HasPrefix(unixPath, "../")
|
|
}
|
|
|
|
func makeFilepath(filename string, dirList []string) (filePath string, err error) {
|
|
if path.IsAbs(filename) || isPathRelative(filename) {
|
|
if isFile(filename) {
|
|
filePath = filename
|
|
}
|
|
} else {
|
|
filePath = searchAmongPath(filename, dirList)
|
|
}
|
|
if len(filePath) == 0 {
|
|
err = fmt.Errorf("source file %q not found", filename)
|
|
}
|
|
return
|
|
}
|