fix(set): removed manual ttl parsing in favour of the .Duration() flag i didn't know existed

This commit is contained in:
Lewis Wynne 2025-11-07 19:52:06 +00:00
parent 6c6bd1adc1
commit a86100e045

View file

@ -22,10 +22,7 @@ THE SOFTWARE.
package cmd package cmd
import ( import (
"fmt"
"io" "io"
"strings"
"time"
"github.com/dgraph-io/badger/v4" "github.com/dgraph-io/badger/v4"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -57,20 +54,10 @@ func set(cmd *cobra.Command, args []string) error {
if err != nil { if err != nil {
return err return err
} }
ttlRaw, err := cmd.Flags().GetString("ttl") ttl, err := cmd.Flags().GetDuration("ttl")
if err != nil { if err != nil {
return err return err
} }
var ttl time.Duration
if strings.TrimSpace(ttlRaw) != "" {
ttl, err = time.ParseDuration(ttlRaw)
if err != nil {
return fmt.Errorf("invalid ttl %q: %w", ttlRaw, err)
}
if ttl <= 0 {
return fmt.Errorf("ttl must be greater than zero")
}
}
trans := TransactionArgs{ trans := TransactionArgs{
key: args[0], key: args[0],
@ -81,7 +68,7 @@ func set(cmd *cobra.Command, args []string) error {
if secret { if secret {
entry = entry.WithMeta(metaSecret) entry = entry.WithMeta(metaSecret)
} }
if ttlRaw != "" { if ttl != 0 {
entry = entry.WithTTL(ttl) entry = entry.WithTTL(ttl)
} }
return tx.SetEntry(entry) return tx.SetEntry(entry)
@ -94,5 +81,5 @@ func set(cmd *cobra.Command, args []string) error {
func init() { func init() {
rootCmd.AddCommand(setCmd) rootCmd.AddCommand(setCmd)
setCmd.Flags().Bool("secret", false, "Mark the stored value as a secret") setCmd.Flags().Bool("secret", false, "Mark the stored value as a secret")
setCmd.Flags().String("ttl", "", "Expire the key after the provided duration (e.g. 24h, 30m)") setCmd.Flags().DurationP("ttl", "t", 0, "Expire the key after the provided duration (e.g. 24h, 30m)")
} }