2014-04-06 13:21:22 -04:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2018-01-22 18:32:33 -05:00
|
|
|
"context"
|
2014-04-06 13:21:22 -04:00
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
|
2020-11-17 19:31:03 -05:00
|
|
|
"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
|
2020-11-19 14:54:31 -05:00
|
|
|
packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
|
2014-04-06 13:21:22 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
// StepOutputDir sets up the output directory by creating it if it does
|
|
|
|
// not exist, deleting it if it does exist and we're forcing, and cleaning
|
|
|
|
// it up when we're done with it.
|
|
|
|
type StepOutputDir struct {
|
|
|
|
Force bool
|
|
|
|
Path string
|
|
|
|
success bool
|
|
|
|
}
|
|
|
|
|
2016-12-16 14:51:55 -05:00
|
|
|
// Run sets up the output directory.
|
2019-03-29 11:50:02 -04:00
|
|
|
func (s *StepOutputDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
|
2020-11-19 14:54:31 -05:00
|
|
|
ui := state.Get("ui").(packersdk.Ui)
|
2014-04-06 13:21:22 -04:00
|
|
|
|
|
|
|
if _, err := os.Stat(s.Path); err == nil && s.Force {
|
|
|
|
ui.Say("Deleting previous output directory...")
|
|
|
|
os.RemoveAll(s.Path)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the directory
|
|
|
|
if err := os.MkdirAll(s.Path, 0755); err != nil {
|
|
|
|
state.Put("error", err)
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
|
|
|
|
// Make sure we can write in the directory
|
|
|
|
f, err := os.Create(filepath.Join(s.Path, "_packer_perm_check"))
|
|
|
|
if err != nil {
|
|
|
|
err = fmt.Errorf("Couldn't write to output directory: %s", err)
|
|
|
|
state.Put("error", err)
|
|
|
|
return multistep.ActionHalt
|
|
|
|
}
|
|
|
|
f.Close()
|
|
|
|
os.Remove(f.Name())
|
|
|
|
|
|
|
|
s.success = true
|
|
|
|
return multistep.ActionContinue
|
|
|
|
}
|
|
|
|
|
2016-12-16 14:51:55 -05:00
|
|
|
// Cleanup deletes the output directory.
|
2014-04-06 13:21:22 -04:00
|
|
|
func (s *StepOutputDir) Cleanup(state multistep.StateBag) {
|
|
|
|
_, cancelled := state.GetOk(multistep.StateCancelled)
|
|
|
|
_, halted := state.GetOk(multistep.StateHalted)
|
|
|
|
|
|
|
|
if !s.success {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if cancelled || halted {
|
2020-11-19 14:54:31 -05:00
|
|
|
ui := state.Get("ui").(packersdk.Ui)
|
2014-04-06 13:21:22 -04:00
|
|
|
|
|
|
|
ui.Say("Deleting output directory...")
|
|
|
|
for i := 0; i < 5; i++ {
|
|
|
|
err := os.RemoveAll(s.Path)
|
|
|
|
if err == nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Printf("Error removing output dir: %s", err)
|
|
|
|
time.Sleep(2 * time.Second)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|