79 lines
2.1 KiB
Go
79 lines
2.1 KiB
Go
package app
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gitea.maximumdirect.net/eric/narratio/internal/config"
|
|
)
|
|
|
|
func resolveSessionConfigPath(flagValue string) (string, error) {
|
|
return resolveSessionConfigPathWithCandidates(flagValue, config.DefaultSessionConfigSearchPaths)
|
|
}
|
|
|
|
func resolveSessionConfigPathWithCandidates(flagValue string, candidates []string) (string, error) {
|
|
if explicit := strings.TrimSpace(flagValue); explicit != "" {
|
|
return explicit, nil
|
|
}
|
|
|
|
resolved, err := discoverSessionConfigPathWithCandidates(candidates)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if resolved.Path != "" {
|
|
return resolved.Path, nil
|
|
}
|
|
return "", missingSessionConfigError(resolved.Searched, "")
|
|
}
|
|
|
|
type sessionConfigDiscovery struct {
|
|
Path string
|
|
Searched []string
|
|
}
|
|
|
|
func discoverSessionConfigPathWithCandidates(candidates []string) (sessionConfigDiscovery, error) {
|
|
ordered := make([]string, 0, len(candidates))
|
|
for _, raw := range candidates {
|
|
path := strings.TrimSpace(raw)
|
|
if path == "" {
|
|
continue
|
|
}
|
|
ordered = append(ordered, path)
|
|
info, err := os.Stat(path)
|
|
if err == nil {
|
|
if info.IsDir() {
|
|
continue
|
|
}
|
|
return sessionConfigDiscovery{Path: filepath.Clean(path), Searched: ordered}, nil
|
|
}
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
continue
|
|
}
|
|
return sessionConfigDiscovery{}, fmt.Errorf("check default session config %q: %w", path, err)
|
|
}
|
|
|
|
return sessionConfigDiscovery{Searched: ordered}, nil
|
|
}
|
|
|
|
func missingSessionConfigError(searched []string, remoteDetail string) error {
|
|
ordered := append([]string(nil), searched...)
|
|
if len(ordered) == 0 {
|
|
if strings.TrimSpace(remoteDetail) != "" {
|
|
return fmt.Errorf("no session config path provided and no default locations configured; %s", remoteDetail)
|
|
}
|
|
return fmt.Errorf("no session config path provided and no default locations configured")
|
|
}
|
|
msg := fmt.Sprintf(
|
|
"no session config path provided and no default session config found; searched: %s",
|
|
strings.Join(ordered, ", "),
|
|
)
|
|
if strings.TrimSpace(remoteDetail) != "" {
|
|
msg += "; " + strings.TrimSpace(remoteDetail)
|
|
}
|
|
msg += "; pass --session to use an explicit path"
|
|
return fmt.Errorf("%s", msg)
|
|
}
|