Skip to content

Commit

Permalink
inject options
Browse files Browse the repository at this point in the history
  • Loading branch information
alec-rabold committed Nov 27, 2024
1 parent 4c48a8e commit a1ea0e0
Showing 1 changed file with 27 additions and 13 deletions.
40 changes: 27 additions & 13 deletions kwok/cloudprovider/options.go → kwok/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,35 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

package kwok
package options

import (
"context"
"errors"
"flag"
"fmt"
"os"

"github.com/samber/lo"

"sigs.k8s.io/karpenter/pkg/operator/options"
"sigs.k8s.io/karpenter/pkg/utils/env"
)

func init() {
options.Injectables = append(options.Injectables, &Options{})
}

type optionsKey struct{}

// Options contains all CLI flags / env vars for the KWOK cloudprovider.
type Options struct {
InstanceTypesFilePath string
}

func GetOptionsOrDie() *Options {
opts := &Options{}
fs := flag.NewFlagSet("kwok", flag.ContinueOnError)
opts.AddFlags(fs)
lo.Must0(opts.Parse(fs, os.Args[1:]...))
return opts
}

func (o *Options) AddFlags(fs *flag.FlagSet) {
func (o *Options) AddFlags(fs *options.FlagSet) {
fs.StringVar(&o.InstanceTypesFilePath, "instance-types-file-path", env.WithDefaultString("INSTANCE_TYPES_FILE_PATH", ""), "Path to a custom instance-types file")
}

func (o *Options) Parse(fs *flag.FlagSet, args ...string) error {
func (o *Options) Parse(fs *options.FlagSet, args ...string) error {
if err := fs.Parse(args); err != nil {
if errors.Is(err, flag.ErrHelp) {
os.Exit(0)
Expand All @@ -53,3 +51,19 @@ func (o *Options) Parse(fs *flag.FlagSet, args ...string) error {
}
return nil
}

func (o *Options) ToContext(ctx context.Context) context.Context {
return ToContext(ctx, o)
}

func ToContext(ctx context.Context, opts *Options) context.Context {
return context.WithValue(ctx, optionsKey{}, opts)
}

func FromContext(ctx context.Context) *Options {
retval := ctx.Value(optionsKey{})
if retval == nil {
return nil
}
return retval.(*Options)
}

0 comments on commit a1ea0e0

Please sign in to comment.