Skip to content

Commit

Permalink
fileutils: make (Le|E)xists return os.PathError
Browse files Browse the repository at this point in the history
wrap the returned error in a os.PathError so the error includes the
file path.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>
  • Loading branch information
giuseppe committed Apr 10, 2024
1 parent 90967d7 commit 543bba0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
7 changes: 7 additions & 0 deletions pkg/fileutils/exists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ func TestExist(t *testing.T) {
if err1 == nil {
return
}

var pathErr1 *os.PathError
var pathErr2 *os.PathError
assert.ErrorAs(t, err1, &pathErr1, "wrong error type")
assert.ErrorAs(t, err2, &pathErr2, "wrong error type")
assert.Equal(t, pathErr1.Path, pathErr1.Path, "different file path")

// on Linux validates that the syscall error is the same
if runtime.GOOS == "linux" {
var syscallErr1 syscall.Errno
Expand Down
14 changes: 12 additions & 2 deletions pkg/fileutils/exists_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package fileutils

import (
"os"

"golang.org/x/sys/unix"
)

Expand All @@ -12,13 +14,21 @@ import (
func Exists(path string) error {
// It uses unix.Faccessat which is a faster operation compared to os.Stat for
// simply checking the existence of a file.
return unix.Faccessat(unix.AT_FDCWD, path, unix.F_OK, 0)
err := unix.Faccessat(unix.AT_FDCWD, path, unix.F_OK, 0)
if err != nil {
return &os.PathError{Op: "faccessat", Path: path, Err: err}
}
return nil
}

// Lexists checks whether a file or directory exists at the given path.
// If the path is a symlink, the symlink itself is checked.
func Lexists(path string) error {
// It uses unix.Faccessat which is a faster operation compared to os.Stat for
// simply checking the existence of a file.
return unix.Faccessat(unix.AT_FDCWD, path, unix.F_OK, unix.AT_SYMLINK_NOFOLLOW)
err := unix.Faccessat(unix.AT_FDCWD, path, unix.F_OK, unix.AT_SYMLINK_NOFOLLOW)
if err != nil {
return &os.PathError{Op: "faccessat", Path: path, Err: err}
}
return nil
}

0 comments on commit 543bba0

Please sign in to comment.