-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
304 lines (237 loc) · 6.5 KB
/
utils.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 (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const exportDir = "exported"
const fileExtension = ".md"
func getExportDataFile() (string, error) {
// Validate arguments
if len(os.Args) < 2 {
return "", errNoFileProvided
}
flag.Parse()
file := flag.Arg(0)
if file == "" {
return "", errNoFileProvided
}
return file, nil
}
func readInputFile(exportDataInputFile string) (ExportData, error) {
exportDataFile, err := os.ReadFile(exportDataInputFile)
if err != nil {
return ExportData{}, errReadingInputFile
}
var exportData ExportData
err = json.Unmarshal(exportDataFile, &exportData)
if err != nil {
return ExportData{}, errUnmarshallingInputFile
}
return exportData, nil
}
func parseExportData(exportData ExportData) (map[string]Tag, map[string]Note, map[string][]string) {
var (
tags = make(map[string]Tag)
notes = make(map[string]Note)
noteTags = make(map[string][]string)
)
for _, item := range exportData.Items {
if item.ContentType == ContentTypeTag {
parseTags(item, tags, noteTags)
}
if item.ContentType == ContentTypeNote {
parseNotes(item, notes)
}
}
return tags, notes, noteTags
}
func parseTags(item Item, tags map[string]Tag, noteTags map[string][]string) {
if item.Deleted {
fmt.Printf("Tag \"%s\":%s is deleted, will not be exported\n", item.Content.Title, item.UUID)
return
}
var parent string
for _, reference := range item.Content.References {
if reference.ReferenceType == ReferenceTypeTagToParentTag {
parent = reference.UUID
}
if reference.ContentType == ContentTypeNote {
noteTags[reference.UUID] = append(noteTags[reference.UUID], item.UUID)
}
}
tags[item.UUID] = Tag{
Name: nameOrUUID(item.Content.Title, item.UUID),
Parent: parent,
}
}
func parseNotes(item Item, notes map[string]Note) {
if item.Content.Trashed {
fmt.Printf("Note \"%s\":%s is deleted, will not be exported\n", item.Content.Title, item.UUID)
return
}
notes[item.UUID] = Note{
UUID: item.UUID,
Title: sanitizeName(nameOrUUID(item.Content.Title, item.UUID)),
Content: item.Content.Text,
UpdatedAt: item.UpdatedAt,
CreatedAt: item.CreatedAt,
}
}
func getFilePath(tags map[string]Tag, tag Tag) string {
if tag.Parent == "" {
return sanitizeName(tag.Name)
}
return filepath.Join(getFilePath(tags, tags[tag.Parent]), sanitizeName(tag.Name))
}
func getExportedFilePath(tags map[string]Tag, tag *Tag) string {
if tag == nil {
return exportDir
}
return filepath.Join(exportDir, getFilePath(tags, *tag))
}
func replaceFirstRune(str, replacement string) string {
var sb strings.Builder
sb.WriteString(string([]rune(str)[:0]))
sb.WriteString(replacement)
sb.WriteString(string([]rune(str)[1:]))
return sb.String()
}
func sanitizeName(filename string) string {
filename = strings.TrimSpace(filename)
// If the following condition is true then both Name and item UUID are empty
// I don't think that should happen on a valid export file
// might need to update the nameOrUUID
if len(filename) == 0 {
return filename
}
filename = strings.ReplaceAll(filename, "<", "-")
filename = strings.ReplaceAll(filename, ">", "-")
filename = strings.ReplaceAll(filename, ":", "-")
filename = strings.ReplaceAll(filename, "\"", "-")
filename = strings.ReplaceAll(filename, "/", "-")
filename = strings.ReplaceAll(filename, "\\", "-")
filename = strings.ReplaceAll(filename, "|", "-")
filename = strings.ReplaceAll(filename, "?", "-")
filename = strings.ReplaceAll(filename, "*", "-")
if string(filename[0]) == "." {
filename = replaceFirstRune(filename, "-")
}
return filename
}
func updateTimes(path string, createdAt time.Time) error {
err := os.Chtimes(path, createdAt, createdAt)
if err != nil {
return errUpdatingTimes
}
return nil
}
func nameOrUUID(title, uuid string) string {
if len(strings.TrimSpace(title)) == 0 {
return uuid
}
return title
}
func pathExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func checkIfPathExistsAndRename(filepath string, extraPath string) string {
if pathExists(filepath + fileExtension) {
return checkIfPathExistsAndRename(filepath+"-"+extraPath, strconv.FormatInt(time.Now().Unix(), 10))
}
return filepath
}
func createTagFolders(tags map[string]Tag) error {
if len(tags) == 0 {
err := createFolders(getExportedFilePath(nil, nil))
if err != nil {
return fmt.Errorf("%w \"%s\"", errCreatingFolder, exportDir)
}
return nil
}
for _, tag := range tags {
tag := tag
path := getExportedFilePath(tags, &tag)
err := createFolders(path)
if err != nil {
return fmt.Errorf("%w \"%s\"", errCreatingFolder, path)
}
}
return nil
}
func createFolders(path string) error {
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
return errCreatingFolder
}
return nil
}
func createNotes(notes map[string]Note, tags map[string]Tag, noteTags map[string][]string) error {
for _, note := range notes {
noteTags := noteTags[note.UUID]
printDuplicatesHeader(noteTags, note)
for _, noteTag := range noteTags {
tag := tags[noteTag]
notePath := getFinalNotePath(tags, &tag, note)
printDuplicatePaths(noteTags, notePath)
err := createNoteAndUpdateTimes(note, notePath)
if err != nil {
return err
}
}
if len(noteTags) == 0 {
err := createNoteAndUpdateTimes(note, getFinalNotePath(tags, nil, note))
if err != nil {
return err
}
}
}
return nil
}
func getFinalNotePath(tags map[string]Tag, tag *Tag, note Note) string {
notePath := filepath.Join(getExportedFilePath(tags, tag), note.Title)
return checkIfPathExistsAndRename(notePath, note.UUID) + fileExtension
}
func printDuplicatesHeader(noteTags []string, note Note) {
if len(noteTags) > 1 {
fmt.Printf("Note \"%s\":%s is duplicated\n", note.Title, note.UUID)
fmt.Printf("\tDuplicate paths:\n")
}
}
func printDuplicatePaths(noteTags []string, notePath string) {
if len(noteTags) > 1 {
fmt.Printf("\t\t%s\n", notePath)
}
}
func createNote(note Note, notePath string) error {
f, err := os.Create(notePath)
if err != nil {
return errCreatingNote
}
_, err = f.Write([]byte(note.Content))
if err != nil {
return errWritingNote
}
err = f.Close()
if err != nil {
return errSavingNote
}
return nil
}
func createNoteAndUpdateTimes(note Note, notePath string) error {
err := createNote(note, notePath)
if err != nil {
return fmt.Errorf("%w - \"%s\"", err, note.Title)
}
err = updateTimes(notePath, note.CreatedAt)
if err != nil {
return fmt.Errorf("%w - \"%s\"", err, notePath)
}
return nil
}