From 0a2f2957ec90064ebbd100b2392e47533188ce87 Mon Sep 17 00:00:00 2001 From: poy Date: Sun, 8 Dec 2019 00:29:25 -0700 Subject: [PATCH] when copying, skip files with the same name When using the COPY command, if the source and destination have the same the file should be skipped rather than copied. This is to prevent the file from being overwritten and therefore producing an empty file. fixes #904 --- pkg/util/fs_util.go | 6 ++++++ pkg/util/fs_util_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/pkg/util/fs_util.go b/pkg/util/fs_util.go index 10fccb7f7b..77376228e4 100644 --- a/pkg/util/fs_util.go +++ b/pkg/util/fs_util.go @@ -551,6 +551,12 @@ func CopyFile(src, dest, buildcontext string) (bool, error) { logrus.Debugf("%s found in .dockerignore, ignoring", src) return true, nil } + if src == dest { + // This is a no-op. Move on, but don't list it as ignored. + // We have to make sure we do this so we don't overwrite our own file. + // See iusse #904 for an example. + return false, nil + } fi, err := os.Stat(src) if err != nil { return false, err diff --git a/pkg/util/fs_util_test.go b/pkg/util/fs_util_test.go index 5a1f008f47..2a4b31c6fd 100644 --- a/pkg/util/fs_util_test.go +++ b/pkg/util/fs_util_test.go @@ -825,3 +825,41 @@ func Test_correctDockerignoreFileIsUsed(t *testing.T) { } } } + +func Test_CopyFile_skips_self(t *testing.T) { + t.Parallel() + tempDir, err := ioutil.TempDir("", "kaniko_test") + if err != nil { + t.Fatal(err) + } + + tempFile := filepath.Join(tempDir, "foo") + expected := "bar" + + if err := ioutil.WriteFile( + tempFile, + []byte(expected), + 0755, + ); err != nil { + t.Fatal(err) + } + + ignored, err := CopyFile(tempFile, tempFile, "") + if err != nil { + t.Fatal(err) + } + + if ignored { + t.Fatal("expected file to NOT be ignored") + } + + // Ensure file has expected contents + actualData, err := ioutil.ReadFile(tempFile) + if err != nil { + t.Fatal(err) + } + + if actual := string(actualData); actual != expected { + t.Fatalf("expected file contents to be %q, but got %q", expected, actual) + } +}