-
Notifications
You must be signed in to change notification settings - Fork 0
/
snippet.go
54 lines (47 loc) · 1.27 KB
/
snippet.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
package snippet
import (
"bytes"
"fmt"
"os"
"github.com/BurntSushi/toml"
"pet/config"
)
type Snippets struct {
Snippets []SnippetInfo `toml:"snippets"`
}
type SnippetInfo struct {
Description string `toml:"description"`
Command string `toml:"command"`
Tag []string `toml:"tag"`
Output string `toml:"output"`
}
// Load reads toml file.
func (snippets *Snippets) Load() error {
snippetFile := config.Conf.General.SnippetFile
if _, err := os.Stat(snippetFile); os.IsNotExist(err) {
return nil
}
if _, err := toml.DecodeFile(snippetFile, snippets); err != nil {
return fmt.Errorf("Failed to load snippet file. %v", err)
}
return nil
}
// Save saves the snippets to toml file.
func (snippets *Snippets) Save() error {
snippetFile := config.Conf.General.SnippetFile
f, err := os.Create(snippetFile)
defer f.Close()
if err != nil {
return fmt.Errorf("Failed to save snippet file. err: %s", err)
}
return toml.NewEncoder(f).Encode(snippets)
}
// ToString returns the contents of toml file.
func (snippets *Snippets) ToString() (string, error) {
var buffer bytes.Buffer
err := toml.NewEncoder(&buffer).Encode(snippets)
if err != nil {
return "", fmt.Errorf("Failed to convert struct to TOML string: %v", err)
}
return buffer.String(), nil
}