github.phpd.cn/hashicorp/packer@v1.3.2/builder/hyperv/common/step_create_build_dir.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"log"
     8  	"os"
     9  
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  type StepCreateBuildDir struct {
    15  	// User supplied directory under which we create the main build
    16  	// directory. The build directory is used to house the VM files and
    17  	// folders during the build. If unspecified the default temp directory
    18  	// for the OS is used
    19  	TempPath string
    20  	// The full path to the build directory. This is the concatenation of
    21  	// TempPath plus a directory uniquely named for the build
    22  	buildDir string
    23  }
    24  
    25  // Creates the main directory used to house the VMs files and folders
    26  // during the build
    27  func (s *StepCreateBuildDir) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    28  	ui := state.Get("ui").(packer.Ui)
    29  
    30  	ui.Say("Creating build directory...")
    31  
    32  	if s.TempPath == "" {
    33  		s.TempPath = os.TempDir()
    34  	}
    35  
    36  	var err error
    37  	s.buildDir, err = ioutil.TempDir(s.TempPath, "packerhv")
    38  	if err != nil {
    39  		err = fmt.Errorf("Error creating build directory: %s", err)
    40  		state.Put("error", err)
    41  		ui.Error(err.Error())
    42  		return multistep.ActionHalt
    43  	}
    44  
    45  	log.Printf("Created build directory: %s", s.buildDir)
    46  
    47  	// Record the build directory location for later steps
    48  	state.Put("build_dir", s.buildDir)
    49  
    50  	return multistep.ActionContinue
    51  }
    52  
    53  // Cleanup removes the build directory
    54  func (s *StepCreateBuildDir) Cleanup(state multistep.StateBag) {
    55  	if s.buildDir == "" {
    56  		return
    57  	}
    58  
    59  	ui := state.Get("ui").(packer.Ui)
    60  	ui.Say("Deleting build directory...")
    61  
    62  	err := os.RemoveAll(s.buildDir)
    63  	if err != nil {
    64  		ui.Error(fmt.Sprintf("Error deleting build directory: %s", err))
    65  	}
    66  }