Files
default-creds-tui/internal/creds/local.go
T
Hadi 624a723b16 init
Signed-off-by: Hadi <[email protected]>
2026-08-27 00:05:08 +02:00

105 lines
2.0 KiB
Go

package creds
import (
"fmt"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
type manufacturerFile struct {
Name string `yaml:"name"`
Icon string `yaml:"icon"`
Tags []string `yaml:"tags"`
Entries []struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
User string `yaml:"user"`
Pass string `yaml:"pass"`
Comment string `yaml:"comment"`
} `yaml:"entries"`
}
func LocalDataDir() string {
cacheDir, err := os.UserCacheDir()
if err != nil {
cacheDir = "."
}
return filepath.Join(cacheDir, "default-creds", "data")
}
func HasLocalData() bool {
entries, err := os.ReadDir(LocalDataDir())
if err != nil {
return false
}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".yaml") {
return true
}
}
return false
}
func LoadLocal(dir string) ([]Entry, error) {
files, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("read local data dir: %w", err)
}
var entries []Entry
for _, f := range files {
if f.IsDir() || !strings.HasSuffix(f.Name(), ".yaml") {
continue
}
data, err := os.ReadFile(filepath.Join(dir, f.Name()))
if err != nil {
continue
}
var doc manufacturerFile
if err := yaml.Unmarshal(data, &doc); err != nil {
continue
}
if doc.Name == "" {
continue
}
for _, e := range doc.Entries {
entries = append(entries, Entry{
Manufacturer: doc.Name,
Name: e.Name,
Icon: doc.Icon,
Tags: doc.Tags,
Version: e.Version,
User: e.User,
Pass: e.Pass,
Comment: e.Comment,
})
}
}
return entries, nil
}
func Filter(entries []Entry, query string) []Entry {
tokens := queryTokens(query)
if len(tokens) == 0 {
return nil
}
var out []Entry
for _, e := range entries {
if e.matches(tokens) {
out = append(out, e)
}
}
return out
}
func LocalStats(entries []Entry) (manufacturers, credentials int) {
seen := make(map[string]bool)
for _, e := range entries {
seen[e.Manufacturer] = true
}
return len(seen), len(entries)
}