Use errors.Is() instead of os.Is{Not,}Exist

If errors for which os.IsExist() or os.IsNotExist() would have returned
true have been wrapped using fmt.Errorf()'s "%w" verb, os.IsExist() and
os.IsNotExist(), not having been retrofitted to use errors.Is(), will
return false.

Use errors.Is() to check if an error is an os.ErrExist or os.ErrNotExist
error instead of calling os.IsExist() or os.IsNotExist().

Signed-off-by: Nalin Dahyabhai <nalin@redhat.com>
This commit is contained in:
Nalin Dahyabhai 2022-07-26 15:27:30 -04:00
parent 9e2421ca3d
commit bb149ea686
16 changed files with 53 additions and 46 deletions

View File

@ -150,7 +150,7 @@ func SetupIntermediateMountNamespace(spec *specs.Spec, bundlePath string) (unmou
// Check if the source is a directory or something else.
info, err := os.Stat(spec.Mounts[i].Source)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
logrus.Warnf("couldn't find %q on host to bind mount into container", spec.Mounts[i].Source)
continue
}
@ -269,7 +269,7 @@ func UnmountMountpoints(mountpoint string, mountpointsToRemove []string) error {
mount := getMountByID(id)
// check if this mountpoint is mounted
if err := unix.Lstat(mount.Mountpoint, &st); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
logrus.Debugf("mountpoint %q is not present(?), skipping", mount.Mountpoint)
continue
}

View File

@ -3,6 +3,7 @@ package buildah
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -445,7 +446,7 @@ func OpenBuilderByPath(store storage.Store, path string) (*Builder, error) {
}
buildstate, err := ioutil.ReadFile(filepath.Join(cdir, stateFile))
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
logrus.Debugf("error reading %q: %v, ignoring container %q", filepath.Join(cdir, stateFile), err, container.ID)
continue
}
@ -482,7 +483,7 @@ func OpenAllBuilders(store storage.Store) (builders []*Builder, err error) {
}
buildstate, err := ioutil.ReadFile(filepath.Join(cdir, stateFile))
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
logrus.Debugf("error reading %q: %v, ignoring container %q", filepath.Join(cdir, stateFile), err, container.ID)
continue
}

View File

@ -6,6 +6,7 @@ package chroot
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -1090,7 +1091,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Bind /dev read-only.
subDev := filepath.Join(spec.Root.Path, "/dev")
if err := unix.Mount("/dev", subDev, "bind", devFlags, ""); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(subDev, 0755)
if err == nil {
err = unix.Mount("/dev", subDev, "bind", devFlags, "")
@ -1114,7 +1115,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Bind /proc read-only.
subProc := filepath.Join(spec.Root.Path, "/proc")
if err := unix.Mount("/proc", subProc, "bind", procFlags, ""); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(subProc, 0755)
if err == nil {
err = unix.Mount("/proc", subProc, "bind", procFlags, "")
@ -1129,7 +1130,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Bind /sys read-only.
subSys := filepath.Join(spec.Root.Path, "/sys")
if err := unix.Mount("/sys", subSys, "bind", sysFlags, ""); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(subSys, 0755)
if err == nil {
err = unix.Mount("/sys", subSys, "bind", sysFlags, "")
@ -1218,7 +1219,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
}
if err != nil {
// If the target can't be stat()ted, check the error.
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return undoBinds, fmt.Errorf("error examining %q for mounting in mount namespace: %w", target, err)
}
// The target isn't there yet, so create it.
@ -1304,7 +1305,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
r := filepath.Join(spec.Root.Path, roPath)
target, err := filepath.EvalSymlinks(r)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// No target, no problem.
continue
}
@ -1313,7 +1314,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Check if the location is already read-only.
var fs unix.Statfs_t
if err = unix.Statfs(target, &fs); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// No target, no problem.
continue
}
@ -1325,7 +1326,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Mount the location over itself, so that we can remount it as read-only.
roFlags := uintptr(unix.MS_NODEV | unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_RDONLY)
if err := unix.Mount(target, target, "", roFlags|unix.MS_BIND|unix.MS_REC, ""); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// No target, no problem.
continue
}
@ -1370,7 +1371,7 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
// Get some info about the target.
targetinfo, err := os.Stat(target)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// No target, no problem.
continue
}

View File

@ -1558,7 +1558,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
} else {
// FreeBSD can return EISDIR for "mkdir /":
// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=59739.
if !os.IsExist(err) && !errors.Is(err, syscall.EISDIR) {
if !errors.Is(err, os.ErrExist) && !errors.Is(err, syscall.EISDIR) {
return fmt.Errorf("copier: put: error checking directory %q: %w", path, err)
}
}
@ -1581,7 +1581,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
}
createFile := func(path string, tr *tar.Reader) (int64, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC|os.O_EXCL, 0600)
if err != nil && os.IsExist(err) {
if err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err2 := os.Lstat(path); err2 == nil && st.IsDir() {
return 0, fmt.Errorf("copier: put: error creating file at %q: %w", path, err)
@ -1626,7 +1626,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
return errorResponse("copier: put: %s (%s): exists but is not a directory", req.Directory, targetDirectory)
}
} else {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return errorResponse("copier: put: %s: %v", req.Directory, err)
}
if err := ensureDirectoryUnderRoot(req.Directory); err != nil {
@ -1738,7 +1738,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
if linkTarget, err = resolvePath(targetDirectory, filepath.Join(req.Root, filepath.FromSlash(hdr.Linkname)), true, nil); err != nil {
return fmt.Errorf("error resolving hardlink target path %q under root %q", hdr.Linkname, req.Root)
}
if err = os.Link(linkTarget, path); err != nil && os.IsExist(err) {
if err = os.Link(linkTarget, path); err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err := os.Lstat(path); err == nil && st.IsDir() {
break
@ -1753,7 +1753,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
// todo: the general solution requires resolving to an absolute path, handling
// renaming, and then possibly converting back to a relative symlink
// }
if err = os.Symlink(filepath.FromSlash(hdr.Linkname), filepath.FromSlash(path)); err != nil && os.IsExist(err) {
if err = os.Symlink(filepath.FromSlash(hdr.Linkname), filepath.FromSlash(path)); err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err := os.Lstat(path); err == nil && st.IsDir() {
break
@ -1768,7 +1768,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
ignoredItems[nameBeforeRenaming] = struct{}{}
goto nextHeader
}
if err = mknod(path, chrMode(0600), int(mkdev(devMajor, devMinor))); err != nil && os.IsExist(err) {
if err = mknod(path, chrMode(0600), int(mkdev(devMajor, devMinor))); err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err := os.Lstat(path); err == nil && st.IsDir() {
break
@ -1783,7 +1783,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
ignoredItems[nameBeforeRenaming] = struct{}{}
goto nextHeader
}
if err = mknod(path, blkMode(0600), int(mkdev(devMajor, devMinor))); err != nil && os.IsExist(err) {
if err = mknod(path, blkMode(0600), int(mkdev(devMajor, devMinor))); err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err := os.Lstat(path); err == nil && st.IsDir() {
break
@ -1794,7 +1794,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
}
}
case tar.TypeDir:
if err = os.Mkdir(path, 0700); err != nil && os.IsExist(err) {
if err = os.Mkdir(path, 0700); err != nil && errors.Is(err, os.ErrExist) {
if st, stErr := os.Lstat(path); stErr == nil && !st.IsDir() {
if req.PutOptions.NoOverwriteNonDirDir {
break
@ -1821,7 +1821,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
// the archive more than once for whatever reason
directoryModes[path] = mode
case tar.TypeFifo:
if err = mkfifo(path, 0600); err != nil && os.IsExist(err) {
if err = mkfifo(path, 0600); err != nil && errors.Is(err, os.ErrExist) {
if req.PutOptions.NoOverwriteDirNonDir {
if st, err := os.Lstat(path); err == nil && st.IsDir() {
break
@ -1943,7 +1943,7 @@ func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response,
} else {
// FreeBSD can return EISDIR for "mkdir /":
// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=59739.
if !os.IsExist(err) && !errors.Is(err, syscall.EISDIR) {
if !errors.Is(err, os.ErrExist) && !errors.Is(err, syscall.EISDIR) {
return errorResponse("copier: mkdir: error checking directory %q: %v", path, err)
}
}

View File

@ -4,6 +4,7 @@ import (
"archive/tar"
"bufio"
"bytes"
"errors"
"flag"
"fmt"
"io"
@ -1508,7 +1509,7 @@ func testEval(t *testing.T) {
for _, vector := range vectors {
t.Run(fmt.Sprintf("id=%s", vector.id), func(t *testing.T) {
err = os.Symlink(vector.linkTarget, linkname)
if err != nil && os.IsExist(err) {
if err != nil && errors.Is(err, os.ErrExist) {
os.Remove(linkname)
err = os.Symlink(vector.linkTarget, linkname)
}

View File

@ -747,7 +747,7 @@ func (i *containerImageSource) GetBlob(ctx context.Context, blob types.BlobInfo,
}
layerFile.Close()
}
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
logrus.Debugf("error checking for layer %q in %q: %v", blob.Digest.String(), blobDir, err)
}
}

View File

@ -3,6 +3,7 @@ package imagebuildah
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"os"
@ -126,7 +127,7 @@ func (s *StageExecutor) Preserve(path string) error {
}
st, err := os.Stat(archivedPath)
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
createdDirPerms := os.FileMode(0755)
if err = copier.Mkdir(s.mountPoint, archivedPath, copier.MkdirOptions{ChmodNew: &createdDirPerms}); err != nil {
return fmt.Errorf("error ensuring volume path exists: %w", err)
@ -168,7 +169,7 @@ func (s *StageExecutor) Preserve(path string) error {
archivedPath := filepath.Join(s.mountPoint, cachedPath)
logrus.Debugf("no longer need cache of %q in %q", archivedPath, s.volumeCache[cachedPath])
if err := os.Remove(s.volumeCache[cachedPath]); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
@ -189,7 +190,7 @@ func (s *StageExecutor) volumeCacheInvalidate(path string) error {
}
for _, cachedPath := range invalidated {
if err := os.Remove(s.volumeCache[cachedPath]); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
@ -220,7 +221,7 @@ func (s *StageExecutor) volumeCacheSaveVFS() (mounts []specs.Mount, err error) {
logrus.Debugf("contents of volume %q are already cached in %q", archivedPath, cacheFile)
continue
}
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
createdDirPerms := os.FileMode(0755)

View File

@ -250,7 +250,7 @@ func Unmount(contentDir string) error {
}
// Ignore EINVAL as the specified merge dir is not a mount point
if err := unix.Unmount(mergeDir, 0); err != nil && !os.IsNotExist(err) && err != unix.EINVAL {
if err := unix.Unmount(mergeDir, 0); err != nil && !errors.Is(err, os.ErrNotExist) && err != unix.EINVAL {
return fmt.Errorf("unmount overlay %s: %w", mergeDir, err)
}
return nil
@ -259,7 +259,7 @@ func Unmount(contentDir string) error {
func recreate(contentDir string) error {
st, err := system.Stat(contentDir)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("failed to stat overlay upper directory: %w", err)
@ -293,7 +293,7 @@ func CleanupContent(containerDir string) (Err error) {
files, err := ioutil.ReadDir(contentDir)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("read directory: %w", err)
@ -305,7 +305,7 @@ func CleanupContent(containerDir string) (Err error) {
}
}
if err := os.RemoveAll(contentDir); err != nil && !os.IsNotExist(err) {
if err := os.RemoveAll(contentDir); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to cleanup overlay directory: %w", err)
}
return nil

View File

@ -245,11 +245,11 @@ func parseSecurityOpts(securityOpts []string, commonOpts *define.CommonBuildOpti
if _, err := os.Stat(SeccompOverridePath); err == nil {
commonOpts.SeccompProfilePath = SeccompOverridePath
} else {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return err
}
if _, err := os.Stat(SeccompDefaultPath); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return err
}
} else {
@ -1072,11 +1072,11 @@ func ContainerIgnoreFile(contextDir, path string) ([]string, string, error) {
}
path = filepath.Join(contextDir, ".containerignore")
excludes, err := imagebuilder.ParseIgnore(path)
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
path = filepath.Join(contextDir, ".dockerignore")
excludes, err = imagebuilder.ParseIgnore(path)
}
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return excludes, "", nil
}
return excludes, path, err

View File

@ -1365,7 +1365,7 @@ func runSetupBuiltinVolumes(mountLabel, mountPoint, containerDir string, builtin
// the volume contents. If we do need to create it, then we'll
// need to populate it, too, so make a note of that.
if _, err := os.Stat(volumePath); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
logrus.Debugf("setting up built-in volume path at %q for %q", volumePath, volume)
@ -1391,7 +1391,7 @@ func runSetupBuiltinVolumes(mountLabel, mountPoint, containerDir string, builtin
return nil, fmt.Errorf("evaluating path %q: %w", srcPath, err)
}
stat, err := os.Stat(srcPath)
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
// If we need to populate the mounted volume's contents with
@ -1844,7 +1844,7 @@ func (b *Builder) cleanupRunMounts(context *imageTypes.SystemContext, mountpoint
var prevErr error
for _, path := range artifacts.TmpFiles {
err := os.Remove(path)
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
if prevErr != nil {
logrus.Error(prevErr)
}

View File

@ -381,7 +381,7 @@ func (b *Builder) setupOCIHooks(config *spec.Spec, hasVolumes bool) (map[string]
for _, hDir := range []string{hooks.DefaultDir, hooks.OverrideDir} {
manager, err := hooks.New(context.Background(), []string{hDir}, []string{})
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, err
@ -690,7 +690,7 @@ func setupNamespaces(logger *logrus.Logger, g *generate.Generator, namespaceOpti
// by the kernel
p := filepath.Join("/proc/sys", strings.Replace(name, ".", "/", -1))
_, err := os.Stat(p)
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return false, nil, false, err
}
if err == nil {

View File

@ -4,6 +4,7 @@
package buildah
import (
"errors"
"fmt"
"os"
@ -33,7 +34,7 @@ func runLabelStdioPipes(stdioPipe [][]int, processLabel, mountLabel string) erro
}
for i := range stdioPipe {
pipeFdName := fmt.Sprintf("/proc/self/fd/%d", stdioPipe[i][0])
if err := selinux.SetFileLabel(pipeFdName, pipeContext); err != nil && !os.IsNotExist(err) {
if err := selinux.SetFileLabel(pipeFdName, pipeContext); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("setting file label on %q: %w", pipeFdName, err)
}
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
@ -69,7 +70,7 @@ var _ = BeforeSuite(func() {
integrationRoot = filepath.Join(cwd, "../../")
buildah := BuildahCreate("/tmp")
buildah.ArtifactPath = artifactDir
if _, err := os.Stat(artifactDir); os.IsNotExist(err) {
if _, err := os.Stat(artifactDir); errors.Is(err, os.ErrNotExist) {
if err = os.Mkdir(artifactDir, 0777); err != nil {
fmt.Printf("%q\n", err)
os.Exit(1)

View File

@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"io/ioutil"
"log"
"net"
@ -16,7 +17,7 @@ func sendThatFile(basepath string) func(w http.ResponseWriter, r *http.Request)
filename := filepath.Join(basepath, filepath.Clean(string([]rune{filepath.Separator})+r.URL.Path))
f, err := os.Open(filename)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
http.NotFound(w, r)
return
}

View File

@ -187,7 +187,7 @@ func IsContainer(id string, store storage.Store) (bool, error) {
// Assuming that if the stateFile exists, that this is a Buildah
// container.
if _, err = os.Stat(filepath.Join(cdir, stateFile)); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err

View File

@ -387,7 +387,7 @@ var (
func fileExistsAndNotADir(path string) bool {
file, err := os.Stat(path)
if file == nil || err != nil || os.IsNotExist(err) {
if file == nil || err != nil || errors.Is(err, os.ErrNotExist) {
return false
}
return !file.IsDir()