github.com/rothwerx/packer@v0.9.0/builder/virtualbox/common/step_output_dir.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"path/filepath"
     8  	"time"
     9  
    10  	"github.com/mitchellh/multistep"
    11  	"github.com/mitchellh/packer/packer"
    12  )
    13  
    14  // StepOutputDir sets up the output directory by creating it if it does
    15  // not exist, deleting it if it does exist and we're forcing, and cleaning
    16  // it up when we're done with it.
    17  type StepOutputDir struct {
    18  	Force bool
    19  	Path  string
    20  
    21  	cleanup bool
    22  }
    23  
    24  func (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction {
    25  	ui := state.Get("ui").(packer.Ui)
    26  
    27  	if _, err := os.Stat(s.Path); err == nil {
    28  		if !s.Force {
    29  			err := fmt.Errorf(
    30  				"Output directory exists: %s\n\n"+
    31  					"Use the force flag to delete it prior to building.",
    32  				s.Path)
    33  			state.Put("error", err)
    34  			return multistep.ActionHalt
    35  		}
    36  
    37  		ui.Say("Deleting previous output directory...")
    38  		os.RemoveAll(s.Path)
    39  	}
    40  
    41  	// Enable cleanup
    42  	s.cleanup = true
    43  
    44  	// Create the directory
    45  	if err := os.MkdirAll(s.Path, 0755); err != nil {
    46  		state.Put("error", err)
    47  		return multistep.ActionHalt
    48  	}
    49  
    50  	// Make sure we can write in the directory
    51  	f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check"))
    52  	if err != nil {
    53  		err = fmt.Errorf("Couldn't write to output directory: %s", err)
    54  		state.Put("error", err)
    55  		return multistep.ActionHalt
    56  	}
    57  	f.Close()
    58  	os.Remove(f.Name())
    59  
    60  	return multistep.ActionContinue
    61  }
    62  
    63  func (s *StepOutputDir) Cleanup(state multistep.StateBag) {
    64  	if !s.cleanup {
    65  		return
    66  	}
    67  
    68  	_, cancelled := state.GetOk(multistep.StateCancelled)
    69  	_, halted := state.GetOk(multistep.StateHalted)
    70  
    71  	if cancelled || halted {
    72  		ui := state.Get("ui").(packer.Ui)
    73  
    74  		ui.Say("Deleting output directory...")
    75  		for i := 0; i < 5; i++ {
    76  			err := os.RemoveAll(s.Path)
    77  			if err == nil {
    78  				break
    79  			}
    80  
    81  			log.Printf("Error removing output dir: %s", err)
    82  			time.Sleep(2 * time.Second)
    83  		}
    84  	}
    85  }