From 339c1214bbeacaa440a979b930567a9edfd3694d Mon Sep 17 00:00:00 2001 From: Adis Durakovic Date: Fri, 8 Mar 2024 14:01:14 +0100 Subject: [PATCH] chore: refactoring --- restic.go | 70 +++++++++++++++++++++++++++++++++---------------------- 1 file changed, 42 insertions(+), 28 deletions(-) diff --git a/restic.go b/restic.go index e8fdd3a..017f39a 100644 --- a/restic.go +++ b/restic.go @@ -27,33 +27,8 @@ func NewRestic(errb *bytes.Buffer, outb *bytes.Buffer, settings *Settings) *Rest return r } -func (r *Restic) core( - repository Repository, - cmd []string, - envs []string, - ctx *context.Context, - cancel *context.CancelFunc, - ch *chan string, -) (string, error) { - - cmds := []string{"-r", repository.Path, "--json"} - cmds = append(cmds, cmd...) - var sout bytes.Buffer - var serr bytes.Buffer - var c *exec.Cmd - - if ctx != nil { - c = exec.CommandContext(*ctx, "/usr/bin/restic", cmds...) - if cancel != nil { - - defer (*cancel)() - } - } else { - c = exec.Command("/usr/bin/restic", cmds...) - } +func (r *Restic) PipeOutErr(c *exec.Cmd, sout *bytes.Buffer, serr *bytes.Buffer, ch *chan string) { stdout, err := c.StdoutPipe() - stderr, err := c.StderrPipe() - if err == nil { go func() { scanner := bufio.NewScanner(stdout) @@ -68,6 +43,13 @@ func (r *Restic) core( sout.WriteString(scanner.Text()) } }() + + } + + stderr, err := c.StderrPipe() + + if err == nil { + go func() { scanner := bufio.NewScanner(stderr) scanner.Split(bufio.ScanLines) @@ -82,7 +64,9 @@ func (r *Restic) core( } }() } +} +func (r *Restic) getEnvs(repository Repository, envs []string) []string { envs = append( envs, []string{"RESTIC_PASSWORD=" + repository.Password, "RESTIC_PROGRESS_FPS=5"}...) @@ -94,7 +78,6 @@ func (r *Restic) core( "AWS_SECRET_ACCESS_KEY=" + repository.Options.S3Secret, }...) } - if repository.Type == "azure" { envs = append( envs, @@ -113,7 +96,38 @@ func (r *Restic) core( "GOOGLE_APPLICATION_CREDENTIALS=" + repository.Options.GoogleApplicationCredentials, }...) } + return envs + +} + +func (r *Restic) core( + repository Repository, + cmd []string, + envs []string, + ctx *context.Context, + cancel *context.CancelFunc, + ch *chan string, +) (string, error) { + + cmds := []string{"-r", repository.Path, "--json"} + cmds = append(cmds, cmd...) + var sout bytes.Buffer + var serr bytes.Buffer + var c *exec.Cmd + + if ctx != nil { + c = exec.CommandContext(*ctx, "/usr/bin/restic", cmds...) + if cancel != nil { + + defer (*cancel)() + } + } else { + c = exec.Command("/usr/bin/restic", cmds...) + } + + r.PipeOutErr(c, &sout, &serr, ch) + envs = r.getEnvs(repository, envs) log.Info("core", "repo", repository.Path, "cmd", cmd, "envs", envs) c.Env = append( @@ -121,7 +135,7 @@ func (r *Restic) core( envs..., ) - err = c.Start() + err := c.Start() if err != nil { log.Error("executing restic command", "err", err) }