src

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

body-fat.go (1430B)


      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 )
     14 
     15 var BodyFat = &command{
     16 	execute: setBodyFat,
     17 
     18 	description: "set the user's body fat percentage on an entry",
     19 	help:        help.BodyFat,
     20 	name:        "body-fat",
     21 }
     22 
     23 func setBodyFat(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) == 0 {
     41 		return fmt.Errorf("missing body fat percentage")
     42 	}
     43 
     44 	bf, err := strconv.ParseFloat(args[0], 64)
     45 	if err != nil {
     46 		return err
     47 	}
     48 
     49 	e.BodyFat = bf
     50 
     51 	if err := store.UpdateEntry(e); err != nil {
     52 		return fmt.Errorf("failed to store entry: %w", err)
     53 	}
     54 
     55 	// If the entry is for today, update the user.
     56 	var currentDate = time.Now().Format(entry.DateFormat)
     57 	if currentDate == date.Format(entry.DateFormat) {
     58 		u.BodyFat = bf
     59 
     60 		if err := store.UpdateUser(u); err != nil {
     61 			return fmt.Errorf("failed to store user: %w", err)
     62 		}
     63 	}
     64 
     65 	fmt.Println(u.FormatPrint())
     66 
     67 	return nil
     68 }