src

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

weight.go (1532B)


      1 package command
      2 
      3 import (
      4 	"errors"
      5 	"fmt"
      6 	"os"
      7 	"strconv"
      8 	"time"
      9 
     10 	"code.dwrz.net/src/pkg/dqs/command/help"
     11 	"code.dwrz.net/src/pkg/dqs/entry"
     12 	"code.dwrz.net/src/pkg/dqs/store"
     13 	"code.dwrz.net/src/pkg/dqs/user/units"
     14 )
     15 
     16 var Weight = &command{
     17 	execute: setWeight,
     18 
     19 	description: "set the user's weight on an entry",
     20 	help:        help.Weight,
     21 	name:        "weight",
     22 }
     23 
     24 func setWeight(args []string, date time.Time, store *store.Store) error {
     25 	u, err := store.GetUser()
     26 	if err != nil && !errors.Is(err, os.ErrNotExist) {
     27 		return fmt.Errorf("failed to get user: %w", err)
     28 	}
     29 	if u == nil {
     30 		return Config.execute(args, date, store)
     31 	}
     32 
     33 	e, err := store.GetEntry(date.Format(entry.DateFormat))
     34 	if err != nil && !errors.Is(err, os.ErrNotExist) {
     35 		return fmt.Errorf("failed to get entry: %w", err)
     36 	}
     37 	if e == nil {
     38 		e = entry.New(date, u)
     39 	}
     40 
     41 	if len(args) == 0 {
     42 		return fmt.Errorf("missing weight")
     43 	}
     44 
     45 	w, err := strconv.ParseFloat(args[0], 64)
     46 	if err != nil {
     47 		return err
     48 	}
     49 
     50 	// Store all units in metric.
     51 	if u.Units == units.Imperial {
     52 		w = units.PoundsToKilogram(w)
     53 	}
     54 
     55 	e.Weight = w
     56 
     57 	if err := store.UpdateEntry(e); err != nil {
     58 		return fmt.Errorf("failed to store entry: %w", err)
     59 	}
     60 
     61 	// If the entry is for today, update the user.
     62 	var currentDate = time.Now().Format(entry.DateFormat)
     63 	if currentDate == date.Format(entry.DateFormat) {
     64 		u.Weight = w
     65 
     66 		if err := store.UpdateUser(u); err != nil {
     67 			return fmt.Errorf("failed to store user: %w", err)
     68 		}
     69 	}
     70 
     71 	fmt.Println(u.FormatPrint())
     72 
     73 	return nil
     74 }