From 26dc680a5caacac796a2b32dc97cb6888ce97034 Mon Sep 17 00:00:00 2001
From: Rafael Rivera <rafael@withinwindows.com>
Date: Tue, 8 Jan 2019 19:03:36 -0800
Subject: [PATCH] Remove characters from cache path that are invalid on Windows

---
 cmd/diff_test.go        | 1 +
 cmd/root.go             | 2 +-
 pkg/util/fs_utils.go    | 8 ++++++++
 pkg/util/image_utils.go | 3 +--
 4 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/cmd/diff_test.go b/cmd/diff_test.go
index 144ceb23..6387c310 100644
--- a/cmd/diff_test.go
+++ b/cmd/diff_test.go
@@ -44,6 +44,7 @@ var imageDiffs = []imageDiff{
 	{"", "", true},
 	{"gcr.io/google-appengine/python", "gcr.io/google-appengine/debian9", false},
 	{"gcr.io/google-appengine/python", "cats", true},
+	{"mcr.microsoft.com/mcr/hello-world:latest", "mcr.microsoft.com/mcr/hello-world:latest", false},
 }
 
 func TestDiffImages(t *testing.T) {
diff --git a/cmd/root.go b/cmd/root.go
index 93696809..7a627ac1 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -168,7 +168,7 @@ func getCacheDir(imageName string) (string, error) {
 	}
 	rootDir := filepath.Join(cacheDir, ".container-diff", "cache")
 	imageName = strings.Replace(imageName, string(os.PathSeparator), "", -1)
-	return filepath.Join(rootDir, filepath.Clean(imageName)), nil
+	return filepath.Join(rootDir, pkgutil.CleanFilePath(imageName)), nil
 }
 
 func getWriter(outputFile string) (io.Writer, error) {
diff --git a/pkg/util/fs_utils.go b/pkg/util/fs_utils.go
index 9ae105d4..3f8c5db7 100644
--- a/pkg/util/fs_utils.go
+++ b/pkg/util/fs_utils.go
@@ -207,3 +207,11 @@ func DirIsEmpty(path string) (bool, error) {
 	}
 	return false, err
 }
+
+// CleanFilePath removes characters from a given path that cannot be used
+// in paths by the underlying platform (e.g. Windows)
+func CleanFilePath(dirtyPath string) string {
+	var windowsReplacements = []string{"<", "_", ">", "_", ":", "_", "?", "_", "*", "_", "?", "_", "|", "_"}
+	replacer := strings.NewReplacer(windowsReplacements...)
+	return filepath.Clean(replacer.Replace(dirtyPath))
+}
diff --git a/pkg/util/image_utils.go b/pkg/util/image_utils.go
index 405b6021..c3b38676 100644
--- a/pkg/util/image_utils.go
+++ b/pkg/util/image_utils.go
@@ -161,8 +161,7 @@ func GetImage(imageName string, includeLayers bool, cacheDir string) (Image, err
 	if err != nil {
 		return Image{}, err
 	}
-	dirName := strings.Replace(RemoveTag(imageName)+"@"+imageDigest.String(), ":", "", -1)
-	path, err := getExtractPathForName(dirName, cacheDir)
+	path, err := getExtractPathForName(RemoveTag(imageName)+"@"+imageDigest.String(), cacheDir)
 	if err != nil {
 		return Image{}, err
 	}