From a26b319610bfeba909d4fd306b46e8ce8d3799bc Mon Sep 17 00:00:00 2001 From: Adrien Pujol Date: Mon, 31 Jul 2023 13:28:56 +0400 Subject: [PATCH] Finished writeFileTxt() and writeFileCsv() --- cmd/edmgen/cmd.go | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/cmd/edmgen/cmd.go b/cmd/edmgen/cmd.go index c917e23..0493d8d 100644 --- a/cmd/edmgen/cmd.go +++ b/cmd/edmgen/cmd.go @@ -1,6 +1,7 @@ package main import ( + "encoding/csv" "errors" "fmt" "os" @@ -60,9 +61,13 @@ func main() { Destination: &flagFormat, Action: func(ctx *cli.Context, v string) error { formats := []string{STDOUT, "csv", "txt"} - if slices.Contains[[]string](formats, flagFormat) { + if !slices.Contains[[]string](formats, flagFormat) { return fmt.Errorf("output %s not currently supported", flagFormat) } + if flagOutput == "" { + logger.print("You need to specify a file output (-o) when selecting specific formats") + os.Exit(1) + } return nil }, }, @@ -152,10 +157,38 @@ func writeStdout(lines []string) { } } -func writeFileTxt(filename string, lines []string) { +func writeFileTxt(filename string, lines []string) error { + f, err := os.Create(filename) + defer f.Close() + if err != nil { + return fmt.Errorf("failed to create file: %s", err) + } + + for _, line := range lines { + _, err := f.WriteString(line + "\n") + if err != nil { + return fmt.Errorf("error writing record to file: %s", err) + } + } + return nil } -func writeFileCsv(filename string, lines []string) { +func writeFileCsv(filename string, lines []string) error { + f, err := os.Create(filename) + defer f.Close() + if err != nil { + return fmt.Errorf("failed to create file: %s", err) + } + + w := csv.NewWriter(f) + defer w.Flush() + + for _, line := range lines { + if err := w.Write([]string{line}); err != nil { + return fmt.Errorf("error writing record to file: %s", err) + } + } + return nil }