go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/flag/reltime.go (about)

     1  // Copyright 2019 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package flag
    16  
    17  import (
    18  	"strconv"
    19  	"time"
    20  
    21  	"go.chromium.org/luci/common/errors"
    22  )
    23  
    24  // RelativeTime is an implementation of flag.Value for parsing a time
    25  // by a relative day offset.
    26  type RelativeTime struct {
    27  	T   *time.Time
    28  	now func() time.Time
    29  }
    30  
    31  // String implements the flag.Value interface.
    32  func (f RelativeTime) String() string {
    33  	if f.T == nil {
    34  		return "<empty>"
    35  	}
    36  	return f.T.Format(time.RFC1123Z)
    37  }
    38  
    39  // Set implements the flag.Value interface.
    40  func (f RelativeTime) Set(s string) error {
    41  	if f.T == nil {
    42  		return errors.Reason("set RelativeTime: nil time pointer").Err()
    43  	}
    44  	n, err := strconv.Atoi(s)
    45  	if err != nil {
    46  		return errors.Annotate(err, "set RelativeTime").Err()
    47  	}
    48  	if f.now == nil {
    49  		f.now = time.Now
    50  	}
    51  	*f.T = f.now().Add(time.Duration(n*24) * time.Hour)
    52  	return nil
    53  }