From 79c5ac14b278fc237f5db1f02664c3c793d955cb Mon Sep 17 00:00:00 2001 From: Miguel Pires Date: Wed, 3 Apr 2024 22:23:24 +0100 Subject: [PATCH] many: remove usages of deprecated io/ioutil package (#13768) * many: remove usages of deprecated io/ioutil package Signed-off-by: Miguel Pires * .golangci.yml: remove errcheck ignore rule for io/ioutil Signed-off-by: Miguel Pires * run-checks: prevent new usages of io/ioutil Signed-off-by: Miguel Pires --------- Signed-off-by: Miguel Pires --- .golangci.yml | 2 +- asserts/database_test.go | 3 +- asserts/fsentryutils.go | 3 +- boot/flags.go | 5 +- boot/modeenv_test.go | 3 +- bootloader/assets/genasset/main_test.go | 3 +- bootloader/assets/grub_test.go | 4 +- bootloader/efi/efi.go | 5 +- bootloader/grubenv/grubenv.go | 3 +- bootloader/lk.go | 3 +- bootloader/lk_test.go | 11 ++-- bootloader/piboot.go | 9 ++- bootloader/piboot_test.go | 15 +++-- bootloader/ubootenv/env.go | 3 +- bootloader/ubootenv/env_test.go | 10 ++-- bootloader/withbootassettesting.go | 3 +- client/aspects_test.go | 4 +- client/asserts_test.go | 4 +- client/change_test.go | 4 +- client/client.go | 3 +- client/client_test.go | 23 ++++---- client/cohort_test.go | 6 +- client/icons.go | 4 +- client/model_test.go | 5 +- client/quota_test.go | 6 +- client/snap_op_test.go | 53 +++++++++-------- client/snapctl.go | 3 +- client/snapshot_test.go | 6 +- client/systems_test.go | 8 +-- client/users_test.go | 10 ++-- client/validate_test.go | 8 +-- cmd/snap-bootstrap/cmd_initramfs_mounts.go | 5 +- .../cmd_initramfs_mounts_test.go | 5 +- cmd/snap-failure/cmd_snapd.go | 3 +- cmd/snap-fde-keymgr/main.go | 7 +-- cmd/snap-recovery-chooser/main_test.go | 5 +- cmd/snap-repair/cmd_done_retry_skip_test.go | 4 +- cmd/snap-repair/runner.go | 3 +- cmd/snap-repair/runner_test.go | 7 +-- cmd/snap-seccomp/main.go | 5 +- cmd/snap-update-ns/change_test.go | 30 +++++----- cmd/snap-update-ns/export_test.go | 17 +++--- cmd/snap-update-ns/utils.go | 7 +-- cmd/snap-update-ns/utils_test.go | 23 ++++---- cmd/snap/cmd_ack.go | 4 +- cmd/snap/cmd_aliases_test.go | 10 ++-- cmd/snap/cmd_auto_import.go | 11 ++-- cmd/snap/cmd_auto_import_test.go | 16 +++--- cmd/snap/cmd_connections_test.go | 22 +++---- cmd/snap/cmd_connectivity_check_test.go | 6 +- cmd/snap/cmd_debug_model_test.go | 4 +- cmd/snap/cmd_debug_seeding_test.go | 4 +- cmd/snap/cmd_ensure_state_soon_test.go | 4 +- cmd/snap/cmd_get_base_declaration_test.go | 6 +- cmd/snap/cmd_interface_test.go | 14 ++--- cmd/snap/cmd_interfaces_test.go | 28 ++++----- cmd/snap/cmd_keys_test.go | 3 +- cmd/snap/cmd_login_test.go | 4 +- cmd/snap/cmd_quota_test.go | 4 +- cmd/snap/cmd_reboot_test.go | 4 +- cmd/snap/cmd_run.go | 5 +- cmd/snap/cmd_sign.go | 7 ++- cmd/snap/cmd_sign_build_test.go | 5 +- cmd/snap/cmd_snap_op_test.go | 6 +- cmd/snap/cmd_validate_test.go | 6 +- cmd/snap/cmd_warnings_test.go | 6 +- cmd/snap/export_test.go | 6 +- cmd/snapd-apparmor/main.go | 5 +- cmd/snaplock/runinhibit/inhibit.go | 6 +- cmd/snaplock/runinhibit/inhibit_test.go | 3 +- daemon/api_apps_test.go | 15 +++-- daemon/api_base_test.go | 3 +- daemon/api_debug_pprof_test.go | 7 ++- daemon/api_download_test.go | 3 +- daemon/api_sideload_n_try_test.go | 9 ++- daemon/api_snapshots_test.go | 3 +- daemon/daemon_test.go | 6 +- gadget/device/encrypt.go | 7 +-- gadget/device/encrypt_test.go | 3 +- gadget/gadget.go | 7 +-- gadget/install/content_test.go | 4 +- gadget/install/install_test.go | 5 +- gadget/mountedfilesystem.go | 8 +-- httputil/client.go | 4 +- httputil/logger_test.go | 4 +- i18n/xgettext-go/main.go | 7 +-- image/image_linux.go | 3 +- image/image_test.go | 35 ++++++------ image/preseed/preseed_linux.go | 5 +- image/preseed/reset.go | 5 +- interfaces/apparmor/backend.go | 5 +- interfaces/apparmor/backend_test.go | 55 ++++++++++-------- interfaces/builtin/common.go | 6 +- interfaces/builtin/common_test.go | 6 +- interfaces/builtin/display_control_test.go | 6 +- interfaces/builtin/kvm.go | 4 +- interfaces/builtin/polkit.go | 4 +- interfaces/builtin/udisks2.go | 4 +- interfaces/mount/backend_test.go | 13 ++--- interfaces/seccomp/backend_test.go | 9 ++- interfaces/system_key.go | 3 +- interfaces/system_key_test.go | 3 +- kernel/kernel.go | 3 +- osutil/bootid.go | 4 +- osutil/disks/disks_linux.go | 10 ++-- osutil/export_test.go | 3 +- osutil/inotify/inotify_linux_test.go | 5 +- osutil/io_test.go | 7 +-- osutil/kcmdline/kcmdline.go | 4 +- osutil/mkfs/mkfs.go | 3 +- osutil/mountinfo_linux.go | 3 +- osutil/strace/timing_test.go | 3 +- osutil/syncdir.go | 9 ++- osutil/udev/crawler/device.go | 4 +- osutil/udev/main.go.sample | 3 +- overlord/configstate/configcore/cloud.go | 3 +- .../configstate/configcore/homedirs_test.go | 3 +- overlord/configstate/configcore/tmp.go | 3 +- overlord/devicestate/crypto.go | 9 ++- .../devicestate_install_mode_test.go | 6 +- overlord/devicestate/handlers_install.go | 3 +- overlord/devicestate/handlers_systems.go | 3 +- overlord/install/install_test.go | 5 +- overlord/managers_test.go | 3 +- overlord/overlord_test.go | 5 +- overlord/patch/patch1.go | 4 +- overlord/servicestate/servicestate_test.go | 5 +- overlord/snapshotstate/backend/reader.go | 5 +- overlord/snapshotstate/snapshotstate_test.go | 3 +- overlord/snapstate/backend/copydata.go | 5 +- overlord/snapstate/backend/copydata_test.go | 29 +++++----- overlord/snapstate/cookies_test.go | 5 +- overlord/snapstate/handlers_link_test.go | 5 +- overlord/snapstate/snapstate_update_test.go | 4 +- overlord/state/copy_test.go | 7 +-- polkit/pid_start_time.go | 4 +- randutil/crypto.go | 4 +- release/release_test.go | 3 +- run-checks | 16 ++++++ sandbox/apparmor/apparmor.go | 7 +-- sandbox/apparmor/apparmor_test.go | 5 +- sandbox/apparmor/process.go | 3 +- sandbox/apparmor/profile_test.go | 41 +++++++------ sandbox/cgroup/freezer.go | 5 +- sandbox/seccomp/export_test.go | 6 +- sandbox/seccomp/seccomp.go | 6 +- sandbox/selinux/selinux_linux.go | 4 +- secboot/secboot_hooks.go | 3 +- secboot/secboot_tpm.go | 7 +-- seed/helpers.go | 3 +- seed/internal/options20.go | 4 +- seed/internal/seed_yaml.go | 4 +- seed/seedwriter/manifest_test.go | 5 +- seed/seedwriter/writer_test.go | 37 ++++++------ snap/implicit.go | 4 +- snap/pack/pack.go | 3 +- snap/pack/pack_test.go | 3 +- snap/snapdir/snapdir.go | 5 +- snap/squashfs/squashfs.go | 5 +- snap/squashfs/squashfs_test.go | 6 +- snap/sysparams/sysparams.go | 4 +- snapdtool/cmdutil.go | 4 +- snapdtool/tool_linux_test.go | 3 +- store/auth.go | 3 +- store/auth_u1_test.go | 7 +-- store/cache.go | 17 +++++- store/store_action_fetch_assertions_test.go | 16 +++--- store/store_action_test.go | 57 +++++++++---------- store/store_download_test.go | 5 +- store/store_test.go | 25 ++++---- store/tooling/auth.go | 3 +- syscheck/squashfs.go | 7 +-- syscheck/version.go | 4 +- sysconfig/cloudinit.go | 7 +-- sysconfig/cloudinit_test.go | 3 +- systemd/systemd_test.go | 7 +-- .../fakestore/cmd/fakestore/cmd_new_repair.go | 4 +- .../cmd/fakestore/cmd_new_snap_decl.go | 4 +- .../cmd/fakestore/cmd_new_snap_rev.go | 4 +- tests/lib/fakestore/refresh/refresh.go | 3 +- tests/lib/fakestore/refresh/snap_asserts.go | 4 +- tests/lib/fakestore/store/store.go | 4 +- tests/lib/fakestore/store/store_test.go | 18 +++--- tests/lib/fde-setup-hook-v1/fde-setup.go | 4 +- tests/lib/fde-setup-hook/fde-setup.go | 5 +- tests/lib/muinstaller/main.go | 3 +- testutil/exec.go | 3 +- testutil/exec_test.go | 5 +- testutil/filecontentchecker.go | 6 +- testutil/lowlevel.go | 32 +++++++++-- testutil/lowlevel_test.go | 13 +++-- usersession/client/client_test.go | 4 +- wrappers/core18.go | 7 +-- wrappers/dbus.go | 3 +- wrappers/desktop.go | 3 +- wrappers/services.go | 3 +- wrappers/services_test.go | 9 ++- x11/xauth.go | 3 +- x11/xauth_test.go | 3 +- 199 files changed, 730 insertions(+), 771 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index c21c045612b..33ff97d445e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -83,7 +83,7 @@ linters-settings: # [deprecated] comma-separated list of pairs of the form pkg:regex # the regex is used to ignore names within pkg. (default "fmt:.*"). # see https://github.com/kisielk/errcheck#the-deprecated-method for details - ignore: fmt:.*,io/ioutil:^Read.* + ignore: fmt:.* # path to a file containing a list of functions to exclude from checking # see https://github.com/kisielk/errcheck#excluding-functions for details diff --git a/asserts/database_test.go b/asserts/database_test.go index 56299d86a49..8722791567b 100644 --- a/asserts/database_test.go +++ b/asserts/database_test.go @@ -25,7 +25,6 @@ import ( "encoding/base64" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -137,7 +136,7 @@ func (dbs *databaseSuite) TestImportKey(c *C) { c.Check(info.Mode().Perm(), Equals, os.FileMode(0600)) // secret // too much "clear box" testing? ok at least until we have // more functionality - privKey, err := ioutil.ReadFile(keyPath) + privKey, err := os.ReadFile(keyPath) c.Assert(err, IsNil) privKeyFromDisk, err := asserts.DecodePrivateKeyInTest(privKey) diff --git a/asserts/fsentryutils.go b/asserts/fsentryutils.go index 858405a459e..e33e9e90201 100644 --- a/asserts/fsentryutils.go +++ b/asserts/fsentryutils.go @@ -21,7 +21,6 @@ package asserts import ( "fmt" - "io/ioutil" "os" "path/filepath" @@ -66,7 +65,7 @@ func entryExists(top string, subpath ...string) bool { func readEntry(top string, subpath ...string) ([]byte, error) { fpath := filepath.Join(top, filepath.Join(subpath...)) - return ioutil.ReadFile(fpath) + return os.ReadFile(fpath) } func removeEntry(top string, subpath ...string) error { diff --git a/boot/flags.go b/boot/flags.go index 075ab862d91..a5988ab380e 100644 --- a/boot/flags.go +++ b/boot/flags.go @@ -22,7 +22,6 @@ package boot import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -224,7 +223,7 @@ func BootFlags(dev snap.Device) ([]string, error) { // bootenv are for this boot or the next one, but the initramfs will always // copy the flags that were set into /run, so we always know the current // boot's flags are written in /run - b, err := ioutil.ReadFile(snapBootFlagsFile) + b, err := os.ReadFile(snapBootFlagsFile) if err != nil { return nil, err } @@ -314,7 +313,7 @@ func HostUbuntuDataForMode(mode string, mod gadget.Model) ([]string, error) { // host mount is snap-bootstrap's /run/snapd/snap-bootstrap/degraded.json, so // we have to go parse that degradedJSONFile := filepath.Join(dirs.SnapBootstrapRunDir, "degraded.json") - b, err := ioutil.ReadFile(degradedJSONFile) + b, err := os.ReadFile(degradedJSONFile) if err != nil { return nil, err } diff --git a/boot/modeenv_test.go b/boot/modeenv_test.go index 4df101ac0ef..2281bc2279c 100644 --- a/boot/modeenv_test.go +++ b/boot/modeenv_test.go @@ -23,7 +23,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -209,7 +208,7 @@ base_status=try err = dupDiskModeenv.Write() c.Assert(err, IsNil) c.Assert(dirs.SnapModeenvFileUnder(s.tmpdir), testutil.FilePresent) - origBytes, err := ioutil.ReadFile(dirs.SnapModeenvFileUnder(s.tmpdir) + ".orig") + origBytes, err := os.ReadFile(dirs.SnapModeenvFileUnder(s.tmpdir) + ".orig") c.Assert(err, IsNil) // the files should be the same c.Assert(dirs.SnapModeenvFileUnder(s.tmpdir), testutil.FileEquals, string(origBytes)) diff --git a/bootloader/assets/genasset/main_test.go b/bootloader/assets/genasset/main_test.go index 7b12162e880..99027f51269 100644 --- a/bootloader/assets/genasset/main_test.go +++ b/bootloader/assets/genasset/main_test.go @@ -22,7 +22,6 @@ package main_test import ( "bytes" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -84,7 +83,7 @@ func (s *generateAssetsTestSuite) TestSimpleAsset(c *C) { c.Assert(err, IsNil) err = generate.Run("asset-name", filepath.Join(d, "in"), filepath.Join(d, "out")) c.Assert(err, IsNil) - data, err := ioutil.ReadFile(filepath.Join(d, "out")) + data, err := os.ReadFile(filepath.Join(d, "out")) c.Assert(err, IsNil) const exp = `// -*- Mode: Go; indent-tabs-mode: t -*- diff --git a/bootloader/assets/grub_test.go b/bootloader/assets/grub_test.go index 4cf5909663d..78583ec186b 100644 --- a/bootloader/assets/grub_test.go +++ b/bootloader/assets/grub_test.go @@ -22,7 +22,7 @@ package assets_test import ( "bytes" "fmt" - "io/ioutil" + "os" "testing" . "gopkg.in/check.v1" @@ -160,7 +160,7 @@ func (s *grubAssetsTestSuite) TestGrubAssetsWereRegenerated(c *C) { } { assetData := assets.Internal(tc.asset) c.Assert(assetData, NotNil) - data, err := ioutil.ReadFile(tc.file) + data, err := os.ReadFile(tc.file) c.Assert(err, IsNil) c.Check(assetData, DeepEquals, data, Commentf("asset %q has not been updated", tc.asset)) } diff --git a/bootloader/efi/efi.go b/bootloader/efi/efi.go index da89d18bb1c..72bf43fdeb8 100644 --- a/bootloader/efi/efi.go +++ b/bootloader/efi/efi.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "unicode/utf16" @@ -113,7 +112,7 @@ func ReadVarBytes(name string) ([]byte, VariableAttr, error) { return nil, 0, cannotReadError(name, err) } defer varf.Close() - b, err := ioutil.ReadAll(varf) + b, err := io.ReadAll(varf) if err != nil { return nil, 0, cannotReadError(name, err) } @@ -173,7 +172,7 @@ func MockVars(vars map[string][]byte, attrs map[string]VariableAttr) (restore fu if !ok { attr = VariableRuntimeAccess | VariableBootServiceAccess } - return ioutil.NopCloser(bytes.NewBuffer(val)), attr, int64(len(val)), nil + return io.NopCloser(bytes.NewBuffer(val)), attr, int64(len(val)), nil } return nil, 0, 0, fmt.Errorf("EFI variable %s not mocked", name) } diff --git a/bootloader/grubenv/grubenv.go b/bootloader/grubenv/grubenv.go index 547d3bea86e..46a8e621d06 100644 --- a/bootloader/grubenv/grubenv.go +++ b/bootloader/grubenv/grubenv.go @@ -22,7 +22,6 @@ package grubenv import ( "bytes" "fmt" - "io/ioutil" "os" "github.com/snapcore/snapd/strutil" @@ -56,7 +55,7 @@ func (g *Env) Set(key, value string) { } func (g *Env) Load() error { - buf, err := ioutil.ReadFile(g.path) + buf, err := os.ReadFile(g.path) if err != nil { return err } diff --git a/bootloader/lk.go b/bootloader/lk.go index 5ad3ea46e0c..188374f4719 100644 --- a/bootloader/lk.go +++ b/bootloader/lk.go @@ -22,7 +22,6 @@ package bootloader import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" @@ -444,7 +443,7 @@ func (l *lk) ExtractKernelAssets(s snap.PlaceInfo, snapf snap.Container) error { // this is live system, extracted bootimg needs to be flashed to // free bootimg partition and env has to be updated with // new kernel snap to bootimg partition mapping - tmpdir, err := ioutil.TempDir("", "bootimg") + tmpdir, err := os.MkdirTemp("", "bootimg") if err != nil { return fmt.Errorf("cannot create temp directory: %v", err) } diff --git a/bootloader/lk_test.go b/bootloader/lk_test.go index 3fa7cf47f21..404748e32f6 100644 --- a/bootloader/lk_test.go +++ b/bootloader/lk_test.go @@ -21,7 +21,6 @@ package bootloader_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -259,7 +258,7 @@ func (s *lkTestSuite) TestExtractKernelAssetsUnpacksBootimgImageBuilding(c *C) { c.Assert(err, IsNil) // just boot.img and snapbootsel.bin are there, no kernel.img - infos, err := ioutil.ReadDir(filepath.Join(s.rootdir, "boot", "lk", "")) + infos, err := os.ReadDir(filepath.Join(s.rootdir, "boot", "lk", "")) c.Assert(err, IsNil) var fnames []string for _, info := range infos { @@ -367,13 +366,13 @@ func (s *lkTestSuite) TestExtractKernelAssetsUnpacksAndRemoveInRuntimeMode(c *C) // and validate it went to the "boot_a" partition bootA := filepath.Join(s.rootdir, "/dev/disk/by-partlabel/boot_a") - content, err := ioutil.ReadFile(bootA) + content, err := os.ReadFile(bootA) c.Assert(err, IsNil) c.Assert(string(content), Equals, "I'm the default boot image name") // also validate that bootB is empty bootB := filepath.Join(s.rootdir, "/dev/disk/by-partlabel/boot_b") - content, err = ioutil.ReadFile(bootB) + content, err = os.ReadFile(bootB) c.Assert(err, IsNil) c.Assert(content, HasLen, 0) @@ -451,7 +450,7 @@ func (s *lkTestSuite) TestExtractKernelAssetsUnpacksAndRemoveInRuntimeModeUC20(c bootAPartUUID, err := disk.FindMatchingPartitionUUIDWithPartLabel("boot_a") c.Assert(err, IsNil) bootA := filepath.Join(s.rootdir, "/dev/disk/by-partuuid", bootAPartUUID) - content, err := ioutil.ReadFile(bootA) + content, err := os.ReadFile(bootA) c.Assert(err, IsNil) c.Assert(string(content), Equals, "I'm the default boot image name") @@ -459,7 +458,7 @@ func (s *lkTestSuite) TestExtractKernelAssetsUnpacksAndRemoveInRuntimeModeUC20(c bootBPartUUID, err := disk.FindMatchingPartitionUUIDWithPartLabel("boot_b") c.Assert(err, IsNil) bootB := filepath.Join(s.rootdir, "/dev/disk/by-partuuid", bootBPartUUID) - content, err = ioutil.ReadFile(bootB) + content, err = os.ReadFile(bootB) c.Assert(err, IsNil) c.Assert(content, HasLen, 0) diff --git a/bootloader/piboot.go b/bootloader/piboot.go index f040c3aff11..0ee34b118ca 100644 --- a/bootloader/piboot.go +++ b/bootloader/piboot.go @@ -22,7 +22,6 @@ package bootloader import ( "encoding/binary" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -238,7 +237,7 @@ func (p *piboot) loadAndApplyConfig(env *ubootenv.Env) error { // Writes os_prefix in RPi config.txt or tryboot.txt func (p *piboot) writeRPiCfgWithOsPrefix(prefix, inFile, outFile string) error { - buf, err := ioutil.ReadFile(inFile) + buf, err := os.ReadFile(inFile) if err != nil { return err } @@ -268,7 +267,7 @@ func (p *piboot) writeRPiCfgWithOsPrefix(prefix, inFile, outFile string) error { } func (p *piboot) writeCmdline(env *ubootenv.Env, defaultsFile, outFile string) error { - buf, err := ioutil.ReadFile(defaultsFile) + buf, err := os.ReadFile(defaultsFile) if err != nil { return err } @@ -390,7 +389,7 @@ func (p *piboot) eepromVersionSupportsTryboot() (bool, error) { // To find out the EEPROM version we do the same as the // rpi-eeprom-update script (see // https://github.com/raspberrypi/rpi-eeprom/blob/master/rpi-eeprom-update) - buf, err := ioutil.ReadFile(rpi4EepromTimeStampPath) + buf, err := os.ReadFile(rpi4EepromTimeStampPath) if err != nil { return false, err } @@ -408,7 +407,7 @@ func (p *piboot) eepromVersionSupportsTryboot() (bool, error) { func (p *piboot) isRaspberryPi4() bool { // For RPi4 detection we do the same as the rpi-eeprom-update script (see // https://github.com/raspberrypi/rpi-eeprom/blob/master/rpi-eeprom-update) - buf, err := ioutil.ReadFile(rpi4RevisionCodesPath) + buf, err := os.ReadFile(rpi4RevisionCodesPath) if err != nil { return false } diff --git a/bootloader/piboot_test.go b/bootloader/piboot_test.go index b4329583d98..8d54c412310 100644 --- a/bootloader/piboot_test.go +++ b/bootloader/piboot_test.go @@ -20,7 +20,6 @@ package bootloader_test import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -155,7 +154,7 @@ func (s *pibootTestSuite) testExtractKernelAssets(c *C, dtbDir string) { snapf, err := snapfile.Open(fn) c.Assert(err, IsNil) - assetsDir, err := ioutil.TempDir("", "kernel-assets") + assetsDir, err := os.MkdirTemp("", "kernel-assets") c.Assert(err, IsNil) defer os.RemoveAll(assetsDir) @@ -313,7 +312,7 @@ func (s *pibootTestSuite) TestCreateConfig(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } @@ -347,7 +346,7 @@ func (s *pibootTestSuite) TestCreateTrybootCfg(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } @@ -376,7 +375,7 @@ func (s *pibootTestSuite) TestCreateTrybootCfg(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } @@ -418,7 +417,7 @@ func (s *pibootTestSuite) TestCreateConfigCurrentNotEmpty(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } @@ -449,7 +448,7 @@ func (s *pibootTestSuite) TestCreateConfigCurrentNotEmpty(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } @@ -487,7 +486,7 @@ func (s *pibootTestSuite) TestOnlyOneOsPrefix(c *C) { }, } for _, fInfo := range files { - readData, err := ioutil.ReadFile(fInfo.path) + readData, err := os.ReadFile(fInfo.path) c.Assert(err, IsNil) c.Assert(string(readData), Equals, fInfo.data) } diff --git a/bootloader/ubootenv/env.go b/bootloader/ubootenv/env.go index f348343a5d8..ccf889c7b70 100644 --- a/bootloader/ubootenv/env.go +++ b/bootloader/ubootenv/env.go @@ -27,7 +27,6 @@ import ( "fmt" "hash/crc32" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -110,7 +109,7 @@ func OpenWithFlags(fname string, flags OpenFlags) (*Env, error) { } defer f.Close() - contentWithHeader, err := ioutil.ReadAll(f) + contentWithHeader, err := io.ReadAll(f) if err != nil { return nil, err } diff --git a/bootloader/ubootenv/env_test.go b/bootloader/ubootenv/env_test.go index 33e55d1998d..188dfc75ab3 100644 --- a/bootloader/ubootenv/env_test.go +++ b/bootloader/ubootenv/env_test.go @@ -22,7 +22,7 @@ package ubootenv_test import ( "bytes" "hash/crc32" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -302,7 +302,7 @@ func (u *uenvTestSuite) TestWritesEmptyFileWithDoubleNewline(c *C) { r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc @@ -330,7 +330,7 @@ func (u *uenvTestSuite) TestWritesEmptyFileWithDoubleNewlineNoHeaderFlagByte(c * r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc @@ -360,7 +360,7 @@ func (u *uenvTestSuite) TestWritesContentCorrectly(c *C) { r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc @@ -399,7 +399,7 @@ func (u *uenvTestSuite) TestWritesContentCorrectlyNoHeaderFlagByte(c *C) { r, err := os.Open(u.envFile) c.Assert(err, IsNil) defer r.Close() - content, err := ioutil.ReadAll(r) + content, err := io.ReadAll(r) c.Assert(err, IsNil) c.Assert(content, DeepEquals, []byte{ // crc diff --git a/bootloader/withbootassettesting.go b/bootloader/withbootassettesting.go index 78559ddca0e..c66a29e5422 100644 --- a/bootloader/withbootassettesting.go +++ b/bootloader/withbootassettesting.go @@ -23,7 +23,6 @@ package bootloader import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -59,7 +58,7 @@ func MaybeInjectTestingBootloaderAssets() { panic(fmt.Sprintf("cannot readlink: %v", err)) } - injectPieceRaw, err := ioutil.ReadFile(filepath.Join(filepath.Dir(selfExe), "bootassetstesting")) + injectPieceRaw, err := os.ReadFile(filepath.Join(filepath.Dir(selfExe), "bootassetstesting")) if os.IsNotExist(err) { logger.Noticef("no boot asset testing marker") return diff --git a/client/aspects_test.go b/client/aspects_test.go index 1f14f22ea87..270c07f0cda 100644 --- a/client/aspects_test.go +++ b/client/aspects_test.go @@ -21,7 +21,7 @@ package client_test import ( "encoding/json" - "io/ioutil" + "io" "net/url" . "gopkg.in/check.v1" @@ -50,7 +50,7 @@ func (cs *clientSuite) TestAspectSet(c *C) { c.Check(cs.reqs[0].Method, Equals, "PUT") c.Check(cs.reqs[0].Header.Get("Content-Type"), Equals, "application/json") c.Check(cs.reqs[0].URL.Path, Equals, "/v2/aspects/a/b/c") - data, err := ioutil.ReadAll(cs.reqs[0].Body) + data, err := io.ReadAll(cs.reqs[0].Body) c.Assert(err, IsNil) // need to decode because entries may have been encoded in any order diff --git a/client/asserts_test.go b/client/asserts_test.go index a1e08ac26e1..1e532ae1795 100644 --- a/client/asserts_test.go +++ b/client/asserts_test.go @@ -21,7 +21,7 @@ package client_test import ( "errors" - "io/ioutil" + "io" "net/http" "net/url" @@ -41,7 +41,7 @@ func (cs *clientSuite) TestClientAssert(c *C) { a := []byte("Assertion.") err := cs.cli.Ack(a) c.Assert(err, IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) c.Check(body, DeepEquals, a) c.Check(cs.req.Method, Equals, "POST") diff --git a/client/change_test.go b/client/change_test.go index 7652d30d52d..e0fe3231201 100644 --- a/client/change_test.go +++ b/client/change_test.go @@ -20,7 +20,7 @@ package client_test import ( - "io/ioutil" + "io" "time" "gopkg.in/check.v1" @@ -227,7 +227,7 @@ func (cs *clientSuite) TestClientAbort(c *check.C) { ReadyTime: time.Date(2016, 04, 21, 1, 2, 4, 0, time.UTC), }) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Equals, "{\"action\":\"abort\"}\n") diff --git a/client/client.go b/client/client.go index 7e103529237..22385191a76 100644 --- a/client/client.go +++ b/client/client.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -438,7 +437,7 @@ func decodeInto(reader io.Reader, v interface{}) error { dec := json.NewDecoder(reader) if err := dec.Decode(v); err != nil { r := dec.Buffered() - buf, err1 := ioutil.ReadAll(r) + buf, err1 := io.ReadAll(r) if err1 != nil { buf = []byte(fmt.Sprintf("error reading buffered response body: %s", err1)) } diff --git a/client/client_test.go b/client/client_test.go index f953f130910..ae7a50db4a9 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -136,7 +135,7 @@ func (cs *clientSuite) TestClientDoReportsErrors(c *C) { func (cs *clientSuite) TestClientWorks(c *C) { var v []int cs.rsp = `[1,2]` - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) statusCode, err := cs.cli.Do("GET", "/this", nil, reqBody, &v, nil) c.Check(err, IsNil) c.Check(statusCode, Equals, 200) @@ -188,7 +187,7 @@ func (cs *clientSuite) TestClientDoNoTimeoutIgnoresRetry(c *C) { var v []int cs.rsp = `[1,2]` cs.err = fmt.Errorf("borken") - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) doOpts := &client.DoOptions{ // Timeout is unset, thus 0, and thus we ignore the retry and only run // once even though there is an error @@ -202,7 +201,7 @@ func (cs *clientSuite) TestClientDoNoTimeoutIgnoresRetry(c *C) { func (cs *clientSuite) TestClientDoRetryValidation(c *C) { var v []int cs.rsp = `[1,2]` - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) doOpts := &client.DoOptions{ Retry: time.Duration(-1), Timeout: time.Duration(time.Minute), @@ -213,7 +212,7 @@ func (cs *clientSuite) TestClientDoRetryValidation(c *C) { } func (cs *clientSuite) TestClientDoRetryWorks(c *C) { - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) cs.err = fmt.Errorf("borken") doOpts := &client.DoOptions{ Retry: time.Duration(time.Millisecond), @@ -228,7 +227,7 @@ func (cs *clientSuite) TestClientDoRetryWorks(c *C) { } func (cs *clientSuite) TestClientOnlyRetryAppropriateErrors(c *C) { - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) doOpts := &client.DoOptions{ Retry: time.Millisecond, Timeout: 1 * time.Minute, @@ -251,7 +250,7 @@ func (cs *clientSuite) TestClientUnderstandsStatusCode(c *C) { var v []int cs.status = 202 cs.rsp = `[1,2]` - reqBody := ioutil.NopCloser(strings.NewReader("")) + reqBody := io.NopCloser(strings.NewReader("")) statusCode, err := cs.cli.Do("GET", "/this", nil, reqBody, &v, nil) c.Check(err, IsNil) c.Check(statusCode, Equals, 202) @@ -559,7 +558,7 @@ func (cs *clientSuite) TestParseError(c *C) { resp = &http.Response{ Status: "400 Bad Request", Header: h, - Body: ioutil.NopCloser(strings.NewReader(`{ + Body: io.NopCloser(strings.NewReader(`{ "status-code": 400, "type": "error", "result": { @@ -573,7 +572,7 @@ func (cs *clientSuite) TestParseError(c *C) { resp = &http.Response{ Status: "400 Bad Request", Header: h, - Body: ioutil.NopCloser(strings.NewReader("{}")), + Body: io.NopCloser(strings.NewReader("{}")), } err = client.ParseErrorInTest(resp) c.Check(err, ErrorMatches, `server error: "400 Bad Request"`) @@ -614,7 +613,7 @@ func (cs *clientSuite) TestDebugEnsureStateSoon(c *C) { c.Check(cs.reqs, HasLen, 1) c.Check(cs.reqs[0].Method, Equals, "POST") c.Check(cs.reqs[0].URL.Path, Equals, "/v2/debug") - data, err := ioutil.ReadAll(cs.reqs[0].Body) + data, err := io.ReadAll(cs.reqs[0].Body) c.Assert(err, IsNil) c.Check(data, DeepEquals, []byte(`{"action":"ensure-state-soon"}`)) } @@ -629,7 +628,7 @@ func (cs *clientSuite) TestDebugGeneric(c *C) { c.Check(cs.reqs, HasLen, 1) c.Check(cs.reqs[0].Method, Equals, "POST") c.Check(cs.reqs[0].URL.Path, Equals, "/v2/debug") - data, err := ioutil.ReadAll(cs.reqs[0].Body) + data, err := io.ReadAll(cs.reqs[0].Body) c.Assert(err, IsNil) c.Check(string(data), DeepEquals, `{"action":"do-something","params":["param1","param2"]}`) } @@ -659,7 +658,7 @@ func (cs *clientSuite) TestDebugMigrateHome(c *C) { c.Check(cs.reqs, HasLen, 1) c.Check(cs.reqs[0].Method, Equals, "POST") c.Check(cs.reqs[0].URL.Path, Equals, "/v2/debug") - data, err := ioutil.ReadAll(cs.reqs[0].Body) + data, err := io.ReadAll(cs.reqs[0].Body) c.Assert(err, IsNil) c.Check(string(data), Equals, `{"action":"migrate-home","snaps":["foo","bar"]}`) } diff --git a/client/cohort_test.go b/client/cohort_test.go index 1751104dee6..564c84a80f8 100644 --- a/client/cohort_test.go +++ b/client/cohort_test.go @@ -22,7 +22,7 @@ package client_test import ( "encoding/json" "errors" - "io/ioutil" + "io" "golang.org/x/xerrors" "gopkg.in/check.v1" @@ -33,7 +33,7 @@ func (cs *clientSuite) TestClientCreateCohortsEndpoint(c *check.C) { c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/cohorts") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var jsonBody map[string]interface{} err = json.Unmarshal(body, &jsonBody) @@ -57,7 +57,7 @@ func (cs *clientSuite) TestClientCreateCohorts(c *check.C) { "bar": "what-what", }) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var jsonBody map[string]interface{} err = json.Unmarshal(body, &jsonBody) diff --git a/client/icons.go b/client/icons.go index b2b4810712f..9c63f809ca5 100644 --- a/client/icons.go +++ b/client/icons.go @@ -22,7 +22,7 @@ package client import ( "context" "fmt" - "io/ioutil" + "io" "regexp" "golang.org/x/xerrors" @@ -58,7 +58,7 @@ func (c *Client) Icon(pkgID string) (*Icon, error) { return nil, fmt.Errorf("%s: cannot determine filename", errPrefix) } - content, err := ioutil.ReadAll(response.Body) + content, err := io.ReadAll(response.Body) if err != nil { return nil, fmt.Errorf("%s: %s", errPrefix, err) } diff --git a/client/model_test.go b/client/model_test.go index 4c2a60341d9..5c562472133 100644 --- a/client/model_test.go +++ b/client/model_test.go @@ -23,7 +23,6 @@ import ( "encoding/json" "errors" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -127,7 +126,7 @@ func (cs *clientSuite) TestClientRemodel(c *C) { c.Check(id, Equals, "d728") c.Assert(cs.req.Header.Get("Content-Type"), Equals, "application/json") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -235,7 +234,7 @@ func (cs *clientSuite) TestClientOfflineRemodel(c *C) { c.Assert(len(matches), Equals, 2) boundary := "--" + matches[1] - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) expected := boundary + ` Content-Disposition: form-data; name="new-model" diff --git a/client/quota_test.go b/client/quota_test.go index e905ac9ee92..579844bb511 100644 --- a/client/quota_test.go +++ b/client/quota_test.go @@ -22,7 +22,7 @@ package client_test import ( "bytes" "encoding/json" - "io/ioutil" + "io" "time" "gopkg.in/check.v1" @@ -79,7 +79,7 @@ func (cs *clientSuite) TestEnsureQuotaGroup(c *check.C) { c.Assert(chgID, check.Equals, "42") c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/quotas") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = jsonutil.DecodeWithNumber(bytes.NewReader(body), &req) @@ -175,7 +175,7 @@ func (cs *clientSuite) TestRemoveQuotaGroup(c *check.C) { c.Assert(chgID, check.Equals, "42") c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/quotas") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) diff --git a/client/snap_op_test.go b/client/snap_op_test.go index 0ae596a3bd7..cb4d614054e 100644 --- a/client/snap_op_test.go +++ b/client/snap_op_test.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime" "mime/multipart" "net/http" @@ -150,7 +149,7 @@ func (cs *clientSuite) TestClientOpSnap(c *check.C) { _, ok := cs.req.Context().Deadline() c.Check(ok, check.Equals, true) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil, check.Commentf(s.action)) jsonBody := make(map[string]string) err = json.Unmarshal(body, &jsonBody) @@ -178,7 +177,7 @@ func (cs *clientSuite) TestClientMultiOpSnap(c *check.C) { c.Assert(cs.req.Header.Get("Content-Type"), check.Equals, "application/json", check.Commentf(s.action)) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil, check.Commentf(s.action)) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -207,7 +206,7 @@ func (cs *clientSuite) TestClientMultiOpSnapTransactional(c *check.C) { c.Assert(cs.req.Header.Get("Content-Type"), check.Equals, "application/json", check.Commentf(s.action)) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil, check.Commentf(s.action)) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -238,7 +237,7 @@ func (cs *clientSuite) TestClientMultiOpSnapIgnoreRunning(c *check.C) { c.Assert(cs.req.Header.Get("Content-Type"), check.Equals, "application/json", check.Commentf(s.action)) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil, check.Commentf(s.action)) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -267,7 +266,7 @@ func (cs *clientSuite) TestClientMultiSnapshot(c *check.C) { c.Assert(err, check.IsNil) c.Check(cs.req.Header.Get("Content-Type"), check.Equals, "application/json") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -296,7 +295,7 @@ func (cs *clientSuite) TestClientOpInstallPath(c *check.C) { id, err := cs.cli.InstallPath(snap, "", nil) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), testutil.Contains, "\r\nsnap-data\r\n") @@ -326,7 +325,7 @@ func (cs *clientSuite) TestClientOpInstallPathIgnoreRunning(c *check.C) { id, err := cs.cli.InstallPath(snap, "", &client.SnapOptions{IgnoreRunning: true}) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, "(?s).*\r\nsnap-data\r\n.*") @@ -357,7 +356,7 @@ func (cs *clientSuite) TestClientOpInstallPathInstance(c *check.C) { id, err := cs.cli.InstallPath(snap, "foo_bar", nil) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, "(?s).*\r\nsnap-data\r\n.*") @@ -389,7 +388,7 @@ func (cs *clientSuite) TestClientOpInstallPathMany(c *check.C) { id, err := cs.cli.InstallPathMany(paths, nil) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) for _, name := range names { @@ -426,7 +425,7 @@ func (cs *clientSuite) TestClientOpInstallPathManyTransactionally(c *check.C) { id, err := cs.cli.InstallPathMany(paths, &client.SnapOptions{Transaction: client.TransactionAllSnaps}) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) for _, name := range names { @@ -469,7 +468,7 @@ func (cs *clientSuite) TestClientOpInstallPathManyWithOptions(c *check.C) { c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Check(string(body), check.Matches, `(?s).*Content-Disposition: form-data; name="dangerous"\r\n\r\ntrue\r\n.*`) @@ -500,7 +499,7 @@ func (cs *clientSuite) TestClientOpInstallPathManyWithQuotaGroup(c *check.C) { c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Check(string(body), check.Matches, `(?s).*Content-Disposition: form-data; name="dangerous"\r\n\r\ntrue\r\n.*`) @@ -528,7 +527,7 @@ func (cs *clientSuite) TestClientOpInstallDangerous(c *check.C) { _, err = cs.cli.InstallPath(snap, "", &opts) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, "(?s).*Content-Disposition: form-data; name=\"dangerous\"\r\n\r\ntrue\r\n.*") @@ -562,7 +561,7 @@ func (cs *clientSuite) TestClientOpInstallUnaliased(c *check.C) { _, err = cs.cli.Install("foo", &opts) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -572,7 +571,7 @@ func (cs *clientSuite) TestClientOpInstallUnaliased(c *check.C) { _, err = cs.cli.InstallPath(snap, "", &opts) c.Assert(err, check.IsNil) - body, err = ioutil.ReadAll(cs.req.Body) + body, err = io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, "(?s).*Content-Disposition: form-data; name=\"unaliased\"\r\n\r\ntrue\r\n.*") @@ -598,7 +597,7 @@ func (cs *clientSuite) TestClientOpInstallTransactional(c *check.C) { _, err = cs.cli.InstallMany([]string{"foo", "bar"}, &opts) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) jsonBody := make(map[string]interface{}) err = json.Unmarshal(body, &jsonBody) @@ -609,7 +608,7 @@ func (cs *clientSuite) TestClientOpInstallTransactional(c *check.C) { _, err = cs.cli.InstallPath(snap, "", &opts) c.Assert(err, check.IsNil) - body, err = ioutil.ReadAll(cs.req.Body) + body, err = io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, @@ -636,7 +635,7 @@ func (cs *clientSuite) TestClientOpInstallPrefer(c *check.C) { _, err = cs.cli.Install("foo", &opts) c.Assert(err, check.IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var jsonBody map[string]interface{} err = json.Unmarshal(body, &jsonBody) @@ -646,7 +645,7 @@ func (cs *clientSuite) TestClientOpInstallPrefer(c *check.C) { _, err = cs.cli.InstallPath(snap, "", &opts) c.Assert(err, check.IsNil) - body, err = ioutil.ReadAll(cs.req.Body) + body, err = io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Assert(string(body), check.Matches, "(?s).*Content-Disposition: form-data; name=\"prefer\"\r\n\r\ntrue\r\n.*") @@ -660,7 +659,7 @@ func formToMap(c *check.C, mr *multipart.Reader) map[string]string { break } c.Assert(err, check.IsNil) - slurp, err := ioutil.ReadAll(p) + slurp, err := io.ReadAll(p) c.Assert(err, check.IsNil) formData[p.FormName()] = string(slurp) } @@ -779,7 +778,7 @@ func (cs *clientSuite) TestClientOpDownload(c *check.C) { // check we posted the right stuff c.Assert(cs.req.Header.Get("Content-Type"), check.Equals, "application/json") c.Assert(cs.req.Header.Get("range"), check.Equals, "") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var jsonBody client.DownloadAction err = json.Unmarshal(body, &jsonBody) @@ -790,7 +789,7 @@ func (cs *clientSuite) TestClientOpDownload(c *check.C) { c.Check(jsonBody.HeaderPeek, check.Equals, true) // ensure we can read the response - content, err := ioutil.ReadAll(rc) + content, err := io.ReadAll(rc) c.Assert(err, check.IsNil) c.Check(string(content), check.Equals, cs.rsp) // and we can close it @@ -827,7 +826,7 @@ func (cs *clientSuite) TestClientOpDownloadResume(c *check.C) { // check we posted the right stuff c.Assert(cs.req.Header.Get("Content-Type"), check.Equals, "application/json") c.Assert(cs.req.Header.Get("range"), check.Equals, "bytes: 64-") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var jsonBody client.DownloadAction err = json.Unmarshal(body, &jsonBody) @@ -839,7 +838,7 @@ func (cs *clientSuite) TestClientOpDownloadResume(c *check.C) { c.Check(jsonBody.ResumeToken, check.Equals, "some-token") // ensure we can read the response - content, err := ioutil.ReadAll(rc) + content, err := io.ReadAll(rc) c.Assert(err, check.IsNil) c.Check(string(content), check.Equals, cs.rsp) // and we can close it @@ -865,7 +864,7 @@ func (cs *clientSuite) TestClientRefreshWithValidationSets(c *check.C) { ValidationSets []string `json:"validation-sets"` Action string `json:"action"` } - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var decodedBody req @@ -900,7 +899,7 @@ func (cs *clientSuite) TestClientHoldMany(c *check.C) { Time string `json:"time"` HoldLevel string `json:"hold-level"` } - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var decodedBody req diff --git a/client/snapctl.go b/client/snapctl.go index d0a8f5a172b..b109958224f 100644 --- a/client/snapctl.go +++ b/client/snapctl.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" ) // InternalSnapctlCmdNeedsStdin returns true if the given snapctl command @@ -72,7 +71,7 @@ func (client *Client) RunSnapctl(options *SnapCtlOptions, stdin io.Reader) (stdo var stdinData []byte if stdin != nil { limitedStdin := &io.LimitedReader{R: stdin, N: stdinReadLimit + 1} - stdinData, err = ioutil.ReadAll(limitedStdin) + stdinData, err = io.ReadAll(limitedStdin) if err != nil { return nil, nil, fmt.Errorf("cannot read stdin: %v", err) } diff --git a/client/snapshot_test.go b/client/snapshot_test.go index 33218a708ec..eed5f24b9ae 100644 --- a/client/snapshot_test.go +++ b/client/snapshot_test.go @@ -21,7 +21,7 @@ package client_test import ( "crypto/sha256" - "io/ioutil" + "io" "net/http" "net/url" "strconv" @@ -185,7 +185,7 @@ func (cs *clientSuite) TestClientExportSnapshot(c *check.C) { } if t.status == 200 { - buf, err := ioutil.ReadAll(r) + buf, err := io.ReadAll(r) c.Assert(err, check.IsNil) c.Assert(string(buf), check.Equals, t.content) } @@ -223,7 +223,7 @@ func (cs *clientSuite) TestClientSnapshotImport(c *check.C) { c.Assert(cs.req.Header.Get("Content-Length"), check.Equals, strconv.Itoa(len(fakeSnapshotData))) c.Check(importSet.ID, check.Equals, t.setID, comm) c.Check(importSet.Snaps, check.DeepEquals, []string{"baz", "bar", "foo"}, comm) - d, err := ioutil.ReadAll(cs.req.Body) + d, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) c.Check(string(d), check.Equals, fakeSnapshotData) } diff --git a/client/systems_test.go b/client/systems_test.go index 52b6e81eabc..3a8ef1a55fc 100644 --- a/client/systems_test.go +++ b/client/systems_test.go @@ -21,7 +21,7 @@ package client_test import ( "encoding/json" - "io/ioutil" + "io" "gopkg.in/check.v1" @@ -140,7 +140,7 @@ func (cs *clientSuite) TestRequestSystemActionHappy(c *check.C) { c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/systems/1234") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) @@ -182,7 +182,7 @@ func (cs *clientSuite) TestRequestSystemRebootHappy(c *check.C) { c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/systems/20201212") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) @@ -377,7 +377,7 @@ func (cs *clientSuite) TestRequestSystemInstallHappy(c *check.C) { c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/systems/1234") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) diff --git a/client/users_test.go b/client/users_test.go index 56aae3e978d..aef019e1244 100644 --- a/client/users_test.go +++ b/client/users_test.go @@ -20,7 +20,7 @@ package client_test import ( - "io/ioutil" + "io" . "gopkg.in/check.v1" @@ -46,7 +46,7 @@ func (cs *clientSuite) TestClientRemoveUser(c *C) { {ID: 11, Username: "one-user", Email: "user@test.com"}, }) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) c.Assert(string(body), Equals, `{"action":"remove","username":"one-user"}`) } @@ -69,7 +69,7 @@ func (cs *clientSuite) TestClientRemoveUserError(c *C) { c.Assert(err, ErrorMatches, "no can do") c.Assert(removed, IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) c.Assert(string(body), Equals, `{"action":"remove","username":"one-user"}`) } @@ -92,7 +92,7 @@ func (cs *clientSuite) TestClientCreateUser(c *C) { c.Assert(cs.req.URL.Path, Equals, "/v2/users") c.Assert(err, IsNil) - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, IsNil) c.Assert(string(body), Equals, `{"action":"create","email":"one@email.com","sudoer":true,"known":true}`) @@ -170,7 +170,7 @@ func (cs *clientSuite) TestClientCreateUsers(c *C) { for _, req := range cs.reqs { c.Assert(req.Method, Equals, "POST") c.Assert(req.URL.Path, Equals, "/v2/users") - data, err := ioutil.ReadAll(req.Body) + data, err := io.ReadAll(req.Body) c.Assert(err, IsNil) bodies = append(bodies, string(data)) } diff --git a/client/validate_test.go b/client/validate_test.go index ba96c77f134..233a251aa76 100644 --- a/client/validate_test.go +++ b/client/validate_test.go @@ -21,7 +21,7 @@ package client_test import ( "encoding/json" - "io/ioutil" + "io" "net/url" "gopkg.in/check.v1" @@ -96,7 +96,7 @@ func (cs *clientSuite) TestApplyValidationSetMonitor(c *check.C) { }) c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/validation-sets/foo/bar") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) @@ -126,7 +126,7 @@ func (cs *clientSuite) TestApplyValidationSetEnforce(c *check.C) { }) c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/validation-sets/foo/bar") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) @@ -164,7 +164,7 @@ func (cs *clientSuite) TestForgetValidationSet(c *check.C) { c.Assert(cs.cli.ForgetValidationSet("foo", "bar", 3), check.IsNil) c.Check(cs.req.Method, check.Equals, "POST") c.Check(cs.req.URL.Path, check.Equals, "/v2/validation-sets/foo/bar") - body, err := ioutil.ReadAll(cs.req.Body) + body, err := io.ReadAll(cs.req.Body) c.Assert(err, check.IsNil) var req map[string]interface{} err = json.Unmarshal(body, &req) diff --git a/cmd/snap-bootstrap/cmd_initramfs_mounts.go b/cmd/snap-bootstrap/cmd_initramfs_mounts.go index 7847b3e11e9..6b6c3eadb8e 100644 --- a/cmd/snap-bootstrap/cmd_initramfs_mounts.go +++ b/cmd/snap-bootstrap/cmd_initramfs_mounts.go @@ -25,7 +25,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -1182,7 +1181,7 @@ func (m *recoverModeStateMachine) unlockEncryptedSaveRunKey() (stateFunc, error) // to get to this state, we needed to have mounted ubuntu-data on host, so // if encrypted, we can try to read the run key from host ubuntu-data saveKey := device.SaveKeyUnder(dirs.SnapFDEDirUnder(boot.InitramfsHostWritableDir(m.model))) - key, err := ioutil.ReadFile(saveKey) + key, err := os.ReadFile(saveKey) if err != nil { // log the error and skip to trying the fallback key m.degradedState.LogErrorf("cannot access run ubuntu-save key: %v", err) @@ -1774,7 +1773,7 @@ func maybeMountSave(disk disks.Disk, rootdir string, encrypted bool, mountOpts * return false, fmt.Errorf("cannot find ubuntu-save encryption key at %v", saveKey) } // we have save.key, volume exists and is encrypted - key, err := ioutil.ReadFile(saveKey) + key, err := os.ReadFile(saveKey) if err != nil { return true, err } diff --git a/cmd/snap-bootstrap/cmd_initramfs_mounts_test.go b/cmd/snap-bootstrap/cmd_initramfs_mounts_test.go index 77f5d1e8aa9..8ddac8566d4 100644 --- a/cmd/snap-bootstrap/cmd_initramfs_mounts_test.go +++ b/cmd/snap-bootstrap/cmd_initramfs_mounts_test.go @@ -23,7 +23,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -3774,7 +3773,7 @@ func (s *initramfsMountsSuite) TestInitramfsMountsRecoverModeHappyEncrypted(c *C } func checkDegradedJSON(c *C, name string, exp map[string]interface{}) { - b, err := ioutil.ReadFile(filepath.Join(dirs.SnapBootstrapRunDir, name)) + b, err := os.ReadFile(filepath.Join(dirs.SnapBootstrapRunDir, name)) c.Assert(err, IsNil) degradedJSONObj := make(map[string]interface{}) err = json.Unmarshal(b, °radedJSONObj) @@ -8229,7 +8228,7 @@ echo '{"features":[]}' {"fde-setup"}, }) - fdeSetupInput, err := ioutil.ReadFile(filepath.Join(s.tmpDir, "fde-setup.input")) + fdeSetupInput, err := os.ReadFile(filepath.Join(s.tmpDir, "fde-setup.input")) c.Assert(err, IsNil) c.Assert(fdeSetupInput, DeepEquals, []byte(`{"op":"features"}`)) diff --git a/cmd/snap-failure/cmd_snapd.go b/cmd/snap-failure/cmd_snapd.go index fdd3fdad4ea..1892e728f9d 100644 --- a/cmd/snap-failure/cmd_snapd.go +++ b/cmd/snap-failure/cmd_snapd.go @@ -23,7 +23,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -64,7 +63,7 @@ var errNoPrevious = errors.New("no revision to go back to") func prevRevision(snapName string) (string, error) { seqFile := filepath.Join(dirs.SnapSeqDir, snapName+".json") - content, err := ioutil.ReadFile(seqFile) + content, err := os.ReadFile(seqFile) if os.IsNotExist(err) { return "", errNoSnapd } diff --git a/cmd/snap-fde-keymgr/main.go b/cmd/snap-fde-keymgr/main.go index 5b176b611d2..9f2223a61b8 100644 --- a/cmd/snap-fde-keymgr/main.go +++ b/cmd/snap-fde-keymgr/main.go @@ -23,7 +23,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "strings" @@ -125,7 +124,7 @@ func (c *cmdAddRecoveryKey) Execute(args []string) error { } if alreadyExists { // we already have the recovery key, read it back - maybeKey, err := ioutil.ReadFile(c.KeyFile) + maybeKey, err := os.ReadFile(c.KeyFile) if err != nil { return fmt.Errorf("cannot read existing recovery key file: %v", err) } @@ -149,7 +148,7 @@ func (c *cmdAddRecoveryKey) Execute(args []string) error { } } case strings.HasPrefix(authz, "file:"): - authzKey, err := ioutil.ReadFile(authz[len("file:"):]) + authzKey, err := os.ReadFile(authz[len("file:"):]) if err != nil { return fmt.Errorf("cannot load authorization key: %v", err) } @@ -178,7 +177,7 @@ func (c *cmdRemoveRecoveryKey) Execute(args []string) error { return fmt.Errorf("cannot remove recovery key from LUKS device: %v", err) } case strings.HasPrefix(authz, "file:"): - authzKey, err := ioutil.ReadFile(authz[len("file:"):]) + authzKey, err := os.ReadFile(authz[len("file:"):]) if err != nil { return fmt.Errorf("cannot load authorization key: %v", err) } diff --git a/cmd/snap-recovery-chooser/main_test.go b/cmd/snap-recovery-chooser/main_test.go index 7b2bd76c20e..3f3e4e2e234 100644 --- a/cmd/snap-recovery-chooser/main_test.go +++ b/cmd/snap-recovery-chooser/main_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log/syslog" "net/http" "net/http/httptest" @@ -127,7 +126,7 @@ echo '{}' _, err := main.RunUI(exec.Command(mockCmd.Exe()), mockSystems) c.Assert(err, IsNil) - data, err := ioutil.ReadFile(tf) + data, err := os.ReadFile(tf) c.Assert(err, IsNil) var input *main.ChooserSystems err = json.Unmarshal(data, &input) @@ -266,7 +265,7 @@ echo '{"label":"label","action":{"mode":"install","title":"reinstall"}}' {"tool"}, }) - capturedStdin, err := ioutil.ReadFile(capturedStdinPath) + capturedStdin, err := os.ReadFile(capturedStdinPath) c.Assert(err, IsNil) var stdoutSystems main.ChooserSystems err = json.Unmarshal(capturedStdin, &stdoutSystems) diff --git a/cmd/snap-repair/cmd_done_retry_skip_test.go b/cmd/snap-repair/cmd_done_retry_skip_test.go index ecdf15eb545..c34ef24a874 100644 --- a/cmd/snap-repair/cmd_done_retry_skip_test.go +++ b/cmd/snap-repair/cmd_done_retry_skip_test.go @@ -20,7 +20,7 @@ package main_test import ( - "io/ioutil" + "io" "os" "strconv" "syscall" @@ -74,7 +74,7 @@ func (r *repairSuite) TestStatusHappy(c *C) { err = repair.ParseArgs([]string{s}) c.Check(err, IsNil) - status, err := ioutil.ReadAll(rp) + status, err := io.ReadAll(rp) c.Assert(err, IsNil) c.Check(string(status), Equals, s+"\n") } diff --git a/cmd/snap-repair/runner.go b/cmd/snap-repair/runner.go index ff8fd16af61..e14225ef5a3 100644 --- a/cmd/snap-repair/runner.go +++ b/cmd/snap-repair/runner.go @@ -27,7 +27,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -750,7 +749,7 @@ func findDevInfo20() (*deviceInfo, error) { func findDevInfo16() (*deviceInfo, error) { workBS := asserts.NewMemoryBackstore() assertSeedDir := filepath.Join(dirs.SnapSeedDir, "assertions") - dc, err := ioutil.ReadDir(assertSeedDir) + dc, err := os.ReadDir(assertSeedDir) if err != nil { return nil, err } diff --git a/cmd/snap-repair/runner_test.go b/cmd/snap-repair/runner_test.go index 667da31e1eb..bf95832618f 100644 --- a/cmd/snap-repair/runner_test.go +++ b/cmd/snap-repair/runner_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -154,7 +153,7 @@ func (s *baseRunnerSuite) signSeqRepairs(c *C, repairs []string) []string { func checkStateJSON(c *C, file string, exp map[string]interface{}) { stateFile := map[string]interface{}{} - b, err := ioutil.ReadFile(file) + b, err := os.ReadFile(file) c.Assert(err, IsNil) err = json.Unmarshal(b, &stateFile) c.Assert(err, IsNil) @@ -948,7 +947,7 @@ func (s *runnerSuite) TestVerify(c *C) { } func (s *runnerSuite) loadSequences(c *C) map[string][]*repair.RepairState { - data, err := ioutil.ReadFile(dirs.SnapRepairStateFile) + data, err := os.ReadFile(dirs.SnapRepairStateFile) c.Assert(err, IsNil) var x struct { Sequences map[string][]*repair.RepairState `json:"sequences"` @@ -1911,7 +1910,7 @@ func (s *runScriptSuite) testScriptRun(c *C, mockScript string) *repair.Repair { } func (s *runScriptSuite) verifyRundir(c *C, names []string) { - dirents, err := ioutil.ReadDir(s.runDir) + dirents, err := os.ReadDir(s.runDir) c.Assert(err, IsNil) c.Assert(dirents, HasLen, len(names)) for i := range dirents { diff --git a/cmd/snap-seccomp/main.go b/cmd/snap-seccomp/main.go index efa96c9c2aa..516b7ea0989 100644 --- a/cmd/snap-seccomp/main.go +++ b/cmd/snap-seccomp/main.go @@ -211,13 +211,12 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" "os" "strconv" "strings" "syscall" - "github.com/seccomp/libseccomp-golang" + seccomp "github.com/seccomp/libseccomp-golang" "github.com/snapcore/snapd/arch" "github.com/snapcore/snapd/osutil" @@ -914,7 +913,7 @@ func main() { fmt.Println("compile needs an input and output file") os.Exit(1) } - content, err = ioutil.ReadFile(os.Args[2]) + content, err = os.ReadFile(os.Args[2]) if err != nil { break } diff --git a/cmd/snap-update-ns/change_test.go b/cmd/snap-update-ns/change_test.go index a957d5d9647..83beae259b5 100644 --- a/cmd/snap-update-ns/change_test.go +++ b/cmd/snap-update-ns/change_test.go @@ -21,7 +21,7 @@ package main_test import ( "errors" - "os" + "io/fs" "path/filepath" "syscall" @@ -776,7 +776,7 @@ func (s *changeSuite) TestPerformFilesystemMountWithoutMountPointAndReadOnlyBase // error, read only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Uid: 0, Gid: 0, Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -911,7 +911,7 @@ func (s *changeSuite) TestPerformFilesystemMountWithoutMountPointAndReadOnlyBase // error, read only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Uid: 0, Gid: 0, Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -1287,7 +1287,7 @@ func (s *changeSuite) TestPerformDirectoryBindMountWithoutMountPointAndReadOnlyB // error, read only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Uid: 0, Gid: 0, Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -1437,7 +1437,7 @@ func (s *changeSuite) TestPerformDirectoryBindMountWithoutMountSourceAndReadOnly // error /rofs is a read-only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -1828,7 +1828,7 @@ func (s *changeSuite) TestPerformFileBindMountWithoutMountPointAndReadOnlyBase(c // error, read only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -2223,7 +2223,7 @@ func (s *changeSuite) TestPerformCreateSymlinkWithoutBaseDirAndReadOnlyBase(c *C // error, read only filesystem, create a mimic {C: `lstat "/rofs" `, R: syscall.Stat_t{Mode: 0755}}, - {C: `readdir "/rofs"`, R: []os.FileInfo(nil)}, + {C: `readdir "/rofs"`, R: []fs.DirEntry(nil)}, {C: `lstat "/tmp/.snap/rofs"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`}, @@ -2368,12 +2368,14 @@ func (s *changeSuite) TestPerformCreateSymlinkWithAvoidedTrespassing(c *C) { syscall.Statfs_t{Type: update.TmpfsMagic}) s.sys.InsertFstatResult(`fstat 4 `, syscall.Stat_t{}) s.sys.InsertSysLstatResult(`lstat "/etc" `, syscall.Stat_t{Mode: 0755}) - otherConf := testutil.FakeFileInfo("other.conf", 0755) - s.sys.InsertReadDirResult(`readdir "/etc"`, []os.FileInfo{otherConf}) + otherConf := testutil.FakeDirEntry("other.conf", 0755) + s.sys.InsertReadDirResult(`readdir "/etc"`, []fs.DirEntry{otherConf}) s.sys.InsertFault(`lstat "/tmp/.snap/etc"`, syscall.ENOENT) s.sys.InsertFault(`lstat "/tmp/.snap/etc/other.conf"`, syscall.ENOENT) s.sys.InsertOsLstatResult(`lstat "/etc"`, testutil.FileInfoDir) - s.sys.InsertOsLstatResult(`lstat "/etc/other.conf"`, otherConf) + otherConfInfo, err := otherConf.Info() + c.Assert(err, IsNil) + s.sys.InsertOsLstatResult(`lstat "/etc/other.conf"`, otherConfInfo) s.sys.InsertFault(`mkdirat 3 "tmp" 0755`, syscall.EEXIST) s.sys.InsertFstatResult(`fstat 5 `, syscall.Stat_t{Mode: syscall.S_IFREG}) s.sys.InsertFstatResult(`fstat 4 `, syscall.Stat_t{Mode: syscall.S_IFDIR}) @@ -2415,7 +2417,7 @@ func (s *changeSuite) TestPerformCreateSymlinkWithAvoidedTrespassing(c *C) { // For convenience we pretend that /etc is empty. The mimic // replicates /etc in /tmp/.snap/etc for subsequent re-construction. {C: `lstat "/etc" `, R: syscall.Stat_t{Mode: 0755}}, - {C: `readdir "/etc"`, R: []os.FileInfo{otherConf}}, + {C: `readdir "/etc"`, R: []fs.DirEntry{otherConf}}, {C: `lstat "/tmp/.snap/etc"`, E: syscall.ENOENT}, {C: `open "/" O_NOFOLLOW|O_CLOEXEC|O_DIRECTORY 0`, R: 3}, {C: `mkdirat 3 "tmp" 0755`, E: syscall.EEXIST}, @@ -2469,7 +2471,7 @@ func (s *changeSuite) TestPerformCreateSymlinkWithAvoidedTrespassing(c *C) { {C: `lstat "/etc"`, R: testutil.FileInfoDir}, {C: `mount "tmpfs" "/etc" "tmpfs" 0 "mode=0755,uid=0,gid=0"`}, // Here we restore the contents of /etc: here it's just one file - other.conf - {C: `lstat "/etc/other.conf"`, R: otherConf}, + {C: `lstat "/etc/other.conf"`, R: otherConfInfo}, {C: `lstat "/tmp/.snap/etc/other.conf"`, E: syscall.ENOENT}, // Create /tmp/.snap/etc/other.conf as an empty file. @@ -2987,7 +2989,7 @@ func (s *changeSuite) TestSyntheticNeededByUsesMountEntryID(c *C) { s.sys.InsertFault(`mkdirat 6 "rofs" 0755`, syscall.EEXIST) s.sys.InsertFault(`mkdirat 7 "dir" 0755`, syscall.EROFS, nil) s.sys.InsertSysLstatResult(`lstat "/snap/some-snap/x1/rofs" `, syscall.Stat_t{}) - s.sys.InsertReadDirResult(`readdir "/snap/some-snap/x1/rofs"`, []os.FileInfo{}) + s.sys.InsertReadDirResult(`readdir "/snap/some-snap/x1/rofs"`, []fs.DirEntry{}) s.sys.InsertOsLstatResult(`lstat "/tmp/.snap/snap/some-snap/x1/rofs"`, testutil.FileInfoDir) s.sys.InsertOsLstatResult(`lstat "/snap/some-snap/x1/rofs"`, testutil.FileInfoDir) s.sys.InsertFstatResult(`fstat 7 `, syscall.Stat_t{}) @@ -3023,7 +3025,7 @@ func (s *changeSuite) TestSyntheticNeededByUsesDefaultMountEntryID(c *C) { s.sys.InsertFault(`mkdirat 6 "rofs" 0755`, syscall.EEXIST) s.sys.InsertFault(`mkdirat 7 "dir" 0755`, syscall.EROFS, nil) s.sys.InsertSysLstatResult(`lstat "/snap/some-snap/x1/rofs" `, syscall.Stat_t{}) - s.sys.InsertReadDirResult(`readdir "/snap/some-snap/x1/rofs"`, []os.FileInfo{}) + s.sys.InsertReadDirResult(`readdir "/snap/some-snap/x1/rofs"`, []fs.DirEntry{}) s.sys.InsertOsLstatResult(`lstat "/tmp/.snap/snap/some-snap/x1/rofs"`, testutil.FileInfoDir) s.sys.InsertOsLstatResult(`lstat "/snap/some-snap/x1/rofs"`, testutil.FileInfoDir) s.sys.InsertFstatResult(`fstat 7 `, syscall.Stat_t{}) diff --git a/cmd/snap-update-ns/export_test.go b/cmd/snap-update-ns/export_test.go index 6bd84852c3d..8041bf49bd6 100644 --- a/cmd/snap-update-ns/export_test.go +++ b/cmd/snap-update-ns/export_test.go @@ -20,6 +20,7 @@ package main import ( + "io/fs" "os" "syscall" @@ -67,7 +68,7 @@ var ( type SystemCalls interface { OsLstat(name string) (os.FileInfo, error) SysLstat(name string, buf *syscall.Stat_t) error - ReadDir(dirname string) ([]os.FileInfo, error) + ReadDir(dirname string) ([]fs.DirEntry, error) Symlinkat(oldname string, dirfd int, newname string) error Readlinkat(dirfd int, path string, buf []byte) (int, error) Remove(name string) error @@ -89,7 +90,7 @@ func MockSystemCalls(sc SystemCalls) (restore func()) { // save oldOsLstat := osLstat oldRemove := osRemove - oldIoutilReadDir := ioutilReadDir + oldOsReadDir := osReadDir oldSysClose := sysClose oldSysFchown := sysFchown @@ -108,7 +109,7 @@ func MockSystemCalls(sc SystemCalls) (restore func()) { // override osLstat = sc.OsLstat osRemove = sc.Remove - ioutilReadDir = sc.ReadDir + osReadDir = sc.ReadDir sysClose = sc.Close sysFchown = sc.Fchown @@ -128,7 +129,7 @@ func MockSystemCalls(sc SystemCalls) (restore func()) { // restore osLstat = oldOsLstat osRemove = oldRemove - ioutilReadDir = oldIoutilReadDir + osReadDir = oldOsReadDir sysClose = oldSysClose sysFchown = oldSysFchown @@ -184,11 +185,11 @@ func MockNeededChanges(f func(old, new *osutil.MountProfile) []*Change) (restore } } -func MockReadDir(fn func(string) ([]os.FileInfo, error)) (restore func()) { - old := ioutilReadDir - ioutilReadDir = fn +func MockReadDir(fn func(string) ([]fs.DirEntry, error)) (restore func()) { + old := osReadDir + osReadDir = fn return func() { - ioutilReadDir = old + osReadDir = old } } diff --git a/cmd/snap-update-ns/utils.go b/cmd/snap-update-ns/utils.go index 759e08ba4c2..bd67ecb424f 100644 --- a/cmd/snap-update-ns/utils.go +++ b/cmd/snap-update-ns/utils.go @@ -21,7 +21,6 @@ package main import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -69,7 +68,7 @@ var ( sysGetuid = sys.Getuid sysGetgid = sys.Getgid - ioutilReadDir = ioutil.ReadDir + osReadDir = os.ReadDir ) // ReadOnlyFsError is an error encapsulating encountered EROFS. @@ -634,7 +633,7 @@ func planWritableMimic(dir, neededBy string) ([]*Change, error) { }, }) // Iterate over the items in the original directory (nothing is mounted _yet_). - entries, err := ioutilReadDir(dir) + entries, err := osReadDir(dir) if err != nil { return nil, err } @@ -646,7 +645,7 @@ func planWritableMimic(dir, neededBy string) ([]*Change, error) { // Bind mount each element from the safe-keeping directory into the // tmpfs. Our Change.Perform() engine can create the missing // directories automatically so we don't bother creating those. - m := fi.Mode() + m := fi.Type() switch { case m.IsDir(): ch.Entry.Options = []string{"rbind"} diff --git a/cmd/snap-update-ns/utils_test.go b/cmd/snap-update-ns/utils_test.go index 55a37e35669..c4cce664e7c 100644 --- a/cmd/snap-update-ns/utils_test.go +++ b/cmd/snap-update-ns/utils_test.go @@ -23,6 +23,7 @@ import ( "bytes" "errors" "fmt" + "io/fs" "os" "path/filepath" "syscall" @@ -686,21 +687,21 @@ func (s *utilsSuite) TestSecureMkdirAllOpenError(c *C) { func (s *utilsSuite) TestPlanWritableMimic(c *C) { s.sys.InsertSysLstatResult(`lstat "/foo" `, syscall.Stat_t{Uid: 0, Gid: 0, Mode: 0755}) - restore := update.MockReadDir(func(dir string) ([]os.FileInfo, error) { + restore := update.MockReadDir(func(dir string) ([]fs.DirEntry, error) { c.Assert(dir, Equals, "/foo") - return []os.FileInfo{ - testutil.FakeFileInfo("file", 0), - testutil.FakeFileInfo("dir", os.ModeDir), - testutil.FakeFileInfo("symlink", os.ModeSymlink), - testutil.FakeFileInfo("error-symlink-readlink", os.ModeSymlink), + return []fs.DirEntry{ + testutil.FakeDirEntry("file", 0), + testutil.FakeDirEntry("dir", os.ModeDir), + testutil.FakeDirEntry("symlink", os.ModeSymlink), + testutil.FakeDirEntry("error-symlink-readlink", os.ModeSymlink), // NOTE: None of the filesystem entries below are supported because // they cannot be placed inside snaps or can only be created at // runtime in areas that are already writable and this would never // have to be handled in a writable mimic. - testutil.FakeFileInfo("block-dev", os.ModeDevice), - testutil.FakeFileInfo("char-dev", os.ModeDevice|os.ModeCharDevice), - testutil.FakeFileInfo("socket", os.ModeSocket), - testutil.FakeFileInfo("pipe", os.ModeNamedPipe), + testutil.FakeDirEntry("block-dev", os.ModeDevice), + testutil.FakeDirEntry("char-dev", os.ModeDevice|os.ModeCharDevice), + testutil.FakeDirEntry("socket", os.ModeSocket), + testutil.FakeDirEntry("pipe", os.ModeNamedPipe), }, nil }) defer restore() @@ -737,7 +738,7 @@ func (s *utilsSuite) TestPlanWritableMimic(c *C) { func (s *utilsSuite) TestPlanWritableMimicErrors(c *C) { s.sys.InsertSysLstatResult(`lstat "/foo" `, syscall.Stat_t{Uid: 0, Gid: 0, Mode: 0755}) - restore := update.MockReadDir(func(dir string) ([]os.FileInfo, error) { + restore := update.MockReadDir(func(dir string) ([]fs.DirEntry, error) { c.Assert(dir, Equals, "/foo") return nil, errTesting }) diff --git a/cmd/snap/cmd_ack.go b/cmd/snap/cmd_ack.go index 92f40ddff9e..f19087039ad 100644 --- a/cmd/snap/cmd_ack.go +++ b/cmd/snap/cmd_ack.go @@ -21,7 +21,7 @@ package main import ( "fmt" - "io/ioutil" + "os" "github.com/jessevdk/go-flags" @@ -60,7 +60,7 @@ func init() { } func ackFile(cli *client.Client, assertFile string) error { - assertData, err := ioutil.ReadFile(assertFile) + assertData, err := os.ReadFile(assertFile) if err != nil { return err } diff --git a/cmd/snap/cmd_aliases_test.go b/cmd/snap/cmd_aliases_test.go index 6e731ab405d..8bb7aa926ec 100644 --- a/cmd/snap/cmd_aliases_test.go +++ b/cmd/snap/cmd_aliases_test.go @@ -20,7 +20,7 @@ package main_test import ( - "io/ioutil" + "io" "net/http" . "gopkg.in/check.v1" @@ -46,7 +46,7 @@ func (s *SnapSuite) TestAliases(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/aliases") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -82,7 +82,7 @@ func (s *SnapSuite) TestAliasesFilterSnap(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/aliases") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -114,7 +114,7 @@ func (s *SnapSuite) TestAliasesNone(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/aliases") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -132,7 +132,7 @@ func (s *SnapSuite) TestAliasesNoneFilterSnap(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/aliases") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ diff --git a/cmd/snap/cmd_auto_import.go b/cmd/snap/cmd_auto_import.go index 1d909b6b506..773085071eb 100644 --- a/cmd/snap/cmd_auto_import.go +++ b/cmd/snap/cmd_auto_import.go @@ -23,7 +23,6 @@ import ( "crypto" "encoding/base64" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -130,7 +129,7 @@ func queueFile(src string) error { } func autoImportFromSpool(cli *client.Client) (added int, err error) { - files, err := ioutil.ReadDir(dirs.SnapAssertsSpoolDir) + files, err := os.ReadDir(dirs.SnapAssertsSpoolDir) if os.IsNotExist(err) { return 0, nil } @@ -185,10 +184,10 @@ func autoImportFromAllMounts(cli *client.Client) (int, error) { return added, nil } -var ioutilTempDir = ioutil.TempDir +var osMkdirTemp = os.MkdirTemp func tryMount(deviceName string) (string, error) { - tmpMountTarget, err := ioutilTempDir("", "snapd-auto-import-mount-") + tmpMountTarget, err := osMkdirTemp("", "snapd-auto-import-mount-") if err != nil { err = fmt.Errorf("cannot create temporary mount point: %v", err) logger.Noticef("error: %v", err) @@ -275,7 +274,7 @@ func removableBlockDevices() (removableDevices []string) { return nil } for _, removableAttr := range removable { - val, err := ioutil.ReadFile(removableAttr) + val, err := os.ReadFile(removableAttr) if err != nil || string(val) != "1\n" { // non removable continue @@ -294,7 +293,7 @@ func removableBlockDevices() (removableDevices []string) { } for _, partAttr := range partitionAttrs { - val, err := ioutil.ReadFile(partAttr) + val, err := os.ReadFile(partAttr) if err != nil || string(val) != "1\n" { // non partition? continue diff --git a/cmd/snap/cmd_auto_import_test.go b/cmd/snap/cmd_auto_import_test.go index 49be9bdaf46..d82e86b9f5a 100644 --- a/cmd/snap/cmd_auto_import_test.go +++ b/cmd/snap/cmd_auto_import_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -50,7 +50,7 @@ func (s *SnapSuite) TestAutoImportAssertsHappy(c *C) { case 0: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/assertions") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(postData, DeepEquals, fakeAssertData) fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`) @@ -58,7 +58,7 @@ func (s *SnapSuite) TestAutoImportAssertsHappy(c *C) { case 1: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/users") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(postData), Equals, `{"action":"create","automatic":true}`) @@ -176,7 +176,7 @@ func (s *SnapSuite) TestAutoImportIntoSpool(c *C) { // in the output c.Check(logbuf.String(), Matches, "(?ms).*queuing for later.*\n") - files, err := ioutil.ReadDir(dirs.SnapAssertsSpoolDir) + files, err := os.ReadDir(dirs.SnapAssertsSpoolDir) c.Assert(err, IsNil) c.Check(files, HasLen, 1) c.Check(files[0].Name(), Equals, "iOkaeet50rajLvL-0Qsf2ELrTdn3XIXRIBlDewcK02zwRi3_TJlUOTl9AaiDXmDn.assert") @@ -198,7 +198,7 @@ func (s *SnapSuite) TestAutoImportFromSpoolHappy(c *C) { case 0: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/assertions") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(postData, DeepEquals, fakeAssertData) fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`) @@ -206,7 +206,7 @@ func (s *SnapSuite) TestAutoImportFromSpoolHappy(c *C) { case 1: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/users") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(postData), Equals, `{"action":"create","automatic":true}`) @@ -525,7 +525,7 @@ func (s *SnapSuite) TestAutoImportAssertsManagedEmptyReply(c *C) { case 0: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/assertions") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(postData, DeepEquals, fakeAssertData) fmt.Fprintln(w, `{"type": "sync", "result": {"ready": true, "status": "Done"}}`) @@ -533,7 +533,7 @@ func (s *SnapSuite) TestAutoImportAssertsManagedEmptyReply(c *C) { case 1: c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, "/v2/users") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(postData), Equals, `{"action":"create","automatic":true}`) diff --git a/cmd/snap/cmd_connections_test.go b/cmd/snap/cmd_connections_test.go index 48c108820b4..11dcbbd6c8e 100644 --- a/cmd/snap/cmd_connections_test.go +++ b/cmd/snap/cmd_connections_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "net/url" @@ -38,7 +38,7 @@ func (s *SnapSuite) TestConnectionsNoneConnected(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -71,7 +71,7 @@ func (s *SnapSuite) TestConnectionsNotInstalled(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) fmt.Fprintln(w, `{"type": "error", "result": {"message": "not found", "value": "foo", "kind": "snap-not-found"}, "status-code": 404}`) @@ -99,7 +99,7 @@ func (s *SnapSuite) TestConnectionsNoneConnectedPlugs(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -141,7 +141,7 @@ func (s *SnapSuite) TestConnectionsNoneConnectedSlots(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -257,7 +257,7 @@ func (s *SnapSuite) TestConnectionsSomeConnected(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -360,7 +360,7 @@ func (s *SnapSuite) TestConnectionsSomeDisconnected(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -412,7 +412,7 @@ func (s *SnapSuite) TestConnectionsOnlyDisconnected(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -441,7 +441,7 @@ func (s *SnapSuite) TestConnectionsFiltering(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -615,7 +615,7 @@ func (s *SnapSuite) TestConnectionsSorting(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -829,7 +829,7 @@ func (s *SnapSuite) TestConnectionsDefiningAttribute(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") c.Check(r.URL.Query(), DeepEquals, query) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ diff --git a/cmd/snap/cmd_connectivity_check_test.go b/cmd/snap/cmd_connectivity_check_test.go index 3c62f6049fb..d775ceea8fa 100644 --- a/cmd/snap/cmd_connectivity_check_test.go +++ b/cmd/snap/cmd_connectivity_check_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "gopkg.in/check.v1" @@ -37,7 +37,7 @@ func (s *SnapSuite) TestConnectivityHappy(c *check.C) { c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "aspect=connectivity") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(data, check.HasLen, 0) fmt.Fprintln(w, `{"type": "sync", "result": {}}`) @@ -64,7 +64,7 @@ func (s *SnapSuite) TestConnectivityUnhappy(c *check.C) { c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "aspect=connectivity") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(data, check.HasLen, 0) fmt.Fprintln(w, `{"type": "sync", "result": {"connectivity":false,"unreachable":["foo.bar.com"]}}`) diff --git a/cmd/snap/cmd_debug_model_test.go b/cmd/snap/cmd_debug_model_test.go index 1a414a31f2e..6b3530a944f 100644 --- a/cmd/snap/cmd_debug_model_test.go +++ b/cmd/snap/cmd_debug_model_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "gopkg.in/check.v1" @@ -37,7 +37,7 @@ func (s *SnapSuite) TestGetModel(c *check.C) { c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "aspect=model") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(string(data), check.Equals, "") fmt.Fprintln(w, `{"type": "sync", "result": {"model": "some-model-json"}}`) diff --git a/cmd/snap/cmd_debug_seeding_test.go b/cmd/snap/cmd_debug_seeding_test.go index d2658e96c41..308ef5c592f 100644 --- a/cmd/snap/cmd_debug_seeding_test.go +++ b/cmd/snap/cmd_debug_seeding_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" . "gopkg.in/check.v1" @@ -463,7 +463,7 @@ seed-completion: -- c.Assert(r.Method, Equals, "GET", comment) c.Assert(r.URL.Path, Equals, "/v2/debug", comment) c.Assert(r.URL.RawQuery, Equals, "aspect=seeding", comment) - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Assert(err, IsNil, comment) c.Assert(string(data), Equals, "", comment) fmt.Fprintln(w, t.jsonResp) diff --git a/cmd/snap/cmd_ensure_state_soon_test.go b/cmd/snap/cmd_ensure_state_soon_test.go index bf1580ff19a..1f3193eb62d 100644 --- a/cmd/snap/cmd_ensure_state_soon_test.go +++ b/cmd/snap/cmd_ensure_state_soon_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "gopkg.in/check.v1" @@ -37,7 +37,7 @@ func (s *SnapSuite) TestEnsureStateSoon(c *check.C) { c.Check(r.Method, check.Equals, "POST") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(data, check.DeepEquals, []byte(`{"action":"ensure-state-soon"}`)) fmt.Fprintln(w, `{"type": "sync", "result": true}`) diff --git a/cmd/snap/cmd_get_base_declaration_test.go b/cmd/snap/cmd_get_base_declaration_test.go index 4d03b469335..d2a1fe36178 100644 --- a/cmd/snap/cmd_get_base_declaration_test.go +++ b/cmd/snap/cmd_get_base_declaration_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "gopkg.in/check.v1" @@ -37,7 +37,7 @@ func (s *SnapSuite) TestGetBaseDeclaration(c *check.C) { c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "aspect=base-declaration") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(data, check.HasLen, 0) fmt.Fprintln(w, `{"type": "sync", "result": {"base-declaration": "hello"}}`) @@ -62,7 +62,7 @@ func (s *SnapSuite) TestBaseDeclaration(c *check.C) { c.Check(r.Method, check.Equals, "GET") c.Check(r.URL.Path, check.Equals, "/v2/debug") c.Check(r.URL.RawQuery, check.Equals, "aspect=base-declaration") - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Check(err, check.IsNil) c.Check(data, check.HasLen, 0) fmt.Fprintln(w, `{"type": "sync", "result": {"base-declaration": "hello"}}`) diff --git a/cmd/snap/cmd_interface_test.go b/cmd/snap/cmd_interface_test.go index b5e98d5553b..a4b0ce45642 100644 --- a/cmd/snap/cmd_interface_test.go +++ b/cmd/snap/cmd_interface_test.go @@ -20,7 +20,7 @@ package main_test import ( - "io/ioutil" + "io" "net/http" "os" @@ -55,7 +55,7 @@ func (s *SnapSuite) TestInterfaceListEmpty(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "select=connected") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -75,7 +75,7 @@ func (s *SnapSuite) TestInterfaceListAllEmpty(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "select=all") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -95,7 +95,7 @@ func (s *SnapSuite) TestInterfaceList(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "select=connected") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -125,7 +125,7 @@ func (s *SnapSuite) TestInterfaceListAll(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "select=all") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -159,7 +159,7 @@ func (s *SnapSuite) TestInterfaceDetails(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "doc=true&names=network&plugs=true&select=all&slots=true") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -197,7 +197,7 @@ func (s *SnapSuite) TestInterfaceDetailsAndAttrs(c *C) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/interfaces") c.Check(r.URL.RawQuery, Equals, "doc=true&names=serial-port&plugs=true&select=all&slots=true") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ diff --git a/cmd/snap/cmd_interfaces_test.go b/cmd/snap/cmd_interfaces_test.go index 8a672476b47..9ee28b9afef 100644 --- a/cmd/snap/cmd_interfaces_test.go +++ b/cmd/snap/cmd_interfaces_test.go @@ -20,7 +20,7 @@ package main_test import ( - "io/ioutil" + "io" "net/http" "os" @@ -36,7 +36,7 @@ func (s *SnapSuite) TestInterfacesZeroSlotsOnePlug(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -65,7 +65,7 @@ func (s *SnapSuite) TestInterfacesZeroPlugsOneSlot(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -96,7 +96,7 @@ func (s *SnapSuite) TestInterfacesOneSlotOnePlug(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -162,7 +162,7 @@ func (s *SnapSuite) TestInterfacesTwoPlugs(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -203,7 +203,7 @@ func (s *SnapSuite) TestInterfacesPlugsWithCommonName(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -270,7 +270,7 @@ func (s *SnapSuite) TestInterfacesOsSnapSlots(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -337,7 +337,7 @@ func (s *SnapSuite) TestInterfacesTwoSlotsAndFiltering(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -386,7 +386,7 @@ func (s *SnapSuite) TestInterfacesOfSpecificSnap(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -430,7 +430,7 @@ func (s *SnapSuite) TestInterfacesOfSystemNicknameSnap(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -485,7 +485,7 @@ func (s *SnapSuite) TestInterfacesOfSpecificSnapAndSlot(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -528,7 +528,7 @@ func (s *SnapSuite) TestInterfacesNothingAtAll(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -549,7 +549,7 @@ func (s *SnapSuite) TestInterfacesOfSpecificType(c *C) { s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ @@ -648,7 +648,7 @@ func (s *SnapSuite) checkConnectionsSystemCoreRemapping(c *C, apiSnapName, cliSn s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) { c.Check(r.Method, Equals, "GET") c.Check(r.URL.Path, Equals, "/v2/connections") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(body, DeepEquals, []byte{}) EncodeResponseBody(c, w, map[string]interface{}{ diff --git a/cmd/snap/cmd_keys_test.go b/cmd/snap/cmd_keys_test.go index 1cb2ac1ef1d..356a6358510 100644 --- a/cmd/snap/cmd_keys_test.go +++ b/cmd/snap/cmd_keys_test.go @@ -22,7 +22,6 @@ package main_test import ( "encoding/json" "fmt" - "io/ioutil" "net/url" "os" "path/filepath" @@ -70,7 +69,7 @@ func (s *SnapKeysSuite) SetUpTest(c *C) { s.tempdir = c.MkDir() for _, fileName := range []string{"pubring.gpg", "secring.gpg", "trustdb.gpg"} { - data, err := ioutil.ReadFile(filepath.Join("test-data", fileName)) + data, err := os.ReadFile(filepath.Join("test-data", fileName)) c.Assert(err, IsNil) err = os.WriteFile(filepath.Join(s.tempdir, fileName), data, 0644) c.Assert(err, IsNil) diff --git a/cmd/snap/cmd_login_test.go b/cmd/snap/cmd_login_test.go index a4f3e1e463c..f3f3e5809de 100644 --- a/cmd/snap/cmd_login_test.go +++ b/cmd/snap/cmd_login_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" . "gopkg.in/check.v1" @@ -37,7 +37,7 @@ func makeLoginTestServer(c *C, n *int) func(w http.ResponseWriter, r *http.Reque case 0: c.Check(r.URL.Path, Equals, "/v2/login") c.Check(r.Method, Equals, "POST") - postData, err := ioutil.ReadAll(r.Body) + postData, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(postData), Equals, `{"email":"foo@example.com","password":"some-password"}`+"\n") fmt.Fprintln(w, mockLoginRsp) diff --git a/cmd/snap/cmd_quota_test.go b/cmd/snap/cmd_quota_test.go index 68b25b0b0ab..3470330946e 100644 --- a/cmd/snap/cmd_quota_test.go +++ b/cmd/snap/cmd_quota_test.go @@ -23,7 +23,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -142,7 +142,7 @@ func (s *quotaSuite) makeFakeQuotaPostHandler(c *check.C, opts fakeQuotaGroupPos c.Check(r.URL.Path, check.Equals, "/v2/quotas") c.Check(r.Method, check.Equals, "POST") - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) c.Assert(err, check.IsNil) switch opts.action { diff --git a/cmd/snap/cmd_reboot_test.go b/cmd/snap/cmd_reboot_test.go index fb3a47bb387..8d0a2c61491 100644 --- a/cmd/snap/cmd_reboot_test.go +++ b/cmd/snap/cmd_reboot_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -107,7 +107,7 @@ func (s *SnapSuite) TestRebootHappy(c *C) { c.Check(r.Method, Equals, "POST") c.Check(r.URL.Path, Equals, tc.expectedEndpoint, Commentf("%v", tc.cmdline)) c.Check(r.URL.RawQuery, Equals, "") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(string(body), Equals, tc.expectedJSON+"\n") fmt.Fprintln(w, `{"type": "sync", "result": {}}`) diff --git a/cmd/snap/cmd_run.go b/cmd/snap/cmd_run.go index 43b7cf34ef2..181c5a9314f 100644 --- a/cmd/snap/cmd_run.go +++ b/cmd/snap/cmd_run.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "os" "os/exec" @@ -894,7 +893,7 @@ func (x *cmdRun) runCmdUnderGdb(origCmd []string, envForExec envForExecFunc) err func (x *cmdRun) runCmdWithTraceExec(origCmd []string, envForExec envForExecFunc) error { // setup private tmp dir with strace fifo - straceTmp, err := ioutil.TempDir("", "exec-trace") + straceTmp, err := os.MkdirTemp("", "exec-trace") if err != nil { return err } @@ -1278,7 +1277,7 @@ func (x *cmdRun) runSnapConfine(info *snap.Info, securityTag, snapApp, hook stri func getSnapDirOptions(snap string) (*dirs.SnapDirOptions, error) { var opts dirs.SnapDirOptions - data, err := ioutil.ReadFile(filepath.Join(dirs.SnapSeqDir, snap+".json")) + data, err := os.ReadFile(filepath.Join(dirs.SnapSeqDir, snap+".json")) if errors.Is(err, os.ErrNotExist) { return &opts, nil } else if err != nil { diff --git a/cmd/snap/cmd_sign.go b/cmd/snap/cmd_sign.go index 65e97aa48d8..582f298b624 100644 --- a/cmd/snap/cmd_sign.go +++ b/cmd/snap/cmd_sign.go @@ -22,7 +22,8 @@ package main import ( "bytes" "fmt" - "io/ioutil" + "io" + "os" "github.com/jessevdk/go-flags" @@ -77,9 +78,9 @@ func (x *cmdSign) Execute(args []string) error { err error ) if !useStdin { - statement, err = ioutil.ReadFile(string(x.Positional.Filename)) + statement, err = os.ReadFile(string(x.Positional.Filename)) } else { - statement, err = ioutil.ReadAll(Stdin) + statement, err = io.ReadAll(Stdin) } if err != nil { return fmt.Errorf(i18n.G("cannot read assertion input: %v"), err) diff --git a/cmd/snap/cmd_sign_build_test.go b/cmd/snap/cmd_sign_build_test.go index 03d57b7b7d2..a5979078b80 100644 --- a/cmd/snap/cmd_sign_build_test.go +++ b/cmd/snap/cmd_sign_build_test.go @@ -21,7 +21,6 @@ package main_test import ( "fmt" - "io/ioutil" "os" "path/filepath" @@ -79,7 +78,7 @@ func (s *SnapSignBuildSuite) TestSignBuildWorks(c *C) { tempdir := c.MkDir() for _, fileName := range []string{"pubring.gpg", "secring.gpg", "trustdb.gpg"} { - data, err := ioutil.ReadFile(filepath.Join("test-data", fileName)) + data, err := os.ReadFile(filepath.Join("test-data", fileName)) c.Assert(err, IsNil) err = os.WriteFile(filepath.Join(tempdir, fileName), data, 0644) c.Assert(err, IsNil) @@ -114,7 +113,7 @@ func (s *SnapSignBuildSuite) TestSignBuildWorksDevelGrade(c *C) { tempdir := c.MkDir() for _, fileName := range []string{"pubring.gpg", "secring.gpg", "trustdb.gpg"} { - data, err := ioutil.ReadFile(filepath.Join("test-data", fileName)) + data, err := os.ReadFile(filepath.Join("test-data", fileName)) c.Assert(err, IsNil) err = os.WriteFile(filepath.Join(tempdir, fileName), data, 0644) c.Assert(err, IsNil) diff --git a/cmd/snap/cmd_snap_op_test.go b/cmd/snap/cmd_snap_op_test.go index 71006f421a3..3e152de44ab 100644 --- a/cmd/snap/cmd_snap_op_test.go +++ b/cmd/snap/cmd_snap_op_test.go @@ -22,7 +22,7 @@ package main_test import ( "encoding/json" "fmt" - "io/ioutil" + "io" "mime" "mime/multipart" "net/http" @@ -948,7 +948,7 @@ func formFile(form *multipart.Form, c *check.C) (name, filename string, content c.Assert(err, check.IsNil) defer body.Close() filename = fheaders[0].Filename - content, err = ioutil.ReadAll(body) + content, err = io.ReadAll(body) c.Assert(err, check.IsNil) return name, filename, content @@ -1287,7 +1287,7 @@ func formFiles(form *multipart.Form, c *check.C) (names, filenames []string, con c.Assert(err, check.IsNil) defer body.Close() - content, err := ioutil.ReadAll(body) + content, err := io.ReadAll(body) c.Assert(err, check.IsNil) contents = append(contents, content) filenames = append(filenames, h.Filename) diff --git a/cmd/snap/cmd_validate_test.go b/cmd/snap/cmd_validate_test.go index 3a579f573af..f5b9f95e6c1 100644 --- a/cmd/snap/cmd_validate_test.go +++ b/cmd/snap/cmd_validate_test.go @@ -21,12 +21,12 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "gopkg.in/check.v1" - "github.com/snapcore/snapd/cmd/snap" + main "github.com/snapcore/snapd/cmd/snap" ) type validateSuite struct { @@ -45,7 +45,7 @@ func makeFakeValidationSetPostHandler(c *check.C, body, action string, sequence c.Check(r.URL.Path, check.Equals, "/v2/validation-sets/foo/bar") c.Check(r.Method, check.Equals, "POST") - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) c.Assert(err, check.IsNil) switch { case sequence != 0 && action != "forget": diff --git a/cmd/snap/cmd_warnings_test.go b/cmd/snap/cmd_warnings_test.go index 0245fcd77a9..008e2881df5 100644 --- a/cmd/snap/cmd_warnings_test.go +++ b/cmd/snap/cmd_warnings_test.go @@ -21,7 +21,7 @@ package main_test import ( "fmt" - "io/ioutil" + "io" "net/http" "time" @@ -68,7 +68,7 @@ func mkWarningsFakeHandler(c *check.C, body string) func(w http.ResponseWriter, c.Check(r.URL.Path, check.Equals, "/v2/warnings") c.Check(r.URL.Query(), check.HasLen, 0) - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) c.Assert(err, check.IsNil) c.Check(string(buf), check.Equals, "") c.Check(r.Method, check.Equals, "GET") @@ -189,7 +189,7 @@ func (s *warningSuite) TestListWithWarnings(c *check.C) { c.Check(r.URL.Path, check.Equals, "/v2/snaps") c.Check(r.URL.Query(), check.HasLen, 0) - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) c.Assert(err, check.IsNil) c.Check(string(buf), check.Equals, "") c.Check(r.Method, check.Equals, "GET") diff --git a/cmd/snap/export_test.go b/cmd/snap/export_test.go index 5ca584431b9..6becdbb9f9d 100644 --- a/cmd/snap/export_test.go +++ b/cmd/snap/export_test.go @@ -382,10 +382,10 @@ func MockSyscallUmount(f func(string, int) error) (restore func()) { } func MockIoutilTempDir(f func(string, string) (string, error)) (restore func()) { - old := ioutilTempDir - ioutilTempDir = f + old := osMkdirTemp + osMkdirTemp = f return func() { - ioutilTempDir = old + osMkdirTemp = old } } diff --git a/cmd/snapd-apparmor/main.go b/cmd/snapd-apparmor/main.go index 6a09eaa1811..32831361be3 100644 --- a/cmd/snapd-apparmor/main.go +++ b/cmd/snapd-apparmor/main.go @@ -36,7 +36,6 @@ package main import ( "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -77,7 +76,7 @@ func isContainerWithInternalPolicy() bool { var nsStackedPath = filepath.Join(appArmorSecurityFSPath, ".ns_stacked") var nsNamePath = filepath.Join(appArmorSecurityFSPath, ".ns_name") - contents, err := ioutil.ReadFile(nsStackedPath) + contents, err := os.ReadFile(nsStackedPath) if err != nil && !errors.Is(err, os.ErrNotExist) { logger.Noticef("Failed to read %s: %v", nsStackedPath, err) return false @@ -87,7 +86,7 @@ func isContainerWithInternalPolicy() bool { return false } - contents, err = ioutil.ReadFile(nsNamePath) + contents, err = os.ReadFile(nsNamePath) if err != nil && !errors.Is(err, os.ErrNotExist) { logger.Noticef("Failed to read %s: %v", nsNamePath, err) return false diff --git a/cmd/snaplock/runinhibit/inhibit.go b/cmd/snaplock/runinhibit/inhibit.go index 3e63f375d12..f6e83e9f97a 100644 --- a/cmd/snaplock/runinhibit/inhibit.go +++ b/cmd/snaplock/runinhibit/inhibit.go @@ -25,7 +25,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "time" @@ -383,7 +383,7 @@ var WaitWhileInhibited = func(ctx context.Context, snapName string, notInhibited } func hintFromFile(hintFile *os.File) (Hint, error) { - buf, err := ioutil.ReadAll(hintFile) + buf, err := io.ReadAll(hintFile) if err != nil { return "", err } @@ -391,7 +391,7 @@ func hintFromFile(hintFile *os.File) (Hint, error) { } func readInhibitInfo(snapName string, hint Hint) (InhibitInfo, error) { - buf, err := ioutil.ReadFile(InhibitInfoFile(snapName, hint)) + buf, err := os.ReadFile(InhibitInfoFile(snapName, hint)) if err != nil { return InhibitInfo{}, err } diff --git a/cmd/snaplock/runinhibit/inhibit_test.go b/cmd/snaplock/runinhibit/inhibit_test.go index 1bb353c6562..841b191d904 100644 --- a/cmd/snaplock/runinhibit/inhibit_test.go +++ b/cmd/snaplock/runinhibit/inhibit_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -85,7 +84,7 @@ func (s *runInhibitSuite) TestLockWithUnsetRevision(c *C) { func testInhibitInfo(c *C, snapName, hint string, expectedInfo runinhibit.InhibitInfo) { infoPath := filepath.Join(runinhibit.InhibitDir, fmt.Sprintf("%s.%s", snapName, hint)) var info runinhibit.InhibitInfo - buf, err := ioutil.ReadFile(infoPath) + buf, err := os.ReadFile(infoPath) c.Assert(err, IsNil) c.Assert(json.Unmarshal(buf, &info), IsNil) c.Check(info, Equals, expectedInfo) diff --git a/daemon/api_apps_test.go b/daemon/api_apps_test.go index 085945e7661..d908f041c0b 100644 --- a/daemon/api_apps_test.go +++ b/daemon/api_apps_test.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "net/http" "net/http/httptest" @@ -811,7 +810,7 @@ func (s *appsSuite) expectLogsAccess() { func (s *appsSuite) TestLogs(c *check.C) { s.expectLogsAccess() - s.jctlRCs = []io.ReadCloser{ioutil.NopCloser(strings.NewReader(` + s.jctlRCs = []io.ReadCloser{io.NopCloser(strings.NewReader(` {"MESSAGE": "hello1", "SYSLOG_IDENTIFIER": "xyzzy", "_PID": "42", "__REALTIME_TIMESTAMP": "42"} {"MESSAGE": "hello2", "SYSLOG_IDENTIFIER": "xyzzy", "_PID": "42", "__REALTIME_TIMESTAMP": "44"} {"MESSAGE": "hello3", "SYSLOG_IDENTIFIER": "xyzzy", "_PID": "42", "__REALTIME_TIMESTAMP": "46"} @@ -847,7 +846,7 @@ func (s *appsSuite) TestLogsNoNamespaceOption(c *check.C) { s.expectLogsAccess() - s.jctlRCs = []io.ReadCloser{ioutil.NopCloser(strings.NewReader(""))} + s.jctlRCs = []io.ReadCloser{io.NopCloser(strings.NewReader(""))} req, err := http.NewRequest("GET", "/v2/logs?names=snap-a.svc2&n=42&follow=false", nil) c.Assert(err, check.IsNil) @@ -871,7 +870,7 @@ func (s *appsSuite) TestLogsWithNamespaceOption(c *check.C) { s.expectLogsAccess() - s.jctlRCs = []io.ReadCloser{ioutil.NopCloser(strings.NewReader(""))} + s.jctlRCs = []io.ReadCloser{io.NopCloser(strings.NewReader(""))} req, err := http.NewRequest("GET", "/v2/logs?names=snap-a.svc2&n=42&follow=false", nil) c.Assert(err, check.IsNil) @@ -905,7 +904,7 @@ func (s *appsSuite) TestLogsN(c *check.C) { {in: strconv.Itoa(math.MaxInt32), out: math.MaxInt32}, } { - s.jctlRCs = []io.ReadCloser{ioutil.NopCloser(strings.NewReader(""))} + s.jctlRCs = []io.ReadCloser{io.NopCloser(strings.NewReader(""))} s.jctlNs = nil req, err := http.NewRequest("GET", "/v2/logs?n="+t.in, nil) @@ -932,9 +931,9 @@ func (s *appsSuite) TestLogsFollow(c *check.C) { s.expectLogsAccess() s.jctlRCs = []io.ReadCloser{ - ioutil.NopCloser(strings.NewReader("")), - ioutil.NopCloser(strings.NewReader("")), - ioutil.NopCloser(strings.NewReader("")), + io.NopCloser(strings.NewReader("")), + io.NopCloser(strings.NewReader("")), + io.NopCloser(strings.NewReader("")), } reqT, err := http.NewRequest("GET", "/v2/logs?follow=true", nil) diff --git a/daemon/api_base_test.go b/daemon/api_base_test.go index 34c9ed7f4d2..547cf84746b 100644 --- a/daemon/api_base_test.go +++ b/daemon/api_base_test.go @@ -23,7 +23,6 @@ import ( "context" "crypto" "fmt" - "io/ioutil" "net/http" "os" "os/user" @@ -537,7 +536,7 @@ version: %s }, nil, "") c.Assert(err, check.IsNil) - content, err := ioutil.ReadFile(snapInfo.MountFile()) + content, err := os.ReadFile(snapInfo.MountFile()) c.Assert(err, check.IsNil) h := sha3.Sum384(content) dgst, err := asserts.EncodeDigest(crypto.SHA3_384, h[:]) diff --git a/daemon/api_debug_pprof_test.go b/daemon/api_debug_pprof_test.go index f0de9bc5f90..44797f46867 100644 --- a/daemon/api_debug_pprof_test.go +++ b/daemon/api_debug_pprof_test.go @@ -21,9 +21,10 @@ package daemon_test import ( "bytes" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "gopkg.in/check.v1" ) @@ -49,10 +50,10 @@ func (s *pprofDebugSuite) TestGetPprofCmdline(c *check.C) { c.Assert(rsp, check.NotNil) c.Assert(rsp.StatusCode, check.Equals, 200) - data, err := ioutil.ReadAll(rsp.Body) + data, err := io.ReadAll(rsp.Body) c.Assert(err, check.IsNil) - cmdline, err := ioutil.ReadFile("/proc/self/cmdline") + cmdline, err := os.ReadFile("/proc/self/cmdline") c.Assert(err, check.IsNil) cmdline = bytes.TrimRight(cmdline, "\x00") c.Assert(string(data), check.DeepEquals, string(cmdline)) diff --git a/daemon/api_download_test.go b/daemon/api_download_test.go index d3a0c9d34ca..d61bc51c5f8 100644 --- a/daemon/api_download_test.go +++ b/daemon/api_download_test.go @@ -25,7 +25,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "strings" @@ -155,7 +154,7 @@ func (s *snapDownloadSuite) DownloadStream(ctx context.Context, name string, dow if resume > 0 { status = 206 } - return ioutil.NopCloser(bytes.NewReader([]byte(snapContent[resume:]))), status, nil + return io.NopCloser(bytes.NewReader([]byte(snapContent[resume:]))), status, nil } panic(fmt.Sprintf("internal error: trying to download %s but not in storeSnaps", name)) } diff --git a/daemon/api_sideload_n_try_test.go b/daemon/api_sideload_n_try_test.go index a41fdb417a0..d2a57545462 100644 --- a/daemon/api_sideload_n_try_test.go +++ b/daemon/api_sideload_n_try_test.go @@ -25,7 +25,6 @@ import ( "crypto/rand" "errors" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -558,7 +557,7 @@ func (s *sideloadSuite) TestLocalInstallSnapDeriveSideInfo(c *check.C) { version: 1`, nil) digest, size, err := asserts.SnapFileSHA3_384(fooSnap) c.Assert(err, check.IsNil) - fooSnapBytes, err := ioutil.ReadFile(fooSnap) + fooSnapBytes, err := os.ReadFile(fooSnap) c.Assert(err, check.IsNil) dev1Acct := assertstest.NewAccount(s.StoreSigning, "devel1", nil, "") @@ -807,7 +806,7 @@ func (s *sideloadSuite) TestFormdataIsWrittenToCorrectTmpLocation(c *check.C) { chgSummary, _ := s.sideloadCheck(c, sideLoadBodyWithoutDevMode, head, "local", snapstate.Flags{RemoveSnapPath: true, Transaction: client.TransactionPerSnap}) c.Check(chgSummary, check.Equals, `Install "local" snap from file "a/b/local.snap"`) - files, err := ioutil.ReadDir(tmpDir) + files, err := os.ReadDir(tmpDir) c.Assert(err, check.IsNil) c.Assert(files, check.HasLen, 0) @@ -1158,7 +1157,7 @@ func (s *sideloadSuite) TestSideloadManySnapsOneNotAsserted(c *check.C) { // unasserted snap twoSnap := snaptest.MakeTestSnapWithFiles(c, `name: two version: 1`, nil) - twoSnapData, err := ioutil.ReadFile(twoSnap) + twoSnapData, err := os.ReadFile(twoSnap) c.Assert(err, check.IsNil) snapData = append(snapData, twoSnapData) @@ -1186,7 +1185,7 @@ func (s *sideloadSuite) mockAssertions(c *check.C, st *state.State, snaps []stri version: 1`, snap), nil) digest, size, err := asserts.SnapFileSHA3_384(thisSnap) c.Assert(err, check.IsNil) - thisSnapData, err := ioutil.ReadFile(thisSnap) + thisSnapData, err := os.ReadFile(thisSnap) c.Assert(err, check.IsNil) snapData = append(snapData, thisSnapData) diff --git a/daemon/api_snapshots_test.go b/daemon/api_snapshots_test.go index d47bacf5052..255c0ac49e6 100644 --- a/daemon/api_snapshots_test.go +++ b/daemon/api_snapshots_test.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -449,7 +448,7 @@ func (s *snapshotSuite) TestImportSnapshotLimits(c *check.C) { var dataRead int defer daemon.MockSnapshotImport(func(ctx context.Context, st *state.State, r io.Reader) (uint64, []string, error) { - data, err := ioutil.ReadAll(r) + data, err := io.ReadAll(r) c.Assert(err, check.IsNil) dataRead = len(data) return uint64(0), nil, nil diff --git a/daemon/daemon_test.go b/daemon/daemon_test.go index 2aec37d97f8..54e70b795e5 100644 --- a/daemon/daemon_test.go +++ b/daemon/daemon_test.go @@ -22,7 +22,7 @@ package daemon import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -801,7 +801,7 @@ version: 1`, si) res, err := http.Get(fmt.Sprintf("http://%s/endp", snapdL.Addr())) c.Assert(err, check.IsNil) c.Check(res.StatusCode, check.Equals, 200) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) res.Body.Close() c.Assert(err, check.IsNil) c.Check(string(body), check.Equals, "OKOK") @@ -1044,7 +1044,7 @@ func (s *daemonSuite) testRestartSystemWiring(c *check.C, prep func(d *Daemon), // finally check that maintenance.json was written appropriate for this // restart reason - b, err := ioutil.ReadFile(dirs.SnapdMaintenanceFile) + b, err := os.ReadFile(dirs.SnapdMaintenanceFile) c.Assert(err, check.IsNil) maintErr := &errorResult{} diff --git a/gadget/device/encrypt.go b/gadget/device/encrypt.go index 86469d69418..2c399edd32d 100644 --- a/gadget/device/encrypt.go +++ b/gadget/device/encrypt.go @@ -22,7 +22,6 @@ package device import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" @@ -45,11 +44,11 @@ func HasEncryptedMarkerUnder(deviceFDEDir string) bool { // ReadEncryptionMarkers reads the encryption marker files at the appropriate // locations. func ReadEncryptionMarkers(dataFDEDir, saveFDEDir string) ([]byte, []byte, error) { - marker1, err := ioutil.ReadFile(encryptionMarkerUnder(dataFDEDir)) + marker1, err := os.ReadFile(encryptionMarkerUnder(dataFDEDir)) if err != nil { return nil, nil, err } - marker2, err := ioutil.ReadFile(encryptionMarkerUnder(saveFDEDir)) + marker2, err := os.ReadFile(encryptionMarkerUnder(saveFDEDir)) if err != nil { return nil, nil, err } @@ -132,7 +131,7 @@ func SealedKeysMethod(rootdir string) (sm SealingMethod, err error) { // TODO:UC20: consider more than the marker for cases where we reseal // outside of run mode stamp := filepath.Join(dirs.SnapFDEDirUnder(rootdir), "sealed-keys") - content, err := ioutil.ReadFile(stamp) + content, err := os.ReadFile(stamp) if os.IsNotExist(err) { return sm, ErrNoSealedKeys } diff --git a/gadget/device/encrypt_test.go b/gadget/device/encrypt_test.go index df6c6f01579..dfcb9ae7295 100644 --- a/gadget/device/encrypt_test.go +++ b/gadget/device/encrypt_test.go @@ -20,7 +20,6 @@ package device_test import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -124,7 +123,7 @@ func (s *deviceSuite) TestStampSealedKeysRunthrough(c *C) { c.Assert(err, IsNil) c.Check(tc.mth, Equals, mth) - content, err := ioutil.ReadFile(filepath.Join(root, "/var/lib/snapd/device/fde/sealed-keys")) + content, err := os.ReadFile(filepath.Join(root, "/var/lib/snapd/device/fde/sealed-keys")) c.Assert(err, IsNil) c.Check(string(content), Equals, tc.expected) } diff --git a/gadget/gadget.go b/gadget/gadget.go index 82db6adb495..05d226fbc5b 100644 --- a/gadget/gadget.go +++ b/gadget/gadget.go @@ -25,7 +25,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "math" "os" "path/filepath" @@ -679,7 +678,7 @@ func LoadDiskVolumesDeviceTraits(dir string) (map[string]DiskVolumeDeviceTraits, return nil, nil } - b, err := ioutil.ReadFile(filename) + b, err := os.ReadFile(filename) if err != nil { return nil, err } @@ -1209,7 +1208,7 @@ func readInfo(f func(string) ([]byte, error), gadgetYamlFn string, model Model) // validation like Validate. func ReadInfo(gadgetSnapRootDir string, model Model) (*Info, error) { gadgetYamlFn := filepath.Join(gadgetSnapRootDir, "meta", "gadget.yaml") - ginfo, err := readInfo(ioutil.ReadFile, gadgetYamlFn, model) + ginfo, err := readInfo(os.ReadFile, gadgetYamlFn, model) if err != nil { return nil, err } @@ -1909,7 +1908,7 @@ func parseCommandLineFromGadget(content []byte) (string, error) { // but could be used on any known to be properly installed gadget. func HasRole(gadgetSnapRootDir string, roles []string) (foundRole string, err error) { gadgetYamlFn := filepath.Join(gadgetSnapRootDir, "meta", "gadget.yaml") - gadgetYaml, err := ioutil.ReadFile(gadgetYamlFn) + gadgetYaml, err := os.ReadFile(gadgetYamlFn) if err != nil { return "", err } diff --git a/gadget/install/content_test.go b/gadget/install/content_test.go index 04132dc13f7..666eaef0d80 100644 --- a/gadget/install/content_test.go +++ b/gadget/install/content_test.go @@ -22,7 +22,7 @@ package install_test import ( "errors" "fmt" - "io/ioutil" + "os" "path/filepath" "syscall" @@ -220,7 +220,7 @@ func (s *contentTestSuite) TestWriteFilesystemContent(c *C) { if err == nil { // the target file system is mounted on a directory named after the structure index - content, err := ioutil.ReadFile(filepath.Join(dirs.SnapRunDir, "gadget-install/dev-node2", "EFI/boot/grubx64.efi")) + content, err := os.ReadFile(filepath.Join(dirs.SnapRunDir, "gadget-install/dev-node2", "EFI/boot/grubx64.efi")) c.Assert(err, IsNil) c.Check(string(content), Equals, "grubx64.efi content") c.Assert(obs.content, DeepEquals, map[string][]*mockContentChange{ diff --git a/gadget/install/install_test.go b/gadget/install/install_test.go index 028ec641fd4..b41c722a87f 100644 --- a/gadget/install/install_test.go +++ b/gadget/install/install_test.go @@ -22,7 +22,6 @@ package install_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -1038,10 +1037,10 @@ func (s *installSuite) testWriteContent(c *C, opts writeContentOpts) { var data []byte for _, mntPt := range []string{espMntPt, bootMntPt} { - data, err = ioutil.ReadFile(filepath.Join(mntPt, "EFI/boot/bootx64.efi")) + data, err = os.ReadFile(filepath.Join(mntPt, "EFI/boot/bootx64.efi")) c.Check(err, IsNil) c.Check(string(data), Equals, "shim.efi.signed content") - data, err = ioutil.ReadFile(filepath.Join(mntPt, "EFI/boot/grubx64.efi")) + data, err = os.ReadFile(filepath.Join(mntPt, "EFI/boot/grubx64.efi")) c.Check(err, IsNil) c.Check(string(data), Equals, "grubx64.efi content") } diff --git a/gadget/mountedfilesystem.go b/gadget/mountedfilesystem.go index 2f53841ad84..3f8447b96a8 100644 --- a/gadget/mountedfilesystem.go +++ b/gadget/mountedfilesystem.go @@ -25,7 +25,7 @@ import ( _ "crypto/sha1" "fmt" "io" - "io/ioutil" + "io/fs" "os" "path/filepath" "sort" @@ -153,7 +153,7 @@ func (m *MountedFilesystemWriter) writeDirectory(volumeRoot, src, dst string, pr dst = filepath.Join(dst, filepath.Base(src)) } - fis, err := ioutil.ReadDir(src) + fis, err := os.ReadDir(src) if err != nil { return fmt.Errorf("cannot list directory entries: %v", err) } @@ -382,7 +382,7 @@ func (f *mountedFilesystemUpdater) Update() error { return nil } -func (f *mountedFilesystemUpdater) sourceDirectoryEntries(srcPath string) ([]os.FileInfo, error) { +func (f *mountedFilesystemUpdater) sourceDirectoryEntries(srcPath string) ([]fs.DirEntry, error) { if err := checkSourceIsDir(srcPath); err != nil { return nil, err } @@ -392,7 +392,7 @@ func (f *mountedFilesystemUpdater) sourceDirectoryEntries(srcPath string) ([]os. return nil, fmt.Errorf("source is a symbolic link") } - return ioutil.ReadDir(srcPath) + return os.ReadDir(srcPath) } // targetInSourceDir resolves the actual target for given source directory name diff --git a/httputil/client.go b/httputil/client.go index 298b21bc061..1c0bfc5cf19 100644 --- a/httputil/client.go +++ b/httputil/client.go @@ -23,10 +23,10 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net" "net/http" "net/url" + "os" "path/filepath" "time" @@ -62,7 +62,7 @@ func (e *ExtraSSLCertsFromDir) Certs() ([]*CertData, error) { } extraCerts := make([]*CertData, 0, len(extraCertFiles)) for _, p := range extraCertFiles { - cert, err := ioutil.ReadFile(p) + cert, err := os.ReadFile(p) if err != nil { return nil, fmt.Errorf("cannot read certificate: %v", err) } diff --git a/httputil/logger_test.go b/httputil/logger_test.go index 66b5b1f1889..c6ee8535807 100644 --- a/httputil/logger_test.go +++ b/httputil/logger_test.go @@ -22,7 +22,7 @@ package httputil_test import ( "bytes" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -113,7 +113,7 @@ func (s loggerSuite) TestNotLoggingOctetStream(c *check.C) { Header: http.Header{ "Content-Type": []string{"application/octet-stream"}, }, - Body: ioutil.NopCloser(strings.NewReader(needle)), + Body: io.NopCloser(strings.NewReader(needle)), } tr := &httputil.LoggedTransport{ Transport: &fakeTransport{ diff --git a/i18n/xgettext-go/main.go b/i18n/xgettext-go/main.go index 44f7e2c3459..95a42a2ac8a 100644 --- a/i18n/xgettext-go/main.go +++ b/i18n/xgettext-go/main.go @@ -7,7 +7,6 @@ import ( "go/parser" "go/token" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -174,13 +173,13 @@ func readContent(fname string) (content []byte, err error) { // If no search directories have been specified or we have an // absolute path, just try to read the contents directly. if len(opts.Directories) == 0 || filepath.IsAbs(fname) { - return ioutil.ReadFile(fname) + return os.ReadFile(fname) } // Otherwise, search for the file in each of the configured // directories. for _, dir := range opts.Directories { - content, err = ioutil.ReadFile(filepath.Join(dir, fname)) + content, err = os.ReadFile(filepath.Join(dir, fname)) if !os.IsNotExist(err) { break } @@ -324,7 +323,7 @@ func main() { var files []string if opts.FilesFrom != "" { - content, err := ioutil.ReadFile(opts.FilesFrom) + content, err := os.ReadFile(opts.FilesFrom) if err != nil { log.Fatalf("cannot read file %v: %v", opts.FilesFrom, err) } diff --git a/image/image_linux.go b/image/image_linux.go index 7d42e4d8fc7..55e414049d6 100644 --- a/image/image_linux.go +++ b/image/image_linux.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -190,7 +189,7 @@ var reserved = []string{"core", "os", "class", "allowed-modes"} func decodeModelAssertion(opts *Options) (*asserts.Model, error) { fn := opts.ModelFile - rawAssert, err := ioutil.ReadFile(fn) + rawAssert, err := os.ReadFile(fn) if err != nil { return nil, fmt.Errorf("cannot read model assertion: %s", err) } diff --git a/image/image_test.go b/image/image_test.go index 6bb790a3579..a0e5bad5cc0 100644 --- a/image/image_test.go +++ b/image/image_test.go @@ -23,7 +23,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -771,7 +770,7 @@ func (s *imageSuite) TestSetupSeed(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -1197,7 +1196,7 @@ func (s *imageSuite) TestSetupSeedWithBase(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -1520,7 +1519,7 @@ func (s *imageSuite) TestSetupSeedWithBaseLegacySnap(c *C) { }) c.Check(runSnaps[1].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 6) @@ -1657,7 +1656,7 @@ func (s *imageSuite) TestSetupSeedWithBaseDefaultTrackSnap(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -1800,7 +1799,7 @@ func (s *imageSuite) TestSetupSeedLocalSnapsWithStoreAsserts(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -2028,7 +2027,7 @@ func (s *imageSuite) TestSetupSeedLocalSnapsWithStoreAssertsValidationEnforce(c }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -2237,7 +2236,7 @@ func (s *imageSuite) TestPrepareClassicModelNoModelAssertion(c *C) { // check assertions seedassertsdir := filepath.Join(seeddir, "assertions") - l, err := ioutil.ReadDir(seedassertsdir) + l, err := os.ReadDir(seedassertsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 9) } @@ -2863,7 +2862,7 @@ func (s *imageSuite) TestSetupSeedClassic(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 3) @@ -2973,7 +2972,7 @@ func (s *imageSuite) TestSetupSeedClassicUC20(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -3036,7 +3035,7 @@ func (s *imageSuite) TestSetupSeedClassicWithLocalClassicSnap(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 2) @@ -3105,7 +3104,7 @@ func (s *imageSuite) TestSetupSeedClassicSnapdOnly(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3150,7 +3149,7 @@ func (s *imageSuite) TestSetupSeedClassicNoSnaps(c *C) { c.Check(essSnaps, HasLen, 0) c.Check(runSnaps, HasLen, 0) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 0) @@ -3340,7 +3339,7 @@ func (s *imageSuite) testSetupSeedCore20Grub(c *C, kernelContent [][]string, exp }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -3505,7 +3504,7 @@ func (s *imageSuite) TestSetupSeedCore20UBoot(c *C) { essSnaps, runSnaps, _ := s.loadSeed(c, seeddir) c.Check(essSnaps, HasLen, 4) c.Check(runSnaps, HasLen, 0) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3894,7 +3893,7 @@ func (s *imageSuite) testSetupSeedWithMixedSnapsAndRevisions(c *C, rules map[str }) } - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -4041,7 +4040,7 @@ func (s *imageSuite) TestSetupSeedSnapRevisionsDownloadHappy(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -4234,7 +4233,7 @@ func (s *imageSuite) TestLocalSnapRevisionMatchingStoreRevision(c *C) { }) c.Check(runSnaps[0].Path, testutil.FilePresent) - l, err := ioutil.ReadDir(seedsnapsdir) + l, err := os.ReadDir(seedsnapsdir) c.Assert(err, IsNil) c.Check(l, HasLen, 4) diff --git a/image/preseed/preseed_linux.go b/image/preseed/preseed_linux.go index b3072060a44..3e0c0507285 100644 --- a/image/preseed/preseed_linux.go +++ b/image/preseed/preseed_linux.go @@ -24,7 +24,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -376,11 +375,11 @@ func systemForPreseeding(systemsDir string) (label string, err error) { } var makePreseedTempDir = func() (string, error) { - return ioutil.TempDir("", "preseed-") + return os.MkdirTemp("", "preseed-") } var makeWritableTempDir = func() (string, error) { - return ioutil.TempDir("", "writable-") + return os.MkdirTemp("", "writable-") } func prepareCore20Chroot(opts *CoreOptions) (popts *preseedCoreOptions, cleanup func(), err error) { diff --git a/image/preseed/reset.go b/image/preseed/reset.go index daf1037abe7..959b324b135 100644 --- a/image/preseed/reset.go +++ b/image/preseed/reset.go @@ -21,7 +21,6 @@ package preseed import ( "fmt" - "io/ioutil" "os" "path/filepath" @@ -37,7 +36,7 @@ import ( // lxd.lxc -> /snap/core/current/usr/lib/snapd/complete.sh // lxc -> lxd.lxc func resetCompletionSymlinks(completersPath string) error { - files, err := ioutil.ReadDir(completersPath) + files, err := os.ReadDir(completersPath) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("error reading %s: %v", completersPath, err) } @@ -46,7 +45,7 @@ func resetCompletionSymlinks(completersPath string) error { // pass 1: find all symlinks pointing at complete.sh for _, fileInfo := range files { - if fileInfo.Mode()&os.ModeSymlink == 0 { + if fileInfo.Type()&os.ModeSymlink == 0 { continue } fullPath := filepath.Join(completersPath, fileInfo.Name()) diff --git a/interfaces/apparmor/backend.go b/interfaces/apparmor/backend.go index e4acd0f4541..5c0c6996a71 100644 --- a/interfaces/apparmor/backend.go +++ b/interfaces/apparmor/backend.go @@ -40,7 +40,6 @@ package apparmor import ( "bytes" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -162,10 +161,10 @@ func snapConfineFromSnapProfile(info *snap.Info) (dir, glob string, content map[ // We must test the ".real" suffix first, this is a workaround for // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=858004 vanillaProfilePath := filepath.Join(info.MountDir(), "/etc/apparmor.d/usr.lib.snapd.snap-confine.real") - vanillaProfileText, err := ioutil.ReadFile(vanillaProfilePath) + vanillaProfileText, err := os.ReadFile(vanillaProfilePath) if os.IsNotExist(err) { vanillaProfilePath = filepath.Join(info.MountDir(), "/etc/apparmor.d/usr.lib.snapd.snap-confine") - vanillaProfileText, err = ioutil.ReadFile(vanillaProfilePath) + vanillaProfileText, err = os.ReadFile(vanillaProfilePath) } if err != nil { return "", "", nil, fmt.Errorf("cannot open apparmor profile for vanilla snap-confine: %s", err) diff --git a/interfaces/apparmor/backend_test.go b/interfaces/apparmor/backend_test.go index 347b31ed090..536269ac938 100644 --- a/interfaces/apparmor/backend_test.go +++ b/interfaces/apparmor/backend_test.go @@ -22,7 +22,6 @@ package apparmor_test import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -814,7 +813,7 @@ func (s *backendSuite) TestDefaultCoreRuntimesTemplateOnlyUsed(c *C) { err := s.Backend.Setup(appSet, interfaces.ConfinementOptions{}, s.Repo, s.meas) c.Assert(err, IsNil) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) for _, line := range []string{ // preamble @@ -854,7 +853,7 @@ func (s *backendSuite) TestBaseDefaultTemplateOnlyUsed(c *C) { err := s.Backend.Setup(appSet, interfaces.ConfinementOptions{}, s.Repo, s.meas) c.Assert(err, IsNil) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) for _, line := range []string{ // preamble @@ -1722,11 +1721,13 @@ func (s *backendSuite) testSetupSnapConfineGeneratedPolicyWithNFS(c *C, profileF c.Assert(err, IsNil) // Because NFS is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "nfs-support") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows network access. @@ -1770,11 +1771,13 @@ func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithNFSAndReExec(c *C) c.Assert(err, IsNil) // Because NFS is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "nfs-support") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows network access. @@ -1812,7 +1815,7 @@ func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError1(c *C) { c.Assert(err, ErrorMatches, "cannot read .*corrupt-proc-self-exe: .*") // We didn't create the policy file. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) @@ -1851,7 +1854,7 @@ func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyError2(c *C) { // While created the policy file initially we also removed it so that // no side-effects remain. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) @@ -1920,15 +1923,17 @@ func (s *backendSuite) testSetupSnapConfineGeneratedPolicyWithOverlay(c *C, prof c.Assert(err, IsNil) // Because overlay is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "overlay-root") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows upperdir access. - data, err := ioutil.ReadFile(filepath.Join(apparmor_sandbox.SnapConfineAppArmorDir, files[0].Name())) + data, err := os.ReadFile(filepath.Join(apparmor_sandbox.SnapConfineAppArmorDir, files[0].Name())) c.Assert(err, IsNil) c.Assert(string(data), testutil.Contains, "\"/upper/{,**/}\" r,") @@ -1967,15 +1972,17 @@ func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithOverlayAndReExec(c c.Assert(err, IsNil) // Because overlay is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "overlay-root") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows upperdir access - data, err := ioutil.ReadFile(filepath.Join(apparmor_sandbox.SnapConfineAppArmorDir, files[0].Name())) + data, err := os.ReadFile(filepath.Join(apparmor_sandbox.SnapConfineAppArmorDir, files[0].Name())) c.Assert(err, IsNil) c.Assert(string(data), testutil.Contains, "\"/upper/{,**/}\" r,") @@ -2021,11 +2028,13 @@ func (s *backendSuite) testSetupSnapConfineGeneratedPolicyWithBPFCapability(c *C // Capability bpf is supported by the parser, so an extra policy file // for snap-confine is present - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "cap-bpf") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) c.Assert(filepath.Join(apparmor_sandbox.SnapConfineAppArmorDir, files[0].Name()), @@ -2089,7 +2098,7 @@ func (s *backendSuite) TestSetupSnapConfineGeneratedPolicyWithBPFProbeError(c *C // Probing apparmor_parser capabilities failed, so nothing gets written // to the snap-confine policy directory - files, err := ioutil.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor_sandbox.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) @@ -2396,7 +2405,7 @@ func (s *backendSuite) TestPtraceTraceRule(c *C) { c.Assert(err, IsNil) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) if tc.expected { @@ -2442,7 +2451,7 @@ func (s *backendSuite) TestHomeIxRule(c *C) { snapInfo := s.InstallSnap(c, tc.opts, "", ifacetest.SambaYamlV1, 1) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) c.Assert(string(data), testutil.Contains, tc.expected) @@ -2483,7 +2492,7 @@ func (s *backendSuite) TestPycacheDenyRule(c *C) { snapInfo := s.InstallSnap(c, tc.opts, "", ifacetest.SambaYamlV1, 1) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) c.Assert(string(data), tc.expected, "deny /usr/lib/python3*/{,**/}__pycache__/ w,") @@ -2508,7 +2517,7 @@ apps: snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapYaml, 1) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.app.cmd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) c.Assert(string(data), testutil.Contains, "capability setuid,") c.Assert(string(data), testutil.Contains, "capability setgid,") @@ -2531,7 +2540,7 @@ apps: snapInfo := s.InstallSnap(c, interfaces.ConfinementOptions{}, "", snapYaml, 1) profile := filepath.Join(dirs.SnapAppArmorDir, "snap.app.cmd") - data, err := ioutil.ReadFile(profile) + data, err := os.ReadFile(profile) c.Assert(err, IsNil) c.Assert(string(data), Not(testutil.Contains), "capability setuid,") c.Assert(string(data), Not(testutil.Contains), "capability setgid,") diff --git a/interfaces/builtin/common.go b/interfaces/builtin/common.go index 1ee890e9b5b..f8e958a95fc 100644 --- a/interfaces/builtin/common.go +++ b/interfaces/builtin/common.go @@ -20,7 +20,7 @@ package builtin import ( - "io/ioutil" + "os" "path/filepath" "github.com/snapcore/snapd/interfaces" @@ -37,9 +37,9 @@ import ( // applicable for testing. var evalSymlinks = filepath.EvalSymlinks -// readDir is either ioutil.ReadDir or a mocked function applicable for +// readDir is either os.ReadDir or a mocked function applicable for // testing. -var readDir = ioutil.ReadDir +var readDir = os.ReadDir type commonInterface struct { name string diff --git a/interfaces/builtin/common_test.go b/interfaces/builtin/common_test.go index 04a16016340..e9939521d2c 100644 --- a/interfaces/builtin/common_test.go +++ b/interfaces/builtin/common_test.go @@ -21,7 +21,7 @@ package builtin import ( "fmt" - "os" + "io/fs" . "gopkg.in/check.v1" @@ -89,8 +89,8 @@ func MockEvalSymlinks(test *testutil.BaseTest, fn func(string) (string, error)) }) } -// MockReadDir replaces the io/ioutil.ReadDir function used inside the caps package. -func MockReadDir(test *testutil.BaseTest, fn func(string) ([]os.FileInfo, error)) { +// MockReadDir replaces the os.ReadDir function used inside the caps package. +func MockReadDir(test *testutil.BaseTest, fn func(string) ([]fs.DirEntry, error)) { orig := readDir readDir = fn test.AddCleanup(func() { diff --git a/interfaces/builtin/display_control_test.go b/interfaces/builtin/display_control_test.go index d6e041afca9..e65c6c730e4 100644 --- a/interfaces/builtin/display_control_test.go +++ b/interfaces/builtin/display_control_test.go @@ -20,7 +20,7 @@ package builtin_test import ( - "io/ioutil" + "io/fs" "os" "path/filepath" @@ -85,8 +85,8 @@ func (s *displayControlInterfaceSuite) TestSanitizePlug(c *C) { func (s *displayControlInterfaceSuite) TestAppArmorSpec(c *C) { c.Assert(os.MkdirAll(filepath.Join(s.tmpdir, "foo_backlight"), 0755), IsNil) c.Assert(os.MkdirAll(filepath.Join(s.tmpdir, "bar_backlight"), 0755), IsNil) - builtin.MockReadDir(&s.BaseTest, func(path string) ([]os.FileInfo, error) { - return ioutil.ReadDir(s.tmpdir) + builtin.MockReadDir(&s.BaseTest, func(path string) ([]fs.DirEntry, error) { + return os.ReadDir(s.tmpdir) }) builtin.MockEvalSymlinks(&s.BaseTest, func(path string) (string, error) { return "(dereferenced)" + path, nil diff --git a/interfaces/builtin/kvm.go b/interfaces/builtin/kvm.go index 2d6aadb239e..1612155587f 100644 --- a/interfaces/builtin/kvm.go +++ b/interfaces/builtin/kvm.go @@ -21,7 +21,7 @@ package builtin import ( "fmt" - "io/ioutil" + "os" "regexp" "strings" @@ -67,7 +67,7 @@ var procCpuinfo = "/proc/cpuinfo" var flagsMatcher = regexp.MustCompile(`(?m)^flags\s+:\s+(.*)$`).FindSubmatch func getCpuFlags() (flags []string, err error) { - buf, err := ioutil.ReadFile(procCpuinfo) + buf, err := os.ReadFile(procCpuinfo) if err != nil { // if we can't read cpuinfo, we want to know _why_ return nil, fmt.Errorf("unable to read %v: %v", procCpuinfo, err) diff --git a/interfaces/builtin/polkit.go b/interfaces/builtin/polkit.go index 5e5df87d4d6..be69672708e 100644 --- a/interfaces/builtin/polkit.go +++ b/interfaces/builtin/polkit.go @@ -22,7 +22,7 @@ package builtin import ( "bytes" "fmt" - "io/ioutil" + "os" "path" "path/filepath" "strings" @@ -96,7 +96,7 @@ func (iface *polkitInterface) getActionPrefix(attribs interfaces.Attrer) (string } func loadPolkitPolicy(filename, actionPrefix string) (polkit.Policy, error) { - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { return nil, fmt.Errorf(`cannot read file %q: %v`, filename, err) } diff --git a/interfaces/builtin/udisks2.go b/interfaces/builtin/udisks2.go index ebc9494e0d9..01e0509f550 100644 --- a/interfaces/builtin/udisks2.go +++ b/interfaces/builtin/udisks2.go @@ -21,7 +21,7 @@ package builtin import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" @@ -445,7 +445,7 @@ func (iface *udisks2Interface) UDevPermanentSlot(spec *udev.Specification, slot if err != nil { return fmt.Errorf("cannot resolve udev-file: %v", err) } - data, err := ioutil.ReadFile(filepath.Join(mountDir, resolvedPath)) + data, err := os.ReadFile(filepath.Join(mountDir, resolvedPath)) if err != nil { return fmt.Errorf("cannot open udev-file: %v", err) } diff --git a/interfaces/mount/backend_test.go b/interfaces/mount/backend_test.go index ef9a748befa..3cc020469ad 100644 --- a/interfaces/mount/backend_test.go +++ b/interfaces/mount/backend_test.go @@ -21,7 +21,6 @@ package mount_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -158,14 +157,14 @@ func (s *backendSuite) TestSetupSetsupSimple(c *C) { expected := strings.Split(fmt.Sprintf("%s\n%s\n", fsEntry1, fsEntry2), "\n") // and that we have the modern fstab file (global for snap) fn := filepath.Join(dirs.SnapMountPolicyDir, "snap.snap-name.fstab") - content, err := ioutil.ReadFile(fn) + content, err := os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected mount profile for the whole snap")) got := strings.Split(string(content), "\n") c.Check(got, testutil.DeepUnsortedMatches, expected) // Check that the user-fstab file was written with the user mount fn = filepath.Join(dirs.SnapMountPolicyDir, "snap.snap-name.user-fstab") - content, err = ioutil.ReadFile(fn) + content, err = os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected user mount profile for the whole snap")) c.Check(string(content), Equals, fsEntry3.String()+"\n") } @@ -276,7 +275,7 @@ func (s *backendSuite) TestSetupUpdates(c *C) { expected := strings.Split(fmt.Sprintf("%s\n%s\n", fsEntry1, fsEntry2), "\n") // and that we have the modern fstab file (global for snap) fn := filepath.Join(dirs.SnapMountPolicyDir, "snap.snap-name.fstab") - content, err := ioutil.ReadFile(fn) + content, err := os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected mount profile for the whole snap")) got := strings.Split(string(content), "\n") c.Check(got, testutil.DeepUnsortedMatches, expected) @@ -297,7 +296,7 @@ func (s *backendSuite) TestSetupUpdates(c *C) { // (because mount profiles are global in the whole snap) expected = strings.Split(fmt.Sprintf("%s\n%s\n%s\n", fsEntry1, fsEntry2, fsEntry3), "\n") // and that we have the modern fstab file (global for snap) - content, err = ioutil.ReadFile(fn) + content, err = os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected mount profile for the whole snap")) got = strings.Split(string(content), "\n") c.Check(got, testutil.DeepUnsortedMatches, expected) @@ -348,7 +347,7 @@ func (s *backendSuite) TestSetupEndureUpdatesError(c *C) { expected := strings.Split(fmt.Sprintf("%s\n%s\n%s\n", fsEntry1, fsEntry2, fsEntry3), "\n") // and that we have the modern fstab file (global for snap) fn := filepath.Join(dirs.SnapMountPolicyDir, "snap.snap-name.fstab") - content, err := ioutil.ReadFile(fn) + content, err := os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected mount profile for the whole snap")) got := strings.Split(string(content), "\n") c.Check(got, testutil.DeepUnsortedMatches, expected) @@ -417,7 +416,7 @@ func (s *backendSuite) TestSetupUpdatesErrorDiscardsNs(c *C) { expected := strings.Split(fmt.Sprintf("%s\n%s\n%s\n", fsEntry1, fsEntry2, fsEntry3), "\n") // and that we have the modern fstab file (global for snap) fn := filepath.Join(dirs.SnapMountPolicyDir, "snap.snap-name.fstab") - content, err := ioutil.ReadFile(fn) + content, err := os.ReadFile(fn) c.Assert(err, IsNil, Commentf("Expected mount profile for the whole snap")) got := strings.Split(string(content), "\n") c.Check(got, testutil.DeepUnsortedMatches, expected) diff --git a/interfaces/seccomp/backend_test.go b/interfaces/seccomp/backend_test.go index f368b6dc703..713d9c4ae76 100644 --- a/interfaces/seccomp/backend_test.go +++ b/interfaces/seccomp/backend_test.go @@ -24,7 +24,6 @@ import ( "encoding/binary" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -180,7 +179,7 @@ fi`) {"snap-seccomp", "version-info"}, // from Initialize() {"snap-seccomp", "compile", profile + ".src", profile + ".bin"}, }) - raw, err := ioutil.ReadFile(profile + ".src") + raw, err := os.ReadFile(profile + ".src") c.Assert(err, IsNil) c.Assert(bytes.HasPrefix(raw, []byte(`# snap-seccomp version information: # 2345cdef 2.3.4 2345cdef - @@ -275,7 +274,7 @@ func (s *backendSuite) TestRealDefaultTemplateIsNormallyUsed(c *C) { err := s.Backend.Setup(appSet, interfaces.ConfinementOptions{}, s.Repo, s.meas) c.Assert(err, IsNil) profile := filepath.Join(dirs.SnapSeccompDir, "snap.samba.smbd") - data, err := ioutil.ReadFile(profile + ".src") + data, err := os.ReadFile(profile + ".src") c.Assert(err, IsNil) for _, line := range []string{ // NOTE: a few randomly picked lines from the real profile. Comments @@ -764,7 +763,7 @@ apps: c.Assert(err, IsNil) // NOTE: we don't call seccomp.MockTemplate() profile := filepath.Join(dirs.SnapSeccompDir, "snap.app.cmd") - data, err := ioutil.ReadFile(profile + ".src") + data, err := os.ReadFile(profile + ".src") c.Assert(err, IsNil) for _, line := range []string{ // NOTE: a few randomly picked lines from the real @@ -810,7 +809,7 @@ apps: c.Assert(err, IsNil) // NOTE: we don't call seccomp.MockTemplate() profile := filepath.Join(dirs.SnapSeccompDir, "snap.app.cmd") - data, err := ioutil.ReadFile(profile + ".src") + data, err := os.ReadFile(profile + ".src") c.Assert(err, IsNil) for _, line := range []string{ // and a few randomly picked lines from root syscalls diff --git a/interfaces/system_key.go b/interfaces/system_key.go index 008637492af..1d9753453e0 100644 --- a/interfaces/system_key.go +++ b/interfaces/system_key.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "reflect" @@ -269,7 +268,7 @@ func SystemKeyMismatch() (bool, error) { } func readSystemKey() (*systemKey, error) { - raw, err := ioutil.ReadFile(dirs.SnapSystemKeyFile) + raw, err := os.ReadFile(dirs.SnapSystemKeyFile) if err != nil && os.IsNotExist(err) { return nil, ErrSystemKeyMissing } diff --git a/interfaces/system_key_test.go b/interfaces/system_key_test.go index c6f905c0a54..a5f879a3971 100644 --- a/interfaces/system_key_test.go +++ b/interfaces/system_key_test.go @@ -23,7 +23,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -104,7 +103,7 @@ func (s *systemKeySuite) testInterfaceWriteSystemKey(c *C, nfsHome, overlayRoot err := interfaces.WriteSystemKey() c.Assert(err, IsNil) - systemKey, err := ioutil.ReadFile(dirs.SnapSystemKeyFile) + systemKey, err := os.ReadFile(dirs.SnapSystemKeyFile) c.Assert(err, IsNil) kernelFeatures, _ := apparmor.KernelFeatures() diff --git a/kernel/kernel.go b/kernel/kernel.go index d7dd00c08b2..3103c884f47 100644 --- a/kernel/kernel.go +++ b/kernel/kernel.go @@ -21,7 +21,6 @@ package kernel import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -66,7 +65,7 @@ func InfoFromKernelYaml(kernelYaml []byte) (*Info, error) { // in the snap root directory if the file exists. func ReadInfo(kernelSnapRootDir string) (*Info, error) { p := filepath.Join(kernelSnapRootDir, "meta", "kernel.yaml") - content, err := ioutil.ReadFile(p) + content, err := os.ReadFile(p) // meta/kernel.yaml is optional so we should not error here if // it is missing if os.IsNotExist(err) { diff --git a/osutil/bootid.go b/osutil/bootid.go index b1aff33fdfb..92d7983482a 100644 --- a/osutil/bootid.go +++ b/osutil/bootid.go @@ -20,7 +20,7 @@ package osutil import ( - "io/ioutil" + "io" "os" "strings" ) @@ -32,7 +32,7 @@ func BootID() (string, error) { return "", err } defer file.Close() - bytes, err := ioutil.ReadAll(file) + bytes, err := io.ReadAll(file) if err != nil { return "", err } diff --git a/osutil/disks/disks_linux.go b/osutil/disks/disks_linux.go index a671847dd91..6781aefa3fd 100644 --- a/osutil/disks/disks_linux.go +++ b/osutil/disks/disks_linux.go @@ -26,7 +26,7 @@ import ( "errors" "fmt" "io" - "io/ioutil" + "os" "os/exec" "path/filepath" "sort" @@ -495,13 +495,13 @@ func parentPartitionPropsForOptions(props map[string]string) (map[string]string, majmin := props["MAJOR"] + ":" + props["MINOR"] dmDir := filepath.Join(dirs.SysfsDir, "dev", "block", majmin, "dm") - dmUUID, err := ioutil.ReadFile(filepath.Join(dmDir, "uuid")) + dmUUID, err := os.ReadFile(filepath.Join(dmDir, "uuid")) if err != nil { return nil, fmt.Errorf(errFmt, err) } dmUUID = bytes.TrimSpace(dmUUID) - dmName, err := ioutil.ReadFile(filepath.Join(dmDir, "name")) + dmName, err := os.ReadFile(filepath.Join(dmDir, "name")) if err != nil { return nil, fmt.Errorf(errFmt, err) } @@ -687,7 +687,7 @@ func (d *disk) populatePartitions() error { // /dev/mmcblk0boot0 disk device on the dragonboard which exists // under the /dev/mmcblk0 disk, but is not a partition and is // instead a proper disk - _, err := ioutil.ReadFile(filepath.Join(path, "partition")) + _, err := os.ReadFile(filepath.Join(path, "partition")) if err != nil { continue } @@ -934,7 +934,7 @@ func AllPhysicalDisks() ([]Disk, error) { // get disks for every block device in /sys/block/ blockDir := filepath.Join(dirs.SysfsDir, "block") - files, err := ioutil.ReadDir(blockDir) + files, err := os.ReadDir(blockDir) if err != nil { return nil, err } diff --git a/osutil/export_test.go b/osutil/export_test.go index 63f40702c50..1c66470beca 100644 --- a/osutil/export_test.go +++ b/osutil/export_test.go @@ -22,7 +22,6 @@ package osutil import ( "fmt" "io" - "io/ioutil" "os" "os/exec" "os/user" @@ -184,7 +183,7 @@ func MockOsReadlink(f func(string) (string, error)) func() { // MockEtcFstab mocks content of /etc/fstab read by IsHomeUsingNFS func MockEtcFstab(text string) (restore func()) { old := etcFstab - f, err := ioutil.TempFile("", "fstab") + f, err := os.CreateTemp("", "fstab") if err != nil { panic(fmt.Errorf("cannot open temporary file: %s", err)) } diff --git a/osutil/inotify/inotify_linux_test.go b/osutil/inotify/inotify_linux_test.go index 09ca850f68c..02214e03336 100644 --- a/osutil/inotify/inotify_linux_test.go +++ b/osutil/inotify/inotify_linux_test.go @@ -7,7 +7,6 @@ package inotify_test import ( - "io/ioutil" "os" "sync/atomic" "testing" @@ -23,7 +22,7 @@ func TestInotifyEvents(t *testing.T) { t.Fatalf("NewWatcher failed: %s", err) } - dir, err := ioutil.TempDir("", "inotify") + dir, err := os.MkdirTemp("", "inotify") if err != nil { t.Fatalf("TempDir failed: %s", err) } @@ -115,7 +114,7 @@ func TestLockOnEvent(t *testing.T) { t.Fatalf("NewWatcher failed: %s", err) } - dir, err := ioutil.TempDir("", "inotify") + dir, err := os.MkdirTemp("", "inotify") if err != nil { t.Fatalf("TempDir failed: %s", err) } diff --git a/osutil/io_test.go b/osutil/io_test.go index 3bb84d50b33..1ecbbbf1e20 100644 --- a/osutil/io_test.go +++ b/osutil/io_test.go @@ -21,7 +21,6 @@ package osutil_test import ( "errors" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -50,7 +49,7 @@ func (ts *AtomicWriteTestSuite) TestAtomicWriteFile(c *C) { c.Check(p, testutil.FileEquals, "canary") // no files left behind! - d, err := ioutil.ReadDir(tmpdir) + d, err := os.ReadDir(tmpdir) c.Assert(err, IsNil) c.Assert(len(d), Equals, 1) } @@ -509,12 +508,12 @@ func (ts *AtomicWriteTestSuite) TestAtomicRenameDir(c *C) { err = osutil.AtomicRename(src+"/", dst+"/") c.Assert(err, IsNil) - d, err := ioutil.ReadDir(dst) + d, err := os.ReadDir(dst) c.Assert(err, IsNil) c.Assert(len(d), Equals, 1) c.Assert(d[0].Name(), Equals, "file") - data, err := ioutil.ReadFile(filepath.Join(dst, "file")) + data, err := os.ReadFile(filepath.Join(dst, "file")) c.Assert(err, IsNil) c.Assert(data, DeepEquals, contents) diff --git a/osutil/kcmdline/kcmdline.go b/osutil/kcmdline/kcmdline.go index 13d45194db5..ab02a1c292c 100644 --- a/osutil/kcmdline/kcmdline.go +++ b/osutil/kcmdline/kcmdline.go @@ -23,7 +23,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "os" "strings" "github.com/snapcore/snapd/osutil" @@ -349,7 +349,7 @@ func parseArgument(args []byte) (argument Argument, end int) { // KernelCommandLine returns the command line reported by the running kernel. func KernelCommandLine() (string, error) { - buf, err := ioutil.ReadFile(procCmdline) + buf, err := os.ReadFile(procCmdline) if err != nil { return "", err } diff --git a/osutil/mkfs/mkfs.go b/osutil/mkfs/mkfs.go index 61e2f74bd38..c5086608b64 100644 --- a/osutil/mkfs/mkfs.go +++ b/osutil/mkfs/mkfs.go @@ -21,7 +21,6 @@ package mkfs import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -185,7 +184,7 @@ func mkfsVfat(img, label, contentsRootDir string, deviceSize, sectorSize quantit // mkfs.vfat does not know how to populate the filesystem with contents, // we need to do the work ourselves - fis, err := ioutil.ReadDir(contentsRootDir) + fis, err := os.ReadDir(contentsRootDir) if err != nil { return fmt.Errorf("cannot list directory contents: %v", err) } diff --git a/osutil/mountinfo_linux.go b/osutil/mountinfo_linux.go index f9d5a9c895b..a350d295e2e 100644 --- a/osutil/mountinfo_linux.go +++ b/osutil/mountinfo_linux.go @@ -24,7 +24,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "sort" "strconv" @@ -97,7 +96,7 @@ func MockProcSelfMountInfoLocation(filename string) (restore func()) { } func MockMountInfo(content string) (restore func()) { - return mockMountInfo(func() (io.ReadCloser, error) { return ioutil.NopCloser(bytes.NewBufferString(content)), nil }) + return mockMountInfo(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewBufferString(content)), nil }) } // LoadMountInfo loads list of mounted entries from /proc/self/mountinfo. This diff --git a/osutil/strace/timing_test.go b/osutil/strace/timing_test.go index bebd140f4f7..e57dbcb5f92 100644 --- a/osutil/strace/timing_test.go +++ b/osutil/strace/timing_test.go @@ -21,7 +21,6 @@ package strace_test import ( "bytes" - "io/ioutil" "os" . "gopkg.in/check.v1" @@ -118,7 +117,7 @@ var sampleStraceSimple = []byte(`21616 1542882400.198907 execve("/snap/bin/test- `) func (s *timingSuite) TestTraceExecveTimings(c *C) { - f, err := ioutil.TempFile("", "strace-extract-test-") + f, err := os.CreateTemp("", "strace-extract-test-") c.Assert(err, IsNil) defer os.Remove(f.Name()) _, err = f.Write(sampleStraceSimple) diff --git a/osutil/syncdir.go b/osutil/syncdir.go index ccc47dfe638..711e91f1829 100644 --- a/osutil/syncdir.go +++ b/osutil/syncdir.go @@ -23,7 +23,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -40,7 +39,7 @@ type SymlinkFileState struct { } func (sym SymlinkFileState) State() (io.ReadCloser, int64, os.FileMode, error) { - return ioutil.NopCloser(bytes.NewReader([]byte(sym.Target))), int64(len(sym.Target)), os.ModeSymlink, nil + return io.NopCloser(bytes.NewReader([]byte(sym.Target))), int64(len(sym.Target)), os.ModeSymlink, nil } // FileReference describes the desired content by referencing an existing file. @@ -93,7 +92,7 @@ func (blob *MemoryFileState) State() (io.ReadCloser, int64, os.FileMode, error) if !blob.Mode.IsRegular() { return nil, 0, os.FileMode(0), fmt.Errorf("internal error: only regular files are supported, got %q instead", blob.Mode.Type()) } - return ioutil.NopCloser(bytes.NewReader(blob.Content)), int64(len(blob.Content)), blob.Mode, nil + return io.NopCloser(bytes.NewReader(blob.Content)), int64(len(blob.Content)), blob.Mode, nil } // ErrSameState is returned when the state of a file has not changed. @@ -264,7 +263,7 @@ func symlinkFileStateEqualTo(filePath string, state FileState) (bool, error) { return false, err } defer readerA.Close() - buf, err := ioutil.ReadAll(readerA) + buf, err := io.ReadAll(readerA) if err != nil { return false, err } @@ -302,7 +301,7 @@ func ensureSymlinkFileState(filePath string, state FileState) error { if err != nil { return err } - buf, err := ioutil.ReadAll(reader) + buf, err := io.ReadAll(reader) if err != nil { return err } diff --git a/osutil/udev/crawler/device.go b/osutil/udev/crawler/device.go index 649895df843..164ec76914c 100644 --- a/osutil/udev/crawler/device.go +++ b/osutil/udev/crawler/device.go @@ -4,7 +4,7 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -90,7 +90,7 @@ func getEventFromUEventFile(path string) (rv map[string]string, err error) { defer f.Close() - data, err := ioutil.ReadAll(f) + data, err := io.ReadAll(f) if err != nil { return nil, err } diff --git a/osutil/udev/main.go.sample b/osutil/udev/main.go.sample index 1f6688d2f22..7581e350fd8 100644 --- a/osutil/udev/main.go.sample +++ b/osutil/udev/main.go.sample @@ -4,7 +4,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "log" "os" "os/signal" @@ -127,7 +126,7 @@ func getOptionnalMatcher() (matcher netlink.Matcher, err error) { return nil, nil } - stream, err := ioutil.ReadFile(*filePath) + stream, err := os.ReadFile(*filePath) if err != nil { return nil, err } diff --git a/overlord/configstate/configcore/cloud.go b/overlord/configstate/configcore/cloud.go index 68f33a6161e..14332dab28f 100644 --- a/overlord/configstate/configcore/cloud.go +++ b/overlord/configstate/configcore/cloud.go @@ -23,7 +23,6 @@ package configcore import ( "encoding/json" "errors" - "io/ioutil" "os" "github.com/snapcore/snapd/dirs" @@ -91,7 +90,7 @@ func setCloudInfoWhenSeeding(tr RunTransaction, opts *fsOnlyContext) error { return nil } - data, err := ioutil.ReadFile(dirs.CloudInstanceDataFile) + data, err := os.ReadFile(dirs.CloudInstanceDataFile) if os.IsNotExist(err) { // nothing to do return nil diff --git a/overlord/configstate/configcore/homedirs_test.go b/overlord/configstate/configcore/homedirs_test.go index 8e6f87631af..bc721aa095f 100644 --- a/overlord/configstate/configcore/homedirs_test.go +++ b/overlord/configstate/configcore/homedirs_test.go @@ -21,7 +21,6 @@ package configcore_test import ( "errors" - "io/ioutil" "os" "path/filepath" "strings" @@ -239,7 +238,7 @@ func (s *homedirsSuite) TestConfigureHomedirsHappy(c *C) { // Check that the config file has been written configPath := filepath.Join(dirs.SnapdStateDir(dirs.GlobalRootDir), "system-params") - contents, err := ioutil.ReadFile(configPath) + contents, err := os.ReadFile(configPath) c.Assert(err, IsNil) c.Check(string(contents), Equals, "homedirs=/home/existingDir\n") diff --git a/overlord/configstate/configcore/tmp.go b/overlord/configstate/configcore/tmp.go index f0960b5bd2d..742868758dd 100644 --- a/overlord/configstate/configcore/tmp.go +++ b/overlord/configstate/configcore/tmp.go @@ -22,7 +22,6 @@ package configcore import ( "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -108,7 +107,7 @@ func handleTmpfsConfiguration(_ sysconfig.Device, tr ConfGetter, opts *fsOnlyCon Content: []byte(content), Mode: 0644, } - oldContent, err := ioutil.ReadFile(cfgFilePath) + oldContent, err := os.ReadFile(cfgFilePath) if err == nil && content == string(oldContent) { modify = false } diff --git a/overlord/devicestate/crypto.go b/overlord/devicestate/crypto.go index bd557f5260b..b32a09e3e61 100644 --- a/overlord/devicestate/crypto.go +++ b/overlord/devicestate/crypto.go @@ -23,7 +23,6 @@ import ( "crypto/x509" "encoding/pem" "errors" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -34,9 +33,9 @@ import ( func generateRSAKey(keyLength int) (*rsa.PrivateKey, error) { // The temporary directory is created with mode - // 0700 by ioutil.TempDir, see: - // https://github.com/golang/go/blob/master/src/io/ioutil/tempfile.go#L84 - tempDir, err := ioutil.TempDir(os.TempDir(), "snapd") + // 0700 by os.MkdirTemp, see: + // https://github.com/golang/go/blob/3b29222ffdcaea70842ed167632468f54a1783ae/src/os/tempfile.go#L98 + tempDir, err := os.MkdirTemp(os.TempDir(), "snapd") if err != nil { return nil, err } @@ -51,7 +50,7 @@ func generateRSAKey(keyLength int) (*rsa.PrivateKey, error) { return nil, osutil.OutputErr(out, err) } - d, err := ioutil.ReadFile(rsaKeyFile) + d, err := os.ReadFile(rsaKeyFile) if err != nil { return nil, err } diff --git a/overlord/devicestate/devicestate_install_mode_test.go b/overlord/devicestate/devicestate_install_mode_test.go index 14b58617f6c..e778d32c81c 100644 --- a/overlord/devicestate/devicestate_install_mode_test.go +++ b/overlord/devicestate/devicestate_install_mode_test.go @@ -22,7 +22,7 @@ package devicestate_test import ( "compress/gzip" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "time" @@ -1111,7 +1111,7 @@ func (s *deviceMgrInstallModeSuite) TestInstallSecuredWithTPMAndSave(c *C) { }) c.Assert(err, IsNil) c.Check(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "ubuntu-save.key"), testutil.FileEquals, []byte(saveKey)) - marker, err := ioutil.ReadFile(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "marker")) + marker, err := os.ReadFile(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "marker")) c.Assert(err, IsNil) c.Check(marker, HasLen, 32) c.Check(filepath.Join(boot.InstallHostFDESaveDir, "marker"), testutil.FileEquals, marker) @@ -1514,7 +1514,7 @@ echo "mock output of: $(basename "$0") $*" defer f.Close() gz, err := gzip.NewReader(f) c.Assert(err, IsNil) - content, err := ioutil.ReadAll(gz) + content, err := io.ReadAll(gz) c.Assert(err, IsNil) c.Check(string(content), Equals, `---- Output of: snap changes mock output of: snap changes diff --git a/overlord/devicestate/handlers_install.go b/overlord/devicestate/handlers_install.go index fc0c7bc16fb..4ba34ea82f4 100644 --- a/overlord/devicestate/handlers_install.go +++ b/overlord/devicestate/handlers_install.go @@ -27,7 +27,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -818,7 +817,7 @@ func verifyFactoryResetMarkerInRun(marker string, hasEncryption bool) error { } func rotateEncryptionKeys() error { - kd, err := ioutil.ReadFile(filepath.Join(dirs.SnapFDEDir, "ubuntu-save.key")) + kd, err := os.ReadFile(filepath.Join(dirs.SnapFDEDir, "ubuntu-save.key")) if err != nil { return fmt.Errorf("cannot open encryption key file: %v", err) } diff --git a/overlord/devicestate/handlers_systems.go b/overlord/devicestate/handlers_systems.go index 794ba906522..9a1e1ea85eb 100644 --- a/overlord/devicestate/handlers_systems.go +++ b/overlord/devicestate/handlers_systems.go @@ -23,7 +23,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -84,7 +83,7 @@ func logNewSystemSnapFile(logfile, fileName string) error { if !strings.HasPrefix(filepath.Dir(fileName), boot.InitramfsUbuntuSeedDir+"/") { return fmt.Errorf("internal error: unexpected recovery system snap location %q", fileName) } - currentLog, err := ioutil.ReadFile(logfile) + currentLog, err := os.ReadFile(logfile) if err != nil && !os.IsNotExist(err) { return err } diff --git a/overlord/install/install_test.go b/overlord/install/install_test.go index 17282d89659..bb3b2ac27a5 100644 --- a/overlord/install/install_test.go +++ b/overlord/install/install_test.go @@ -23,7 +23,6 @@ import ( "bytes" "crypto" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -898,13 +897,13 @@ func (s *installSuite) TestPrepareEncryptedSystemData(c *C) { c.Assert(err, IsNil) c.Check(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "ubuntu-save.key"), testutil.FileEquals, []byte(saveKey)) - marker, err := ioutil.ReadFile(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "marker")) + marker, err := os.ReadFile(filepath.Join(filepath.Join(dirs.GlobalRootDir, "/run/mnt/ubuntu-data/system-data/var/lib/snapd/device/fde"), "marker")) c.Assert(err, IsNil) c.Check(marker, HasLen, 32) c.Check(filepath.Join(boot.InstallHostFDESaveDir, "marker"), testutil.FileEquals, marker) // the assets cache was written to - l, err := ioutil.ReadDir(filepath.Join(dirs.SnapBootAssetsDir, "trusted")) + l, err := os.ReadDir(filepath.Join(dirs.SnapBootAssetsDir, "trusted")) c.Assert(err, IsNil) c.Assert(l, HasLen, 1) } diff --git a/overlord/managers_test.go b/overlord/managers_test.go index e58cafbf8ca..cb4a11017b4 100644 --- a/overlord/managers_test.go +++ b/overlord/managers_test.go @@ -28,7 +28,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -1098,7 +1097,7 @@ func (s *baseMgrsSuite) mockStore(c *C) *httptest.Server { return case "auth:sessions": // quick validity check - reqBody, err := ioutil.ReadAll(r.Body) + reqBody, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(bytes.Contains(reqBody, []byte("nonce: NONCE")), Equals, true) c.Check(bytes.Contains(reqBody, []byte(fmt.Sprintf("serial: %s", s.expectedSerial))), Equals, true) diff --git a/overlord/overlord_test.go b/overlord/overlord_test.go index 713b2e2bdbc..3c5a8fd0e72 100644 --- a/overlord/overlord_test.go +++ b/overlord/overlord_test.go @@ -24,7 +24,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -1325,7 +1324,7 @@ func (ovs *overlordSuite) TestStartupTimeout(c *C) { } func (ovs *overlordSuite) TestLockWithTimeoutHappy(c *C) { - f, err := ioutil.TempFile("", "testlock-*") + f, err := os.CreateTemp("", "testlock-*") defer func() { f.Close() os.Remove(f.Name()) @@ -1354,7 +1353,7 @@ func (ovs *overlordSuite) TestLockWithTimeoutFailed(c *C) { }) defer restoreNotify() - f, err := ioutil.TempFile("", "testlock-*") + f, err := os.CreateTemp("", "testlock-*") defer func() { f.Close() os.Remove(f.Name()) diff --git a/overlord/patch/patch1.go b/overlord/patch/patch1.go index dd61d823b89..6afc17d7be6 100644 --- a/overlord/patch/patch1.go +++ b/overlord/patch/patch1.go @@ -21,7 +21,7 @@ package patch import ( "errors" - "io/ioutil" + "os" "path/filepath" "github.com/snapcore/snapd/logger" @@ -48,7 +48,7 @@ type patch1SideInfo struct { var patch1ReadType = func(name string, rev snap.Revision) (snap.Type, error) { snapYamlFn := filepath.Join(snap.MountDir(name, rev), "meta", "snap.yaml") - meta, err := ioutil.ReadFile(snapYamlFn) + meta, err := os.ReadFile(snapYamlFn) if err != nil { return snap.TypeApp, err } diff --git a/overlord/servicestate/servicestate_test.go b/overlord/servicestate/servicestate_test.go index 5ff333e7449..cd5a07a34b9 100644 --- a/overlord/servicestate/servicestate_test.go +++ b/overlord/servicestate/servicestate_test.go @@ -25,7 +25,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/user" "path/filepath" @@ -955,7 +954,7 @@ func (s *snapServiceOptionsSuite) TestLogReader(c *C) { c.Check(n, Equals, 100) c.Check(follow, Equals, false) c.Check(namespaces, Equals, false) - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }) defer restore() @@ -1033,7 +1032,7 @@ func (s *snapServiceOptionsSuite) TestLogReaderNamespaces(c *C) { c.Check(n, Equals, 100) c.Check(follow, Equals, false) c.Check(namespaces, Equals, true) - return ioutil.NopCloser(strings.NewReader("")), nil + return io.NopCloser(strings.NewReader("")), nil }) defer restore() diff --git a/overlord/snapshotstate/backend/reader.go b/overlord/snapshotstate/backend/reader.go index bbcecfaefa7..8641abbe40a 100644 --- a/overlord/snapshotstate/backend/reader.go +++ b/overlord/snapshotstate/backend/reader.go @@ -27,7 +27,6 @@ import ( "fmt" "hash" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -126,7 +125,7 @@ func Open(fn string, setID uint64) (reader *Reader, e error) { reader.Broken = err.Error() return reader, err } - metaHashBuf, err := ioutil.ReadAll(io.TeeReader(metaHashReader, &sz)) + metaHashBuf, err := io.ReadAll(io.TeeReader(metaHashReader, &sz)) if err != nil { reader.Broken = err.Error() return reader, err @@ -294,7 +293,7 @@ func (r *Reader) Restore(ctx context.Context, current snap.Revision, usernames [ } // TODO: have something more atomic in osutil - tempdir, err := ioutil.TempDir(parent, ".snapshot") + tempdir, err := os.MkdirTemp(parent, ".snapshot") if err != nil { return rs, err } diff --git a/overlord/snapshotstate/snapshotstate_test.go b/overlord/snapshotstate/snapshotstate_test.go index ea6252923e8..16208fb8ebb 100644 --- a/overlord/snapshotstate/snapshotstate_test.go +++ b/overlord/snapshotstate/snapshotstate_test.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "os/exec" "os/user" @@ -1844,7 +1843,7 @@ func (snapshotSuite) TestImportSnapshotHappy(c *check.C) { buf := bytes.NewBufferString(fakeSnapshotData) restore := snapshotstate.MockBackendImport(func(ctx context.Context, id uint64, r io.Reader, flags *backend.ImportFlags) ([]string, error) { - d, err := ioutil.ReadAll(r) + d, err := io.ReadAll(r) c.Assert(err, check.IsNil) c.Check(fakeSnapshotData, check.Equals, string(d)) return fakeSnapNames, nil diff --git a/overlord/snapstate/backend/copydata.go b/overlord/snapstate/backend/copydata.go index e8b896649bd..4fef7480922 100644 --- a/overlord/snapstate/backend/copydata.go +++ b/overlord/snapstate/backend/copydata.go @@ -22,7 +22,6 @@ package backend import ( "errors" "fmt" - "io/ioutil" "os" "os/user" "path/filepath" @@ -286,7 +285,7 @@ func (b Backend) UndoHideSnapData(snapName string) error { } var removeIfEmpty = func(dir string) error { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return err } @@ -351,7 +350,7 @@ func (b Backend) InitExposedSnapHome(snapName string, rev snap.Revision, opts *d undoInfo.Created = append(undoInfo.Created, newUserHome) userData := snap.UserDataDir(usr.HomeDir, snapName, rev, opts) - files, err := ioutil.ReadDir(userData) + files, err := os.ReadDir(userData) if err != nil { if errors.Is(err, os.ErrNotExist) { // there's nothing to copy into ~/Snap/ (like on a fresh install) diff --git a/overlord/snapstate/backend/copydata_test.go b/overlord/snapstate/backend/copydata_test.go index c142aad5e1c..5a681952877 100644 --- a/overlord/snapstate/backend/copydata_test.go +++ b/overlord/snapstate/backend/copydata_test.go @@ -22,7 +22,6 @@ package backend_test import ( "errors" "fmt" - "io/ioutil" "os" "os/user" "path/filepath" @@ -178,16 +177,16 @@ func (s *copydataSuite) testCopyDataMulti(c *C, snapDir string, opts *dirs.SnapD c.Assert(err, IsNil) canaryDataFile := filepath.Join(v1.DataDir(), "canary.txt") - err = ioutil.WriteFile(canaryDataFile, canaryData, 0644) + err = os.WriteFile(canaryDataFile, canaryData, 0644) c.Assert(err, IsNil) canaryDataFile = filepath.Join(v1.CommonDataDir(), "canary.common") - err = ioutil.WriteFile(canaryDataFile, canaryData, 0644) + err = os.WriteFile(canaryDataFile, canaryData, 0644) c.Assert(err, IsNil) for i := range snapHomeDataDirs { - err = ioutil.WriteFile(filepath.Join(snapHomeDataDirs[i], "canary.home"), canaryData, 0644) + err = os.WriteFile(filepath.Join(snapHomeDataDirs[i], "canary.home"), canaryData, 0644) c.Assert(err, IsNil) - err = ioutil.WriteFile(filepath.Join(snapHomeCommonDirs[i], "canary.common_home"), canaryData, 0644) + err = os.WriteFile(filepath.Join(snapHomeCommonDirs[i], "canary.common_home"), canaryData, 0644) c.Assert(err, IsNil) } @@ -263,7 +262,7 @@ func (s *copydataSuite) populateData(c *C, revision snap.Revision) { } func (s *copydataSuite) populatedData(d string) string { - bs, err := ioutil.ReadFile(filepath.Join(dirs.SnapDataDir, "hello", d, "random-subdir", "canary")) + bs, err := os.ReadFile(filepath.Join(dirs.SnapDataDir, "hello", d, "random-subdir", "canary")) if err == nil { return string(bs) } @@ -797,13 +796,13 @@ func (s *copydataSuite) TestHideSnapData(c *C) { // check versioned file was moved opts := &dirs.SnapDirOptions{HiddenSnapDataDir: true} revFile := filepath.Join(info.UserDataDir(homedir, opts), "canary.home") - data, err := ioutil.ReadFile(revFile) + data, err := os.ReadFile(revFile) c.Assert(err, IsNil) c.Assert(data, DeepEquals, []byte("10\n")) // check common file was moved commonFile := filepath.Join(info.UserCommonDataDir(homedir, opts), "file.txt") - data, err = ioutil.ReadFile(commonFile) + data, err = os.ReadFile(commonFile) c.Assert(err, IsNil) c.Assert(data, DeepEquals, []byte("some content")) @@ -894,7 +893,7 @@ func (s *copydataSuite) TestHideSnapDataOverwrite(c *C) { c.Assert(s.be.HideSnapData("hello"), IsNil) // check versioned file was moved and previous contents were overwritten - data, err := ioutil.ReadFile(revFile) + data, err := os.ReadFile(revFile) c.Assert(err, IsNil) c.Assert(data, DeepEquals, []byte("10\n")) @@ -949,13 +948,13 @@ func (s *copydataSuite) TestUndoHideSnapData(c *C) { // check versioned file was restored revFile := filepath.Join(info.UserDataDir(homedir, nil), "file.txt") - data, err := ioutil.ReadFile(revFile) + data, err := os.ReadFile(revFile) c.Assert(err, IsNil) c.Assert(data, DeepEquals, []byte("some content")) // check common file was restored commonFile := filepath.Join(info.UserCommonDataDir(homedir, nil), "file.txt") - data, err = ioutil.ReadFile(commonFile) + data, err = os.ReadFile(commonFile) c.Assert(err, IsNil) c.Assert(data, DeepEquals, []byte("other content")) @@ -1069,7 +1068,7 @@ func (s *copydataSuite) TestRemoveIfEmpty(c *C) { // dir contains a file, shouldn't do anything c.Assert(backend.RemoveIfEmpty(dirs.GlobalRootDir), IsNil) - files, err := ioutil.ReadDir(dirs.GlobalRootDir) + files, err := os.ReadDir(dirs.GlobalRootDir) c.Assert(err, IsNil) c.Check(files, HasLen, 1) c.Check(filepath.Join(dirs.GlobalRootDir, files[0].Name()), testutil.FileEquals, "stuff") @@ -1158,7 +1157,7 @@ func (s *copydataSuite) TestInitSnapUserHome(c *C) { c.Check(undoInfo.Created, DeepEquals, []string{exposedHome}) expectedFile := filepath.Join(exposedHome, "file") - data, err := ioutil.ReadFile(expectedFile) + data, err := os.ReadFile(expectedFile) c.Assert(err, IsNil) c.Check(string(data), Equals, "stuff") @@ -1340,7 +1339,7 @@ func (s *copydataSuite) TestInitSnapNothingToCopy(c *C) { c.Assert(err, IsNil) c.Check(exists, Equals, true) - entries, err := ioutil.ReadDir(newHomeDir) + entries, err := os.ReadDir(newHomeDir) c.Assert(err, IsNil) c.Check(entries, HasLen, 0) } @@ -1405,7 +1404,7 @@ func (s *copydataSuite) TestInitAlreadyExistsDir(c *C) { c.Check(exists, Equals, true) c.Check(isDir, Equals, true) - files, err := ioutil.ReadDir(newHome) + files, err := os.ReadDir(newHome) c.Assert(err, IsNil) c.Check(files, HasLen, 1) c.Check(files[0].Name(), Equals, "file") diff --git a/overlord/snapstate/cookies_test.go b/overlord/snapstate/cookies_test.go index 2b9b0ce71c3..7d4a6a238bd 100644 --- a/overlord/snapstate/cookies_test.go +++ b/overlord/snapstate/cookies_test.go @@ -23,7 +23,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" @@ -108,14 +107,14 @@ func (s *cookiesSuite) TestSyncCookies(c *C) { cookieFile := filepath.Join(dirs.SnapCookieDir, "snap.some-snap") c.Assert(osutil.FileExists(cookieFile), Equals, true) - data, err := ioutil.ReadFile(cookieFile) + data, err := os.ReadFile(cookieFile) c.Assert(err, IsNil) c.Assert(newCookies[string(data)], NotNil) c.Assert(newCookies[string(data)], Equals, "some-snap") cookieFile = filepath.Join(dirs.SnapCookieDir, "snap.other-snap") c.Assert(osutil.FileExists(cookieFile), Equals, true) - data, err = ioutil.ReadFile(cookieFile) + data, err = os.ReadFile(cookieFile) c.Assert(err, IsNil) c.Assert(newCookies[string(data)], NotNil) c.Assert(newCookies[string(data)], Equals, "other-snap") diff --git a/overlord/snapstate/handlers_link_test.go b/overlord/snapstate/handlers_link_test.go index 52c108a4e4b..e99224d4120 100644 --- a/overlord/snapstate/handlers_link_test.go +++ b/overlord/snapstate/handlers_link_test.go @@ -22,7 +22,6 @@ package snapstate_test import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -339,7 +338,7 @@ func (s *linkSnapSuite) TestDoLinkSnapSeqFile(c *C) { c.Assert(err, IsNil) // and check that the sequence file got updated - seqContent, err := ioutil.ReadFile(filepath.Join(dirs.SnapSeqDir, "foo.json")) + seqContent, err := os.ReadFile(filepath.Join(dirs.SnapSeqDir, "foo.json")) c.Assert(err, IsNil) c.Check(string(seqContent), Equals, `{"sequence":[{"name":"foo","snap-id":"","revision":"11"},{"name":"foo","snap-id":"","revision":"33"}],"current":"33","migrated-hidden":false,"migrated-exposed-home":false}`) } @@ -404,7 +403,7 @@ func (s *linkSnapSuite) TestDoUndoLinkSnap(c *C) { c.Check(t.Status(), Equals, state.UndoneStatus) // and check that the sequence file got updated - seqContent, err := ioutil.ReadFile(filepath.Join(dirs.SnapSeqDir, "foo.json")) + seqContent, err := os.ReadFile(filepath.Join(dirs.SnapSeqDir, "foo.json")) c.Assert(err, IsNil) c.Check(string(seqContent), Equals, `{"sequence":[],"current":"unset","migrated-hidden":false,"migrated-exposed-home":false}`) diff --git a/overlord/snapstate/snapstate_update_test.go b/overlord/snapstate/snapstate_update_test.go index 679f0409856..42e4570b9ee 100644 --- a/overlord/snapstate/snapstate_update_test.go +++ b/overlord/snapstate/snapstate_update_test.go @@ -24,7 +24,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "sort" @@ -8221,7 +8221,7 @@ func assertMigrationInSeqFile(c *C, snap string, expected *dirs.SnapDirOptions) c.Assert(err, IsNil) defer file.Close() - data, err := ioutil.ReadAll(file) + data, err := io.ReadAll(file) c.Assert(err, IsNil) // check sequence file has expected migration value diff --git a/overlord/state/copy_test.go b/overlord/state/copy_test.go index 0789b946564..eb3ebe781fa 100644 --- a/overlord/state/copy_test.go +++ b/overlord/state/copy_test.go @@ -20,7 +20,6 @@ package state_test import ( - "io/ioutil" "os" "path/filepath" @@ -94,7 +93,7 @@ func (ss *stateSuite) TestCopyStateIntegration(c *C) { c.Assert(err, IsNil) // and check that the right bits got copied - dstContent, err := ioutil.ReadFile(dstStateFile) + dstContent, err := os.ReadFile(dstStateFile) c.Assert(err, IsNil) c.Check(string(dstContent), Equals, `{"data":{"auth":{"last-id":1,"users":[{"id":1,"email":"some@user.com","macaroon":"1234","store-macaroon":"5678","store-discharges":["9012345"]}]}}`+stateSuffix) } @@ -117,7 +116,7 @@ func (ss *stateSuite) TestCopyState(c *C) { err = state.CopyState(srcStateFile, dstStateFile, []string{"A.B", "no-existing-does-not-error", "E.F", "E", "I", "E.non-existing"}) c.Assert(err, IsNil) - dstContent, err := ioutil.ReadFile(dstStateFile) + dstContent, err := os.ReadFile(dstStateFile) c.Assert(err, IsNil) c.Check(string(dstContent), Equals, `{"data":{"A":{"B":[{"C":1},{"D":2}]},"E":{"F":2,"G":3},"I":null}`+stateSuffix) } @@ -141,7 +140,7 @@ func (ss *stateSuite) TestCopyStateDuplicatesInDataEntriesAreFine(c *C) { err = state.CopyState(srcStateFile, dstStateFile, []string{"E", "E"}) c.Assert(err, IsNil) - dstContent, err := ioutil.ReadFile(dstStateFile) + dstContent, err := os.ReadFile(dstStateFile) c.Assert(err, IsNil) c.Check(string(dstContent), Equals, `{"data":{"E":{"F":2,"G":3}}`+stateSuffix) } diff --git a/polkit/pid_start_time.go b/polkit/pid_start_time.go index 9ceaf95bfcf..35fea6a86a4 100644 --- a/polkit/pid_start_time.go +++ b/polkit/pid_start_time.go @@ -22,7 +22,7 @@ package polkit import ( "fmt" - "io/ioutil" + "os" "strconv" "strings" ) @@ -39,7 +39,7 @@ func getStartTimeForPid(pid int32) (uint64, error) { // // https://cgit.freedesktop.org/polkit/tree/src/polkit/polkitunixprocess.c func getStartTimeForProcStatFile(filename string) (uint64, error) { - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { return 0, err } diff --git a/randutil/crypto.go b/randutil/crypto.go index 65c2ecf2c7d..04f0ee222d2 100644 --- a/randutil/crypto.go +++ b/randutil/crypto.go @@ -23,7 +23,7 @@ import ( cryptorand "crypto/rand" "encoding/base64" "fmt" - "io/ioutil" + "os" "strings" ) @@ -56,7 +56,7 @@ var kernelUUIDPath = "/proc/sys/kernel/random/uuid" // /proc/sys/kernel/random/uuid. Only to be used in very specific uses, most // random code should use CryptoToken(Bytes) instead. func RandomKernelUUID() (string, error) { - b, err := ioutil.ReadFile(kernelUUIDPath) + b, err := os.ReadFile(kernelUUIDPath) if err != nil { return "", fmt.Errorf("cannot read kernel generated uuid: %w", err) } diff --git a/release/release_test.go b/release/release_test.go index cef4f3a1dbf..7eb6ba50c42 100644 --- a/release/release_test.go +++ b/release/release_test.go @@ -21,7 +21,6 @@ package release_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -69,7 +68,7 @@ BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/" // MockFilesystemRootType changes relase.ProcMountsPath so that it points to a temp file // generated to contain the provided filesystem type func MockFilesystemRootType(c *C, fsType string) (restorer func()) { - tmpfile, err := ioutil.TempFile(c.MkDir(), "proc_mounts_mock_") + tmpfile, err := os.CreateTemp(c.MkDir(), "proc_mounts_mock_") c.Assert(err, IsNil) // Sample contents of /proc/mounts. The second line is the one that matters. diff --git a/run-checks b/run-checks index 9118df8bafe..80fda0463b2 100755 --- a/run-checks +++ b/run-checks @@ -207,6 +207,22 @@ if [ "$STATIC" = 1 ]; then exit 1 fi + echo "Checking for usages of deprecated io/ioutil" + got="" + for dir in $(go list -f '{{.Dir}}' ./... | grep -v '/vendor/' ); do + # shellcheck disable=SC2063 + s="$(grep -nP io/ioutil "$dir"/*.go || true)" + if [ -n "$s" ]; then + got="$s\\n$got" + fi + done + + if [ -n "$got" ]; then + echo 'Found usages of deprecated io/ioutil, please use "io" or "os" equivalents' + echo "$got" + exit 1 + fi + if command -v shellcheck >/dev/null; then exclude_tools_path=tests/lib/external/snapd-testing-tools echo "Checking shell scripts..." diff --git a/sandbox/apparmor/apparmor.go b/sandbox/apparmor/apparmor.go index f0739ec1451..3d6878bb4e8 100644 --- a/sandbox/apparmor/apparmor.go +++ b/sandbox/apparmor/apparmor.go @@ -23,7 +23,6 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -346,8 +345,8 @@ func (aap *appArmorProbe) ParserFeatures() ([]string, error) { } func probeKernelFeatures() ([]string, error) { - // note that ioutil.ReadDir() is already sorted - dentries, err := ioutil.ReadDir(filepath.Join(rootPath, featuresSysPath)) + // note that os.ReadDir() is already sorted + dentries, err := os.ReadDir(filepath.Join(rootPath, featuresSysPath)) if err != nil { return []string{}, err } @@ -356,7 +355,7 @@ func probeKernelFeatures() ([]string, error) { if fi.IsDir() { features = append(features, fi.Name()) // also read any sub-features - subdenties, err := ioutil.ReadDir(filepath.Join(rootPath, featuresSysPath, fi.Name())) + subdenties, err := os.ReadDir(filepath.Join(rootPath, featuresSysPath, fi.Name())) if err != nil { return []string{}, err } diff --git a/sandbox/apparmor/apparmor_test.go b/sandbox/apparmor/apparmor_test.go index 4ccbe4585ce..fff4cda4a21 100644 --- a/sandbox/apparmor/apparmor_test.go +++ b/sandbox/apparmor/apparmor_test.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math" "os" "path/filepath" @@ -308,7 +307,7 @@ exit "$EXIT_CODE" } c.Check(mockParserCmd.Calls(), DeepEquals, expectedCalls) - data, err := ioutil.ReadFile(filepath.Join(d, "stdin")) + data, err := os.ReadFile(filepath.Join(d, "stdin")) c.Assert(err, IsNil) c.Check(string(data), Equals, `profile snap-test { change_profile unsafe /**, @@ -493,7 +492,7 @@ func (s *apparmorSuite) TestUpdateHomedirsTunableHappy(c *C) { err := apparmor.UpdateHomedirsTunable([]string{"/home/a", "/dir2"}) c.Assert(err, IsNil) configFile := filepath.Join(dirs.GlobalRootDir, "/etc/apparmor.d/tunables/home.d/snapd") - fileContents, err := ioutil.ReadFile(configFile) + fileContents, err := os.ReadFile(configFile) c.Assert(err, IsNil) c.Check(string(fileContents), Equals, `# Generated by snapd -- DO NOT EDIT!`+"\n"+`@{HOMEDIRS}+="/home/a" "/dir2"`+"\n") diff --git a/sandbox/apparmor/process.go b/sandbox/apparmor/process.go index d1ff8827b0e..2728353bbc5 100644 --- a/sandbox/apparmor/process.go +++ b/sandbox/apparmor/process.go @@ -21,7 +21,6 @@ package apparmor import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -37,7 +36,7 @@ func labelFromPid(pid int) (string, error) { // fallback procFile = filepath.Join(rootPath, fmt.Sprintf("proc/%v/attr/current", pid)) } - contents, err := ioutil.ReadFile(procFile) + contents, err := os.ReadFile(procFile) if os.IsNotExist(err) { return "unconfined", nil } else if err != nil { diff --git a/sandbox/apparmor/profile_test.go b/sandbox/apparmor/profile_test.go index d64c2266f23..db04a960ab7 100644 --- a/sandbox/apparmor/profile_test.go +++ b/sandbox/apparmor/profile_test.go @@ -22,7 +22,6 @@ package apparmor_test import ( "errors" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -405,7 +404,7 @@ func (s *appArmorSuite) TestSetupSnapConfineSnippetsNoSnippets(c *C) { // Because overlay/nfs is not used there are no local policy files but the // directory was created. - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) } @@ -437,11 +436,13 @@ func (s *appArmorSuite) TestSetupSnapConfineSnippetsHomedirs(c *C) { // Homedirs was specified, so we expect an entry for each homedir in a // snippet 'homedirs' - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "homedirs") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) c.Assert(filepath.Join(apparmor.SnapConfineAppArmorDir, files[0].Name()), @@ -469,7 +470,7 @@ func (s *appArmorSuite) TestSetupSnapConfineGeneratedPolicyWithHomedirsLoadError // Probing apparmor_parser capabilities failed, so nothing gets written // to the snap-confine policy directory - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) @@ -498,11 +499,13 @@ func (s *appArmorSuite) TestSetupSnapConfineSnippetsBPF(c *C) { // Capability bpf is supported by the parser, so an extra policy file // for snap-confine is present - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "cap-bpf") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) c.Assert(filepath.Join(apparmor.SnapConfineAppArmorDir, files[0].Name()), @@ -532,7 +535,7 @@ func (s *appArmorSuite) TestSetupSnapConfineGeneratedPolicyWithBPFProbeError(c * // Probing apparmor_parser capabilities failed, so nothing gets written // to the snap-confine policy directory - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) @@ -557,15 +560,17 @@ func (s *appArmorSuite) TestSetupSnapConfineSnippetsOverlay(c *C) { c.Check(wasChanged, Equals, true) // Because overlay is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "overlay-root") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows upperdir access. - data, err := ioutil.ReadFile(filepath.Join(apparmor.SnapConfineAppArmorDir, files[0].Name())) + data, err := os.ReadFile(filepath.Join(apparmor.SnapConfineAppArmorDir, files[0].Name())) c.Assert(err, IsNil) c.Assert(string(data), testutil.Contains, "\"/upper/{,**/}\" r,") } @@ -587,11 +592,13 @@ func (s *appArmorSuite) TestSetupSnapConfineSnippetsNFS(c *C) { c.Check(wasChanged, Equals, true) // Because NFS is being used, we have the extra policy file. - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) c.Assert(files[0].Name(), Equals, "nfs-support") - c.Assert(files[0].Mode(), Equals, os.FileMode(0644)) + fi, err := files[0].Info() + c.Assert(err, IsNil) + c.Assert(fi.Mode().Perm(), Equals, os.FileMode(0644)) c.Assert(files[0].IsDir(), Equals, false) // The policy allows network access. @@ -629,7 +636,7 @@ func (s *appArmorSuite) TestSetupSnapConfineGeneratedPolicyError1(c *C) { // While other stuff failed we created the policy directory and didn't // write any files to it. - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Check(err, IsNil) c.Check(files, HasLen, 0) @@ -692,7 +699,7 @@ func (s *appArmorSuite) TestSetupSnapConfineGeneratedPolicyError3(c *C) { c.Check(wasChanged, Equals, false) // The policy directory was unchanged. - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 1) } @@ -711,7 +718,7 @@ func (s *appArmorSuite) TestRemoveSnapConfineSnippets(c *C) { c.Check(err, IsNil) // The files were removed - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) } @@ -728,7 +735,7 @@ func (s *appArmorSuite) TestRemoveSnapConfineSnippetsNoSnippets(c *C) { c.Check(err, IsNil) // Nothing happens - files, err := ioutil.ReadDir(apparmor.SnapConfineAppArmorDir) + files, err := os.ReadDir(apparmor.SnapConfineAppArmorDir) c.Assert(err, IsNil) c.Assert(files, HasLen, 0) } diff --git a/sandbox/cgroup/freezer.go b/sandbox/cgroup/freezer.go index 0bd715c288b..0dbaded8582 100644 --- a/sandbox/cgroup/freezer.go +++ b/sandbox/cgroup/freezer.go @@ -22,7 +22,6 @@ package cgroup import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -94,7 +93,7 @@ func freezeSnapProcessesImplV1(snapName string) error { return fmt.Errorf("cannot freeze processes of snap %q, %v", snapName, err) } for i := 0; i < 30; i++ { - data, err := ioutil.ReadFile(fname) + data, err := os.ReadFile(fname) if err != nil { return fmt.Errorf("cannot determine the freeze state of processes of snap %q, %v", snapName, err) } @@ -206,7 +205,7 @@ func freezeSnapProcessesImplV2(snapName string) error { return fmt.Errorf("cannot freeze processes of snap %q, %v", snapName, err) } for i := 0; i < 30; i++ { - data, err := ioutil.ReadFile(fname) + data, err := os.ReadFile(fname) if err != nil { if os.IsNotExist(err) { // group may be gone diff --git a/sandbox/seccomp/export_test.go b/sandbox/seccomp/export_test.go index e516925ad42..7ce07579fe5 100644 --- a/sandbox/seccomp/export_test.go +++ b/sandbox/seccomp/export_test.go @@ -20,10 +20,10 @@ package seccomp func MockIoutilReadfile(newReadfile func(string) ([]byte, error)) (restorer func()) { - old := ioutilReadFile - ioutilReadFile = newReadfile + old := osReadFile + osReadFile = newReadfile return func() { - ioutilReadFile = old + osReadFile = old } } diff --git a/sandbox/seccomp/seccomp.go b/sandbox/seccomp/seccomp.go index 566ecdd20b3..d4719f6232d 100644 --- a/sandbox/seccomp/seccomp.go +++ b/sandbox/seccomp/seccomp.go @@ -20,7 +20,7 @@ package seccomp import ( - "io/ioutil" + "os" "sort" "strings" "sync" @@ -58,10 +58,10 @@ func (scp *secCompProbe) actions() []string { return scp.probedActions } -var ioutilReadFile = ioutil.ReadFile +var osReadFile = os.ReadFile func probeActions() []string { - contents, err := ioutilReadFile("/proc/sys/kernel/seccomp/actions_avail") + contents, err := osReadFile("/proc/sys/kernel/seccomp/actions_avail") if err != nil { return []string{} } diff --git a/sandbox/selinux/selinux_linux.go b/sandbox/selinux/selinux_linux.go index 88f56a56c7e..0d240aba0ce 100644 --- a/sandbox/selinux/selinux_linux.go +++ b/sandbox/selinux/selinux_linux.go @@ -22,7 +22,7 @@ package selinux import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "github.com/snapcore/snapd/osutil" @@ -48,7 +48,7 @@ func IsEnforcing() (bool, error) { return false, nil } - rawState, err := ioutil.ReadFile(filepath.Join(mnt, "enforce")) + rawState, err := os.ReadFile(filepath.Join(mnt, "enforce")) if err != nil { return false, err } diff --git a/secboot/secboot_hooks.go b/secboot/secboot_hooks.go index b5120cb19cc..6e7d25cb88d 100644 --- a/secboot/secboot_hooks.go +++ b/secboot/secboot_hooks.go @@ -26,7 +26,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" sb "github.com/snapcore/secboot" @@ -137,7 +136,7 @@ func unlockVolumeUsingSealedKeyFDERevealKey(sealedEncryptionKeyFile, sourceDevic func unlockVolumeUsingSealedKeyFDERevealKeyV1(sealedEncryptionKeyFile, sourceDevice, targetDevice, mapperName string) (UnlockResult, error) { res := UnlockResult{IsEncrypted: true, PartDevice: sourceDevice} - sealedKey, err := ioutil.ReadFile(sealedEncryptionKeyFile) + sealedKey, err := os.ReadFile(sealedEncryptionKeyFile) if err != nil { return res, fmt.Errorf("cannot read sealed key file: %v", err) } diff --git a/secboot/secboot_tpm.go b/secboot/secboot_tpm.go index 4505fe1c3d8..8257ccf4009 100644 --- a/secboot/secboot_tpm.go +++ b/secboot/secboot_tpm.go @@ -24,7 +24,6 @@ import ( "crypto/rand" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -441,7 +440,7 @@ func ResealKeys(params *ResealKeysParams) error { return err } - authKey, err := ioutil.ReadFile(params.TPMPolicyAuthKeyFile) + authKey, err := os.ReadFile(params.TPMPolicyAuthKeyFile) if err != nil { return fmt.Errorf("cannot read the policy auth key file: %v", err) } @@ -549,7 +548,7 @@ func tpmProvision(tpm *sb_tpm2.Connection, mode TPMProvisionMode, lockoutAuthFil var currentLockoutAuth []byte if mode == TPMPartialReprovision { logger.Debugf("using existing lockout authorization") - d, err := ioutil.ReadFile(lockoutAuthFile) + d, err := os.ReadFile(lockoutAuthFile) if err != nil { return fmt.Errorf("cannot read existing lockout auth: %v", err) } @@ -703,7 +702,7 @@ func resetLockoutCounter(lockoutAuthFile string) error { } defer tpm.Close() - lockoutAuth, err := ioutil.ReadFile(lockoutAuthFile) + lockoutAuth, err := os.ReadFile(lockoutAuthFile) if err != nil { return fmt.Errorf("cannot read existing lockout auth: %v", err) } diff --git a/seed/helpers.go b/seed/helpers.go index 65b1ece54dd..44bf534f89e 100644 --- a/seed/helpers.go +++ b/seed/helpers.go @@ -21,7 +21,6 @@ package seed import ( "fmt" - "io/ioutil" "os" "path/filepath" @@ -61,7 +60,7 @@ func newMemAssertionsDB(commitObserve func(verified asserts.Assertion)) (db *ass func loadAssertions(assertsDir string, loadedFunc func(*asserts.Ref) error) (*asserts.Batch, error) { logger.Debugf("loading assertions from %s", assertsDir) - dc, err := ioutil.ReadDir(assertsDir) + dc, err := os.ReadDir(assertsDir) if err != nil { if os.IsNotExist(err) { return nil, ErrNoAssertions diff --git a/seed/internal/options20.go b/seed/internal/options20.go index 705126c95ca..62b45c3012c 100644 --- a/seed/internal/options20.go +++ b/seed/internal/options20.go @@ -21,7 +21,7 @@ package internal import ( "fmt" - "io/ioutil" + "os" "strings" "gopkg.in/yaml.v2" @@ -63,7 +63,7 @@ type Options20 struct { func ReadOptions20(optionsFn string) (*Options20, error) { errPrefix := "cannot read grade dangerous options yaml" - yamlData, err := ioutil.ReadFile(optionsFn) + yamlData, err := os.ReadFile(optionsFn) if err != nil { return nil, fmt.Errorf("%s: %v", errPrefix, err) } diff --git a/seed/internal/seed_yaml.go b/seed/internal/seed_yaml.go index b04c435a23e..88fe4fe9034 100644 --- a/seed/internal/seed_yaml.go +++ b/seed/internal/seed_yaml.go @@ -21,7 +21,7 @@ package internal import ( "fmt" - "io/ioutil" + "os" "strings" "gopkg.in/yaml.v2" @@ -62,7 +62,7 @@ type Seed16 struct { func ReadSeedYaml(fn string) (*Seed16, error) { errPrefix := "cannot read seed yaml" - yamlData, err := ioutil.ReadFile(fn) + yamlData, err := os.ReadFile(fn) if err != nil { return nil, fmt.Errorf("%s: %v", errPrefix, err) } diff --git a/seed/seedwriter/manifest_test.go b/seed/seedwriter/manifest_test.go index 68b8486519f..134184997d5 100644 --- a/seed/seedwriter/manifest_test.go +++ b/seed/seedwriter/manifest_test.go @@ -20,7 +20,6 @@ package seedwriter_test import ( - "io/ioutil" "os" "path/filepath" "time" @@ -149,7 +148,7 @@ func (s *manifestSuite) TestWriteManifest(c *C) { }, }, ) - contents, err := ioutil.ReadFile(filePath) + contents, err := os.ReadFile(filePath) c.Assert(err, IsNil) c.Check(string(contents), Equals, `canonical/base-set=4 canonical/opt-set 1 @@ -324,7 +323,7 @@ func (s *manifestSuite) TestManifestMarkValidationSetSeededUsedHappy(c *C) { manifest.Write(manifestFile) // Read it back in and verify contents - data, err := ioutil.ReadFile(manifestFile) + data, err := os.ReadFile(manifestFile) c.Assert(err, IsNil) c.Assert(string(data), Equals, "canonical/base-set=1\n") diff --git a/seed/seedwriter/writer_test.go b/seed/seedwriter/writer_test.go index 10050ad9a5c..78fb2c0f9ce 100644 --- a/seed/seedwriter/writer_test.go +++ b/seed/seedwriter/writer_test.go @@ -23,7 +23,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -890,7 +889,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore16(c *C) { }) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 3) @@ -1009,7 +1008,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore18(c *C) { }) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 6) @@ -1247,7 +1246,7 @@ func (s *writerSuite) TestLocalSnapsCore18FullUse(c *C) { } c.Check(assertedNum, Equals, 2) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 6) @@ -2037,7 +2036,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaExtraSnaps(c *C) { }) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 8) @@ -2194,7 +2193,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaLocalExtraSnaps(c *C) { }) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 8) @@ -2311,7 +2310,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20(c *C) { c.Check(p, testutil.FilePresent) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 7) @@ -2381,11 +2380,11 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20(c *C) { c.Check(filepath.Join(systemDir, "extra-snaps"), testutil.FileAbsent) // check auxiliary store info - l, err = ioutil.ReadDir(filepath.Join(systemDir, "snaps")) + l, err = os.ReadDir(filepath.Join(systemDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 1) - b, err := ioutil.ReadFile(filepath.Join(systemDir, "snaps", "aux-info.json")) + b, err := os.ReadFile(filepath.Join(systemDir, "snaps", "aux-info.json")) c.Assert(err, IsNil) var auxInfos map[string]map[string]interface{} err = json.Unmarshal(b, &auxInfos) @@ -3030,7 +3029,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20LocalSnaps(c *C) { systemDir := filepath.Join(s.opts.SeedDir, "systems", s.opts.Label) c.Check(systemDir, testutil.FilePresent) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3128,7 +3127,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20ChannelOverrides(c *C) { systemDir := filepath.Join(s.opts.SeedDir, "systems", s.opts.Label) c.Check(systemDir, testutil.FilePresent) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 5) @@ -3247,7 +3246,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20ModelOverrideSnapd(c *C) { c.Check(p, testutil.FilePresent) } - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3433,7 +3432,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20ExtraSnaps(c *C) { systemDir := filepath.Join(s.opts.SeedDir, "systems", s.opts.Label) c.Check(systemDir, testutil.FilePresent) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3589,7 +3588,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20LocalAssertedSnaps(c *C) { systemDir := filepath.Join(s.opts.SeedDir, "systems", s.opts.Label) c.Check(systemDir, testutil.FilePresent) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -3705,7 +3704,7 @@ func (s *writerSuite) TestSeedSnapsWriteMetaCore20SignedLocalAssertedSnaps(c *C) systemDir := filepath.Join(s.opts.SeedDir, "systems", s.opts.Label) c.Check(systemDir, testutil.FilePresent) - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -4101,7 +4100,7 @@ func (s *writerSuite) TestValidateValidationSetsCore20EnforcedHappy(c *C) { c.Check(systemDir, testutil.FilePresent) // check snaps - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -4211,7 +4210,7 @@ func (s *writerSuite) TestValidateValidationSetsCore18EnforcedHappy(c *C) { c.Assert(seedYaml.Snaps, HasLen, 4) // check snaps - l, err := ioutil.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) + l, err := os.ReadDir(filepath.Join(s.opts.SeedDir, "snaps")) c.Assert(err, IsNil) c.Check(l, HasLen, 4) @@ -4346,7 +4345,7 @@ func (s *writerSuite) TestManifestCorrectlyProduced(c *C) { err = w.WriteMeta() c.Assert(err, IsNil) - b, err := ioutil.ReadFile(path.Join(s.opts.SeedDir, "seed.manifest")) + b, err := os.ReadFile(path.Join(s.opts.SeedDir, "seed.manifest")) c.Assert(err, IsNil) c.Check(string(b), Equals, `core20 1 pc 1 @@ -4637,7 +4636,7 @@ sequence: 1`) // the manifest is tracking validation-sets, then we should not // see pc/pc-kernel in the manifest, instead it should just show // the validation-set tracking those. - m, err := ioutil.ReadFile(s.opts.ManifestPath) + m, err := os.ReadFile(s.opts.ManifestPath) c.Assert(err, IsNil) c.Check(string(m), Equals, `canonical/base-set 1 core20 1 diff --git a/snap/implicit.go b/snap/implicit.go index a91a87a9380..f8a01d76adb 100644 --- a/snap/implicit.go +++ b/snap/implicit.go @@ -21,7 +21,7 @@ package snap import ( "fmt" - "io/ioutil" + "os" "github.com/snapcore/snapd/osutil" ) @@ -37,7 +37,7 @@ func addImplicitHooks(snapInfo *Info, hooksDir string) error { return nil } - fileInfos, err := ioutil.ReadDir(hooksDir) + fileInfos, err := os.ReadDir(hooksDir) if err != nil { return fmt.Errorf("unable to read hooks directory: %s", err) } diff --git a/snap/pack/pack.go b/snap/pack/pack.go index dd5cefc53e1..3baa0fbbb9d 100644 --- a/snap/pack/pack.go +++ b/snap/pack/pack.go @@ -22,7 +22,6 @@ package pack import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" @@ -162,7 +161,7 @@ func snapPath(info *snap.Info, targetDir, snapName string) string { } func excludesFile() (filename string, err error) { - tmpf, err := ioutil.TempFile("", ".snap-pack-exclude-") + tmpf, err := os.CreateTemp("", ".snap-pack-exclude-") if err != nil { return "", err } diff --git a/snap/pack/pack_test.go b/snap/pack/pack_test.go index 62ebeab95a4..c14a92c5735 100644 --- a/snap/pack/pack_test.go +++ b/snap/pack/pack_test.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -124,7 +123,7 @@ func makeExampleComponentSourceDir(c *C, componentYaml string) string { metaDir := filepath.Join(tempdir, "meta") err := os.Mkdir(metaDir, 0755) c.Assert(err, IsNil) - err = ioutil.WriteFile(filepath.Join(metaDir, "component.yaml"), []byte(componentYaml), 0644) + err = os.WriteFile(filepath.Join(metaDir, "component.yaml"), []byte(componentYaml), 0644) c.Assert(err, IsNil) return tempdir } diff --git a/snap/snapdir/snapdir.go b/snap/snapdir/snapdir.go index ef2cd39c514..8b4e5618da0 100644 --- a/snap/snapdir/snapdir.go +++ b/snap/snapdir/snapdir.go @@ -22,7 +22,6 @@ package snapdir import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" @@ -85,7 +84,7 @@ func (s *SnapDir) RandomAccessFile(file string) (interface { } func (s *SnapDir) ReadFile(file string) (content []byte, err error) { - return ioutil.ReadFile(filepath.Join(s.path, file)) + return os.ReadFile(filepath.Join(s.path, file)) } func (s *SnapDir) ReadLink(file string) (string, error) { @@ -196,7 +195,7 @@ func (s *SnapDir) Walk(relative string, walkFn filepath.WalkFunc) error { } func (s *SnapDir) ListDir(path string) ([]string, error) { - fileInfos, err := ioutil.ReadDir(filepath.Join(s.path, path)) + fileInfos, err := os.ReadDir(filepath.Join(s.path, path)) if err != nil { return nil, err } diff --git a/snap/squashfs/squashfs.go b/snap/squashfs/squashfs.go index 161a177691a..f2cbd9c33c4 100644 --- a/snap/squashfs/squashfs.go +++ b/snap/squashfs/squashfs.go @@ -24,7 +24,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "os/exec" "path" @@ -228,7 +227,7 @@ func (s *Snap) Size() (size int64, err error) { } func (s *Snap) withUnpackedFile(filePath string, f func(p string) error) error { - tmpdir, err := ioutil.TempDir("", "read-file") + tmpdir, err := os.MkdirTemp("", "read-file") if err != nil { return err } @@ -264,7 +263,7 @@ func (s *Snap) RandomAccessFile(filePath string) (interface { // ReadFile returns the content of a single file inside a squashfs snap. func (s *Snap) ReadFile(filePath string) (content []byte, err error) { err = s.withUnpackedFile(filePath, func(p string) (err error) { - content, err = ioutil.ReadFile(p) + content, err = os.ReadFile(p) return }) if err != nil { diff --git a/snap/squashfs/squashfs_test.go b/snap/squashfs/squashfs_test.go index 96ff0029696..5dc9d32a68e 100644 --- a/snap/squashfs/squashfs_test.go +++ b/snap/squashfs/squashfs_test.go @@ -23,7 +23,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "math" "os" "os/exec" @@ -122,7 +122,7 @@ func (s *SquashfsTestSuite) SetUpTest(c *C) { restore := osutil.MockMountInfo("") s.AddCleanup(restore) - s.outf, err = ioutil.TempFile(c.MkDir(), "") + s.outf, err = os.CreateTemp(c.MkDir(), "") c.Assert(err, IsNil) s.oldStdout, s.oldStderr = os.Stdout, os.Stderr os.Stdout, os.Stderr = s.outf, s.outf @@ -134,7 +134,7 @@ func (s *SquashfsTestSuite) TearDownTest(c *C) { // this ensures things were quiet _, err := s.outf.Seek(0, 0) c.Assert(err, IsNil) - outbuf, err := ioutil.ReadAll(s.outf) + outbuf, err := io.ReadAll(s.outf) c.Assert(err, IsNil) c.Check(string(outbuf), Equals, "") } diff --git a/snap/sysparams/sysparams.go b/snap/sysparams/sysparams.go index 4601847189d..e5b0a82002b 100644 --- a/snap/sysparams/sysparams.go +++ b/snap/sysparams/sysparams.go @@ -22,7 +22,7 @@ package sysparams import ( "bufio" "fmt" - "io/ioutil" + "os" "strings" "github.com/snapcore/snapd/dirs" @@ -98,7 +98,7 @@ func Open(rootdir string) (*SystemParams, error) { return &SystemParams{rootdir: rootdir}, nil } - data, err := ioutil.ReadFile(sspFile) + data, err := os.ReadFile(sspFile) if err != nil { return nil, fmt.Errorf("cannot read system-params: %v", err) } diff --git a/snapdtool/cmdutil.go b/snapdtool/cmdutil.go index 8ac3f4307c2..74bb3e56be5 100644 --- a/snapdtool/cmdutil.go +++ b/snapdtool/cmdutil.go @@ -24,7 +24,7 @@ import ( "bytes" "debug/elf" "fmt" - "io/ioutil" + "io" "os" "os/exec" "path/filepath" @@ -44,7 +44,7 @@ func elfInterp(cmd string) (string, error) { for _, prog := range el.Progs { if prog.Type == elf.PT_INTERP { r := prog.Open() - interp, err := ioutil.ReadAll(r) + interp, err := io.ReadAll(r) if err != nil { return "", nil } diff --git a/snapdtool/tool_linux_test.go b/snapdtool/tool_linux_test.go index 694346225ad..cc613615862 100644 --- a/snapdtool/tool_linux_test.go +++ b/snapdtool/tool_linux_test.go @@ -1,7 +1,6 @@ package snapdtool_test import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -89,7 +88,7 @@ VERSION=42 ` func benchmarkCSRE(b *testing.B, data string) { - tempdir, err := ioutil.TempDir("", "") + tempdir, err := os.MkdirTemp("", "") if err != nil { b.Fatalf("tempdir: %v", err) } diff --git a/store/auth.go b/store/auth.go index 422e7bec760..024364e41df 100644 --- a/store/auth.go +++ b/store/auth.go @@ -24,7 +24,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "sync" @@ -269,7 +268,7 @@ func requestDeviceSession(httpClient *http.Client, deviceSessionEndpoint string, if resp.StatusCode == 200 || resp.StatusCode == 202 { return json.NewDecoder(resp.Body).Decode(&responseData) } - body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1e6)) // do our best to read the body + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1e6)) // do our best to read the body return fmt.Errorf("store server returned status %d and body %q", resp.StatusCode, body) }) if err != nil { diff --git a/store/auth_u1_test.go b/store/auth_u1_test.go index 9d85b54e1d9..134f09f949a 100644 --- a/store/auth_u1_test.go +++ b/store/auth_u1_test.go @@ -21,7 +21,6 @@ package store_test import ( "io" - "io/ioutil" "net/http" "net/http/httptest" "time" @@ -240,7 +239,7 @@ func (s *authTestSuite) TestRefreshDischargeMacaroonMissingData(c *C) { func (s *authTestSuite) TestRefreshDischargeMacaroonError(c *C) { n := 0 mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - data, err := ioutil.ReadAll(r.Body) + data, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Assert(data, NotNil) c.Assert(string(data), Equals, `{"discharge_macaroon":"soft-expired-serialized-discharge-macaroon"}`) @@ -374,7 +373,7 @@ func (pe *testDeviceSessionRequestParamsEncoder) EncodedModel() string { func (s *authTestSuite) TestRequestDeviceSession(c *C) { mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(jsonReq), Equals, `{"device-session-request":"session-request","model-assertion":"model-assertion","serial-assertion":"serial-assertion"}`) c.Check(r.Header.Get("X-Device-Authorization"), Equals, "") @@ -391,7 +390,7 @@ func (s *authTestSuite) TestRequestDeviceSession(c *C) { func (s *authTestSuite) TestRequestDeviceSessionWithPreviousSession(c *C) { mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(jsonReq), Equals, `{"device-session-request":"session-request","model-assertion":"model-assertion","serial-assertion":"serial-assertion"}`) c.Check(r.Header.Get("X-Device-Authorization"), Equals, `Macaroon root="previous-session"`) diff --git a/store/cache.go b/store/cache.go index 2e3ad3e19f6..8e19c5a5093 100644 --- a/store/cache.go +++ b/store/cache.go @@ -22,7 +22,6 @@ package store import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -148,7 +147,7 @@ func (cm *CacheManager) Put(cacheKey, sourcePath string) error { func (cm *CacheManager) count() int { // TODO: Use something more effective than a list of all entries // here. This will waste a lot of memory on large dirs. - if l, err := ioutil.ReadDir(cm.cacheDir); err == nil { + if l, err := os.ReadDir(cm.cacheDir); err == nil { return len(l) } return 0 @@ -161,10 +160,22 @@ func (cm *CacheManager) path(cacheKey string) string { // cleanup ensures that only maxItems are stored in the cache func (cm *CacheManager) cleanup() error { - fil, err := ioutil.ReadDir(cm.cacheDir) + entries, err := os.ReadDir(cm.cacheDir) if err != nil { return err } + + // we need the modtime so convert to FileInfo + fil := make([]os.FileInfo, 0, len(entries)) + for _, entry := range entries { + fi, err := entry.Info() + if err != nil { + return err + } + + fil = append(fil, fi) + } + if len(fil) <= cm.maxItems { return nil } diff --git a/store/store_action_fetch_assertions_test.go b/store/store_action_fetch_assertions_test.go index 3306953f7cc..ed01d07ff51 100644 --- a/store/store_action_fetch_assertions_test.go +++ b/store/store_action_fetch_assertions_test.go @@ -22,7 +22,7 @@ package store_test import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -81,7 +81,7 @@ func (s *storeActionFetchAssertionsSuite) testFetch(c *C, assertionMaxFormats ma // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -187,7 +187,7 @@ func (s *storeActionFetchAssertionsSuite) TestUpdateIfNewerThan(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -318,7 +318,7 @@ func (s *storeActionFetchAssertionsSuite) TestFetchNotFound(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -413,7 +413,7 @@ func (s *storeActionFetchAssertionsSuite) TestFetchValidationSetNotFound(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -584,7 +584,7 @@ func (s *storeActionFetchAssertionsSuite) TestUpdateSequenceForming(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -734,7 +734,7 @@ func (s *storeActionFetchAssertionsSuite) TestUpdateSequenceFormingCommonGroupin // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -899,7 +899,7 @@ func (s *storeActionFetchAssertionsSuite) TestFetchOptionalPrimaryKeys(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` diff --git a/store/store_action_test.go b/store/store_action_test.go index d003cb4da84..d93ce24e52e 100644 --- a/store/store_action_test.go +++ b/store/store_action_test.go @@ -23,7 +23,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -95,7 +94,7 @@ func (s *storeActionSuite) TestSnapAction(c *C) { c.Check(r.Header.Get("Snap-Device-Location"), Equals, "") c.Check(r.Header.Get("Snap-Classic"), Equals, "false") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -206,7 +205,7 @@ func (s *storeActionSuite) TestSnapActionNonZeroEpochAndEpochBump(c *C) { c.Check(r.Header.Get("Snap-Device-Architecture"), Equals, arch.DpkgArchitecture()) c.Check(r.Header.Get("Snap-Classic"), Equals, "false") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -305,7 +304,7 @@ func (s *storeActionSuite) TestSnapActionNoResults(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -369,7 +368,7 @@ func (s *storeActionSuite) TestSnapActionRefreshedDateIsOptional(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -422,7 +421,7 @@ func (s *storeActionSuite) TestSnapActionSkipBlocked(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -511,7 +510,7 @@ func (s *storeActionSuite) TestSnapActionSkipCurrent(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -672,7 +671,7 @@ func (s *storeActionSuite) TestSnapActionIgnoreValidation(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -828,7 +827,7 @@ func (s *storeActionSuite) TestInstallFallbackChannelIsStable(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -923,7 +922,7 @@ func (s *storeActionSuite) TestSnapActionNonDefaultsHeaders(c *C) { c.Check(r.Header.Get("Snap-Device-Location"), Equals, `cloud-name="gcp" region="us-west1" availability-zone="us-west1-b"`) c.Check(r.Header.Get("Snap-Classic"), Equals, "true") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1018,7 +1017,7 @@ func (s *storeActionSuite) TestSnapActionWithDeltas(c *C) { c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) c.Check(r.Header.Get("Snap-Accept-Delta-Format"), Equals, "xdelta3") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1104,7 +1103,7 @@ func (s *storeActionSuite) TestSnapActionOptions(c *C) { c.Check(r.Header.Get("Snap-Refresh-Managed"), Equals, "true") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1222,7 +1221,7 @@ func (s *storeActionSuite) testSnapActionGet(action, cohort, redirectChannel str c.Check(r.Header.Get("Snap-Device-Architecture"), Equals, arch.DpkgArchitecture()) c.Check(r.Header.Get("Snap-Classic"), Equals, "false") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1335,7 +1334,7 @@ func (s *storeActionSuite) TestSnapActionInstallAmend(c *C) { c.Check(r.Header.Get("Snap-Device-Architecture"), Equals, arch.DpkgArchitecture()) c.Check(r.Header.Get("Snap-Classic"), Equals, "false") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1505,7 +1504,7 @@ func (s *storeActionSuite) testSnapActionGetWithRevision(action string, c *C) { c.Check(r.Header.Get("Snap-Device-Architecture"), Equals, arch.DpkgArchitecture()) c.Check(r.Header.Get("Snap-Classic"), Equals, "false") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1582,7 +1581,7 @@ func (s *storeActionSuite) TestSnapActionRevisionNotAvailable(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1763,7 +1762,7 @@ func (s *storeActionSuite) TestSnapActionSnapNotFound(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -1887,7 +1886,7 @@ func (s *storeActionSuite) TestSnapActionOtherErrors(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2239,7 +2238,7 @@ func (s *storeActionSuite) TestSnapActionRefreshesBothAuths(c *C) { io.WriteString(w, `{"nonce": "1234567890:9876543210"}`) case authSessionPath: // validity of request - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req map[string]string err = json.Unmarshal(jsonReq, &req) @@ -2301,7 +2300,7 @@ func (s *storeActionSuite) TestSnapActionRefreshParallelInstall(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2404,7 +2403,7 @@ func (s *storeActionSuite) TestSnapActionRefreshStableInstanceKey(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2515,7 +2514,7 @@ func (s *storeActionSuite) TestSnapActionRefreshWithHeld(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2609,7 +2608,7 @@ func (s *storeActionSuite) TestSnapActionRefreshWithHeldUnsupportedProxy(c *C) { // mock version that doesn't support `held` field (e.g. 52) w.Header().Set("Snap-Store-Version", "52") - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2708,7 +2707,7 @@ func (s *storeActionSuite) TestSnapActionRefreshWithValidationSets(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2800,7 +2799,7 @@ func (s *storeActionSuite) TestSnapActionRevisionNotAvailableParallelInstall(c * // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -2946,7 +2945,7 @@ func (s *storeActionSuite) TestSnapActionInstallParallelInstall(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -3060,7 +3059,7 @@ func (s *storeActionSuite) TestSnapActionInstallUnexpectedInstallKey(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -3144,7 +3143,7 @@ func (s *storeActionSuite) TestSnapActionRefreshUnexpectedInstanceKey(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` @@ -3228,7 +3227,7 @@ func (s *storeActionSuite) TestSnapActionUnexpectedErrorKey(c *C) { // check device authorization is set, implicitly checking doRequest was used c.Check(r.Header.Get("Snap-Device-Authorization"), Equals, `Macaroon root="device-macaroon"`) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req struct { Context []map[string]interface{} `json:"context"` diff --git a/store/store_download_test.go b/store/store_download_test.go index 67a30df28b5..279d6a811d6 100644 --- a/store/store_download_test.go +++ b/store/store_download_test.go @@ -25,7 +25,6 @@ import ( "crypto" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -599,7 +598,7 @@ func (s *storeDownloadSuite) TestDownloadDelta(c *C) { }) defer restore() - w, err := ioutil.TempFile("", "") + w, err := os.CreateTemp("", "") c.Assert(err, IsNil) defer os.Remove(w.Name()) @@ -764,7 +763,7 @@ func (s *storeDownloadSuite) TestDownloadStreamOK(c *C) { restore := store.MockDoDownloadReq(func(ctx context.Context, url *url.URL, cdnHeader string, resume int64, s *store.Store, user *auth.UserState) (*http.Response, error) { c.Check(url.String(), Equals, "URL") r := &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(expectedContent[resume:])), + Body: io.NopCloser(bytes.NewReader(expectedContent[resume:])), } if resume > 0 { r.StatusCode = 206 diff --git a/store/store_test.go b/store/store_test.go index 3716290cc8f..e4079f2d16a 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -475,7 +474,7 @@ func (s *storeTestSuite) TestDoRequestSetsAuth(c *C) { defer response.Body.Close() c.Assert(err, IsNil) - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") } @@ -511,7 +510,7 @@ func (s *storeTestSuite) TestDoRequestDoesNotSetAuthForLocalOnlyUser(c *C) { defer response.Body.Close() c.Assert(err, IsNil) - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") } @@ -544,7 +543,7 @@ func (s *storeTestSuite) TestDoRequestAuthNoSerial(c *C) { defer response.Body.Close() c.Assert(err, IsNil) - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") } @@ -589,7 +588,7 @@ func (s *storeTestSuite) TestDoRequestRefreshesAuth(c *C) { defer response.Body.Close() c.Assert(err, IsNil) - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") c.Check(refreshDischargeEndpointHit, Equals, true) @@ -641,7 +640,7 @@ func (s *storeTestSuite) TestEnsureDeviceSession(c *C) { io.WriteString(w, `{"nonce": "1234567890:9876543210"}`) case authSessionPath: // validity of request - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req map[string]string err = json.Unmarshal(jsonReq, &req) @@ -687,7 +686,7 @@ func (s *storeTestSuite) TestEnsureDeviceSessionSerialisation(c *C) { io.WriteString(w, `{"nonce": "1234567890:9876543210"}`) case authSessionPath: // validity of request - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req map[string]string err = json.Unmarshal(jsonReq, &req) @@ -775,7 +774,7 @@ func (s *storeTestSuite) TestDoRequestSetsAndRefreshesDeviceAuth(c *C) { io.WriteString(w, `{"nonce": "1234567890:9876543210"}`) case authSessionPath: // validity of request - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req map[string]string err = json.Unmarshal(jsonReq, &req) @@ -815,7 +814,7 @@ func (s *storeTestSuite) TestDoRequestSetsAndRefreshesDeviceAuth(c *C) { c.Assert(err, IsNil) defer response.Body.Close() - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") c.Check(deviceSessionRequested, Equals, true) @@ -866,7 +865,7 @@ func (s *storeTestSuite) TestDoRequestSetsAndRefreshesBothAuths(c *C) { io.WriteString(w, `{"nonce": "1234567890:9876543210"}`) case authSessionPath: // validity of request - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) var req map[string]string err = json.Unmarshal(jsonReq, &req) @@ -907,7 +906,7 @@ func (s *storeTestSuite) TestDoRequestSetsAndRefreshesBothAuths(c *C) { c.Check(resp.StatusCode, Equals, 200) - responseData, err := ioutil.ReadAll(resp.Body) + responseData, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") c.Check(refreshDischargeEndpointHit, Equals, true) @@ -941,7 +940,7 @@ func (s *storeTestSuite) TestDoRequestSetsExtraHeaders(c *C) { defer response.Body.Close() c.Assert(err, IsNil) - responseData, err := ioutil.ReadAll(response.Body) + responseData, err := io.ReadAll(response.Body) c.Assert(err, IsNil) c.Check(string(responseData), Equals, "response-data") } @@ -4008,7 +4007,7 @@ func (s *storeTestSuite) TestBuy(c *C) { c.Check(r.Header.Get("Accept"), Equals, store.JsonContentType) c.Check(r.Header.Get("Content-Type"), Equals, store.JsonContentType) c.Check(r.URL.Path, Equals, buyPath) - jsonReq, err := ioutil.ReadAll(r.Body) + jsonReq, err := io.ReadAll(r.Body) c.Assert(err, IsNil) c.Check(string(jsonReq), Equals, test.expectedInput) if test.buyErrorCode == "" { diff --git a/store/tooling/auth.go b/store/tooling/auth.go index 50bc6f3d1af..c958f9c3836 100644 --- a/store/tooling/auth.go +++ b/store/tooling/auth.go @@ -24,7 +24,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" "net/http" "os" @@ -61,7 +60,7 @@ func getAuthorizer() (store.Authorizer, error) { } var err error - data, err = ioutil.ReadFile(authFn) + data, err = os.ReadFile(authFn) if err != nil { return nil, fmt.Errorf("cannot read auth file %q: %v", authFn, err) } diff --git a/syscheck/squashfs.go b/syscheck/squashfs.go index e62a56f7ae8..29933a202c1 100644 --- a/syscheck/squashfs.go +++ b/syscheck/squashfs.go @@ -25,7 +25,6 @@ import ( "encoding/base64" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -82,13 +81,13 @@ func checkSquashfsMount() error { return err } - tmpSquashfsFile, err := ioutil.TempFile("", "syscheck-squashfs-") + tmpSquashfsFile, err := os.CreateTemp("", "syscheck-squashfs-") if err != nil { return err } defer os.Remove(tmpSquashfsFile.Name()) - tmpMountDir, err := ioutil.TempDir("", "syscheck-mountpoint-") + tmpMountDir, err := os.MkdirTemp("", "syscheck-mountpoint-") if err != nil { return err } @@ -127,7 +126,7 @@ func checkSquashfsMount() error { }() // syscheck check the - content, err := ioutil.ReadFile(filepath.Join(tmpMountDir, "canary.txt")) + content, err := os.ReadFile(filepath.Join(tmpMountDir, "canary.txt")) if err != nil { return fmt.Errorf("squashfs mount returned no err but canary file cannot be read") } diff --git a/syscheck/version.go b/syscheck/version.go index 3941949aa1a..7abc9324c2e 100644 --- a/syscheck/version.go +++ b/syscheck/version.go @@ -22,7 +22,7 @@ package syscheck import ( "bytes" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" @@ -41,7 +41,7 @@ func init() { // and set to proper value func supportsMayDetachMounts(kver string) error { p := filepath.Join(dirs.GlobalRootDir, "/proc/sys/fs/may_detach_mounts") - value, err := ioutil.ReadFile(p) + value, err := os.ReadFile(p) if err != nil { return fmt.Errorf("cannot read the value of fs.may_detach_mounts kernel parameter: %v", err) } diff --git a/sysconfig/cloudinit.go b/sysconfig/cloudinit.go index 2d389edde55..2a61d2d3378 100644 --- a/sysconfig/cloudinit.go +++ b/sysconfig/cloudinit.go @@ -22,7 +22,6 @@ package sysconfig import ( "encoding/json" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -169,14 +168,14 @@ func filterCloudCfgFile(in string, allowedDatasources []string) (string, error) // intersect with what we support dstFileName := filepath.Base(in) - filteredFile, err := ioutil.TempFile("", dstFileName) + filteredFile, err := os.CreateTemp("", dstFileName) if err != nil { return "", err } defer filteredFile.Close() // open the source and unmarshal it as yaml - unfilteredFileBytes, err := ioutil.ReadFile(in) + unfilteredFileBytes, err := os.ReadFile(in) if err != nil { return "", err } @@ -238,7 +237,7 @@ func cloudDatasourcesInUse(configFile string) (*cloudDatasourcesInUseResult, err // TODO: are there other keys in addition to those that we support in // filtering that might mention datasources ? - b, err := ioutil.ReadFile(configFile) + b, err := os.ReadFile(configFile) if err != nil { return nil, err } diff --git a/sysconfig/cloudinit_test.go b/sysconfig/cloudinit_test.go index 356d81776a1..4aaa8b90056 100644 --- a/sysconfig/cloudinit_test.go +++ b/sysconfig/cloudinit_test.go @@ -21,7 +21,6 @@ package sysconfig_test import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -1445,7 +1444,7 @@ reporting: } // otherwise we have expected output in the file - b, err := ioutil.ReadFile(out) + b, err := os.ReadFile(out) c.Assert(err, IsNil, comment) c.Assert(string(b), Equals, t.outStr, comment) } diff --git a/systemd/systemd_test.go b/systemd/systemd_test.go index d729cfe00c2..dec51960e0d 100644 --- a/systemd/systemd_test.go +++ b/systemd/systemd_test.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -186,7 +185,7 @@ func (s *SystemdTestSuite) myJctl(svcs []string, n int, follow, namespaces bool) return nil, err } - return ioutil.NopCloser(bytes.NewReader(out)), err + return io.NopCloser(bytes.NewReader(out)), err } func (s *SystemdTestSuite) TestMockVersion(c *C) { @@ -945,7 +944,7 @@ func (s *SystemdTestSuite) TestLogs(c *C) { reader, err := New(SystemMode, s.rep).LogReader([]string{"foo"}, 24, false, false) c.Check(err, IsNil) - logs, err := ioutil.ReadAll(reader) + logs, err := io.ReadAll(reader) c.Assert(err, IsNil) c.Check(string(logs), Equals, expected) c.Check(s.jns, DeepEquals, []string{"24"}) @@ -2223,7 +2222,7 @@ HereIsOneLineWithoutAnEqualSign } func (s *SystemdTestSuite) TestListMountUnitsHappy(c *C) { - tmpDir, err := ioutil.TempDir("/tmp", "snapd-systemd-test-list-mounts-*") + tmpDir, err := os.MkdirTemp("/tmp", "snapd-systemd-test-list-mounts-*") c.Assert(err, IsNil) defer os.RemoveAll(tmpDir) diff --git a/tests/lib/fakestore/cmd/fakestore/cmd_new_repair.go b/tests/lib/fakestore/cmd/fakestore/cmd_new_repair.go index c7d2398e453..77e3033b4e5 100644 --- a/tests/lib/fakestore/cmd/fakestore/cmd_new_repair.go +++ b/tests/lib/fakestore/cmd/fakestore/cmd_new_repair.go @@ -22,7 +22,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "os" "github.com/snapcore/snapd/tests/lib/fakestore/refresh" ) @@ -39,7 +39,7 @@ type cmdNewRepair struct { func (x *cmdNewRepair) Execute(args []string) error { headers := map[string]interface{}{} if x.RepairJSON != "" { - content, err := ioutil.ReadFile(x.RepairJSON) + content, err := os.ReadFile(x.RepairJSON) if err != nil { return err } diff --git a/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_decl.go b/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_decl.go index e2e6b707f95..110b5b91e02 100644 --- a/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_decl.go +++ b/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_decl.go @@ -22,7 +22,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "os" "github.com/snapcore/snapd/tests/lib/fakestore/refresh" ) @@ -39,7 +39,7 @@ type cmdNewSnapDeclaration struct { func (x *cmdNewSnapDeclaration) Execute(args []string) error { headers := map[string]interface{}{} if x.SnapDeclJsonPath != "" { - content, err := ioutil.ReadFile(x.SnapDeclJsonPath) + content, err := os.ReadFile(x.SnapDeclJsonPath) if err != nil { return err } diff --git a/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_rev.go b/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_rev.go index 65509b4576c..82bb653e8c0 100644 --- a/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_rev.go +++ b/tests/lib/fakestore/cmd/fakestore/cmd_new_snap_rev.go @@ -22,7 +22,7 @@ package main import ( "encoding/json" "fmt" - "io/ioutil" + "os" "github.com/snapcore/snapd/tests/lib/fakestore/refresh" ) @@ -39,7 +39,7 @@ type cmdNewSnapRevision struct { func (x *cmdNewSnapRevision) Execute(args []string) error { headers := map[string]interface{}{} if x.SnapRevJsonPath != "" { - content, err := ioutil.ReadFile(x.SnapRevJsonPath) + content, err := os.ReadFile(x.SnapRevJsonPath) if err != nil { return err } diff --git a/tests/lib/fakestore/refresh/refresh.go b/tests/lib/fakestore/refresh/refresh.go index 9f1bf3aaf6d..c0d2bddbb66 100644 --- a/tests/lib/fakestore/refresh/refresh.go +++ b/tests/lib/fakestore/refresh/refresh.go @@ -21,7 +21,6 @@ package refresh import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -114,7 +113,7 @@ func writeAssert(a asserts.Assertion, targetDir string) (string, error) { func makeFakeRefreshForSnap(snap, targetDir, snapBlob, snapOrigBlob string, db *asserts.Database, f asserts.Fetcher) error { // make a fake update snap in /var/tmp (which is not a tempfs) - fakeUpdateDir, err := ioutil.TempDir("/var/tmp", "snap-build-") + fakeUpdateDir, err := os.MkdirTemp("/var/tmp", "snap-build-") if err != nil { return fmt.Errorf("creating tmp for fake update: %v", err) } diff --git a/tests/lib/fakestore/refresh/snap_asserts.go b/tests/lib/fakestore/refresh/snap_asserts.go index 632d2a652df..cc03b6b87f7 100644 --- a/tests/lib/fakestore/refresh/snap_asserts.go +++ b/tests/lib/fakestore/refresh/snap_asserts.go @@ -21,7 +21,7 @@ package refresh import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "time" @@ -115,7 +115,7 @@ func NewRepair(targetDir string, scriptFilename string, headers map[string]inter } } - scriptBodyBytes, err := ioutil.ReadFile(scriptFilename) + scriptBodyBytes, err := os.ReadFile(scriptFilename) if err != nil { return "", err } diff --git a/tests/lib/fakestore/store/store.go b/tests/lib/fakestore/store/store.go index 0a5daf4587f..7c9d3f069ef 100644 --- a/tests/lib/fakestore/store/store.go +++ b/tests/lib/fakestore/store/store.go @@ -24,10 +24,10 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net" "net/http" "net/url" + "os" "path/filepath" "regexp" "strconv" @@ -561,7 +561,7 @@ func (s *Store) collectAssertions() (asserts.Backstore, error) { } for _, fn := range aFiles { - b, err := ioutil.ReadFile(fn) + b, err := os.ReadFile(fn) if err != nil { return nil, err } diff --git a/tests/lib/fakestore/store/store_test.go b/tests/lib/fakestore/store/store_test.go index a7959b3839a..12b1ee4f89a 100644 --- a/tests/lib/fakestore/store/store_test.go +++ b/tests/lib/fakestore/store/store_test.go @@ -22,7 +22,7 @@ package store import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -97,7 +97,7 @@ func (s *storeTestSuite) TestTrivialGetWorks(c *C) { defer resp.Body.Close() c.Assert(resp.StatusCode, Equals, 418) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Assert(string(body), Equals, "I'm a teapot") @@ -109,7 +109,7 @@ func (s *storeTestSuite) TestSearchEndpoint(c *C) { defer resp.Body.Close() c.Assert(resp.StatusCode, Equals, 501) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Assert(string(body), Equals, "search not implemented") @@ -471,7 +471,7 @@ func (s *storeTestSuite) TestAssertionsEndpointPreloaded(c *C) { c.Assert(resp.StatusCode, Equals, 200) c.Check(resp.Header.Get("Content-Type"), Equals, "application/x.ubuntu.assertion") - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, string(asserts.Encode(systestkeys.TestRootAccount))) } @@ -490,7 +490,7 @@ func (s *storeTestSuite) TestAssertionsEndpointFromAssertsDir(c *C) { defer resp.Body.Close() c.Assert(resp.StatusCode, Equals, 200) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, exampleSnapRev) } @@ -504,7 +504,7 @@ func (s *storeTestSuite) TestAssertionsEndpointSequenceAssertion(c *C) { defer resp.Body.Close() c.Check(resp.StatusCode, Equals, 200) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, exampleValidationSet) } @@ -518,7 +518,7 @@ func (s *storeTestSuite) TestAssertionsEndpointSequenceAssertionLatest(c *C) { defer resp.Body.Close() c.Check(resp.StatusCode, Equals, 200) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, exampleValidationSet) } @@ -532,7 +532,7 @@ func (s *storeTestSuite) TestAssertionsEndpointSequenceAssertionInvalidSequence( defer resp.Body.Close() c.Assert(resp.StatusCode, Equals, 400) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, "cannot retrieve assertion [16 canonical base-set]: the requested sequence must be above 0\n") } @@ -543,7 +543,7 @@ func (s *storeTestSuite) TestAssertionsEndpointSequenceInvalid(c *C) { defer resp.Body.Close() c.Assert(resp.StatusCode, Equals, 400) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, IsNil) c.Check(string(body), Equals, "cannot retrieve assertion [16 canonical base-set]: cannot parse sequence foo: strconv.Atoi: parsing \"foo\": invalid syntax\n") } diff --git a/tests/lib/fde-setup-hook-v1/fde-setup.go b/tests/lib/fde-setup-hook-v1/fde-setup.go index 43b0c38e4ea..ec4840cfd04 100644 --- a/tests/lib/fde-setup-hook-v1/fde-setup.go +++ b/tests/lib/fde-setup-hook-v1/fde-setup.go @@ -5,7 +5,7 @@ import ( "encoding/base64" "encoding/json" "fmt" - "io/ioutil" + "io" "os" "os/exec" "path/filepath" @@ -109,7 +109,7 @@ func runFdeRevealKey() error { var js fdeRevealJSON var jsStrict fdeRevealJSONStrict - b, err := ioutil.ReadAll(os.Stdin) + b, err := io.ReadAll(os.Stdin) if err != nil { return err } diff --git a/tests/lib/fde-setup-hook/fde-setup.go b/tests/lib/fde-setup-hook/fde-setup.go index 702b3fff487..ac649ff89bb 100644 --- a/tests/lib/fde-setup-hook/fde-setup.go +++ b/tests/lib/fde-setup-hook/fde-setup.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -69,7 +68,7 @@ func runFdeSetup() error { if fromInitrd { var err error - input, err = ioutil.ReadAll(os.Stdin) + input, err = io.ReadAll(os.Stdin) if err != nil { return err } @@ -157,7 +156,7 @@ func runFdeRevealKey() error { var js fdeRevealJSON var jsStrict fdeRevealJSONStrict - b, err := ioutil.ReadAll(osStdin) + b, err := io.ReadAll(osStdin) if err != nil { return err } diff --git a/tests/lib/muinstaller/main.go b/tests/lib/muinstaller/main.go index a8aa10c6df8..6799eeb3d62 100644 --- a/tests/lib/muinstaller/main.go +++ b/tests/lib/muinstaller/main.go @@ -25,7 +25,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -75,7 +74,7 @@ func emptyFixedBlockDevices() (devices []string, err error) { } devicesLoop: for _, removableAttr := range removable { - val, err := ioutil.ReadFile(removableAttr) + val, err := os.ReadFile(removableAttr) if err != nil || string(val) != "0\n" { // removable, ignore continue diff --git a/testutil/exec.go b/testutil/exec.go index ce5ac173ccb..8f210e935ef 100644 --- a/testutil/exec.go +++ b/testutil/exec.go @@ -23,7 +23,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "os/exec" "path" @@ -193,7 +192,7 @@ func (cmd *MockCmd) Restore() { // {"cmd", "arg1", "arg2"}, // second invocation of "cmd" // } func (cmd *MockCmd) Calls() [][]string { - raw, err := ioutil.ReadFile(cmd.logFile) + raw, err := os.ReadFile(cmd.logFile) if os.IsNotExist(err) { return nil } diff --git a/testutil/exec_test.go b/testutil/exec_test.go index d757cb3afde..19c98d1807c 100644 --- a/testutil/exec_test.go +++ b/testutil/exec_test.go @@ -21,7 +21,6 @@ package testutil import ( "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -90,11 +89,11 @@ func (s *mockCommandSuite) TestMockShellchecksWhenAvailable(c *check.C) { {"shellcheck", "-s", "bash", "-"}, }) - scriptData, err := ioutil.ReadFile(mock.Exe()) + scriptData, err := os.ReadFile(mock.Exe()) c.Assert(err, check.IsNil) c.Assert(string(scriptData), Contains, "\necho some-command\n") - data, err := ioutil.ReadFile(filepath.Join(tmpDir, "input")) + data, err := os.ReadFile(filepath.Join(tmpDir, "input")) c.Assert(err, check.IsNil) c.Assert(data, check.DeepEquals, scriptData) } diff --git a/testutil/filecontentchecker.go b/testutil/filecontentchecker.go index 9c928ec30a4..d12fc3294dc 100644 --- a/testutil/filecontentchecker.go +++ b/testutil/filecontentchecker.go @@ -22,7 +22,7 @@ package testutil import ( "bytes" "fmt" - "io/ioutil" + "os" "regexp" "strings" @@ -77,7 +77,7 @@ func (c *fileContentChecker) Check(params []interface{}, names []string) (result } func fileContentCheck(filename string, content interface{}, exact bool) (result bool, error string) { - buf, err := ioutil.ReadFile(filename) + buf, err := os.ReadFile(filename) if err != nil { return false, fmt.Sprintf("Cannot read file %q: %v", filename, err) } @@ -93,7 +93,7 @@ func fileContentCheck(filename string, content interface{}, exact bool) (result result = presentableBuf == content.String() case FileContentRef: referenceFilename := string(content) - reference, err := ioutil.ReadFile(referenceFilename) + reference, err := os.ReadFile(referenceFilename) if err != nil { return false, fmt.Sprintf("Cannot read reference file %q: %v", referenceFilename, err) } diff --git a/testutil/lowlevel.go b/testutil/lowlevel.go index c22a2b9d78f..de3c9c02677 100644 --- a/testutil/lowlevel.go +++ b/testutil/lowlevel.go @@ -21,6 +21,7 @@ package testutil import ( "fmt" + "io/fs" "os" "strings" "syscall" @@ -55,6 +56,27 @@ func FakeFileInfo(name string, mode os.FileMode) os.FileInfo { return &fakeFileInfo{name: name, mode: mode} } +// fakeDirEntry implements fs.DirEntry for testing. +type fakeDirEntry struct { + name string + mode os.FileMode +} + +func (de *fakeDirEntry) Name() string { return de.name } +func (de *fakeDirEntry) Type() fs.FileMode { return de.mode.Type() } +func (de *fakeDirEntry) IsDir() bool { return de.Type().IsDir() } +func (de *fakeDirEntry) Info() (fs.FileInfo, error) { + return &fakeFileInfo{ + name: de.Name(), + mode: de.mode, + }, nil +} + +// FakeDirEntry returns a fake object implementing fs.DirEntry +func FakeDirEntry(name string, mode os.FileMode) fs.DirEntry { + return &fakeDirEntry{name: name, mode: mode} +} + // Convenient FakeFileInfo objects for InsertLstatResult var ( FileInfoFile = &fakeFileInfo{} @@ -160,7 +182,7 @@ type SyscallRecorder struct { sysLstats map[string]syscall.Stat_t fstats map[string]syscall.Stat_t fstatfses map[string]func() syscall.Statfs_t - readdirs map[string][]os.FileInfo + readdirs map[string][]fs.DirEntry readlinkats map[string]string // allocated file descriptors fds map[int]string @@ -467,15 +489,15 @@ func (sys *SyscallRecorder) Fstatfs(fd int, buf *syscall.Statfs_t) error { } // InsertReadDirResult makes given subsequent call readdir return the specified fake file infos. -func (sys *SyscallRecorder) InsertReadDirResult(call string, infos []os.FileInfo) { +func (sys *SyscallRecorder) InsertReadDirResult(call string, infos []fs.DirEntry) { if sys.readdirs == nil { - sys.readdirs = make(map[string][]os.FileInfo) + sys.readdirs = make(map[string][]fs.DirEntry) } sys.readdirs[call] = infos } // ReadDir is a fake implementation of os.ReadDir -func (sys *SyscallRecorder) ReadDir(dirname string) ([]os.FileInfo, error) { +func (sys *SyscallRecorder) ReadDir(dirname string) ([]fs.DirEntry, error) { call := fmt.Sprintf("readdir %q", dirname) val, err := sys.rcall(call, func(call string) (interface{}, error) { if fi, ok := sys.readdirs[call]; ok { @@ -484,7 +506,7 @@ func (sys *SyscallRecorder) ReadDir(dirname string) ([]os.FileInfo, error) { panic(fmt.Sprintf("one of InsertReadDirResult() or InsertFault() for %s must be used", call)) }) if err == nil { - return val.([]os.FileInfo), nil + return val.([]fs.DirEntry), nil } return nil, err } diff --git a/testutil/lowlevel_test.go b/testutil/lowlevel_test.go index 59116e7eccc..969c099312e 100644 --- a/testutil/lowlevel_test.go +++ b/testutil/lowlevel_test.go @@ -21,6 +21,7 @@ package testutil_test import ( "fmt" + "io/fs" "os" "syscall" @@ -40,9 +41,11 @@ func (s *lowLevelSuite) SetUpTest(c *check.C) { } func (s *lowLevelSuite) TestFakeFileInfo(c *check.C) { - ffi := testutil.FakeFileInfo("name", 0755) + ffi := testutil.FakeDirEntry("name", 0755) c.Assert(ffi.Name(), check.Equals, "name") - c.Assert(ffi.Mode(), check.Equals, os.FileMode(0755)) + fi, err := ffi.Info() + c.Assert(err, check.IsNil) + c.Assert(fi.Mode().Perm(), check.Equals, os.FileMode(0755)) c.Assert(testutil.FileInfoFile.Mode().IsDir(), check.Equals, false) c.Assert(testutil.FileInfoFile.Mode().IsRegular(), check.Equals, true) @@ -625,9 +628,9 @@ func (s *lowLevelSuite) TestReadDir(c *check.C) { } func (s *lowLevelSuite) TestReadDirSuccess(c *check.C) { - files := []os.FileInfo{ - testutil.FakeFileInfo("file", 0644), - testutil.FakeFileInfo("dir", 0755|os.ModeDir), + files := []fs.DirEntry{ + testutil.FakeDirEntry("file", 0644), + testutil.FakeDirEntry("dir", 0755|os.ModeDir), } s.sys.InsertReadDirResult(`readdir "/foo"`, files) files, err := s.sys.ReadDir("/foo") diff --git a/usersession/client/client_test.go b/usersession/client/client_test.go index 5b49d5f41d9..ffb9c5909f4 100644 --- a/usersession/client/client_test.go +++ b/usersession/client/client_test.go @@ -23,7 +23,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" "os" @@ -719,7 +719,7 @@ func (s *clientSuite) TestFinishRefreshNotification(c *C) { s.handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { atomic.AddInt32(&n, 1) c.Assert(r.URL.Path, Equals, "/v1/notifications/finish-refresh") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) c.Check(err, IsNil) c.Check(string(body), DeepEquals, `{"instance-name":"some-snap"}`) }) diff --git a/wrappers/core18.go b/wrappers/core18.go index 4128d35d65c..e524824451f 100644 --- a/wrappers/core18.go +++ b/wrappers/core18.go @@ -22,7 +22,6 @@ package wrappers import ( "bytes" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -49,7 +48,7 @@ func snapdSkipStart(content []byte) bool { // snapdUnitSkipStart returns true for units that should not be started // automatically func snapdUnitSkipStart(unitPath string) (skip bool, err error) { - content, err := ioutil.ReadFile(unitPath) + content, err := os.ReadFile(unitPath) if err != nil { if os.IsNotExist(err) { // no point in starting units that do not exist @@ -238,7 +237,7 @@ func AddSnapdSnapServices(s *snap.Info, opts *AddSnapdSnapServicesOptions, inter if err != nil { return nil, err } - content, err := ioutil.ReadFile(unit) + content, err := os.ReadFile(unit) if err != nil { return nil, err } @@ -483,7 +482,7 @@ func writeSnapdUserServicesOnCore(s *snap.Info, opts *AddSnapdSnapServicesOption if err != nil { return err } - content, err := ioutil.ReadFile(unit) + content, err := os.ReadFile(unit) if err != nil { return err } diff --git a/wrappers/dbus.go b/wrappers/dbus.go index 4813e5e07e4..b6046f9e6ca 100644 --- a/wrappers/dbus.go +++ b/wrappers/dbus.go @@ -21,7 +21,6 @@ package wrappers import ( "bytes" - "io/ioutil" "os" "path/filepath" "regexp" @@ -68,7 +67,7 @@ var snapNameLine = regexp.MustCompile(`(?m)^X-Snap=(.*)$`) // snapNameFromServiceFile returns the snap name for the D-Bus service activation file. func snapNameFromServiceFile(filename string) (owner string, err error) { - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { return "", err } diff --git a/wrappers/desktop.go b/wrappers/desktop.go index 95ce1c491bc..c39a4d51a4e 100644 --- a/wrappers/desktop.go +++ b/wrappers/desktop.go @@ -23,7 +23,6 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -258,7 +257,7 @@ func deriveDesktopFilesContent(s *snap.Info) (map[string]osutil.FileState, error content := make(map[string]osutil.FileState) for _, df := range desktopFiles { base := filepath.Base(df) - fileContent, err := ioutil.ReadFile(df) + fileContent, err := os.ReadFile(df) if err != nil { return nil, err } diff --git a/wrappers/services.go b/wrappers/services.go index 7ac9ac546c6..43f08c76e97 100644 --- a/wrappers/services.go +++ b/wrappers/services.go @@ -22,7 +22,6 @@ package wrappers import ( "context" "fmt" - "io/ioutil" "os" "os/user" "path/filepath" @@ -413,7 +412,7 @@ func tryFileUpdate(path string, desiredContent []byte) (old *osutil.MemoryFileSt oldFileState := osutil.MemoryFileState{} if st, err := os.Stat(path); err == nil { - b, err := ioutil.ReadFile(path) + b, err := os.ReadFile(path) if err != nil { return nil, false, err } diff --git a/wrappers/services_test.go b/wrappers/services_test.go index e1aa9fe0def..1b9de8e5f10 100644 --- a/wrappers/services_test.go +++ b/wrappers/services_test.go @@ -22,7 +22,6 @@ package wrappers_test import ( "errors" "fmt" - "io/ioutil" "os" "os/user" "path/filepath" @@ -4100,7 +4099,7 @@ func (s *servicesTestSuite) TestServiceWatchdog(c *C) { err := s.addSnapServices(info, false) c.Assert(err, IsNil) - content, err := ioutil.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc2.service")) + content, err := os.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc2.service")) c.Assert(err, IsNil) c.Check(strings.Contains(string(content), "\nWatchdogSec=12\n"), Equals, true) @@ -4109,7 +4108,7 @@ func (s *servicesTestSuite) TestServiceWatchdog(c *C) { filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc4.service"), } for _, svcPath := range noWatchdog { - content, err := ioutil.ReadFile(svcPath) + content, err := os.ReadFile(svcPath) c.Assert(err, IsNil) c.Check(strings.Contains(string(content), "WatchdogSec="), Equals, false) } @@ -4530,11 +4529,11 @@ func (s *servicesTestSuite) TestServiceRestartDelay(c *C) { err := s.addSnapServices(info, false) c.Assert(err, IsNil) - content, err := ioutil.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc2.service")) + content, err := os.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc2.service")) c.Assert(err, IsNil) c.Check(strings.Contains(string(content), "\nRestartSec=12\n"), Equals, true) - content, err = ioutil.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc3.service")) + content, err = os.ReadFile(filepath.Join(dirs.GlobalRootDir, "/etc/systemd/system/snap.hello-snap.svc3.service")) c.Assert(err, IsNil) c.Check(strings.Contains(string(content), "RestartSec="), Equals, false) } diff --git a/x11/xauth.go b/x11/xauth.go index b6456e4dd0d..b51acf2dd62 100644 --- a/x11/xauth.go +++ b/x11/xauth.go @@ -23,7 +23,6 @@ import ( "encoding/binary" "fmt" "io" - "io/ioutil" "os" ) @@ -122,7 +121,7 @@ func ValidateXauthority(r io.Reader) error { // MockXauthority will create a fake xauthority file and place it // on a temporary path which is returned as result. func MockXauthority(cookies int) (string, error) { - f, err := ioutil.TempFile("", "xauth") + f, err := os.CreateTemp("", "xauth") if err != nil { return "", err } diff --git a/x11/xauth_test.go b/x11/xauth_test.go index e9931587f4d..9a2eff51774 100644 --- a/x11/xauth_test.go +++ b/x11/xauth_test.go @@ -20,7 +20,6 @@ package x11_test import ( - "io/ioutil" "os" "testing" @@ -51,7 +50,7 @@ func (s *xauthTestSuite) TestXauthFileExistsButIsEmpty(c *C) { } func (s *xauthTestSuite) TestXauthFileExistsButHasInvalidContent(c *C) { - f, err := ioutil.TempFile("", "xauth") + f, err := os.CreateTemp("", "xauth") c.Assert(err, IsNil) defer os.Remove(f.Name())