Files

87 lines
1.7 KiB
Go

package transportcfg
import (
"encoding/base64"
"os"
"path/filepath"
"strings"
)
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, perm); err != nil {
return err
}
return os.Rename(tmp, path)
}
func ReadJSONFiles(rootDir string) ([][]byte, error) {
entries, err := os.ReadDir(rootDir)
if err != nil {
if os.IsNotExist(err) {
return [][]byte{}, nil
}
return nil, err
}
out := make([][]byte, 0, len(entries))
for _, ent := range entries {
if ent.IsDir() {
continue
}
name := strings.ToLower(strings.TrimSpace(ent.Name()))
if !strings.HasSuffix(name, ".json") {
continue
}
path := filepath.Join(rootDir, ent.Name())
data, err := os.ReadFile(path)
if err != nil {
continue
}
out = append(out, data)
}
return out, nil
}
func SelectRecordCandidate[T any](
records []T,
historyID string,
recordID func(T) string,
eligible func(T) bool,
) (T, bool) {
id := strings.TrimSpace(historyID)
if id != "" {
for _, rec := range records {
if strings.TrimSpace(recordID(rec)) == id {
return rec, eligible(rec)
}
}
var zero T
return zero, false
}
for _, rec := range records {
if eligible(rec) {
return rec, true
}
}
var zero T
return zero, false
}
func DecodeBase64Optional(raw string, exists bool) ([]byte, bool, error) {
if !exists {
return nil, false, nil
}
s := strings.TrimSpace(raw)
if s == "" {
return nil, true, nil
}
data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return nil, false, err
}
return data, true, nil
}