From f7a2922d7d21832b00f96333018d9975007e8cc0 Mon Sep 17 00:00:00 2001 From: Steven Polley Date: Tue, 5 Nov 2024 21:54:16 -0700 Subject: [PATCH] add flag to output to file --- main.go | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/main.go b/main.go index e80efc6..e0c44a6 100644 --- a/main.go +++ b/main.go @@ -1,12 +1,11 @@ package main import ( - "bytes" "encoding/csv" "flag" "fmt" - "io" "log" + "os" "sort" "strconv" "time" @@ -21,6 +20,8 @@ func init() { func main() { cfAPIKey := flag.String("cfapikey", "", "in cf, my profile -> API Tokens -> Create Token") + onlyZone := flag.String("onlyZone", "", "if specified, only the zone with this name will be processed. If omitted, all zones will be processed") + outFile := flag.String("outFile", "cfcleaner.csv", "the path of the output file") flag.Parse() if *cfAPIKey == "" { @@ -38,6 +39,9 @@ func main() { outRows := make([]cf.Record, 0) for _, zone := range zones { + if *onlyZone != "" && zone.Name != *onlyZone { + continue + } log.Printf("processing zone '%s' with ID '%s'", zone.Name, zone.ID) records, err := cfClient.GetRecords(zone) @@ -60,20 +64,25 @@ func main() { return outRows[i].NumberQueries < outRows[j].NumberQueries }) - buf := bytes.NewBuffer(nil) - writer := csv.NewWriter(buf) - writer.Write([]string{"Name", "Type", "NumberQueries", "CreatedOn", "ModifiedOn", "Comment", "Content"}) + f, err := os.OpenFile(*outFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0600) + if err != nil { + log.Fatalf("failed to open output file '%s': %v", *outFile, err) + } + defer f.Close() + + writer := csv.NewWriter(f) + defer writer.Flush() + err = writer.Write([]string{"Name", "Type", "NumberQueries", "CreatedOn", "ModifiedOn", "Comment", "Content"}) + if err != nil { + log.Fatalf("failed to write to outFile: %v", err) + } for _, row := range outRows { - writer.Write([]string{row.Name, row.Type, strconv.Itoa(row.NumberQueries), row.CreatedOn.Format(time.RFC3339), row.ModifiedOn.Format(time.RFC3339), row.Comment, row.Content}) - } - writer.Flush() - - b, err := io.ReadAll(buf) - if err != nil { - log.Fatalf("failed to read bytes from output buffer: %v", err) + err = writer.Write([]string{row.Name, row.Type, strconv.Itoa(row.NumberQueries), row.CreatedOn.Format(time.RFC3339), row.ModifiedOn.Format(time.RFC3339), row.Comment, row.Content}) + if err != nil { + log.Fatalf("failed to write to outFile: %v", err) + } } - fmt.Println(string(b)) - + fmt.Printf("wrote to file: %s\n", *outFile) }