remove.go (1502B)
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 Remove = &command{ 16 execute: removePortions, 17 18 description: "remove portions from an entry", 19 help: help.Remove, 20 name: "remove", 21 } 22 23 func removePortions(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.Remove(q); err != nil { 62 return fmt.Errorf( 63 "failed to remove 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 }