src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

add.go (1476B)


      1 package command
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"os"
      7 	"time"
      8 
      9 	"code.dwrz.net/src/pkg/dqs/command/help"
     10 	"code.dwrz.net/src/pkg/dqs/entry"
     11 	"code.dwrz.net/src/pkg/dqs/portion"
     12 	"code.dwrz.net/src/pkg/dqs/store"
     13 )
     14 
     15 var Add = &command{
     16 	execute: addPortions,
     17 
     18 	description: "add portions to an entry",
     19 	help:        help.Add,
     20 	name:        "add",
     21 }
     22 
     23 func addPortions(args []string, date time.Time, store *store.Store) error {
     24 	u, err := store.GetUser()
     25 	if err != nil && !errors.Is(err, os.ErrNotExist) {
     26 		return fmt.Errorf("failed to get user: %w", err)
     27 	}
     28 	if u == nil {
     29 		return Config.execute(args, date, store)
     30 	}
     31 
     32 	e, err := store.GetEntry(date.Format(entry.DateFormat))
     33 	if err != nil && !errors.Is(err, os.ErrNotExist) {
     34 		return fmt.Errorf("failed to get entry: %w", err)
     35 	}
     36 	if e == nil {
     37 		e = entry.New(date, u)
     38 	}
     39 
     40 	if len(args) < 2 {
     41 		return fmt.Errorf("missing category and quantity")
     42 	}
     43 	if len(args)%2 != 0 {
     44 		return fmt.Errorf("uneven number of arguments")
     45 	}
     46 
     47 	for i := 0; i < len(args); i += 2 {
     48 		portionCategory := args[i]
     49 		quantity := args[i+1]
     50 
     51 		c, err := e.Category(portionCategory)
     52 		if err != nil {
     53 			return err
     54 		}
     55 
     56 		q, err := portion.Parse(quantity)
     57 		if err != nil {
     58 			return err
     59 		}
     60 
     61 		if err := c.Add(q); err != nil {
     62 			return fmt.Errorf(
     63 				"failed to add portions: %w", err,
     64 			)
     65 		}
     66 	}
     67 
     68 	if err := store.UpdateEntry(e); err != nil {
     69 		return fmt.Errorf("failed to store entry: %w", err)
     70 	}
     71 
     72 	fmt.Println(e.FormatPrint(u))
     73 
     74 	return nil
     75 }