github.com/rothwerx/packer@v0.9.0/builder/parallels/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  	success bool
    21  }
    22  
    23  func (s *StepOutputDir) Run(state multistep.StateBag) multistep.StepAction {
    24  	ui := state.Get("ui").(packer.Ui)
    25  
    26  	if _, err := os.Stat(s.Path); err == nil && s.Force {
    27  		ui.Say("Deleting previous output directory...")
    28  		os.RemoveAll(s.Path)
    29  	}
    30  
    31  	// Create the directory
    32  	if err := os.MkdirAll(s.Path, 0755); err != nil {
    33  		state.Put("error", err)
    34  		return multistep.ActionHalt
    35  	}
    36  
    37  	// Make sure we can write in the directory
    38  	f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check"))
    39  	if err != nil {
    40  		err = fmt.Errorf("Couldn't write to output directory: %s", err)
    41  		state.Put("error", err)
    42  		return multistep.ActionHalt
    43  	}
    44  	f.Close()
    45  	os.Remove(f.Name())
    46  
    47  	s.success = true
    48  	return multistep.ActionContinue
    49  }
    50  
    51  func (s *StepOutputDir) Cleanup(state multistep.StateBag) {
    52  	_, cancelled := state.GetOk(multistep.StateCancelled)
    53  	_, halted := state.GetOk(multistep.StateHalted)
    54  
    55  	if !s.success {
    56  		return
    57  	}
    58  
    59  	if cancelled || halted {
    60  		ui := state.Get("ui").(packer.Ui)
    61  
    62  		ui.Say("Deleting output directory...")
    63  		for i := 0; i < 5; i++ {
    64  			err := os.RemoveAll(s.Path)
    65  			if err == nil {
    66  				break
    67  			}
    68  
    69  			log.Printf("Error removing output dir: %s", err)
    70  			time.Sleep(2 * time.Second)
    71  		}
    72  	}
    73  }