This repository has been archived by the owner on Aug 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelperFunctions.go
410 lines (352 loc) · 11.5 KB
/
helperFunctions.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
// helperFunctions.go // This file contains commonly used functions //>
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strconv"
"strings"
"syscall"
"github.com/goccy/go-json"
"github.com/schollz/progressbar/v3"
)
// signalHandler sets up a channel to listen for interrupt signals and returns a function that can be called to check if an interrupt has been received.
func signalHandler(ctx context.Context, cancel context.CancelFunc) (func() bool, error) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
cancel() // Call the cancel function when an interrupt is received
}()
return func() bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}, nil
}
// fetchBinaryFromURL fetches a binary from the given URL and saves it to the specified destination.
func fetchBinaryFromURL(url, destination string) error {
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Ensure the cancel function is called when the function returns
// Set up signal handling
interrupted, err := signalHandler(ctx, cancel)
if err != nil {
return fmt.Errorf("failed to set up signal handler: %v", err)
}
// Create a temporary directory if it doesn't exist
if err := os.MkdirAll(TEMPDIR, 0o755); err != nil {
return fmt.Errorf("failed to create temporary directory: %v", err)
}
// Create a temporary file to download the binary
tempFile := filepath.Join(TEMPDIR, filepath.Base(destination)+".tmp")
out, err := os.Create(tempFile)
if err != nil {
return fmt.Errorf("failed to create temporary file: %v", err)
}
defer out.Close()
// Schedule the deletion of the temporary file
defer func() {
if err := os.Remove(tempFile); err != nil && !os.IsNotExist(err) {
fmt.Printf("\r\033[Kfailed to remove temporary file: %v\n", err)
}
}()
// Fetch the binary from the given URL
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("error creating request: %v", err)
}
// Ensure that redirects are followed
client := &http.Client{
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return nil
},
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to fetch binary from %s: %v", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to fetch binary from %s. HTTP status code: %d", url, resp.StatusCode)
}
bar := spawnProgressBar(resp.ContentLength)
// Write the binary to the temporary file with progress bar
_, err = io.Copy(io.MultiWriter(out, bar), resp.Body)
if err != nil {
return fmt.Errorf("failed to write to temporary file: %v", err)
}
// Close the file before setting executable bit
if err := out.Close(); err != nil {
return fmt.Errorf("failed to close temporary file: %v", err)
}
// Use copyFile to move the binary to its destination
if err := copyFile(tempFile, destination); err != nil {
return fmt.Errorf("failed to move binary to destination: %v", err)
}
// Set executable bit immediately after copying
if err := os.Chmod(destination, 0o755); err != nil {
return fmt.Errorf("failed to set executable bit: %v", err)
}
// Check if the operation was interrupted
if interrupted() {
fmt.Println("\r\033[KDownload interrupted. Cleaning up...")
// Ensure the temporary file is removed if the operation was interrupted
if err := os.Remove(tempFile); err != nil && !os.IsNotExist(err) {
fmt.Printf("failed to remove temporary file: %v\n", err)
}
}
fmt.Print("\033[2K\r") // Clean the line
return nil
}
// copyFile copies(removes original after copy) a file from src to dst
func copyFile(src, dst string) error {
// Check if the destination file already exists
if fileExists(dst) {
if err := os.Remove(dst); err != nil {
return fmt.Errorf("%v", err)
}
}
sourceFile, err := os.Open(src)
if err != nil {
return fmt.Errorf("failed to open source file: %v", err)
}
defer sourceFile.Close()
destFile, err := os.Create(dst)
if err != nil {
return fmt.Errorf("failed to create destination file: %v", err)
}
_, err = io.Copy(destFile, sourceFile)
if err != nil {
destFile.Close() // Ensure the destination file is closed
return fmt.Errorf("failed to copy file: %v", err)
}
if err := destFile.Close(); err != nil {
return fmt.Errorf("failed to close destination file: %v", err)
}
// Remove the temporary file after copying
if err := os.Remove(src); err != nil {
return fmt.Errorf("failed to remove source file: %v", err)
}
return nil
}
func fetchJSON(url string, v interface{}) error {
response, err := http.Get(url)
if err != nil {
return fmt.Errorf("error fetching from %s: %v", url, err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("error reading from %s: %v", url, err)
}
if err := json.Unmarshal(body, v); err != nil {
return fmt.Errorf("error decoding from %s: %v", url, err)
}
return nil
}
// removeDuplicates removes duplicate elements from the input slice.
func removeDuplicates(input []string) []string {
seen := make(map[string]bool)
unique := []string{}
if input != nil {
for _, entry := range input {
if _, value := seen[entry]; !value {
seen[entry] = true
unique = append(unique, entry)
}
}
} else {
unique = input
}
return unique
}
// sortBinaries sorts the input slice of binaries.
func sortBinaries(binaries []string) []string {
sort.Strings(binaries)
return binaries
}
// fileExists checks if a file exists.
func fileExists(filePath string) bool {
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
// isExecutable checks if the file at the specified path is executable.
func isExecutable(filePath string) bool {
info, err := os.Stat(filePath)
if err != nil {
return false
}
return info.Mode().IsRegular() && (info.Mode().Perm()&0o111) != 0
}
// listFilesInDir lists all files in a directory
func listFilesInDir(dir string) ([]string, error) {
var files []string
entries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for _, entry := range entries {
if !entry.IsDir() {
files = append(files, dir+"/"+entry.Name())
}
}
return files, nil
}
func spawnProgressBar(contentLength int64) *progressbar.ProgressBar {
if UseProgressBar {
return progressbar.NewOptions(int(contentLength),
progressbar.OptionClearOnFinish(),
progressbar.OptionFullWidth(),
progressbar.OptionShowBytes(true),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "=",
SaucerHead: ">",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}),
)
}
return progressbar.NewOptions(-1,
progressbar.OptionSetWriter(io.Discard),
progressbar.OptionSetVisibility(false),
progressbar.OptionShowBytes(false),
)
}
// sanitizeString removes certain punctuation from the end of the string and converts it to lower case.
func sanitizeString(s string) string {
// Define the punctuation to remove
punctuation := []string{".", " ", ",", "!", "?"}
// Convert string to lower case
s = strings.ToLower(s)
// Remove specified punctuation from the end of the string
for _, p := range punctuation {
s = s[:len(s)-len(p)]
}
return s
}
// contanins will return true if the provided slice of []strings contains the word str
func contains(slice []string, str string) bool {
for _, v := range slice {
if v == str {
return true
}
}
return false
}
// errorEncoder generates a unique error code based on the sum of ASCII values of the error message.
func errorEncoder(format string, args ...interface{}) int {
formattedErrorMessage := fmt.Sprintf(format, args...)
var sum int
for _, char := range formattedErrorMessage {
sum += int(char)
}
errorCode := sum % 256
fmt.Fprint(os.Stderr, formattedErrorMessage)
return errorCode
}
// errorOut prints the error message to stderr and exits the program with the error code generated by errorEncoder.
func errorOut(format string, args ...interface{}) {
os.Exit(errorEncoder(format, args...))
}
// GetTerminalWidth attempts to determine the width of the terminal.
// It first tries using "stty size", then "tput cols", and finally falls back to 80 columns.
func getTerminalWidth() int {
// Try using stty size
cmd := exec.Command("stty", "size")
cmd.Stdin = os.Stdin
out, err := cmd.Output()
if err == nil {
// stty size returns rows and columns
parts := strings.Split(strings.TrimSpace(string(out)), " ")
if len(parts) == 2 {
width, _ := strconv.Atoi(parts[1])
return width
}
}
// Fallback to tput cols
cmd = exec.Command("tput", "cols")
cmd.Stdin = os.Stdin
out, err = cmd.Output()
if err == nil {
width, _ := strconv.Atoi(strings.TrimSpace(string(out)))
return width
}
// Fallback to 80 columns
return 80
}
// NOTE: \n will always get cut off when using a truncate function, this may also happen to other formatting options
// truncateSprintf formats the string and truncates it if it exceeds the terminal width.
func truncateSprintf(format string, a ...interface{}) string {
// Format the string first
formatted := fmt.Sprintf(format, a...)
// Determine the truncation length & truncate the formatted string if it exceeds the available space
availableSpace := getTerminalWidth() - len(indicator)
if len(formatted) > availableSpace {
formatted = formatted[:availableSpace]
for strings.HasSuffix(formatted, ",") || strings.HasSuffix(formatted, ".") || strings.HasSuffix(formatted, " ") {
formatted = formatted[:len(formatted)-1]
}
formatted = fmt.Sprintf("%s%s", formatted, indicator) // Add the dots.
}
return formatted
}
// truncatePrintf is a drop-in replacement for fmt.Printf that truncates the input string if it exceeds a certain length.
func truncatePrintf(format string, a ...interface{}) (n int, err error) {
if DisableTruncation {
return fmt.Printf(format, a...)
}
if AddNewLineToTruncateFn {
return fmt.Println(truncateSprintf(format, a...))
}
return fmt.Print(truncateSprintf(format, a...))
}
// validateProgramsFrom validates programs against the files in the specified directory against the remote binaries.
func validateProgramsFrom(InstallDir string, programsToValidate []string) ([]string, error) {
// Fetch the list of binaries from the remote source once
remotePrograms, err := listBinaries()
if err != nil {
return nil, fmt.Errorf("failed to list remote binaries: %w", err)
}
// List files from the specified directory
files, err := listFilesInDir(InstallDir)
if err != nil {
return nil, fmt.Errorf("failed to list files in %s: %w", InstallDir, err)
}
validPrograms := make([]string, 0)
invalidPrograms := make([]string, 0)
programsToValidate = removeDuplicates(programsToValidate)
// If programsToValidate is nil, validate all programs in the install directory
if programsToValidate == nil {
for _, file := range files {
// Extract the file name from the full path
fileName := filepath.Base(file)
if contains(remotePrograms, fileName) {
validPrograms = append(validPrograms, fileName)
} else {
invalidPrograms = append(invalidPrograms, fileName)
}
}
} else {
// Only check the ones specified in programsToValidate
for _, program := range programsToValidate {
if contains(remotePrograms, program) {
validPrograms = append(validPrograms, program)
} else {
invalidPrograms = append(invalidPrograms, program)
}
}
}
// Handle the list of programs received based on the last element
// If programsToValidate is not nil, handle based on the last element
return validPrograms, nil
}