autorestic/internal/utils.go

85 lines
1.6 KiB
Go
Raw Normal View History

2021-04-09 01:55:10 +02:00
package internal
import (
"bytes"
"fmt"
2021-04-12 00:02:35 +02:00
"io"
2021-04-09 01:55:10 +02:00
"os"
"os/exec"
2021-04-17 13:04:40 +02:00
"github.com/cupcakearmy/autorestic/internal/colors"
2021-04-09 01:55:10 +02:00
)
2021-05-06 15:04:35 +02:00
var RESTIC_BIN string
2021-04-09 01:55:10 +02:00
func CheckIfCommandIsCallable(cmd string) bool {
_, err := exec.LookPath(cmd)
return err == nil
}
func CheckIfResticIsCallable() bool {
2021-05-06 15:04:35 +02:00
return CheckIfCommandIsCallable(RESTIC_BIN)
2021-04-09 01:55:10 +02: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
2021-04-17 13:04:40 +02:00
if VERBOSE {
colors.Faint.Printf("> Executing: %s\n", cmd)
}
2021-04-09 01:55:10 +02: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 15:04:35 +02:00
options.Command = RESTIC_BIN
2021-10-28 18:10:14 +02:00
var c = GetConfig()
var optionsAsString = getOptions(c.Global, "")
args = append(optionsAsString, args...)
2021-04-09 01:55:10 +02:00
return ExecuteCommand(options, args...)
}
2021-04-12 00:02:35 +02:00
func CopyFile(from, to string) error {
original, err := os.Open(from)
2021-04-12 00:02:35 +02:00
if err != nil {
return nil
}
defer original.Close()
new, err := os.Create(to)
2021-04-12 00:02:35 +02:00
if err != nil {
return nil
}
defer new.Close()
if _, err := io.Copy(new, original); err != nil {
return err
}
return nil
}
2021-10-31 22:32:01 +01:00
func CheckIfVolumeExists(volume string) bool {
2021-10-31 23:58:08 +01:00
_, err := ExecuteCommand(ExecuteOptions{Command: "docker"}, "volume", "inspect", volume)
2021-10-31 22:32:01 +01:00
return err == nil
}