package dirtoexcel import ( "fmt" "math" "os" "regexp" "strconv" "time" "github.com/lmittmann/tint" "github.com/spf13/cobra" "github.com/xuri/excelize/v2" "golang.org/x/exp/slog" ) const re = `^(?P[a-zA-Z0-9-]+)(?:_[a-zA-Z]+)?_(?P\d+\.\d{1,2})` func init() { slog.SetDefault(slog.New(tint.Options{ Level: slog.LevelDebug, TimeFormat: time.Kitchen, }.NewHandler(os.Stderr))) } func Run(cmd *cobra.Command, args []string) { outfile, err := cmd.Flags().GetString("out") if err != nil { slog.Error("failed to get outfile string", "error", err) os.Exit(1) } if outfile == "" { outfile = fmt.Sprintf("%d.xlsx", time.Now().Unix()) } if err := Create(outfile, args[0]); err != nil { slog.Error("failed to create excel", "error", err) os.Exit(1) } } func Create(out, dir string) error { log := slog.With("dir", dir, "out", out) f := excelize.NewFile() defer func() { if err := f.Close(); err != nil { log.Error("failed to close excel file") } }() files, err := os.ReadDir(dir) if err != nil { return fmt.Errorf("failed to read dir: %w", err) } r, err := regexp.Compile(re) if err != nil { return fmt.Errorf("failed to compile regex: %w", err) } for i, j := range files { if j.IsDir() { continue } log.Info("found", "file", j.Name()) res := r.FindAllStringSubmatch(j.Name(), -1) if res == nil { return fmt.Errorf("nothing found") } if len(res) != 1 || len(res[0]) != 3 { return fmt.Errorf("strange numbers of matches") } company := res[0][1] log.Debug("extracted", slog.String("company", company)) if err := f.SetCellStr("Sheet1", fmt.Sprintf("A%d", i+1), company); err != nil { return fmt.Errorf("failed to set cell: %w", err) } value, err := strconv.ParseFloat(res[0][2], 32) if err != nil { return fmt.Errorf("failed to parse value: %w", err) } rValue := math.Round(value*100) / 100 log.Debug("extracted", slog.Float64("value", rValue)) if err := f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+1), rValue); err != nil { return fmt.Errorf("failed to set cell: %w", err) } } if err := f.SaveAs(out); err != nil { return fmt.Errorf("failed to save excel: %w", err) } log.Info("created excel") return nil }