0
0
mirror of https://github.com/thegeeklab/wp-plugin-go.git synced 2024-10-22 23:30:39 +00:00
wp-plugin-go/file/file.go

57 lines
1.5 KiB
Go
Raw Normal View History

2024-02-09 08:38:23 +00:00
package file
2024-03-11 08:23:17 +00:00
import (
2024-03-11 10:57:11 +00:00
"fmt"
2024-03-11 08:23:17 +00:00
"os"
2024-03-11 10:57:11 +00:00
"path/filepath"
2024-03-11 08:23:17 +00:00
)
2024-02-09 08:38:23 +00:00
// The MSDN docs appear to say that a normal path that is 248 bytes long will work;
// empirically the path must be less then 248 bytes long.
// See https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation
const maxPathLenght = 248
// ReadStringOrFile returns the content of a string or a file if the file exists.
// The returned boolean value indicates whether the specified `input` was a file path or not.
func ReadStringOrFile(input string) (string, bool, error) {
if len(input) >= maxPathLenght {
return input, false, nil
}
// Check if input is a file path
if _, err := os.Stat(input); err != nil && os.IsNotExist(err) {
// No file found => use input as result
return input, false, nil
} else if err != nil {
return "", false, err
}
result, err := os.ReadFile(input)
if err != nil {
return "", true, err
}
return string(result), true, nil
}
2024-03-11 10:57:11 +00:00
// ExpandFileList takes a list of file globs and expands them into a list
// of matching file paths. It returns the expanded file list and any errors
// from glob matching. This allows safely passing user input globs through to
// glob matching.
func ExpandFileList(fileList []string) ([]string, error) {
var result []string
for _, glob := range fileList {
globbed, err := filepath.Glob(glob)
if err != nil {
return result, fmt.Errorf("failed to match %s: %w", glob, err)
}
if globbed != nil {
result = append(result, globbed...)
}
}
return result, nil
}