-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgist.go
98 lines (79 loc) · 1.73 KB
/
gist.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
package main
import (
"bufio"
"encoding/json"
"os"
"path/filepath"
)
type Gist struct {
Snippets map[string]*Snippet
}
type Snippet struct {
GistID string `json:",omitempty"`
GistURL string `json:",omitempty"`
Line int
File string
Path string
Name string
Content string
Description string
}
func SnippetPath(file, snippetName string) string {
cfile := filepath.ToSlash(file)
ext := filepath.Ext(cfile)
root := file[:len(cfile)-len(ext)]
return root + "#" + snippetName + ext
}
func NewGist() *Gist {
return &Gist{
Snippets: make(map[string]*Snippet),
}
}
func LoadGist(name string) (*Gist, error) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
gist := NewGist()
err = json.NewDecoder(bufio.NewReader(f)).Decode(gist)
return gist, err
}
func SaveGist(name string, gist *Gist) error {
f, err := os.Create(name)
if err != nil {
return err
}
defer f.Close()
wr := bufio.NewWriter(f)
defer wr.Flush()
enc := json.NewEncoder(wr)
enc.SetIndent("", " ")
err = enc.Encode(gist)
return err
}
func (gist *Gist) EqualContent(old *Gist) bool {
if len(gist.Snippets) != len(old.Snippets) {
return false
}
return len(gist.ChangedSnippets(old)) == 0
}
func (gist *Gist) ChangedSnippets(old *Gist) []*Snippet {
changed := []*Snippet{}
for newSnipName, newSnippet := range gist.Snippets {
oldSnippet, found := old.Snippets[newSnipName]
if !found {
changed = append(changed, newSnippet)
continue
}
if !newSnippet.EqualContent(oldSnippet) {
changed = append(changed, newSnippet)
continue
}
}
return changed
}
func (snippet *Snippet) EqualContent(old *Snippet) bool {
return snippet.Content == old.Content &&
snippet.Description == old.Description
}