From 230079f73a361d5001c2dc81618e43a0a78531c0 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 17:45:01 -0700 Subject: [PATCH 01/11] spell fixes --- builder/amazon/chroot/step_mount_device.go | 2 +- builder/amazon/common/step_security_group.go | 2 +- builder/amazon/ebs/tags_acc_test.go | 4 ++-- builder/docker/communicator_test.go | 2 +- builder/openstack/step_key_pair_test.go | 7 ++++--- .../common/step_attach_parallels_tools.go | 2 +- .../common/step_upload_parallels_tools.go | 2 +- builder/parallels/iso/builder_test.go | 2 +- builder/parallels/pvm/builder.go | 2 +- builder/parallels/pvm/config_test.go | 2 +- builder/profitbricks/step_create_server.go | 19 ++++++++++--------- builder/profitbricks/step_take_snapshot.go | 5 +++-- builder/qemu/builder_test.go | 4 ++-- builder/virtualbox/iso/builder_test.go | 4 ++-- builder/virtualbox/ovf/config_test.go | 4 ++-- builder/vmware/iso/builder_test.go | 4 ++-- builder/vmware/vmx/builder_test.go | 4 ++-- command/build.go | 4 ++-- common/retry_test.go | 2 +- packer/build.go | 4 ++-- packer/builder.go | 4 ++-- .../amazon-import/post-processor.go | 10 +++++----- post-processor/vagrant-cloud/step_upload.go | 2 +- .../vagrant-cloud/step_verify_upload.go | 9 +++++---- provisioner/ansible/scp.go | 2 +- provisioner/windows-restart/provisioner.go | 6 +++--- .../windows-restart/provisioner_test.go | 6 +++--- 27 files changed, 62 insertions(+), 58 deletions(-) diff --git a/builder/amazon/chroot/step_mount_device.go b/builder/amazon/chroot/step_mount_device.go index c7b74b9e6..0ea3b0529 100644 --- a/builder/amazon/chroot/step_mount_device.go +++ b/builder/amazon/chroot/step_mount_device.go @@ -82,7 +82,7 @@ func (s *StepMountDevice) Run(state multistep.StateBag) multistep.StepAction { ui.Say("Mounting the root device...") stderr := new(bytes.Buffer) - // build mount options from mount_options config, usefull for nouuid options + // build mount options from mount_options config, useful for nouuid options // or other specific device type settings for mount opts := "" if len(s.MountOptions) > 0 { diff --git a/builder/amazon/common/step_security_group.go b/builder/amazon/common/step_security_group.go index c96b20bf4..3206fd254 100644 --- a/builder/amazon/common/step_security_group.go +++ b/builder/amazon/common/step_security_group.go @@ -77,7 +77,7 @@ func (s *StepSecurityGroup) Run(state multistep.StateBag) multistep.StepAction { } // We loop and retry this a few times because sometimes the security - // group isn't available immediately because AWS resources are eventaully + // group isn't available immediately because AWS resources are eventually // consistent. ui.Say(fmt.Sprintf( "Authorizing access to port %d the temporary security group...", diff --git a/builder/amazon/ebs/tags_acc_test.go b/builder/amazon/ebs/tags_acc_test.go index 5d7866c89..d7114dc91 100644 --- a/builder/amazon/ebs/tags_acc_test.go +++ b/builder/amazon/ebs/tags_acc_test.go @@ -84,11 +84,11 @@ func checkTags() builderT.TestCheckFunc { }) if err != nil { - return fmt.Errorf("Error retreiving Snapshots for AMI Artifcat (%#v) in Tags Test: %s", artifact, err) + return fmt.Errorf("Error retrieving Snapshots for AMI Artifact (%#v) in Tags Test: %s", artifact, err) } if len(resp.Snapshots) == 0 { - return fmt.Errorf("No Snapshots found for AMI Artifcat (%#v) in Tags Test", artifact) + return fmt.Errorf("No Snapshots found for AMI Artifact (%#v) in Tags Test", artifact) } // Grab the snapshots, check the tags diff --git a/builder/docker/communicator_test.go b/builder/docker/communicator_test.go index be533b8e7..fb005de06 100644 --- a/builder/docker/communicator_test.go +++ b/builder/docker/communicator_test.go @@ -99,7 +99,7 @@ func TestUploadDownload(t *testing.T) { } } -// TestLargeDownload verifies that files are the apporpriate size after being +// TestLargeDownload verifies that files are the appropriate size after being // downloaded. This is to identify and fix the race condition in #2793. You may // need to use github.com/cbednarski/rerun to verify since this problem occurs // only intermittently. diff --git a/builder/openstack/step_key_pair_test.go b/builder/openstack/step_key_pair_test.go index 67b6ed558..997844611 100644 --- a/builder/openstack/step_key_pair_test.go +++ b/builder/openstack/step_key_pair_test.go @@ -2,10 +2,11 @@ package openstack import ( "bytes" - "github.com/mitchellh/packer/packer" - "golang.org/x/crypto/ssh" "os/exec" "testing" + + "github.com/mitchellh/packer/packer" + "golang.org/x/crypto/ssh" ) var ber_encoded_key = ` @@ -71,7 +72,7 @@ mKMH6Gf6COfSIbLuejdzSOUAmjkFpm+nwBkka1eHdAy4ALn9wNQz3w== func TestBerToDer(t *testing.T) { _, err := exec.LookPath("openssl") if err != nil { - t.Skipf("OpenSSL not availible skippint test.") + t.Skipf("OpenSSL not available skipping test.") } msg := new(bytes.Buffer) diff --git a/builder/parallels/common/step_attach_parallels_tools.go b/builder/parallels/common/step_attach_parallels_tools.go index 1e809a8e0..a4fd0559b 100644 --- a/builder/parallels/common/step_attach_parallels_tools.go +++ b/builder/parallels/common/step_attach_parallels_tools.go @@ -36,7 +36,7 @@ func (s *StepAttachParallelsTools) Run(state multistep.StateBag) multistep.StepA return multistep.ActionContinue } - // Get the Paralells Tools path on the host machine + // Get the Parallels Tools path on the host machine parallelsToolsPath := state.Get("parallels_tools_path").(string) // Attach the guest additions to the computer diff --git a/builder/parallels/common/step_upload_parallels_tools.go b/builder/parallels/common/step_upload_parallels_tools.go index 9df78bd38..97ba02d72 100644 --- a/builder/parallels/common/step_upload_parallels_tools.go +++ b/builder/parallels/common/step_upload_parallels_tools.go @@ -47,7 +47,7 @@ func (s *StepUploadParallelsTools) Run(state multistep.StateBag) multistep.StepA return multistep.ActionContinue } - // Get the Paralells Tools path on the host machine + // Get the Parallels Tools path on the host machine parallelsToolsPath := state.Get("parallels_tools_path").(string) f, err := os.Open(parallelsToolsPath) diff --git a/builder/parallels/iso/builder_test.go b/builder/parallels/iso/builder_test.go index b43da12f9..1761101be 100644 --- a/builder/parallels/iso/builder_test.go +++ b/builder/parallels/iso/builder_test.go @@ -90,7 +90,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/parallels/pvm/builder.go b/builder/parallels/pvm/builder.go index 565ea5a6e..bcfc75b8b 100644 --- a/builder/parallels/pvm/builder.go +++ b/builder/parallels/pvm/builder.go @@ -36,7 +36,7 @@ func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packe // Create the driver that we'll use to communicate with Parallels driver, err := parallelscommon.NewDriver() if err != nil { - return nil, fmt.Errorf("Failed creating Paralles driver: %s", err) + return nil, fmt.Errorf("Failed creating Parallels driver: %s", err) } // Set up the state. diff --git a/builder/parallels/pvm/config_test.go b/builder/parallels/pvm/config_test.go index 9334e9136..3add12e6e 100644 --- a/builder/parallels/pvm/config_test.go +++ b/builder/parallels/pvm/config_test.go @@ -87,7 +87,7 @@ func TestNewConfig_InvalidFloppies(t *testing.T) { c["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} _, _, errs := NewConfig(c) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/profitbricks/step_create_server.go b/builder/profitbricks/step_create_server.go index 90c7bd2e2..f9e7ff140 100644 --- a/builder/profitbricks/step_create_server.go +++ b/builder/profitbricks/step_create_server.go @@ -4,12 +4,13 @@ import ( "encoding/json" "errors" "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" - "github.com/profitbricks/profitbricks-sdk-go" "strconv" "strings" "time" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" + "github.com/profitbricks/profitbricks-sdk-go" ) type stepCreateServer struct{} @@ -83,7 +84,7 @@ func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { err := s.waitTillProvisioned(datacenter.Headers.Get("Location"), *c) if err != nil { - ui.Error(fmt.Sprintf("Error occured while creating a datacenter %s", err.Error())) + ui.Error(fmt.Sprintf("Error occurred while creating a datacenter %s", err.Error())) return multistep.ActionHalt } @@ -97,13 +98,13 @@ func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { }) if lan.StatusCode > 299 { - ui.Error(fmt.Sprintf("Error occured %s", parseErrorMessage(lan.Response))) + ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(lan.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(lan.Headers.Get("Location"), *c) if err != nil { - ui.Error(fmt.Sprintf("Error occured while creating a LAN %s", err.Error())) + ui.Error(fmt.Sprintf("Error occurred while creating a LAN %s", err.Error())) return multistep.ActionHalt } @@ -117,13 +118,13 @@ func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { }) if lan.StatusCode > 299 { - ui.Error(fmt.Sprintf("Error occured %s", parseErrorMessage(nic.Response))) + ui.Error(fmt.Sprintf("Error occurred %s", parseErrorMessage(nic.Response))) return multistep.ActionHalt } err = s.waitTillProvisioned(nic.Headers.Get("Location"), *c) if err != nil { - ui.Error(fmt.Sprintf("Error occured while creating a NIC %s", err.Error())) + ui.Error(fmt.Sprintf("Error occurred while creating a NIC %s", err.Error())) return multistep.ActionHalt } @@ -182,7 +183,7 @@ func (d *stepCreateServer) setPB(username string, password string, url string) { func (d *stepCreateServer) checkForErrors(instance profitbricks.Resp) error { if instance.StatusCode > 299 { - return errors.New(fmt.Sprintf("Error occured %s", string(instance.Body))) + return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body))) } return nil } diff --git a/builder/profitbricks/step_take_snapshot.go b/builder/profitbricks/step_take_snapshot.go index 65bbe7373..6f06f446c 100644 --- a/builder/profitbricks/step_take_snapshot.go +++ b/builder/profitbricks/step_take_snapshot.go @@ -4,10 +4,11 @@ import ( "encoding/json" "errors" "fmt" + "time" + "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" "github.com/profitbricks/profitbricks-sdk-go" - "time" ) type stepTakeSnapshot struct{} @@ -49,7 +50,7 @@ func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) { func (d *stepTakeSnapshot) checkForErrors(instance profitbricks.Resp) error { if instance.StatusCode > 299 { - return errors.New(fmt.Sprintf("Error occured %s", string(instance.Body))) + return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body))) } return nil } diff --git a/builder/qemu/builder_test.go b/builder/qemu/builder_test.go index db0309b4a..554909abc 100644 --- a/builder/qemu/builder_test.go +++ b/builder/qemu/builder_test.go @@ -301,11 +301,11 @@ func TestBuilderPrepare_FloppyFiles(t *testing.T) { func TestBuilderPrepare_InvalidFloppies(t *testing.T) { var b Builder config := testConfig() - config["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} + config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/virtualbox/iso/builder_test.go b/builder/virtualbox/iso/builder_test.go index cc15072de..ed6b7ba1e 100644 --- a/builder/virtualbox/iso/builder_test.go +++ b/builder/virtualbox/iso/builder_test.go @@ -126,11 +126,11 @@ func TestBuilderPrepare_FloppyFiles(t *testing.T) { func TestBuilderPrepare_InvalidFloppies(t *testing.T) { var b Builder config := testConfig() - config["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} + config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/virtualbox/ovf/config_test.go b/builder/virtualbox/ovf/config_test.go index 3de527acd..cb4e457aa 100644 --- a/builder/virtualbox/ovf/config_test.go +++ b/builder/virtualbox/ovf/config_test.go @@ -42,10 +42,10 @@ func TestNewConfig_FloppyFiles(t *testing.T) { func TestNewConfig_InvalidFloppies(t *testing.T) { c := testConfig(t) - c["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} + c["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} _, _, errs := NewConfig(c) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/vmware/iso/builder_test.go b/builder/vmware/iso/builder_test.go index 5c1ca5d11..8af4cc62e 100644 --- a/builder/vmware/iso/builder_test.go +++ b/builder/vmware/iso/builder_test.go @@ -127,11 +127,11 @@ func TestBuilderPrepare_FloppyFiles(t *testing.T) { func TestBuilderPrepare_InvalidFloppies(t *testing.T) { var b Builder config := testConfig() - config["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} + config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/vmware/vmx/builder_test.go b/builder/vmware/vmx/builder_test.go index 1c7f795f0..ef82cd0e2 100644 --- a/builder/vmware/vmx/builder_test.go +++ b/builder/vmware/vmx/builder_test.go @@ -56,11 +56,11 @@ func TestBuilderPrepare_FloppyFiles(t *testing.T) { func TestBuilderPrepare_InvalidFloppies(t *testing.T) { var b Builder config := testConfig(t) - config["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} + config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existant floppies should trigger multierror") + t.Fatalf("Non existent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/command/build.go b/command/build.go index 9cb382311..d1f4b0c54 100644 --- a/command/build.go +++ b/command/build.go @@ -211,7 +211,7 @@ func (c BuildCommand) Run(args []string) int { c.Ui.Error("\n==> Some builds didn't complete successfully and had errors:") for name, err := range errors { - // Create a UI for the machine readable stuff to be targetted + // Create a UI for the machine readable stuff to be targeted ui := &packer.TargettedUi{ Target: name, Ui: c.Ui, @@ -226,7 +226,7 @@ func (c BuildCommand) Run(args []string) int { if len(artifacts.m) > 0 { c.Ui.Say("\n==> Builds finished. The artifacts of successful builds are:") for name, buildArtifacts := range artifacts.m { - // Create a UI for the machine readable stuff to be targetted + // Create a UI for the machine readable stuff to be targeted ui := &packer.TargettedUi{ Target: name, Ui: c.Ui, diff --git a/common/retry_test.go b/common/retry_test.go index 4940dbc67..141e0fae4 100644 --- a/common/retry_test.go +++ b/common/retry_test.go @@ -56,7 +56,7 @@ func TestRetry(t *testing.T) { return false, nil }) if numTries != expectedTries { - t.Fatalf("Unsuccessul retry function should have been called %d times. Only called %d times.", expectedTries, numTries) + t.Fatalf("Unsuccessful retry function should have been called %d times. Only called %d times.", expectedTries, numTries) } if err != RetryExhaustedError { t.Fatalf("Unsuccessful retry function should have returned a retry exhausted error. Actual error: %s", err) diff --git a/packer/build.go b/packer/build.go index a7aa5973a..dfc8bff7f 100644 --- a/packer/build.go +++ b/packer/build.go @@ -56,7 +56,7 @@ type Build interface { Run(Ui, Cache) ([]Artifact, error) // Cancel will cancel a running build. This will block until the build - // is actually completely cancelled. + // is actually completely canceled. Cancel() // SetDebug will enable/disable debug mode. Debug mode is always @@ -210,7 +210,7 @@ func (b *coreBuild) Run(originalUi Ui, cache Cache) ([]Artifact, error) { hook := &DispatchHook{Mapping: hooks} artifacts := make([]Artifact, 0, 1) - // The builder just has a normal Ui, but targetted + // The builder just has a normal Ui, but targeted builderUi := &TargettedUi{ Target: b.Name(), Ui: originalUi, diff --git a/packer/builder.go b/packer/builder.go index 369b9a53e..7e82986f9 100644 --- a/packer/builder.go +++ b/packer/builder.go @@ -14,7 +14,7 @@ type Builder interface { // Prepare is responsible for configuring the builder and validating // that configuration. Any setup should be done in this method. Note that // NO side effects should take place in prepare, it is meant as a state - // setup only. Calling Prepare is not necessarilly followed by a Run. + // setup only. Calling Prepare is not necessarily followed by a Run. // // The parameters to Prepare are a set of interface{} values of the // configuration. These are almost always `map[string]interface{}` @@ -24,7 +24,7 @@ type Builder interface { // configuration. // // Prepare should return a list of warnings along with any errors - // that occured while preparing. + // that occurred while preparing. Prepare(...interface{}) ([]string, error) // Run is where the actual build should take place. It takes a Build and a Ui. diff --git a/post-processor/amazon-import/post-processor.go b/post-processor/amazon-import/post-processor.go index a339da040..77ea77cb9 100644 --- a/post-processor/amazon-import/post-processor.go +++ b/post-processor/amazon-import/post-processor.go @@ -33,7 +33,7 @@ type Config struct { Name string `mapstructure:"ami_name"` Description string `mapstructure:"ami_description"` Users []string `mapstructure:"ami_users"` - Groups []string `mapstrcuture:"ami_groups"` + Groups []string `mapstructure:"ami_groups"` ctx interpolate.Context } @@ -42,7 +42,7 @@ type PostProcessor struct { config Config } -// Entry point for configuration parisng when we've defined +// Entry point for configuration parsing when we've defined func (p *PostProcessor) Configure(raws ...interface{}) error { p.config.ctx.Funcs = awscommon.TemplateFuncs err := config.Decode(&p.config, &config.DecodeOpts{ @@ -74,7 +74,7 @@ func (p *PostProcessor) Configure(raws ...interface{}) error { // Check we have AWS access variables defined somewhere errs = packer.MultiErrorAppend(errs, p.config.AccessConfig.Prepare(&p.config.ctx)...) - // define all our required paramaters + // define all our required parameters templates := map[string]*string{ "s3_bucket_name": &p.config.S3Bucket, } @@ -178,7 +178,7 @@ func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (pac ui.Message(fmt.Sprintf("Started import of s3://%s/%s, task id %s", p.config.S3Bucket, p.config.S3Key, *import_start.ImportTaskId)) - // Wait for import process to complete, this takess a while + // Wait for import process to complete, this takes a while ui.Message(fmt.Sprintf("Waiting for task %s to complete (may take a while)", *import_start.ImportTaskId)) stateChange := awscommon.StateChangeConf{ @@ -307,7 +307,7 @@ func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (pac } - // Apply atttributes for AMI specified in config + // Apply attributes for AMI specified in config // (duped from builder/amazon/common/step_modify_ami_attributes.go) options := make(map[string]*ec2.ModifyImageAttributeInput) if p.config.Description != "" { diff --git a/post-processor/vagrant-cloud/step_upload.go b/post-processor/vagrant-cloud/step_upload.go index 2bada80b8..0d53a99d6 100644 --- a/post-processor/vagrant-cloud/step_upload.go +++ b/post-processor/vagrant-cloud/step_upload.go @@ -54,7 +54,7 @@ func (s *stepUpload) Run(state multistep.StateBag) multistep.StepAction { return multistep.ActionHalt } - ui.Message("Box succesfully uploaded") + ui.Message("Box successfully uploaded") return multistep.ActionContinue } diff --git a/post-processor/vagrant-cloud/step_verify_upload.go b/post-processor/vagrant-cloud/step_verify_upload.go index fbed25c6c..4a90ffa2d 100644 --- a/post-processor/vagrant-cloud/step_verify_upload.go +++ b/post-processor/vagrant-cloud/step_verify_upload.go @@ -2,10 +2,11 @@ package vagrantcloud import ( "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "log" "time" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) type stepVerifyUpload struct { @@ -88,8 +89,8 @@ func (s *stepVerifyUpload) Run(state multistep.StateBag) multistep.StepAction { return multistep.ActionHalt } - ui.Message(fmt.Sprintf("Upload succesfully verified with token %s", providerCheck.HostedToken)) - log.Printf("Box succesfully verified %s == %s", upload.Token, providerCheck.HostedToken) + ui.Message(fmt.Sprintf("Upload successfully verified with token %s", providerCheck.HostedToken)) + log.Printf("Box successfully verified %s == %s", upload.Token, providerCheck.HostedToken) return multistep.ActionContinue case <-time.After(600 * time.Second): diff --git a/provisioner/ansible/scp.go b/provisioner/ansible/scp.go index 912b4faa7..03a8fe526 100644 --- a/provisioner/ansible/scp.go +++ b/provisioner/ansible/scp.go @@ -54,7 +54,7 @@ func scpUploadSession(opts []byte, rest string, in io.Reader, out io.Writer, com // directory on the remote side, but ansible only sends files, so there's no // need to set targetIsDir, because it can be safely assumed that rest is // intended to be a file, and whatever names are used in 'C' commands are - // irrelavant. + // irrelevant. state := &scpUploadState{target: rest, srcRoot: d, comm: comm} fmt.Fprintf(out, scpOK) // signal the client to start the transfer. diff --git a/provisioner/windows-restart/provisioner.go b/provisioner/windows-restart/provisioner.go index 15c3ef774..139acc19a 100644 --- a/provisioner/windows-restart/provisioner.go +++ b/provisioner/windows-restart/provisioner.go @@ -116,7 +116,7 @@ var waitForRestart = func(p *Provisioner, comm packer.Communicator) error { cmd = &packer.RemoteCmd{Command: trycommand} err = cmd.StartWithUi(comm, ui) if err != nil { - // Couldnt execute, we asume machine is rebooting already + // Couldn't execute, we assume machine is rebooting already break } if cmd.ExitStatus == 1115 || cmd.ExitStatus == 1190 { @@ -175,8 +175,8 @@ var waitForCommunicator = func(p *Provisioner) error { for { select { case <-p.cancel: - log.Println("Communicator wait cancelled, exiting loop") - return fmt.Errorf("Communicator wait cancelled") + log.Println("Communicator wait canceled, exiting loop") + return fmt.Errorf("Communicator wait canceled") case <-time.After(retryableSleep): } diff --git a/provisioner/windows-restart/provisioner_test.go b/provisioner/windows-restart/provisioner_test.go index 81fc83c91..6ba63f8b5 100644 --- a/provisioner/windows-restart/provisioner_test.go +++ b/provisioner/windows-restart/provisioner_test.go @@ -319,7 +319,7 @@ func TestRetryable(t *testing.T) { err := p.Prepare(config) err = p.retryable(retryMe) if err != nil { - t.Fatalf("should not have error retrying funuction") + t.Fatalf("should not have error retrying function") } count = 0 @@ -327,7 +327,7 @@ func TestRetryable(t *testing.T) { err = p.Prepare(config) err = p.retryable(retryMe) if err == nil { - t.Fatalf("should have error retrying funuction") + t.Fatalf("should have error retrying function") } } @@ -368,7 +368,7 @@ func TestProvision_Cancel(t *testing.T) { }() <-waitDone - // Expect interupt error + // Expect interrupt error if err == nil { t.Fatal("should have error") } From d1b20b3d9ccb1c264581adeb508e4fc10d62b32e Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 18:02:51 -0700 Subject: [PATCH 02/11] remove a bunch of dead code. https://github.com/dominikh/go-tools/tree/master/cmd/unused --- .../amazon/chroot/step_chroot_provision.go | 4 +- builder/amazon/chroot/step_prepare_device.go | 6 +-- builder/azure/arm/step_get_certificate.go | 11 ++-- builder/azure/pkcs12/pkcs12.go | 17 ------ builder/googlecompute/config.go | 1 - builder/googlecompute/step_instance_info.go | 2 - .../common/step_polling_installation.go | 6 +-- builder/profitbricks/step_take_snapshot.go | 9 ---- builder/qemu/step_wait_for_shutdown.go | 43 --------------- builder/vmware/iso/output_dir.go | 52 ------------------- commands.go | 20 ------- main.go | 2 - packer/rpc/dial.go | 33 ------------ packer/rpc/post_processor.go | 8 +-- packer/rpc/server.go | 18 ------- post-processor/compress/artifact.go | 3 +- provisioner/chef-client/provisioner.go | 14 ----- signal.go | 39 -------------- template/interpolate/render.go | 46 +++------------- 19 files changed, 25 insertions(+), 309 deletions(-) delete mode 100644 builder/qemu/step_wait_for_shutdown.go delete mode 100644 packer/rpc/dial.go delete mode 100644 signal.go diff --git a/builder/amazon/chroot/step_chroot_provision.go b/builder/amazon/chroot/step_chroot_provision.go index 09ad9b8c9..168b65bb8 100644 --- a/builder/amazon/chroot/step_chroot_provision.go +++ b/builder/amazon/chroot/step_chroot_provision.go @@ -1,14 +1,14 @@ package chroot import ( + "log" + "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" - "log" ) // StepChrootProvision provisions the instance within a chroot. type StepChrootProvision struct { - mounts []string } func (s *StepChrootProvision) Run(state multistep.StateBag) multistep.StepAction { diff --git a/builder/amazon/chroot/step_prepare_device.go b/builder/amazon/chroot/step_prepare_device.go index d8683620b..62ac82b93 100644 --- a/builder/amazon/chroot/step_prepare_device.go +++ b/builder/amazon/chroot/step_prepare_device.go @@ -2,15 +2,15 @@ package chroot import ( "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "log" "os" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) // StepPrepareDevice finds an available device and sets it. type StepPrepareDevice struct { - mounts []string } func (s *StepPrepareDevice) Run(state multistep.StateBag) multistep.StepAction { diff --git a/builder/azure/arm/step_get_certificate.go b/builder/azure/arm/step_get_certificate.go index 22403ea94..fb2a36ccc 100644 --- a/builder/azure/arm/step_get_certificate.go +++ b/builder/azure/arm/step_get_certificate.go @@ -13,12 +13,11 @@ import ( ) type StepGetCertificate struct { - client *AzureClient - template string - get func(keyVaultName string, secretName string) (string, error) - say func(message string) - error func(e error) - pause func() + client *AzureClient + get func(keyVaultName string, secretName string) (string, error) + say func(message string) + error func(e error) + pause func() } func NewStepGetCertificate(client *AzureClient, ui packer.Ui) *StepGetCertificate { diff --git a/builder/azure/pkcs12/pkcs12.go b/builder/azure/pkcs12/pkcs12.go index 316c2e731..7db1a2e05 100644 --- a/builder/azure/pkcs12/pkcs12.go +++ b/builder/azure/pkcs12/pkcs12.go @@ -30,23 +30,6 @@ type contentInfo struct { Content asn1.RawValue `asn1:"tag:0,explicit,optional"` } -type encryptedData struct { - Version int - EncryptedContentInfo encryptedContentInfo -} - -type encryptedContentInfo struct { - ContentType asn1.ObjectIdentifier - ContentEncryptionAlgorithm pkix.AlgorithmIdentifier - EncryptedContent []byte `asn1:"tag:0,optional"` -} - -func (i encryptedContentInfo) GetAlgorithm() pkix.AlgorithmIdentifier { - return i.ContentEncryptionAlgorithm -} - -func (i encryptedContentInfo) GetData() []byte { return i.EncryptedContent } - type safeBag struct { Id asn1.ObjectIdentifier Value asn1.RawValue `asn1:"tag:0,explicit"` diff --git a/builder/googlecompute/config.go b/builder/googlecompute/config.go index 330ea5900..fd8b7ba8a 100644 --- a/builder/googlecompute/config.go +++ b/builder/googlecompute/config.go @@ -54,7 +54,6 @@ type Config struct { Zone string `mapstructure:"zone"` Account AccountFile - privateKeyBytes []byte stateTimeout time.Duration imageAlreadyExists bool ctx interpolate.Context diff --git a/builder/googlecompute/step_instance_info.go b/builder/googlecompute/step_instance_info.go index 511906206..63653f420 100644 --- a/builder/googlecompute/step_instance_info.go +++ b/builder/googlecompute/step_instance_info.go @@ -12,8 +12,6 @@ import ( // stepInstanceInfo represents a Packer build step that gathers GCE instance info. type StepInstanceInfo struct { Debug bool - - info int } // Run executes the Packer build step that gathers GCE instance info. diff --git a/builder/hyperv/common/step_polling_installation.go b/builder/hyperv/common/step_polling_installation.go index 7cef6a108..aa61a1e53 100644 --- a/builder/hyperv/common/step_polling_installation.go +++ b/builder/hyperv/common/step_polling_installation.go @@ -3,18 +3,18 @@ package common import ( "bytes" "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "log" "os/exec" "strings" "time" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) const port string = "13000" type StepPollingInstalation struct { - step int } func (s *StepPollingInstalation) Run(state multistep.StateBag) multistep.StepAction { diff --git a/builder/profitbricks/step_take_snapshot.go b/builder/profitbricks/step_take_snapshot.go index 6f06f446c..35820f3e1 100644 --- a/builder/profitbricks/step_take_snapshot.go +++ b/builder/profitbricks/step_take_snapshot.go @@ -2,8 +2,6 @@ package profitbricks import ( "encoding/json" - "errors" - "fmt" "time" "github.com/mitchellh/multistep" @@ -48,13 +46,6 @@ func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction { func (s *stepTakeSnapshot) Cleanup(state multistep.StateBag) { } -func (d *stepTakeSnapshot) checkForErrors(instance profitbricks.Resp) error { - if instance.StatusCode > 299 { - return errors.New(fmt.Sprintf("Error occurred %s", string(instance.Body))) - } - return nil -} - func (d *stepTakeSnapshot) waitTillProvisioned(path string, config Config) { d.setPB(config.PBUsername, config.PBPassword, config.PBUrl) waitCount := 50 diff --git a/builder/qemu/step_wait_for_shutdown.go b/builder/qemu/step_wait_for_shutdown.go deleted file mode 100644 index 5418b967f..000000000 --- a/builder/qemu/step_wait_for_shutdown.go +++ /dev/null @@ -1,43 +0,0 @@ -package qemu - -import ( - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" - "time" -) - -// stepWaitForShutdown waits for the shutdown of the currently running -// qemu VM. -type stepWaitForShutdown struct { - Message string -} - -func (s *stepWaitForShutdown) Run(state multistep.StateBag) multistep.StepAction { - driver := state.Get("driver").(Driver) - ui := state.Get("ui").(packer.Ui) - - stopCh := make(chan struct{}) - defer close(stopCh) - - cancelCh := make(chan struct{}) - go func() { - for { - if _, ok := state.GetOk(multistep.StateCancelled); ok { - close(cancelCh) - return - } - - select { - case <-stopCh: - return - case <-time.After(100 * time.Millisecond): - } - } - }() - - ui.Say(s.Message) - driver.WaitForShutdown(cancelCh) - return multistep.ActionContinue -} - -func (s *stepWaitForShutdown) Cleanup(state multistep.StateBag) {} diff --git a/builder/vmware/iso/output_dir.go b/builder/vmware/iso/output_dir.go index 0c08a225f..30eab2e31 100644 --- a/builder/vmware/iso/output_dir.go +++ b/builder/vmware/iso/output_dir.go @@ -1,10 +1,5 @@ package iso -import ( - "os" - "path/filepath" -) - // OutputDir is an interface type that abstracts the creation and handling // of the output directory for VMware-based products. The abstraction is made // so that the output directory can be properly made on remote (ESXi) based @@ -17,50 +12,3 @@ type OutputDir interface { RemoveAll() error SetOutputDir(string) } - -// localOutputDir is an OutputDir implementation where the directory -// is on the local machine. -type localOutputDir struct { - dir string -} - -func (d *localOutputDir) DirExists() (bool, error) { - _, err := os.Stat(d.dir) - return err == nil, nil -} - -func (d *localOutputDir) ListFiles() ([]string, error) { - files := make([]string, 0, 10) - - visit := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - if !info.IsDir() { - files = append(files, path) - } - return nil - } - - return files, filepath.Walk(d.dir, visit) -} - -func (d *localOutputDir) MkdirAll() error { - return os.MkdirAll(d.dir, 0755) -} - -func (d *localOutputDir) Remove(path string) error { - return os.Remove(path) -} - -func (d *localOutputDir) RemoveAll() error { - return os.RemoveAll(d.dir) -} - -func (d *localOutputDir) SetOutputDir(path string) { - d.dir = path -} - -func (d *localOutputDir) String() string { - return d.dir -} diff --git a/commands.go b/commands.go index 02d55c707..9b02b5941 100644 --- a/commands.go +++ b/commands.go @@ -1,9 +1,6 @@ package main import ( - "os" - "os/signal" - "github.com/mitchellh/cli" "github.com/mitchellh/packer/command" "github.com/mitchellh/packer/version" @@ -68,20 +65,3 @@ func init() { }, } } - -// makeShutdownCh creates an interrupt listener and returns a channel. -// A message will be sent on the channel for every interrupt received. -func makeShutdownCh() <-chan struct{} { - resultCh := make(chan struct{}) - - signalCh := make(chan os.Signal, 4) - signal.Notify(signalCh, os.Interrupt) - go func() { - for { - <-signalCh - resultCh <- struct{}{} - } - }() - - return resultCh -} diff --git a/main.go b/main.go index 5f760e824..06a4c7402 100644 --- a/main.go +++ b/main.go @@ -187,8 +187,6 @@ func wrappedMain() int { Ui: ui, } - //setupSignalHandlers(env) - cli := &cli.CLI{ Args: args, Commands: Commands, diff --git a/packer/rpc/dial.go b/packer/rpc/dial.go deleted file mode 100644 index 10e2cad14..000000000 --- a/packer/rpc/dial.go +++ /dev/null @@ -1,33 +0,0 @@ -package rpc - -import ( - "net" - "net/rpc" -) - -// rpcDial makes a TCP connection to a remote RPC server and returns -// the client. This will set the connection up properly so that keep-alives -// are set and so on and should be used to make all RPC connections within -// this package. -func rpcDial(address string) (*rpc.Client, error) { - tcpConn, err := tcpDial(address) - if err != nil { - return nil, err - } - - // Create an RPC client around our connection - return rpc.NewClient(tcpConn), nil -} - -// tcpDial connects via TCP to the designated address. -func tcpDial(address string) (*net.TCPConn, error) { - conn, err := net.Dial("tcp", address) - if err != nil { - return nil, err - } - - // Set a keep-alive so that the connection stays alive even when idle - tcpConn := conn.(*net.TCPConn) - tcpConn.SetKeepAlive(true) - return tcpConn, nil -} diff --git a/packer/rpc/post_processor.go b/packer/rpc/post_processor.go index b183780b9..5831b125e 100644 --- a/packer/rpc/post_processor.go +++ b/packer/rpc/post_processor.go @@ -1,8 +1,9 @@ package rpc import ( - "github.com/mitchellh/packer/packer" "net/rpc" + + "github.com/mitchellh/packer/packer" ) // An implementation of packer.PostProcessor where the PostProcessor is actually @@ -15,9 +16,8 @@ type postProcessor struct { // PostProcessorServer wraps a packer.PostProcessor implementation and makes it // exportable as part of a Golang RPC server. type PostProcessorServer struct { - client *rpc.Client - mux *muxBroker - p packer.PostProcessor + mux *muxBroker + p packer.PostProcessor } type PostProcessorConfigureArgs struct { diff --git a/packer/rpc/server.go b/packer/rpc/server.go index c82772049..ff1753269 100644 --- a/packer/rpc/server.go +++ b/packer/rpc/server.go @@ -4,14 +4,11 @@ import ( "io" "log" "net/rpc" - "sync/atomic" "github.com/mitchellh/packer/packer" "github.com/ugorji/go/codec" ) -var endpointId uint64 - const ( DefaultArtifactEndpoint string = "Artifact" DefaultBuildEndpoint = "Build" @@ -140,18 +137,3 @@ func (s *Server) Serve() { rpcCodec := codec.GoRpc.ServerCodec(stream, h) s.server.ServeCodec(rpcCodec) } - -// registerComponent registers a single Packer RPC component onto -// the RPC server. If id is true, then a unique ID number will be appended -// onto the end of the endpoint. -// -// The endpoint name is returned. -func registerComponent(server *rpc.Server, name string, rcvr interface{}, id bool) string { - endpoint := name - if id { - log.Printf("%s.%d", endpoint, atomic.AddUint64(&endpointId, 1)) - } - - server.RegisterName(endpoint, rcvr) - return endpoint -} diff --git a/post-processor/compress/artifact.go b/post-processor/compress/artifact.go index 4b19f779f..9bd89b213 100644 --- a/post-processor/compress/artifact.go +++ b/post-processor/compress/artifact.go @@ -8,8 +8,7 @@ import ( const BuilderId = "packer.post-processor.compress" type Artifact struct { - Path string - files []string + Path string } func (a *Artifact) BuilderId() string { diff --git a/provisioner/chef-client/provisioner.go b/provisioner/chef-client/provisioner.go index aeac7d274..a0be8df9b 100644 --- a/provisioner/chef-client/provisioner.go +++ b/provisioner/chef-client/provisioner.go @@ -319,20 +319,6 @@ func (p *Provisioner) Cancel() { os.Exit(0) } -func (p *Provisioner) uploadDirectory(ui packer.Ui, comm packer.Communicator, dst string, src string) error { - if err := p.createDir(ui, comm, dst); err != nil { - return err - } - - // Make sure there is a trailing "/" so that the directory isn't - // created on the other side. - if src[len(src)-1] != '/' { - src = src + "/" - } - - return comm.UploadDir(dst, src, nil) -} - func (p *Provisioner) uploadFile(ui packer.Ui, comm packer.Communicator, remotePath string, localPath string) error { ui.Message(fmt.Sprintf("Uploading %s...", localPath)) diff --git a/signal.go b/signal.go deleted file mode 100644 index 8846a3451..000000000 --- a/signal.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "log" - "os" - "os/signal" - "syscall" - - "github.com/mitchellh/packer/packer" - "github.com/mitchellh/packer/packer/plugin" -) - -// Prepares the signal handlers so that we handle interrupts properly. -// The signal handler exists in a goroutine. -func setupSignalHandlers(ui packer.Ui) { - ch := make(chan os.Signal, 1) - signal.Notify(ch, os.Interrupt) - signal.Notify(ch, syscall.SIGTERM) - - go func() { - // First interrupt. We mostly ignore this because it allows the - // plugins time to cleanup. - <-ch - log.Println("First interrupt. Ignoring to allow plugins to clean up.") - - ui.Error("Interrupt signal received. Cleaning up...") - - // Second interrupt. Go down hard. - <-ch - log.Println("Second interrupt. Exiting now.") - - ui.Error("Interrupt signal received twice. Forcefully exiting now.") - - // Force kill all the plugins, but mark that we're killing them - // first so that we don't get panics everywhere. - plugin.CleanupClients() - os.Exit(1) - }() -} diff --git a/template/interpolate/render.go b/template/interpolate/render.go index 2120c171f..4c49d43b8 100644 --- a/template/interpolate/render.go +++ b/template/interpolate/render.go @@ -147,14 +147,13 @@ type renderWalker struct { // If it is nil, it means the top wasn't replaced. Top interface{} - key []string - lastValue reflect.Value - loc reflectwalk.Location - cs []reflect.Value - csKey []reflect.Value - csData interface{} - sliceIndex int - unknownKeys []string + key []string + lastValue reflect.Value + loc reflectwalk.Location + cs []reflect.Value + csKey []reflect.Value + csData interface{} + sliceIndex int } // renderWalkerFunc is the callback called by interpolationWalk. @@ -281,34 +280,3 @@ func (w *renderWalker) Primitive(v reflect.Value) error { return nil } - -func (w *renderWalker) removeCurrent() { - // Append the key to the unknown keys - w.unknownKeys = append(w.unknownKeys, strings.Join(w.key, ".")) - - for i := 1; i <= len(w.cs); i++ { - c := w.cs[len(w.cs)-i] - switch c.Kind() { - case reflect.Map: - // Zero value so that we delete the map key - var val reflect.Value - - // Get the key and delete it - k := w.csData.(reflect.Value) - c.SetMapIndex(k, val) - return - } - } - - panic("No container found for removeCurrent") -} - -func (w *renderWalker) replaceCurrent(v reflect.Value) { - c := w.cs[len(w.cs)-2] - switch c.Kind() { - case reflect.Map: - // Get the key and delete it - k := w.csKey[len(w.csKey)-1] - c.SetMapIndex(k, v) - } -} From 0149f679deaa7db404034c2c96b88558fc6391f5 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 18:06:50 -0700 Subject: [PATCH 03/11] Print instead of Printf with no dynamic first variable. --- builder/amazon/common/step_encrypted_ami.go | 2 +- builder/qemu/step_configure_vnc.go | 7 ++++--- provisioner/powershell/provisioner.go | 2 +- provisioner/shell/provisioner.go | 2 +- provisioner/windows-restart/provisioner.go | 2 +- provisioner/windows-shell/provisioner.go | 2 +- 6 files changed, 9 insertions(+), 8 deletions(-) diff --git a/builder/amazon/common/step_encrypted_ami.go b/builder/amazon/common/step_encrypted_ami.go index 40e985322..6a4c2967e 100644 --- a/builder/amazon/common/step_encrypted_ami.go +++ b/builder/amazon/common/step_encrypted_ami.go @@ -25,7 +25,7 @@ func (s *StepCreateEncryptedAMICopy) Run(state multistep.StateBag) multistep.Ste // Encrypt boot not set, so skip step if !s.EncryptBootVolume { if kmsKeyId != "" { - log.Printf(fmt.Sprintf("Ignoring KMS Key ID: %s, encrypted=false", kmsKeyId)) + log.Printf("Ignoring KMS Key ID: %s, encrypted=false", kmsKeyId) } return multistep.ActionContinue } diff --git a/builder/qemu/step_configure_vnc.go b/builder/qemu/step_configure_vnc.go index d7bace29e..bda624f89 100644 --- a/builder/qemu/step_configure_vnc.go +++ b/builder/qemu/step_configure_vnc.go @@ -2,11 +2,12 @@ package qemu import ( "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "log" "math/rand" "net" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) // This step configures the VM to enable the VNC server. @@ -28,7 +29,7 @@ func (stepConfigureVNC) Run(state multistep.StateBag) multistep.StepAction { // best. msg := fmt.Sprintf("Looking for available port between %d and %d on %s", config.VNCPortMin, config.VNCPortMax, config.VNCBindAddress) ui.Say(msg) - log.Printf(msg) + log.Print(msg) var vncPort uint portRange := int(config.VNCPortMax - config.VNCPortMin) for { diff --git a/provisioner/powershell/provisioner.go b/provisioner/powershell/provisioner.go index 4d5ffadf7..8448cf819 100644 --- a/provisioner/powershell/provisioner.go +++ b/provisioner/powershell/provisioner.go @@ -317,7 +317,7 @@ func (p *Provisioner) retryable(f func() error) error { // Create an error and log it err = fmt.Errorf("Retryable error: %s", err) - log.Printf(err.Error()) + log.Print(err.Error()) // Check if we timed out, otherwise we retry. It is safe to // retry since the only error case above is if the command diff --git a/provisioner/shell/provisioner.go b/provisioner/shell/provisioner.go index f8a646d66..30468aee1 100644 --- a/provisioner/shell/provisioner.go +++ b/provisioner/shell/provisioner.go @@ -348,7 +348,7 @@ func (p *Provisioner) retryable(f func() error) error { // Create an error and log it err = fmt.Errorf("Retryable error: %s", err) - log.Printf(err.Error()) + log.Print(err.Error()) // Check if we timed out, otherwise we retry. It is safe to // retry since the only error case above is if the command diff --git a/provisioner/windows-restart/provisioner.go b/provisioner/windows-restart/provisioner.go index 139acc19a..ae58dd9d1 100644 --- a/provisioner/windows-restart/provisioner.go +++ b/provisioner/windows-restart/provisioner.go @@ -217,7 +217,7 @@ func (p *Provisioner) retryable(f func() error) error { // Create an error and log it err = fmt.Errorf("Retryable error: %s", err) - log.Printf(err.Error()) + log.Print(err.Error()) // Check if we timed out, otherwise we retry. It is safe to // retry since the only error case above is if the command diff --git a/provisioner/windows-shell/provisioner.go b/provisioner/windows-shell/provisioner.go index e770d867a..b0d50998f 100644 --- a/provisioner/windows-shell/provisioner.go +++ b/provisioner/windows-shell/provisioner.go @@ -270,7 +270,7 @@ func (p *Provisioner) retryable(f func() error) error { // Create an error and log it err = fmt.Errorf("Retryable error: %s", err) - log.Printf(err.Error()) + log.Print(err.Error()) // Check if we timed out, otherwise we retry. It is safe to // retry since the only error case above is if the command From 79287d7e477437024d7bc2a8c31ea33dfe2b31ca Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 18:29:55 -0700 Subject: [PATCH 04/11] simplify some code --- builder/amazon/common/access_config.go | 4 ++-- builder/amazon/common/ami_config.go | 2 +- builder/amazon/common/cli_config.go | 5 +---- builder/amazon/common/step_source_ami_info.go | 2 +- builder/docker/ecr_login.go | 2 +- builder/virtualbox/common/step_run.go | 5 +++-- common/download.go | 2 +- common/floppy_config.go | 4 ++-- common/step_create_floppy.go | 13 ++++++------ communicator/ssh/communicator.go | 20 ++++--------------- config.go | 7 +------ packer/rpc/mux_broker.go | 6 ++---- provisioner/file/provisioner.go | 2 +- 13 files changed, 27 insertions(+), 47 deletions(-) diff --git a/builder/amazon/common/access_config.go b/builder/amazon/common/access_config.go index 046631755..5e11fcd32 100644 --- a/builder/amazon/common/access_config.go +++ b/builder/amazon/common/access_config.go @@ -66,7 +66,7 @@ func (c *AccessConfig) Config() (*aws.Config, error) { func (c *AccessConfig) Region() (string, error) { if c.RawRegion != "" { if !c.SkipValidation { - if valid := ValidateRegion(c.RawRegion); valid == false { + if valid := ValidateRegion(c.RawRegion); !valid { return "", fmt.Errorf("Not a valid region: %s", c.RawRegion) } } @@ -85,7 +85,7 @@ func (c *AccessConfig) Region() (string, error) { func (c *AccessConfig) Prepare(ctx *interpolate.Context) []error { var errs []error if c.RawRegion != "" && !c.SkipValidation { - if valid := ValidateRegion(c.RawRegion); valid == false { + if valid := ValidateRegion(c.RawRegion); !valid { errs = append(errs, fmt.Errorf("Unknown region: %s", c.RawRegion)) } } diff --git a/builder/amazon/common/ami_config.go b/builder/amazon/common/ami_config.go index c7674dbbe..a60d0d788 100644 --- a/builder/amazon/common/ami_config.go +++ b/builder/amazon/common/ami_config.go @@ -48,7 +48,7 @@ func (c *AMIConfig) Prepare(ctx *interpolate.Context) []error { if !c.AMISkipRegionValidation { // Verify the region is real - if valid := ValidateRegion(region); valid == false { + if valid := ValidateRegion(region); !valid { errs = append(errs, fmt.Errorf("Unknown region: %s", region)) continue } diff --git a/builder/amazon/common/cli_config.go b/builder/amazon/common/cli_config.go index fc4d36fd7..d37c1d14e 100644 --- a/builder/amazon/common/cli_config.go +++ b/builder/amazon/common/cli_config.go @@ -90,10 +90,7 @@ func (c *CLIConfig) Prepare(name string) error { c.SourceProfile = c.ProfileName } c.profileCred, err = credsFromName(c.SourceProfile) - if err != nil { - return err - } - return nil + return err } func (c *CLIConfig) getSessionName(rawName string) (string, error) { diff --git a/builder/amazon/common/step_source_ami_info.go b/builder/amazon/common/step_source_ami_info.go index bd03fcdf8..2346502fc 100644 --- a/builder/amazon/common/step_source_ami_info.go +++ b/builder/amazon/common/step_source_ami_info.go @@ -85,7 +85,7 @@ func (s *StepSourceAMIInfo) Run(state multistep.StateBag) multistep.StepAction { return multistep.ActionHalt } - if len(imageResp.Images) > 1 && s.AmiFilters.MostRecent == false { + if len(imageResp.Images) > 1 && !s.AmiFilters.MostRecent { err := fmt.Errorf("Your query returned more than one result. Please try a more specific search, or set most_recent to true.") state.Put("error", err) ui.Error(err.Error()) diff --git a/builder/docker/ecr_login.go b/builder/docker/ecr_login.go index 6d2df0877..737107589 100644 --- a/builder/docker/ecr_login.go +++ b/builder/docker/ecr_login.go @@ -50,7 +50,7 @@ func (c *AwsAccessConfig) config(region string) (*aws.Config, error) { // or an error. func (c *AwsAccessConfig) EcrGetLogin(ecrUrl string) (string, string, error) { - exp := regexp.MustCompile("(?:http://|https://|)([0-9]*)\\.dkr\\.ecr\\.(.*)\\.amazonaws\\.com.*") + exp := regexp.MustCompile(`(?:http://|https://|)([0-9]*)\.dkr\.ecr\.(.*)\.amazonaws\.com.*`) splitUrl := exp.FindStringSubmatch(ecrUrl) if len(splitUrl) != 3 { return "", "", fmt.Errorf("Failed to parse the ECR URL: %s it should be on the form .dkr.ecr..amazonaws.com", ecrUrl) diff --git a/builder/virtualbox/common/step_run.go b/builder/virtualbox/common/step_run.go index 9958bf2a2..487f31430 100644 --- a/builder/virtualbox/common/step_run.go +++ b/builder/virtualbox/common/step_run.go @@ -2,9 +2,10 @@ package common import ( "fmt" + "time" + "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" - "time" ) // This step starts the virtual machine. @@ -29,7 +30,7 @@ func (s *StepRun) Run(state multistep.StateBag) multistep.StepAction { ui.Say("Starting the virtual machine...") guiArgument := "gui" - if s.Headless == true { + if s.Headless { vrdpIpRaw, vrdpIpOk := state.GetOk("vrdpIp") vrdpPortRaw, vrdpPortOk := state.GetOk("vrdpPort") diff --git a/common/download.go b/common/download.go index e4d9d4048..86dea34d1 100644 --- a/common/download.go +++ b/common/download.go @@ -205,7 +205,7 @@ func (d *DownloadClient) VerifyChecksum(path string) (bool, error) { log.Printf("Verifying checksum of %s", path) d.config.Hash.Reset() io.Copy(d.config.Hash, f) - return bytes.Compare(d.config.Hash.Sum(nil), d.config.Checksum) == 0, nil + return bytes.Equal(d.config.Hash.Sum(nil), d.config.Checksum), nil } // HTTPDownloader is an implementation of Downloader that downloads diff --git a/common/floppy_config.go b/common/floppy_config.go index 5a68816ed..ecaa5eddb 100644 --- a/common/floppy_config.go +++ b/common/floppy_config.go @@ -23,7 +23,7 @@ func (c *FloppyConfig) Prepare(ctx *interpolate.Context) []error { } for _, path := range c.FloppyFiles { - if strings.IndexAny(path, "*?[") >= 0 { + if strings.ContainsAny(path, "*?[") { _, err = filepath.Glob(path) } else { _, err = os.Stat(path) @@ -38,7 +38,7 @@ func (c *FloppyConfig) Prepare(ctx *interpolate.Context) []error { } for _, path := range c.FloppyDirectories { - if strings.IndexAny(path, "*?[") >= 0 { + if strings.ContainsAny(path, "*?[") { _, err = filepath.Glob(path) } else { _, err = os.Stat(path) diff --git a/common/step_create_floppy.go b/common/step_create_floppy.go index eb0a6057e..d00bc4da8 100644 --- a/common/step_create_floppy.go +++ b/common/step_create_floppy.go @@ -2,10 +2,6 @@ package common import ( "fmt" - "github.com/mitchellh/go-fs" - "github.com/mitchellh/go-fs/fat" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "io" "io/ioutil" "log" @@ -13,6 +9,11 @@ import ( "path" "path/filepath" "strings" + + "github.com/mitchellh/go-fs" + "github.com/mitchellh/go-fs/fat" + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) // StepCreateFloppy will create a floppy disk with the given files. @@ -96,7 +97,7 @@ func (s *StepCreateFloppy) Run(state multistep.StateBag) multistep.StepAction { // Utility functions for walking through a directory grabbing all files flatly globFiles := func(files []string, list chan string) { for _, filename := range files { - if strings.IndexAny(filename, "*?[") >= 0 { + if strings.ContainsAny(filename, "*?[") { matches, _ := filepath.Glob(filename) if err != nil { continue @@ -173,7 +174,7 @@ func (s *StepCreateFloppy) Run(state multistep.StateBag) multistep.StepAction { ui.Message("Collecting paths from floppy_dirs") var pathqueue []string for _, filename := range s.Directories { - if strings.IndexAny(filename, "*?[") >= 0 { + if strings.ContainsAny(filename, "*?[") { matches, err := filepath.Glob(filename) if err != nil { state.Put("error", fmt.Errorf("Error adding path %s to floppy: %s", filename, err)) diff --git a/communicator/ssh/communicator.go b/communicator/ssh/communicator.go index e3082bac1..9cef308fb 100644 --- a/communicator/ssh/communicator.go +++ b/communicator/ssh/communicator.go @@ -620,14 +620,10 @@ func (c *comm) scpDownloadSession(path string, output io.Writer) error { fmt.Fprint(w, "\x00") - if err := checkSCPStatus(stdoutR); err != nil { - return err - } - - return nil + return checkSCPStatus(stdoutR) } - if strings.Index(path, " ") == -1 { + if !strings.Contains(path, " ") { return c.scpSession("scp -vf "+path, scpFunc) } return c.scpSession("scp -vf "+strconv.Quote(path), scpFunc) @@ -805,11 +801,7 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi * } fmt.Fprint(w, "\x00") - if err := checkSCPStatus(r); err != nil { - return err - } - - return nil + return checkSCPStatus(r) } func scpUploadDirProtocol(name string, w io.Writer, r *bufio.Reader, f func() error, fi os.FileInfo) error { @@ -830,11 +822,7 @@ func scpUploadDirProtocol(name string, w io.Writer, r *bufio.Reader, f func() er } fmt.Fprintln(w, "E") - if err != nil { - return err - } - - return nil + return err } func scpUploadDir(root string, fs []os.FileInfo, w io.Writer, r *bufio.Reader) error { diff --git a/config.go b/config.go index 801d73437..a62e28323 100644 --- a/config.go +++ b/config.go @@ -155,13 +155,8 @@ func (c *config) discover(path string) error { return err } - err = c.discoverSingle( + return c.discoverSingle( filepath.Join(path, "packer-provisioner-*"), &c.Provisioners) - if err != nil { - return err - } - - return nil } func (c *config) discoverSingle(glob string, m *map[string]string) error { diff --git a/packer/rpc/mux_broker.go b/packer/rpc/mux_broker.go index 7af76f640..aeb72afbf 100644 --- a/packer/rpc/mux_broker.go +++ b/packer/rpc/mux_broker.go @@ -183,9 +183,7 @@ func (m *muxBroker) timeoutWait(id uint32, p *muxBrokerPending) { // If we timed out, then check if we have a channel in the buffer, // and if so, close it. if timeout { - select { - case s := <-p.ch: - s.Close() - } + s := <-p.ch + s.Close() } } diff --git a/provisioner/file/provisioner.go b/provisioner/file/provisioner.go index 19e5c4bea..433c9f23a 100644 --- a/provisioner/file/provisioner.go +++ b/provisioner/file/provisioner.go @@ -112,7 +112,7 @@ func (p *Provisioner) ProvisionDownload(ui packer.Ui, comm packer.Communicator) } } // if the src was a dir, download the dir - if strings.HasSuffix(src, "/") || strings.IndexAny(src, "*?[") >= 0 { + if strings.HasSuffix(src, "/") || strings.ContainsAny(src, "*?[") { return comm.DownloadDir(src, dst, nil) } From bf64d7bdc2a549d73f91c8378719303756a8d0f2 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 18:40:46 -0700 Subject: [PATCH 05/11] automagic simplification --- builder/azure/pkcs12/bmp-string_test.go | 6 +++--- builder/azure/pkcs12/crypto_test.go | 6 +++--- builder/azure/pkcs12/pbkdf_test.go | 2 +- post-processor/vagrant/aws_test.go | 2 +- post-processor/vagrant/digitalocean_test.go | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/builder/azure/pkcs12/bmp-string_test.go b/builder/azure/pkcs12/bmp-string_test.go index fcbc7b7b1..8d4599e91 100644 --- a/builder/azure/pkcs12/bmp-string_test.go +++ b/builder/azure/pkcs12/bmp-string_test.go @@ -35,7 +35,7 @@ func TestBMPStringDecode(t *testing.T) { func TestBMPString(t *testing.T) { str, err := bmpString("") - if bytes.Compare(str, []byte{0, 0}) != 0 { + if !bytes.Equal(str, []byte{0, 0}) { t.Errorf("expected empty string to return double 0, but found: % x", str) } if err != nil { @@ -44,7 +44,7 @@ func TestBMPString(t *testing.T) { // Example from https://tools.ietf.org/html/rfc7292#appendix-B str, err = bmpString("Beavis") - if bytes.Compare(str, []byte{0x00, 0x42, 0x00, 0x65, 0x00, 0x61, 0x00, 0x0076, 0x00, 0x69, 0x00, 0x73, 0x00, 0x00}) != 0 { + if !bytes.Equal(str, []byte{0x00, 0x42, 0x00, 0x65, 0x00, 0x61, 0x00, 0x0076, 0x00, 0x69, 0x00, 0x73, 0x00, 0x00}) { t.Errorf("expected 'Beavis' to return 0x00 0x42 0x00 0x65 0x00 0x61 0x00 0x76 0x00 0x69 0x00 0x73 0x00 0x00, but found: % x", str) } if err != nil { @@ -54,7 +54,7 @@ func TestBMPString(t *testing.T) { // some characters from the "Letterlike Symbols Unicode block" tst := "\u2115 - Double-struck N" str, err = bmpString(tst) - if bytes.Compare(str, []byte{0x21, 0x15, 0x00, 0x20, 0x00, 0x2d, 0x00, 0x20, 0x00, 0x44, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x62, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x2d, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x75, 0x00, 0x63, 0x00, 0x6b, 0x00, 0x20, 0x00, 0x4e, 0x00, 0x00}) != 0 { + if !bytes.Equal(str, []byte{0x21, 0x15, 0x00, 0x20, 0x00, 0x2d, 0x00, 0x20, 0x00, 0x44, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x62, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x2d, 0x00, 0x73, 0x00, 0x74, 0x00, 0x72, 0x00, 0x75, 0x00, 0x63, 0x00, 0x6b, 0x00, 0x20, 0x00, 0x4e, 0x00, 0x00}) { t.Errorf("expected '%s' to return 0x21 0x15 0x00 0x20 0x00 0x2d 0x00 0x20 0x00 0x44 0x00 0x6f 0x00 0x75 0x00 0x62 0x00 0x6c 0x00 0x65 0x00 0x2d 0x00 0x73 0x00 0x74 0x00 0x72 0x00 0x75 0x00 0x63 0x00 0x6b 0x00 0x20 0x00 0x4e 0x00 0x00, but found: % x", tst, str) } if err != nil { diff --git a/builder/azure/pkcs12/crypto_test.go b/builder/azure/pkcs12/crypto_test.go index 3f40ba771..fb7f8484d 100644 --- a/builder/azure/pkcs12/crypto_test.go +++ b/builder/azure/pkcs12/crypto_test.go @@ -47,7 +47,7 @@ func pbDecrypt(info decryptable, password []byte) (decrypted []byte, err error) if psLen := int(decrypted[len(decrypted)-1]); psLen > 0 && psLen <= cbc.BlockSize() { m := decrypted[:len(decrypted)-psLen] ps := decrypted[len(decrypted)-psLen:] - if bytes.Compare(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) != 0 { + if !bytes.Equal(ps, bytes.Repeat([]byte{byte(psLen)}, psLen)) { return nil, ErrDecryption } decrypted = m @@ -87,7 +87,7 @@ func TestPbDecrypterFor(t *testing.T) { expectedM := []byte{185, 73, 135, 249, 137, 1, 122, 247} cbc.CryptBlocks(M, M) - if bytes.Compare(M, expectedM) != 0 { + if !bytes.Equal(M, expectedM) { t.Errorf("expected M to be '%d', but found '%d", expectedM, M) } } @@ -127,7 +127,7 @@ func TestPbDecrypt(t *testing.T) { if err != nil { t.Errorf("error decrypting C=%x: %v", c, err) } - if bytes.Compare(m, e) != 0 { + if !bytes.Equal(m, e) { t.Errorf("expected C=%x to be decoded to M=%x, but found %x", c, e, m) } case error: diff --git a/builder/azure/pkcs12/pbkdf_test.go b/builder/azure/pkcs12/pbkdf_test.go index a52b697d8..cd66e059e 100644 --- a/builder/azure/pkcs12/pbkdf_test.go +++ b/builder/azure/pkcs12/pbkdf_test.go @@ -12,7 +12,7 @@ func TestThatPBKDFWorksCorrectlyForLongKeys(t *testing.T) { password, _ := bmpString("sesame") key := pbkdf(salt, password, 2048) - if expected := []byte("\x7c\xd9\xfd\x3e\x2b\x3b\xe7\x69\x1a\x44\xe3\xbe\xf0\xf9\xea\x0f\xb9\xb8\x97\xd4\xe3\x25\xd9\xd1"); bytes.Compare(key, expected) != 0 { + if expected := []byte("\x7c\xd9\xfd\x3e\x2b\x3b\xe7\x69\x1a\x44\xe3\xbe\xf0\xf9\xea\x0f\xb9\xb8\x97\xd4\xe3\x25\xd9\xd1"); !bytes.Equal(key, expected) { t.Fatalf("expected key '% x', but found '% x'", key, expected) } } diff --git a/post-processor/vagrant/aws_test.go b/post-processor/vagrant/aws_test.go index 7754a48ec..02eb02365 100644 --- a/post-processor/vagrant/aws_test.go +++ b/post-processor/vagrant/aws_test.go @@ -31,7 +31,7 @@ func TestAWSProvider_ArtifactId(t *testing.T) { t.Fatalf("should not have error: %s", err) } result := `aws.region_config "us-east-1", ami: "ami-1234"` - if strings.Index(vagrantfile, result) == -1 { + if !strings.Contains(vagrantfile, result) { t.Fatalf("wrong substitution: %s", vagrantfile) } } diff --git a/post-processor/vagrant/digitalocean_test.go b/post-processor/vagrant/digitalocean_test.go index 964877c75..6256fc249 100644 --- a/post-processor/vagrant/digitalocean_test.go +++ b/post-processor/vagrant/digitalocean_test.go @@ -31,11 +31,11 @@ func TestDigitalOceanProvider_ArtifactId(t *testing.T) { t.Fatalf("should not have error: %s", err) } image := `digital_ocean.image = "42"` - if strings.Index(vagrantfile, image) == -1 { + if !strings.Contains(vagrantfile, image) { t.Fatalf("wrong image substitution: %s", vagrantfile) } region := `digital_ocean.region = "San Francisco"` - if strings.Index(vagrantfile, region) == -1 { + if !strings.Contains(vagrantfile, region) { t.Fatalf("wrong region substitution: %s", vagrantfile) } } From 35578d9ed112cb72d69bc706f8311cd29069387a Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 18:47:10 -0700 Subject: [PATCH 06/11] remove unnecessary type conversions --- builder/amazon/common/access_config.go | 2 +- builder/amazon/common/state.go | 2 +- builder/azure/common/gluestrings.go | 2 +- builder/cloudstack/ssh.go | 2 +- builder/digitalocean/step_create_droplet.go | 5 +- builder/hyperv/common/driver_ps_4.go | 6 +- builder/hyperv/common/step_configure_ip.go | 7 +- builder/triton/access_config.go | 2 +- builder/virtualbox/common/ssh.go | 2 +- common/powershell/hyperv/hyperv.go | 74 ++++++++++----------- common/powershell/powershell.go | 2 +- communicator/ssh/password.go | 5 +- provisioner/ansible/scp.go | 2 +- 13 files changed, 58 insertions(+), 55 deletions(-) diff --git a/builder/amazon/common/access_config.go b/builder/amazon/common/access_config.go index 5e11fcd32..1fd66d091 100644 --- a/builder/amazon/common/access_config.go +++ b/builder/amazon/common/access_config.go @@ -115,5 +115,5 @@ func GetInstanceMetaData(path string) (contents []byte, err error) { if err != nil { return } - return []byte(body), err + return body, err } diff --git a/builder/amazon/common/state.go b/builder/amazon/common/state.go index e529f0c5f..42beb0e00 100644 --- a/builder/amazon/common/state.go +++ b/builder/amazon/common/state.go @@ -163,7 +163,7 @@ func WaitForState(conf *StateChangeConf) (i interface{}, err error) { log.Printf("Waiting for state to become: %s", conf.Target) sleepSeconds := SleepSeconds() - maxTicks := int(TimeoutSeconds()/sleepSeconds) + 1 + maxTicks := TimeoutSeconds()/sleepSeconds + 1 notfoundTick := 0 for { diff --git a/builder/azure/common/gluestrings.go b/builder/azure/common/gluestrings.go index 0988b98a9..b59b15fcf 100644 --- a/builder/azure/common/gluestrings.go +++ b/builder/azure/common/gluestrings.go @@ -18,5 +18,5 @@ func GlueStrings(a, b string) string { shift++ } - return string(a[:shift]) + b + return a[:shift] + b } diff --git a/builder/cloudstack/ssh.go b/builder/cloudstack/ssh.go index 1deabc9f6..b980102f4 100644 --- a/builder/cloudstack/ssh.go +++ b/builder/cloudstack/ssh.go @@ -44,7 +44,7 @@ func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) { return nil, fmt.Errorf("Error loading configured private key file: %s", err) } - signer, err := ssh.ParsePrivateKey([]byte(privateKey)) + signer, err := ssh.ParsePrivateKey(privateKey) if err != nil { return nil, fmt.Errorf("Error setting up SSH config: %s", err) } diff --git a/builder/digitalocean/step_create_droplet.go b/builder/digitalocean/step_create_droplet.go index acd9fd771..0a214199a 100644 --- a/builder/digitalocean/step_create_droplet.go +++ b/builder/digitalocean/step_create_droplet.go @@ -3,10 +3,11 @@ package digitalocean import ( "fmt" + "io/ioutil" + "github.com/digitalocean/godo" "github.com/mitchellh/multistep" "github.com/mitchellh/packer/packer" - "io/ioutil" ) type stepCreateDroplet struct { @@ -41,7 +42,7 @@ func (s *stepCreateDroplet) Run(state multistep.StateBag) multistep.StepAction { Slug: c.Image, }, SSHKeys: []godo.DropletCreateSSHKey{ - {ID: int(sshKeyId)}, + {ID: sshKeyId}, }, PrivateNetworking: c.PrivateNetworking, UserData: userData, diff --git a/builder/hyperv/common/driver_ps_4.go b/builder/hyperv/common/driver_ps_4.go index ae125259a..e563f89ea 100644 --- a/builder/hyperv/common/driver_ps_4.go +++ b/builder/hyperv/common/driver_ps_4.go @@ -254,7 +254,7 @@ func (d *HypervPS4Driver) verifyPSVersion() error { return err } - versionOutput := strings.TrimSpace(string(cmdOut)) + versionOutput := strings.TrimSpace(cmdOut) log.Printf("%s output: %s", versionCmd, versionOutput) ver, err := strconv.ParseInt(versionOutput, 10, 32) @@ -283,7 +283,7 @@ func (d *HypervPS4Driver) verifyPSHypervModule() error { return err } - res := strings.TrimSpace(string(cmdOut)) + res := strings.TrimSpace(cmdOut) if res == "False" { err := fmt.Errorf("%s", "PS Hyper-V module is not loaded. Make sure Hyper-V feature is on.") @@ -305,7 +305,7 @@ func (d *HypervPS4Driver) verifyHypervPermissions() error { return err } - res := strings.TrimSpace(string(cmdOut)) + res := strings.TrimSpace(cmdOut) if res == "False" { isAdmin, _ := powershell.IsCurrentUserAnAdministrator() diff --git a/builder/hyperv/common/step_configure_ip.go b/builder/hyperv/common/step_configure_ip.go index 90e17b238..330f784a0 100644 --- a/builder/hyperv/common/step_configure_ip.go +++ b/builder/hyperv/common/step_configure_ip.go @@ -2,11 +2,12 @@ package common import ( "fmt" - "github.com/mitchellh/multistep" - "github.com/mitchellh/packer/packer" "log" "strings" "time" + + "github.com/mitchellh/multistep" + "github.com/mitchellh/packer/packer" ) type StepConfigureIp struct { @@ -35,7 +36,7 @@ func (s *StepConfigureIp) Run(state multistep.StateBag) multistep.StepAction { return multistep.ActionHalt } - ip = strings.TrimSpace(string(cmdOut)) + ip = strings.TrimSpace(cmdOut) if ip != "False" { break diff --git a/builder/triton/access_config.go b/builder/triton/access_config.go index 05959e7b8..08deefdff 100644 --- a/builder/triton/access_config.go +++ b/builder/triton/access_config.go @@ -59,7 +59,7 @@ func (c *AccessConfig) CreateTritonClient() (*cloudapi.Client, error) { return nil, err } - userauth, err := auth.NewAuth(c.Account, string(keyData), "rsa-sha256") + userauth, err := auth.NewAuth(c.Account, keyData, "rsa-sha256") if err != nil { return nil, err } diff --git a/builder/virtualbox/common/ssh.go b/builder/virtualbox/common/ssh.go index b4a05c549..0ad514be9 100644 --- a/builder/virtualbox/common/ssh.go +++ b/builder/virtualbox/common/ssh.go @@ -15,7 +15,7 @@ func CommHost(host string) func(multistep.StateBag) (string, error) { func SSHPort(state multistep.StateBag) (int, error) { sshHostPort := state.Get("sshHostPort").(int) - return int(sshHostPort), nil + return sshHostPort, nil } func SSHConfigFunc(config SSHConfig) func(multistep.StateBag) (*gossh.ClientConfig, error) { diff --git a/common/powershell/hyperv/hyperv.go b/common/powershell/hyperv/hyperv.go index e57a98f0d..a674857b0 100644 --- a/common/powershell/hyperv/hyperv.go +++ b/common/powershell/hyperv/hyperv.go @@ -575,7 +575,7 @@ func GetExternalOnlineVirtualSwitch() (string, error) { var script = ` $adapters = Get-NetAdapter -Physical -ErrorAction SilentlyContinue | Where-Object { $_.Status -eq 'Up' } | Sort-Object -Descending -Property Speed -foreach ($adapter in $adapters) { +foreach ($adapter in $adapters) { $switch = Get-VMSwitch -SwitchType External | Where-Object { $_.NetAdapterInterfaceDescription -eq $adapter.InterfaceDescription } if ($switch -ne $null) { @@ -605,10 +605,10 @@ $adapters = foreach ($name in $names) { Get-NetAdapter -Physical -Name $name -ErrorAction SilentlyContinue | where status -eq 'up' } -foreach ($adapter in $adapters) { +foreach ($adapter in $adapters) { $switch = Get-VMSwitch -SwitchType External | where { $_.NetAdapterInterfaceDescription -eq $adapter.InterfaceDescription } - if ($switch -eq $null) { + if ($switch -eq $null) { $switch = New-VMSwitch -Name $switchName -NetAdapterName $adapter.Name -AllowManagementOS $true -Notes 'Parent OS, VMs, WiFi' } @@ -617,9 +617,9 @@ foreach ($adapter in $adapters) { } } -if($switch -ne $null) { - Get-VMNetworkAdapter -VMName $vmName | Connect-VMNetworkAdapter -VMSwitch $switch -} else { +if($switch -ne $null) { + Get-VMNetworkAdapter -VMName $vmName | Connect-VMNetworkAdapter -VMSwitch $switch +} else { Write-Error 'No internet adapters found' } ` @@ -721,7 +721,7 @@ $vm.Uptime.TotalSeconds return 0, err } - uptime, err := strconv.ParseUint(strings.TrimSpace(string(cmdOut)), 10, 64) + uptime, err := strconv.ParseUint(strings.TrimSpace(cmdOut), 10, 64) return uptime, err } @@ -752,7 +752,7 @@ func IpAddress(mac string) (string, error) { param([string]$mac, [int]$addressIndex) try { $ip = Get-Vm | %{$_.NetworkAdapters} | ?{$_.MacAddress -eq $mac} | %{$_.IpAddresses[$addressIndex]} - + if($ip -eq $null) { return "" } @@ -807,7 +807,7 @@ func TypeScanCodes(vmName string, scanCodes string) error { param([string]$vmName, [string]$scanCodes) #Requires -Version 3 #Requires -RunAsAdministrator - + function Get-VMConsole { [CmdletBinding()] @@ -815,16 +815,16 @@ param([string]$vmName, [string]$scanCodes) [Parameter(Mandatory)] [string] $VMName ) - + $ErrorActionPreference = "Stop" - + $vm = Get-CimInstance -Namespace "root\virtualization\v2" -ClassName Msvm_ComputerSystem -ErrorAction Ignore -Verbose:$false | where ElementName -eq $VMName | select -first 1 if ($vm -eq $null){ Write-Error ("VirtualMachine({0}) is not found!" -f $VMName) } - + $vmKeyboard = $vm | Get-CimAssociatedInstance -ResultClassName "Msvm_Keyboard" -ErrorAction Ignore -Verbose:$false - + if ($vmKeyboard -eq $null) { $vmKeyboard = Get-CimInstance -Namespace "root\virtualization\v2" -ClassName Msvm_Keyboard -ErrorAction Ignore -Verbose:$false | where SystemName -eq $vm.Name | select -first 1 } @@ -832,22 +832,22 @@ param([string]$vmName, [string]$scanCodes) if ($vmKeyboard -eq $null) { $vmKeyboard = Get-CimInstance -Namespace "root\virtualization" -ClassName Msvm_Keyboard -ErrorAction Ignore -Verbose:$false | where SystemName -eq $vm.Name | select -first 1 } - + if ($vmKeyboard -eq $null){ Write-Error ("VirtualMachine({0}) keyboard class is not found!" -f $VMName) } - + #TODO: It may be better using New-Module -AsCustomObject to return console object? - + #Console object to return $console = [pscustomobject] @{ Msvm_ComputerSystem = $vm Msvm_Keyboard = $vmKeyboard } - + #Need to import assembly to use System.Windows.Input.Key Add-Type -AssemblyName WindowsBase - + #region Add Console Members $console | Add-Member -MemberType ScriptMethod -Name TypeText -Value { [OutputType([bool])] @@ -859,13 +859,13 @@ param([string]$vmName, [string]$scanCodes) $result = $this.Msvm_Keyboard | Invoke-CimMethod -MethodName "TypeText" -Arguments @{ asciiText = $AsciiText } return (0 -eq $result.ReturnValue) } - + #Define method:TypeCtrlAltDel $console | Add-Member -MemberType ScriptMethod -Name TypeCtrlAltDel -Value { $result = $this.Msvm_Keyboard | Invoke-CimMethod -MethodName "TypeCtrlAltDel" return (0 -eq $result.ReturnValue) } - + #Define method:TypeKey $console | Add-Member -MemberType ScriptMethod -Name TypeKey -Value { [OutputType([bool])] @@ -874,9 +874,9 @@ param([string]$vmName, [string]$scanCodes) [Windows.Input.Key] $Key, [Windows.Input.ModifierKeys] $ModifierKey = [Windows.Input.ModifierKeys]::None ) - + $keyCode = [Windows.Input.KeyInterop]::VirtualKeyFromKey($Key) - + switch ($ModifierKey) { ([Windows.Input.ModifierKeys]::Control){ $modifierKeyCode = [Windows.Input.KeyInterop]::VirtualKeyFromKey([Windows.Input.Key]::LeftCtrl)} @@ -884,7 +884,7 @@ param([string]$vmName, [string]$scanCodes) ([Windows.Input.ModifierKeys]::Shift){ $modifierKeyCode = [Windows.Input.KeyInterop]::VirtualKeyFromKey([Windows.Input.Key]::LeftShift)} ([Windows.Input.ModifierKeys]::Windows){ $modifierKeyCode = [Windows.Input.KeyInterop]::VirtualKeyFromKey([Windows.Input.Key]::LWin)} } - + if ($ModifierKey -eq [Windows.Input.ModifierKeys]::None) { $result = $this.Msvm_Keyboard | Invoke-CimMethod -MethodName "TypeKey" -Arguments @{ keyCode = $keyCode } @@ -897,7 +897,7 @@ param([string]$vmName, [string]$scanCodes) } $result = return (0 -eq $result.ReturnValue) } - + #Define method:Scancodes $console | Add-Member -MemberType ScriptMethod -Name TypeScancodes -Value { [OutputType([bool])] @@ -908,7 +908,7 @@ param([string]$vmName, [string]$scanCodes) $result = $this.Msvm_Keyboard | Invoke-CimMethod -MethodName "TypeScancodes" -Arguments @{ ScanCodes = $ScanCodes } return (0 -eq $result.ReturnValue) } - + #Define method:ExecCommand $console | Add-Member -MemberType ScriptMethod -Name ExecCommand -Value { param ( @@ -918,46 +918,46 @@ param([string]$vmName, [string]$scanCodes) if ([String]::IsNullOrEmpty($Command)){ return } - + $console.TypeText($Command) > $null $console.TypeKey([Windows.Input.Key]::Enter) > $null #sleep -Milliseconds 100 } - + #Define method:Dispose $console | Add-Member -MemberType ScriptMethod -Name Dispose -Value { $this.Msvm_ComputerSystem.Dispose() $this.Msvm_Keyboard.Dispose() } - - + + #endregion - + return $console } - + $vmConsole = Get-VMConsole -VMName $vmName $scanCodesToSend = '' $scanCodes.Split(' ') | %{ $scanCode = $_ - + if ($scanCode.StartsWith('wait')){ $timeToWait = $scanCode.Substring(4) if (!$timeToWait){ $timeToWait = "1" } - + if ($scanCodesToSend){ $scanCodesToSendByteArray = [byte[]]@($scanCodesToSend.Split(' ') | %{"0x$_"}) - + $scanCodesToSendByteArray | %{ $vmConsole.TypeScancodes($_) } } - + write-host "Special code found, will sleep $timeToWait second(s) at this point." Start-Sleep -s $timeToWait - + $scanCodesToSend = '' } else { if ($scanCodesToSend){ @@ -971,7 +971,7 @@ param([string]$vmName, [string]$scanCodes) } if ($scanCodesToSend){ $scanCodesToSendByteArray = [byte[]]@($scanCodesToSend.Split(' ') | %{"0x$_"}) - + $scanCodesToSendByteArray | %{ $vmConsole.TypeScancodes($_) } diff --git a/common/powershell/powershell.go b/common/powershell/powershell.go index 423bcd857..83190d1a4 100644 --- a/common/powershell/powershell.go +++ b/common/powershell/powershell.go @@ -219,7 +219,7 @@ param([string]$moduleName) return false, err } - res := strings.TrimSpace(string(cmdOut)) + res := strings.TrimSpace(cmdOut) if res == powerShellFalse { err := fmt.Errorf("PowerShell %s module is not loaded. Make sure %s feature is on.", moduleName, moduleName) diff --git a/communicator/ssh/password.go b/communicator/ssh/password.go index 8db6f82da..774be47f1 100644 --- a/communicator/ssh/password.go +++ b/communicator/ssh/password.go @@ -1,8 +1,9 @@ package ssh import ( - "golang.org/x/crypto/ssh" "log" + + "golang.org/x/crypto/ssh" ) // An implementation of ssh.KeyboardInteractiveChallenge that simply sends @@ -19,7 +20,7 @@ func PasswordKeyboardInteractive(password string) ssh.KeyboardInteractiveChallen // Just send the password back for all questions answers := make([]string, len(questions)) for i := range answers { - answers[i] = string(password) + answers[i] = password } return answers, nil diff --git a/provisioner/ansible/scp.go b/provisioner/ansible/scp.go index 03a8fe526..b36b22590 100644 --- a/provisioner/ansible/scp.go +++ b/provisioner/ansible/scp.go @@ -321,7 +321,7 @@ func scpResponse(r *bufio.Reader) error { // 1 is a warning. Anything higher (really just 2) is an error. if code > 1 { - return errors.New(string(message)) + return errors.New(message) } log.Println("WARNING:", err) From cc11ec356649f17fda157e1b5ab8881e3992e90c Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 20:35:22 -0700 Subject: [PATCH 07/11] check for a couple errors --- builder/amazon/chroot/communicator.go | 5 ++++- builder/amazon/common/step_run_source_instance.go | 10 ++++++++-- communicator/ssh/communicator.go | 2 +- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/builder/amazon/chroot/communicator.go b/builder/amazon/chroot/communicator.go index b77ee03e8..24284efab 100644 --- a/builder/amazon/chroot/communicator.go +++ b/builder/amazon/chroot/communicator.go @@ -69,7 +69,10 @@ func (c *Communicator) Upload(dst string, r io.Reader, fi *os.FileInfo) error { return fmt.Errorf("Error preparing shell script: %s", err) } defer os.Remove(tf.Name()) - io.Copy(tf, r) + + if _, err := io.Copy(tf, r); err != nil { + return err + } cpCmd, err := c.CmdWrapper(fmt.Sprintf("cp %s %s", tf.Name(), dst)) if err != nil { diff --git a/builder/amazon/common/step_run_source_instance.go b/builder/amazon/common/step_run_source_instance.go index 8ac837875..0f33611a2 100644 --- a/builder/amazon/common/step_run_source_instance.go +++ b/builder/amazon/common/step_run_source_instance.go @@ -342,7 +342,10 @@ func (s *StepRunSourceInstance) Cleanup(state multistep.StateBag) { Target: "cancelled", } - WaitForState(&stateChange) + _, err := WaitForState(&stateChange) + if err != nil { + ui.Error(err.Error()) + } } @@ -359,6 +362,9 @@ func (s *StepRunSourceInstance) Cleanup(state multistep.StateBag) { Target: "terminated", } - WaitForState(&stateChange) + _, err := WaitForState(&stateChange) + if err != nil { + ui.Error(err.Error()) + } } } diff --git a/communicator/ssh/communicator.go b/communicator/ssh/communicator.go index 9cef308fb..d9fc0442d 100644 --- a/communicator/ssh/communicator.go +++ b/communicator/ssh/communicator.go @@ -250,7 +250,7 @@ func (c *comm) newSession() (session *ssh.Session, err error) { func (c *comm) reconnect() (err error) { if c.conn != nil { - c.conn.Close() + return c.conn.Close() } // Set the conn and client to nil since we'll recreate it From de296ac06b33f674946c7ae62051ed6dd9920b96 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Tue, 28 Mar 2017 20:45:25 -0700 Subject: [PATCH 08/11] simplify --- provisioner/windows-shell/provisioner.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/provisioner/windows-shell/provisioner.go b/provisioner/windows-shell/provisioner.go index b0d50998f..6baebe70a 100644 --- a/provisioner/windows-shell/provisioner.go +++ b/provisioner/windows-shell/provisioner.go @@ -150,11 +150,7 @@ func (p *Provisioner) Prepare(raws ...interface{}) error { } } - if errs != nil { - return errs - } - - return nil + return errs } // This function takes the inline scripts, concatenates them From 4fcbf75da91f31974b963ed4f0604acf3324d1d6 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Wed, 29 Mar 2017 12:38:33 -0700 Subject: [PATCH 09/11] s/non existent/nonexistent/ --- builder/parallels/iso/builder_test.go | 2 +- builder/parallels/pvm/config_test.go | 2 +- builder/qemu/builder_test.go | 2 +- builder/virtualbox/iso/builder_test.go | 2 +- builder/virtualbox/ovf/config_test.go | 2 +- builder/vmware/iso/builder_test.go | 2 +- builder/vmware/vmx/builder_test.go | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/builder/parallels/iso/builder_test.go b/builder/parallels/iso/builder_test.go index 1761101be..8230941a1 100644 --- a/builder/parallels/iso/builder_test.go +++ b/builder/parallels/iso/builder_test.go @@ -90,7 +90,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/parallels/pvm/config_test.go b/builder/parallels/pvm/config_test.go index 3add12e6e..87fd96b3d 100644 --- a/builder/parallels/pvm/config_test.go +++ b/builder/parallels/pvm/config_test.go @@ -87,7 +87,7 @@ func TestNewConfig_InvalidFloppies(t *testing.T) { c["floppy_files"] = []string{"nonexistant.bat", "nonexistant.ps1"} _, _, errs := NewConfig(c) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/qemu/builder_test.go b/builder/qemu/builder_test.go index 554909abc..9704d37b8 100644 --- a/builder/qemu/builder_test.go +++ b/builder/qemu/builder_test.go @@ -305,7 +305,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/virtualbox/iso/builder_test.go b/builder/virtualbox/iso/builder_test.go index ed6b7ba1e..5cf8bde28 100644 --- a/builder/virtualbox/iso/builder_test.go +++ b/builder/virtualbox/iso/builder_test.go @@ -130,7 +130,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/virtualbox/ovf/config_test.go b/builder/virtualbox/ovf/config_test.go index cb4e457aa..9797c4831 100644 --- a/builder/virtualbox/ovf/config_test.go +++ b/builder/virtualbox/ovf/config_test.go @@ -45,7 +45,7 @@ func TestNewConfig_InvalidFloppies(t *testing.T) { c["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} _, _, errs := NewConfig(c) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/vmware/iso/builder_test.go b/builder/vmware/iso/builder_test.go index 8af4cc62e..886d01dae 100644 --- a/builder/vmware/iso/builder_test.go +++ b/builder/vmware/iso/builder_test.go @@ -131,7 +131,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { diff --git a/builder/vmware/vmx/builder_test.go b/builder/vmware/vmx/builder_test.go index ef82cd0e2..22b639f2b 100644 --- a/builder/vmware/vmx/builder_test.go +++ b/builder/vmware/vmx/builder_test.go @@ -60,7 +60,7 @@ func TestBuilderPrepare_InvalidFloppies(t *testing.T) { b = Builder{} _, errs := b.Prepare(config) if errs == nil { - t.Fatalf("Non existent floppies should trigger multierror") + t.Fatalf("Nonexistent floppies should trigger multierror") } if len(errs.(*packer.MultiError).Errors) != 2 { From 048e3166456acc476dd869b8702990938868d319 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Wed, 29 Mar 2017 12:44:42 -0700 Subject: [PATCH 10/11] s/TargettedUi/TargetedUI/ --- command/build.go | 4 ++-- packer/build.go | 4 ++-- packer/ui.go | 16 ++++++++-------- packer/ui_test.go | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/command/build.go b/command/build.go index d1f4b0c54..9e79326a4 100644 --- a/command/build.go +++ b/command/build.go @@ -212,7 +212,7 @@ func (c BuildCommand) Run(args []string) int { c.Ui.Error("\n==> Some builds didn't complete successfully and had errors:") for name, err := range errors { // Create a UI for the machine readable stuff to be targeted - ui := &packer.TargettedUi{ + ui := &packer.TargetedUI{ Target: name, Ui: c.Ui, } @@ -227,7 +227,7 @@ func (c BuildCommand) Run(args []string) int { c.Ui.Say("\n==> Builds finished. The artifacts of successful builds are:") for name, buildArtifacts := range artifacts.m { // Create a UI for the machine readable stuff to be targeted - ui := &packer.TargettedUi{ + ui := &packer.TargetedUI{ Target: name, Ui: c.Ui, } diff --git a/packer/build.go b/packer/build.go index dfc8bff7f..d14024b77 100644 --- a/packer/build.go +++ b/packer/build.go @@ -211,7 +211,7 @@ func (b *coreBuild) Run(originalUi Ui, cache Cache) ([]Artifact, error) { artifacts := make([]Artifact, 0, 1) // The builder just has a normal Ui, but targeted - builderUi := &TargettedUi{ + builderUi := &TargetedUI{ Target: b.Name(), Ui: originalUi, } @@ -236,7 +236,7 @@ PostProcessorRunSeqLoop: for _, ppSeq := range b.postProcessors { priorArtifact := builderArtifact for i, corePP := range ppSeq { - ppUi := &TargettedUi{ + ppUi := &TargetedUI{ Target: fmt.Sprintf("%s (%s)", b.Name(), corePP.processorType), Ui: originalUi, } diff --git a/packer/ui.go b/packer/ui.go index 7616eb7ac..c107c23b8 100644 --- a/packer/ui.go +++ b/packer/ui.go @@ -46,12 +46,12 @@ type ColoredUi struct { Ui Ui } -// TargettedUi is a UI that wraps another UI implementation and modifies +// TargetedUI is a UI that wraps another UI implementation and modifies // the output to indicate a specific target. Specifically, all Say output // is prefixed with the target name. Message output is not prefixed but // is offset by the length of the target so that output is lined up properly // with Say output. Machine-readable output has the proper target set. -type TargettedUi struct { +type TargetedUI struct { Target string Ui Ui } @@ -132,28 +132,28 @@ func (u *ColoredUi) supportsColors() bool { return cygwin } -func (u *TargettedUi) Ask(query string) (string, error) { +func (u *TargetedUI) Ask(query string) (string, error) { return u.Ui.Ask(u.prefixLines(true, query)) } -func (u *TargettedUi) Say(message string) { +func (u *TargetedUI) Say(message string) { u.Ui.Say(u.prefixLines(true, message)) } -func (u *TargettedUi) Message(message string) { +func (u *TargetedUI) Message(message string) { u.Ui.Message(u.prefixLines(false, message)) } -func (u *TargettedUi) Error(message string) { +func (u *TargetedUI) Error(message string) { u.Ui.Error(u.prefixLines(true, message)) } -func (u *TargettedUi) Machine(t string, args ...string) { +func (u *TargetedUI) Machine(t string, args ...string) { // Prefix in the target, then pass through u.Ui.Machine(fmt.Sprintf("%s,%s", u.Target, t), args...) } -func (u *TargettedUi) prefixLines(arrow bool, message string) string { +func (u *TargetedUI) prefixLines(arrow bool, message string) string { arrowText := "==>" if !arrow { arrowText = strings.Repeat(" ", len(arrowText)) diff --git a/packer/ui_test.go b/packer/ui_test.go index e65a7f3db..76d0cd5b5 100644 --- a/packer/ui_test.go +++ b/packer/ui_test.go @@ -97,9 +97,9 @@ func TestColoredUi_noColorEnv(t *testing.T) { } } -func TestTargettedUi(t *testing.T) { +func TestTargetedUI(t *testing.T) { bufferUi := testUi() - targettedUi := &TargettedUi{ + targettedUi := &TargetedUI{ Target: "foo", Ui: bufferUi, } @@ -142,11 +142,11 @@ func TestColoredUi_ImplUi(t *testing.T) { } } -func TestTargettedUi_ImplUi(t *testing.T) { +func TestTargetedUI_ImplUi(t *testing.T) { var raw interface{} - raw = &TargettedUi{} + raw = &TargetedUI{} if _, ok := raw.(Ui); !ok { - t.Fatalf("TargettedUi must implement Ui") + t.Fatalf("TargetedUI must implement Ui") } } From 6f27f673468ea3cecab740e990b56e2c79fc8856 Mon Sep 17 00:00:00 2001 From: Matthew Hooker Date: Wed, 29 Mar 2017 13:38:31 -0700 Subject: [PATCH 11/11] more fixes from errcheck --- builder/profitbricks/step_create_server.go | 14 ++++++++++---- builder/profitbricks/step_take_snapshot.go | 5 ++++- post-processor/amazon-import/post-processor.go | 2 +- provisioner/ansible/provisioner.go | 4 +++- provisioner/ansible/scp.go | 10 +++++----- 5 files changed, 23 insertions(+), 12 deletions(-) diff --git a/builder/profitbricks/step_create_server.go b/builder/profitbricks/step_create_server.go index f9e7ff140..ef606e380 100644 --- a/builder/profitbricks/step_create_server.go +++ b/builder/profitbricks/step_create_server.go @@ -72,7 +72,11 @@ func (s *stepCreateServer) Run(state multistep.StateBag) multistep.StepAction { if datacenter.StatusCode > 299 { if datacenter.StatusCode > 299 { var restError RestError - json.Unmarshal([]byte(datacenter.Response), &restError) + err := json.Unmarshal([]byte(datacenter.Response), &restError) + if err != nil { + ui.Error(fmt.Sprintf("Error decoding json response: %s", err.Error())) + return multistep.ActionHalt + } if len(restError.Messages) > 0 { ui.Error(restError.Messages[0].Message) } else { @@ -147,9 +151,11 @@ func (s *stepCreateServer) Cleanup(state multistep.StateBag) { if dcId, ok := state.GetOk("datacenter_id"); ok { resp := profitbricks.DeleteDatacenter(dcId.(string)) - s.checkForErrors(resp) - err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c) - if err != nil { + if err := s.checkForErrors(resp); err != nil { + ui.Error(fmt.Sprintf( + "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) + } + if err := s.waitTillProvisioned(resp.Headers.Get("Location"), *c); err != nil { ui.Error(fmt.Sprintf( "Error deleting Virtual Data Center. Please destroy it manually: %s", err)) } diff --git a/builder/profitbricks/step_take_snapshot.go b/builder/profitbricks/step_take_snapshot.go index 35820f3e1..1c172daef 100644 --- a/builder/profitbricks/step_take_snapshot.go +++ b/builder/profitbricks/step_take_snapshot.go @@ -28,7 +28,10 @@ func (s *stepTakeSnapshot) Run(state multistep.StateBag) multistep.StepAction { if snapshot.StatusCode > 299 { var restError RestError - json.Unmarshal([]byte(snapshot.Response), &restError) + if err := json.Unmarshal([]byte(snapshot.Response), &restError); err != nil { + ui.Error(err.Error()) + return multistep.ActionHalt + } if len(restError.Messages) > 0 { ui.Error(restError.Messages[0].Message) } else { diff --git a/post-processor/amazon-import/post-processor.go b/post-processor/amazon-import/post-processor.go index 77ea77cb9..236436e13 100644 --- a/post-processor/amazon-import/post-processor.go +++ b/post-processor/amazon-import/post-processor.go @@ -239,7 +239,7 @@ func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (pac return nil, false, fmt.Errorf("Error waiting for AMI (%s): %s", *resp.ImageId, err) } - ec2conn.DeregisterImage(&ec2.DeregisterImageInput{ + _, err = ec2conn.DeregisterImage(&ec2.DeregisterImageInput{ ImageId: &createdami, }) diff --git a/provisioner/ansible/provisioner.go b/provisioner/ansible/provisioner.go index 642d99bd8..0577c58f3 100644 --- a/provisioner/ansible/provisioner.go +++ b/provisioner/ansible/provisioner.go @@ -355,7 +355,9 @@ func (p *Provisioner) executeAnsible(ui packer.Ui, comm packer.Communicator, pri go repeat(stderr) log.Printf("Executing Ansible: %s", strings.Join(cmd.Args, " ")) - cmd.Start() + if err := cmd.Start(); err != nil { + return err + } wg.Wait() err = cmd.Wait() if err != nil { diff --git a/provisioner/ansible/scp.go b/provisioner/ansible/scp.go index b36b22590..6378bdc14 100644 --- a/provisioner/ansible/scp.go +++ b/provisioner/ansible/scp.go @@ -104,8 +104,7 @@ func (state *scpDownloadState) FileProtocol(path string, info os.FileInfo, in *b size := info.Size() perms := fmt.Sprintf("C%04o", info.Mode().Perm()) fmt.Fprintln(out, perms, size, info.Name()) - err := scpResponse(in) - if err != nil { + if err := scpResponse(in); err != nil { return err } @@ -194,8 +193,7 @@ func (state *scpUploadState) FileProtocol(in *bufio.Reader, out io.Writer) error return err } - err = scpResponse(in) - if err != nil { + if err := scpResponse(in); err != nil { return err } @@ -260,7 +258,9 @@ type scpDownloadState struct { func (state *scpDownloadState) Protocol(in *bufio.Reader, out io.Writer) error { r := bufio.NewReader(in) // read the byte sent by the other side to start the transfer - scpResponse(r) + if err := scpResponse(r); err != nil { + return err + } return filepath.Walk(state.srcRoot, func(path string, info os.FileInfo, err error) error { if err != nil {