Skip to content

Commit

Permalink
Refactor main package
Browse files Browse the repository at this point in the history
  • Loading branch information
jckuester committed Jan 29, 2021
1 parent 7435e6c commit 421a3b9
Show file tree
Hide file tree
Showing 5 changed files with 234 additions and 171 deletions.
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ require (
github.com/gruntwork-io/terratest v0.23.0
github.com/jckuester/awsls v0.4.1-0.20200809110610-a39a0788d3d5
github.com/jckuester/terradozer v0.1.2
github.com/kr/pty v1.1.1
github.com/onsi/gomega v1.9.0
github.com/spf13/pflag v1.0.3
github.com/stretchr/testify v1.6.1
Expand Down
66 changes: 66 additions & 0 deletions handle_args.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package main

import (
"fmt"
"os"

"github.com/jckuester/awsrm/pkg/resource"

"github.com/apex/log"

"github.com/fatih/color"
awsls "github.com/jckuester/awsls/aws"
"github.com/jckuester/awsls/util"
)

func handleInputFromArgs(args []string, profile, region string, dryRun bool) int {
log.Debug("input via args")

var profiles []string
var regions []string

if profile != "" {
profiles = []string{profile}
} else {
env, ok := os.LookupEnv("AWS_PROFILE")
if ok {
profiles = []string{env}
}
}

if region != "" {
regions = []string{region}
}

clients, err := util.NewAWSClientPool(profiles, regions)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

var resources []awsls.Resource
rType := args[0]
for _, client := range clients {
for _, id := range args[1:] {
resources = append(resources, awsls.Resource{
Type: rType,
ID: id,
Profile: client.Profile,
Region: client.Region,
})
}
}

var clientKeys []util.AWSClientKey
for k := range clients {
clientKeys = append(clientKeys, k)
}

err = resource.Delete(clientKeys, resources, os.Stdin, dryRun)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

return 0
}
53 changes: 53 additions & 0 deletions handle_pipe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"fmt"
"os"

"github.com/jckuester/awsrm/pkg/resource"

"github.com/apex/log"
"github.com/fatih/color"
"github.com/jckuester/awsls/util"
)

func isInputFromPipe() bool {
fileInfo, _ := os.Stdin.Stat()
log.Debugf("%v\n", fileInfo.Mode())

return fileInfo.Mode()&os.ModeNamedPipe != 0
}

func handleInputFromPipe(dryRun bool) int {
log.Debug("input via pipe")

resources, err := resource.Read(os.Stdin)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

var clientKeys []util.AWSClientKey
for _, r := range resources {
clientKeys = append(clientKeys, util.AWSClientKey{Profile: r.Profile, Region: r.Region})
}

err = os.Stdin.Close()
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

confirmDevice, err := os.Open("/dev/tty")
if err != nil {
log.Fatalf("can't open /dev/tty: %s", err)
}

err = resource.Delete(clientKeys, resources, confirmDevice, dryRun)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

return 0
}
178 changes: 8 additions & 170 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
package main

import (
"bufio"
"fmt"
"io"
"io/ioutil"
stdlog "log"
"os"
"strings"

"github.com/apex/log"
"github.com/apex/log/handlers/cli"
"github.com/fatih/color"
awsls "github.com/jckuester/awsls/aws"
"github.com/jckuester/awsls/resource"
"github.com/jckuester/awsls/util"
"github.com/jckuester/awsrm/internal"
terradozerRes "github.com/jckuester/terradozer/pkg/resource"
flag "github.com/spf13/pflag"
)

Expand All @@ -29,6 +22,7 @@ func mainExitCode() int {
var version bool
var profile string
var region string
var dryRun bool

flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)

Expand All @@ -37,8 +31,9 @@ func mainExitCode() int {
}

flags.BoolVar(&logDebug, "debug", false, "Enable debug logging")
flags.StringVarP(&profile, "profile", "p", "", "The AWS profile for the account to delete resources in")
flags.StringVarP(&region, "region", "r", "", "The region to delete resources in")
flags.BoolVar(&dryRun, "dry-run", false, "Don't deleteResources anything, just show what would be deleted")
flags.StringVarP(&profile, "profile", "p", "", "The AWS profile for the account to deleteResources resources in")
flags.StringVarP(&region, "region", "r", "", "The region to deleteResources resources in")
flags.BoolVar(&version, "version", false, "Show application version")

_ = flags.Parse(os.Args[1:])
Expand All @@ -61,173 +56,16 @@ func mainExitCode() int {
return 0
}

var resources []awsls.Resource
var err error
var confirmDevice *os.File
var clientKeys []util.AWSClientKey

if isInputFromPipe() {
log.Debug("input via pipe")

resources, err = readResources(os.Stdin)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

err = os.Stdin.Close()
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

confirmDevice, err = os.Open("/dev/tty")
if err != nil {
log.Fatalf("can't open /dev/tty: %s", err)
}
} else {
log.Debug("input via args")

if len(args) < 2 {
printHelp(flags)
return 1
}

var profiles []string
var regions []string

if profile != "" {
profiles = []string{profile}
} else {
env, ok := os.LookupEnv("AWS_PROFILE")
if ok {
profiles = []string{env}
}
}

if region != "" {
regions = []string{region}
}

clients, err := util.NewAWSClientPool(profiles, regions)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
return 1
}

rType := args[0]
for _, client := range clients {
for _, id := range args[1:] {
resources = append(resources, awsls.Resource{
Type: rType,
ID: id,
Profile: client.Profile,
Region: client.Region,
})
}
}

for k := range clients {
clientKeys = append(clientKeys, k)
}

confirmDevice = os.Stdin
return handleInputFromPipe(dryRun)
}

providers, err := util.NewProviderPool(clientKeys)
if err != nil {
fmt.Fprint(os.Stderr, color.RedString("\nError: %s\n", err))
if len(args) < 2 {
printHelp(flags)
return 1
}

resourcesWithUpdatedState := resource.GetStates(resources, providers)

internal.LogTitle("showing resources that would be deleted (dry run)")

// always show the resources that would be affected before deleting anything
for _, r := range resourcesWithUpdatedState {
log.WithFields(log.Fields{
"id": r.ID,
"profile": r.Profile,
"region": r.Region,
}).Warn(internal.Pad(r.Type))
}

if len(resourcesWithUpdatedState) == 0 {
internal.LogTitle("all resources have already been deleted")
return 0
}

internal.LogTitle(fmt.Sprintf("total number of resources that would be deleted: %d",
len(resourcesWithUpdatedState)))

if !internal.UserConfirmedDeletion(confirmDevice, false) {
return 0
}

internal.LogTitle("Starting to delete resources")

numDeletedResources := terradozerRes.DestroyResources(
convertToDestroyableResources(resourcesWithUpdatedState), 5)

internal.LogTitle(fmt.Sprintf("total number of deleted resources: %d", numDeletedResources))

return 0
}

func isInputFromPipe() bool {
fileInfo, _ := os.Stdin.Stat()
log.Debugf("%v\n", fileInfo.Mode())

return fileInfo.Mode()&os.ModeNamedPipe != 0
}

func readResources(r io.Reader) ([]awsls.Resource, error) {
var result []awsls.Resource

scanner := bufio.NewScanner(bufio.NewReader(r))
for scanner.Scan() {
line := scanner.Text()
rAttrs := strings.Fields(line)
if len(rAttrs) < 4 {
return nil, fmt.Errorf("input must be of form: <resource_type> <resource_id> <profile> <region>")
}

rType := rAttrs[0]
profile := rAttrs[2]

if !resource.IsType(rType) {
return nil, fmt.Errorf("is not a Terraform resource type: %s", rType)
}

if profile == `N\A` {
profile = ""
}

result = append(result, awsls.Resource{
Type: rType,
ID: rAttrs[1],
Profile: profile,
Region: rAttrs[3],
})
}

err := scanner.Err()
if err != nil {
return nil, err
}

return result, nil
}

func convertToDestroyableResources(resources []awsls.Resource) []terradozerRes.DestroyableResource {
var result []terradozerRes.DestroyableResource

for _, r := range resources {
result = append(result, r.UpdatableResource.(terradozerRes.DestroyableResource))
}

return result
return handleInputFromArgs(args, profile, region, dryRun)
}

func printHelp(fs *flag.FlagSet) {
Expand Down
Loading

0 comments on commit 421a3b9

Please sign in to comment.