diff --git a/cmd/insights/contributors.go b/cmd/insights/contributors.go index 1420f6a..171a6d8 100644 --- a/cmd/insights/contributors.go +++ b/cmd/insights/contributors.go @@ -1,7 +1,9 @@ package insights import ( + "bytes" "context" + "encoding/csv" "errors" "fmt" "net/http" @@ -134,11 +136,39 @@ func (cis contributorsInsightsSlice) BuildOutput(format string) (string, error) return utils.OutputJSON(cis) case constants.OutputYAML: return utils.OutputYAML(cis) + case constants.OuputCSV: + return cis.OutputCSV() default: return "", fmt.Errorf("unknown output format %s", format) } } +func (cis contributorsInsightsSlice) OutputCSV() (string, error) { + if len(cis) == 0 { + return "", fmt.Errorf("repository is either non-existent or has not been indexed yet") + } + b := new(bytes.Buffer) + writer := csv.NewWriter(b) + + // write headers + err := writer.WriteAll([][]string{{"Repository URL", "New Contributors", "Recent Contributors", "Alumni Contributors", "Repeat Contributors"}}) + if err != nil { + return "", err + } + + // write records + for _, ci := range cis { + err := writer.WriteAll([][]string{{ci.RepoURL, strconv.Itoa(len(ci.New)), strconv.Itoa(len(ci.Recent)), + strconv.Itoa(len(ci.Alumni)), strconv.Itoa(len(ci.Repeat))}}) + + if err != nil { + return "", err + } + } + + return b.String(), nil +} + func (cis contributorsInsightsSlice) OutputTable() (string, error) { tables := make([]string, 0, len(cis)) for i := range cis { diff --git a/pkg/constants/output.go b/pkg/constants/output.go index 3cdb360..652f9d2 100644 --- a/pkg/constants/output.go +++ b/pkg/constants/output.go @@ -4,4 +4,5 @@ const ( OutputJSON = "json" OutputTable = "table" OutputYAML = "yaml" + OuputCSV = "csv" )