forked from MrMilenko/Pinecone
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsondata.go
104 lines (89 loc) · 2.37 KB
/
jsondata.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
package main
import (
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"fyne.io/fyne/v2/theme"
)
func removeCommentsFromJSON(jsonStr string) string {
// remove // style comments
re := regexp.MustCompile(`(?m)^[ \t]*//.*\n?`)
jsonStr = re.ReplaceAllString(jsonStr, "")
// remove /* ... */ style comments
re = regexp.MustCompile(`/\*[\s\S]*?\*/`)
jsonStr = re.ReplaceAllString(jsonStr, "")
return jsonStr
}
func downloadJSONData(url string) ([]byte, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github.v3.raw")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func loadJSONData(jsonFilePath, owner, repo, path string, v interface{}, updateFlag bool) error {
if updateFlag {
// Notify we're checking for updates
fmt.Printf("Checking for PineCone updates..\n")
// Download JSON data
jsonData, err := downloadJSONData(fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s", owner, repo, path))
if err != nil {
return err
}
// Check if downloaded JSON is different from existing JSON
if _, err := os.Stat(jsonFilePath); err == nil {
existingData, err := os.ReadFile(jsonFilePath)
if err != nil {
return err
}
existingHash := fmt.Sprintf("%x", sha1.Sum(existingData))
newHash := fmt.Sprintf("%x", sha1.Sum(jsonData))
if existingHash == newHash {
return json.Unmarshal(existingData, &v)
}
}
// Write the newly downloaded JSON to file
if guiEnabled {
addText(theme.ForegroundColor(), "Updating %s...", jsonFilePath)
} else {
fmt.Printf("Updating %s...\n", jsonFilePath)
}
err = os.WriteFile(jsonFilePath, jsonData, 0o644)
if err != nil {
return err
}
// Load the newly downloaded JSON data
if guiEnabled {
addText(theme.ForegroundColor(), "Reloading %s...", path)
} else {
fmt.Printf("Reloading %s...\n", path)
}
jsonStr := removeCommentsFromJSON(string(jsonData))
err = json.Unmarshal([]byte(jsonStr), &v)
if err != nil {
return err
}
} else {
// Load existing JSON data
jsonData, err := os.ReadFile(jsonFilePath)
if err != nil {
return err
}
jsonStr := removeCommentsFromJSON(string(jsonData))
err = json.Unmarshal([]byte(jsonStr), &v)
if err != nil {
return err
}
}
return nil
}