main.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8. func main() {
  9. op := flag.String("op", "sum", "Operation to be executed")
  10. column := flag.Int("col", 1, "CSV column on which to execute operation")
  11. flag.Parse()
  12. if err := run(flag.Args(), *op, *column, os.Stdout); err != nil {
  13. _, err := fmt.Fprintln(os.Stderr, err)
  14. if err != nil {
  15. return
  16. }
  17. os.Exit(1)
  18. }
  19. }
  20. func run(filenames []string, op string, column int, out io.Writer) error {
  21. var opFunc statsFunc
  22. if len(filenames) == 0 {
  23. return ErrNoFiles
  24. }
  25. if column < 1 {
  26. return fmt.Errorf("%w: %d", ErrInvalidColumn, column)
  27. }
  28. switch op {
  29. case "sum":
  30. opFunc = sum
  31. case "avg":
  32. opFunc = avg
  33. default:
  34. return fmt.Errorf("%w: %s", ErrInvalidOperation, op)
  35. }
  36. consolidate := make([]float64, 0)
  37. // Loop through all files adding their data to consolidate
  38. for _, fname := range filenames {
  39. // Open the file for reading
  40. f, err := os.Open(fname)
  41. if err != nil {
  42. return fmt.Errorf("cannot open file: %w", err)
  43. }
  44. // Parse the CSV into a slice of float64 numbers
  45. data, err := csv2float(f, column)
  46. if err != nil {
  47. return err
  48. }
  49. if err := f.Close(); err != nil {
  50. return err
  51. }
  52. // Append the data to consolidate
  53. consolidate = append(consolidate, data...)
  54. }
  55. _, err := fmt.Fprintln(out, opFunc(consolidate))
  56. return err
  57. }