packer/cache: Preserve any extension found on keys

This allows us to hand cache paths to any programs that may want to
interpret file extensions in order to behave differently. For
example, VirtualBox may want ISO images to end with .iso.
This commit is contained in:
Emil Sit 2013-07-20 00:19:05 -04:00
parent c5fe163352
commit 594476ec91
2 changed files with 20 additions and 5 deletions

View File

@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/hex"
"path/filepath"
"regexp"
"sync"
)
@ -14,6 +15,9 @@ type Cache interface {
// Packer guarantees that no other process will write to this file while
// the lock is held.
//
// If the key has an extension (e.g., file.ext), the resulting path
// will have that extension as well.
//
// The cache will block and wait for the lock.
Lock(string) string
@ -68,7 +72,13 @@ func (f *FileCache) RUnlock(key string) {
}
func (f *FileCache) cachePath(key string, hashKey string) string {
return filepath.Join(f.CacheDir, hashKey)
var suffixPattern = regexp.MustCompile(`(\.\w+)$`)
matches := suffixPattern.FindStringSubmatch(key)
suffix := ""
if matches != nil {
suffix = matches[0]
}
return filepath.Join(f.CacheDir, hashKey+suffix)
}
func (f *FileCache) hashKey(key string) string {

View File

@ -3,6 +3,7 @@ package packer
import (
"io/ioutil"
"os"
"strings"
"testing"
)
@ -36,19 +37,23 @@ func TestFileCache(t *testing.T) {
defer os.RemoveAll(cacheDir)
cache := &FileCache{CacheDir: cacheDir}
path := cache.Lock("foo")
path := cache.Lock("foo.iso")
if !strings.HasSuffix(path, ".iso") {
t.Fatalf("path doesn't end with suffix '%s': '%s'", ".iso", path)
}
err = ioutil.WriteFile(path, []byte("data"), 0666)
if err != nil {
t.Fatalf("error writing: %s", err)
}
cache.Unlock("foo")
cache.Unlock("foo.iso")
path, ok := cache.RLock("foo")
path, ok := cache.RLock("foo.iso")
if !ok {
t.Fatal("cache says key doesn't exist")
}
defer cache.RUnlock("foo")
defer cache.RUnlock("foo.iso")
data, err := ioutil.ReadFile(path)
if err != nil {