file: Fix incorrect handling of non-existent files in llbsolver's rmPath

The os.RemoveAll() call returns nil if the path doesn't exist. When the
rmPath function is called with allowNotFound set to false, it doesn't change the
behaviour of the function.

Change the code so if allowNotFound is set to false, we first check
whether the file exists. If it doesn't exist, return an error.

Add tests for three relevant cases.

Signed-off-by: Jakub Ciolek <jakub@ciolek.dev>
This commit is contained in:
Jakub Ciolek
2023-07-23 15:18:37 +02:00
parent b3c9653655
commit ce439567a4
2 changed files with 42 additions and 5 deletions

View File

@@ -161,14 +161,15 @@ func rmPath(root, src string, allowNotFound bool) error {
}
p := filepath.Join(dir, base)
if err := os.RemoveAll(p); err != nil {
if errors.Is(err, os.ErrNotExist) && allowNotFound {
return nil
if !allowNotFound {
_, err := os.Stat(p)
if errors.Is(err, os.ErrNotExist) {
return err
}
return err
}
return nil
return os.RemoveAll(p)
}
func docopy(ctx context.Context, src, dest string, action pb.FileActionCopy, u *copy.User, idmap *idtools.IdentityMapping) error {

View File

@@ -0,0 +1,36 @@
package file
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestRmPathNonExistentFileAllowNotFoundFalse(t *testing.T) {
root := t.TempDir()
err := rmPath(root, "doesnt_exist", false)
require.Error(t, err)
require.True(t, os.IsNotExist(err))
}
func TestRmPathNonExistentFileAllowNotFoundTrue(t *testing.T) {
root := t.TempDir()
require.NoError(t, rmPath(root, "doesnt_exist", true))
}
func TestRmPathFileExists(t *testing.T) {
root := t.TempDir()
src := filepath.Join(root, "exists")
file, err := os.Create(src)
require.NoError(t, err)
file.Close()
require.NoError(t, rmPath(root, "exists", false))
_, err = os.Stat(src)
require.True(t, os.IsNotExist(err))
}