98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package dirtoexcel
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/charmbracelet/log"
|
|
"github.com/spf13/cobra"
|
|
"github.com/xuri/excelize/v2"
|
|
)
|
|
|
|
const re = `^(?P<company>[a-zA-Z0-9-]+)(?:_[a-zA-Z]+)?_(?P<value>\d+\.\d{1,2})`
|
|
|
|
func init() {
|
|
log.SetDefault(
|
|
log.NewWithOptions(os.Stderr, log.Options{ReportTimestamp: true, TimeFormat: time.Kitchen}),
|
|
)
|
|
}
|
|
|
|
func Run(cmd *cobra.Command, args []string) {
|
|
outfile, err := cmd.Flags().GetString("out")
|
|
if err != nil {
|
|
log.Fatal("failed to get outfile string", "error", err)
|
|
}
|
|
|
|
if outfile == "" {
|
|
outfile = fmt.Sprintf("%d.xlsx", time.Now().Unix())
|
|
}
|
|
|
|
if err := Create(outfile, args[0]); err != nil {
|
|
log.Fatal("failed to create excel", "error", err)
|
|
}
|
|
}
|
|
|
|
func Create(out, dir string) error {
|
|
log := log.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")
|
|
}
|
|
|
|
if err := f.SetCellStr("Sheet1", fmt.Sprintf("A%d", i+1), res[0][1]); 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)
|
|
}
|
|
|
|
if err := f.SetCellValue("Sheet1", fmt.Sprintf("B%d", i+1), math.Round(value*100)/100); 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
|
|
}
|