grafana / unused

CLI tool, Prometheus exporter, and Go module to list your unused disks in all cloud providers
Apache License 2.0
52 stars 1 forks source link

Add csv_export command #52

Closed fedordikarev closed 4 months ago

fedordikarev commented 1 year ago

Closes: https://github.com/grafana/unused/issues/51

This is proof-of-concept solution to actually test that idea. I added here csv_export as separate ui as I don't found yet how to make it with nice and clear code: switch between csv and tabWriter in Table functions.

Lets discuss is it a good idea or not, should we keep it as separate ui or restructure a bit. @inkel what do you think?

inkel commented 1 year ago

Hey @fedordikarev nice idea! I believe there's value for this, but I don't think it warrants a new CsvExport function.

I was looking at the code and both CsvExport and GroupTable and they are almost equal but only differ in a few places, so I think the easiest to make it nice and clean would be to introduce a new interface and implementations like the following:

type TableWriter interface {
    Write([]string) error
    Flush() error
}

type TabWriter struct {
    w *tabwriter.Writer
}

func NewTabWriter(w io.Writer) TabWriter {
    return &TabWriter{
        w: tabwriter.NewWriter(w, 8, 4, 2, ' ', 0),
    }
}

func (w *TabWriter) Write(row []string) error {
    _, err := fmt.Fprintln(w.w, strings.Join(row, "\t"))
    return err
}

func (w *TabWriter) Flush() error {
    return w.w.Flush()
}

type CSVWriter struct {
    w *csv.Writer
}

func NewCSVWriter(w io.Writer) TabWriter {
    return &CSVWriter{
        w: csv.NewWriter(w),
    }
}

func (w *CSVWriter) Write(row []string) error {
    return w.w.Write(row)
}

func (w *CSVWriter) Flush() error {
    if err := w.w.Error(); err != nil {
        return err
    }
    return w.w.Flush()
}

Then we can change the Table function to accept an additional parameter and change the calls to fmt.Fprintln with calls to TabWriter.Write:

func Table(ctx context.Context, w TableWriter, options Options) error {
   // …existing code…
}

Last but not least, in main.go we would need to adjust it to support either versions (there are a few more changes missing). And now we can remove CsvExport.

What do you think? I'm happy to help.

inkel commented 4 months ago

This isn't required anymore for now, so we're closing it for now.