57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
|
|
package ui
|
||
|
|
|
||
|
|
import (
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"os"
|
||
|
|
)
|
||
|
|
|
||
|
|
// LoadUI loads UI translations from a JSON file for the specified language
|
||
|
|
func LoadUI(lang string) (*UI, error) {
|
||
|
|
if lang != "en" && lang != "es" {
|
||
|
|
return nil, fmt.Errorf("unsupported language: %s", lang)
|
||
|
|
}
|
||
|
|
|
||
|
|
filename := fmt.Sprintf("data/ui-%s.json", lang)
|
||
|
|
filepath, err := findDataFile(filename)
|
||
|
|
if err != nil {
|
||
|
|
return nil, err
|
||
|
|
}
|
||
|
|
|
||
|
|
data, err := os.ReadFile(filepath)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("error reading file %s: %w", filename, err)
|
||
|
|
}
|
||
|
|
|
||
|
|
var uiData UI
|
||
|
|
if err := json.Unmarshal(data, &uiData); err != nil {
|
||
|
|
return nil, fmt.Errorf("error parsing JSON: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
return &uiData, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// findDataFile locates a data file by searching up the directory tree
|
||
|
|
func findDataFile(filename string) (string, error) {
|
||
|
|
// Try current directory first
|
||
|
|
if _, err := os.Stat(filename); err == nil {
|
||
|
|
return filename, nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// Try parent directories (for tests running from subdirectories)
|
||
|
|
paths := []string{
|
||
|
|
filename, // Current dir
|
||
|
|
"../" + filename, // One level up
|
||
|
|
"../../" + filename, // Two levels up (for tests in internal/handlers)
|
||
|
|
"../../../" + filename, // Three levels up
|
||
|
|
}
|
||
|
|
|
||
|
|
for _, path := range paths {
|
||
|
|
if _, err := os.Stat(path); err == nil {
|
||
|
|
return path, nil
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return "", fmt.Errorf("file not found: %s (searched: current dir, ../, ../../, ../../../)", filename)
|
||
|
|
}
|