forked from scottjbarr/bookmarkable
/
storage.go
122 lines (93 loc) · 1.89 KB
/
storage.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
110
111
112
113
114
115
116
117
118
119
120
121
122
package bookmarkable
import (
"fmt"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
type gistStore struct {
id *string
token *string
name *string
client *github.Client
content *string
filename *github.GistFilename
gist *github.Gist
file *github.GistFile
}
func (gs *gistStore) getClient() *github.Client {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: *gs.token},
)
tc := oauth2.NewClient(oauth2.NoContext, ts)
return github.NewClient(tc)
}
func newGistStore(id *string, token *string) *gistStore {
name := "bookmarkable"
gs := gistStore{
id: id,
name: &name,
token: token,
}
var filename github.GistFilename
filename = "bookmarkable.json"
gs.filename = &filename
gs.client = gs.getClient()
return &gs
}
func (gs *gistStore) init() error {
var err error
err = gs.retrieve()
if err != nil {
return err
}
if gs.gist != nil {
return nil
}
return err
}
func (gs *gistStore) byID() error {
gist, _, err := gs.client.Gists.Get(*gs.id)
if err != nil {
return err
}
gs.gist = gist
file := gist.Files[*gs.filename]
gs.file = &file
gs.content = gs.file.Content
return nil
}
func (gs *gistStore) retrieve() error {
if gs.id != nil {
return gs.byID()
}
gists, _, err := gs.client.Gists.List("", nil)
if err != nil {
return err
}
for _, g := range gists {
if g.Description != nil && *g.Description == *gs.name {
gs.id = g.ID
}
}
// not found
if gs.id == nil {
return fmt.Errorf("Not found")
}
return gs.byID()
}
func (gs *gistStore) update() error {
files := make(map[github.GistFilename]github.GistFile, 0)
f := "bookmarkable.json"
files[*gs.filename] = github.GistFile{
Filename: &f,
Content: gs.content,
}
gs.gist = &github.Gist{}
gs.gist.Files = files
gist, _, err := gs.client.Gists.Edit(*gs.id, gs.gist)
if err != nil {
return err
}
gs.gist = gist
return nil
}