-
Notifications
You must be signed in to change notification settings - Fork 2
/
sgo.go
410 lines (337 loc) · 9.16 KB
/
sgo.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package main
import (
"bytes"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"io"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/cavaliercoder/grab"
ui "github.com/gizak/termui"
"github.com/mholt/archiver"
"github.com/olekukonko/tablewriter"
)
const (
viewGoVersions = "goversions"
viewGoFiles = "gofiles"
)
var mutex = &sync.Mutex{}
var viewInFocus = viewGoFiles
var selectedGoVersion = 0
var selectedGoFile = 0
var goVersions []string
var goFiles []string
var doc *goquery.Document
var downloadFileLinks = make(map[string]string)
var downloadFileSHA = make(map[string]string)
var uiVersionsList = ui.NewList()
var uiFilesList = ui.NewList()
//var uiInfo = ui.NewPar("Info")
var uiInfo = ui.NewList()
var uiDownloadProgress = ui.NewGauge()
var uiDownloadSpeed = ui.NewSparklines()
func getGolangData(url string) {
var err error
doc, err = goquery.NewDocument(url)
if err != nil {
log.Fatal(err)
}
r, err := regexp.Compile("([a-zA-Z0-9.]+)")
if err != nil {
log.Fatal(err)
}
goVersions = nil
doc.Find("div .expanded > h2").Each(func(i int, s *goquery.Selection) {
goVersions = append(goVersions, r.FindString(s.Text()))
})
}
func updateGoVersions() {
var strs []string
checkLimits()
for index, s := range goVersions {
if index == selectedGoVersion {
strs = append(strs, fmt.Sprintf("[%s](fg-white,bg-green)", s))
} else {
strs = append(strs, fmt.Sprintf("%s", s))
}
}
uiVersionsList.Items = strs
}
func addTextToInfoPanel(text string) {
uiInfo.Items = append(uiInfo.Items, text)
height := uiInfo.GetHeight()
startPosition := len(uiInfo.Items) - height + 2
if startPosition < 0 {
startPosition = 0
}
uiInfo.Items = uiInfo.Items[startPosition:]
}
func downloadFile(url string) error {
addTextToInfoPanel(fmt.Sprintf("Downloading %s...\n", url))
respch, err := grab.GetAsync(".", url)
if err != nil {
fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", url, err)
os.Exit(1)
}
addTextToInfoPanel(fmt.Sprintf("Initializing download...\n"))
uiDownloadProgress.Percent = 0
go func() {
var resp *grab.Response
t := time.NewTicker(100 * time.Millisecond)
var sinceLastTime uint64
var spdata []int
for {
select {
case r := <-respch:
if r != nil {
resp = r
addTextToInfoPanel(fmt.Sprintf("Downloading...\n"))
}
case <-t.C:
if resp == nil {
continue
}
if resp.Error != nil {
fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n", url, resp.Error)
//return resp.Error
return
}
if resp.IsComplete() {
addTextToInfoPanel(fmt.Sprintf("Successfully downloaded to ./%s\n", resp.Filename))
uiDownloadProgress.Percent = 100
addTextToInfoPanel("Verifying...\n")
sha := downloadFileSHA[getGoFile()]
var hasher hash.Hash
if len(sha) == 64 {
hasher = sha256.New()
} else if len(sha) == 40 {
hasher = sha1.New()
} else {
addTextToInfoPanel(fmt.Sprintf("Unknown hash length of %d.\n", len(sha)))
return
}
f, err := os.Open(resp.Filename)
if err != nil {
addTextToInfoPanel(fmt.Sprintf(err.Error()))
return
}
defer f.Close()
if _, err := io.Copy(hasher, f); err != nil {
addTextToInfoPanel(fmt.Sprintf(err.Error()))
return
}
fileSHA := hex.EncodeToString(hasher.Sum(nil))
if sha != fileSHA {
addTextToInfoPanel("Download file doesn't match SHA.\n")
addTextToInfoPanel(fmt.Sprintf("File SHA: %s\nExpected SHA:\n%s\n", fileSHA, sha))
return
}
addTextToInfoPanel(fmt.Sprintf("File SHA matches: %s\n", fileSHA))
addTextToInfoPanel(fmt.Sprintf("Extracting...\n"))
if strings.Contains(resp.Filename, ".zip") {
archiver.Zip.Open(resp.Filename, ".")
} else if strings.Contains(resp.Filename, ".tar.gz") {
archiver.TarGz.Open(resp.Filename, ".")
}
os.Rename("go", getGoVersion())
addTextToInfoPanel(fmt.Sprintf("Done extracting.\n"))
t.Stop()
return
}
uiDownloadProgress.Percent = int(100 * resp.Progress())
thisTime := resp.BytesTransferred() - sinceLastTime
sinceLastTime = resp.BytesTransferred()
spdata = append(spdata, int(thisTime))
uiDownloadSpeed.Lines[0].Data = spdata
}
}
}()
return nil
}
func updateFilesView(s string) error {
var err error
var b bytes.Buffer
var headers []string
var data [][]string
goFiles = nil
table := tablewriter.NewWriter(&b)
doc.Find("div[id=\"" + strings.TrimSpace(s) + "\"] > .expanded > table > thead > tr > th").Each(func(i int, s *goquery.Selection) {
headers = append(headers, s.Text())
})
doc.Find("div[id=\"" + strings.TrimSpace(s) + "\"] > .expanded > table > tbody > tr").Each(func(i int, tr *goquery.Selection) {
var row []string
var a *goquery.Selection
tr.Find("td").Each(func(i int, td *goquery.Selection) {
if a == nil {
a = td.Find("a")
}
if link, exists := a.Attr("href"); exists {
downloadFileLinks[a.Text()] = link
}
tt := td.Find("tt")
if tt != nil && a != nil {
downloadFileSHA[a.Text()] = tt.Text()
}
row = append(row, td.Text())
})
if len(row) > 0 {
goFiles = append(goFiles, row[0])
}
data = append(data, row)
})
table.SetHeader(headers)
//table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
table.SetBorder(false)
//table.SetCenterSeparator("|")
table.AppendBulk(data)
table.Render()
checkLimits()
strs := strings.Split(b.String(), "\n")
for index, s := range strs {
if index == selectedGoFile+2 { // +2 To skip headers.
strs[index] = "[" + strings.TrimRight(s, "\n") + "](fg-white,bg-blue)\n"
break
}
}
uiFilesList.Items = strs
return err
}
func getGoVersion() string {
return goVersions[selectedGoVersion]
}
func getGoFile() string {
return goFiles[selectedGoFile]
}
func checkLimits() {
if selectedGoVersion < 0 {
selectedGoVersion = 0
} else if selectedGoVersion >= len(goVersions) {
selectedGoVersion = len(goVersions) - 1
}
if selectedGoFile < 0 {
selectedGoFile = 0
} else if selectedGoFile >= len(goFiles) {
selectedGoFile = len(goFiles) - 1
}
}
func updateViewInFocus() {
if viewInFocus == viewGoFiles {
uiFilesList.BorderLabelBg = ui.ColorWhite
//uiFilesList.BorderLabelFg = ui.ColorBlack
//uiVersionsList.BorderLabelFg = ui.ColorGreen
uiVersionsList.BorderLabelBg = ui.ColorDefault
} else if viewInFocus == viewGoVersions {
uiFilesList.BorderLabelBg = ui.ColorDefault
//uiFilesList.BorderLabelFg = ui.ColorGreen
uiVersionsList.BorderLabelBg = ui.ColorWhite
}
}
func main() {
url := "https://golang.org/dl/"
log.Printf("Getting data from %s...\n", url)
getGolangData(url)
if err := ui.Init(); err != nil {
panic(err)
}
defer ui.Close()
spark := ui.NewSparkline()
spark.Height = 8
spark.LineColor = ui.ColorCyan
spark.TitleColor = ui.ColorWhite
uiDownloadSpeed.Add(spark)
uiDownloadSpeed.Height = 11
uiDownloadSpeed.BorderLabel = "Download Speed"
uiFilesList.Height = len(goVersions) + 2
uiFilesList.BorderLabel = "Go Files"
uiFilesList.Width = 20
uiFilesList.Border = true
uiInfo.BorderLabel = "Info Panel"
uiInfo.Items = []string{"Ready."}
//uiInfo.Text = "Ready.\n"
uiInfo.Height = 14
updateFilesView(getGoVersion())
uiDownloadProgress.LabelAlign = ui.AlignCenter
uiDownloadProgress.Height = 3
uiDownloadProgress.Border = true
uiDownloadProgress.BorderLabel = "Download Progress"
uiDownloadProgress.BarColor = ui.ColorRed
updateGoVersions()
uiVersionsList.BorderLabel = "Go Versions"
uiVersionsList.Height = len(goVersions) + 2
uiVersionsList.Width = 10
// build layout
ui.Body.AddRows(
ui.NewRow(
ui.NewCol(2, 0, uiVersionsList),
ui.NewCol(10, 0, uiFilesList)),
ui.NewRow(
ui.NewCol(6, 0, uiDownloadProgress, uiDownloadSpeed),
ui.NewCol(6, 0, uiInfo)))
// calculate layout
ui.Body.Align()
ui.Merge("timer", ui.NewTimerCh(10*time.Millisecond))
ui.Render(ui.Body)
ui.Handle("/sys/kbd/q", func(ui.Event) {
ui.StopLoop()
})
ui.Handle("/sys/kbd/Q", func(ui.Event) {
ui.StopLoop()
})
ui.Handle("/sys/kbd/C-c", func(ui.Event) {
ui.StopLoop()
})
ui.Handle("/sys/kbd/<up>", func(ui.Event) {
mutex.Lock()
defer mutex.Unlock()
if viewInFocus == viewGoFiles {
selectedGoFile--
updateFilesView(getGoVersion())
} else if viewInFocus == viewGoVersions {
selectedGoVersion--
updateGoVersions()
updateFilesView(getGoVersion())
}
})
ui.Handle("/sys/kbd/<enter>", func(ui.Event) {
downloadFile(downloadFileLinks[getGoFile()])
})
ui.Handle("/sys/kbd/<down>", func(ui.Event) {
mutex.Lock()
defer mutex.Unlock()
if viewInFocus == viewGoFiles {
selectedGoFile++
updateFilesView(getGoVersion())
} else if viewInFocus == viewGoVersions {
selectedGoVersion++
updateGoVersions()
updateFilesView(getGoVersion())
}
})
ui.Handle("/sys/kbd/<tab>", func(ui.Event) {
if viewInFocus == viewGoFiles {
viewInFocus = viewGoVersions
} else if viewInFocus == viewGoVersions {
viewInFocus = viewGoFiles
}
updateViewInFocus()
})
ui.Handle("/timer/", func(e ui.Event) {
ui.Render(ui.Body)
})
ui.Handle("/sys/wnd/resize", func(e ui.Event) {
ui.Body.Width = ui.TermWidth()
ui.Body.Align()
ui.Clear()
ui.Render(ui.Body)
})
updateViewInFocus()
ui.Loop()
}