From 14a345504f03c02a70b9323d157deccab236d86a Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Sat, 13 Aug 2022 14:30:05 +0800 Subject: [PATCH] refactor: docker engine with options --- cmd/damon.go | 5 ++--- engine/docker.go | 28 +++++++++++++--------------- engine/options.go | 30 ++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 18 deletions(-) create mode 100644 engine/options.go diff --git a/cmd/damon.go b/cmd/damon.go index 2067ff2..d739c45 100644 --- a/cmd/damon.go +++ b/cmd/damon.go @@ -137,8 +137,7 @@ func runDaemon(ctx context.Context, input *Input) func(cmd *cobra.Command, args initLogging(cfg) - opts := engine.Opts{} - engine, err := engine.NewEnv(opts) + engine, err := engine.New() if err != nil { log.WithError(err). Fatalln("cannot load the docker engine") @@ -161,7 +160,7 @@ func runDaemon(ctx context.Context, input *Input) func(cmd *cobra.Command, args count++ if count == 5 { log.WithError(err). - Fatalln("retry count reached") + Fatalf("retry count reached: %d", count) } time.Sleep(time.Second) } else { diff --git a/engine/docker.go b/engine/docker.go index 9aee014..c3017e9 100644 --- a/engine/docker.go +++ b/engine/docker.go @@ -6,30 +6,28 @@ import ( "github.com/docker/docker/client" ) -// Opts configures the Docker engine. -type Opts struct { - HidePull bool -} - type Docker struct { client client.APIClient hidePull bool } -func New(client client.APIClient, opts Opts) *Docker { - return &Docker{ - client: client, - hidePull: opts.HidePull, - } -} - -// NewEnv returns a new Engine from the environment. -func NewEnv(opts Opts) (*Docker, error) { +func New(opts ...Option) (*Docker, error) { cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return nil, err } - return New(cli, opts), nil + + srv := &Docker{ + client: cli, + } + + // Loop through each option + for _, opt := range opts { + // Call the option giving the instantiated + opt.Apply(srv) + } + + return srv, nil } // Ping pings the Docker daemon. diff --git a/engine/options.go b/engine/options.go new file mode 100644 index 0000000..791c6b1 --- /dev/null +++ b/engine/options.go @@ -0,0 +1,30 @@ +package engine + +import "github.com/docker/docker/client" + +// An Option configures a mutex. +type Option interface { + Apply(*Docker) +} + +// OptionFunc is a function that configure a value. +type OptionFunc func(*Docker) + +// Apply calls f(option) +func (f OptionFunc) Apply(docker *Docker) { + f(docker) +} + +// WithClient set custom client +func WithClient(c client.APIClient) Option { + return OptionFunc(func(q *Docker) { + q.client = c + }) +} + +// WithHidePull set custom client +func WithHidePull(v bool) Option { + return OptionFunc(func(q *Docker) { + q.hidePull = v + }) +}