github.com/sneal/packer@v0.5.2/builder/vmware/common/step_output_dir.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"time"
     7  
     8  	"github.com/mitchellh/multistep"
     9  	"github.com/mitchellh/packer/packer"
    10  )
    11  
    12  // StepOutputDir sets up the output directory by creating it if it does
    13  // not exist, deleting it if it does exist and we're forcing, and cleaning
    14  // it up when we're done with it.
    15  type StepOutputDir struct {
    16  	Force bool
    17  
    18  	success bool
    19  }
    20  
    21  func (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction {
    22  	dir := state.Get("dir").(OutputDir)
    23  	ui := state.Get("ui").(packer.Ui)
    24  
    25  	exists, err := dir.DirExists()
    26  	if err != nil {
    27  		state.Put("error", err)
    28  		return multistep.ActionHalt
    29  	}
    30  
    31  	if exists {
    32  		if s.Force {
    33  			ui.Say("Deleting previous output directory...")
    34  			dir.RemoveAll()
    35  		} else {
    36  			state.Put("error", fmt.Errorf(
    37  				"Output directory '%s' already exists.", dir.String()))
    38  			return multistep.ActionHalt
    39  		}
    40  	}
    41  
    42  	if err := dir.MkdirAll(); err != nil {
    43  		state.Put("error", err)
    44  		return multistep.ActionHalt
    45  	}
    46  
    47  	s.success = true
    48  	return multistep.ActionContinue
    49  }
    50  
    51  func (s *StepOutputDir) Cleanup(state multistep.StateBag) {
    52  	if !s.success {
    53  		return
    54  	}
    55  
    56  	_, cancelled := state.GetOk(multistep.StateCancelled)
    57  	_, halted := state.GetOk(multistep.StateHalted)
    58  
    59  	if cancelled || halted {
    60  		dir := state.Get("dir").(OutputDir)
    61  		ui := state.Get("ui").(packer.Ui)
    62  
    63  		ui.Say("Deleting output directory...")
    64  		for i := 0; i < 5; i++ {
    65  			err := dir.RemoveAll()
    66  			if err == nil {
    67  				break
    68  			}
    69  
    70  			log.Printf("Error removing output dir: %s", err)
    71  			time.Sleep(2 * time.Second)
    72  		}
    73  	}
    74  }