autorestic/internal/utils.go

86 lines
1.7 KiB
Go
Raw Normal View History

2021-04-08 23:55:10 +00:00
package internal
import (
"bytes"
"fmt"
2021-04-11 22:02:35 +00:00
"io"
2021-04-08 23:55:10 +00:00
"os"
"os/exec"
2021-04-17 11:04:40 +00:00
"github.com/cupcakearmy/autorestic/internal/colors"
2022-02-16 20:42:54 +00:00
"github.com/cupcakearmy/autorestic/internal/flags"
2021-04-08 23:55:10 +00:00
)
2021-05-06 13:04:35 +00:00
var RESTIC_BIN string
2021-04-08 23:55:10 +00:00
func CheckIfCommandIsCallable(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
func CheckIfResticIsCallable() bool {
2021-05-06 13:04:35 +00:00
return CheckIfCommandIsCallable(RESTIC_BIN)
2021-04-08 23:55:10 +00:00
}
type ExecuteOptions struct {
Command string
Envs map[string]string
Dir string
}
func ExecuteCommand(options ExecuteOptions, args ...string) (string, error) {
cmd := exec.Command(options.Command, args...)
env := os.Environ()
for k, v := range options.Envs {
env = append(env, fmt.Sprintf("%s=%s", k, v))
}
cmd.Env = env
cmd.Dir = options.Dir
2022-02-16 20:42:54 +00:00
if flags.VERBOSE {
2021-04-17 11:04:40 +00:00
colors.Faint.Printf("> Executing: %s\n", cmd)
}
2021-04-08 23:55:10 +00:00
var out bytes.Buffer
var error bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &error
err := cmd.Run()
if err != nil {
return error.String(), err
}
return out.String(), nil
}
func ExecuteResticCommand(options ExecuteOptions, args ...string) (string, error) {
2021-05-06 13:04:35 +00:00
options.Command = RESTIC_BIN
2021-10-28 16:10:14 +00:00
var c = GetConfig()
var optionsAsString = getOptions(c.Global, "")
args = append(optionsAsString, args...)
2021-04-08 23:55:10 +00:00
return ExecuteCommand(options, args...)
}
2021-04-11 22:02:35 +00:00
func CopyFile(from, to string) error {
original, err := os.Open(from)
2021-04-11 22:02:35 +00:00
if err != nil {
return nil
}
defer original.Close()
new, err := os.Create(to)
2021-04-11 22:02:35 +00:00
if err != nil {
return nil
}
defer new.Close()
if _, err := io.Copy(new, original); err != nil {
return err
}
return nil
}
2021-10-31 21:32:01 +00:00
func CheckIfVolumeExists(volume string) bool {
2021-10-31 22:58:08 +00:00
_, err := ExecuteCommand(ExecuteOptions{Command: "docker"}, "volume", "inspect", volume)
2021-10-31 21:32:01 +00:00
return err == nil
}