Replace os.Is* error checks with errors.Is

Using os.Is{Exist,NotExist,Permission} checks is not recommended in the
new code (see official documentation). While using it in the existing
code is OK, it may still result in a subtle errors later (for a specific
example of that, see [1]).

Replace those with errors.Is.

Generated by:

	gofmt -r 'os.IsExist(a) -> errors.Is(a, os.ErrExist)' -w .
	gofmt -r 'os.IsNotExist(a) -> errors.Is(a, os.ErrNotExist)' -w .
	gofmt -r 'os.IsPermission(a) -> errors.Is(a, os.ErrPermission)' -w .
	goimports -w .
	git diff vendor test/tools/vendor | patch -p1 -R

[1]: https://github.com/opencontainers/runc/pull/5061
Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
This commit is contained in:
Kir Kolyshkin
2026-05-21 13:03:36 -07:00
parent 2d09c79dfe
commit 7f7b35356f
32 changed files with 62 additions and 53 deletions

View File

@@ -3,6 +3,7 @@
package main
import (
"errors"
"fmt"
"io"
"io/fs"
@@ -70,7 +71,7 @@ func service() int {
}
err := os.Remove(dockerSock)
if err == nil || os.IsNotExist(err) {
if err == nil || errors.Is(err, os.ErrNotExist) {
err = os.Symlink(target, dockerSock)
}

View File

@@ -48,7 +48,7 @@ func uninstall(_ *cobra.Command, _ []string) error {
}
if err := os.Remove(fileName); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("could not remove plist file: %s", fileName)
}
}

View File

@@ -3,6 +3,7 @@
package system
import (
"errors"
"fmt"
"net/url"
"os"
@@ -107,7 +108,7 @@ func service(cmd *cobra.Command, args []string) error {
// socket activation uses a unix:// socket in the shipped unit files but apiURI is coded as "" at this layer.
if uri.Scheme == "unix" && !registry.IsRemote() {
if err := syscall.Unlink(uri.Path); err != nil && !os.IsNotExist(err) {
if err := syscall.Unlink(uri.Path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
mask := syscall.Umask(0o177)

View File

@@ -404,7 +404,7 @@ func (c *Container) specFromState() (*spec.Spec, error) {
logrus.Warnf("Error unmarshalling container %s config: %v", c.ID(), err)
return c.config.Spec, nil
}
} else if !os.IsNotExist(err) {
} else if !errors.Is(err, os.ErrNotExist) {
// ignore when the file does not exist
return nil, fmt.Errorf("opening container config: %w", err)
}

View File

@@ -907,7 +907,7 @@ func (c *Container) cleanupExecBundle(sessionID string) (err error) {
path := c.execBundlePath(sessionID)
for range 50 {
err = os.RemoveAll(path)
if err == nil || os.IsNotExist(err) {
if err == nil || errors.Is(err, os.ErrNotExist) {
return nil
}
if pathErr, ok := err.(*os.PathError); ok {
@@ -990,7 +990,7 @@ func (c *Container) createExecBundle(sessionID string) (retErr error) {
}()
if err := os.MkdirAll(c.execExitFileDir(sessionID), execDirPermission); err != nil {
// The directory is allowed to exist
if !os.IsExist(err) {
if !errors.Is(err, os.ErrExist) {
return fmt.Errorf("creating OCI runtime exit file path %s: %w", c.execExitFileDir(sessionID), err)
}
}

View File

@@ -738,17 +738,17 @@ func (c *Container) removeConmonFiles() error {
return fmt.Errorf("failed to get attach socket path for container %s: %w", c.ID(), err)
}
if err := os.Remove(attachFile); err != nil && !os.IsNotExist(err) {
if err := os.Remove(attachFile); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("removing container %s attach file: %w", c.ID(), err)
}
ctlFile := filepath.Join(c.bundlePath(), "ctl")
if err := os.Remove(ctlFile); err != nil && !os.IsNotExist(err) {
if err := os.Remove(ctlFile); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("removing container %s ctl file: %w", c.ID(), err)
}
winszFile := filepath.Join(c.bundlePath(), "winsz")
if err := os.Remove(winszFile); err != nil && !os.IsNotExist(err) {
if err := os.Remove(winszFile); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("removing container %s winsz file: %w", c.ID(), err)
}
@@ -757,7 +757,7 @@ func (c *Container) removeConmonFiles() error {
if err != nil {
return err
}
if err := os.Remove(exitFile); err != nil && !os.IsNotExist(err) {
if err := os.Remove(exitFile); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("removing container %s exit file: %w", c.ID(), err)
}
@@ -1826,7 +1826,7 @@ func (c *Container) mountStorage() (_ string, deferredErr error) {
defer unix.Close(dirfd)
err = unix.Mkdirat(dirfd, "etc", 0o755)
if err != nil && !os.IsExist(err) {
if err != nil && !errors.Is(err, os.ErrExist) {
return "", fmt.Errorf("create /etc: %w", err)
}
// If the etc directory was created, chown it to root in the container
@@ -1926,7 +1926,7 @@ func (c *Container) mountNamedVolume(v *ContainerNamedVolume, mountpoint string)
// Skip the rest if it exists.
srcStat, err := os.Lstat(srcDir)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// Source does not exist, don't bother copying
// up.
return vol, nil
@@ -2386,7 +2386,7 @@ func (c *Container) postDeleteHooks(ctx context.Context) error {
func (c *Container) writeStringToRundir(destFile, contents string) (string, error) {
destFileName := filepath.Join(c.state.RunDir, destFile)
if err := os.Remove(destFileName); err != nil && !os.IsNotExist(err) {
if err := os.Remove(destFileName); err != nil && !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("removing %s for container %s: %w", destFile, c.ID(), err)
}
@@ -2420,7 +2420,7 @@ func (c *Container) saveSpec(spec *spec.Spec) error {
// paths
jsonPath := filepath.Join(c.bundlePath(), "config.json")
if err := fileutils.Exists(jsonPath); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("doing stat on container %s spec: %w", c.ID(), err)
}
// The spec does not exist, we're fine
@@ -2456,7 +2456,7 @@ func (c *Container) setupOCIHooks(ctx context.Context, config *spec.Spec) (map[s
for _, hDir := range []string{hooks.DefaultDir, hooks.OverrideDir} {
manager, err := hooks.New(ctx, []string{hDir}, []string{"precreate", "poststop"})
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, err
@@ -2718,7 +2718,7 @@ func (c *Container) checkExitFile() error {
// Check for the exit file
info, err := os.Stat(exitFile)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// Container is still running, no error
return nil
}

View File

@@ -979,7 +979,7 @@ func (c *Container) mountNotifySocket(g generate.Generator) error {
notifyDir := filepath.Join(c.bundlePath(), "notify")
logrus.Debugf("Checking notify %q dir", notifyDir)
if err := os.MkdirAll(notifyDir, 0o755); err != nil {
if !os.IsExist(err) {
if !errors.Is(err, os.ErrExist) {
return fmt.Errorf("unable to create notify %q dir: %w", notifyDir, err)
}
}
@@ -1958,13 +1958,13 @@ func (c *Container) makeBindMounts() error {
// another container.
if c.config.NetNsCtr == "" {
if resolvePath, ok := c.state.BindMounts[resolvconf.DefaultResolvConf]; ok {
if err := os.Remove(resolvePath); err != nil && !os.IsNotExist(err) {
if err := os.Remove(resolvePath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("container %s: %w", c.ID(), err)
}
delete(c.state.BindMounts, resolvconf.DefaultResolvConf)
}
if hostsPath, ok := c.state.BindMounts[config.DefaultHostsFile]; ok {
if err := os.Remove(hostsPath); err != nil && !os.IsNotExist(err) {
if err := os.Remove(hostsPath); err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("container %s: %w", c.ID(), err)
}
delete(c.state.BindMounts, config.DefaultHostsFile)
@@ -2843,7 +2843,7 @@ func (c *Container) generatePasswdAndGroup() (string, string, error) {
return "", "", fmt.Errorf("creating path to container %s /etc/passwd: %w", c.ID(), err)
}
orig, err := os.ReadFile(originPasswdFile)
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return "", "", err
}
passwdFile, err := c.writeStringToStaticDir("passwd", string(orig)+passwdEntry)
@@ -2889,7 +2889,7 @@ func (c *Container) generatePasswdAndGroup() (string, string, error) {
return "", "", fmt.Errorf("creating path to container %s /etc/group: %w", c.ID(), err)
}
orig, err := os.ReadFile(originGroupFile)
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return "", "", err
}
groupFile, err := c.writeStringToStaticDir("group", string(orig)+groupEntry)
@@ -2932,7 +2932,7 @@ func (c *Container) cleanupOverlayMounts() error {
func (c *Container) createSecretMountDir(runPath string) error {
src := filepath.Join(c.state.RunDir, "/run/secrets")
err := fileutils.Exists(src)
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
if err := umask.MkdirAllIgnoreUmask(src, os.FileMode(0o755)); err != nil {
return err
}
@@ -3087,7 +3087,7 @@ func (c *Container) fixVolumePermissionsUnlocked(v *ContainerNamedVolume, vol *V
if err := setVolumeAtime(mountPoint, st); err != nil {
return err
}
} else if !os.IsNotExist(err) {
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}

View File

@@ -4,6 +4,7 @@ package libpod
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
@@ -236,7 +237,7 @@ func (c *Container) addSharedNamespaces(g *generate.Generator) error {
availableUIDs, availableGIDs, err := rootless.GetAvailableIDMaps()
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// The kernel-provided files only exist if user namespaces are supported
logrus.Debugf("User or group ID mappings not available: %s", err)
} else {

View File

@@ -3,6 +3,7 @@
package libpod
import (
"errors"
"fmt"
"io/fs"
"os"
@@ -436,7 +437,7 @@ func (c *Container) addSharedNamespaces(g *generate.Generator) error {
availableUIDs, availableGIDs, err := rootless.GetAvailableIDMaps()
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// The kernel-provided files only exist if user namespaces are supported
logrus.Debugf("User or group ID mappings not available: %s", err)
} else {
@@ -687,7 +688,7 @@ func (c *Container) makePlatformMtabLink(etcInTheContainerFd, rootUID, rootGID i
// If /etc/mtab does not exist in container image, then we need to
// create it, so that mount command within the container will work.
err := unix.Symlinkat("/proc/mounts", etcInTheContainerFd, "mtab")
if err != nil && !os.IsExist(err) {
if err != nil && !errors.Is(err, os.ErrExist) {
return fmt.Errorf("creating /etc/mtab symlink: %w", err)
}
// If the symlink was created, then also chown it to root in the container

View File

@@ -61,7 +61,7 @@ func (c *Container) stat(containerMountPoint string, containerPath string) (*def
// have to look into the error string. Turning it into an
// ENOENT lets the API handlers return the correct status code
// which is crucial for the remote client.
if os.IsNotExist(statErr) || strings.Contains(statErr.Error(), "o such file or directory") {
if errors.Is(statErr, os.ErrNotExist) || strings.Contains(statErr.Error(), "o such file or directory") {
statErr = copy.ErrENOENT
}
}

View File

@@ -83,7 +83,7 @@ func (locks *FileLocks) AllocateLock() (uint32, error) {
path := locks.getLockPath(id)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666)
if err != nil {
if os.IsExist(err) {
if errors.Is(err, os.ErrExist) {
continue
}
return 0, fmt.Errorf("creating lock file: %w", err)

View File

@@ -124,7 +124,7 @@ func newConmonOCIRuntime(name string, paths []string, conmonPath string, runtime
for _, path := range paths {
stat, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
continue
}
return nil, fmt.Errorf("cannot stat OCI runtime %s path: %w", name, err)

View File

@@ -183,7 +183,7 @@ func (p *VolumePlugin) getURI() string {
// Does not actually ping the API, just verifies that the socket still exists.
func (p *VolumePlugin) verifyReachable() error {
if err := fileutils.Exists(p.SocketPath); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
pluginsLock.Lock()
defer pluginsLock.Unlock()
delete(plugins, p.Name)

View File

@@ -599,7 +599,7 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (_ *Contai
if useDevShm && !MountExists(ctr.config.Spec.Mounts, "/dev/shm") && ctr.config.ShmDir == "" && !ctr.config.NoShm {
ctr.config.ShmDir = filepath.Join(ctr.bundlePath(), "shm")
if err := os.MkdirAll(ctr.config.ShmDir, 0o700); err != nil {
if !os.IsExist(err) {
if !errors.Is(err, os.ErrExist) {
return nil, fmt.Errorf("unable to create shm dir: %w", err)
}
}

View File

@@ -29,7 +29,7 @@ func (r *Runtime) stopPauseProcess() error {
pausePidPath := rootless.GetPausePidPath(stateDir)
data, err := os.ReadFile(pausePidPath)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return fmt.Errorf("cannot read pause process pid file: %w", err)

View File

@@ -88,11 +88,11 @@ func DefaultSeccompPath() (string, error) {
if err == nil {
return config.SeccompOverridePath, nil
}
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return "", err
}
if err := fileutils.Exists(config.SeccompDefaultPath); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return "", err
}
return "", nil

View File

@@ -131,7 +131,7 @@ func handlePut(w http.ResponseWriter, r *http.Request, decoder *schema.Decoder,
})
if err != nil {
switch {
case errors.Is(err, define.ErrNoSuchCtr) || os.IsNotExist(err):
case errors.Is(err, define.ErrNoSuchCtr) || errors.Is(err, os.ErrNotExist):
// 404 is returned for an absent container and path. The
// clients must deal with it accordingly.
utils.Error(w, http.StatusNotFound, fmt.Errorf("the container does not exist: %w", err))

View File

@@ -541,7 +541,7 @@ func cliOpts(cc handlers.CreateContainerConfig, rtc *config.Config) (*entities.C
continue
}
if err := os.MkdirAll(vol, 0o755); err != nil {
if !os.IsExist(err) {
if !errors.Is(err, os.ErrExist) {
return nil, nil, fmt.Errorf("making volume mountpoint for volume %s: %w", vol, err)
}
}

View File

@@ -621,7 +621,7 @@ func prepareContainerFiles(containerFiles []string, contextDir string, stdinDest
} else {
// If Containerfile does not exist, assume it is in context directory and do Not add to tarfile
if err := fileutils.Lexists(containerfile); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
containerfile = c

View File

@@ -2,6 +2,7 @@ package bindings_test
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
@@ -31,7 +32,7 @@ const (
func getPodmanBinary() string {
_, err := os.Stat(devPodmanBinaryLocation)
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return defaultPodmanBinaryLocation
}
return devPodmanBinaryLocation
@@ -152,7 +153,7 @@ func (b *bindingTest) startAPIService() *Session {
sock := strings.TrimPrefix(b.sock, "unix://")
for range 10 {
if _, err := os.Stat(sock); err != nil {
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
break
}
time.Sleep(time.Second)
@@ -264,7 +265,7 @@ func createCache() {
b := newBindingTest()
for _, i := range CACHE_IMAGES {
_, err := os.Stat(filepath.Join(ImageCacheDir, i.tarballName))
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// pull the image
b.Pull(i.name)
b.Save(i)

View File

@@ -4,6 +4,7 @@ package bindings_test
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
@@ -103,7 +104,7 @@ func readProc() ([]string, error) {
name += err.Error()
case d.Type()&fs.ModeSymlink != 0:
n, err := os.Readlink(path)
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if n == "" {

View File

@@ -77,7 +77,7 @@ func CRImportCheckpointConfigOnly(destination, input string) error {
// it exists deletes all files listed.
func CRRemoveDeletedFiles(id, baseDirectory, containerRootDirectory string) error {
deletedFiles, _, err := metadata.ReadContainerCheckpointDeletedFiles(baseDirectory)
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
// No files to delete. Just return
return nil
}

View File

@@ -63,7 +63,7 @@ func ResolveHostPath(path string) (*FileInfo, error) {
statInfo, err := os.Stat(resolvedHostPath)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return nil, ErrENOENT
}
return nil, err

View File

@@ -360,7 +360,7 @@ func (ir *ImageEngine) Save(_ context.Context, nameOrID string, tags []string, o
if info.Mode().IsRegular() {
return fmt.Errorf("%q already exists as a regular file", opts.Output)
}
case os.IsNotExist(err):
case errors.Is(err, os.ErrNotExist):
if err := os.Mkdir(opts.Output, 0o755); err != nil {
return err
}

View File

@@ -1,6 +1,7 @@
package lookup
import (
"errors"
"os"
"strconv"
@@ -123,7 +124,7 @@ func GetUser(containerMount, userIDorName string) (*user.User, error) {
}
return u.Uid == uid
})
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if len(users) > 0 {
@@ -158,7 +159,7 @@ func GetGroup(containerMount, groupIDorName string) (*user.Group, error) {
}
return g.Gid == gid
})
if err != nil && !os.IsNotExist(err) {
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
if len(groups) > 0 {

View File

@@ -52,7 +52,7 @@ func TryJoinPauseProcess(stateDir string) (bool, int, error) {
pidFileLock, err := lockfile.GetLockFile(pausePidPath)
if err != nil {
// The file was deleted by another process.
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return false, -1, nil
}
return false, -1, fmt.Errorf("acquiring lock on %s: %w", pausePidPath, err)

View File

@@ -193,7 +193,7 @@ func AddPolicyEntries(policyPath string, input AddPolicyEntriesInput) error {
}
err = fileutils.Exists(policyPath)
if !os.IsNotExist(err) {
if !errors.Is(err, os.ErrNotExist) {
policyContent, err := os.ReadFile(policyPath)
if err != nil {
return err

View File

@@ -1,6 +1,7 @@
package trust
import (
"errors"
"fmt"
"os"
"path/filepath"
@@ -58,7 +59,7 @@ func loadAndMergeConfig(dirPath string) (*registryConfiguration, error) {
dir, err := os.Open(dirPath)
if err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
return &mergedConfig, nil
}
return nil, err

View File

@@ -102,7 +102,7 @@ func ParseDockerignore(containerfiles []string, root string) ([]string, string,
}
}
}
if dockerIgnoreErr != nil && !os.IsNotExist(dockerIgnoreErr) {
if dockerIgnoreErr != nil && !errors.Is(dockerIgnoreErr, os.ErrNotExist) {
return nil, ignoreFile, err
}
}

View File

@@ -180,7 +180,7 @@ func AddPrivilegedDevices(g *generate.Generator, systemdMode bool) error {
func getDevices(path string) ([]spec.LinuxDevice, error) {
files, err := os.ReadDir(path)
if err != nil {
if rootless.IsRootless() && os.IsPermission(err) {
if rootless.IsRootless() && errors.Is(err, os.ErrPermission) {
return nil, nil
}
return nil, err

View File

@@ -4,6 +4,7 @@ package integration
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
@@ -464,7 +465,7 @@ RUN exit 5`, CITEST_IMAGE)
// Write target and fake files
targetSubPath := filepath.Join(podmanTest.TempDir, "emptydir")
if _, err = os.Stat(targetSubPath); err != nil {
if os.IsNotExist(err) {
if errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(targetSubPath, 0o755)
Expect(err).ToNot(HaveOccurred())
}

View File

@@ -621,7 +621,7 @@ func (p *PodmanTestIntegration) createArtifact(image string) {
return
}
destName := imageTarPath(image)
if _, err := os.Stat(destName); os.IsNotExist(err) {
if _, err := os.Stat(destName); errors.Is(err, os.ErrNotExist) {
GinkgoWriter.Printf("Caching %s at %s...\n", image, destName)
p.pullImage(image, false)