2020-03-22 11:01:27 +03:00
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2020-03-28 05:16:45 +03:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2020-03-22 11:42:35 +03:00
|
|
|
"os"
|
2020-03-22 11:01:27 +03:00
|
|
|
"os/exec"
|
2020-03-29 10:41:10 +03:00
|
|
|
"strconv"
|
2020-03-22 11:01:27 +03:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-03-29 10:41:10 +03:00
|
|
|
// SafeParseInt64 ...
|
|
|
|
func SafeParseInt64(s string, d int64) int64 {
|
|
|
|
n, err := strconv.ParseInt(s, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return d
|
|
|
|
}
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
|
2020-03-28 05:16:45 +03:00
|
|
|
func Download(url, filename string) error {
|
|
|
|
res, err := http.Get(url)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
|
|
|
data, err := ioutil.ReadAll(res.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := ioutil.WriteFile(filename, data, 0644); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-03-22 11:42:35 +03:00
|
|
|
// FileExists ...
|
|
|
|
func FileExists(name string) bool {
|
|
|
|
if _, err := os.Stat(name); err != nil {
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2020-03-22 11:01:27 +03:00
|
|
|
// CmdExists ...
|
|
|
|
func CmdExists(cmd string) bool {
|
|
|
|
_, err := exec.LookPath(cmd)
|
|
|
|
return err == nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RunCmd ...
|
|
|
|
func RunCmd(timeout int, command string, args ...string) error {
|
2020-03-29 14:11:32 +03:00
|
|
|
var (
|
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
|
|
|
)
|
|
|
|
|
|
|
|
if timeout > 0 {
|
|
|
|
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
|
|
|
|
} else {
|
|
|
|
ctx, cancel = context.WithCancel(context.Background())
|
|
|
|
}
|
2020-03-22 11:01:27 +03:00
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
cmd := exec.CommandContext(ctx, command, args...)
|
|
|
|
|
|
|
|
out, err := cmd.CombinedOutput()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("cmd.CombinedOutput error: %w\n%s", err, out)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|