github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/builder/hyperv/common/step_create_tempdir.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  type StepCreateTempDir struct {
    14  	// The user-supplied root directories into which we create subdirectories.
    15  	TempPath    string
    16  	VhdTempPath string
    17  	// The subdirectories with the randomly generated name.
    18  	dirPath    string
    19  	vhdDirPath string
    20  }
    21  
    22  func (s *StepCreateTempDir) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    23  	ui := state.Get("ui").(packer.Ui)
    24  
    25  	ui.Say("Creating temporary directory...")
    26  
    27  	if s.TempPath == "" {
    28  		s.TempPath = os.TempDir()
    29  	}
    30  
    31  	packerTempDir, err := ioutil.TempDir(s.TempPath, "packerhv")
    32  	if err != nil {
    33  		err := fmt.Errorf("Error creating temporary directory: %s", err)
    34  		state.Put("error", err)
    35  		ui.Error(err.Error())
    36  		return multistep.ActionHalt
    37  	}
    38  
    39  	s.dirPath = packerTempDir
    40  	state.Put("packerTempDir", packerTempDir)
    41  
    42  	if s.VhdTempPath == "" {
    43  		// Fall back to regular temp dir if no separate VHD temp dir set.
    44  		state.Put("packerVhdTempDir", packerTempDir)
    45  	} else {
    46  		packerVhdTempDir, err := ioutil.TempDir(s.VhdTempPath, "packerhv-vhd")
    47  		if err != nil {
    48  			err := fmt.Errorf("Error creating temporary VHD directory: %s", err)
    49  			state.Put("error", err)
    50  			ui.Error(err.Error())
    51  			return multistep.ActionHalt
    52  		}
    53  
    54  		s.vhdDirPath = packerVhdTempDir
    55  		state.Put("packerVhdTempDir", packerVhdTempDir)
    56  	}
    57  
    58  	//	ui.Say("packerTempDir = '" + packerTempDir + "'")
    59  
    60  	return multistep.ActionContinue
    61  }
    62  
    63  func (s *StepCreateTempDir) Cleanup(state multistep.StateBag) {
    64  	ui := state.Get("ui").(packer.Ui)
    65  
    66  	if s.dirPath != "" {
    67  		ui.Say("Deleting temporary directory...")
    68  
    69  		err := os.RemoveAll(s.dirPath)
    70  
    71  		if err != nil {
    72  			ui.Error(fmt.Sprintf("Error deleting temporary directory: %s", err))
    73  		}
    74  	}
    75  
    76  	if s.vhdDirPath != "" && s.dirPath != s.vhdDirPath {
    77  		ui.Say("Deleting temporary VHD directory...")
    78  
    79  		err := os.RemoveAll(s.vhdDirPath)
    80  
    81  		if err != nil {
    82  			ui.Error(fmt.Sprintf("Error deleting temporary VHD directory: %s", err))
    83  		}
    84  	}
    85  }