@@ -152,6 +152,7 @@ type Flag struct {
152152 Value Value // value as set
153153 DefValue string // default value (as text); for usage message
154154 Changed bool // If the user set the value (or if left to default)
155+ Deprecated string // If this flag is deprecated, this string is the new or now thing to use
155156 Annotations map [string ][]string // used by cobra.Command bash autocomple code
156157}
157158
@@ -243,6 +244,16 @@ func (f *FlagSet) lookup(name normalizedName) *Flag {
243244 return f .formal [name ]
244245}
245246
247+ // Mark a flag deprecated in your program
248+ func (f * FlagSet ) MarkDeprecated (name string , usageMessage string ) error {
249+ flag := f .Lookup (name )
250+ if flag == nil {
251+ return fmt .Errorf ("flag %q does not exist" , name )
252+ }
253+ flag .Deprecated = usageMessage
254+ return nil
255+ }
256+
246257// Lookup returns the Flag structure of the named command-line flag,
247258// returning nil if none exists.
248259func Lookup (name string ) * Flag {
@@ -264,7 +275,10 @@ func (f *FlagSet) Set(name, value string) error {
264275 f .actual = make (map [normalizedName ]* Flag )
265276 }
266277 f .actual [normalName ] = flag
267- f .lookup (normalName ).Changed = true
278+ flag .Changed = true
279+ if len (flag .Deprecated ) > 0 {
280+ fmt .Fprintf (os .Stderr , "Flag --%s has been deprecated, %s\n " , flag .Name , flag .Deprecated )
281+ }
268282 return nil
269283}
270284
@@ -277,6 +291,9 @@ func Set(name, value string) error {
277291// otherwise, the default values of all defined flags in the set.
278292func (f * FlagSet ) PrintDefaults () {
279293 f .VisitAll (func (flag * Flag ) {
294+ if len (flag .Deprecated ) > 0 {
295+ return
296+ }
280297 format := "--%s=%s: %s\n "
281298 if _ , ok := flag .Value .(* stringValue ); ok {
282299 // put quotes on the value
@@ -295,6 +312,9 @@ func (f *FlagSet) FlagUsages() string {
295312 x := new (bytes.Buffer )
296313
297314 f .VisitAll (func (flag * Flag ) {
315+ if len (flag .Deprecated ) > 0 {
316+ return
317+ }
298318 format := "--%s=%s: %s\n "
299319 if _ , ok := flag .Value .(* stringValue ); ok {
300320 // put quotes on the value
@@ -466,6 +486,9 @@ func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
466486 }
467487 f .actual [f .normalizeFlagName (flag .Name )] = flag
468488 flag .Changed = true
489+ if len (flag .Deprecated ) > 0 {
490+ fmt .Fprintf (os .Stderr , "Flag --%s has been deprecated, %s\n " , flag .Name , flag .Deprecated )
491+ }
469492 return nil
470493}
471494
0 commit comments