23
|
1 |
// config.go |
|
2 |
// |
|
3 |
// This file implements the configuration part for when you need the API |
|
4 |
// key to modify things in the Mastodon configuration and manage measurements. |
|
5 |
|
8
|
6 |
package gondole |
23
|
7 |
|
|
8 |
import ( |
|
9 |
"fmt" |
|
10 |
"io/ioutil" |
|
11 |
"os" |
|
12 |
"path/filepath" |
|
13 |
"strings" |
|
14 |
|
|
15 |
"github.com/naoina/toml" |
|
16 |
) |
|
17 |
|
|
18 |
/* |
|
19 |
Assume the application is registered if $HOME/.config/<gondole>/config.toml already exist |
|
20 |
*/ |
|
21 |
|
|
22 |
const ( |
|
23 |
DefaultName = "config.toml" |
|
24 |
) |
|
25 |
|
|
26 |
// Config holds our parameters |
|
27 |
type Config struct { |
|
28 |
ID int64 |
|
29 |
Name string |
|
30 |
BearerToken string |
|
31 |
} |
|
32 |
|
|
33 |
// Check the parameter for either tag or filename |
|
34 |
func checkName(file string) (str string) { |
|
35 |
// Full path, MUST have .toml |
|
36 |
if bfile := []byte(file); bfile[0] == '/' { |
|
37 |
if !strings.HasSuffix(file, ".toml") { |
|
38 |
str = "" |
|
39 |
} else { |
|
40 |
str = file |
|
41 |
} |
|
42 |
return |
|
43 |
} |
|
44 |
|
|
45 |
// If ending with .toml, take it literally |
|
46 |
if strings.HasSuffix(file, ".toml") { |
|
47 |
str = file |
|
48 |
return |
|
49 |
} |
|
50 |
|
|
51 |
// Check for tag |
|
52 |
if !strings.HasSuffix(file, ".toml") { |
|
53 |
// file must be a tag so add a "." |
|
54 |
str = filepath.Join(os.Getenv("HOME"), |
|
55 |
fmt.Sprintf(".%s", file), |
|
56 |
"config.toml") |
|
57 |
} |
|
58 |
return |
|
59 |
} |
|
60 |
|
|
61 |
// LoadConfig reads a file as a TOML document and return the structure |
|
62 |
func LoadConfig(name, redirectURL string) (c *Config, err error) { |
|
63 |
c = new(Config) |
|
64 |
|
|
65 |
sFile := filepath.Join(os.Getenv("HOME"), |
|
66 |
".config", |
|
67 |
"gondole", |
|
68 |
DefaultName, |
|
69 |
) |
|
70 |
|
|
71 |
// Check if there is any config file |
|
72 |
if _, err := os.Stat(sFile); err != nil { |
|
73 |
// No config file is no error |
|
74 |
|
|
75 |
|
|
76 |
} else { |
|
77 |
// Read it |
|
78 |
buf, err := ioutil.ReadFile(sFile) |
|
79 |
if err != nil { |
|
80 |
return c, fmt.Errorf("Can not read %s", sFile) |
|
81 |
} |
|
82 |
|
|
83 |
err = toml.Unmarshal(buf, &c) |
|
84 |
if err != nil { |
|
85 |
return c, fmt.Errorf("Error parsing toml %s: %v", |
|
86 |
sFile, err) |
|
87 |
} |
|
88 |
} |
|
89 |
return c, nil |
|
90 |
} |
|
91 |
|
|
92 |
func WriteConfig(c * Config) (err error) { |
|
93 |
sc, err := toml.Marshal(c) |
|
94 |
if err != nil { |
|
95 |
|
|
96 |
} |
|
97 |
err = ioutil.WriteFile(filepath.Join(os.Getenv("HOME"), ".config", "gondole", DefaultName), sc, 0600) |
|
98 |
return |
|
99 |
} |