Skip to content

Commit ef08475

Browse files
committed
cli/command/container: ignore "not found" error on cidfile.Close
Ignore errors when trying to remove a CID-file that no longer exists; also remove the path from the custom error as os.Remove already returns a os.PathError, which includes the path. Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
1 parent 16bbf5d commit ef08475

2 files changed

Lines changed: 26 additions & 11 deletions

File tree

cli/command/container/create.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,8 @@ func (cid *cidFile) Close() error {
177177
if cid.written {
178178
return nil
179179
}
180-
if err := os.Remove(cid.path); err != nil {
181-
return fmt.Errorf("failed to remove the CID file '%s': %w", cid.path, err)
180+
if err := os.Remove(cid.path); err != nil && !errors.Is(err, os.ErrNotExist) {
181+
return fmt.Errorf("failed to remove the CID file: %w", err)
182182
}
183183

184184
return nil

cli/command/container/create_test.go

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"io"
77
"os"
8+
"path/filepath"
89
"runtime"
910
"sort"
1011
"strings"
@@ -42,17 +43,31 @@ func TestNewCIDFileWhenFileAlreadyExists(t *testing.T) {
4243
}
4344

4445
func TestCIDFileCloseWithNoWrite(t *testing.T) {
45-
tempdir := fs.NewDir(t, "test-cid-file")
46-
defer tempdir.Remove()
46+
// Closing should remove the file if it was not written to.
47+
t.Run("closing should remove file", func(t *testing.T) {
48+
filename := filepath.Join(t.TempDir(), "cidfile-1")
49+
file, err := newCIDFile(filename)
50+
assert.NilError(t, err)
51+
assert.Check(t, is.Equal(file.path, filename))
4752

48-
path := tempdir.Join("cidfile")
49-
file, err := newCIDFile(path)
50-
assert.NilError(t, err)
51-
assert.Check(t, is.Equal(file.path, path))
53+
assert.NilError(t, file.Close())
54+
_, err = os.Stat(filename)
55+
assert.Check(t, os.IsNotExist(err))
56+
})
5257

53-
assert.NilError(t, file.Close())
54-
_, err = os.Stat(path)
55-
assert.Check(t, os.IsNotExist(err))
58+
// Closing (and removing) the file should not produce an error if the file no longer exists.
59+
t.Run("close should remove file", func(t *testing.T) {
60+
filename := filepath.Join(t.TempDir(), "cidfile-2")
61+
file, err := newCIDFile(filename)
62+
assert.NilError(t, err)
63+
assert.Check(t, is.Equal(file.path, filename))
64+
65+
assert.NilError(t, os.Remove(filename))
66+
_, err = os.Stat(filename)
67+
assert.Check(t, os.IsNotExist(err))
68+
69+
assert.NilError(t, file.Close())
70+
})
5671
}
5772

5873
func TestCIDFileCloseWithWrite(t *testing.T) {

0 commit comments

Comments
 (0)