From 9a3f4a3c61a1f579be68b2ff0c9d58a5b5d07cd2 Mon Sep 17 00:00:00 2001 From: Fabio Forni Date: Thu, 23 Nov 2023 13:33:21 +0100 Subject: [PATCH] stepwriter: Add DryRun --- installer/stepwriter/dryrun.go | 78 ++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 installer/stepwriter/dryrun.go diff --git a/installer/stepwriter/dryrun.go b/installer/stepwriter/dryrun.go new file mode 100644 index 0000000..3276980 --- /dev/null +++ b/installer/stepwriter/dryrun.go @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: Fabio Forni +// SPDX-License-Identifier: MPL-2.0 + +package stepwriter + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" + + "github.com/livingsilver94/backee/installer" + "github.com/livingsilver94/backee/service" +) + +var ( + buf = &strings.Builder{} +) + +type DryRun struct{} + +func (DryRun) Setup(script string) error { + return printMultiline(strings.NewReader(script)) +} + +func (DryRun) InstallPackages(fullCmd []string) error { + return printf("Will run %q", strings.Join(fullCmd, " ")) +} + +func (DryRun) SymlinkFile(dst service.FilePath, src string) error { + defer buf.Reset() + fmt.Fprintf(buf, "%s → %s", src, dst.Path) + if dst.Mode != 0 { + fmt.Fprintf(buf, " with permission %o", dst.Mode) + } + return printLine(buf.String()) +} + +func (DryRun) CopyFile(dst service.FilePath, src installer.FileCopy) error { + defer buf.Reset() + fmt.Fprintf(buf, "Will write %s", dst.Path) + if dst.Mode != 0 { + fmt.Fprintf(buf, " with permission %o", dst.Mode) + } + buf.WriteString(" with the following content:") + err := printLine(buf.String()) + if err != nil { + return err + } + _, err = src.WriteTo(os.Stdout) + return err +} + +func (DryRun) Finalize(script string) error { + return printMultiline(strings.NewReader(script)) +} + +func printLine(str string) error { + _, err := fmt.Println("\t" + str) + return err +} + +func printMultiline(read io.Reader) error { + lines := bufio.NewScanner(read) + for lines.Scan() { + err := printLine(lines.Text()) + if err != nil { + return err + } + } + return nil +} + +func printf(format string, args ...any) error { + _, err := fmt.Printf("\t"+format+"\n", args) + return err +}