-
Notifications
You must be signed in to change notification settings - Fork 217
/
sync.go
112 lines (95 loc) · 2.27 KB
/
sync.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
package sync
import (
"fmt"
"io/ioutil"
"os"
"time"
"github.com/knqyf263/pet/config"
"github.com/knqyf263/pet/snippet"
"github.com/pkg/errors"
)
// Client manages communication with the remote Snippet repository
type Client interface {
GetSnippet() (*Snippet, error)
UploadSnippet(string) error
}
// Snippet is the remote snippet
type Snippet struct {
Content string
UpdatedAt time.Time
}
// AutoSync syncs snippets automatically
func AutoSync(file string) error {
client, err := NewSyncClient()
if err != nil {
return errors.Wrap(err, "Failed to initialize API client")
}
snippet, err := client.GetSnippet()
if err != nil {
return err
}
fi, err := os.Stat(file)
if os.IsNotExist(err) || fi.Size() == 0 {
return download(snippet.Content)
} else if err != nil {
return errors.Wrap(err, "Failed to get a FileInfo")
}
local := fi.ModTime().UTC()
remote := snippet.UpdatedAt.UTC()
switch {
case local.After(remote):
return upload(client)
case remote.After(local):
return download(snippet.Content)
default:
return nil
}
}
// NewSyncClient returns Client
func NewSyncClient() (Client, error) {
if config.Conf.General.Backend == "gitlab" {
client, err := NewGitLabClient()
if err != nil {
return nil, errors.Wrap(err, "Failed to initialize GitLab client")
}
return client, nil
}
client, err := NewGistClient()
if err != nil {
return nil, errors.Wrap(err, "Failed to initialize Gist client")
}
return client, nil
}
func upload(client Client) (err error) {
var snippets snippet.Snippets
if err := snippets.Load(); err != nil {
return errors.Wrap(err, "Failed to load the local snippets")
}
body, err := snippets.ToString()
if err != nil {
return err
}
if err = client.UploadSnippet(body); err != nil {
return errors.Wrap(err, "Failed to upload snippet")
}
fmt.Println("Upload success")
return nil
}
func download(content string) error {
snippetFile := config.Conf.General.SnippetFile
var snippets snippet.Snippets
if err := snippets.Load(); err != nil {
return err
}
body, err := snippets.ToString()
if err != nil {
return err
}
if content == body {
// no need to download
fmt.Println("Already up-to-date")
return nil
}
fmt.Println("Download success")
return ioutil.WriteFile(snippetFile, []byte(content), os.ModePerm)
}