Skip to content

Commit

Permalink
Merge pull request #1883 from giuseppe/decorate-exists-error
Browse files Browse the repository at this point in the history
fileutils: make (Le|E)xists return os.PathError
  • Loading branch information
openshift-merge-bot[bot] authored Apr 10, 2024
2 parents 90967d7 + 543bba0 commit dfdc6bf
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 dfdc6bf

Please sign in to comment.