github.phpd.cn/hashicorp/packer@v1.3.2/builder/lxc/step_prepare_output_dir.go (about)

     1  package lxc
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"os"
     7  	"time"
     8  
     9  	"github.com/hashicorp/packer/helper/multistep"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  type stepPrepareOutputDir struct{}
    14  
    15  func (stepPrepareOutputDir) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    16  	config := state.Get("config").(*Config)
    17  	ui := state.Get("ui").(packer.Ui)
    18  
    19  	if _, err := os.Stat(config.OutputDir); err == nil && config.PackerForce {
    20  		ui.Say("Deleting previous output directory...")
    21  		os.RemoveAll(config.OutputDir)
    22  	}
    23  
    24  	if err := os.MkdirAll(config.OutputDir, 0755); err != nil {
    25  		state.Put("error", err)
    26  		return multistep.ActionHalt
    27  	}
    28  
    29  	return multistep.ActionContinue
    30  }
    31  
    32  func (stepPrepareOutputDir) Cleanup(state multistep.StateBag) {
    33  	_, cancelled := state.GetOk(multistep.StateCancelled)
    34  	_, halted := state.GetOk(multistep.StateHalted)
    35  
    36  	if cancelled || halted {
    37  		config := state.Get("config").(*Config)
    38  		ui := state.Get("ui").(packer.Ui)
    39  
    40  		ui.Say("Deleting output directory...")
    41  		for i := 0; i < 5; i++ {
    42  			err := os.RemoveAll(config.OutputDir)
    43  			if err == nil {
    44  				break
    45  			}
    46  
    47  			log.Printf("Error removing output dir: %s", err)
    48  			time.Sleep(2 * time.Second)
    49  		}
    50  	}
    51  }