From cff9cb577c6ee182c41ce3dbec9e43f6f712a86c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 17 Apr 2019 16:20:02 -0700 Subject: [PATCH] constructor: allow nil options This can make it significantly easier to configure libp2p with optional options. --- config/config.go | 3 +++ config/config_test.go | 23 +++++++++++++++++++++++ libp2p.go | 3 +++ libp2p_test.go | 25 +++++++++++++++++++++++++ 4 files changed, 54 insertions(+) create mode 100644 config/config_test.go diff --git a/config/config.go b/config/config.go index 61b3c0318..0b8c676bd 100644 --- a/config/config.go +++ b/config/config.go @@ -242,6 +242,9 @@ type Option func(cfg *Config) error // encountered (if any). func (cfg *Config) Apply(opts ...Option) error { for _, opt := range opts { + if opt == nil { + continue + } if err := opt(cfg); err != nil { return err } diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 000000000..7f99b833a --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,23 @@ +package config + +import ( + "testing" +) + +func TestNilOption(t *testing.T) { + var cfg Config + optsRun := 0 + opt := func(c *Config) error { + optsRun++ + return nil + } + if err := cfg.Apply(nil); err != nil { + t.Fatal(err) + } + if err := cfg.Apply(opt, nil, nil, opt, opt, nil); err != nil { + t.Fatal(err) + } + if optsRun != 3 { + t.Fatalf("expected to have handled 3 options, handled %d", optsRun) + } +} diff --git a/libp2p.go b/libp2p.go index ad026ad4b..252c9a292 100644 --- a/libp2p.go +++ b/libp2p.go @@ -19,6 +19,9 @@ type Option = config.Option func ChainOptions(opts ...Option) Option { return func(cfg *Config) error { for _, opt := range opts { + if opt == nil { + continue + } if err := opt(cfg); err != nil { return err } diff --git a/libp2p_test.go b/libp2p_test.go index 3ecedb3b8..84aaa9e46 100644 --- a/libp2p_test.go +++ b/libp2p_test.go @@ -133,3 +133,28 @@ func makeRandomHost(t *testing.T, port int) (host.Host, error) { return New(ctx, opts...) } + +func TestChainOptions(t *testing.T) { + var cfg Config + var optsRun []int + optcount := 0 + newOpt := func() Option { + index := optcount + optcount++ + return func(c *Config) error { + optsRun = append(optsRun, index) + return nil + } + } + if err := cfg.Apply(newOpt(), nil, ChainOptions(newOpt(), newOpt(), ChainOptions(), ChainOptions(nil, newOpt()))); err != nil { + t.Fatal(err) + } + if optcount != len(optsRun) { + t.Errorf("expected to have handled %d options, handled %d", optcount, len(optsRun)) + } + for i, x := range optsRun { + if i != x { + t.Errorf("expected opt %d, got opt %d", i, x) + } + } +}