Skip to content

Instantly share code, notes, and snippets.

@drov0
Created December 4, 2019 18:14
Show Gist options
  • Save drov0/5f561a1254a1aac46ac1b336f36a499d to your computer and use it in GitHub Desktop.
Save drov0/5f561a1254a1aac46ac1b336f36a499d to your computer and use it in GitHub Desktop.
timestamp flag
package cli
import (
"flag"
"fmt"
"time"
"github.com/golang/protobuf/ptypes"
protoTimestamp "github.com/golang/protobuf/ptypes/timestamp"
)
// TimestampFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration)
type TimestampFlag struct {
Name string
Aliases []string
Usage string
EnvVars []string
FilePath string
Required bool
Hidden bool
Value protoTimestamp.Timestamp
DefaultText string
HasBeenSet bool
}
// IsSet returns whether or not the flag has been set through env or file
func (f *TimestampFlag) IsSet() bool {
return f.HasBeenSet
}
// String returns a readable representation of this value
// (for usage defaults)
func (f *TimestampFlag) String() string {
return FlagStringer(f)
}
// Names returns the names of the flag
func (f *TimestampFlag) Names() []string {
return flagNames(f)
}
// IsRequired returns whether or not the flag is required
func (f *TimestampFlag) IsRequired() bool {
return f.Required
}
// TakesValue returns true of the flag takes a value, otherwise false
func (f *TimestampFlag) TakesValue() bool {
return true
}
// GetUsage returns the usage string for the flag
func (f *TimestampFlag) GetUsage() string {
return f.Usage
}
// GetValue returns the flags value as string representation and an empty
// string if the flag takes no value at all.
func (f *TimestampFlag) GetValue() string {
return ""//f.Value.String()
}
// Apply populates the flag given the flag set and environment
func (f *TimestampFlag) Apply(set *flag.FlagSet) error {
if val, ok := flagFromEnvOrFile(f.EnvVars, f.FilePath); ok {
if val != "" {
layout := "2006-01-02T15:04:05"
parsedTime, err := time.Parse(layout, val)
if err != nil {
return fmt.Errorf("could not parse %q as timestamp value for flag %s: %s", val, f.Name, err)
}
timestamp, err := ptypes.TimestampProto(parsedTime)
if err != nil {
return fmt.Errorf("could not parse %q as a proto timestamp value for flag %s: %s", val, f.Name, err)
}
f.Value = *timestamp
f.HasBeenSet = true
}
}
for _, name := range f.Names() {
set.Var(f.Value, name, f.Usage)
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment