Skip to content

Commit

Permalink
Merge pull request #5 from thaim/refactoring-stdout
Browse files Browse the repository at this point in the history
  • Loading branch information
thaim authored Jan 5, 2023
2 parents aac6394 + e6ed2ad commit 1f3a062
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 10 deletions.
10 changes: 4 additions & 6 deletions ec2id.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func NewAwsClient() (EC2DescribeInstancesAPI, error){
return ec2.NewFromConfig(cfg), nil
}

func Ec2id(name string, client EC2DescribeInstancesAPI) error {
func Ec2id(name string, client EC2DescribeInstancesAPI) (string, error) {
var params *ec2.DescribeInstancesInput = nil
if len(name) != 0 {
params = &ec2.DescribeInstancesInput{
Expand All @@ -45,11 +45,11 @@ func Ec2id(name string, client EC2DescribeInstancesAPI) error {
result, err := GetInstances(context.TODO(), client, params)
if err != nil {
fmt.Fprintln(os.Stderr, "Got an error retrieving information about your Amazon EC2 instance")
return err
return "", err
}

if len(result.Reservations) == 0 {
return nil
return "", nil
}

// TODO jmespath.Searchで書き換えるとシンプルになる?
Expand All @@ -67,7 +67,5 @@ func Ec2id(name string, client EC2DescribeInstancesAPI) error {
}
}

fmt.Println(*filteredInstance.InstanceId)

return nil
return *filteredInstance.InstanceId, nil
}
13 changes: 10 additions & 3 deletions ec2id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func TestEc2id(t *testing.T) {
Filters: []types.Filter{
{
Name: aws.String("tag:Name"),
Values: []string{"test"},
Values: []string{"noexist"},
},
},
}).
Expand All @@ -29,20 +29,24 @@ func TestEc2id(t *testing.T) {
cases := []struct {
name string
client EC2DescribeInstancesAPI
instanceName string
expect string
wantErr bool
expectErr string
}{
{
name: "",
name: "return no instance-id",
client: mockClient,
instanceName: "noexist",
expect: "",
wantErr: false,
expectErr: "",
},
}

for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
err := Ec2id("test", tt.client)
id, err := Ec2id(tt.instanceName, tt.client)
if tt.wantErr {
if (!strings.Contains(err.Error(), tt.expectErr)) {
t.Errorf("expect NoSuchKey error, got %T", err)
Expand All @@ -52,6 +56,9 @@ func TestEc2id(t *testing.T) {
if err != nil {
t.Errorf("expect no error, got error: %v", err)
}
if expected := tt.expect; id != expected {
t.Errorf("expect no output, got id: %s", id)
}
})
}
}
6 changes: 5 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ func main() {
fmt.Fprintf(os.Stderr, "initialized failed:%v\n", err)
os.Exit(1)
}
return Ec2id(name, client)
id, err := Ec2id(name, client)
if err == nil {
fmt.Println(id)
}
return err
},
HideHelpCommand: true,
Version: getVersion(),
Expand Down

0 comments on commit 1f3a062

Please sign in to comment.