github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/cli/opts/duration.go (about)

     1  package opts
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/pkg/errors"
     7  )
     8  
     9  // PositiveDurationOpt is an option type for time.Duration that uses a pointer.
    10  // It behave similarly to DurationOpt but only allows positive duration values.
    11  type PositiveDurationOpt struct {
    12  	DurationOpt
    13  }
    14  
    15  // Set a new value on the option. Setting a negative duration value will cause
    16  // an error to be returned.
    17  func (d *PositiveDurationOpt) Set(s string) error {
    18  	err := d.DurationOpt.Set(s)
    19  	if err != nil {
    20  		return err
    21  	}
    22  	if *d.DurationOpt.value < 0 {
    23  		return errors.Errorf("duration cannot be negative")
    24  	}
    25  	return nil
    26  }
    27  
    28  // DurationOpt is an option type for time.Duration that uses a pointer. This
    29  // allows us to get nil values outside, instead of defaulting to 0
    30  type DurationOpt struct {
    31  	value *time.Duration
    32  }
    33  
    34  // NewDurationOpt creates a DurationOpt with the specified duration
    35  func NewDurationOpt(value *time.Duration) *DurationOpt {
    36  	return &DurationOpt{
    37  		value: value,
    38  	}
    39  }
    40  
    41  // Set a new value on the option
    42  func (d *DurationOpt) Set(s string) error {
    43  	v, err := time.ParseDuration(s)
    44  	d.value = &v
    45  	return err
    46  }
    47  
    48  // Type returns the type of this option, which will be displayed in `--help` output
    49  func (d *DurationOpt) Type() string {
    50  	return "duration"
    51  }
    52  
    53  // String returns a string repr of this option
    54  func (d *DurationOpt) String() string {
    55  	if d.value != nil {
    56  		return d.value.String()
    57  	}
    58  	return ""
    59  }
    60  
    61  // Value returns the time.Duration
    62  func (d *DurationOpt) Value() *time.Duration {
    63  	return d.value
    64  }