-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathconfig.go
109 lines (94 loc) · 2.42 KB
/
config.go
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// -*- tab-width: 4; -*-
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/go-yaml/yaml"
)
type Hooks struct {
Pre string
Post string
}
type Config struct {
Nick string
Twturl string
Twtfile string
Following map[string]string // nick -> url
DiscloseIdentity bool
Timeline string
Hooks Hooks
IncludeYourself bool
nicks map[string]string // normalizeURL(url) -> nick
path string // location of loaded config
}
func (conf *Config) Write() error {
if conf.path == "" {
return errors.New("error: no config file path found")
}
data, err := yaml.Marshal(conf)
if err != nil {
return fmt.Errorf("error marshalling config: %s", err)
}
return ioutil.WriteFile(conf.path, data, 0666)
}
func (conf *Config) Parse(data []byte) error {
return yaml.Unmarshal(data, conf)
}
func (conf *Config) Read(confdir string) string {
var paths []string
if confdir != "" {
paths = append(paths, confdir)
} else {
if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" {
paths = append(paths, fmt.Sprintf("%s/twet", xdg))
}
paths = append(paths,
fmt.Sprintf("%s/.config/twet", homedir),
fmt.Sprintf("%s/Library/Application Support/twet", homedir),
fmt.Sprintf("%s/.twet", homedir))
}
filename := "config.yaml"
foundpath := ""
for _, path := range paths {
configfile := fmt.Sprintf("%s/%s", path, filename)
data, err := ioutil.ReadFile(configfile)
if err != nil {
// try next path
continue
}
if err := conf.Parse(data); err != nil {
log.Fatal(fmt.Sprintf("error parsing config file: %s: %s", filename, err))
}
foundpath = path
break
}
if foundpath == "" {
log.Fatal(fmt.Sprintf("config file %q not found; looked in: %q", filename, paths))
}
conf.Timeline = strings.ToLower(conf.Timeline)
if conf.Timeline != "new" && conf.Timeline != "full" {
log.Fatal(fmt.Sprintf("unexpected config timeline: %s", conf.Timeline))
}
conf.path = filepath.Join(foundpath, filename)
return foundpath
}
func (conf *Config) urlToNick(url string) string {
if conf.nicks == nil {
conf.nicks = make(map[string]string)
for n, u := range conf.Following {
if u = NormalizeURL(u); u == "" {
continue
}
conf.nicks[u] = n
}
if conf.Nick != "" && conf.Twturl != "" {
conf.nicks[NormalizeURL(conf.Twturl)] = conf.Nick
}
}
return conf.nicks[NormalizeURL(url)]
}