Skip to content

Commit

Permalink
Finished writeFileTxt() and writeFileCsv()
Browse files Browse the repository at this point in the history
  • Loading branch information
crashdump committed Jul 31, 2023
1 parent f5db4d8 commit a26b319
Showing 1 changed file with 36 additions and 3 deletions.
39 changes: 36 additions & 3 deletions cmd/edmgen/cmd.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"encoding/csv"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -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
},
},
Expand Down Expand Up @@ -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
}

0 comments on commit a26b319

Please sign in to comment.