From ebcd0375aab6676977c74e299775300e4e3b038a Mon Sep 17 00:00:00 2001 From: Miguel de la Cruz Date: Sat, 7 Mar 2020 11:11:40 +0100 Subject: [PATCH] Add import csv command --- cmd/add.go | 44 ++++++++++++++++++++++++++++++++++---------- cmd/status.go | 6 +++--- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/cmd/add.go b/cmd/add.go index f5223e4..e72079b 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -2,6 +2,7 @@ package cmd import ( "bufio" + "encoding/csv" "fmt" "os" "strconv" @@ -59,17 +60,13 @@ func GovetAddCmd() *cobra.Command { } func CsvAddCmd() *cobra.Command { - cmd := &cobra.Command{ + return &cobra.Command{ Use: "csv", Short: "Generates the tickets reading a csv file", - Example: ` campaigner add csv --file tickets.csv`, - Args: cobra.NoArgs, - RunE: csvAddCmdF, + Example: ` campaigner add csv tickets.csv`, + Args: cobra.ExactArgs(1), + Run: csvAddCmdF, } - - cmd.Flags().BoolP("file-only", "f", false, "Generates one ticket per file instead of per match") - - return cmd } func AddCmd() *cobra.Command { @@ -150,6 +147,33 @@ func govetAddCmdF(_ *cobra.Command, _ []string) error { return fmt.Errorf("not implemented yet") } -func csvAddCmdF(cmd *cobra.Command, _ []string) error { - return fmt.Errorf("not implemented yet") +func csvAddCmdF(cmd *cobra.Command, args []string) { + file, err := os.Open(args[0]) + if err != nil { + ErrorAndExit(cmd, err) + } + + cmp, err := campaign.Read() + if err != nil { + ErrorAndExit(cmd, err) + } + + csvReader := csv.NewReader(bufio.NewReader(file)) + records, err := csvReader.ReadAll() + if err != nil { + ErrorAndExit(cmd, err) + } + + headers := records[0] + for _, line := range records[1:] { + data := map[string]interface{}{} + for i, header := range headers { + data[header] = line[i] + } + cmp.Tickets = append(cmp.Tickets, &model.Ticket{Data: data}) + } + + if err := campaign.Save(cmp); err != nil { + ErrorAndExit(cmd, err) + } } diff --git a/cmd/status.go b/cmd/status.go index f865800..1c9905c 100644 --- a/cmd/status.go +++ b/cmd/status.go @@ -8,10 +8,10 @@ import ( func StatusCmd() *cobra.Command { return &cobra.Command{ - Use: "status", + Use: "status", Short: "Prints the current status of the campaign", - Args: cobra.NoArgs, - Run: statusCmdF, + Args: cobra.NoArgs, + Run: statusCmdF, } }