mirror of
https://github.com/weaveworks/scope.git
synced 2026-07-16 03:49:52 +00:00
ParseNetworks belongs in report
This commit is contained in:
@@ -2,11 +2,30 @@ package report
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Networks represent a set of subnets
|
||||
type Networks []*net.IPNet
|
||||
|
||||
// ParseNetworks converts a string of space-separated CIDRs to a Networks.
|
||||
func ParseNetworks(v string) Networks {
|
||||
set := map[string]struct{}{}
|
||||
for _, s := range strings.Fields(v) {
|
||||
_, ipNet, err := net.ParseCIDR(s)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
set[ipNet.String()] = struct{}{}
|
||||
}
|
||||
nets := Networks{}
|
||||
for s := range set {
|
||||
_, ipNet, _ := net.ParseCIDR(s)
|
||||
nets = append(nets, ipNet)
|
||||
}
|
||||
return nets
|
||||
}
|
||||
|
||||
// Interface is exported for testing.
|
||||
type Interface interface {
|
||||
Addrs() ([]net.Addr, error)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package report_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
@@ -24,6 +25,28 @@ func TestContains(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseNetworks(t *testing.T) {
|
||||
var (
|
||||
bignetStr = "10.1.0.1/16"
|
||||
smallnetStr = "5.6.7.8/32"
|
||||
bignet = mustParseCIDR(bignetStr)
|
||||
smallnet = mustParseCIDR(smallnetStr)
|
||||
)
|
||||
for _, tc := range []struct {
|
||||
input string
|
||||
want report.Networks
|
||||
}{
|
||||
{"", report.Networks{}},
|
||||
{fmt.Sprintf("%s", bignetStr), report.Networks([]*net.IPNet{bignet})},
|
||||
{fmt.Sprintf("%s %s", bignetStr, bignetStr), report.Networks([]*net.IPNet{bignet})},
|
||||
{fmt.Sprintf("%s foo %s oops %s", smallnetStr, smallnetStr, smallnetStr), report.Networks([]*net.IPNet{smallnet})},
|
||||
} {
|
||||
if want, have := tc.want, report.ParseNetworks(tc.input); !reflect.DeepEqual(want, have) {
|
||||
t.Error(test.Diff(want, have))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mustParseCIDR(s string) *net.IPNet {
|
||||
_, ipNet, err := net.ParseCIDR(s)
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user