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