-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnotes.go
304 lines (275 loc) · 7.58 KB
/
notes.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"time"
"github.com/briandowns/spinner"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
)
const notesFilePathPrefix = "daily_notes_"
const notesGistDescription = "Daily Notes via notes app"
// GistNotesMap - Offline mapping of local notes files with respective remote gist-ids
type GistNotesMap struct {
GistID string `json:"gist_id"`
Filename string `json:"filename"`
}
func getOrCreateNotesDir() string {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Fatal(err)
}
dirPath := filepath.Join(homeDir, ".notes")
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.Mkdir(dirPath, 0700)
if err != nil {
log.Fatal(err)
}
}
return dirPath
}
func getOrCreateNotesDataDir() string {
dirPath := getOrCreateNotesDir()
dataDirPath := filepath.Join(dirPath, "data")
if _, err := os.Stat(dataDirPath); os.IsNotExist(err) {
err := os.Mkdir(dataDirPath, 0700)
if err != nil {
log.Fatal(err)
}
}
return dataDirPath
}
func getOrCreateNotesConfigDir() string {
dirPath := getOrCreateNotesDir()
configDirPath := filepath.Join(dirPath, "config")
if _, err := os.Stat(configDirPath); os.IsNotExist(err) {
err := os.Mkdir(configDirPath, 0700)
if err != nil {
log.Fatal(err)
}
}
return configDirPath
}
func getOrCreateLocalGistStore() string {
configDirPath := getOrCreateNotesConfigDir()
localGistStore := filepath.Join(configDirPath, "gist_store.json")
_, err := os.Open(localGistStore)
if err != nil {
os.Create(localGistStore)
}
return localGistStore
}
func getGithubPersonalToken() (token string) {
token, exists := os.LookupEnv("GITHUB_CREATE_GIST_TOKEN")
if exists == false {
fmt.Println(`No GITHUB_CREATE_GIST_TOKEN found..!
You can get your personal token from https://github.com/settings/tokens/new?scopes=gist&description=notes-cli
Paste the following line in your ~/.bashrc or ~/.zshrc
export GITHUB_CREATE_GIST_TOKEN='<token>'`,
)
os.Exit(1)
}
return token
}
func getAllLocalNotesFiles() []string {
dataDirPath := getOrCreateNotesDataDir()
markdownsFiles, err := filepath.Glob(filepath.Join(dataDirPath, "*.md"))
if err != nil {
log.Fatal(err)
}
return markdownsFiles
}
func getGists(token string) []*github.Gist {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
var allGists []*github.Gist
for {
opt := &github.GistListOptions{ListOptions: github.ListOptions{PerPage: 100}}
gists, resp, err := client.Gists.List(ctx, "", opt)
if err != nil {
log.Fatal(err)
}
allGists = append(allGists, gists...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
return allGists
}
func getOrCreateGist(token string, markdownFilePath string, GistID string) string {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
markdownFileName := filepath.Base(markdownFilePath)
markdownFileContentByte, err := ioutil.ReadFile(markdownFilePath)
if err != nil {
log.Fatal(err)
}
markdownFileContent := string(markdownFileContentByte)
tmpGistFile := github.GistFile{Filename: &markdownFileName, Content: &markdownFileContent}
var tmpFilesObj = map[github.GistFilename]github.GistFile{
github.GistFilename(markdownFileName): tmpGistFile,
}
var gistVisibilityToPublic = false
// create gist
gistDescription := notesGistDescription
if GistID == "" {
tmpGistObj := github.Gist{
Files: tmpFilesObj,
Public: &gistVisibilityToPublic,
Description: &gistDescription,
}
gistResponse, _, err := client.Gists.Create(ctx, &tmpGistObj)
if err != nil {
log.Fatal(err)
}
return *gistResponse.ID
}
tmpGistObj := github.Gist{
Files: tmpFilesObj,
Public: &gistVisibilityToPublic,
Description: &gistDescription, ID: &GistID,
}
gistResponse, _, err := client.Gists.Edit(ctx, GistID, &tmpGistObj)
if err != nil {
log.Fatal(err)
}
return *gistResponse.ID
}
func doDownSync() {
// download all gists with `daily_notes` prefix
// TODO
}
func doUpSync() {
// upload local gists
token := getGithubPersonalToken()
localGistStorePath := getOrCreateLocalGistStore()
gistStoreFile, _ := ioutil.ReadFile(localGistStorePath)
data := []GistNotesMap{}
_ = json.Unmarshal([]byte(gistStoreFile), &data)
localMarkdownsFiles := getAllLocalNotesFiles()
var filesToBeSynced []GistNotesMap
for i := 0; i < len(localMarkdownsFiles); i++ {
var fileFoundInStore = false
for j := 0; j < len(data); j++ {
if data[j].Filename == localMarkdownsFiles[i] {
filesToBeSynced = append(filesToBeSynced, data[j])
fileFoundInStore = true
break
}
}
if fileFoundInStore == false {
filesToBeSynced = append(filesToBeSynced, GistNotesMap{"", localMarkdownsFiles[i]})
}
}
for i := 0; i < len(filesToBeSynced); i++ {
filesToBeSynced[i].GistID = getOrCreateGist(token, filesToBeSynced[i].Filename, filesToBeSynced[i].GistID)
}
syncedFileData, _ := json.MarshalIndent(filesToBeSynced, "", " ")
_ = ioutil.WriteFile(localGistStorePath, syncedFileData, 0644)
}
func performSync() {
fmt.Println("Syncing your gists....")
loader := spinner.New(spinner.CharSets[36], 100*time.Millisecond)
loader.Start()
doUpSync()
doDownSync()
loader.Stop()
fmt.Println("Done!")
}
func runEditor(cmd *exec.Cmd) error {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
err := cmd.Run()
return err
}
func isVimEditor(editor string) bool {
re := regexp.MustCompile("(g|n|neo)?vim")
if re.Match([]byte(editor)) {
return true
}
return false
}
func getWorkingTextEditorWithFileBrowsingSupport() string {
commands := [...]string{"vim", "vi", "nvim", "emacs"}
prefixPath := [...]string{"/usr/bin/", "/usr/local/bin/"}
for i := 0; i < len(commands); i++ {
for j := 0; j < len(prefixPath); j++ {
cmdFilePath := prefixPath[j] + commands[i]
if _, err := os.Stat(cmdFilePath); !os.IsNotExist(err) {
return cmdFilePath
}
}
}
fmt.Println("Unable to find terminal based filebrowser like vim, emacs, nvim, vi etc..!")
log.Fatal("Please install any of the above software to browse notes in terminal")
return ""
}
func getEditorCommand(editor string, mode string) *exec.Cmd {
currentTime := time.Now()
var filename string
dataDirPath := getOrCreateNotesDataDir()
if mode == "write" {
filename = filepath.Join(dataDirPath, notesFilePathPrefix+currentTime.Format("2006_01_02")+".md")
} else {
filename = dataDirPath
}
if isVimEditor(editor) && mode == "write" {
cmd := exec.Command(editor, "+normal Go", filename)
return cmd
}
return exec.Command(editor, filename)
}
func showUsage() {
helpMessage := `notes - A simple note-taking app
Usage: notes [OPTIONS]
Options:
write - write in markdown file created with today's date stamp
read - browse all notes in terminal file browser
sync - upload all markdown files to your github as Private Gist
Example:
notes write
notes read
notes sync
`
fmt.Println(helpMessage)
}
func main() {
if len(os.Args) == 1 {
showUsage()
return
}
mode := os.Args[1]
editor, exists := os.LookupEnv("EDITOR")
if exists == false {
fmt.Println("EDITOR not set in your enviornment!")
fmt.Println("edit your env(~/.bashrc etc) and write export EDITOR='vim'")
}
if mode == "write" {
cmd := getEditorCommand(editor, mode)
runEditor(cmd)
} else if mode == "read" {
editor := getWorkingTextEditorWithFileBrowsingSupport()
cmd := getEditorCommand(editor, mode)
runEditor(cmd)
} else if mode == "sync" {
performSync()
} else {
showUsage()
}
}