| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package featuregate // import "go.opentelemetry.io/collector/featuregate" |
| 5 |
|
| 6 |
import ( |
| 7 |
"flag" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"go.uber.org/multierr" |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
featureGatesFlag = "feature-gates" |
| 15 |
featureGatesFlagDescription = "Comma-delimited list of feature gate identifiers. Prefix with '-' to disable the feature. '+' or no prefix will enable the feature." |
| 16 |
) |
| 17 |
|
| 18 |
// RegisterFlagsOption is an option for RegisterFlags. |
| 19 |
type RegisterFlagsOption interface { |
| 20 |
private() |
| 21 |
} |
| 22 |
|
| 23 |
// RegisterFlags that directly applies feature gate statuses to a Registry. |
| 24 |
func (r *Registry) RegisterFlags(flagSet *flag.FlagSet, _ ...RegisterFlagsOption) { |
| 25 |
flagSet.Var(&flagValue{reg: r}, featureGatesFlag, featureGatesFlagDescription) |
| 26 |
} |
| 27 |
|
| 28 |
// flagValue implements the flag.Value interface and directly applies feature gate statuses to a Registry. |
| 29 |
type flagValue struct { |
| 30 |
reg *Registry |
| 31 |
} |
| 32 |
|
| 33 |
func (f *flagValue) String() string { |
| 34 |
// This function can be called by isZeroValue https://github.com/golang/go/blob/go1.23.3/src/flag/flag.go#L630 |
| 35 |
// which creates an instance of flagValue using reflect.New. In this case, the field `reg` is nil. |
| 36 |
if f.reg == nil { |
| 37 |
return "" |
| 38 |
} |
| 39 |
|
| 40 |
var ids []string |
| 41 |
f.reg.VisitAll(func(g *Gate) { |
| 42 |
id := g.ID() |
| 43 |
if !g.IsEnabled() { |
| 44 |
id = "-" + id |
| 45 |
} |
| 46 |
ids = append(ids, id) |
| 47 |
}) |
| 48 |
return strings.Join(ids, ",") |
| 49 |
} |
| 50 |
|
| 51 |
func (f *flagValue) Set(s string) error { |
| 52 |
if s == "" { |
| 53 |
return nil |
| 54 |
} |
| 55 |
|
| 56 |
var errs error |
| 57 |
ids := strings.Split(s, ",") |
| 58 |
for i := range ids { |
| 59 |
id := ids[i] |
| 60 |
val := true |
| 61 |
switch id[0] { |
| 62 |
case '-': |
| 63 |
id = id[1:] |
| 64 |
val = false |
| 65 |
case '+': |
| 66 |
id = id[1:] |
| 67 |
} |
| 68 |
errs = multierr.Append(errs, f.reg.Set(id, val)) |
| 69 |
} |
| 70 |
return errs |
| 71 |
} |