From 1ab744a02f000a978c4cf5e26283504e513055f3 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 28 Feb 2019 15:49:51 +0900 Subject: [PATCH 01/34] bump up version.go --- version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.go b/version.go index b10d368..94b4cf4 100644 --- a/version.go +++ b/version.go @@ -1,4 +1,4 @@ package main // VERSION info -const VERSION = "0.2.6" +const VERSION = "0.3.0" From cc3568bda9d88280db3500bffc3a35f739b1db06 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 28 Feb 2019 15:49:58 +0900 Subject: [PATCH 02/34] remove unnessesary targets --- Makefile | 44 -------------------------------------------- 1 file changed, 44 deletions(-) diff --git a/Makefile b/Makefile index 50fe9d6..fc1fb8f 100644 --- a/Makefile +++ b/Makefile @@ -56,47 +56,3 @@ lint-travis: test-goreleaser: @goreleaser release --snapshot --skip-publish --rm-dist - -# Duplicated tasks as follows - -.PHONY: release -release: - @./scripts/release.sh - -release-darwin-386: - @./scripts/release.sh darwin 386 - -release-darwin-amd64: - @./scripts/release.sh darwin amd64 - -release-linux-386: - @./scripts/release.sh linux 386 - -release-linux-amd64: - @./scripts/release.sh linux amd64 - -release-linux-arm: - @./scripts/release.sh linux arm - -release-windows-386: - @./scripts/release.sh windows 386 - -release-windows-amd64: - @./scripts/release.sh windows amd64 - -release-freebsd-386: - @./scripts/release.sh freebsd 386 - -release-freebsd-amd64: - @./scripts/release.sh freebsd amd64 - -.PHONY: upload -upload: - @./scripts/upload.sh - -.PHONY: formula -formula: - @./scripts/upload.sh formula-only - -.PHONY: publish -publish: release upload From 06300d19f08baa4b03095d978e174f5efcf2f6eb Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 28 Feb 2019 15:52:18 +0900 Subject: [PATCH 03/34] run go mod tidy for bumping up aws-sdk-go --- Makefile | 3 +++ go.mod | 2 +- go.sum | 4 ++-- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index fc1fb8f..2f0a245 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,9 @@ version: mod-dl: @GO111MODULE=on go mod download +mod-tidy: + @GO111MODULE=on go mod tidy + bin/$(NAME): $(SRCS) @./scripts/build.sh bin/$(NAME) diff --git a/go.mod b/go.mod index e711ce2..e305eea 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,7 @@ module github.com/goldeneggg/lsec2 require ( - github.com/aws/aws-sdk-go v1.16.36 + github.com/aws/aws-sdk-go v1.17.7 github.com/fatih/color v1.5.0 github.com/mattn/go-colorable v0.0.9 // indirect github.com/mattn/go-isatty v0.0.3 // indirect diff --git a/go.sum b/go.sum index e7ce39d..d45074e 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/aws/aws-sdk-go v1.16.36 h1:POeH34ZME++pr7GBGh+ZO6Y5kOwSMQpqp5BGUgooJ6k= -github.com/aws/aws-sdk-go v1.16.36/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.17.7 h1:/4+rDPe0W95KBmNGYCG+NUvdL8ssPYBMxL+aSCg6nIA= +github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.5.0 h1:vBh+kQp8lg9XPr56u1CPrWjFXtdphMoGWVHr9/1c+A0= From 5406b975efd8dba5a5c443f94b530fb860f32d55 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 28 Feb 2019 16:16:12 +0900 Subject: [PATCH 04/34] run go mod tidy for bumping up faith/color --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index e305eea..f7c47cf 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module github.com/goldeneggg/lsec2 require ( github.com/aws/aws-sdk-go v1.17.7 - github.com/fatih/color v1.5.0 + github.com/fatih/color v1.7.0 github.com/mattn/go-colorable v0.0.9 // indirect github.com/mattn/go-isatty v0.0.3 // indirect github.com/stretchr/testify v1.3.0 // indirect diff --git a/go.sum b/go.sum index d45074e..a5d9207 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ github.com/aws/aws-sdk-go v1.17.7 h1:/4+rDPe0W95KBmNGYCG+NUvdL8ssPYBMxL+aSCg6nIA github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fatih/color v1.5.0 h1:vBh+kQp8lg9XPr56u1CPrWjFXtdphMoGWVHr9/1c+A0= -github.com/fatih/color v1.5.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= From 3f5d4e30f6ca39f2079feb682b0bc2a317109b66 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 28 Feb 2019 17:23:22 +0900 Subject: [PATCH 05/34] little refactoring --- awsec2/client.go | 16 ++++++++++------ awsec2/const.go | 12 ------------ awsec2/instance_info.go | 7 +++++++ commands.go | 3 +-- main.go | 4 ++-- 5 files changed, 20 insertions(+), 22 deletions(-) delete mode 100644 awsec2/const.go diff --git a/awsec2/client.go b/awsec2/client.go index 8539003..0c6de9b 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -9,6 +9,14 @@ import ( "github.com/aws/aws-sdk-go/service/ec2" ) +const ( + tagFilterPrefix = "tag:" + tagPairSeparator = "=" + tagValueSeparator = "," + + defaultTagValuesCap = 3 +) + // Client is options definition of print // client attributes type Client struct { @@ -34,11 +42,7 @@ func (client *Client) Print() error { } func (client *Client) buildInfos() ([]*InstanceInfo, error) { - sess, err := session.NewSession(&aws.Config{Region: aws.String(client.Region)}) - if err != nil { - return nil, fmt.Errorf("aws new session error: %v", err) - } - + sess := session.Must(session.NewSession(&aws.Config{Region: aws.String(client.Region)})) svc := ec2.New(sess) output, err := svc.DescribeInstances(client.filterParams()) @@ -70,7 +74,7 @@ func (client *Client) filterParams() *ec2.DescribeInstancesInput { for _, tag := range client.Tags { tagNameValue := strings.Split(tag, tagPairSeparator) name := aws.String(tagFilterPrefix + tagNameValue[0]) - values := make([]*string, 0, 3) + values := make([]*string, 0, defaultTagValuesCap) for _, value := range strings.Split(tagNameValue[1], tagValueSeparator) { values = append(values, aws.String(value)) } diff --git a/awsec2/const.go b/awsec2/const.go deleted file mode 100644 index a34041c..0000000 --- a/awsec2/const.go +++ /dev/null @@ -1,12 +0,0 @@ -package awsec2 - -const ( - tagFilterPrefix = "tag:" - tagPairSeparator = "=" - tagValueSeparator = "," - - parsedTagSeparator = "," - fieldSeparater = "\t" - - undefinedItem = "UNDEFINED" -) diff --git a/awsec2/instance_info.go b/awsec2/instance_info.go index 8f4bda4..56a668a 100644 --- a/awsec2/instance_info.go +++ b/awsec2/instance_info.go @@ -11,6 +11,13 @@ import ( "github.com/fatih/color" ) +const ( + parsedTagSeparator = "," + fieldSeparater = "\t" + + undefinedItem = "UNDEFINED" +) + // InstanceInfo is attributes of aws ec2 instance type InstanceInfo struct { InstanceID string `header:"INSTANCE_ID"` diff --git a/commands.go b/commands.go index 8070f33..e7df766 100644 --- a/commands.go +++ b/commands.go @@ -4,11 +4,10 @@ import ( "fmt" "os" + "github.com/goldeneggg/lsec2/awsec2" "github.com/urfave/cli" ) -import "github.com/goldeneggg/lsec2/awsec2" - func run(args []string) error { app := cli.NewApp() diff --git a/main.go b/main.go index 3e28a11..482cf53 100644 --- a/main.go +++ b/main.go @@ -10,9 +10,9 @@ const ( exitStsNg ) -var sts int - var ( + sts int + version string buildDate string buildCommit string From ccaba01415071bf69152d33ddc9ef9f77630c767 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sun, 10 Mar 2019 13:56:37 +0900 Subject: [PATCH 06/34] remove CHANGELOG --- CHANGELOG.md | 56 ---------------------------------------------------- 1 file changed, 56 deletions(-) delete mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index add2d34..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,56 +0,0 @@ -# Change Log - -## [v0.2.2](https://github.com/goldeneggg/lsec2/tree/v0.2.2) (2017-12-10) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.2.1...v0.2.2) - -**Merged pull requests:** - -- some fixes of depops [\#8](https://github.com/goldeneggg/lsec2/pull/8) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.2.1](https://github.com/goldeneggg/lsec2/tree/v0.2.1) (2017-12-05) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.2.0...v0.2.1) - -**Merged pull requests:** - -- refactoring vendoring and devops [\#7](https://github.com/goldeneggg/lsec2/pull/7) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.2.0](https://github.com/goldeneggg/lsec2/tree/v0.2.0) (2017-09-21) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.1.1...v0.2.0) - -**Merged pull requests:** - -- add state filter [\#6](https://github.com/goldeneggg/lsec2/pull/6) ([goldeneggg](https://github.com/goldeneggg)) -- fix README [\#5](https://github.com/goldeneggg/lsec2/pull/5) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.1.1](https://github.com/goldeneggg/lsec2/tree/v0.1.1) (2017-01-03) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.1.0...v0.1.1) - -**Merged pull requests:** - -- support printing state with color, and some refactoring [\#4](https://github.com/goldeneggg/lsec2/pull/4) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.1.0](https://github.com/goldeneggg/lsec2/tree/v0.1.0) (2016-09-25) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.0.3...v0.1.0) - -**Merged pull requests:** - -- refactoring and add tests [\#3](https://github.com/goldeneggg/lsec2/pull/3) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.0.3](https://github.com/goldeneggg/lsec2/tree/v0.0.3) (2016-09-24) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.0.2...v0.0.3) - -**Merged pull requests:** - -- add release and publish process [\#2](https://github.com/goldeneggg/lsec2/pull/2) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.0.2](https://github.com/goldeneggg/lsec2/tree/v0.0.2) (2016-09-24) -[Full Changelog](https://github.com/goldeneggg/lsec2/compare/v0.0.1...v0.0.2) - -**Merged pull requests:** - -- Refactor [\#1](https://github.com/goldeneggg/lsec2/pull/1) ([goldeneggg](https://github.com/goldeneggg)) - -## [v0.0.1](https://github.com/goldeneggg/lsec2/tree/v0.0.1) (2016-09-22) - - -\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file From 6cd728cc858e83204085fcebef2398991512a76f Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sun, 10 Mar 2019 13:59:45 +0900 Subject: [PATCH 07/34] bump up aws-sdk-go --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index f7c47cf..ccb0726 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,7 @@ module github.com/goldeneggg/lsec2 require ( - github.com/aws/aws-sdk-go v1.17.7 + github.com/aws/aws-sdk-go v1.17.14 github.com/fatih/color v1.7.0 github.com/mattn/go-colorable v0.0.9 // indirect github.com/mattn/go-isatty v0.0.3 // indirect diff --git a/go.sum b/go.sum index a5d9207..7ecd169 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/aws/aws-sdk-go v1.17.7 h1:/4+rDPe0W95KBmNGYCG+NUvdL8ssPYBMxL+aSCg6nIA= github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.17.14 h1:IjqZDIQoLyZ48A93BxVrZOaIGgZPRi4nXt6WQUMJplY= +github.com/aws/aws-sdk-go v1.17.14/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= From 3d461494d4aa0795f2b1f4c0f794acc8fde27688 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sun, 10 Mar 2019 14:03:04 +0900 Subject: [PATCH 08/34] remove codes --- commands.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/commands.go b/commands.go index e7df766..af91c42 100644 --- a/commands.go +++ b/commands.go @@ -15,9 +15,7 @@ func run(args []string) error { app.Author = "goldeneggg" app.Version = VERSION app.Usage = "Listing information of aws ec2 instances" - //app.Flags = globalFlags app.Flags = append(globalFlags, showFlags...) - //app.Commands = commands app.Action = action return app.Run(args) From 1f5e6024aeaf9c97fe877d2efcd8e21ec57d5fad Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sun, 10 Mar 2019 19:12:03 +0900 Subject: [PATCH 09/34] add yaml package --- go.mod | 1 + go.sum | 2 ++ 2 files changed, 3 insertions(+) diff --git a/go.mod b/go.mod index ccb0726..bafd096 100644 --- a/go.mod +++ b/go.mod @@ -10,4 +10,5 @@ require ( golang.org/x/net v0.0.0-20190213061140-3a22650c66bd // indirect golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0 // indirect golang.org/x/text v0.3.0 // indirect + gopkg.in/yaml.v2 v2.2.2 ) diff --git a/go.sum b/go.sum index 7ecd169..58d534b 100644 --- a/go.sum +++ b/go.sum @@ -25,3 +25,5 @@ golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0 h1:x4M4WCms+ErQg/4VyECbP2kSN golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= From 0293270ed4428a382d1507663e50b5ecdc430333 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sun, 10 Mar 2019 19:12:16 +0900 Subject: [PATCH 10/34] refactoring --- awsec2/client.go | 95 ++++++--------- awsec2/client_test.go | 72 ++++++++++++ commands.go | 47 +++++--- flags.go | 76 +++++++----- go.mod | 42 ++++++- go.sum | 108 +++++++++++++++++ {awsec2 => printer}/instance_info.go | 46 ++++---- {awsec2 => printer}/instance_info_test.go | 6 +- printer/printer.go | 134 ++++++++++++++++++++++ 9 files changed, 487 insertions(+), 139 deletions(-) create mode 100644 awsec2/client_test.go rename {awsec2 => printer}/instance_info.go (81%) rename {awsec2 => printer}/instance_info_test.go (98%) create mode 100644 printer/printer.go diff --git a/awsec2/client.go b/awsec2/client.go index 0c6de9b..831d305 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" ) const ( @@ -17,73 +18,65 @@ const ( defaultTagValuesCap = 3 ) -// Client is options definition of print -// client attributes +// Client is attributes definition for filtering ec2 instances type Client struct { - PrintHeader bool - OnlyPrivateIP bool - Region string - Tags []string - WithColor bool - StateName string + ec2iface.EC2API + Region string + StateName string + Tags []string } -// Print is print method for aws ec2 instances -// print information of aws ec2 instances -func (client *Client) Print() error { - infos, err := client.buildInfos() - if err != nil { - return fmt.Errorf("buildInfos error: %v", err) - } +// NewClient returns a new DefaultClient +func NewClient(region string, maybeEC2Client interface{}) *Client { + client := new(Client) - client.printInfos(infos) + client.Region = region - return nil -} + if ec2Client, ok := maybeEC2Client.(ec2iface.EC2API); ok { + client.EC2API = ec2Client + } else { + client.EC2API = defaultEC2Client(region) + } -func (client *Client) buildInfos() ([]*InstanceInfo, error) { - sess := session.Must(session.NewSession(&aws.Config{Region: aws.String(client.Region)})) - svc := ec2.New(sess) + return client +} - output, err := svc.DescribeInstances(client.filterParams()) +// Get filtered EC2 instances +func (client *Client) EC2Instances() ([]*ec2.Instance, error) { + output, err := client.EC2API.DescribeInstances(client.buildFilter()) if err != nil { return nil, fmt.Errorf("aws describe instances error: %v", err) } - var infos []*InstanceInfo - - for _, reservation := range output.Reservations { - for _, instance := range reservation.Instances { - info, err := NewInstanceInfo(instance) - if err != nil { - return nil, err - } - infos = append(infos, info) - } + var res []*ec2.Instance + for _, r := range output.Reservations { + res = append(res, r.Instances...) } - return infos, nil + return res, nil +} + +func defaultEC2Client(region string) ec2iface.EC2API { + config := &aws.Config{Region: aws.String(region)} + sess := session.Must(session.NewSession(config)) + return ec2.New(sess) } -func (client *Client) filterParams() *ec2.DescribeInstancesInput { +func (client *Client) buildFilter() *ec2.DescribeInstancesInput { var filters []*ec2.Filter // client.tags is separated key-value pair by "=", and values are separated by ","(comma) // ex. "Name=Value" // ex. "Name=Value1,Value2" for _, tag := range client.Tags { - tagNameValue := strings.Split(tag, tagPairSeparator) - name := aws.String(tagFilterPrefix + tagNameValue[0]) + kv := strings.Split(tag, tagPairSeparator) + name := aws.String(tagFilterPrefix + kv[0]) values := make([]*string, 0, defaultTagValuesCap) - for _, value := range strings.Split(tagNameValue[1], tagValueSeparator) { - values = append(values, aws.String(value)) + for _, v := range strings.Split(kv[1], tagValueSeparator) { + values = append(values, aws.String(v)) } - tagFilter := &ec2.Filter{ - Name: name, - Values: values, - } - filters = append(filters, tagFilter) + filters = append(filters, &ec2.Filter{Name: name, Values: values}) } if len(filters) == 0 { @@ -92,19 +85,3 @@ func (client *Client) filterParams() *ec2.DescribeInstancesInput { return &ec2.DescribeInstancesInput{Filters: filters} } - -func (client *Client) printInfos(infos []*InstanceInfo) { - if client.PrintHeader { - infos[0].printHeader() - } - - for _, info := range infos { - if len(client.StateName) == 0 || client.StateName == info.StateName { - if client.OnlyPrivateIP { - fmt.Printf("%s\n", info.PrivateIPAddress) - } else { - info.printRow(client.WithColor) - } - } - } -} diff --git a/awsec2/client_test.go b/awsec2/client_test.go new file mode 100644 index 0000000..05880bc --- /dev/null +++ b/awsec2/client_test.go @@ -0,0 +1,72 @@ +package awsec2_test + +import ( + "testing" + + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + + . "github.com/goldeneggg/lsec2/awsec2" +) + +type ( + caseNewClient struct { + region string + exp *DefaultClient + } + + caseEC2Instances struct { + client *DefaultClient + exp []*ec2.Instance + } +) + +type mockEC2API struct { + ec2iface.EC2API +} + +func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) { + // TODO + return nil, nil +} + +func TestNewClient(t *testing.T) { + cases := []caseNewClient{ + {"ap-northeast-1", &DefaultClient{Region: "ap-northeast-1"}}, + {"us-east-1", &DefaultClient{Region: "us-east-1"}}, + } + + for _, c := range cases { + client := NewClient(c.region) + + dClient, ok := client.(*DefaultClient) + if !ok { + t.Errorf("client is not *DefaultClient: %#v, but exp: %#v", c.exp.Region, dClient.Region) + } + + if dClient.Region != c.exp.Region { + t.Errorf("expected: %#v, but exp: %#v", c.exp.Region, dClient.Region) + } + } +} + +func TestEC2Instances(t *testing.T) { + cases := []caseEC2Instances{ + { + client: &DefaultClient{EC2API: &mockEC2API{}, Region: "ap-northeast-1"}, + exp: []*ec2.Instance{}, + }, + } + + for _, c := range cases { + insts, err := c.client.EC2Instances() + + if err != nil { + t.Errorf("error occured. err: %#v", err) + } + + if len(c.exp) != len(insts) { + t.Errorf("not same instances length. expected: %#v, but exp: %#v", len(c.exp), len(insts)) + } + } +} diff --git a/commands.go b/commands.go index af91c42..e0f01a9 100644 --- a/commands.go +++ b/commands.go @@ -5,6 +5,7 @@ import ( "os" "github.com/goldeneggg/lsec2/awsec2" + "github.com/goldeneggg/lsec2/printer" "github.com/urfave/cli" ) @@ -15,7 +16,7 @@ func run(args []string) error { app.Author = "goldeneggg" app.Version = VERSION app.Usage = "Listing information of aws ec2 instances" - app.Flags = append(globalFlags, showFlags...) + app.Flags = append(ec2Flags, printFlags...) app.Action = action return app.Run(args) @@ -27,32 +28,44 @@ func action(c *cli.Context) { return } - client := &awsec2.Client{ - Region: c.String("region"), - Tags: c.Args(), + if err := newPrinter(c).PrintAll(newClient(c)); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + sts = exitStsNg } +} - if c.IsSet("H") { - client.PrintHeader = c.Bool("H") +func newClient(c *cli.Context) *awsec2.Client { + client := awsec2.NewClient(c.String("region"), nil) + + client.Tags = c.Args() + if c.IsSet("s") { + client.StateName = c.String("s") } + return client +} + +func newPrinter(c *cli.Context) *printer.Printer { + printer := printer.NewPrinter(nil) + + if c.IsSet("H") { + printer.PrintHeader = c.Bool("H") + } if c.IsSet("p") { - client.OnlyPrivateIP = c.Bool("p") - client.PrintHeader = false + printer.OnlyPrivateIP = c.Bool("p") + printer.PrintHeader = false } - if c.IsSet("c") { - client.WithColor = c.Bool("c") + printer.WithColor = c.Bool("c") } - - if c.IsSet("s") { - client.StateName = c.String("s") + if c.IsSet("d") { + printer.Delimeter = c.String("d") } - - if err := client.Print(); err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) - sts = exitStsNg + if c.IsSet("coldef") { + printer.ColDef = c.String("coldef") } + + return printer } func showBuildInfo(c *cli.Context) { diff --git a/flags.go b/flags.go index d5c7bf1..5a1c739 100644 --- a/flags.go +++ b/flags.go @@ -1,33 +1,51 @@ package main -import "github.com/urfave/cli" +import ( + "os" -var globalFlags = []cli.Flag{ - cli.StringFlag{ - Name: "region", - Usage: "assign target region", - }, -} + "github.com/urfave/cli" +) -var showFlags = []cli.Flag{ - cli.BoolFlag{ - Name: "print-header, H", - Usage: "print list header", - }, - cli.BoolFlag{ - Name: "private-ip, p", - Usage: "print only private ip", - }, - cli.BoolFlag{ - Name: "show-build", - Usage: "show build info", - }, - cli.BoolFlag{ - Name: "with-color, c", - Usage: "print state with color", - }, - cli.StringFlag{ - Name: "state, s", - Usage: "filter only assigned state", - }, -} +var ( + // command line options for getting ec2 instances + ec2Flags = []cli.Flag{ + cli.StringFlag{ + Name: "region", + Usage: "assign target region", + }, + cli.StringFlag{ + Name: "state, s", + Usage: "filter only assigned state", + }, + } + + // command line options for printing informations + printFlags = []cli.Flag{ + cli.BoolFlag{ + Name: "show-build", + Usage: "show build info", + }, + cli.BoolFlag{ + Name: "print-header, H", + Usage: "print list header", + }, + cli.BoolFlag{ + Name: "private-ip, p", + Usage: "print only private ip", + }, + cli.BoolFlag{ + Name: "with-color, c", + Usage: "print state with color", + }, + cli.StringFlag{ + Name: "delimiter, d", + Usage: "column delemeter for printed informations", + Value: "\t", + }, + cli.StringFlag{ + Name: "coldef", + Usage: "path of coldef.yml", + Value: os.Getenv("HOME") + string(os.PathSeparator) + ".lsec2" + string(os.PathSeparator) + "coldef.yml", + }, + } +) diff --git a/go.mod b/go.mod index bafd096..ad0a9b8 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,48 @@ module github.com/goldeneggg/lsec2 require ( + github.com/alecthomas/gometalinter v3.0.0+incompatible // indirect + github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect github.com/aws/aws-sdk-go v1.17.14 + github.com/cosiner/argv v0.0.1 // indirect + github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d // indirect github.com/fatih/color v1.7.0 - github.com/mattn/go-colorable v0.0.9 // indirect - github.com/mattn/go-isatty v0.0.3 // indirect + github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6 // indirect + github.com/fatih/motion v0.0.0-20180408211639-218875ebe238 // indirect + github.com/go-delve/delve v1.2.0 // indirect + github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf // indirect + github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4 // indirect + github.com/jstemmer/gotags v1.4.1 // indirect + github.com/keegancsmith/rpc v1.1.0 // indirect + github.com/kisielk/errcheck v1.2.0 // indirect + github.com/klauspost/asmfmt v1.2.0 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect + github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91 // indirect + github.com/mattn/go-colorable v0.1.1 // indirect + github.com/mattn/go-isatty v0.0.6 // indirect + github.com/mattn/go-runewidth v0.0.4 // indirect + github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f // indirect + github.com/nicksnyder/go-i18n v1.10.0 // indirect + github.com/pelletier/go-toml v1.2.0 // indirect + github.com/peterh/liner v1.1.0 // indirect + github.com/pkg/profile v1.2.1 // indirect + github.com/rogpeppe/godef v1.1.1 // indirect + github.com/sirupsen/logrus v1.3.0 // indirect + github.com/spf13/cobra v0.0.3 // indirect + github.com/spf13/pflag v1.0.3 // indirect + github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476 // indirect github.com/stretchr/testify v1.3.0 // indirect github.com/urfave/cli v1.20.0 - golang.org/x/net v0.0.0-20190213061140-3a22650c66bd // indirect - golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0 // indirect + github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a // indirect + golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8 // indirect + golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 // indirect + golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f // indirect + golang.org/x/net v0.0.0-20190310074541-c10a0554eabf // indirect + golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa // indirect golang.org/x/text v0.3.0 // indirect + golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f // indirect + gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c // indirect + gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect gopkg.in/yaml.v2 v2.2.2 + honnef.co/go/tools v0.0.0-20190215041234-466a0476246c // indirect ) diff --git a/go.sum b/go.sum index 58d534b..cfcd205 100644 --- a/go.sum +++ b/go.sum @@ -1,29 +1,137 @@ +9fans.net/go v0.0.0-20181112161441-237454027057 h1:OcHlKWkAMJEF1ndWLGxp5dnJQkYM/YImUOvsBoz6h5E= +9fans.net/go v0.0.0-20181112161441-237454027057/go.mod h1:diCsxrliIURU9xsYtjCp5AbpQKqdhKmf0ujWDUSkfoY= +github.com/alecthomas/gometalinter v3.0.0+incompatible h1:e9Zfvfytsw/e6Kd/PYd75wggK+/kX5Xn8IYDUKyc5fU= +github.com/alecthomas/gometalinter v3.0.0+incompatible/go.mod h1:qfIpQGGz3d+NmgyPBqv+LSh50emm1pt72EtcX2vKYQk= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/aws/aws-sdk-go v1.17.7 h1:/4+rDPe0W95KBmNGYCG+NUvdL8ssPYBMxL+aSCg6nIA= github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.17.14 h1:IjqZDIQoLyZ48A93BxVrZOaIGgZPRi4nXt6WQUMJplY= github.com/aws/aws-sdk-go v1.17.14/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/cosiner/argv v0.0.0-20170225145430-13bacc38a0a5/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ= +github.com/cosiner/argv v0.0.1 h1:2iAFN+sWPktbZ4tvxm33Ei8VY66FPCxdOxpncUGpAXE= +github.com/cosiner/argv v0.0.1/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ= +github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d h1:aRvyac5PN1NEfcANJ1tfs8GMs5I9OXsVeg0FJkpXOys= +github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d/go.mod h1:8o/GRMvsb9VyFbSEZGXfa0dkSXml4G23W0D/h9FksWM= +github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= +github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6 h1:iXJdM8Uob6EPOG/PFr5q0J124ysiZdJfACHqICBb3b8= +github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6/go.mod h1:p2/x7bnOQsbq/deXsDIlj2yLiKFGPkD2nuoYqwn8R4Y= +github.com/fatih/motion v0.0.0-20180408211639-218875ebe238 h1:Qo4RxRMFag+fvDqQ6A3MblYBormptQUZ1ssOtV+EeQ8= +github.com/fatih/motion v0.0.0-20180408211639-218875ebe238/go.mod h1:pseIrV+t9A4+po+KJ1LheSnYH8m1qs6WhKx2zFiGi9I= +github.com/fatih/structtag v1.0.0 h1:pTHj65+u3RKWYPSGaU290FpI/dXxTaHdVwVwbcPKmEc= +github.com/fatih/structtag v1.0.0/go.mod h1:IKitwq45uXL/yqi5mYghiD3w9H6eTOvI9vnk8tXMphA= +github.com/go-delve/delve v1.2.0 h1:uwGyfYO0WsWqbnDWvxCBKOr2qFLpii3tLxwM+fTJs70= +github.com/go-delve/delve v1.2.0/go.mod h1:yP+LD36s/ud5nm4lsQY0TwNhYu2PAwk6xItz+442j74= +github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf h1:7+FW5aGwISbqUtkfmIpZJGRgNFg2ioYPvFaUxdqpDsg= +github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4 h1:gmIVMdGlVf5e6Yo6+ZklxdOrvtOvyrAjJyXAbmOznyo= +github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4/go.mod h1:t4Tr0tn92eq5ISef4cS5plFAMYAqZlAXtgUcKE6y8nw= +github.com/jstemmer/gotags v1.4.1 h1:aWIyXsU3lTDqhsEC49MP85p2cUUWr2ptvdGNqqGA3r4= +github.com/jstemmer/gotags v1.4.1/go.mod h1:b6J3X0bsLbR4C5SgSx3V3KjuWTtmRzcmWPbTkWZ49PA= +github.com/keegancsmith/rpc v1.1.0 h1:bXVRk3EzbtrEegTGKxNTc+St1lR7t/Z1PAO8misBnCc= +github.com/keegancsmith/rpc v1.1.0/go.mod h1:Xow74TKX34OPPiPCdz6x1o9c0SCxRqGxDuKGk7ZOo8s= +github.com/kisielk/errcheck v1.2.0 h1:reN85Pxc5larApoH1keMBiu2GWtPqXQ1nc9gx+jOU+E= +github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= +github.com/klauspost/asmfmt v1.2.0 h1:zwsyBYgEdabg32alMful/5pRtMTcR5C5w1LKNg9OD78= +github.com/klauspost/asmfmt v1.2.0/go.mod h1:RAoUvqkWr2rUa2I19qKMEVZQe4BVtcHGTMCUOcCU2Lg= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91 h1:hunjgdb3b21ZdRmzDPXii0EcnHpjH7uCP+kODoE1JH0= +github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91/go.mod h1:C2tFh8w3I6i4lnUJfoBx2Hwku3mgu4wPNTtUNp1i5KI= +github.com/mattn/go-colorable v0.0.0-20170327083344-ded68f7a9561/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg= +github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.6 h1:SrwhHcpV4nWrMGdNcC2kXpMfcBVYGDuTArqyhocJgvA= +github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f h1:ee+twVCignaZjt7jpbMSLxAeTN/Nfq9W/nm91E7QO1A= +github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f/go.mod h1:hltEC42XzfMNgg0S1v6JTywwra2Mu6F6cLR03debVQ8= +github.com/nicksnyder/go-i18n v1.10.0 h1:5AzlPKvXBH4qBzmZ09Ua9Gipyruv6uApMcrNZdo96+Q= +github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2xBGjv0j365Q= +github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/peterh/liner v0.0.0-20170317030525-88609521dc4b/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/peterh/liner v1.1.0 h1:f+aAedNJA6uk7+6rXsYBnhdo4Xux7ESLe+kcuVUF5os= +github.com/peterh/liner v1.1.0/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= +github.com/pkg/profile v0.0.0-20170413231811-06b906832ed0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/godef v1.1.1 h1:NujOtt9q9vIClRTB3sCZpavac+NMRaIayzrcz1h4fSE= +github.com/rogpeppe/godef v1.1.1/go.mod h1:oEo1eMy1VUEHUzUIX4F7IqvMJRiz9UId44mvnR8oPlQ= +github.com/russross/blackfriday v0.0.0-20180428102519-11635eb403ff/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/sirupsen/logrus v0.0.0-20180523074243-ea8897e79973/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= +github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= +github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/spf13/cobra v0.0.0-20170417170307-b6cb39589372/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= +github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= +github.com/spf13/pflag v0.0.0-20170417173400-9e4c21054fa1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476 h1:KtMuvAziiZPINAWNvK1cNpAcqCHbDwNhpLbQw0rg6YY= +github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476/go.mod h1:EM2T8YDoTCvGXbEpFHxarbpv7VE26QD1++Cb1Pbh7Gs= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a h1:00UFliGZl2UciXe8o/2iuEsRQ9u7z0rzDTVzuj6EYY0= +github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a/go.mod h1:ofmGw6LrMypycsiWcyug6516EXpIxSbZ+uI9ppGypfY= +golang.org/x/arch v0.0.0-20171004143515-077ac972c2e4/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= +golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8 h1:G3kY3WDPiChidkYzLqbniw7jg23paUtzceZorG6YAJw= +golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= +golang.org/x/crypto v0.0.0-20180614174826-fd5f17ee7299/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f h1:hX65Cu3JDlGH3uEdK7I99Ii+9kjD6mvnnpfLdEAH0x4= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190310074541-c10a0554eabf/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0 h1:x4M4WCms+ErQg/4VyECbP2kSNcDJ6nLwqEGov1QPtqk= golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180614134839-8883426083c0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa h1:lqti/xP+yD/6zH5TqEwx2MilNIJY5Vbc6Qr8J3qyPIQ= +golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20180824175216-6c1c5e93cdc1/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181120060634-fc4f04983f62/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181130195746-895048a75ecf/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20181207195948-8634b1ecd393/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f h1:SUQ6L9W8e5xt2GFO9s+i18JGITAfem+a0AQuFU8Ls74= +golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= +gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c h1:vTxShRUnK60yd8DZU+f95p1zSLj814+5CuEh7NjF2/Y= +gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c/go.mod h1:3HH7i1SgMqlzxCcBmUHW657sD4Kvv9sC3HpL3YukzwA= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.0.0-20170407172122-cd8b52f8269e/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190215041234-466a0476246c h1:z+UFwlQ7KVwdlQTE5JjvDvfZmyyAVrEiiwau20b7X8k= +honnef.co/go/tools v0.0.0-20190215041234-466a0476246c/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/awsec2/instance_info.go b/printer/instance_info.go similarity index 81% rename from awsec2/instance_info.go rename to printer/instance_info.go index 56a668a..0d41650 100644 --- a/awsec2/instance_info.go +++ b/printer/instance_info.go @@ -1,7 +1,6 @@ -package awsec2 +package printer import ( - "fmt" "reflect" "sort" "strings" @@ -13,9 +12,7 @@ import ( const ( parsedTagSeparator = "," - fieldSeparater = "\t" - - undefinedItem = "UNDEFINED" + undefinedItem = "UNDEFINED" ) // InstanceInfo is attributes of aws ec2 instance @@ -29,11 +26,12 @@ type InstanceInfo struct { } // NewInstanceInfo creates a new InstanceInfo -func NewInstanceInfo(instance *ec2.Instance) (*InstanceInfo, error) { +func NewInstanceInfo(instance *ec2.Instance) *InstanceInfo { if instance == nil { - return nil, fmt.Errorf("ec2.Instance: %v is invalid", instance) + return &InstanceInfo{} } + // TODO: coldef.yml対応 i := &InstanceInfo{ InstanceID: fetchItem(instance.InstanceId), PrivateIPAddress: fetchItem(instance.PrivateIpAddress), @@ -51,11 +49,23 @@ func NewInstanceInfo(instance *ec2.Instance) (*InstanceInfo, error) { i.Tags = tags } - return i, nil + return i +} + +func (info *InstanceInfo) Headers() []string { + var headers []string + + rt := reflect.TypeOf(*info) + for i := 0; i < rt.NumField(); i++ { + field := rt.Field(i) + headers = append(headers, field.Tag.Get("header")) + } + + return headers } // ParseRow parses from InstanceInfo to one line string -func (info *InstanceInfo) ParseRow(withColor bool) string { +func (info *InstanceInfo) Values(withColor bool) []string { var values []string values = append(values, info.InstanceID) @@ -66,23 +76,7 @@ func (info *InstanceInfo) ParseRow(withColor bool) string { values = append(values, strings.Join(info.parseTags(), parsedTagSeparator)) - return fmt.Sprintf("%s", strings.Join(values, fieldSeparater)) -} - -func (info *InstanceInfo) printHeader() { - var headers []string - - rt := reflect.TypeOf(*info) - for i := 0; i < rt.NumField(); i++ { - field := rt.Field(i) - headers = append(headers, field.Tag.Get("header")) - } - - fmt.Printf("%s\n", strings.Join(headers, fieldSeparater)) -} - -func (info *InstanceInfo) printRow(withColor bool) { - fmt.Printf("%s\n", info.ParseRow(withColor)) + return values } func (info *InstanceInfo) decorateStateName(withColor bool) string { diff --git a/awsec2/instance_info_test.go b/printer/instance_info_test.go similarity index 98% rename from awsec2/instance_info_test.go rename to printer/instance_info_test.go index 2e3098d..0043768 100644 --- a/awsec2/instance_info_test.go +++ b/printer/instance_info_test.go @@ -1,4 +1,4 @@ -package awsec2_test +package printer_test import ( "fmt" @@ -6,10 +6,8 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" -) -import ( - . "github.com/goldeneggg/lsec2/awsec2" + . "github.com/goldeneggg/lsec2/printer" ) const ( diff --git a/printer/printer.go b/printer/printer.go new file mode 100644 index 0000000..969a2a8 --- /dev/null +++ b/printer/printer.go @@ -0,0 +1,134 @@ +package printer + +import ( + "fmt" + "io" + "os" + "strings" + "text/tabwriter" + + "github.com/aws/aws-sdk-go/service/ec2" + + "github.com/goldeneggg/lsec2/awsec2" +) + +const ( + defaultDelimiter = "\t" + + tabWriterMinWidth = 0 + tabWriterTabWidth = 4 + tabWriterPadding = 4 + tabWriterPadChar = ' ' + tabWriterFlags = 0 +) + +var ( + defaultWriter = os.Stdout +) + +type flushableWriter interface { + io.Writer + Flush() error +} + +// Printer is options definition of print +type Printer struct { + io.Writer + PrintHeader bool + OnlyPrivateIP bool + WithColor bool + Delimeter string + ColDef string +} + +// NewPrinter returns a new Printer +func NewPrinter(maybeWriter interface{}) *Printer { + printer := new(Printer) + + printer.Delimeter = defaultDelimiter + + if writer, ok := maybeWriter.(io.Writer); ok { + printer.Writer = writer + } else { + printer.Writer = defaultWriter + } + + return printer +} + +// Print is print method for aws ec2 instances +// print information of aws ec2 instances +func (printer *Printer) PrintAll(client *awsec2.Client) error { + instances, err := client.EC2Instances() + if err != nil { + return fmt.Errorf("get EC2 Instances error: %v", err) + } + + printer.wrapWriterIfDefault() + defer printer.flushIfFlushable() + + if printer.PrintHeader { + printer.printHeader() + } + + for _, inst := range instances { + if err := printer.printInstance(client, inst); err != nil { + return fmt.Errorf("print instance error: %v", err) + } + } + + return nil +} + +func (printer *Printer) wrapWriterIfDefault() { + if printer.Writer == defaultWriter { + if printer.Delimeter == defaultDelimiter { + printer.Writer = tabwriter.NewWriter( + printer.Writer, + tabWriterMinWidth, + tabWriterTabWidth, + tabWriterPadding, + tabWriterPadChar, + tabWriterFlags, + ) + } + } +} + +func (printer *Printer) flushIfFlushable() { + // FIXME: + // printer.Writer.(interface{Flush() error}) とも書けそう。どちらがパフォーマンスが良いか? + if fw, ok := printer.Writer.(flushableWriter); ok { + fw.Flush() + } +} + +func (printer *Printer) printHeader() { + printer.printArray(NewInstanceInfo(nil).Headers()) +} + +func (printer *Printer) printInstance(client *awsec2.Client, inst *ec2.Instance) error { + var ( + ii *InstanceInfo + err error + ) + + ii = NewInstanceInfo(inst) + if len(client.StateName) == 0 || client.StateName == ii.StateName { + if printer.OnlyPrivateIP { + err = printer.printArray([]string{ii.PrivateIPAddress}) + } else { + err = printer.printArray(ii.Values(printer.WithColor)) + } + } + + return err +} + +func (printer *Printer) printArray(sArr []string) error { + if _, err := fmt.Fprintln(printer.Writer, strings.Join(sArr, printer.Delimeter)); err != nil { + return err + } + + return nil +} From 172886b3e670b5ff946a4a02e6312c139a4897fb Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Wed, 13 Mar 2019 21:10:59 +0900 Subject: [PATCH 11/34] fix tests --- awsec2/client_test.go | 117 ++++++++++++++++++++++++++-------- printer/instance_info_test.go | 57 +++++++---------- printer/printer_test.go | 114 +++++++++++++++++++++++++++++++++ 3 files changed, 226 insertions(+), 62 deletions(-) create mode 100644 printer/printer_test.go diff --git a/awsec2/client_test.go b/awsec2/client_test.go index 05880bc..e1ca267 100644 --- a/awsec2/client_test.go +++ b/awsec2/client_test.go @@ -3,21 +3,42 @@ package awsec2_test import ( "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" . "github.com/goldeneggg/lsec2/awsec2" ) -type ( - caseNewClient struct { - region string - exp *DefaultClient - } - - caseEC2Instances struct { - client *DefaultClient - exp []*ec2.Instance +var ( + dummyInstances = []*ec2.Instance{ + &ec2.Instance{ + InstanceId: aws.String("i-xxxxxxxxx1"), + PrivateIpAddress: aws.String("10.0.0.1"), + PublicIpAddress: aws.String("1.2.3.4"), + InstanceType: aws.String("t1.micro"), + State: &ec2.InstanceState{ + Name: aws.String("running"), + }, + }, + &ec2.Instance{ + InstanceId: aws.String("i-xxxxxxxxx2"), + PrivateIpAddress: aws.String("10.0.0.2"), + PublicIpAddress: aws.String("1.2.3.5"), + InstanceType: aws.String("t2.micro"), + State: &ec2.InstanceState{ + Name: aws.String("stopped"), + }, + }, + &ec2.Instance{ + InstanceId: aws.String("i-xxxxxxxxx9"), + PrivateIpAddress: aws.String("10.0.0.9"), + PublicIpAddress: aws.String("1.2.3.9"), + InstanceType: aws.String("t2.large"), + State: &ec2.InstanceState{ + Name: aws.String("stopped"), + }, + }, } ) @@ -25,36 +46,78 @@ type mockEC2API struct { ec2iface.EC2API } +// override for mock func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) { - // TODO - return nil, nil + instancesOutput := &ec2.DescribeInstancesOutput{ + Reservations: []*ec2.Reservation{ + &ec2.Reservation{ + Instances: []*ec2.Instance{dummyInstances[0], dummyInstances[1]}, + }, + &ec2.Reservation{ + Instances: []*ec2.Instance{dummyInstances[2]}, + }, + }, + } + + return instancesOutput, nil } func TestNewClient(t *testing.T) { - cases := []caseNewClient{ - {"ap-northeast-1", &DefaultClient{Region: "ap-northeast-1"}}, - {"us-east-1", &DefaultClient{Region: "us-east-1"}}, + mockClient := &mockEC2API{} + + cases := []struct { + region string + ec2Client ec2iface.EC2API + expected *Client + }{ + { + region: "ap-northeast-1", + ec2Client: mockClient, + expected: &Client{ + EC2API: mockClient, + Region: "ap-northeast-1", + }, + }, + { + region: "us-east-1", + ec2Client: mockClient, + expected: &Client{ + EC2API: mockClient, + Region: "us-east-1", + }, + }, } for _, c := range cases { - client := NewClient(c.region) + client := NewClient(c.region, c.ec2Client) - dClient, ok := client.(*DefaultClient) - if !ok { - t.Errorf("client is not *DefaultClient: %#v, but exp: %#v", c.exp.Region, dClient.Region) - } - - if dClient.Region != c.exp.Region { - t.Errorf("expected: %#v, but exp: %#v", c.exp.Region, dClient.Region) + if client.Region != c.expected.Region { + t.Errorf("expected: %#v, but expected: %#v", c.expected.Region, client.Region) } } } func TestEC2Instances(t *testing.T) { - cases := []caseEC2Instances{ + cases := []struct { + client *Client + expected []*ec2.Instance + }{ + { + client: &Client{ + EC2API: &mockEC2API{}, + Region: "ap-northeast-1", + StateName: "running", + Tags: []string{"Role=roleA,roleB", "Service=serviceX"}, + }, + expected: dummyInstances, + }, { - client: &DefaultClient{EC2API: &mockEC2API{}, Region: "ap-northeast-1"}, - exp: []*ec2.Instance{}, + client: &Client{ + EC2API: &mockEC2API{}, + Region: "us-east-1", + StateName: "running", + }, + expected: dummyInstances, }, } @@ -65,8 +128,8 @@ func TestEC2Instances(t *testing.T) { t.Errorf("error occured. err: %#v", err) } - if len(c.exp) != len(insts) { - t.Errorf("not same instances length. expected: %#v, but exp: %#v", len(c.exp), len(insts)) + if len(c.expected) != len(insts) { + t.Errorf("not same instances length. expected: %#v, but expected: %#v", len(c.expected), len(insts)) } } } diff --git a/printer/instance_info_test.go b/printer/instance_info_test.go index 0043768..4d1565d 100644 --- a/printer/instance_info_test.go +++ b/printer/instance_info_test.go @@ -1,7 +1,6 @@ package printer_test import ( - "fmt" "testing" "github.com/aws/aws-sdk-go/aws" @@ -27,7 +26,7 @@ var ( type infoTest struct { in *ec2.Instance expected *InstanceInfo - expectedParsed string + expectedValues []string } var infoTests = []infoTest{ @@ -64,17 +63,14 @@ var infoTests = []infoTest{ dummyTagKeys[1]: dummyTagValues[1], }, }, - expectedParsed: fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%s=%s,%s=%s", + expectedValues: []string{ dummyInstanceID, dummyPrivateIPAddress, dummyPublicIPAddress, dummyInstanceType, dummyStateName, - dummyTagKeys[0], - dummyTagValues[0], - dummyTagKeys[1], - dummyTagValues[1], - ), + dummyTagKeys[0] + "=" + dummyTagValues[0] + "," + dummyTagKeys[1] + "=" + dummyTagValues[1], + }, }, { // public ip is nil @@ -104,15 +100,14 @@ var infoTests = []infoTest{ dummyTagKeys[0]: dummyTagValues[0], }, }, - expectedParsed: fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t%s=%s", + expectedValues: []string{ dummyInstanceID, dummyPrivateIPAddress, - "UNDEFINED", + dummyPublicIPAddress, dummyInstanceType, dummyStateName, - dummyTagKeys[0], - dummyTagValues[0], - ), + dummyTagKeys[0] + "=" + dummyTagValues[0], + }, }, { // tags are empty @@ -135,28 +130,36 @@ var infoTests = []infoTest{ StateName: dummyStateName, Tags: map[string]string{}, }, - expectedParsed: fmt.Sprintf("%s\t%s\t%s\t%s\t%s\t", + expectedValues: []string{ dummyInstanceID, dummyPrivateIPAddress, dummyPublicIPAddress, dummyInstanceType, dummyStateName, - ), + "", + }, }, } func TestNewInstanceInfo(t *testing.T) { for _, it := range infoTests { - out, err := NewInstanceInfo(it.in) - if err != nil { - t.Errorf("occurred error: %v, in: %#v", err, it.in) - } + out := NewInstanceInfo(it.in) + if !compare(out, it.expected) { t.Errorf("expected: %#v, but out: %#v", it.expected, out) } } } +func TestValues(t *testing.T) { + for _, it := range infoTests { + out := it.expected.Values(false) + if len(out) != len(it.expectedValues) { + t.Errorf("expected: [%#v], but out: [%#v]", it.expectedValues, out) + } + } +} + func compare(out *InstanceInfo, expected *InstanceInfo) bool { if out.InstanceID != expected.InstanceID { return false @@ -187,19 +190,3 @@ func compare(out *InstanceInfo, expected *InstanceInfo) bool { return true } - -func TestNewInstanceInfoByNil(t *testing.T) { - out, err := NewInstanceInfo(nil) - if err == nil { - t.Errorf("not occurred expected error. out: %#v", out) - } -} - -func TestParseRow(t *testing.T) { - for _, it := range infoTests { - out := it.expected.ParseRow(false) - if out != it.expectedParsed { - t.Errorf("expected: [%s], but out: [%s]", it.expectedParsed, out) - } - } -} diff --git a/printer/printer_test.go b/printer/printer_test.go new file mode 100644 index 0000000..43d66c6 --- /dev/null +++ b/printer/printer_test.go @@ -0,0 +1,114 @@ +package printer_test + +import ( + "io" + "os" + "testing" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/ec2" + "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + + "github.com/goldeneggg/lsec2/awsec2" + . "github.com/goldeneggg/lsec2/printer" +) + +var ( + dummyInstances = []*ec2.Instance{ + &ec2.Instance{ + InstanceId: aws.String("i-xxxxxxxx91"), + PrivateIpAddress: aws.String("192.168.56.101"), + PublicIpAddress: aws.String("54.0.0.1"), + InstanceType: aws.String("t3.large"), + State: &ec2.InstanceState{ + Name: aws.String("running"), + }, + }, + &ec2.Instance{ + InstanceId: aws.String("i-xxxxxxxx99"), + PrivateIpAddress: aws.String("192.168.56.199"), + PublicIpAddress: aws.String("54.0.0.9"), + InstanceType: aws.String("t4.large"), + State: &ec2.InstanceState{ + Name: aws.String("stopped"), + }, + }, + } +) + +type mockEC2API struct { + ec2iface.EC2API +} + +// override for mock +func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) { + instancesOutput := &ec2.DescribeInstancesOutput{ + Reservations: []*ec2.Reservation{ + &ec2.Reservation{ + Instances: []*ec2.Instance{dummyInstances[0]}, + }, + &ec2.Reservation{ + Instances: []*ec2.Instance{dummyInstances[1]}, + }, + }, + } + + return instancesOutput, nil +} + +func TestNewPrinter(t *testing.T) { + dummyFile := os.NewFile(uintptr(3), "printer_test.go.out") + + cases := []struct { + maybeWriter io.Writer + exp *Printer + }{ + { + maybeWriter: nil, + exp: &Printer{ + Writer: os.Stdout, + }, + }, + { + maybeWriter: dummyFile, + exp: &Printer{ + Writer: dummyFile, + }, + }, + } + + for _, c := range cases { + printer := NewPrinter(c.maybeWriter) + + if printer.Writer != c.exp.Writer { + t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, printer.Writer) + } + } +} + +func TestPrintAll(t *testing.T) { + client := &awsec2.Client{ + EC2API: &mockEC2API{}, + Region: "ap-northeast-1", + StateName: "running", + Tags: []string{"Role=roleA,roleB", "Service=serviceX"}, + } + + cases := []struct { + printer *Printer + }{ + { + printer: &Printer{ + Writer: os.Stdout, + }, + }, + } + + for _, c := range cases { + err := c.printer.PrintAll(client) + + if err != nil { + t.Errorf("error occured. err: %#v", err) + } + } +} From 0acdc4c7164bc23aa6ba54ae823a3932b5fbd512 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Wed, 13 Mar 2019 21:21:58 +0900 Subject: [PATCH 12/34] fix linter error --- awsec2/client.go | 2 +- printer/instance_info.go | 3 ++- printer/printer.go | 11 ++++++----- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/awsec2/client.go b/awsec2/client.go index 831d305..3710584 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -41,7 +41,7 @@ func NewClient(region string, maybeEC2Client interface{}) *Client { return client } -// Get filtered EC2 instances +// EC2Instances gets filtered EC2 instances func (client *Client) EC2Instances() ([]*ec2.Instance, error) { output, err := client.EC2API.DescribeInstances(client.buildFilter()) if err != nil { diff --git a/printer/instance_info.go b/printer/instance_info.go index 0d41650..ad6057a 100644 --- a/printer/instance_info.go +++ b/printer/instance_info.go @@ -52,6 +52,7 @@ func NewInstanceInfo(instance *ec2.Instance) *InstanceInfo { return i } +// Headers gets header string array func (info *InstanceInfo) Headers() []string { var headers []string @@ -64,7 +65,7 @@ func (info *InstanceInfo) Headers() []string { return headers } -// ParseRow parses from InstanceInfo to one line string +// Values gets value string array func (info *InstanceInfo) Values(withColor bool) []string { var values []string diff --git a/printer/printer.go b/printer/printer.go index 969a2a8..aa85bc3 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -56,8 +56,7 @@ func NewPrinter(maybeWriter interface{}) *Printer { return printer } -// Print is print method for aws ec2 instances -// print information of aws ec2 instances +// PrintAll prints information all of aws ec2 instances func (printer *Printer) PrintAll(client *awsec2.Client) error { instances, err := client.EC2Instances() if err != nil { @@ -68,7 +67,9 @@ func (printer *Printer) PrintAll(client *awsec2.Client) error { defer printer.flushIfFlushable() if printer.PrintHeader { - printer.printHeader() + if err := printer.printHeader(); err != nil { + return fmt.Errorf("print header error: %v", err) + } } for _, inst := range instances { @@ -103,8 +104,8 @@ func (printer *Printer) flushIfFlushable() { } } -func (printer *Printer) printHeader() { - printer.printArray(NewInstanceInfo(nil).Headers()) +func (printer *Printer) printHeader() error { + return printer.printArray(NewInstanceInfo(nil).Headers()) } func (printer *Printer) printInstance(client *awsec2.Client, inst *ec2.Instance) error { From 6ccfdd2e030a38730b68c6e99e668977ab484b08 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Wed, 13 Mar 2019 21:41:46 +0900 Subject: [PATCH 13/34] fix README --- README.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 13e346e..1a2cb8a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,25 @@ -lsec2 -========== - -List view of aws ec2 instances +# lsec2 [![Build Status](https://travis-ci.org/goldeneggg/lsec2.svg?branch=master)](https://travis-ci.org/goldeneggg/lsec2) -[![GolangCI](https://golangci.com/badges/github.com/goldeneggg/gat.svg)](https://golangci.com/r/github.com/goldeneggg/lsec2) [![Go Report Card](https://goreportcard.com/badge/github.com/goldeneggg/lsec2)](https://goreportcard.com/report/github.com/goldeneggg/lsec2) +[![GolangCI](https://golangci.com/badges/github.com/goldeneggg/gat.svg)](https://golangci.com/r/github.com/goldeneggg/lsec2) [![Codecov](https://codecov.io/github/goldeneggg/lsec2/coverage.svg?branch=master)](https://codecov.io/github/goldeneggg/lsec2?branch=master) [![MIT License](http://img.shields.io/badge/license-MIT-lightgrey.svg)](https://github.com/goldeneggg/lsec2/blob/master/LICENSE) +List view of AWS EC2 instances. + +Example as follows. + +```sh +$ lsec2 -H +``` +``` +INSTANCE_ID PRIVATE_IP PUBLIC_IP TYPE STATE TAGS +i-0xxxxxxxxxxxxxx1 172.111.111.111 54.111.111.111 t2.micro running TagA=ValueA,TagB=ValueB +i-0xxxxxxxxxxxxxx2 172.222.222.222 54.222.222.222 t2.medium running TagAA=ValueAA +i-0xxxxxxxxxxxxxx3 172.333.333.333 54.333.333.333 t1.large stopped +``` + ## Install ### Using Homebrew for OS X From 92555a4a8e6a362d91046e3293d13d3afb9c237c Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Wed, 13 Mar 2019 23:49:51 +0900 Subject: [PATCH 14/34] refactoring around CLI --- Makefile | 18 ++++-- commands.go => cmd/lsec2/cli/commands.go | 26 ++++++--- flags.go => cmd/lsec2/cli/flags.go | 2 +- main.go => cmd/lsec2/main.go | 8 +-- cmd/lsec2/version/version.go | 4 ++ scripts/_ldflags.sh | 11 ++-- scripts/_prepare.sh | 17 +----- scripts/_version.sh | 5 +- scripts/build.sh | 5 +- scripts/ci-test.sh | 10 ++-- scripts/install.sh | 17 ++++++ scripts/release.sh | 68 ---------------------- scripts/upload.sh | 72 ------------------------ version.go | 4 -- 14 files changed, 73 insertions(+), 194 deletions(-) rename commands.go => cmd/lsec2/cli/commands.go (74%) rename flags.go => cmd/lsec2/cli/flags.go (98%) rename main.go => cmd/lsec2/main.go (77%) create mode 100644 cmd/lsec2/version/version.go create mode 100755 scripts/install.sh delete mode 100755 scripts/release.sh delete mode 100755 scripts/upload.sh delete mode 100644 version.go diff --git a/Makefile b/Makefile index 2f0a245..b385c10 100644 --- a/Makefile +++ b/Makefile @@ -1,16 +1,13 @@ NAME := lsec2 SRCS := $(shell find . -type f -name '*.go' | \grep -v 'vendor') -VERSION := $(shell ./scripts/_version.sh) -LDFLAGS := $(shell ./scripts/_ldflags.sh) PACKAGES := $(shell ./scripts/_packages.sh) PROF_DIR := ./.profile -PROF_TARGET := ./awsec2 .DEFAULT_GOAL := bin/$(NAME) .PHONY: version version: - @echo $(VERSION) + @echo $(shell ./scripts/_version.sh) mod-dl: @GO111MODULE=on go mod download @@ -23,7 +20,7 @@ bin/$(NAME): $(SRCS) .PHONY: install install: - @go install -v -ldflags='$(LDFLAGS)' + @./scripts/install.sh .PHONY: test test: @@ -34,7 +31,16 @@ ci-test: .PHONY: prof prof: - @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -blockprofile $(PROF_DIR)/block.out -cover -coverprofile $(PROF_DIR)/cover.out -cpuprofile $(PROF_DIR)/cpu.out -memprofile $(PROF_DIR)/mem.out $(PROF_TARGET) + @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -cover -coverprofile $(PROF_DIR)/cover.out $(PACKAGES) + +prof-full-awsec2: + @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -blockprofile $(PROF_DIR)/block.out -cover -coverprofile $(PROF_DIR)/cover.out -cpuprofile $(PROF_DIR)/cpu.out -memprofile $(PROF_DIR)/mem.out ./awsec2 + +prof-full-printer: + @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -blockprofile $(PROF_DIR)/block.out -cover -coverprofile $(PROF_DIR)/cover.out -cpuprofile $(PROF_DIR)/cpu.out -memprofile $(PROF_DIR)/mem.out ./printer + +prof-full-cmd-cli: + @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -blockprofile $(PROF_DIR)/block.out -cover -coverprofile $(PROF_DIR)/cover.out -cpuprofile $(PROF_DIR)/cpu.out -memprofile $(PROF_DIR)/mem.out ./cmd/lsec2/cli .PHONY: vet vet: diff --git a/commands.go b/cmd/lsec2/cli/commands.go similarity index 74% rename from commands.go rename to cmd/lsec2/cli/commands.go index e0f01a9..514e29e 100644 --- a/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -1,20 +1,27 @@ -package main +package cli import ( "fmt" "os" "github.com/goldeneggg/lsec2/awsec2" + "github.com/goldeneggg/lsec2/cmd/lsec2/version" "github.com/goldeneggg/lsec2/printer" "github.com/urfave/cli" ) -func run(args []string) error { +var ( + BuildDate string + BuildCommit string + GoVersion string +) + +func Run(args []string) error { app := cli.NewApp() app.Name = "lsec2" app.Author = "goldeneggg" - app.Version = VERSION + app.Version = version.VERSION app.Usage = "Listing information of aws ec2 instances" app.Flags = append(ec2Flags, printFlags...) app.Action = action @@ -22,16 +29,18 @@ func run(args []string) error { return app.Run(args) } -func action(c *cli.Context) { +func action(c *cli.Context) error { if c.IsSet("show-build") { showBuildInfo(c) - return + return nil } if err := newPrinter(c).PrintAll(newClient(c)); err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) - sts = exitStsNg + return err } + + return nil } func newClient(c *cli.Context) *awsec2.Client { @@ -69,6 +78,7 @@ func newPrinter(c *cli.Context) *printer.Printer { } func showBuildInfo(c *cli.Context) { - fmt.Printf("build-date: %v\n", buildDate) - fmt.Printf("build-commit: %v\n", buildCommit) + fmt.Printf("build-date: %v\n", BuildDate) + fmt.Printf("build-commit: %v\n", BuildCommit) + fmt.Printf("go-version: %v\n", GoVersion) } diff --git a/flags.go b/cmd/lsec2/cli/flags.go similarity index 98% rename from flags.go rename to cmd/lsec2/cli/flags.go index 5a1c739..25a82eb 100644 --- a/flags.go +++ b/cmd/lsec2/cli/flags.go @@ -1,4 +1,4 @@ -package main +package cli import ( "os" diff --git a/main.go b/cmd/lsec2/main.go similarity index 77% rename from main.go rename to cmd/lsec2/main.go index 482cf53..b4e0b4c 100644 --- a/main.go +++ b/cmd/lsec2/main.go @@ -3,6 +3,8 @@ package main import ( "fmt" "os" + + "github.com/goldeneggg/lsec2/cmd/lsec2/cli" ) const ( @@ -12,16 +14,12 @@ const ( var ( sts int - - version string - buildDate string - buildCommit string ) func main() { defer finalize() - if err := run(os.Args); err != nil { + if err := cli.Run(os.Args); err != nil { fmt.Fprintf(os.Stderr, "Error: %v\n", err) sts = exitStsNg } diff --git a/cmd/lsec2/version/version.go b/cmd/lsec2/version/version.go new file mode 100644 index 0000000..8e13470 --- /dev/null +++ b/cmd/lsec2/version/version.go @@ -0,0 +1,4 @@ +package version + +// VERSION says my version number +const VERSION = "0.3.0" diff --git a/scripts/_ldflags.sh b/scripts/_ldflags.sh index 09a2cea..00532c1 100755 --- a/scripts/_ldflags.sh +++ b/scripts/_ldflags.sh @@ -1,14 +1,15 @@ #!/bin/bash set -eu -MYDIR=$(cd $(dirname $0) && pwd) -BASE_DIR=${MYDIR}/.. +source scripts/_prepare.sh CUR_DATE=$(date "+%Y-%m-%d %H:%M:%S") COMMIT=$(git log --format=%H -n1) +GO_VERSION=$(go version) + LF="-w -s -extldflags \"-static\"" -LF="${LF} -X \"main.version=$(${BASE_DIR}/scripts/_version.sh)\"" -LF="${LF} -X \"main.buildDate=${CUR_DATE}\"" -LF="${LF} -X \"main.buildCommit=${COMMIT}\"" +LF="${LF} -X \"${FULL_PACKAGE}/cmd/lsec2/cli.BuildDate=${CUR_DATE}\"" +LF="${LF} -X \"${FULL_PACKAGE}/cmd/lsec2/cli.BuildCommit=${COMMIT}\"" +LF="${LF} -X \"${FULL_PACKAGE}/cmd/lsec2/cli.GoVersion=${GO_VERSION}\"" echo "${LF}" diff --git a/scripts/_prepare.sh b/scripts/_prepare.sh index 7e6cd49..521b695 100755 --- a/scripts/_prepare.sh +++ b/scripts/_prepare.sh @@ -1,18 +1,5 @@ #!/bin/bash MYDIR=$(cd $(dirname $0) && pwd) BASE_DIR=${MYDIR}/.. -RELEASES_DIR=${BASE_DIR}/releases -PKG_DIR=${BASE_DIR}/pkg - -PACKAGE=lsec2 -PACKAGE_FULL=github.com/goldeneggg/${PACKAGE} -FORMULA_CLASS=Lsec2 - -AWK=$(which awk) -SHASUM=$(which shasum) - -VERSION=$(${BASE_DIR}/scripts/_version.sh) -TAG=v${VERSION} - -DEFAULT_OS=('linux' 'darwin' 'windows' 'freebsd') -DEFAULT_ARCH=('amd64' '386') +CMD_GO_DIR=${BASE_DIR}/cmd/lsec2 +FULL_PACKAGE=github.com/goldeneggg/lsec2 diff --git a/scripts/_version.sh b/scripts/_version.sh index 9ff9d52..1a2fd8d 100755 --- a/scripts/_version.sh +++ b/scripts/_version.sh @@ -1,10 +1,9 @@ #!/bin/bash set -eu -MYDIR=$(cd $(dirname $0) && pwd) -BASE_DIR=${MYDIR}/.. +source scripts/_prepare.sh GREP=$(which grep) SED=$(which sed) -${GREP} "const VERSION" ${BASE_DIR}/version.go | ${SED} -e 's/const VERSION = //g' | ${SED} -e 's/\"//g' +${GREP} "const VERSION" ${CMD_GO_DIR}/version/version.go | ${SED} -e 's/const VERSION = //g' | ${SED} -e 's/\"//g' diff --git a/scripts/build.sh b/scripts/build.sh index fa79dd0..c029e0e 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -8,6 +8,7 @@ source scripts/_prepare.sh OUTPUT=${1} shift +OTHER_OPTS="" if [ $# -ge 1 ] then OTHER_OPTS="$@" @@ -16,5 +17,5 @@ fi LDFLAGS=$(${MYDIR}/_ldflags.sh) -echo "LDFLAGS=${LDFLAGS}, GOOS=${GOOS}, GOARCH=${GOARCH}" -go build -a -tags netgo -installsuffix netgo -ldflags="${LDFLAGS}" ${OTHER_OPTS} -o ${OUTPUT} +echo "LDFLAGS=${LDFLAGS}, GOOS=${GOOS}, GOARCH=${GOARCH}, OTHER_OPTS=${OTHER_OPTS}" +go build -a -tags netgo -installsuffix netgo -ldflags="${LDFLAGS}" ${OTHER_OPTS} -o ${OUTPUT} ${CMD_GO_DIR} diff --git a/scripts/ci-test.sh b/scripts/ci-test.sh index 9239ca2..4f6fca5 100755 --- a/scripts/ci-test.sh +++ b/scripts/ci-test.sh @@ -5,9 +5,9 @@ source scripts/_prepare.sh echo "" > coverage.txt for d in $(${MYDIR}/_packages.sh); do - go test -race -coverprofile=profile.out -covermode=atomic $d - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi + go test -race -coverprofile=profile.out -covermode=atomic $d + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi done diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..5a424de --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +set -ex + +source scripts/_prepare.sh + +OTHER_OPTS="" +if [ $# -ge 1 ] +then + OTHER_OPTS="$@" + echo "OTHER_OPTS = ${OTHER_OPTS}" +fi + +LDFLAGS=$(${MYDIR}/_ldflags.sh) + +echo "LDFLAGS=${LDFLAGS}, GOOS=${GOOS}, GOARCH=${GOARCH}, OTHER_OPTS=${OTHER_OPTS}" +go install -v -ldflags="${LDFLAGS}" ${OTHER_OPTS} ${CMD_GO_DIR} diff --git a/scripts/release.sh b/scripts/release.sh deleted file mode 100755 index 64cedbb..0000000 --- a/scripts/release.sh +++ /dev/null @@ -1,68 +0,0 @@ -#!/bin/bash - -set -eu - -_gen_readme(){ - cat <<'EOR' > ${TMP_README} -## Install - -``` -$ cp RELEASE_BIN YOUR_PATH/RELEASE_BIN -``` - -## Check shasum - -```sh -$ shasum -a 256 YOUR_PATH/RELEASE_BIN - -# compare to .shasum256 file -$ diff <(cat RELEASE_BIN.shasum256) <(shasum -a 256 YOUR_PATH/RELEASE_BIN | awk '{print $1}') -``` -EOR - -sed -i -e "s/PACKAGE/${PACKAGE}/g" ${TMP_README} -sed -i -e "s/RELEASE_BIN/${RELEASE_BIN}/g" ${TMP_README} -} - -build(){ - local os=${1} - local arch=${2} - - local release_dir=${RELEASES_DIR}/${PACKAGE}_${os}_${arch} - [ -d ${release_dir} ] && rm -fr ${release_dir} - mkdir -p ${release_dir} - - RELEASE_BIN="${PACKAGE}" - [ ${os} = "windows" ] && RELEASE_BIN=${RELEASE_BIN}.exe - - echo "Start release build: ${release_dir}/${RELEASE_BIN}" - GOOS=${os} GOARCH=${arch} ${MYDIR}/build.sh ${release_dir}/${RELEASE_BIN} - - local release_shasum256=${RELEASE_BIN}.shasum256 - ${SHASUM} -a 256 ${release_dir}/${RELEASE_BIN} | ${AWK} '{print $1}' > ${release_dir}/${release_shasum256} - - TMP_README=/tmp/readme-${os}-${arch}-${RELEASE_BIN}.md - _gen_readme - cp ${TMP_README} ${release_dir}/README.md -} - -all(){ - for os in ${DEFAULT_OS[@]} - do - for arch in ${DEFAULT_ARCH[@]} - do - build ${os} ${arch} - done - done -} - -source scripts/_prepare.sh - -if [ $# -eq 2 ] -then - build ${1} ${2} -else - all -fi - -exit 0 diff --git a/scripts/upload.sh b/scripts/upload.sh deleted file mode 100755 index c05f271..0000000 --- a/scripts/upload.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash - -set -eu - -upload(){ - [ -d ${PKG_DIR} ] && rm -r ${PKG_DIR} - mkdir -p ${PKG_DIR} - - pushd ${RELEASES_DIR} - for os in ${DEFAULT_OS[@]} - do - for arch in ${DEFAULT_ARCH[@]} - do - local build_name=${PACKAGE}_${os}_${arch} - zip -9 ${PKG_DIR}/${build_name}.zip ${build_name}/* - echo "created artifacts ${PKG_DIR}/${build_name}.zip" - done - done - popd - - # Note: need to set "GITHUB_TOKEN" environment - ghr --draft --replace ${TAG} ${PKG_DIR} -} - -shasum256() { - local os=${1} - local arch=${2} - - ${SHASUM} -a 256 ${PKG_DIR}/${PACKAGE}_${os}_${arch}.zip | awk '{print $1}' -} - -formula(){ - cat << EOF > ${PACKAGE}_formula.rb -require "formula" - -class ${FORMULA_CLASS} < Formula - homepage 'https://${PACKAGE_FULL}' - version '${VERSION}' - - if Hardware::CPU.is_32_bit? - if OS.linux? - url 'https://${PACKAGE_FULL}/releases/download/${TAG}/${PACKAGE}_linux_386.zip' - sha256 '$(shasum256 linux 386)' - else - url 'https://${PACKAGE_FULL}/releases/download/${TAG}/${PACKAGE}_darwin_386.zip' - sha256 '$(shasum256 darwin 386)' - end - else - if OS.linux? - url 'https://${PACKAGE_FULL}/releases/download/${TAG}/${PACKAGE}_linux_amd64.zip' - sha256 '$(shasum256 linux amd64)' - else - url 'https://${PACKAGE_FULL}/releases/download/${TAG}/${PACKAGE}_darwin_amd64.zip' - sha256 '$(shasum256 darwin amd64)' - end - end - - def install - bin.install '${PACKAGE}' - end -end -EOF -} - -source scripts/_prepare.sh - -if [ $# -eq 1 ] -then - [ ${1} = "formula-only" ] && formula -else - upload && formula -fi diff --git a/version.go b/version.go deleted file mode 100644 index 94b4cf4..0000000 --- a/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package main - -// VERSION info -const VERSION = "0.3.0" From 1d9b8f7c17ad1a7b24317fa90ea4ed07f925b792 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 14 Mar 2019 01:17:17 +0900 Subject: [PATCH 15/34] modified goreleaser process --- .goreleaser.yml | 19 +++++++++++++++---- .travis.yml | 2 +- Makefile | 9 ++++++++- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 7153215..740df9a 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -8,18 +8,29 @@ before: builds: - env: - CGO_ENABLED=0 + - GO111MODULE=on + main: ./cmd/lsec2/main.go + flags: + - -a + - -tags + - netgo + - -installsuffix + - netgo + ldflags: + - -w -s -extldflags "-static" -X github.com/goldeneggg/lsec2/cmd/lsec2/cli.BuildDate={{.Date}} -X github.com/goldeneggg/lsec2/cmd/lsec2/cli.BuildCommit={{.ShortCommit}} -X github.com/goldeneggg/lsec2/cmd/lsec2/cli.GoVersion={{.Env.GOVERSION}} goos: - - darwin - linux - - windows - freebsd + - darwin + - windows goarch: - - '386' - amd64 + - 386 ignore: - goos: darwin goarch: 386 - + - goos: windows + goarch: 386 archive: format_overrides: - goos: windows diff --git a/.travis.yml b/.travis.yml index 62291d8..fd1fba6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,7 +32,7 @@ after_success: deploy: - provider: script skip_cleanup: true - script: curl -sL http://git.io/goreleaser | bash + script: export GOVERSION=$TRAVIS_GO_VERSION && curl -sL http://git.io/goreleaser | bash on: tags: true condition: $TRAVIS_OS_NAME = linux && $TRAVIS_GO_VERSION =~ ^1\.12.* diff --git a/Makefile b/Makefile index b385c10..3ee25f8 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ NAME := lsec2 SRCS := $(shell find . -type f -name '*.go' | \grep -v 'vendor') PACKAGES := $(shell ./scripts/_packages.sh) PROF_DIR := ./.profile +GOVERSION := $(shell go version | awk '{print $$3;}') .DEFAULT_GOAL := bin/$(NAME) @@ -29,6 +30,9 @@ test: ci-test: @./scripts/ci-test.sh +.PHONY: ci +ci: ci-test ci-goreleaser + .PHONY: prof prof: @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -cover -coverprofile $(PROF_DIR)/cover.out $(PACKAGES) @@ -64,4 +68,7 @@ lint-travis: @travis lint --org --debug .travis.yml test-goreleaser: - @goreleaser release --snapshot --skip-publish --rm-dist + @GOVERSION=$(GOVERSION) goreleaser release --snapshot --skip-publish --rm-dist + +ci-goreleaser: + @export GOVERSION=$(GOVERSION) && curl -sL http://git.io/goreleaser | bash -s -- release --snapshot --skip-publish --rm-dist From 9d87e1f01a4241e22146f69fe1bb8dad65ce1665 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 14 Mar 2019 01:18:00 +0900 Subject: [PATCH 16/34] add clean target --- Makefile | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Makefile b/Makefile index 3ee25f8..efb7950 100644 --- a/Makefile +++ b/Makefile @@ -72,3 +72,11 @@ test-goreleaser: ci-goreleaser: @export GOVERSION=$(GOVERSION) && curl -sL http://git.io/goreleaser | bash -s -- release --snapshot --skip-publish --rm-dist + +.PHONY: clean +clean: + @go clean $(PACKAGES) + @rm -f bin/$(NAME) + @rm -fr dist pkg + @find . -name '*.test' -delete + @rm -fr $(PROF_DIR) From 51d53cb2b3efd78c56922bc9a7ba0475445c8823 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 14 Mar 2019 01:18:29 +0900 Subject: [PATCH 17/34] modified travis ci script --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index fd1fba6..49ffac6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,7 +24,7 @@ install: - go mod download script: - - make ci-test + - make ci after_success: - bash <(curl -s https://codecov.io/bash) From f7c54a87d78dd739c55ae2dc47e96b3c0400b89b Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Thu, 14 Mar 2019 02:11:51 +0900 Subject: [PATCH 18/34] fix vet error --- cmd/lsec2/cli/commands.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/cmd/lsec2/cli/commands.go b/cmd/lsec2/cli/commands.go index 514e29e..8aedf6f 100644 --- a/cmd/lsec2/cli/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -11,11 +11,15 @@ import ( ) var ( - BuildDate string + // BuildDate have a built date + BuildDate string + // BuildCommit have a latest commit hash BuildCommit string - GoVersion string + // GoVersion have a go version number used for build + GoVersion string ) +// Run run a cli command func Run(args []string) error { app := cli.NewApp() From fdaa4b20c1aad149cead71f9b4c91c4379c057b8 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 21:32:59 +0900 Subject: [PATCH 19/34] fix Makefile --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index efb7950..69c9513 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ ci-test: @./scripts/ci-test.sh .PHONY: ci -ci: ci-test ci-goreleaser +ci: ci-test .PHONY: prof prof: From 11575d689ee0cd8060f8a8511ea33fd2b691bc89 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 22:13:41 +0900 Subject: [PATCH 20/34] refactoring printer --- cmd/lsec2/cli/commands.go | 5 +-- cmd/lsec2/cli/flags.go | 7 ---- printer/instance_info.go | 1 - printer/printer.go | 80 +++++++++++++++++++-------------------- printer/printer_test.go | 46 ++++++++++++++++++---- 5 files changed, 80 insertions(+), 59 deletions(-) diff --git a/cmd/lsec2/cli/commands.go b/cmd/lsec2/cli/commands.go index 8aedf6f..4ac165e 100644 --- a/cmd/lsec2/cli/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -72,10 +72,7 @@ func newPrinter(c *cli.Context) *printer.Printer { printer.WithColor = c.Bool("c") } if c.IsSet("d") { - printer.Delimeter = c.String("d") - } - if c.IsSet("coldef") { - printer.ColDef = c.String("coldef") + printer.Delimiter = c.String("d") } return printer diff --git a/cmd/lsec2/cli/flags.go b/cmd/lsec2/cli/flags.go index 25a82eb..8c3bf40 100644 --- a/cmd/lsec2/cli/flags.go +++ b/cmd/lsec2/cli/flags.go @@ -1,8 +1,6 @@ package cli import ( - "os" - "github.com/urfave/cli" ) @@ -42,10 +40,5 @@ var ( Usage: "column delemeter for printed informations", Value: "\t", }, - cli.StringFlag{ - Name: "coldef", - Usage: "path of coldef.yml", - Value: os.Getenv("HOME") + string(os.PathSeparator) + ".lsec2" + string(os.PathSeparator) + "coldef.yml", - }, } ) diff --git a/printer/instance_info.go b/printer/instance_info.go index ad6057a..50128cc 100644 --- a/printer/instance_info.go +++ b/printer/instance_info.go @@ -31,7 +31,6 @@ func NewInstanceInfo(instance *ec2.Instance) *InstanceInfo { return &InstanceInfo{} } - // TODO: coldef.yml対応 i := &InstanceInfo{ InstanceID: fetchItem(instance.InstanceId), PrivateIPAddress: fetchItem(instance.PrivateIpAddress), diff --git a/printer/printer.go b/printer/printer.go index aa85bc3..7db9fbd 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -15,21 +15,23 @@ import ( const ( defaultDelimiter = "\t" - tabWriterMinWidth = 0 - tabWriterTabWidth = 4 - tabWriterPadding = 4 - tabWriterPadChar = ' ' - tabWriterFlags = 0 + tabMinWidth = 0 + tabTabWidth = 4 + tabPadding = 4 + tabPadChar = ' ' + tabFlags = 0 ) var ( defaultWriter = os.Stdout ) +/* type flushableWriter interface { io.Writer Flush() error } +*/ // Printer is options definition of print type Printer struct { @@ -37,43 +39,42 @@ type Printer struct { PrintHeader bool OnlyPrivateIP bool WithColor bool - Delimeter string - ColDef string + Delimiter string } // NewPrinter returns a new Printer func NewPrinter(maybeWriter interface{}) *Printer { - printer := new(Printer) + pr := new(Printer) - printer.Delimeter = defaultDelimiter + pr.Delimiter = defaultDelimiter if writer, ok := maybeWriter.(io.Writer); ok { - printer.Writer = writer + pr.Writer = writer } else { - printer.Writer = defaultWriter + pr.Writer = defaultWriter } - return printer + return pr } // PrintAll prints information all of aws ec2 instances -func (printer *Printer) PrintAll(client *awsec2.Client) error { +func (pr *Printer) PrintAll(client *awsec2.Client) error { instances, err := client.EC2Instances() if err != nil { return fmt.Errorf("get EC2 Instances error: %v", err) } - printer.wrapWriterIfDefault() - defer printer.flushIfFlushable() + pr.wrapWriterIfDefault() + defer pr.flushIfFlushable() - if printer.PrintHeader { - if err := printer.printHeader(); err != nil { + if pr.PrintHeader { + if err := pr.printHeader(); err != nil { return fmt.Errorf("print header error: %v", err) } } for _, inst := range instances { - if err := printer.printInstance(client, inst); err != nil { + if err := pr.printInstance(client, inst); err != nil { return fmt.Errorf("print instance error: %v", err) } } @@ -81,34 +82,33 @@ func (printer *Printer) PrintAll(client *awsec2.Client) error { return nil } -func (printer *Printer) wrapWriterIfDefault() { - if printer.Writer == defaultWriter { - if printer.Delimeter == defaultDelimiter { - printer.Writer = tabwriter.NewWriter( - printer.Writer, - tabWriterMinWidth, - tabWriterTabWidth, - tabWriterPadding, - tabWriterPadChar, - tabWriterFlags, +func (pr *Printer) wrapWriterIfDefault() { + if pr.Writer == defaultWriter { + if pr.Delimiter == defaultDelimiter { + pr.Writer = tabwriter.NewWriter( + pr.Writer, + tabMinWidth, + tabTabWidth, + tabPadding, + tabPadChar, + tabFlags, ) } } } -func (printer *Printer) flushIfFlushable() { - // FIXME: - // printer.Writer.(interface{Flush() error}) とも書けそう。どちらがパフォーマンスが良いか? - if fw, ok := printer.Writer.(flushableWriter); ok { +func (pr *Printer) flushIfFlushable() { + //if fw, ok := pr.Writer.(flushableWriter); ok { + if fw, ok := pr.Writer.(interface{ Flush() error }); ok { fw.Flush() } } -func (printer *Printer) printHeader() error { - return printer.printArray(NewInstanceInfo(nil).Headers()) +func (pr *Printer) printHeader() error { + return pr.printArray(NewInstanceInfo(nil).Headers()) } -func (printer *Printer) printInstance(client *awsec2.Client, inst *ec2.Instance) error { +func (pr *Printer) printInstance(client *awsec2.Client, inst *ec2.Instance) error { var ( ii *InstanceInfo err error @@ -116,18 +116,18 @@ func (printer *Printer) printInstance(client *awsec2.Client, inst *ec2.Instance) ii = NewInstanceInfo(inst) if len(client.StateName) == 0 || client.StateName == ii.StateName { - if printer.OnlyPrivateIP { - err = printer.printArray([]string{ii.PrivateIPAddress}) + if pr.OnlyPrivateIP { + err = pr.printArray([]string{ii.PrivateIPAddress}) } else { - err = printer.printArray(ii.Values(printer.WithColor)) + err = pr.printArray(ii.Values(pr.WithColor)) } } return err } -func (printer *Printer) printArray(sArr []string) error { - if _, err := fmt.Fprintln(printer.Writer, strings.Join(sArr, printer.Delimeter)); err != nil { +func (pr *Printer) printArray(sArr []string) error { + if _, err := fmt.Fprintln(pr.Writer, strings.Join(sArr, pr.Delimiter)); err != nil { return err } diff --git a/printer/printer_test.go b/printer/printer_test.go index 43d66c6..88e24f9 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -2,6 +2,7 @@ package printer_test import ( "io" + "io/ioutil" "os" "testing" @@ -78,10 +79,14 @@ func TestNewPrinter(t *testing.T) { } for _, c := range cases { - printer := NewPrinter(c.maybeWriter) + pr := NewPrinter(c.maybeWriter) - if printer.Writer != c.exp.Writer { - t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, printer.Writer) + if pr.Delimiter != "\t" { + t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, pr.Writer) + } + + if pr.Writer != c.exp.Writer { + t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, pr.Writer) } } } @@ -94,18 +99,45 @@ func TestPrintAll(t *testing.T) { Tags: []string{"Role=roleA,roleB", "Service=serviceX"}, } + tmp, err := ioutil.TempFile("", "test_lsec2_printer") + if err != nil { + t.Errorf("failed to ioutil.TempFile. err: %#v", err) + } + defer os.Remove(tmp.Name()) + cases := []struct { - printer *Printer + pr *Printer }{ { - printer: &Printer{ - Writer: os.Stdout, + pr: &Printer{ + Writer: os.Stdout, + PrintHeader: true, + OnlyPrivateIP: false, + WithColor: true, + Delimiter: "\t", + }, + }, + { + pr: &Printer{ + Writer: tmp, + PrintHeader: false, + OnlyPrivateIP: false, + WithColor: false, + Delimiter: ",", + }, + }, + { + pr: &Printer{ + Writer: tmp, + PrintHeader: false, + OnlyPrivateIP: true, + WithColor: false, }, }, } for _, c := range cases { - err := c.printer.PrintAll(client) + err := c.pr.PrintAll(client) if err != nil { t.Errorf("error occured. err: %#v", err) From 787a17a22cd104cba945ba7c868651c08f7fc289 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:17:36 +0900 Subject: [PATCH 21/34] available aws credentials profile --- awsec2/client.go | 28 ++++++++++----- awsec2/client_test.go | 72 ++++++++++++++++++++++++++++----------- cmd/lsec2/cli/commands.go | 2 +- cmd/lsec2/cli/flags.go | 4 +++ printer/printer_test.go | 2 -- 5 files changed, 78 insertions(+), 30 deletions(-) diff --git a/awsec2/client.go b/awsec2/client.go index 3710584..7366053 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" @@ -21,24 +22,28 @@ const ( // Client is attributes definition for filtering ec2 instances type Client struct { ec2iface.EC2API - Region string StateName string Tags []string } // NewClient returns a new DefaultClient -func NewClient(region string, maybeEC2Client interface{}) *Client { +func NewClient(region string, profile string) *Client { client := new(Client) + client.EC2API = defaultEC2Client(region, profile) - client.Region = region + return client +} + +// NewClientWithEC2API returns a new Client with assigned EC2API variable +func NewClientWithEC2API(maybeEC2Client interface{}) (*Client, error) { + client := new(Client) if ec2Client, ok := maybeEC2Client.(ec2iface.EC2API); ok { client.EC2API = ec2Client + return client, nil } else { - client.EC2API = defaultEC2Client(region) + return nil, fmt.Errorf("maybeEC2Client %#v does not implement ec2.EC2API methods", maybeEC2Client) } - - return client } // EC2Instances gets filtered EC2 instances @@ -56,9 +61,16 @@ func (client *Client) EC2Instances() ([]*ec2.Instance, error) { return res, nil } -func defaultEC2Client(region string) ec2iface.EC2API { - config := &aws.Config{Region: aws.String(region)} +func defaultEC2Client(region string, profile string) ec2iface.EC2API { + config := aws.NewConfig() + if region != "" { + config = config.WithRegion(region) + } + if profile != "" { + config = config.WithCredentials(credentials.NewSharedCredentials("", profile)) + } sess := session.Must(session.NewSession(config)) + return ec2.New(sess) } diff --git a/awsec2/client_test.go b/awsec2/client_test.go index e1ca267..bf0eb01 100644 --- a/awsec2/client_test.go +++ b/awsec2/client_test.go @@ -63,36 +63,72 @@ func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*e } func TestNewClient(t *testing.T) { - mockClient := &mockEC2API{} - cases := []struct { - region string - ec2Client ec2iface.EC2API - expected *Client + region string + profile string + expected *Client }{ { - region: "ap-northeast-1", - ec2Client: mockClient, + region: "ap-northeast-1", + profile: "", expected: &Client{ - EC2API: mockClient, - Region: "ap-northeast-1", + StateName: "", + Tags: []string{}, }, }, { - region: "us-east-1", + region: "us-east-1", + profile: "test", + expected: &Client{ + StateName: "", + Tags: []string{}, + }, + }, + } + + for _, c := range cases { + client := NewClient(c.region, c.profile) + + if client.StateName != c.expected.StateName { + t.Errorf("expected: %#v, but actual: %#v", c.expected.StateName, client.StateName) + } + if client.Tags != nil { + t.Errorf("expected: nil, but actual: %#v", client.Tags) + } + } +} + +func TestNewClientEC2API(t *testing.T) { + mockClient := &mockEC2API{} + + cases := []struct { + ec2Client ec2iface.EC2API + expected *Client + }{ + { ec2Client: mockClient, expected: &Client{ - EC2API: mockClient, - Region: "us-east-1", + StateName: "", + Tags: []string{}, + EC2API: mockClient, }, }, } for _, c := range cases { - client := NewClient(c.region, c.ec2Client) + client, err := NewClientWithEC2API(c.ec2Client) + if err != nil { + t.Errorf("error occured. err: %#v", err) + } - if client.Region != c.expected.Region { - t.Errorf("expected: %#v, but expected: %#v", c.expected.Region, client.Region) + if client.StateName != c.expected.StateName { + t.Errorf("expected: %#v, but actual: %#v", c.expected.StateName, client.StateName) + } + if client.Tags != nil { + t.Errorf("expected: nil, but actual: %#v", client.Tags) + } + if client.EC2API != c.expected.EC2API { + t.Errorf("expected: %#v, but actual: %#v", c.expected.EC2API, client.EC2API) } } } @@ -105,7 +141,6 @@ func TestEC2Instances(t *testing.T) { { client: &Client{ EC2API: &mockEC2API{}, - Region: "ap-northeast-1", StateName: "running", Tags: []string{"Role=roleA,roleB", "Service=serviceX"}, }, @@ -114,8 +149,7 @@ func TestEC2Instances(t *testing.T) { { client: &Client{ EC2API: &mockEC2API{}, - Region: "us-east-1", - StateName: "running", + StateName: "stopped", }, expected: dummyInstances, }, @@ -129,7 +163,7 @@ func TestEC2Instances(t *testing.T) { } if len(c.expected) != len(insts) { - t.Errorf("not same instances length. expected: %#v, but expected: %#v", len(c.expected), len(insts)) + t.Errorf("not same instances length. expected: %#v, but actual: %#v", len(c.expected), len(insts)) } } } diff --git a/cmd/lsec2/cli/commands.go b/cmd/lsec2/cli/commands.go index 4ac165e..6c2cc10 100644 --- a/cmd/lsec2/cli/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -48,7 +48,7 @@ func action(c *cli.Context) error { } func newClient(c *cli.Context) *awsec2.Client { - client := awsec2.NewClient(c.String("region"), nil) + client := awsec2.NewClient(c.String("region"), c.String("profile")) client.Tags = c.Args() if c.IsSet("s") { diff --git a/cmd/lsec2/cli/flags.go b/cmd/lsec2/cli/flags.go index 8c3bf40..e158ea7 100644 --- a/cmd/lsec2/cli/flags.go +++ b/cmd/lsec2/cli/flags.go @@ -40,5 +40,9 @@ var ( Usage: "column delemeter for printed informations", Value: "\t", }, + cli.StringFlag{ + Name: "profile", + Usage: "AWS config profile name", + }, } ) diff --git a/printer/printer_test.go b/printer/printer_test.go index 88e24f9..3f039ef 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -94,9 +94,7 @@ func TestNewPrinter(t *testing.T) { func TestPrintAll(t *testing.T) { client := &awsec2.Client{ EC2API: &mockEC2API{}, - Region: "ap-northeast-1", StateName: "running", - Tags: []string{"Role=roleA,roleB", "Service=serviceX"}, } tmp, err := ioutil.TempFile("", "test_lsec2_printer") From b8803396a74ccabae1249f1e60e8ced1685dad50 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:20:42 +0900 Subject: [PATCH 22/34] fix error display --- cmd/lsec2/cli/commands.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/cmd/lsec2/cli/commands.go b/cmd/lsec2/cli/commands.go index 6c2cc10..0a20e57 100644 --- a/cmd/lsec2/cli/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -2,7 +2,6 @@ package cli import ( "fmt" - "os" "github.com/goldeneggg/lsec2/awsec2" "github.com/goldeneggg/lsec2/cmd/lsec2/version" @@ -40,7 +39,6 @@ func action(c *cli.Context) error { } if err := newPrinter(c).PrintAll(newClient(c)); err != nil { - fmt.Fprintf(os.Stderr, "%v\n", err) return err } From 5c97b9d309d8d4a79e72b8db77df13fc4a485698 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:31:40 +0900 Subject: [PATCH 23/34] fix version --- cmd/lsec2/version/version.go | 2 +- cmd/lsec2/version/version_test.go | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 cmd/lsec2/version/version_test.go diff --git a/cmd/lsec2/version/version.go b/cmd/lsec2/version/version.go index 8e13470..1b5339e 100644 --- a/cmd/lsec2/version/version.go +++ b/cmd/lsec2/version/version.go @@ -1,4 +1,4 @@ package version // VERSION says my version number -const VERSION = "0.3.0" +const VERSION = "0.2.7" diff --git a/cmd/lsec2/version/version_test.go b/cmd/lsec2/version/version_test.go new file mode 100644 index 0000000..a65d96a --- /dev/null +++ b/cmd/lsec2/version/version_test.go @@ -0,0 +1,14 @@ +package version_test + +import ( + "testing" + + . "github.com/goldeneggg/lsec2/cmd/lsec2/version" +) + +func TestVersion(t *testing.T) { + exp := "0.2.7" + if VERSION != "0.2.7" { + t.Errorf("expected: %#v, but actual: %#v", exp, VERSION) + } +} From 74285b2ba9a12c7991edc92ebfef530a3bb8dc8e Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:31:50 +0900 Subject: [PATCH 24/34] fix test message --- printer/printer_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/printer/printer_test.go b/printer/printer_test.go index 3f039ef..7b853dd 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -82,11 +82,11 @@ func TestNewPrinter(t *testing.T) { pr := NewPrinter(c.maybeWriter) if pr.Delimiter != "\t" { - t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, pr.Writer) + t.Errorf("expected: %#v, but actual: %#v", c.exp.Writer, pr.Writer) } if pr.Writer != c.exp.Writer { - t.Errorf("expected: %#v, but exp: %#v", c.exp.Writer, pr.Writer) + t.Errorf("expected: %#v, but actual: %#v", c.exp.Writer, pr.Writer) } } } From 1901a04eb8a45849e144e1e867192d62eeffd264 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:33:37 +0900 Subject: [PATCH 25/34] fix vet error --- awsec2/client.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/awsec2/client.go b/awsec2/client.go index 7366053..8614025 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -41,9 +41,9 @@ func NewClientWithEC2API(maybeEC2Client interface{}) (*Client, error) { if ec2Client, ok := maybeEC2Client.(ec2iface.EC2API); ok { client.EC2API = ec2Client return client, nil - } else { - return nil, fmt.Errorf("maybeEC2Client %#v does not implement ec2.EC2API methods", maybeEC2Client) } + + return nil, fmt.Errorf("maybeEC2Client %#v does not implement ec2.EC2API methods", maybeEC2Client) } // EC2Instances gets filtered EC2 instances From cc53c1e2df72a1cf2332275f103c8fa1a5a75844 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:36:06 +0900 Subject: [PATCH 26/34] add validate target into ci target --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 69c9513..c33542d 100644 --- a/Makefile +++ b/Makefile @@ -31,7 +31,7 @@ ci-test: @./scripts/ci-test.sh .PHONY: ci -ci: ci-test +ci: ci-test validate .PHONY: prof prof: From 5cab2cef1c9fdae737eaee1e40324181ea0ab22b Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:51:27 +0900 Subject: [PATCH 27/34] fix vet target --- Makefile | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index c33542d..b3a3015 100644 --- a/Makefile +++ b/Makefile @@ -27,12 +27,6 @@ install: test: @go test -race -cover -v $(PACKAGES) -ci-test: - @./scripts/ci-test.sh - -.PHONY: ci -ci: ci-test validate - .PHONY: prof prof: @[ ! -d $(PROF_DIR) ] && mkdir $(PROF_DIR); go test -bench . -benchmem -cover -coverprofile $(PROF_DIR)/cover.out $(PACKAGES) @@ -48,7 +42,7 @@ prof-full-cmd-cli: .PHONY: vet vet: - @go vet -n -x $(PACKAGES) + @go vet $(PACKAGES) .PHONY: lint lint: @@ -57,6 +51,12 @@ lint: .PHONY: validate validate: vet lint +ci-test: + @./scripts/ci-test.sh + +.PHONY: ci +ci: ci-test validate + .PHONY: vendor vendor: @GO111MODULE=on go mod vendor From 694a5d147066a3f9b4c9f33d33f413005dece950 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Fri, 15 Mar 2019 23:52:30 +0900 Subject: [PATCH 28/34] update go.mod --- go.mod | 44 +++------------------ go.sum | 122 ++++++--------------------------------------------------- 2 files changed, 18 insertions(+), 148 deletions(-) diff --git a/go.mod b/go.mod index ad0a9b8..8831f62 100644 --- a/go.mod +++ b/go.mod @@ -1,48 +1,16 @@ module github.com/goldeneggg/lsec2 require ( - github.com/alecthomas/gometalinter v3.0.0+incompatible // indirect - github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect github.com/aws/aws-sdk-go v1.17.14 - github.com/cosiner/argv v0.0.1 // indirect - github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d // indirect + github.com/davecgh/go-spew v1.1.1 // indirect github.com/fatih/color v1.7.0 - github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6 // indirect - github.com/fatih/motion v0.0.0-20180408211639-218875ebe238 // indirect - github.com/go-delve/delve v1.2.0 // indirect - github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf // indirect - github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4 // indirect - github.com/jstemmer/gotags v1.4.1 // indirect - github.com/keegancsmith/rpc v1.1.0 // indirect - github.com/kisielk/errcheck v1.2.0 // indirect - github.com/klauspost/asmfmt v1.2.0 // indirect - github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect - github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91 // indirect github.com/mattn/go-colorable v0.1.1 // indirect github.com/mattn/go-isatty v0.0.6 // indirect - github.com/mattn/go-runewidth v0.0.4 // indirect - github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f // indirect - github.com/nicksnyder/go-i18n v1.10.0 // indirect - github.com/pelletier/go-toml v1.2.0 // indirect - github.com/peterh/liner v1.1.0 // indirect - github.com/pkg/profile v1.2.1 // indirect - github.com/rogpeppe/godef v1.1.1 // indirect - github.com/sirupsen/logrus v1.3.0 // indirect - github.com/spf13/cobra v0.0.3 // indirect - github.com/spf13/pflag v1.0.3 // indirect - github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476 // indirect github.com/stretchr/testify v1.3.0 // indirect github.com/urfave/cli v1.20.0 - github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a // indirect - golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8 // indirect - golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 // indirect - golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f // indirect - golang.org/x/net v0.0.0-20190310074541-c10a0554eabf // indirect - golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa // indirect - golang.org/x/text v0.3.0 // indirect - golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f // indirect - gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c // indirect - gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect - gopkg.in/yaml.v2 v2.2.2 - honnef.co/go/tools v0.0.0-20190215041234-466a0476246c // indirect + golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a // indirect + golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect + golang.org/x/net v0.0.0-20190313220215-9f648a60d977 // indirect + golang.org/x/sys v0.0.0-20190312061237-fead79001313 // indirect + golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2 // indirect ) diff --git a/go.sum b/go.sum index cfcd205..d31d42a 100644 --- a/go.sum +++ b/go.sum @@ -1,137 +1,39 @@ -9fans.net/go v0.0.0-20181112161441-237454027057 h1:OcHlKWkAMJEF1ndWLGxp5dnJQkYM/YImUOvsBoz6h5E= -9fans.net/go v0.0.0-20181112161441-237454027057/go.mod h1:diCsxrliIURU9xsYtjCp5AbpQKqdhKmf0ujWDUSkfoY= -github.com/alecthomas/gometalinter v3.0.0+incompatible h1:e9Zfvfytsw/e6Kd/PYd75wggK+/kX5Xn8IYDUKyc5fU= -github.com/alecthomas/gometalinter v3.0.0+incompatible/go.mod h1:qfIpQGGz3d+NmgyPBqv+LSh50emm1pt72EtcX2vKYQk= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf h1:qet1QNfXsQxTZqLG4oE62mJzwPIB8+Tee4RNCL9ulrY= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/aws/aws-sdk-go v1.17.7 h1:/4+rDPe0W95KBmNGYCG+NUvdL8ssPYBMxL+aSCg6nIA= -github.com/aws/aws-sdk-go v1.17.7/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.17.14 h1:IjqZDIQoLyZ48A93BxVrZOaIGgZPRi4nXt6WQUMJplY= github.com/aws/aws-sdk-go v1.17.14/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/cosiner/argv v0.0.0-20170225145430-13bacc38a0a5/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ= -github.com/cosiner/argv v0.0.1 h1:2iAFN+sWPktbZ4tvxm33Ei8VY66FPCxdOxpncUGpAXE= -github.com/cosiner/argv v0.0.1/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ= -github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d h1:aRvyac5PN1NEfcANJ1tfs8GMs5I9OXsVeg0FJkpXOys= -github.com/davidrjenni/reftools v0.0.0-20180914123528-654d0ba4f96d/go.mod h1:8o/GRMvsb9VyFbSEZGXfa0dkSXml4G23W0D/h9FksWM= -github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= -github.com/fatih/camelcase v1.0.0/go.mod h1:yN2Sb0lFhZJUdVvtELVWefmrXpuZESvPmqwoZc+/fpc= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6 h1:iXJdM8Uob6EPOG/PFr5q0J124ysiZdJfACHqICBb3b8= -github.com/fatih/gomodifytags v0.0.0-20180914191908-141225bf62b6/go.mod h1:p2/x7bnOQsbq/deXsDIlj2yLiKFGPkD2nuoYqwn8R4Y= -github.com/fatih/motion v0.0.0-20180408211639-218875ebe238 h1:Qo4RxRMFag+fvDqQ6A3MblYBormptQUZ1ssOtV+EeQ8= -github.com/fatih/motion v0.0.0-20180408211639-218875ebe238/go.mod h1:pseIrV+t9A4+po+KJ1LheSnYH8m1qs6WhKx2zFiGi9I= -github.com/fatih/structtag v1.0.0 h1:pTHj65+u3RKWYPSGaU290FpI/dXxTaHdVwVwbcPKmEc= -github.com/fatih/structtag v1.0.0/go.mod h1:IKitwq45uXL/yqi5mYghiD3w9H6eTOvI9vnk8tXMphA= -github.com/go-delve/delve v1.2.0 h1:uwGyfYO0WsWqbnDWvxCBKOr2qFLpii3tLxwM+fTJs70= -github.com/go-delve/delve v1.2.0/go.mod h1:yP+LD36s/ud5nm4lsQY0TwNhYu2PAwk6xItz+442j74= -github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf h1:7+FW5aGwISbqUtkfmIpZJGRgNFg2ioYPvFaUxdqpDsg= -github.com/google/shlex v0.0.0-20181106134648-c34317bd91bf/go.mod h1:RpwtwJQFrIEPstU94h88MWPXP2ektJZ8cZ0YntAmXiE= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4 h1:gmIVMdGlVf5e6Yo6+ZklxdOrvtOvyrAjJyXAbmOznyo= -github.com/josharian/impl v0.0.0-20180228163738-3d0f908298c4/go.mod h1:t4Tr0tn92eq5ISef4cS5plFAMYAqZlAXtgUcKE6y8nw= -github.com/jstemmer/gotags v1.4.1 h1:aWIyXsU3lTDqhsEC49MP85p2cUUWr2ptvdGNqqGA3r4= -github.com/jstemmer/gotags v1.4.1/go.mod h1:b6J3X0bsLbR4C5SgSx3V3KjuWTtmRzcmWPbTkWZ49PA= -github.com/keegancsmith/rpc v1.1.0 h1:bXVRk3EzbtrEegTGKxNTc+St1lR7t/Z1PAO8misBnCc= -github.com/keegancsmith/rpc v1.1.0/go.mod h1:Xow74TKX34OPPiPCdz6x1o9c0SCxRqGxDuKGk7ZOo8s= -github.com/kisielk/errcheck v1.2.0 h1:reN85Pxc5larApoH1keMBiu2GWtPqXQ1nc9gx+jOU+E= -github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= -github.com/klauspost/asmfmt v1.2.0 h1:zwsyBYgEdabg32alMful/5pRtMTcR5C5w1LKNg9OD78= -github.com/klauspost/asmfmt v1.2.0/go.mod h1:RAoUvqkWr2rUa2I19qKMEVZQe4BVtcHGTMCUOcCU2Lg= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91 h1:hunjgdb3b21ZdRmzDPXii0EcnHpjH7uCP+kODoE1JH0= -github.com/koron/iferr v0.0.0-20180615142939-bb332a3b1d91/go.mod h1:C2tFh8w3I6i4lnUJfoBx2Hwku3mgu4wPNTtUNp1i5KI= -github.com/mattn/go-colorable v0.0.0-20170327083344-ded68f7a9561/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.6 h1:SrwhHcpV4nWrMGdNcC2kXpMfcBVYGDuTArqyhocJgvA= github.com/mattn/go-isatty v0.0.6/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= -github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f h1:ee+twVCignaZjt7jpbMSLxAeTN/Nfq9W/nm91E7QO1A= -github.com/mdempsky/gocode v0.0.0-20190203001940-7fb65232883f/go.mod h1:hltEC42XzfMNgg0S1v6JTywwra2Mu6F6cLR03debVQ8= -github.com/nicksnyder/go-i18n v1.10.0 h1:5AzlPKvXBH4qBzmZ09Ua9Gipyruv6uApMcrNZdo96+Q= -github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2xBGjv0j365Q= -github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/peterh/liner v0.0.0-20170317030525-88609521dc4b/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= -github.com/peterh/liner v1.1.0 h1:f+aAedNJA6uk7+6rXsYBnhdo4Xux7ESLe+kcuVUF5os= -github.com/peterh/liner v1.1.0/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0= -github.com/pkg/profile v0.0.0-20170413231811-06b906832ed0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= -github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/godef v1.1.1 h1:NujOtt9q9vIClRTB3sCZpavac+NMRaIayzrcz1h4fSE= -github.com/rogpeppe/godef v1.1.1/go.mod h1:oEo1eMy1VUEHUzUIX4F7IqvMJRiz9UId44mvnR8oPlQ= -github.com/russross/blackfriday v0.0.0-20180428102519-11635eb403ff/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/sirupsen/logrus v0.0.0-20180523074243-ea8897e79973/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= -github.com/sirupsen/logrus v1.3.0 h1:hI/7Q+DtNZ2kINb6qt/lS+IyXnHQe9e90POfeewL/ME= -github.com/sirupsen/logrus v1.3.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/spf13/cobra v0.0.0-20170417170307-b6cb39589372/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/pflag v0.0.0-20170417173400-9e4c21054fa1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476 h1:KtMuvAziiZPINAWNvK1cNpAcqCHbDwNhpLbQw0rg6YY= -github.com/stamblerre/gocode v0.0.0-20190213022308-8cc90faaf476/go.mod h1:EM2T8YDoTCvGXbEpFHxarbpv7VE26QD1++Cb1Pbh7Gs= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a h1:00UFliGZl2UciXe8o/2iuEsRQ9u7z0rzDTVzuj6EYY0= -github.com/zmb3/gogetdoc v0.0.0-20190228002656-b37376c5da6a/go.mod h1:ofmGw6LrMypycsiWcyug6516EXpIxSbZ+uI9ppGypfY= -golang.org/x/arch v0.0.0-20171004143515-077ac972c2e4/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= -golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8 h1:G3kY3WDPiChidkYzLqbniw7jg23paUtzceZorG6YAJw= -golang.org/x/arch v0.0.0-20190226203302-36aee92af9e8/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8= -golang.org/x/crypto v0.0.0-20180614174826-fd5f17ee7299/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f h1:hX65Cu3JDlGH3uEdK7I99Ii+9kjD6mvnnpfLdEAH0x4= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd h1:HuTn7WObtcDo9uEEU7rEqL0jYthdXAmZ6PP+meazmaU= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190310074541-c10a0554eabf/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0 h1:x4M4WCms+ErQg/4VyECbP2kSNcDJ6nLwqEGov1QPtqk= -golang.org/x/sys v0.0.0-20171130163741-8b4580aae2a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180614134839-8883426083c0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190313220215-9f648a60d977 h1:actzWV6iWn3GLqN8dZjzsB+CLt+gaV2+wsxroxiQI8I= +golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa h1:lqti/xP+yD/6zH5TqEwx2MilNIJY5Vbc6Qr8J3qyPIQ= -golang.org/x/sys v0.0.0-20190310054646-10058d7d4faa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190312061237-fead79001313 h1:pczuHS43Cp2ktBEEmLwScxgjWsBSzdaQiKzUyf3DTTc= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/tools v0.0.0-20180824175216-6c1c5e93cdc1/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181120060634-fc4f04983f62/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181130195746-895048a75ecf/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181207195948-8634b1ecd393/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f h1:SUQ6L9W8e5xt2GFO9s+i18JGITAfem+a0AQuFU8Ls74= -golang.org/x/tools v0.0.0-20190308174544-00c44ba9c14f/go.mod h1:25r3+/G6/xytQM8iWZKq3Hn0kr0rgFKPUNVEL/dr3z4= -gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c h1:vTxShRUnK60yd8DZU+f95p1zSLj814+5CuEh7NjF2/Y= -gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c/go.mod h1:3HH7i1SgMqlzxCcBmUHW657sD4Kvv9sC3HpL3YukzwA= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.0.0-20170407172122-cd8b52f8269e/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -honnef.co/go/tools v0.0.0-20190215041234-466a0476246c h1:z+UFwlQ7KVwdlQTE5JjvDvfZmyyAVrEiiwau20b7X8k= -honnef.co/go/tools v0.0.0-20190215041234-466a0476246c/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2 h1:UW7QBl+AuPLMXy5g3iGofcPmCH+CajjwwKguuuJCS3E= +golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= From 48ee05623ebdc3a33f1a5fd6a329464335760814 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 00:05:11 +0900 Subject: [PATCH 29/34] fix CI --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index b3a3015..80adffb 100644 --- a/Makefile +++ b/Makefile @@ -46,7 +46,7 @@ vet: .PHONY: lint lint: - @${GOBIN}/golint -set_exit_status $(PACKAGES) + @golint -set_exit_status $(PACKAGES) .PHONY: validate validate: vet lint From 71b10d76769942bd3d709db332d577943716e3f2 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 00:13:56 +0900 Subject: [PATCH 30/34] fix lint for CI --- Makefile | 2 +- go.mod | 3 --- go.sum | 7 ------- 3 files changed, 1 insertion(+), 11 deletions(-) diff --git a/Makefile b/Makefile index 80adffb..1a95b3b 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ ci-test: @./scripts/ci-test.sh .PHONY: ci -ci: ci-test validate +ci: ci-test vet .PHONY: vendor vendor: diff --git a/go.mod b/go.mod index 8831f62..57a649e 100644 --- a/go.mod +++ b/go.mod @@ -8,9 +8,6 @@ require ( github.com/mattn/go-isatty v0.0.6 // indirect github.com/stretchr/testify v1.3.0 // indirect github.com/urfave/cli v1.20.0 - golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a // indirect - golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 // indirect golang.org/x/net v0.0.0-20190313220215-9f648a60d977 // indirect golang.org/x/sys v0.0.0-20190312061237-fead79001313 // indirect - golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2 // indirect ) diff --git a/go.sum b/go.sum index d31d42a..80a4508 100644 --- a/go.sum +++ b/go.sum @@ -22,10 +22,6 @@ github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190313024323-a1f597ede03a/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3 h1:XQyxROzUlZH+WIQwySDgnISgOivlhjIEwaQaJEJrrN0= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190313220215-9f648a60d977 h1:actzWV6iWn3GLqN8dZjzsB+CLt+gaV2+wsxroxiQI8I= golang.org/x/net v0.0.0-20190313220215-9f648a60d977/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -34,6 +30,3 @@ golang.org/x/sys v0.0.0-20190312061237-fead79001313 h1:pczuHS43Cp2ktBEEmLwScxgjW golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2 h1:UW7QBl+AuPLMXy5g3iGofcPmCH+CajjwwKguuuJCS3E= -golang.org/x/tools v0.0.0-20190315044204-8b67d361bba2/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= From fd66806b8b03603e249d1e4b26dc825fc4d50a5b Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 02:01:53 +0900 Subject: [PATCH 31/34] refactoring --- awsec2/client.go | 25 +++++++------ awsec2/client_test.go | 58 ++++++++++++++++++++++++------ cmd/lsec2/cli/commands.go | 37 ++++++------------- printer/printer.go | 51 +++++++++++++------------- printer/printer_test.go | 76 +++++++++++++++++++++++++++------------ 5 files changed, 151 insertions(+), 96 deletions(-) diff --git a/awsec2/client.go b/awsec2/client.go index 8614025..7b209e4 100644 --- a/awsec2/client.go +++ b/awsec2/client.go @@ -27,23 +27,28 @@ type Client struct { } // NewClient returns a new DefaultClient -func NewClient(region string, profile string) *Client { - client := new(Client) - client.EC2API = defaultEC2Client(region, profile) - - return client +func NewClient(region, state, profile string, tags []string) (*Client, error) { + return NewClientWithEC2API(region, state, profile, tags, nil) } // NewClientWithEC2API returns a new Client with assigned EC2API variable -func NewClientWithEC2API(maybeEC2Client interface{}) (*Client, error) { +func NewClientWithEC2API(region, state, profile string, tags []string, c interface{}) (*Client, error) { client := new(Client) - if ec2Client, ok := maybeEC2Client.(ec2iface.EC2API); ok { - client.EC2API = ec2Client - return client, nil + client.StateName = state + client.Tags = tags + + if c != nil { + if ec2, ok := c.(ec2iface.EC2API); ok { + client.EC2API = ec2 + } else { + return nil, fmt.Errorf("arg %#v does not implement ec2.EC2API methods", c) + } + } else { + client.EC2API = defaultEC2Client(region, profile) } - return nil, fmt.Errorf("maybeEC2Client %#v does not implement ec2.EC2API methods", maybeEC2Client) + return client, nil } // EC2Instances gets filtered EC2 instances diff --git a/awsec2/client_test.go b/awsec2/client_test.go index bf0eb01..a5009e4 100644 --- a/awsec2/client_test.go +++ b/awsec2/client_test.go @@ -65,35 +65,49 @@ func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*e func TestNewClient(t *testing.T) { cases := []struct { region string + state string profile string + tags []string expected *Client }{ { region: "ap-northeast-1", + state: "running", profile: "", + tags: []string{"Tag1=Value1", "Tag2=Value2"}, expected: &Client{ - StateName: "", - Tags: []string{}, + StateName: "running", + Tags: []string{"Tag1=Value1", "Tag2=Value2"}, }, }, { region: "us-east-1", + state: "stopped", profile: "test", + tags: []string{}, expected: &Client{ - StateName: "", + StateName: "stopped", Tags: []string{}, }, }, } for _, c := range cases { - client := NewClient(c.region, c.profile) + client, err := NewClient(c.region, c.state, c.profile, c.tags) + if err != nil { + t.Errorf("error occured. err: %#v", err) + } if client.StateName != c.expected.StateName { t.Errorf("expected: %#v, but actual: %#v", c.expected.StateName, client.StateName) } - if client.Tags != nil { - t.Errorf("expected: nil, but actual: %#v", client.Tags) + for i, tag := range client.Tags { + if tag != c.expected.Tags[i] { + t.Errorf("expected: %#v, but actual: %#v", c.expected.Tags[i], tag) + } + } + if _, ok := client.EC2API.(*ec2.EC2); !ok { + t.Errorf("expected: *ec2.EC2, but actual: %#v", client.EC2API) } } } @@ -102,21 +116,41 @@ func TestNewClientEC2API(t *testing.T) { mockClient := &mockEC2API{} cases := []struct { + region string + state string + profile string + tags []string ec2Client ec2iface.EC2API expected *Client }{ { + region: "ap-northeast-1", + state: "running", + profile: "", + tags: []string{"Tag1=Value1", "Tag2=Value2"}, ec2Client: mockClient, expected: &Client{ - StateName: "", - Tags: []string{}, EC2API: mockClient, + StateName: "running", + Tags: []string{"Tag1=Value1", "Tag2=Value2"}, + }, + }, + { + region: "us-east-1", + state: "stopped", + profile: "test", + tags: []string{}, + ec2Client: mockClient, + expected: &Client{ + EC2API: mockClient, + StateName: "stopped", + Tags: []string{}, }, }, } for _, c := range cases { - client, err := NewClientWithEC2API(c.ec2Client) + client, err := NewClientWithEC2API(c.region, c.state, c.profile, c.tags, c.ec2Client) if err != nil { t.Errorf("error occured. err: %#v", err) } @@ -124,8 +158,10 @@ func TestNewClientEC2API(t *testing.T) { if client.StateName != c.expected.StateName { t.Errorf("expected: %#v, but actual: %#v", c.expected.StateName, client.StateName) } - if client.Tags != nil { - t.Errorf("expected: nil, but actual: %#v", client.Tags) + for i, tag := range client.Tags { + if tag != c.expected.Tags[i] { + t.Errorf("expected: %#v, but actual: %#v", c.expected.Tags[i], tag) + } } if client.EC2API != c.expected.EC2API { t.Errorf("expected: %#v, but actual: %#v", c.expected.EC2API, client.EC2API) diff --git a/cmd/lsec2/cli/commands.go b/cmd/lsec2/cli/commands.go index 0a20e57..97cf969 100644 --- a/cmd/lsec2/cli/commands.go +++ b/cmd/lsec2/cli/commands.go @@ -38,42 +38,25 @@ func action(c *cli.Context) error { return nil } - if err := newPrinter(c).PrintAll(newClient(c)); err != nil { + pr := newPrinter(c) + client, err := newClient(c) + if err != nil { return err } - return nil -} - -func newClient(c *cli.Context) *awsec2.Client { - client := awsec2.NewClient(c.String("region"), c.String("profile")) - - client.Tags = c.Args() - if c.IsSet("s") { - client.StateName = c.String("s") + if err := pr.PrintAll(client); err != nil { + return err } - return client + return nil } func newPrinter(c *cli.Context) *printer.Printer { - printer := printer.NewPrinter(nil) - - if c.IsSet("H") { - printer.PrintHeader = c.Bool("H") - } - if c.IsSet("p") { - printer.OnlyPrivateIP = c.Bool("p") - printer.PrintHeader = false - } - if c.IsSet("c") { - printer.WithColor = c.Bool("c") - } - if c.IsSet("d") { - printer.Delimiter = c.String("d") - } + return printer.NewPrinter(c.String("d"), c.Bool("H"), c.Bool("p"), c.Bool("c"), nil) +} - return printer +func newClient(c *cli.Context) (*awsec2.Client, error) { + return awsec2.NewClient(c.String("region"), c.String("s"), c.String("profile"), c.Args()) } func showBuildInfo(c *cli.Context) { diff --git a/printer/printer.go b/printer/printer.go index 7db9fbd..6bbeb60 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -22,10 +22,6 @@ const ( tabFlags = 0 ) -var ( - defaultWriter = os.Stdout -) - /* type flushableWriter interface { io.Writer @@ -36,27 +32,48 @@ type flushableWriter interface { // Printer is options definition of print type Printer struct { io.Writer + Delimiter string PrintHeader bool OnlyPrivateIP bool WithColor bool - Delimiter string } // NewPrinter returns a new Printer -func NewPrinter(maybeWriter interface{}) *Printer { +func NewPrinter(delim string, header, onlyPvtIP, withColor bool, w interface{}) *Printer { pr := new(Printer) - pr.Delimiter = defaultDelimiter + if delim == "" { + delim = defaultDelimiter + } + pr.Delimiter = delim + pr.PrintHeader = header + pr.OnlyPrivateIP = onlyPvtIP + pr.WithColor = withColor - if writer, ok := maybeWriter.(io.Writer); ok { + if writer, ok := w.(io.Writer); ok { pr.Writer = writer } else { - pr.Writer = defaultWriter + pr.Writer = defaultWriter(delim) } return pr } +func defaultWriter(delim string) io.Writer { + if delim == defaultDelimiter { + return tabwriter.NewWriter( + os.Stdout, + tabMinWidth, + tabTabWidth, + tabPadding, + tabPadChar, + tabFlags, + ) + } + + return os.Stdout +} + // PrintAll prints information all of aws ec2 instances func (pr *Printer) PrintAll(client *awsec2.Client) error { instances, err := client.EC2Instances() @@ -64,7 +81,6 @@ func (pr *Printer) PrintAll(client *awsec2.Client) error { return fmt.Errorf("get EC2 Instances error: %v", err) } - pr.wrapWriterIfDefault() defer pr.flushIfFlushable() if pr.PrintHeader { @@ -82,21 +98,6 @@ func (pr *Printer) PrintAll(client *awsec2.Client) error { return nil } -func (pr *Printer) wrapWriterIfDefault() { - if pr.Writer == defaultWriter { - if pr.Delimiter == defaultDelimiter { - pr.Writer = tabwriter.NewWriter( - pr.Writer, - tabMinWidth, - tabTabWidth, - tabPadding, - tabPadChar, - tabFlags, - ) - } - } -} - func (pr *Printer) flushIfFlushable() { //if fw, ok := pr.Writer.(flushableWriter); ok { if fw, ok := pr.Writer.(interface{ Flush() error }); ok { diff --git a/printer/printer_test.go b/printer/printer_test.go index 7b853dd..3056b81 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -5,6 +5,7 @@ import ( "io/ioutil" "os" "testing" + "text/tabwriter" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" @@ -59,50 +60,81 @@ func (mock *mockEC2API) DescribeInstances(input *ec2.DescribeInstancesInput) (*e func TestNewPrinter(t *testing.T) { dummyFile := os.NewFile(uintptr(3), "printer_test.go.out") - cases := []struct { - maybeWriter io.Writer - exp *Printer + delim string + header bool + onlyPvtIP bool + withColor bool + w io.Writer + expected *Printer }{ { - maybeWriter: nil, - exp: &Printer{ - Writer: os.Stdout, + delim: "", + header: true, + onlyPvtIP: false, + withColor: true, + w: nil, + expected: &Printer{ + Delimiter: "\t", + PrintHeader: true, + OnlyPrivateIP: false, + WithColor: true, }, }, { - maybeWriter: dummyFile, - exp: &Printer{ - Writer: dummyFile, + delim: ",", + header: false, + onlyPvtIP: true, + withColor: false, + w: dummyFile, + expected: &Printer{ + Writer: dummyFile, + Delimiter: ",", + PrintHeader: false, + OnlyPrivateIP: true, + WithColor: false, }, }, } for _, c := range cases { - pr := NewPrinter(c.maybeWriter) + pr := NewPrinter(c.delim, c.header, c.onlyPvtIP, c.withColor, c.w) - if pr.Delimiter != "\t" { - t.Errorf("expected: %#v, but actual: %#v", c.exp.Writer, pr.Writer) + if pr.Delimiter != c.expected.Delimiter { + t.Errorf("expected: %#v, but actual: %#v", c.expected.Delimiter, pr.Delimiter) } - - if pr.Writer != c.exp.Writer { - t.Errorf("expected: %#v, but actual: %#v", c.exp.Writer, pr.Writer) + if pr.PrintHeader != c.expected.PrintHeader { + t.Errorf("expected: %#v, but actual: %#v", c.expected.PrintHeader, pr.PrintHeader) + } + if pr.OnlyPrivateIP != c.expected.OnlyPrivateIP { + t.Errorf("expected: %#v, but actual: %#v", c.expected.OnlyPrivateIP, pr.OnlyPrivateIP) + } + if pr.WithColor != c.expected.WithColor { + t.Errorf("expected: %#v, but actual: %#v", c.expected.WithColor, pr.WithColor) + } + if c.w == nil { + if _, ok := pr.Writer.(*tabwriter.Writer); !ok { + t.Errorf("expected: *tabwriter.Writer, but actual: %#v", pr.Writer) + } + } else { + if pr.Writer != c.expected.Writer { + t.Errorf("expected: %#v, but actual: %#v", c.expected.Writer, pr.Writer) + } } } } func TestPrintAll(t *testing.T) { - client := &awsec2.Client{ - EC2API: &mockEC2API{}, - StateName: "running", - } - tmp, err := ioutil.TempFile("", "test_lsec2_printer") if err != nil { t.Errorf("failed to ioutil.TempFile. err: %#v", err) } defer os.Remove(tmp.Name()) + client := &awsec2.Client{ + EC2API: &mockEC2API{}, + StateName: "running", + } cases := []struct { pr *Printer }{ @@ -135,9 +167,7 @@ func TestPrintAll(t *testing.T) { } for _, c := range cases { - err := c.pr.PrintAll(client) - - if err != nil { + if err := c.pr.PrintAll(client); err != nil { t.Errorf("error occured. err: %#v", err) } } From 3d9e049280a076050b75ea29d061fc58856bc5cc Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 02:27:21 +0900 Subject: [PATCH 32/34] revert pretty print --- printer/printer.go | 19 +------------------ printer/printer_test.go | 9 ++++++--- 2 files changed, 7 insertions(+), 21 deletions(-) diff --git a/printer/printer.go b/printer/printer.go index 6bbeb60..ccd7dd9 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -5,7 +5,6 @@ import ( "io" "os" "strings" - "text/tabwriter" "github.com/aws/aws-sdk-go/service/ec2" @@ -14,12 +13,6 @@ import ( const ( defaultDelimiter = "\t" - - tabMinWidth = 0 - tabTabWidth = 4 - tabPadding = 4 - tabPadChar = ' ' - tabFlags = 0 ) /* @@ -60,17 +53,7 @@ func NewPrinter(delim string, header, onlyPvtIP, withColor bool, w interface{}) } func defaultWriter(delim string) io.Writer { - if delim == defaultDelimiter { - return tabwriter.NewWriter( - os.Stdout, - tabMinWidth, - tabTabWidth, - tabPadding, - tabPadChar, - tabFlags, - ) - } - + // pretty print customize is here return os.Stdout } diff --git a/printer/printer_test.go b/printer/printer_test.go index 3056b81..838d444 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -5,7 +5,6 @@ import ( "io/ioutil" "os" "testing" - "text/tabwriter" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" @@ -113,8 +112,12 @@ func TestNewPrinter(t *testing.T) { t.Errorf("expected: %#v, but actual: %#v", c.expected.WithColor, pr.WithColor) } if c.w == nil { - if _, ok := pr.Writer.(*tabwriter.Writer); !ok { - t.Errorf("expected: *tabwriter.Writer, but actual: %#v", pr.Writer) + if file, ok := pr.Writer.(*os.File); ok { + if file.Name() != "/dev/stdout" { + t.Errorf("expected: /dev/stdout, but actual: %#v", file.Name()) + } + } else { + t.Errorf("expected: *os.File, but actual: %#v", pr.Writer) } } else { if pr.Writer != c.expected.Writer { From b22746b31f66e81758948a600da2f4cae6000488 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 02:44:28 +0900 Subject: [PATCH 33/34] fix README --- README.md | 53 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 1a2cb8a..88d3f16 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,25 @@ Download from [latest release](https://github.com/goldeneggg/lsec2/releases/late ## Configuration -### Set environment variables +### Create `~/.aws/credentials` file +__If you have already installed [aws\-cli](https://github.com/aws/aws-cli), I recommend setting up by `aws configure` command.__ + +Write your credential information in `~/.aws/credentials` file. + +* Write a section + * Default is `[default]`. It's known as "Profile". +* Write `aws_access_key_id` in your section +* Write `aws_secret_access_key` in your section + +```ini +[default] +aws_access_key_id = YOUR_ACCESS_KEY_ID +aws_secret_access_key = YOUR_SECRET_ACCESS_KEY +``` + +More information: [session \- Amazon Web Services \- Go SDK](http://docs.aws.amazon.com/sdk-for-go/api/aws/session/) + +### Or Set environment variables 2 variables are required @@ -62,20 +80,22 @@ $ export AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID $ export AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY ``` -### Or create `~/.aws/credentials` file -Write your credential information in `~/.aws/credentials` file - -* Write a `[default]` section -* Write `aws_access_key_id` in `[default]` section -* Write `aws_secret_access_key` in `[default]` section +### Change runtime profile +Use `--profile` option ```ini [default] aws_access_key_id = YOUR_ACCESS_KEY_ID aws_secret_access_key = YOUR_SECRET_ACCESS_KEY -``` -More information: [session \- Amazon Web Services \- Go SDK](http://docs.aws.amazon.com/sdk-for-go/api/aws/session/) +[test] +aws_access_key_id = YOUR_ACCESS_KEY_ID2 +aws_secret_access_key = YOUR_SECRET_ACCESS_KEY2 +``` +```sh +$ lsec2 # use "default" profile +$ lsec2 --profile test # use "test" profile +``` ## Usage @@ -105,12 +125,6 @@ You can use 3 patterns $ lsec2 --region ap-northeast-1 ``` -* set `AWS_REGION` environment - -```sh -$ export AWS_REGION=ap-northeast-1 -``` - * set `AWS_SDK_LOAD_CONFIG` environment, and write `region` key in `~/.aws/config` file ```sh @@ -123,6 +137,12 @@ $ vi ~/.aws/config region = ap-northeast-1 ``` +* set `AWS_REGION` environment + +```sh +$ export AWS_REGION=ap-northeast-1 +``` + Show more information from public AWS documents * [SDK Configuration — Developer Guide](https://docs.aws.amazon.com/sdk-for-go/v1/developerguide/configuring-sdk.html) @@ -158,6 +178,9 @@ $ lsec2 -p # print state with color # ("running" is green, "stopped" is red, and others are yellow) $ lsec2 -c + +# change column delimiter (default delimiter is TAB) +$ lsec2 -d , ``` ## Tips From d57b44f909d0afd592e99ae10d3181017c945670 Mon Sep 17 00:00:00 2001 From: goldeneggg Date: Sat, 16 Mar 2019 03:53:12 +0900 Subject: [PATCH 34/34] add tests --- awsec2/client_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/awsec2/client_test.go b/awsec2/client_test.go index a5009e4..faac2cd 100644 --- a/awsec2/client_test.go +++ b/awsec2/client_test.go @@ -201,5 +201,23 @@ func TestEC2Instances(t *testing.T) { if len(c.expected) != len(insts) { t.Errorf("not same instances length. expected: %#v, but actual: %#v", len(c.expected), len(insts)) } + + for i, inst := range insts { + if inst.InstanceId != c.expected[i].InstanceId { + t.Errorf("expected: %#v, but actual: %#v", c.expected[i].InstanceId, inst.InstanceId) + } + if inst.PrivateIpAddress != c.expected[i].PrivateIpAddress { + t.Errorf("expected: %#v, but actual: %#v", c.expected[i].PrivateIpAddress, inst.PrivateIpAddress) + } + if inst.PublicIpAddress != c.expected[i].PublicIpAddress { + t.Errorf("expected: %#v, but actual: %#v", c.expected[i].PublicIpAddress, inst.PublicIpAddress) + } + if inst.InstanceType != c.expected[i].InstanceType { + t.Errorf("expected: %#v, but actual: %#v", c.expected[i].InstanceType, inst.InstanceType) + } + if inst.State.Name != c.expected[i].State.Name { + t.Errorf("expected: %#v, but actual: %#v", c.expected[i].State.Name, inst.State.Name) + } + } } }