Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
79 lines (64 loc) · 2 KB
/
Copy pathconfig.go
File metadata and controls
79 lines (64 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (C) 2026 Gregory Anders <greg@gpanders.com>
//
// SPDX-License-Identifier: GPL-3.0-or-later
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"codeberg.org/emersion/go-scfg"
"codeberg.org/gpanders/ijq/internal/options"
)
type Config struct {
HistoryFile options.HistoryFile `scfg:"history-file"`
JQCommand options.JQCommand `scfg:"jq-bin"`
HideInputPane options.HideInputPane `scfg:"hide-input-pane"`
LibraryPaths options.LibraryPaths `scfg:"library-paths"`
CopyFilterToClipboardOnExit bool `scfg:"copy-filter-to-clipboard-on-exit"`
Keymap Keymap `scfg:"keymaps"`
}
func DefaultConfig() Config {
var dataDir string
if dataHome := os.Getenv("XDG_DATA_HOME"); dataHome != "" {
dataDir = dataHome
} else if home, err := os.UserHomeDir(); err == nil {
dataDir = filepath.Join(home, ".local", "share")
}
var historyFile options.HistoryFile
if dataDir != "" {
historyFile = options.HistoryFile(filepath.Join(dataDir, "ijq", "history"))
}
return Config{
HistoryFile: historyFile,
JQCommand: "jq",
HideInputPane: false,
Keymap: DefaultKeymap(),
}
}
func NewConfig(path string) (Config, error) {
cfg := DefaultConfig()
f, err := os.Open(filepath.Clean(path))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return cfg, nil
}
return Config{}, fmt.Errorf("failed to open config file: %w", err)
}
defer f.Close()
if err := scfg.NewDecoder(f).Decode(&cfg); err != nil {
return Config{}, fmt.Errorf("failed to parse config file: %w", err)
}
return cfg, nil
}
func DefaultConfigPath() (string, error) {
var config string
if configHome := os.Getenv("XDG_CONFIG_HOME"); configHome != "" {
config = configHome
} else if home, err := os.UserHomeDir(); err == nil {
config = filepath.Join(home, ".config")
} else {
return "", errors.New("couldn't find path to config file")
}
return filepath.Join(config, "ijq", "config"), nil
}