Skip to content

Commit ce43956

Browse files
committed
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 <[email protected]>
1 parent b3c9653 commit ce43956

File tree

2 files changed

+42
-5
lines changed

2 files changed

+42
-5
lines changed

solver/llbsolver/file/backend.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -161,14 +161,15 @@ func rmPath(root, src string, allowNotFound bool) error {
161161
}
162162
p := filepath.Join(dir, base)
163163

164-
if err := os.RemoveAll(p); err != nil {
165-
if errors.Is(err, os.ErrNotExist) && allowNotFound {
166-
return nil
164+
if !allowNotFound {
165+
_, err := os.Stat(p)
166+
167+
if errors.Is(err, os.ErrNotExist) {
168+
return err
167169
}
168-
return err
169170
}
170171

171-
return nil
172+
return os.RemoveAll(p)
172173
}
173174

174175
func docopy(ctx context.Context, src, dest string, action pb.FileActionCopy, u *copy.User, idmap *idtools.IdentityMapping) error {

solver/llbsolver/file/backend_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package file
2+
3+
import (
4+
"os"
5+
"path/filepath"
6+
"testing"
7+
8+
"github.com/stretchr/testify/require"
9+
)
10+
11+
func TestRmPathNonExistentFileAllowNotFoundFalse(t *testing.T) {
12+
root := t.TempDir()
13+
err := rmPath(root, "doesnt_exist", false)
14+
require.Error(t, err)
15+
require.True(t, os.IsNotExist(err))
16+
}
17+
18+
func TestRmPathNonExistentFileAllowNotFoundTrue(t *testing.T) {
19+
root := t.TempDir()
20+
require.NoError(t, rmPath(root, "doesnt_exist", true))
21+
}
22+
23+
func TestRmPathFileExists(t *testing.T) {
24+
root := t.TempDir()
25+
26+
src := filepath.Join(root, "exists")
27+
file, err := os.Create(src)
28+
require.NoError(t, err)
29+
file.Close()
30+
31+
require.NoError(t, rmPath(root, "exists", false))
32+
33+
_, err = os.Stat(src)
34+
35+
require.True(t, os.IsNotExist(err))
36+
}

0 commit comments

Comments
 (0)