github.com/sneal/packer@v0.5.2/builder/vmware/common/step_clean_files.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/multistep"
     6  	"github.com/mitchellh/packer/packer"
     7  	"os"
     8  	"path/filepath"
     9  )
    10  
    11  // These are the extensions of files that are important for the function
    12  // of a VMware virtual machine. Any other file is discarded as part of the
    13  // build.
    14  var KeepFileExtensions = []string{".nvram", ".vmdk", ".vmsd", ".vmx", ".vmxf"}
    15  
    16  // This step removes unnecessary files from the final result.
    17  //
    18  // Uses:
    19  //   dir    OutputDir
    20  //   ui     packer.Ui
    21  //
    22  // Produces:
    23  //   <nothing>
    24  type StepCleanFiles struct{}
    25  
    26  func (StepCleanFiles) Run(state multistep.StateBag) multistep.StepAction {
    27  	dir := state.Get("dir").(OutputDir)
    28  	ui := state.Get("ui").(packer.Ui)
    29  
    30  	ui.Say("Deleting unnecessary VMware files...")
    31  	files, err := dir.ListFiles()
    32  	if err != nil {
    33  		state.Put("error", err)
    34  		return multistep.ActionHalt
    35  	}
    36  
    37  	for _, path := range files {
    38  		// If the file isn't critical to the function of the
    39  		// virtual machine, we get rid of it.
    40  		keep := false
    41  		ext := filepath.Ext(path)
    42  		for _, goodExt := range KeepFileExtensions {
    43  			if goodExt == ext {
    44  				keep = true
    45  				break
    46  			}
    47  		}
    48  
    49  		if !keep {
    50  			ui.Message(fmt.Sprintf("Deleting: %s", path))
    51  			if err = dir.Remove(path); err != nil {
    52  				// Only report the error if the file still exists. We do this
    53  				// because sometimes the files naturally get removed on their
    54  				// own as VMware does its own cleanup.
    55  				if _, serr := os.Stat(path); serr == nil || !os.IsNotExist(serr) {
    56  					state.Put("error", err)
    57  					return multistep.ActionHalt
    58  				}
    59  			}
    60  		}
    61  	}
    62  
    63  	return multistep.ActionContinue
    64  }
    65  
    66  func (StepCleanFiles) Cleanup(multistep.StateBag) {}