/
helpers.go
122 lines (107 loc) · 2.69 KB
/
helpers.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
/*
* Quick Script Runner: A quick and easy way to run gists
* Copyright © 2020 Brett Bender
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package cmd
import (
"bufio"
"fmt"
"github.com/go-cmd/cmd"
"github.com/ttacon/chalk"
"io"
"log"
"net/http"
"os"
"strings"
)
func DownloadFile(filepath string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
return err
}
func CheckError(err error) bool {
if err != nil {
if strings.Contains(err.Error(), "executable file not found") {
fmt.Println(NewMessage(chalk.Red, "That language isn't supported on your system!"))
return true
}
fmt.Println(NewMessage(chalk.Red, err.Error()).String())
return true
}
return false
}
func RunCommand(executable string, args ...string) error {
// Create Cmd with options
cmO := cmd.Options{
Buffered: false,
Streaming: true,
}
envCmd := cmd.NewCmdOptions(cmO, executable, args...)
// Print STDOUT and STDERR lines streaming from Cmd
doneChan := make(chan struct{})
go func() {
defer close(doneChan)
for envCmd.Stdout != nil || envCmd.Stderr != nil {
select {
case line, open := <-envCmd.Stdout:
if !open {
envCmd.Stdout = nil
continue
}
fmt.Println(line)
case line, open := <-envCmd.Stderr:
if !open {
envCmd.Stderr = nil
continue
}
fmt.Fprintln(os.Stderr, line)
}
}
}()
// Run and wait for Cmd to return, discard Status
stat := <-envCmd.Start()
// Wait for goroutine to print everything
<-doneChan
return stat.Error
}
func getFirstLine(path string) (string, error) {
buf, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer func() {
if err = buf.Close(); err != nil {
log.Fatal(err)
}
}()
snl := bufio.NewScanner(buf)
snl.Scan()
txt := snl.Text()
if err := snl.Err(); err != nil {return "", err}
return txt, nil
}