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