github.phpd.cn/hashicorp/packer@v1.3.2/builder/vmware/common/step_output_dir.go (about) 1 package common 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "time" 8 9 "github.com/hashicorp/packer/helper/multistep" 10 "github.com/hashicorp/packer/packer" 11 ) 12 13 // StepOutputDir sets up the output directory by creating it if it does 14 // not exist, deleting it if it does exist and we're forcing, and cleaning 15 // it up when we're done with it. 16 type StepOutputDir struct { 17 Force bool 18 19 success bool 20 } 21 22 func (s *StepOutputDir) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { 23 dir := state.Get("dir").(OutputDir) 24 ui := state.Get("ui").(packer.Ui) 25 26 exists, err := dir.DirExists() 27 if err != nil { 28 state.Put("error", err) 29 return multistep.ActionHalt 30 } 31 32 if exists { 33 if s.Force { 34 ui.Say("Deleting previous output directory...") 35 dir.RemoveAll() 36 } else { 37 state.Put("error", fmt.Errorf( 38 "Output directory '%s' already exists.", dir.String())) 39 return multistep.ActionHalt 40 } 41 } 42 43 if err := dir.MkdirAll(); err != nil { 44 state.Put("error", err) 45 return multistep.ActionHalt 46 } 47 48 s.success = true 49 return multistep.ActionContinue 50 } 51 52 func (s *StepOutputDir) Cleanup(state multistep.StateBag) { 53 if !s.success { 54 return 55 } 56 57 _, cancelled := state.GetOk(multistep.StateCancelled) 58 _, halted := state.GetOk(multistep.StateHalted) 59 60 if cancelled || halted { 61 dir := state.Get("dir").(OutputDir) 62 ui := state.Get("ui").(packer.Ui) 63 64 exists, _ := dir.DirExists() 65 if exists { 66 ui.Say("Deleting output directory...") 67 for i := 0; i < 5; i++ { 68 err := dir.RemoveAll() 69 if err == nil { 70 break 71 } 72 73 log.Printf("Error removing output dir: %s", err) 74 time.Sleep(2 * time.Second) 75 } 76 } 77 } 78 }