Merge pull request #7102 from hashicorp/pr/6950

Add tmp package that offers Dir & File funcs
This commit is contained in:
Megan Marsh 2019-01-09 12:21:34 -08:00 committed by GitHub
commit 14aa2afbb1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 132 additions and 142 deletions

View File

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@ -14,6 +13,7 @@ import (
"syscall" "syscall"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
// Communicator is a special communicator that works by executing // Communicator is a special communicator that works by executing
@ -67,7 +67,7 @@ func (c *Communicator) Start(cmd *packer.RemoteCmd) error {
func (c *Communicator) Upload(dst string, r io.Reader, fi *os.FileInfo) error { func (c *Communicator) Upload(dst string, r io.Reader, fi *os.FileInfo) error {
dst = filepath.Join(c.Chroot, dst) dst = filepath.Join(c.Chroot, dst)
log.Printf("Uploading to chroot dir: %s", dst) log.Printf("Uploading to chroot dir: %s", dst)
tf, err := ioutil.TempFile("", "packer-amazon-chroot") tf, err := tmp.File("packer-amazon-chroot")
if err != nil { if err != nil {
return fmt.Errorf("Error preparing shell script: %s", err) return fmt.Errorf("Error preparing shell script: %s", err)
} }

View File

@ -3,11 +3,11 @@ package docker
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
// StepTempDir creates a temporary directory that we use in order to // StepTempDir creates a temporary directory that we use in order to
@ -21,13 +21,7 @@ func (s *StepTempDir) Run(_ context.Context, state multistep.StateBag) multistep
ui.Say("Creating a temporary directory for sharing data...") ui.Say("Creating a temporary directory for sharing data...")
var err error tempdir, err := tmp.Dir("packer-docker")
var tempdir string
configTmpDir, err := packer.ConfigTmpDir()
if err == nil {
tempdir, err = ioutil.TempDir(configTmpDir, "packer-docker")
}
if err != nil { if err != nil {
err := fmt.Errorf("Error making temp dir: %s", err) err := fmt.Errorf("Error making temp dir: %s", err)
state.Put("error", err) state.Put("error", err)

View File

@ -3,11 +3,9 @@ package docker
import ( import (
"context" "context"
"os" "os"
"path/filepath"
"testing" "testing"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
) )
func TestStepTempDir_impl(t *testing.T) { func TestStepTempDir_impl(t *testing.T) {
@ -52,46 +50,3 @@ func testStepTempDir_impl(t *testing.T) string {
func TestStepTempDir(t *testing.T) { func TestStepTempDir(t *testing.T) {
testStepTempDir_impl(t) testStepTempDir_impl(t)
} }
func TestStepTempDir_notmpdir(t *testing.T) {
tempenv := "PACKER_TMP_DIR"
oldenv := os.Getenv(tempenv)
defer os.Setenv(tempenv, oldenv)
os.Setenv(tempenv, "")
dir1 := testStepTempDir_impl(t)
cd, err := packer.ConfigDir()
if err != nil {
t.Fatalf("bad ConfigDir")
}
td := filepath.Join(cd, "tmp")
os.Setenv(tempenv, td)
dir2 := testStepTempDir_impl(t)
if filepath.Dir(dir1) != filepath.Dir(dir2) {
t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2))
}
}
func TestStepTempDir_packertmpdir(t *testing.T) {
tempenv := "PACKER_TMP_DIR"
oldenv := os.Getenv(tempenv)
defer os.Setenv(tempenv, oldenv)
os.Setenv(tempenv, ".")
dir1 := testStepTempDir_impl(t)
abspath, err := filepath.Abs(".")
if err != nil {
t.Fatalf("bad absolute path")
}
dir2 := filepath.Join(abspath, "tmp")
if filepath.Dir(dir1) != filepath.Dir(dir2) {
t.Fatalf("temp base directories do not match: %s %s", filepath.Dir(dir1), filepath.Dir(dir2))
}
}

View File

@ -9,6 +9,7 @@ import (
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
type StepCreateBuildDir struct { type StepCreateBuildDir struct {
@ -29,12 +30,13 @@ func (s *StepCreateBuildDir) Run(_ context.Context, state multistep.StateBag) mu
ui.Say("Creating build directory...") ui.Say("Creating build directory...")
var err error
if s.TempPath == "" { if s.TempPath == "" {
s.TempPath = os.TempDir() s.buildDir, err = tmp.Dir("hyperv")
} else {
s.buildDir, err = ioutil.TempDir(s.TempPath, "hyperv")
} }
var err error
s.buildDir, err = ioutil.TempDir(s.TempPath, "packerhv")
if err != nil { if err != nil {
err = fmt.Errorf("Error creating build directory: %s", err) err = fmt.Errorf("Error creating build directory: %s", err)
state.Put("error", err) state.Put("error", err)

View File

@ -38,7 +38,7 @@ func TestStepCreateBuildDir_Defaults(t *testing.T) {
// This prevents the regexp interpreting backslashes as escape sequences // This prevents the regexp interpreting backslashes as escape sequences
stateBuildDir := filepath.ToSlash(v.(string)) stateBuildDir := filepath.ToSlash(v.(string))
expectedBuildDirRe := regexp.MustCompile( expectedBuildDirRe := regexp.MustCompile(
filepath.ToSlash(filepath.Join(os.TempDir(), "packerhv") + `[[:digit:]]{9}$`)) filepath.ToSlash(filepath.Join(os.TempDir(), "hyperv") + `[[:digit:]]{9}$`))
match := expectedBuildDirRe.MatchString(stateBuildDir) match := expectedBuildDirRe.MatchString(stateBuildDir)
if !match { if !match {
t.Fatalf("Got path that doesn't match expected format in 'build_dir': %s", stateBuildDir) t.Fatalf("Got path that doesn't match expected format in 'build_dir': %s", stateBuildDir)
@ -79,7 +79,7 @@ func TestStepCreateBuildDir_UserDefinedTempPath(t *testing.T) {
// This prevents the regexp interpreting backslashes as escape sequences // This prevents the regexp interpreting backslashes as escape sequences
stateBuildDir := filepath.ToSlash(v.(string)) stateBuildDir := filepath.ToSlash(v.(string))
expectedBuildDirRe := regexp.MustCompile( expectedBuildDirRe := regexp.MustCompile(
filepath.ToSlash(filepath.Join(step.TempPath, "packerhv") + `[[:digit:]]{9}$`)) filepath.ToSlash(filepath.Join(step.TempPath, "hyperv") + `[[:digit:]]{9}$`))
match := expectedBuildDirRe.MatchString(stateBuildDir) match := expectedBuildDirRe.MatchString(stateBuildDir)
if !match { if !match {
t.Fatalf("Got path that doesn't match expected format in 'build_dir': %s", stateBuildDir) t.Fatalf("Got path that doesn't match expected format in 'build_dir': %s", stateBuildDir)

View File

@ -4,13 +4,13 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
const ( const (
@ -93,7 +93,7 @@ func (s *StepMountFloppydrive) Cleanup(state multistep.StateBag) {
} }
func (s *StepMountFloppydrive) copyFloppy(path string) (string, error) { func (s *StepMountFloppydrive) copyFloppy(path string) (string, error) {
tempdir, err := ioutil.TempDir("", "packer") tempdir, err := tmp.Dir("hyperv")
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -5,12 +5,11 @@ package iso
import ( import (
"context" "context"
"fmt" "fmt"
"os"
"reflect" "reflect"
"strconv" "strconv"
"testing" "testing"
"os"
hypervcommon "github.com/hashicorp/packer/builder/hyperv/common" hypervcommon "github.com/hashicorp/packer/builder/hyperv/common"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"

View File

@ -12,6 +12,7 @@ import (
"syscall" "syscall"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
type LxcAttachCommunicator struct { type LxcAttachCommunicator struct {
@ -60,7 +61,7 @@ func (c *LxcAttachCommunicator) Start(cmd *packer.RemoteCmd) error {
func (c *LxcAttachCommunicator) Upload(dst string, r io.Reader, fi *os.FileInfo) error { func (c *LxcAttachCommunicator) Upload(dst string, r io.Reader, fi *os.FileInfo) error {
log.Printf("Uploading to rootfs: %s", dst) log.Printf("Uploading to rootfs: %s", dst)
tf, err := ioutil.TempFile("", "packer-lxc-attach") tf, err := tmp.File("packer-lxc-attach")
if err != nil { if err != nil {
return fmt.Errorf("Error uploading file to rootfs: %s", err) return fmt.Errorf("Error uploading file to rootfs: %s", err)
} }

View File

@ -13,6 +13,7 @@ import (
"github.com/hashicorp/packer/helper/communicator" "github.com/hashicorp/packer/helper/communicator"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
) )
@ -137,13 +138,13 @@ func berToDer(ber []byte, ui packer.Ui) []byte {
return ber return ber
} }
berKey, err := ioutil.TempFile("", "packer-ber-privatekey-") berKey, err := tmp.File("packer-ber-privatekey-")
defer os.Remove(berKey.Name()) defer os.Remove(berKey.Name())
if err != nil { if err != nil {
return ber return ber
} }
ioutil.WriteFile(berKey.Name(), ber, os.ModeAppend) ioutil.WriteFile(berKey.Name(), ber, os.ModeAppend)
derKey, err := ioutil.TempFile("", "packer-der-privatekey-") derKey, err := tmp.File("packer-der-privatekey-")
defer os.Remove(derKey.Name()) defer os.Remove(derKey.Name())
if err != nil { if err != nil {
return ber return ber

View File

@ -15,6 +15,7 @@ import (
"github.com/ChrisTrenkamp/goxpath" "github.com/ChrisTrenkamp/goxpath"
"github.com/ChrisTrenkamp/goxpath/tree/xmltree" "github.com/ChrisTrenkamp/goxpath/tree/xmltree"
"github.com/hashicorp/packer/packer/tmp"
) )
// Parallels9Driver is a base type for Parallels builders. // Parallels9Driver is a base type for Parallels builders.
@ -288,7 +289,7 @@ func (d *Parallels9Driver) SendKeyScanCodes(vmName string, codes ...string) erro
return nil return nil
} }
f, err := ioutil.TempFile("", "prltype") f, err := tmp.File("prltype")
if err != nil { if err != nil {
return err return err
} }

View File

@ -4,13 +4,13 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
// This step attaches the ISO to the virtual machine. // This step attaches the ISO to the virtual machine.
@ -106,7 +106,7 @@ func (s *StepAttachFloppy) Cleanup(state multistep.StateBag) {
} }
func (s *StepAttachFloppy) copyFloppy(path string) (string, error) { func (s *StepAttachFloppy) copyFloppy(path string) (string, error) {
tempdir, err := ioutil.TempDir("", "packer") tempdir, err := tmp.Dir("virtualbox")
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"strings" "strings"
@ -13,6 +12,7 @@ import (
"github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -153,7 +153,7 @@ func (s *StepDownloadGuestAdditions) downloadAdditionsSHA256(ctx context.Context
"https://download.virtualbox.org/virtualbox/%s/SHA256SUMS", "https://download.virtualbox.org/virtualbox/%s/SHA256SUMS",
additionsVersion) additionsVersion)
checksumsFile, err := ioutil.TempFile("", "packer") checksumsFile, err := tmp.File("packer")
if err != nil { if err != nil {
state.Put("error", fmt.Errorf( state.Put("error", fmt.Errorf(
"Failed creating temporary file to store guest addition checksums: %s", "Failed creating temporary file to store guest addition checksums: %s",

View File

@ -12,6 +12,7 @@ import (
vmwcommon "github.com/hashicorp/packer/builder/vmware/common" vmwcommon "github.com/hashicorp/packer/builder/vmware/common"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -410,7 +411,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
if config.RemoteType != "" { if config.RemoteType != "" {
// For remote builds, we just put the VMX in a temporary // For remote builds, we just put the VMX in a temporary
// directory since it just gets uploaded anyways. // directory since it just gets uploaded anyways.
vmxDir, err = ioutil.TempDir("", "packer-vmx") vmxDir, err = tmp.Dir("vmw-iso")
if err != nil { if err != nil {
err := fmt.Errorf("Error preparing VMX template: %s", err) err := fmt.Errorf("Error preparing VMX template: %s", err)
state.Put("error", err) state.Put("error", err)

View File

@ -47,6 +47,7 @@ func tmpnam(prefix string) string {
dir := os.TempDir() dir := os.TempDir()
max := int(math.Pow(2, float64(length))) max := int(math.Pow(2, float64(length)))
// FIXME use ioutil.TempFile() or at least mimic implementation, this could loop forever
n, err := rand.Intn(max), nil n, err := rand.Intn(max), nil
for path = filepath.Join(dir, prefix+strconv.Itoa(n)); err == nil; _, err = os.Stat(path) { for path = filepath.Join(dir, prefix+strconv.Itoa(n)); err == nil; _, err = os.Stat(path) {
n = rand.Intn(max) n = rand.Intn(max)

View File

@ -3,7 +3,6 @@ package vmx
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -12,6 +11,7 @@ import (
vmwcommon "github.com/hashicorp/packer/builder/vmware/common" vmwcommon "github.com/hashicorp/packer/builder/vmware/common"
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
// StepCloneVMX takes a VMX file and clones the VM into the output directory. // StepCloneVMX takes a VMX file and clones the VM into the output directory.
@ -50,7 +50,7 @@ func (s *StepCloneVMX) Run(_ context.Context, state multistep.StateBag) multiste
// * The disk compaction step needs the paths to all attached disks // * The disk compaction step needs the paths to all attached disks
if remoteDriver, ok := driver.(vmwcommon.RemoteDriver); ok { if remoteDriver, ok := driver.(vmwcommon.RemoteDriver); ok {
remoteVmxPath := vmxPath remoteVmxPath := vmxPath
tempDir, err := ioutil.TempDir("", "packer-vmx") tempDir, err := tmp.Dir("packer-vmx")
if err != nil { if err != nil {
return halt(err) return halt(err)
} }

View File

@ -4,12 +4,13 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
"github.com/hashicorp/packer/packer/tmp"
) )
const ( const (
@ -121,7 +122,7 @@ func (ps *PowerShellCmd) getPowerShellPath() (string, error) {
} }
func saveScript(fileContents string) (string, error) { func saveScript(fileContents string) (string, error) {
file, err := ioutil.TempFile(os.TempDir(), "ps") file, err := tmp.File("powershell")
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -3,7 +3,6 @@ package shell_local
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
"runtime" "runtime"
@ -13,6 +12,7 @@ import (
"github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common"
commonhelper "github.com/hashicorp/packer/helper/common" commonhelper "github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -107,7 +107,7 @@ func Run(ui packer.Ui, config *Config) (bool, error) {
} }
func createInlineScriptFile(config *Config) (string, error) { func createInlineScriptFile(config *Config) (string, error) {
tf, err := ioutil.TempFile("", "packer-shell") tf, err := tmp.File("packer-shell")
if err != nil { if err != nil {
return "", fmt.Errorf("Error preparing shell script: %s", err) return "", fmt.Errorf("Error preparing shell script: %s", err)
} }

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"path" "path"
@ -13,6 +12,7 @@ import (
"github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/mitchellh/go-fs" "github.com/mitchellh/go-fs"
"github.com/mitchellh/go-fs/fat" "github.com/mitchellh/go-fs/fat"
) )
@ -39,7 +39,7 @@ func (s *StepCreateFloppy) Run(_ context.Context, state multistep.StateBag) mult
ui.Say("Creating floppy disk...") ui.Say("Creating floppy disk...")
// Create a temporary file to be our floppy drive // Create a temporary file to be our floppy drive
floppyF, err := ioutil.TempFile("", "packer") floppyF, err := tmp.File("packer")
if err != nil { if err != nil {
state.Put("error", state.Put("error",
fmt.Errorf("Error creating temporary file for floppy: %s", err)) fmt.Errorf("Error creating temporary file for floppy: %s", err))

View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/pkg/sftp" "github.com/pkg/sftp"
"golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent" "golang.org/x/crypto/ssh/agent"
@ -793,7 +794,7 @@ func scpUploadFile(dst string, src io.Reader, w io.Writer, r *bufio.Reader, fi *
} else { } else {
// Create a temporary file where we can copy the contents of the src // Create a temporary file where we can copy the contents of the src
// so that we can determine the length, since SCP is length-prefixed. // so that we can determine the length, since SCP is length-prefixed.
tf, err := ioutil.TempFile("", "packer-upload") tf, err := tmp.File("packer-upload")
if err != nil { if err != nil {
return fmt.Errorf("Error creating temporary file for upload: %s", err) return fmt.Errorf("Error creating temporary file for upload: %s", err)
} }

View File

@ -1,12 +1,13 @@
package communicator package communicator
import ( import (
"io/ioutil"
"testing" "testing"
"github.com/hashicorp/packer/packer/tmp"
) )
func TestPEM(t *testing.T) string { func TestPEM(t *testing.T) string {
tf, err := ioutil.TempFile("", "packer") tf, err := tmp.File("packer")
if err != nil { if err != nil {
t.Fatalf("err: %s", err) t.Fatalf("err: %s", err)
} }

View File

@ -21,6 +21,7 @@ import (
"github.com/hashicorp/packer/command" "github.com/hashicorp/packer/command"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/plugin" "github.com/hashicorp/packer/packer/plugin"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/version" "github.com/hashicorp/packer/version"
"github.com/mitchellh/cli" "github.com/mitchellh/cli"
"github.com/mitchellh/panicwrap" "github.com/mitchellh/panicwrap"
@ -69,7 +70,7 @@ func realMain() int {
// We always send logs to a temporary file that we use in case // We always send logs to a temporary file that we use in case
// there is a panic. Otherwise, we delete it. // there is a panic. Otherwise, we delete it.
logTempFile, err := ioutil.TempFile("", "packer-log") logTempFile, err := tmp.File("packer-log")
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err) fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err)
return 1 return 1

View File

@ -5,6 +5,8 @@ import (
"os" "os"
"strings" "strings"
"testing" "testing"
"github.com/hashicorp/packer/packer/tmp"
) )
type TestCache struct{} type TestCache struct{}
@ -30,7 +32,7 @@ func TestFileCache_Implements(t *testing.T) {
} }
func TestFileCache(t *testing.T) { func TestFileCache(t *testing.T) {
cacheDir, err := ioutil.TempDir("", "packer") cacheDir, err := tmp.Dir("packer")
if err != nil { if err != nil {
t.Fatalf("error creating temporary dir: %s", err) t.Fatalf("error creating temporary dir: %s", err)
} }

View File

@ -21,29 +21,7 @@ func ConfigDir() (string, error) {
return configDir() return configDir()
} }
// ConfigTmpDir returns the configuration tmp directory for Packer
func ConfigTmpDir() (string, error) {
if tmpdir := os.Getenv("PACKER_TMP_DIR"); tmpdir != "" {
return filepath.Abs(tmpdir)
}
configdir, err := configDir()
if err != nil {
return "", err
}
td := filepath.Join(configdir, "tmp")
_, err = os.Stat(td)
if os.IsNotExist(err) {
if err = os.MkdirAll(td, 0755); err != nil {
return "", err
}
} else if err != nil {
return "", err
}
return td, nil
}
func homeDir() (string, error) { func homeDir() (string, error) {
// Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470 // Prefer $HOME over user.Current due to glibc bug: golang.org/issue/13470
if home := os.Getenv("HOME"); home != "" { if home := os.Getenv("HOME"); home != "" {
log.Printf("Detected home directory from env var: %s", home) log.Printf("Detected home directory from env var: %s", home)

View File

@ -10,7 +10,6 @@ package plugin
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"math/rand" "math/rand"
"net" "net"
@ -23,6 +22,7 @@ import (
"time" "time"
packrpc "github.com/hashicorp/packer/packer/rpc" packrpc "github.com/hashicorp/packer/packer/rpc"
"github.com/hashicorp/packer/packer/tmp"
) )
// This is a count of the number of interrupts the process has received. // This is a count of the number of interrupts the process has received.
@ -125,7 +125,7 @@ func serverListener_tcp(minPort, maxPort int64) (net.Listener, error) {
} }
func serverListener_unix() (net.Listener, error) { func serverListener_unix() (net.Listener, error) {
tf, err := ioutil.TempFile("", "packer-plugin") tf, err := tmp.File("packer-plugin")
if err != nil { if err != nil {
return nil, err return nil, err
} }

46
packer/tmp/tmp.go Normal file
View File

@ -0,0 +1,46 @@
// Package tmp provides temporary directory helpers.
//
// tmp stores temporary items in the system's
// temporary directory unless a corresponding
// environment variable is set ( see os.TempDir ).
//
// On Unix systems, it uses $TMPDIR if non-empty, else /tmp.
// On Windows, it uses GetTempPath, returning the first non-empty
// value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
// On Plan 9, it returns /tmp.
//
// The directory is neither guaranteed to exist nor have accessible
// permissions.
package tmp
import (
"io/ioutil"
"os"
)
var tmpDir = os.TempDir()
// Dir creates a new temporary directory in the system temporary
// directory with a name beginning with prefix and returns the path
// of the new directory.
// Multiple programs calling Dir simultaneously
// will not choose the same directory.
// It is the caller's responsibility
// to remove the file when no longer needed.
func Dir(prefix string) (string, error) {
return ioutil.TempDir(tmpDir, prefix)
}
// File creates a new temporary file in the system temporary
// directory, opens the file for reading and writing, and
// returns the resulting *os.File.
// The filename is generated by taking pattern and adding a random
// string to the end. If pattern includes a "*", the random string
// replaces the last "*".
// Multiple programs calling File simultaneously
// will not choose the same file. The caller can use f.Name()
// to find the pathname of the file. It is the caller's responsibility
// to remove the file when no longer needed.
func File(pattern string) (*os.File, error) {
return ioutil.TempFile(tmpDir, pattern)
}

View File

@ -14,6 +14,7 @@ import (
"github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
) )
@ -95,7 +96,7 @@ func (p *PostProcessor) PostProcessProvider(name string, provider Provider, ui p
} }
// Create a temporary directory for us to build the contents of the box in // Create a temporary directory for us to build the contents of the box in
dir, err := ioutil.TempDir("", "packer") dir, err := tmp.Dir("packer")
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }

View File

@ -1,11 +1,11 @@
package vagrant package vagrant
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/hashicorp/packer/packer/tmp"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -14,8 +14,10 @@ func TestVBoxProvider_impl(t *testing.T) {
} }
func TestDecomressOVA(t *testing.T) { func TestDecomressOVA(t *testing.T) {
td, err := ioutil.TempDir("", "pp-vagrant-virtualbox") td, err := tmp.Dir("pp-vagrant-virtualbox")
assert.NoError(t, err) assert.NoError(t, err)
defer os.RemoveAll(td)
fixture := "../../common/test-fixtures/decompress-tar/outside_parent.tar" fixture := "../../common/test-fixtures/decompress-tar/outside_parent.tar"
err = DecompressOva(td, fixture) err = DecompressOva(td, fixture)
assert.NoError(t, err) assert.NoError(t, err)
@ -23,5 +25,4 @@ func TestDecomressOVA(t *testing.T) {
assert.Error(t, err) assert.Error(t, err)
_, err = os.Stat(filepath.Join(td, "demo.poc")) _, err = os.Stat(filepath.Join(td, "demo.poc"))
assert.NoError(t, err) assert.NoError(t, err)
os.RemoveAll(td)
} }

View File

@ -2,7 +2,6 @@ package ansiblelocal
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -11,6 +10,7 @@ import (
"github.com/hashicorp/packer/common/uuid" "github.com/hashicorp/packer/common/uuid"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -212,7 +212,7 @@ func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
} }
if len(p.config.InventoryFile) == 0 { if len(p.config.InventoryFile) == 0 {
tf, err := ioutil.TempFile("", "packer-provisioner-ansible-local") tf, err := tmp.File("packer-provisioner-ansible-local")
if err != nil { if err != nil {
return fmt.Errorf("Error preparing inventory file: %s", err) return fmt.Errorf("Error preparing inventory file: %s", err)
} }

View File

@ -29,6 +29,7 @@ import (
commonhelper "github.com/hashicorp/packer/helper/common" commonhelper "github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -499,7 +500,7 @@ func newUserKey(pubKeyFile string) (*userKey, error) {
Headers: nil, Headers: nil,
Bytes: privateKeyDer, Bytes: privateKeyDer,
} }
tf, err := ioutil.TempFile("", "ansible-key") tf, err := tmp.File("ansible-key")
if err != nil { if err != nil {
return nil, errors.New("failed to create temp file for generated key") return nil, errors.New("failed to create temp file for generated key")
} }

View File

@ -6,7 +6,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -14,6 +13,7 @@ import (
"time" "time"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
) )
const ( const (
@ -43,7 +43,7 @@ func scpUploadSession(opts []byte, rest string, in io.Reader, out io.Writer, com
return errors.New("no scp target specified") return errors.New("no scp target specified")
} }
d, err := ioutil.TempDir("", "packer-ansible-upload") d, err := tmp.Dir("ansible-upload")
if err != nil { if err != nil {
fmt.Fprintf(out, scpEmptyError) fmt.Fprintf(out, scpEmptyError)
return err return err
@ -68,7 +68,7 @@ func scpDownloadSession(opts []byte, rest string, in io.Reader, out io.Writer, c
return errors.New("no scp source specified") return errors.New("no scp source specified")
} }
d, err := ioutil.TempDir("", "packer-ansible-download") d, err := tmp.Dir("ansible-download")
if err != nil { if err != nil {
fmt.Fprintf(out, scpEmptyError) fmt.Fprintf(out, scpEmptyError)
return err return err

View File

@ -6,7 +6,6 @@ import (
"bufio" "bufio"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
"sort" "sort"
@ -18,6 +17,7 @@ import (
commonhelper "github.com/hashicorp/packer/helper/common" commonhelper "github.com/hashicorp/packer/helper/common"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/provisioner" "github.com/hashicorp/packer/provisioner"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -232,7 +232,7 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
// Takes the inline scripts, concatenates them into a temporary file and // Takes the inline scripts, concatenates them into a temporary file and
// returns a string containing the location of said file. // returns a string containing the location of said file.
func extractScript(p *Provisioner) (string, error) { func extractScript(p *Provisioner) (string, error) {
temp, err := ioutil.TempFile(os.TempDir(), "packer-powershell-provisioner") temp, err := tmp.File("powershell-provisioner")
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -7,7 +7,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"math/rand" "math/rand"
"os" "os"
@ -18,6 +17,7 @@ import (
"github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
@ -216,7 +216,7 @@ func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
// If we have an inline script, then turn that into a temporary // If we have an inline script, then turn that into a temporary
// shell script and use that. // shell script and use that.
if p.config.Inline != nil { if p.config.Inline != nil {
tf, err := ioutil.TempFile("", "packer-shell") tf, err := tmp.File("packer-shell")
if err != nil { if err != nil {
return fmt.Errorf("Error preparing shell script: %s", err) return fmt.Errorf("Error preparing shell script: %s", err)
} }
@ -242,7 +242,7 @@ func (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {
} }
if p.config.UseEnvVarFile == true { if p.config.UseEnvVarFile == true {
tf, err := ioutil.TempFile("", "packer-shell-vars") tf, err := tmp.File("packer-shell-vars")
if err != nil { if err != nil {
return fmt.Errorf("Error preparing shell script: %s", err) return fmt.Errorf("Error preparing shell script: %s", err)
} }

View File

@ -6,7 +6,6 @@ import (
"bufio" "bufio"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
"sort" "sort"
@ -16,9 +15,11 @@ import (
"github.com/hashicorp/packer/common" "github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer"
"github.com/hashicorp/packer/packer/tmp"
"github.com/hashicorp/packer/template/interpolate" "github.com/hashicorp/packer/template/interpolate"
) )
//FIXME query remote host or use %SYSTEMROOT%, %TEMP% and more creative filename
const DefaultRemotePath = "c:/Windows/Temp/script.bat" const DefaultRemotePath = "c:/Windows/Temp/script.bat"
var retryableSleep = 2 * time.Second var retryableSleep = 2 * time.Second
@ -157,7 +158,7 @@ func (p *Provisioner) Prepare(raws ...interface{}) error {
// into a temporary file and returns a string containing the location // into a temporary file and returns a string containing the location
// of said file. // of said file.
func extractScript(p *Provisioner) (string, error) { func extractScript(p *Provisioner) (string, error) {
temp, err := ioutil.TempFile(os.TempDir(), "packer-windows-shell-provisioner") temp, err := tmp.File("windows-shell-provisioner")
if err != nil { if err != nil {
log.Printf("Unable to create temporary file for inline scripts: %s", err) log.Printf("Unable to create temporary file for inline scripts: %s", err)
return "", err return "", err

View File

@ -6,13 +6,13 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
"strings" "strings"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/hashicorp/packer/packer/tmp"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
) )
@ -328,7 +328,7 @@ func ParseFile(path string) (*Template, error) {
var err error var err error
if path == "-" { if path == "-" {
// Create a temp file for stdin in case of errors // Create a temp file for stdin in case of errors
f, err = ioutil.TempFile(os.TempDir(), "packer") f, err = tmp.File("parse")
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -185,8 +185,8 @@ You must specify (only) one of `commit`, `discard`, or `export_path`.
information see the [section on ECR](#amazon-ec2-container-registry). information see the [section on ECR](#amazon-ec2-container-registry).
- `exec_user` (string) - Username or UID (format: - `exec_user` (string) - Username or UID (format:
<name\|uid>\[:<group\|gid>\]) to run remote commands with. You <name\\\|uid>\[:<group\\\|gid>\]) to run remote commands with.
may need this if you get permission errors trying to run the `shell` or You may need this if you get permission errors trying to run the `shell` or
other provisioners. other provisioners.
- `login` (boolean) - Defaults to false. If true, the builder will login in - `login` (boolean) - Defaults to false. If true, the builder will login in
@ -380,8 +380,9 @@ portable provisioning scripts.
## Overriding the host directory ## Overriding the host directory
By default, Packer creates a temporary folder under your home directory, and By default, Packer creates a temporary folder under your system temporary
uses that to stage files for uploading into the container. If you would like to directory, and uses that to stage files for uploading into the container. If
change the path to this temporary folder, you can set the `PACKER_TMP_DIR` you would like to change the path to this temporary folder, you can set
environment variable. This can be useful, for example, if you have your home environment variable `TMPDIR` (Unix) / `TMP` `TEMP` `USERPROFILE` (Windows) .
directory permissions set up to disallow access from the docker daemon. This can be useful, for example, if you have your home directory permissions
set up to disallow access from the docker daemon.

View File

@ -42,9 +42,9 @@ each can be found below:
new versions of Packer. If you want to disable this for security or privacy new versions of Packer. If you want to disable this for security or privacy
reasons, you can set this environment variable to `1`. reasons, you can set this environment variable to `1`.
- `TMPDIR` (Unix) / `TMP` (Windows) - The location of the directory used for - `TMPDIR` (Unix) / `TMP` `TEMP` `USERPROFILE` (Windows) - The location of
temporary files (defaults to `/tmp` on Linux/Unix and the directory used for temporary files (defaults to `/tmp` on Linux/Unix
`%USERPROFILE%\AppData\Local\Temp` on Windows Vista and above). It might be and `%USERPROFILE%\AppData\Local\Temp` on Windows Vista and above). It
necessary to customize it when working with large files since `/tmp` is a might be necessary to customize it when working with large files since
memory-backed filesystem in some Linux distributions in which case `/tmp` is a memory-backed filesystem in some Linux distributions in which
`/var/tmp` might be preferred. case `/var/tmp` might be preferred.