From 69bc44b04f71ec08db9cf62b91966875423c9bc7 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Sun, 28 Nov 2021 12:29:43 +0800 Subject: [PATCH] chore: run `gofumpt -w .` and `go mod tidy` `gofumpt` enforces a stricter format than `gofmt`, see more here https://github.com/mvdan/gofumpt Signed-off-by: Eng Zer Jun --- cmds/boot/fbnetboot/main.go | 3 +- cmds/contrib/flash/flash.go | 6 +- cmds/core/backoff/main_test.go | 1 - cmds/core/basename/basename_test.go | 3 +- cmds/core/cat/cat.go | 4 +- cmds/core/cat/cat_test.go | 2 +- cmds/core/chmod/chmod.go | 15 +- cmds/core/chmod/chmod_test.go | 80 ++++---- cmds/core/chroot/chroot_test.go | 2 - cmds/core/cmp/cmp_test.go | 6 +- cmds/core/comm/comm_test.go | 2 +- cmds/core/cp/cp_test.go | 6 +- cmds/core/cpio/cpio_test.go | 10 +- cmds/core/cpio/testdata/dir-hard-link.go | 4 +- cmds/core/date/date_test.go | 3 +- cmds/core/dd/dd.go | 2 +- cmds/core/dd/dd_test.go | 13 +- cmds/core/df/df.go | 2 +- cmds/core/find/find.go | 2 +- cmds/core/fusermount/fusermount.go | 8 +- cmds/core/fusermount/fusermount_linux.go | 6 +- cmds/core/fusermount/fusermount_test.go | 5 +- cmds/core/gpt/gpt.go | 6 +- cmds/core/grep/grep_test.go | 2 +- cmds/core/hostname/hostname_plan9.go | 2 +- cmds/core/id/id.go | 3 - cmds/core/id/id_test.go | 6 +- cmds/core/init/init_linux.go | 1 - cmds/core/init/init_plan9.go | 1 - cmds/core/io/io.go | 12 +- cmds/core/io/smn.go | 2 +- cmds/core/ip/ip_linux.go | 1 - cmds/core/kexec/kexec_linux.go | 1 - cmds/core/kill/kill_test.go | 26 ++- cmds/core/ln/ln_test.go | 5 +- cmds/core/losetup/losetup_linux.go | 5 +- cmds/core/ls/ls.go | 2 +- cmds/core/ls/ls_linux_test.go | 2 +- cmds/core/ls/ls_plan9.go | 4 +- cmds/core/ls/ls_test.go | 6 +- cmds/core/lsdrivers/lsdrivers_linux_test.go | 8 +- cmds/core/lsdrivers/main_linux.go | 1 + cmds/core/man/gen/gen.go | 2 +- cmds/core/md5sum/md5sum_test.go | 3 +- cmds/core/mkdir/mkdir.go | 10 +- cmds/core/mkdir/mkdir_test.go | 18 +- cmds/core/mkfifo/mkfifo.go | 2 +- cmds/core/mkfifo/mkfifo_test.go | 5 +- cmds/core/mknod/mknod_linux.go | 2 +- cmds/core/mknod/mknod_test.go | 2 +- cmds/core/mktemp/mktemp.go | 4 +- cmds/core/mktemp/mktemp_test.go | 3 +- cmds/core/mount/mount.go | 1 - cmds/core/mv/mv.go | 1 - cmds/core/mv/mv_test.go | 14 +- cmds/core/pci/pci.go | 12 +- cmds/core/ps/ps.go | 4 +- cmds/core/ps/ps_linux.go | 7 +- cmds/core/ps/ps_test.go | 50 +++-- cmds/core/readlink/readlink_test.go | 10 +- cmds/core/rm/rm.go | 3 +- cmds/core/rm/rm_test.go | 12 +- cmds/core/rsdp/rsdp.go | 4 +- cmds/core/seq/seq_test.go | 9 +- cmds/core/shasum/shasum.go | 3 - cmds/core/shasum/shasum_test.go | 3 +- cmds/core/sleep/sleep_test.go | 2 +- cmds/core/sluinit/uinit_linux.go | 4 +- cmds/core/sort/sort_test.go | 16 +- cmds/core/sshd/sshd.go | 4 +- cmds/core/strings/strings.go | 4 +- cmds/core/strings/strings_test.go | 30 ++- cmds/core/stty/stty.go | 2 - cmds/core/sync/sync.go | 2 +- cmds/core/tee/tee.go | 2 +- cmds/core/time/time_test.go | 2 +- cmds/core/truncate/truncate.go | 2 +- cmds/core/truncate/truncate_test.go | 4 +- cmds/core/uniq/uniq.go | 12 +- cmds/core/uptime/uptime.go | 2 +- cmds/core/uptime/uptime_test.go | 8 +- cmds/core/watchdog/watchdog_linux.go | 4 +- cmds/core/wc/wc.go | 12 +- cmds/core/wc/wc_test.go | 2 +- cmds/core/wget/wget.go | 4 +- cmds/core/wget/wget_test.go | 12 +- cmds/core/which/which_test.go | 2 - cmds/exp/ash/parse.go | 13 +- cmds/exp/ash/tty_linux.go | 1 - cmds/exp/bootvars/main.go | 6 +- cmds/exp/builtin/builtin.go | 4 +- cmds/exp/bzimage/bzimage.go | 16 +- cmds/exp/bzimage/bzimage_test.go | 15 +- cmds/exp/cbmem/cbmem_linux_test.go | 4 +- cmds/exp/cbmem/const.go | 1 + cmds/exp/cbmem/gen/gen.go | 5 +- cmds/exp/cbmem/main_linux.go | 7 +- cmds/exp/cbmem/timestamps.go | 2 +- cmds/exp/cbmem/types.go | 4 + cmds/exp/cksum/cksum_test.go | 2 +- cmds/exp/console/console.go | 3 +- cmds/exp/disk_unlock/disk_unlock.go | 1 - cmds/exp/dmidecode/dmidecode.go | 26 ++- cmds/exp/dmidecode/dmidecode_test.go | 2 +- cmds/exp/ectool/commands.go | 122 +++++++----- cmds/exp/ectool/io.go | 4 +- cmds/exp/ed/commands.go | 20 +- cmds/exp/fdtdump/fdtdump.go | 4 +- cmds/exp/field/field.go | 22 +-- cmds/exp/forth/forth.go | 2 +- cmds/exp/freq/freq.go | 12 +- cmds/exp/hdparm/hdparm.go | 1 - cmds/exp/lsfabric/lsfabric.go | 8 +- cmds/exp/netbootxyz/netbootxyz.go | 4 +- cmds/exp/netbootxyz/network.go | 1 - cmds/exp/newsshd/newsshd.go | 1 + cmds/exp/pflask/pflask.go | 26 ++- cmds/exp/pox/pox.go | 10 +- cmds/exp/pox/pox_test.go | 6 +- cmds/exp/run/run.go | 1 - cmds/exp/run/tempfile.go | 2 +- cmds/exp/rush/parse.go | 13 +- cmds/exp/rush/rush.go | 2 +- cmds/exp/rush/tty_linux.go | 1 - cmds/exp/smbios_transfer/smbios_transfer.go | 4 +- cmds/exp/srvfiles/srvfiles.go | 1 - cmds/exp/tcz/tcz.go | 14 +- cmds/exp/validate/validate_test.go | 8 +- examples/fixmynetboot/main.go | 7 +- examples/uinit/uinit.go | 16 +- go.mod | 37 ++-- go.sum | 2 - integration/generic-tests/dhclient_test.go | 2 +- integration/generic-tests/tcz_test.go | 1 - integration/testcmd/common/common.go | 4 +- pkg/acpi/acpi.go | 1 - pkg/acpi/acpi_test.go | 5 +- pkg/acpi/rsdp.go | 4 +- pkg/acpi/sdt.go | 4 +- pkg/acpi/tables_linux_test.go | 1 - pkg/bb/bb.go | 6 +- pkg/boot/boottest/json.go | 2 +- pkg/boot/bzimage/bzimage.go | 10 +- pkg/boot/bzimage/bzimage_test.go | 6 +- pkg/boot/bzimage/header.go | 16 +- pkg/boot/bzimage/kver.go | 38 ++-- pkg/boot/bzimage/kver_test.go | 24 +-- pkg/boot/fit/fit.go | 2 +- pkg/boot/fit/fit_test.go | 2 - pkg/boot/fit/vfit.go | 30 ++- pkg/boot/grub/echo_test.go | 4 +- pkg/boot/grub/grub.go | 1 - pkg/boot/grub/grub_test.go | 1 - pkg/boot/ibft/ibft.go | 6 +- pkg/boot/ibft/ibft_test.go | 4 +- pkg/boot/kexec/memory_linux_test.go | 8 +- pkg/boot/menu/menu_test.go | 22 +-- pkg/boot/multiboot/multiboot.go | 16 +- pkg/boot/multiboot/multiboot_test.go | 1 - pkg/boot/netboot/ipxe/ipxe.go | 8 +- pkg/boot/syslinux/syslinux.go | 1 - pkg/boot/systembooter/booter.go | 3 +- pkg/boot/uefi/fv.go | 12 +- pkg/boot/uefi/fv_test.go | 3 +- pkg/boot/uefi/uefi.go | 10 +- pkg/cmdline/cmdline.go | 3 - pkg/cmdline/cmdline_test.go | 2 - pkg/complete/complete_test.go | 16 +- pkg/complete/prefix.go | 3 +- pkg/complete/prefix_test.go | 4 +- pkg/cp/cp_test.go | 4 +- pkg/cpio/const.go | 24 +-- pkg/cpio/cpio.go | 2 +- pkg/cpio/fs_plan9.go | 2 +- pkg/cpio/fs_unix.go | 2 +- pkg/cpio/newc.go | 6 +- pkg/cpio/newc_test.go | 29 +-- pkg/cpio/sysinfo_plan9.go | 2 +- pkg/cpio/utils.go | 2 +- pkg/crypto/ed25519.go | 8 +- pkg/crypto/ed25519_test.go | 6 +- pkg/curl/schemes.go | 11 +- pkg/curl/schemes_test.go | 1 - pkg/dhclient/dhclient.go | 2 +- pkg/fb/fb.go | 5 +- pkg/find/find_test.go | 10 +- pkg/flash/spimock/spimock.go | 2 +- pkg/forth/forth.go | 2 +- pkg/forth/forth_test.go | 2 - pkg/gpio/gpio_linux_test.go | 1 - pkg/gzip/options_test.go | 1 + pkg/ipmi/ipmi.go | 5 +- pkg/ipmi/ocp/ocp.go | 2 +- pkg/kexecbin/kexecbin.go | 8 +- pkg/ldd/ldd_darwin_test.go | 2 +- pkg/ldd/ldd_test.go | 2 +- pkg/libinit/proc_plan9.go | 4 +- pkg/libinit/root_linux.go | 70 ++++--- pkg/lockfile/lockfile.go | 4 +- pkg/ls/fileinfo_plan9.go | 1 - pkg/mei/mei_linux.go | 2 +- pkg/mei/mkhiclient_linux.go | 1 - pkg/memio/mmap_linux.go | 4 +- pkg/mount/gpt/gpt.go | 68 +++---- pkg/mount/gpt/gpt_test.go | 10 +- pkg/mount/loop/losetup_linux.go | 8 +- pkg/mount/loop/losetup_linux_test.go | 4 +- pkg/mount/magic.go | 10 +- pkg/mount/mount_linux.go | 6 +- pkg/mount/mtd/chips_test.go | 4 +- pkg/mount/mtd/dat.go | 2 +- pkg/mount/scuzz/ata.go | 4 +- pkg/mount/scuzz/sg_linux.go | 2 +- pkg/mount/scuzz/sg_linux_test.go | 132 ++++++------- pkg/mount/switch_root_linux.go | 4 +- pkg/msr/msr_linux.go | 6 +- pkg/msr/msr_linux_test.go | 4 +- pkg/namespace/builder_test.go | 10 +- pkg/namespace/namespace_test.go | 6 +- pkg/namespace/parser.go | 1 - pkg/namespace/parser_test.go | 2 +- pkg/ntpdate/ntpdate.go | 3 +- pkg/pci/bits_test.go | 9 +- pkg/pci/devices.go | 4 +- pkg/pci/ids.go | 3 +- pkg/pci/lookup.go | 1 - pkg/pci/lookup_test.go | 4 +- pkg/pci/pci.go | 7 +- pkg/pci/pci_linux.go | 5 +- pkg/pci/pci_linux_test.go | 6 +- pkg/pogosh/arithmetic_test.go | 47 +++-- pkg/pogosh/exec.go | 11 +- pkg/pogosh/lexer_test.go | 184 +++++++++++++----- pkg/pogosh/parser.go | 27 --- pkg/qemu/devices.go | 2 +- pkg/rng/entropy.go | 4 +- pkg/rtc/rtc_linux.go | 6 +- pkg/securelaunch/eventlog/eventlog.go | 4 +- pkg/securelaunch/helpers.go | 7 +- pkg/securelaunch/launcher/launcher.go | 2 - pkg/securelaunch/measurement/cpuid.go | 5 +- pkg/securelaunch/measurement/dmi.go | 2 +- pkg/securelaunch/measurement/files.go | 2 +- pkg/securelaunch/measurement/storage.go | 4 +- pkg/securelaunch/policy/policy.go | 5 +- pkg/securelaunch/tpm/tpm.go | 9 +- pkg/shlex/shlex_test.go | 1 - pkg/smbios/struct_parser.go | 4 +- pkg/strace/internal/abi/flag_test.go | 13 +- pkg/strace/socket.go | 4 +- pkg/strace/syscall_linux.go | 1 - pkg/strace/syscall_linux_amd64.go | 3 +- pkg/tarutil/tar.go | 4 +- pkg/tarutil/tar_test.go | 4 +- pkg/termios/sgtty.go | 2 +- pkg/termios/termios_darwin.go | 4 +- pkg/termios/termios_linux.go | 2 +- pkg/termios/termios_plan9.go | 5 +- pkg/termios/termios_test.go | 3 - pkg/termios/var_darwin.go | 44 ++--- pkg/termios/var_linux.go | 70 ++++--- pkg/termios/var_unix.go | 6 +- pkg/testutil/stdin.go | 2 +- pkg/tss/capabilities.go | 1 - pkg/tss/nvram.go | 2 +- pkg/tss/structures.go | 1 - pkg/txtlog/txtlog.go | 12 +- pkg/uefivars/boot/boot.go | 8 +- pkg/uefivars/boot/boot_test.go | 12 +- pkg/uefivars/boot/efiDevicePathProtocol.go | 16 +- .../boot/efiDevicePathProtocol_test.go | 4 +- pkg/uefivars/boot/efiDppACPI.go | 4 +- pkg/uefivars/boot/efiDppACPI_test.go | 6 +- pkg/uefivars/boot/efiDppHardware_test.go | 2 +- pkg/uefivars/boot/efiDppMedia.go | 50 ++--- pkg/uefivars/boot/efiDppMedia_test.go | 10 +- pkg/uefivars/boot/efiDppMessage.go | 70 +++---- pkg/uefivars/boot/efiDppMessage_test.go | 4 +- pkg/uefivars/boot/efiDppResolver.go | 12 +- pkg/uefivars/boot/fuzz.go | 6 +- pkg/uefivars/boot/fuzz_test.go | 8 +- pkg/uefivars/vars.go | 2 +- pkg/uefivars/vars_test.go | 6 +- pkg/uio/reader.go | 2 +- pkg/uio/reader_test.go | 4 +- pkg/ulog/log_linux_test.go | 1 - pkg/upath/symlink_test.go | 7 +- pkg/upath/urootpath_test.go | 2 +- pkg/uroot/builder/bb.go | 2 +- pkg/uroot/builder/bb_test.go | 3 +- pkg/uroot/initramfs/cpio.go | 2 +- pkg/uroot/initramfs/dir.go | 2 +- pkg/uroot/initramfs/files.go | 2 +- pkg/uroot/initramfs/files_test.go | 72 +++---- pkg/uroot/uroot.go | 46 ++--- pkg/uroot/uroot_test.go | 2 +- pkg/uzip/uzip.go | 2 +- pkg/uzip/uzip_test.go | 3 +- pkg/vfile/vfile_test.go | 12 +- pkg/vmtest/gotest.go | 2 +- pkg/vmtest/integration.go | 4 +- pkg/vpd/vpd.go | 2 +- pkg/watchdogd/watchdogd.go | 1 - tools/mkinitramfs/main.go | 4 +- tools/testramfs/testramfs.go | 3 +- tools/vpdbootmanager/add_test.go | 4 +- tools/vpdbootmanager/main_test.go | 4 +- u-root.go | 4 +- uroot_test.go | 6 +- 309 files changed, 1392 insertions(+), 1435 deletions(-) diff --git a/cmds/boot/fbnetboot/main.go b/cmds/boot/fbnetboot/main.go index 3169204cfa..b1488b708d 100644 --- a/cmds/boot/fbnetboot/main.go +++ b/cmds/boot/fbnetboot/main.go @@ -270,7 +270,7 @@ func boot(ifname string, dhcp dhcpFunc) error { if filename == "." || filename == "" { return fmt.Errorf("invalid empty file name extracted from file path %s", u.Path) } - if err = ioutil.WriteFile(filename, body, 0400); err != nil { + if err = ioutil.WriteFile(filename, body, 0o400); err != nil { return fmt.Errorf("DHCP: cannot write to file %s: %v", filename, err) } debug("DHCP: saved boot file to %s", filename) @@ -327,7 +327,6 @@ func loadCaCerts() (*x509.CertPool, error) { debug("CA certs appended from PEM") } return rootCAs, nil - } func getClientForBootfile(bootfile string) (*http.Client, error) { diff --git a/cmds/contrib/flash/flash.go b/cmds/contrib/flash/flash.go index 6957a290e2..ef8e76f867 100644 --- a/cmds/contrib/flash/flash.go +++ b/cmds/contrib/flash/flash.go @@ -54,8 +54,10 @@ type programmer interface { Close() error } -type programmerParams map[string]string -type programmerInit func(programmerParams) (programmer, error) +type ( + programmerParams map[string]string + programmerInit func(programmerParams) (programmer, error) +) // supportedProgrammers is populated by the other files in this package. var supportedProgrammers = map[string]programmerInit{} diff --git a/cmds/core/backoff/main_test.go b/cmds/core/backoff/main_test.go index 446efe0cfc..8426a52eb8 100644 --- a/cmds/core/backoff/main_test.go +++ b/cmds/core/backoff/main_test.go @@ -39,7 +39,6 @@ func TestRun(t *testing.T) { gotErrorString, wantErrorString) } - }) } } diff --git a/cmds/core/basename/basename_test.go b/cmds/core/basename/basename_test.go index 1a53efca87..14b0901e53 100644 --- a/cmds/core/basename/basename_test.go +++ b/cmds/core/basename/basename_test.go @@ -20,8 +20,7 @@ type test struct { } func TestBasename(t *testing.T) { - - var tests = []test{ + tests := []test{ { flags: []string{"foo.h", ".h"}, out: "foo\n", diff --git a/cmds/core/cat/cat.go b/cmds/core/cat/cat.go index c78144f319..7fca3755fb 100644 --- a/cmds/core/cat/cat.go +++ b/cmds/core/cat/cat.go @@ -22,9 +22,7 @@ import ( "os" ) -var ( - _ = flag.Bool("u", false, "ignored") -) +var _ = flag.Bool("u", false, "ignored") func cat(reader io.Reader, writer io.Writer) error { if _, err := io.Copy(writer, reader); err != nil { diff --git a/cmds/core/cat/cat_test.go b/cmds/core/cat/cat_test.go index 7490d420ce..ee5b656866 100644 --- a/cmds/core/cat/cat_test.go +++ b/cmds/core/cat/cat_test.go @@ -26,7 +26,7 @@ func setup(t *testing.T, data []byte) (string, error) { for i, d := range data { n := fmt.Sprintf("%v%d", filepath.Join(dir, "file"), i) - if err := ioutil.WriteFile(n, []byte{d}, 0666); err != nil { + if err := ioutil.WriteFile(n, []byte{d}, 0o666); err != nil { return "", err } } diff --git a/cmds/core/chmod/chmod.go b/cmds/core/chmod/chmod.go index 9245b77c5d..264f354343 100644 --- a/cmds/core/chmod/chmod.go +++ b/cmds/core/chmod/chmod.go @@ -69,7 +69,7 @@ func calculateMode(modeString string) (mode os.FileMode, octval uint64, mask uin var err error octval, err = strconv.ParseUint(modeString, 8, 32) if err == nil { - if octval > 0777 { + if octval > 0o777 { log.Fatalf("Invalid octal value %0o. Value should be less than or equal to 0777.", octval) } // a fully described octal mode was supplied, signal that with a special value for mask @@ -102,10 +102,10 @@ func calculateMode(modeString string) (mode os.FileMode, octval uint64, mask uin } // m[2] is [-+=] - var operator = m[2] + operator := m[2] // Use a mask so that we do not overwrite permissions for a user/group that was not specified - mask = 0777 + mask = 0o777 // For "-", invert octvalDigit before applying the mask if operator == "-" { @@ -115,20 +115,20 @@ func calculateMode(modeString string) (mode os.FileMode, octval uint64, mask uin // m[1] is [ugoa]+ if strings.Contains(m[1], "o") || strings.Contains(m[1], "a") { octval += octvalDigit - mask = mask & 0770 + mask = mask & 0o770 } if strings.Contains(m[1], "g") || strings.Contains(m[1], "a") { octval += octvalDigit << 3 - mask = mask & 0707 + mask = mask & 0o707 } if strings.Contains(m[1], "u") || strings.Contains(m[1], "a") { octval += octvalDigit << 6 - mask = mask & 0077 + mask = mask & 0o077 } // For "+" the mask is superfluous, reset it if operator == "+" { - mask = 0777 + mask = 0o777 } // The mode is fully described, signal that with a special value for mask @@ -161,7 +161,6 @@ func main() { fi, err := os.Stat(reference) if err != nil { log.Fatalf("bad reference file: %v", err) - } mask = special mode = fi.Mode() diff --git a/cmds/core/chmod/chmod_test.go b/cmds/core/chmod/chmod_test.go index 8ab292ad81..4d0977bf14 100644 --- a/cmds/core/chmod/chmod_test.go +++ b/cmds/core/chmod/chmod_test.go @@ -42,33 +42,34 @@ func TestChmodSimple(t *testing.T) { defer f.Close() for k, v := range map[string]fileModeTrans{ - "0777": {before: 0000, after: 0777}, - "0644": {before: 0777, after: 0644}, - "u-rwx": {before: 0777, after: 0077}, - "g-rx": {before: 0777, after: 0727}, - "a-xr": {before: 0222, after: 0222}, - "a-xw": {before: 0666, after: 0444}, - "u-xw": {before: 0666, after: 0466}, - "a=": {before: 0777, after: 0000}, - "u=": {before: 0777, after: 0077}, - "u-": {before: 0777, after: 0777}, - "o+": {before: 0700, after: 0700}, - "g=rx": {before: 0777, after: 0757}, - "u=rx": {before: 0077, after: 0577}, - "o=rx": {before: 0077, after: 0075}, - "u=xw": {before: 0742, after: 0342}, - "a-rwx": {before: 0777, after: 0000}, - "a-rx": {before: 0777, after: 0222}, - "a-x": {before: 0777, after: 0666}, - "o+rwx": {before: 0000, after: 0007}, - "a+rwx": {before: 0000, after: 0777}, - "a+xrw": {before: 0000, after: 0777}, - "a+xxxxxxxx": {before: 0000, after: 0111}, - "o+xxxxx": {before: 0000, after: 0001}, - "a+rx": {before: 0000, after: 0555}, - "a+r": {before: 0111, after: 0555}, - "a=rwx": {before: 0000, after: 0777}, - "a=rx": {before: 0000, after: 0555}} { + "0777": {before: 0o000, after: 0o777}, + "0644": {before: 0o777, after: 0o644}, + "u-rwx": {before: 0o777, after: 0o077}, + "g-rx": {before: 0o777, after: 0o727}, + "a-xr": {before: 0o222, after: 0o222}, + "a-xw": {before: 0o666, after: 0o444}, + "u-xw": {before: 0o666, after: 0o466}, + "a=": {before: 0o777, after: 0o000}, + "u=": {before: 0o777, after: 0o077}, + "u-": {before: 0o777, after: 0o777}, + "o+": {before: 0o700, after: 0o700}, + "g=rx": {before: 0o777, after: 0o757}, + "u=rx": {before: 0o077, after: 0o577}, + "o=rx": {before: 0o077, after: 0o075}, + "u=xw": {before: 0o742, after: 0o342}, + "a-rwx": {before: 0o777, after: 0o000}, + "a-rx": {before: 0o777, after: 0o222}, + "a-x": {before: 0o777, after: 0o666}, + "o+rwx": {before: 0o000, after: 0o007}, + "a+rwx": {before: 0o000, after: 0o777}, + "a+xrw": {before: 0o000, after: 0o777}, + "a+xxxxxxxx": {before: 0o000, after: 0o111}, + "o+xxxxx": {before: 0o000, after: 0o001}, + "a+rx": {before: 0o000, after: 0o555}, + "a+r": {before: 0o111, after: 0o555}, + "a=rwx": {before: 0o000, after: 0o777}, + "a=rx": {before: 0o000, after: 0o555}, + } { // Set up the 'before' state err := os.Chmod(f.Name(), v.before) if err != nil { @@ -106,7 +107,8 @@ func TestChmodRecursive(t *testing.T) { defer os.RemoveAll(tempDir) var targetDirectories []string - for _, dir := range []string{"L1_A", "L1_B", "L1_C", + for _, dir := range []string{ + "L1_A", "L1_B", "L1_C", filepath.Join("L1_A", "L2_A"), filepath.Join("L1_A", "L2_B"), filepath.Join("L1_A", "L2_C"), @@ -118,7 +120,7 @@ func TestChmodRecursive(t *testing.T) { filepath.Join("L1_C", "L2_C"), } { dir = filepath.Join(tempDir, dir) - err := os.Mkdir(dir, os.FileMode(0700)) + err := os.Mkdir(dir, os.FileMode(0o700)) if err != nil { t.Fatalf("cannot create test directory: %v", err) } @@ -126,14 +128,15 @@ func TestChmodRecursive(t *testing.T) { } for k, v := range map[string]fileModeTrans{ - "0707": {before: 0755, after: 0707}, - "0770": {before: 0755, after: 0770}, - "o-rwx": {before: 0777, after: 0770}, - "g-rx": {before: 0777, after: 0727}, - "a=rrrrrwx": {before: 0777, after: 0777}, - "a+w": {before: 0700, after: 0722}, - "g+xr": {before: 0700, after: 0750}, - "a=rx": {before: 0777, after: 0555}} { + "0707": {before: 0o755, after: 0o707}, + "0770": {before: 0o755, after: 0o770}, + "o-rwx": {before: 0o777, after: 0o770}, + "g-rx": {before: 0o777, after: 0o727}, + "a=rrrrrwx": {before: 0o777, after: 0o777}, + "a+w": {before: 0o700, after: 0o722}, + "g+xr": {before: 0o700, after: 0o750}, + "a=rx": {before: 0o777, after: 0o555}, + } { // Set up the 'before' state for _, dir := range targetDirectories { @@ -177,7 +180,7 @@ func TestChmodReference(t *testing.T) { } defer targetFile.Close() - for _, perm := range []os.FileMode{0777, 0644} { + for _, perm := range []os.FileMode{0o777, 0o644} { err = os.Chmod(sourceFile.Name(), perm) if err != nil { t.Fatalf("chmod(%q) failed: %v", sourceFile.Name(), err) @@ -224,7 +227,6 @@ func TestInvocationErrors(t *testing.T) { skipTo int skipFrom int }{ - { args: []string{f.Name()}, want: "Usage", diff --git a/cmds/core/chroot/chroot_test.go b/cmds/core/chroot/chroot_test.go index c743b5a984..03f68041ed 100644 --- a/cmds/core/chroot/chroot_test.go +++ b/cmds/core/chroot/chroot_test.go @@ -65,7 +65,6 @@ func TestUserSpecString(t *testing.T) { if str != input { t.Errorf("Unexpected error with input: %s, String method returned: %s", input, str) } - } func testGroupSet(input string, expected []uint32) error { @@ -127,5 +126,4 @@ func TestGroupsSet(t *testing.T) { if err = testGroupSet(input, expected); err == nil { t.Errorf("Expected error on input: %s, got: %v", input, groups.groups) } - } diff --git a/cmds/core/cmp/cmp_test.go b/cmds/core/cmp/cmp_test.go index bbfa4eb0ed..e5dd47b235 100644 --- a/cmds/core/cmp/cmp_test.go +++ b/cmds/core/cmp/cmp_test.go @@ -12,9 +12,8 @@ import ( ) func TestEmit(t *testing.T) { - - var buf = []byte("hello\nthis is a test\n") - var buf2 = []byte("hello\nthiz is a text") + buf := []byte("hello\nthis is a test\n") + buf2 := []byte("hello\nthiz is a text") c1 := make(chan byte, 8192) c2 := make(chan byte, 8192) @@ -36,5 +35,4 @@ func TestEmit(t *testing.T) { if err != io.EOF { t.Errorf("%v", err) } - } diff --git a/cmds/core/comm/comm_test.go b/cmds/core/comm/comm_test.go index 58a0765101..9bda650fc8 100644 --- a/cmds/core/comm/comm_test.go +++ b/cmds/core/comm/comm_test.go @@ -66,7 +66,7 @@ func TestComm(t *testing.T) { var files [2]string for i, contents := range []string{test.in1, test.in2} { files[i] = filepath.Join(tmpDir, fmt.Sprintf("txt%d", i)) - if err := ioutil.WriteFile(files[i], []byte(contents), 0600); err != nil { + if err := ioutil.WriteFile(files[i], []byte(contents), 0o600); err != nil { t.Fatalf("Failed to create test file %d: %v", i, err) } } diff --git a/cmds/core/cp/cp_test.go b/cmds/core/cp/cp_test.go index 2d8bd2175a..57740d9011 100644 --- a/cmds/core/cp/cp_test.go +++ b/cmds/core/cp/cp_test.go @@ -151,11 +151,11 @@ func TestCpRecursive(t *testing.T) { defer os.RemoveAll(tempDir) srcDir := filepath.Join(tempDir, "src") - if err := os.Mkdir(srcDir, 0755); err != nil { + if err := os.Mkdir(srcDir, 0o755); err != nil { t.Fatal(err) } dstDir := filepath.Join(tempDir, "dst-exists") - if err := os.Mkdir(dstDir, 0755); err != nil { + if err := os.Mkdir(dstDir, 0o755); err != nil { t.Fatal(err) } @@ -205,7 +205,7 @@ func TestCpRecursiveMultiple(t *testing.T) { defer os.RemoveAll(tempDir) dstTest := filepath.Join(tempDir, "destination") - if err := os.Mkdir(dstTest, 0755); err != nil { + if err := os.Mkdir(dstTest, 0o755); err != nil { t.Fatalf("Failed on build directory %v: %v", dstTest, err) } diff --git a/cmds/core/cpio/cpio_test.go b/cmds/core/cpio/cpio_test.go index 9f1be3ba29..75f85f6cb8 100644 --- a/cmds/core/cpio/cpio_test.go +++ b/cmds/core/cpio/cpio_test.go @@ -32,7 +32,7 @@ func TestCpio(t *testing.T) { } defer os.RemoveAll(tempDir) - var targets = []dirEnt{ + targets := []dirEnt{ {Name: "file1", Type: "file", Content: "Hello World"}, {Name: "file2", Type: "file", Content: ""}, {Name: "directory1", Type: "dir"}, @@ -44,10 +44,10 @@ func TestCpio(t *testing.T) { }...) } for _, ent := range targets { - var name = filepath.Join(tempDir, ent.Name) + name := filepath.Join(tempDir, ent.Name) switch ent.Type { case "dir": - err := os.Mkdir(name, os.FileMode(0700)) + err := os.Mkdir(name, os.FileMode(0o700)) if err != nil { t.Fatalf("cannot create test directory: %v", err) } @@ -76,7 +76,7 @@ func TestCpio(t *testing.T) { // the FileInfo for each target. This needs to happen in a second // pass because of the link count. for key, ent := range targets { - var name = filepath.Join(tempDir, ent.Name) + name := filepath.Join(tempDir, ent.Name) targets[key].FileInfo, err = os.Stat(name) if err != nil { t.Fatalf("cannot stat temporary dirent: %v", err) @@ -126,7 +126,7 @@ func TestCpio(t *testing.T) { } for _, ent := range targets { - var name = filepath.Join(tempExtractDir, ent.Name) + name := filepath.Join(tempExtractDir, ent.Name) newFileInfo, err := os.Stat(name) if err != nil { t.Error(err) diff --git a/cmds/core/cpio/testdata/dir-hard-link.go b/cmds/core/cpio/testdata/dir-hard-link.go index b4c356e246..556bc3aaff 100644 --- a/cmds/core/cpio/testdata/dir-hard-link.go +++ b/cmds/core/cpio/testdata/dir-hard-link.go @@ -22,8 +22,8 @@ func main() { } rw := archiver.Writer(os.Stdout) for _, rec := range []cpio.Record{ - cpio.Directory("directory1", 0755), - cpio.Directory("directory2", 0755), + cpio.Directory("directory1", 0o755), + cpio.Directory("directory2", 0o755), } { rec.UID = uint64(os.Getuid()) rec.GID = uint64(os.Getgid()) diff --git a/cmds/core/date/date_test.go b/cmds/core/date/date_test.go index 7afa95bc1d..1e398ce9fe 100644 --- a/cmds/core/date/date_test.go +++ b/cmds/core/date/date_test.go @@ -25,7 +25,6 @@ func TestDateNoFlags(t *testing.T) { if d != dTest { t.Errorf("Mismatched dates; want %v, got %v\n", d, dTest) } - } // using u flag @@ -74,7 +73,7 @@ func TestDateMapExamples(t *testing.T) { example string // correct example } - var tests = []dateTest{ + tests := []dateTest{ { "%a %b %e %H:%M:%S %Z %Y", "Tue Jun 26 09:58:10 PDT 1990", diff --git a/cmds/core/dd/dd.go b/cmds/core/dd/dd.go index 9c93a6f2ee..11dc21e494 100644 --- a/cmds/core/dd/dd.go +++ b/cmds/core/dd/dd.go @@ -354,7 +354,7 @@ func outFile(name string, outputBytes int64, seek int64, flags int) (io.Writer, out = os.Stdout } else { perm := os.O_CREATE | os.O_WRONLY | (flags & allowedFlags) - if out, err = os.OpenFile(name, perm, 0666); err != nil { + if out, err = os.OpenFile(name, perm, 0o666); err != nil { return nil, fmt.Errorf("error opening output file %q: %v", name, err) } } diff --git a/cmds/core/dd/dd_test.go b/cmds/core/dd/dd_test.go index c65a37ff8f..fa0a1b8599 100644 --- a/cmds/core/dd/dd_test.go +++ b/cmds/core/dd/dd_test.go @@ -57,7 +57,6 @@ func TestNewChunkedBuffer(t *testing.T) { len(newIntermediateBuffer.data), newIntermediateBuffer.outChunk, newIntermediateBuffer.flags, tt.BufferSize, tt.outChunkSize, tt.flags) } - }) } } @@ -255,7 +254,6 @@ func TestRead(t *testing.T) { if !reflect.DeepEqual(buffer, tt.expected) { t.Errorf("Got: %v - Want: %v", buffer, tt.expected) } - }) } } @@ -333,7 +331,7 @@ func setupDatafile(t *testing.T, name string) (string, func()) { } dataFilePath := filepath.Join(testDir, name) - err = ioutil.WriteFile(dataFilePath, []byte("ABCDEFG"), 0644) + err = ioutil.WriteFile(dataFilePath, []byte("ABCDEFG"), 0o644) if err != nil { t.Errorf("unable to mockup file: %v", err) } @@ -441,7 +439,7 @@ func TestConvertArgs(t *testing.T) { // TestDd implements a table-driven test. func TestDd(t *testing.T) { - var tests = []struct { + tests := []struct { name string flags []string stdin string @@ -449,7 +447,6 @@ func TestDd(t *testing.T) { count int64 compare func(io.Reader, []byte, int64) error }{ - { name: "Simple copying from input to output", flags: []string{}, @@ -597,7 +594,7 @@ func byteCount(i io.Reader, o []byte, n int64) error { // TestFiles uses `if` and `of` arguments. func TestFiles(t *testing.T) { - var tests = []struct { + tests := []struct { name string flags []string inFile []byte @@ -668,10 +665,10 @@ func TestFiles(t *testing.T) { defer os.RemoveAll(tmpDir) inFile := filepath.Join(tmpDir, "inFile") outFile := filepath.Join(tmpDir, "outFile") - if err := ioutil.WriteFile(inFile, tt.inFile, 0666); err != nil { + if err := ioutil.WriteFile(inFile, tt.inFile, 0o666); err != nil { t.Error(err) } - if err := ioutil.WriteFile(outFile, tt.outFile, 0666); err != nil { + if err := ioutil.WriteFile(outFile, tt.outFile, 0o666); err != nil { t.Error(err) } diff --git a/cmds/core/df/df.go b/cmds/core/df/df.go index 28bea4cfc7..8ce2056103 100644 --- a/cmds/core/df/df.go +++ b/cmds/core/df/df.go @@ -134,7 +134,7 @@ func SetUnits() { func df() { SetUnits() mounts, _ := mountinfo() - var blocksize = "1K" + blocksize := "1K" if *inMB { blocksize = "1M" } diff --git a/cmds/core/find/find.go b/cmds/core/find/find.go index b97907e567..205c5cf4e4 100644 --- a/cmds/core/find/find.go +++ b/cmds/core/find/find.go @@ -44,7 +44,7 @@ func init() { } func main() { - var fileTypes = map[string]os.FileMode{ + fileTypes := map[string]os.FileMode{ "f": 0, "file": 0, "d": os.ModeDir, diff --git a/cmds/core/fusermount/fusermount.go b/cmds/core/fusermount/fusermount.go index c5e6f98d83..709c3e952c 100644 --- a/cmds/core/fusermount/fusermount.go +++ b/cmds/core/fusermount/fusermount.go @@ -50,9 +50,7 @@ var ( mpt string ) -var ( - help = "usage: fusermount [-u|--unmount] [-z|--lazy] [-v|--verbose] " -) +const help = "usage: fusermount [-u|--unmount] [-z|--lazy] [-v|--verbose] " func usage() { log.Fatalf(help) @@ -127,9 +125,9 @@ func getCommFD() (int, error) { } func doMount(fd int) error { - var flags = uintptr(unix.MS_NODEV | unix.MS_NOSUID) + flags := uintptr(unix.MS_NODEV | unix.MS_NOSUID) // From the kernel: - //if (!d->fd_present || !d->rootmode_present || + // if (!d->fd_present || !d->rootmode_present || // !d->user_id_present || !d->group_id_present) // return 0; // Yeah. You get EINVAL if any one of these is not set. diff --git a/cmds/core/fusermount/fusermount_linux.go b/cmds/core/fusermount/fusermount_linux.go index bfc0912e5b..0d90523631 100644 --- a/cmds/core/fusermount/fusermount_linux.go +++ b/cmds/core/fusermount/fusermount_linux.go @@ -6,9 +6,7 @@ package main import "golang.org/x/sys/unix" -var ( - fileSystemUID, fileSystemGID int -) +var fileSystemUID, fileSystemGID int func dropPrivs() error { uid := unix.Getuid() @@ -36,6 +34,6 @@ func restorePrivs() { func preMount() error { // I guess this umask is the thing to do. - unix.Umask(033) + unix.Umask(0o33) return nil } diff --git a/cmds/core/fusermount/fusermount_test.go b/cmds/core/fusermount/fusermount_test.go index 1f959e580a..e693431529 100644 --- a/cmds/core/fusermount/fusermount_test.go +++ b/cmds/core/fusermount/fusermount_test.go @@ -31,7 +31,7 @@ func testArgs(t *testing.T) { } defer os.RemoveAll(tmpDir) tdir := filepath.Join(tmpDir, "a/b/c") - if err := os.MkdirAll(tdir, 0777); err != nil { + if err := os.MkdirAll(tdir, 0o777); err != nil { t.Fatal(err) } ldir := filepath.Join(tmpDir, "d") @@ -39,7 +39,7 @@ func testArgs(t *testing.T) { t.Fatal(err) } - var tab = []struct { + tab := []struct { n string o string e int @@ -161,6 +161,7 @@ func TestMount(t *testing.T) { t.Fatal(err) } } + func TestMain(m *testing.M) { testutil.Run(m, main) } diff --git a/cmds/core/gpt/gpt.go b/cmds/core/gpt/gpt.go index ed516fcb8e..0153982e10 100644 --- a/cmds/core/gpt/gpt.go +++ b/cmds/core/gpt/gpt.go @@ -26,9 +26,7 @@ import ( const cmd = "gpt [options] file" -var ( - write = flag.Bool("w", false, "Write GPT to file") -) +var write = flag.Bool("w", false, "Write GPT to file") func init() { defUsage := flag.Usage @@ -58,7 +56,7 @@ func main() { switch *write { case true: - var p = &gpt.PartitionTable{} + p := &gpt.PartitionTable{} if err := json.NewDecoder(os.Stdin).Decode(&p); err != nil { log.Fatalf("Reading in JSON: %v", err) } diff --git a/cmds/core/grep/grep_test.go b/cmds/core/grep/grep_test.go index 8f6e0a8343..90e51d4b8c 100644 --- a/cmds/core/grep/grep_test.go +++ b/cmds/core/grep/grep_test.go @@ -16,7 +16,7 @@ import ( // GrepTest is a table-driven which spawns grep with a variety of options and inputs. // We need to look at any output data, as well as exit status for things like the -q switch. func TestGrep(t *testing.T) { - var tab = []struct { + tab := []struct { i string o string s int diff --git a/cmds/core/hostname/hostname_plan9.go b/cmds/core/hostname/hostname_plan9.go index 2efd8f8325..6a79c52a0b 100644 --- a/cmds/core/hostname/hostname_plan9.go +++ b/cmds/core/hostname/hostname_plan9.go @@ -10,5 +10,5 @@ package main import "io/ioutil" func Sethostname(n string) error { - return ioutil.WriteFile("#c/sysname", []byte(n), 0644) + return ioutil.WriteFile("#c/sysname", []byte(n), 0o644) } diff --git a/cmds/core/id/id.go b/cmds/core/id/id.go index ad5462789d..159afe57e3 100644 --- a/cmds/core/id/id.go +++ b/cmds/core/id/id.go @@ -168,10 +168,8 @@ func IDCommand(u User) { var groupOutput []string for gid, name := range u.Groups() { - if !flags.groups { groupOutput = append(groupOutput, fmt.Sprintf("%d(%s)", gid, name)) - } else { if flags.name { groupOutput = append(groupOutput, fmt.Sprintf("%s ", name)) @@ -193,7 +191,6 @@ func main() { flag.Parse() if !correctFlags(flags.groups, flags.group, flags.user) { log.Fatalf("id: cannot print \"only\" of more than one choice") - } if flags.name && !(flags.groups || flags.group || flags.user) { log.Fatalf("id: cannot print only names in default format") diff --git a/cmds/core/id/id_test.go b/cmds/core/id/id_test.go index d706bf4652..5dcf66d3fd 100644 --- a/cmds/core/id/id_test.go +++ b/cmds/core/id/id_test.go @@ -17,9 +17,7 @@ import ( "github.com/u-root/u-root/pkg/testutil" ) -var ( - logPrefixLength = len("2009/11/10 23:00:00 ") -) +var logPrefixLength = len("2009/11/10 23:00:00 ") type test struct { opt []string @@ -37,7 +35,7 @@ func run(c *exec.Cmd) (string, string, error) { // Test incorrect invocation of id func TestInvocation(t *testing.T) { - var tests = []test{ + tests := []test{ {opt: []string{"-n"}, out: "id: cannot print only names in default format\n"}, {opt: []string{"-G", "-g"}, out: "id: cannot print \"only\" of more than one choice\n"}, {opt: []string{"-G", "-u"}, out: "id: cannot print \"only\" of more than one choice\n"}, diff --git a/cmds/core/init/init_linux.go b/cmds/core/init/init_linux.go index b197bc8567..942d321a54 100644 --- a/cmds/core/init/init_linux.go +++ b/cmds/core/init/init_linux.go @@ -85,5 +85,4 @@ func osInitGo() *initCmds { libinit.Command("/bin/sh", ctty), }, } - } diff --git a/cmds/core/init/init_plan9.go b/cmds/core/init/init_plan9.go index 1f6607b2ec..6b88f159a5 100644 --- a/cmds/core/init/init_plan9.go +++ b/cmds/core/init/init_plan9.go @@ -33,5 +33,4 @@ func osInitGo() *initCmds { libinit.Command("/bin/sh"), }, } - } diff --git a/cmds/core/io/io.go b/cmds/core/io/io.go index b9356751cc..a7380cd9d6 100644 --- a/cmds/core/io/io.go +++ b/cmds/core/io/io.go @@ -36,11 +36,13 @@ import ( "github.com/u-root/u-root/pkg/memio" ) -type cmdFunc func(addr int64, data memio.UintN) error -type cmd struct { - f cmdFunc - addrBits, valBits int -} +type ( + cmdFunc func(addr int64, data memio.UintN) error + cmd struct { + f cmdFunc + addrBits, valBits int + } +) var ( readCmds = map[string]*cmd{} diff --git a/cmds/core/io/smn.go b/cmds/core/io/smn.go index 45e3102fbd..c3bfcdd739 100644 --- a/cmds/core/io/smn.go +++ b/cmds/core/io/smn.go @@ -31,7 +31,7 @@ io ws index value # write value to system management network on newer AMD CPUs. } func do(addr int64, data memio.UintN, op func(int64, memio.UintN) error) error { - var a = newInt(uint64(addr), 32) + a := newInt(uint64(addr), 32) if err := memio.Write(pcibase+0xb8, a); err != nil { return err } diff --git a/cmds/core/ip/ip_linux.go b/cmds/core/ip/ip_linux.go index afd461e56c..c0dd29936e 100644 --- a/cmds/core/ip/ip_linux.go +++ b/cmds/core/ip/ip_linux.go @@ -391,5 +391,4 @@ func main() { if err != nil { log.Fatal(err) } - } diff --git a/cmds/core/kexec/kexec_linux.go b/cmds/core/kexec/kexec_linux.go index 23b1b651f8..ed3bab30ae 100644 --- a/cmds/core/kexec/kexec_linux.go +++ b/cmds/core/kexec/kexec_linux.go @@ -134,7 +134,6 @@ func main() { for _, n := range strings.Fields(opts.initramfs) { files = append(files, uio.NewLazyFile(n)) } - } var i io.ReaderAt if len(files) > 0 { diff --git a/cmds/core/kill/kill_test.go b/cmds/core/kill/kill_test.go index 185cef3889..b55b72758f 100644 --- a/cmds/core/kill/kill_test.go +++ b/cmds/core/kill/kill_test.go @@ -59,20 +59,18 @@ func TestKillProcess(t *testing.T) { } func TestBadInvocations(t *testing.T) { - var ( - tab = []struct { - a []string - err string - }{ - {a: []string{"-1w34"}, err: "1w34 is not a valid signal\n"}, - {a: []string{"-s"}, err: eUsage + "\n"}, - {a: []string{"-s", "a"}, err: "a is not a valid signal\n"}, - {a: []string{"a"}, err: "Some processes could not be killed: [a: arguments must be process or job IDS]\n"}, - {a: []string{"--signal"}, err: eUsage + "\n"}, - {a: []string{"--signal", "a"}, err: "a is not a valid signal\n"}, - {a: []string{"-1", "a"}, err: "Some processes could not be killed: [a: arguments must be process or job IDS]\n"}, - } - ) + tab := []struct { + a []string + err string + }{ + {a: []string{"-1w34"}, err: "1w34 is not a valid signal\n"}, + {a: []string{"-s"}, err: eUsage + "\n"}, + {a: []string{"-s", "a"}, err: "a is not a valid signal\n"}, + {a: []string{"a"}, err: "Some processes could not be killed: [a: arguments must be process or job IDS]\n"}, + {a: []string{"--signal"}, err: eUsage + "\n"}, + {a: []string{"--signal", "a"}, err: "a is not a valid signal\n"}, + {a: []string{"-1", "a"}, err: "Some processes could not be killed: [a: arguments must be process or job IDS]\n"}, + } tmpDir, err := ioutil.TempDir("", "KillTest") if err != nil { diff --git a/cmds/core/ln/ln_test.go b/cmds/core/ln/ln_test.go index 40f2ff03d9..d9285d0fdd 100644 --- a/cmds/core/ln/ln_test.go +++ b/cmds/core/ln/ln_test.go @@ -242,11 +242,11 @@ func TestLn(t *testing.T) { t.Logf("Creating: %v (dir: %v)", f.name, f.dir) p := filepath.Join(f.name) if f.dir { - if err := os.Mkdir(p, 0750); err != nil && err == os.ErrExist { + if err := os.Mkdir(p, 0o750); err != nil && err == os.ErrExist { t.Skipf("Creation of dir %q fails: %v", p, err) } } else { - if err := ioutil.WriteFile(p, []byte{'.'}, 0640); err != nil { + if err := ioutil.WriteFile(p, []byte{'.'}, 0o640); err != nil { t.Fatal(err) } } @@ -267,7 +267,6 @@ func TestLn(t *testing.T) { t.Logf("%q -> %q (hardlink)", expected.name, expected.linksTo) testHardLink(expected.name, expected.linksTo, t) } - } // backing to testDir folder diff --git a/cmds/core/losetup/losetup_linux.go b/cmds/core/losetup/losetup_linux.go index 683cc7a669..b16db8ea4a 100644 --- a/cmds/core/losetup/losetup_linux.go +++ b/cmds/core/losetup/losetup_linux.go @@ -21,9 +21,7 @@ import ( "github.com/u-root/u-root/pkg/mount/loop" ) -var ( - detach = flag.Bool("d", false, "Detach the device") -) +var detach = flag.Bool("d", false, "Detach the device") func main() { var ( @@ -65,5 +63,4 @@ func main() { } log.Printf("Attached %s to %s", devicename, filename) - } diff --git a/cmds/core/ls/ls.go b/cmds/core/ls/ls.go index 6ee44328eb..7b52c58fbc 100644 --- a/cmds/core/ls/ls.go +++ b/cmds/core/ls/ls.go @@ -90,7 +90,7 @@ func listName(stringer ls.Stringer, d string, w io.Writer, prefix bool) error { } func indicator(fi ls.FileInfo) string { - if fi.Mode.IsRegular() && fi.Mode&0111 != 0 { + if fi.Mode.IsRegular() && fi.Mode&0o111 != 0 { return "*" } if fi.Mode&os.ModeDir != 0 { diff --git a/cmds/core/ls/ls_linux_test.go b/cmds/core/ls/ls_linux_test.go index f136e75cf7..faa144f60e 100644 --- a/cmds/core/ls/ls_linux_test.go +++ b/cmds/core/ls/ls_linux_test.go @@ -36,7 +36,7 @@ func TestLargeDevNumber(t *testing.T) { } defer os.RemoveAll(tmpDir) file := filepath.Join(tmpDir, "large_node") - if err := unix.Mknod(file, 0660|unix.S_IFBLK, 0x12345678); err != nil { + if err := unix.Mknod(file, 0o660|unix.S_IFBLK, 0x12345678); err != nil { t.Fatal(err) } defer os.Remove(file) diff --git a/cmds/core/ls/ls_plan9.go b/cmds/core/ls/ls_plan9.go index 1f5d0b7631..6fe585dfc5 100644 --- a/cmds/core/ls/ls_plan9.go +++ b/cmds/core/ls/ls_plan9.go @@ -11,6 +11,4 @@ import ( flag "github.com/spf13/pflag" ) -var ( - final = flag.BoolP("print-last", "p", false, "Print only the final path element of each file name") -) +var final = flag.BoolP("print-last", "p", false, "Print only the final path element of each file name") diff --git a/cmds/core/ls/ls_test.go b/cmds/core/ls/ls_test.go index 2d16af297d..b8bdc51f22 100644 --- a/cmds/core/ls/ls_test.go +++ b/cmds/core/ls/ls_test.go @@ -88,14 +88,14 @@ func TestLs(t *testing.T) { // Create an empty directory. testDir := filepath.Join(tmpDir, "testDir") - os.Mkdir(testDir, 0700) + os.Mkdir(testDir, 0o700) // Create some files. os.Create(filepath.Join(testDir, "f1")) os.Create(filepath.Join(testDir, "f2")) os.Create(filepath.Join(testDir, "f3\nline 2")) os.Create(filepath.Join(testDir, ".f4")) - os.Mkdir(filepath.Join(testDir, "d1"), 0740) + os.Mkdir(filepath.Join(testDir, "d1"), 0o740) os.Create(filepath.Join(testDir, "d1/f4")) // Table-driven testing @@ -113,7 +113,7 @@ func TestLs(t *testing.T) { } func TestIndicator(t *testing.T) { - var tests = []struct { + tests := []struct { lsInfo ls.FileInfo symbol string }{ diff --git a/cmds/core/lsdrivers/lsdrivers_linux_test.go b/cmds/core/lsdrivers/lsdrivers_linux_test.go index c77eedd6d4..a97819290b 100644 --- a/cmds/core/lsdrivers/lsdrivers_linux_test.go +++ b/cmds/core/lsdrivers/lsdrivers_linux_test.go @@ -25,7 +25,7 @@ func makeDFL(d []dfl) error { for _, f := range d { switch f.t { case "d": - if err := os.MkdirAll(f.n, 0755); err != nil { + if err := os.MkdirAll(f.n, 0o755); err != nil { return err } case "l": @@ -52,13 +52,12 @@ func allDone(dir string, t *testing.T) { // This tests one of the unused components, the alarm timer func TestUnusedAlarmTimer(t *testing.T) { dir, err := ioutil.TempDir("", "lsdrivers") - if err != nil { t.Fatal(err) } // generated by: tar cf - /sys/bus | tar tvf - | awk '{printf("{t:\"%s\", n: \"%s\", l: \"%s\"},\n", substr($1,1,1), $6, $8)}' // Then filter what you need. - var alarmtimer = []dfl{ + alarmtimer := []dfl{ {t: "d", n: filepath.Join(dir, "sys/bus/platform/drivers/alarmtimer/"), l: ""}, } if err := makeDFL(alarmtimer); err != nil { @@ -90,12 +89,11 @@ func TestUnusedAlarmTimer(t *testing.T) { // This tests one of the unused components, acpi.button func TestUsedPWRButton(t *testing.T) { dir, err := ioutil.TempDir("", "lsdrivers") - if err != nil { t.Fatal(err) } // generated by: tar cf - /sys/bus | tar tvf - | awk '{printf("{t:\"%s\", n: \"%s\", l: \"%s\"},\n", substr($1,1,1), $6, $8)}' - var alarmtimer = []dfl{ + alarmtimer := []dfl{ {t: "d", n: filepath.Join(dir, "sys/bus/acpi/drivers/button/"), l: ""}, {t: "l", n: filepath.Join(dir, "sys/bus/acpi/drivers/button/LNXPWRBN:00"), l: "../../../../devices/LNXSYSTM:00/LNXPWRBN:00"}, } diff --git a/cmds/core/lsdrivers/main_linux.go b/cmds/core/lsdrivers/main_linux.go index 711f27a9fe..e7e9db6b30 100644 --- a/cmds/core/lsdrivers/main_linux.go +++ b/cmds/core/lsdrivers/main_linux.go @@ -65,6 +65,7 @@ func lsdrivers(bus string, unused bool) ([]string, error) { } return d, nil } + func main() { flag.Parse() drivers, err := lsdrivers("/sys/bus", *unused) diff --git a/cmds/core/man/gen/gen.go b/cmds/core/man/gen/gen.go index a5e901f3d5..adae57f0c0 100644 --- a/cmds/core/man/gen/gen.go +++ b/cmds/core/man/gen/gen.go @@ -112,7 +112,7 @@ func walk(mans map[string]string, root string) (err error) { func writeFile(fname string, mans map[string]string) error { dir := filepath.Dir(fname) if _, err := os.Stat(dir); os.IsNotExist(err) { - if err := os.Mkdir(dir, 0775); err != nil { + if err := os.Mkdir(dir, 0o775); err != nil { return err } } diff --git a/cmds/core/md5sum/md5sum_test.go b/cmds/core/md5sum/md5sum_test.go index 2e2a03fade..79ac7bf070 100644 --- a/cmds/core/md5sum/md5sum_test.go +++ b/cmds/core/md5sum/md5sum_test.go @@ -11,7 +11,7 @@ import ( ) func TestCksum(t *testing.T) { - var testMatrix = []struct { + testMatrix := []struct { data []byte cksum string }{ @@ -24,7 +24,6 @@ func TestCksum(t *testing.T) { t.Errorf("md5sum verification failed. (Expected: %s, Received: %s)", testData.cksum, calculateMd5Sum("", testData.data)) } } - } func TestMain(m *testing.M) { diff --git a/cmds/core/mkdir/mkdir.go b/cmds/core/mkdir/mkdir.go index d6fce9288f..d8c9584e23 100644 --- a/cmds/core/mkdir/mkdir.go +++ b/cmds/core/mkdir/mkdir.go @@ -23,10 +23,10 @@ import ( const ( cmd = "mkdir [-m mode] [-v] [-p] [more directories]" - defaultCreationMode = 0777 - stickyBit = 01000 - sgidBit = 02000 - suidBit = 04000 + defaultCreationMode = 0o777 + stickyBit = 0o1000 + sgidBit = 0o2000 + suidBit = 0o4000 ) var ( @@ -62,7 +62,7 @@ func main() { m = defaultCreationMode } else { m, err = strconv.ParseUint(*mode, 8, 32) - if err != nil || m > 07777 { + if err != nil || m > 0o7777 { log.Fatalf("invalid mode '%s'", *mode) } } diff --git a/cmds/core/mkdir/mkdir_test.go b/cmds/core/mkdir/mkdir_test.go index 8676dc6237..a294947837 100644 --- a/cmds/core/mkdir/mkdir_test.go +++ b/cmds/core/mkdir/mkdir_test.go @@ -34,7 +34,7 @@ type MkdirPermTestCase struct { var ( stubDirNames = []string{"stub", "stub2"} - umaskDefault = 022 + umaskDefault = 0o22 errorTestCases = []MkdirErrorTestcase{ { name: "No Arg Error", @@ -74,49 +74,49 @@ var ( { name: "Default Perm", args: []string{stubDirNames[0]}, - perm: os.FileMode(0755 | os.ModeDir), + perm: os.FileMode(0o755 | os.ModeDir), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm in Octal Form", args: []string{"-m=0777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir), + perm: os.FileMode(0o777 | os.ModeDir), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm not in Octal Form", args: []string{"-m=777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir), + perm: os.FileMode(0o777 | os.ModeDir), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm with Sticky Bit", args: []string{"-m=1777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir | os.ModeSticky), + perm: os.FileMode(0o777 | os.ModeDir | os.ModeSticky), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm with SGID Bit", args: []string{"-m=2777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir | os.ModeSetgid), + perm: os.FileMode(0o777 | os.ModeDir | os.ModeSetgid), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm with SUID Bit", args: []string{"-m=4777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir | os.ModeSetuid), + perm: os.FileMode(0o777 | os.ModeDir | os.ModeSetuid), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm with Sticky Bit and SUID Bit", args: []string{"-m=5777", stubDirNames[0]}, - perm: os.FileMode(0777 | os.ModeDir | os.ModeSticky | os.ModeSetuid), + perm: os.FileMode(0o777 | os.ModeDir | os.ModeSticky | os.ModeSetuid), dirNames: []string{stubDirNames[0]}, }, { name: "Custom Perm for 2 Directories", args: []string{"-m=5777", stubDirNames[0], stubDirNames[1]}, - perm: os.FileMode(0777 | os.ModeDir | os.ModeSticky | os.ModeSetuid), + perm: os.FileMode(0o777 | os.ModeDir | os.ModeSticky | os.ModeSetuid), dirNames: stubDirNames, }, } diff --git a/cmds/core/mkfifo/mkfifo.go b/cmds/core/mkfifo/mkfifo.go index 6b02707bc4..b3f33c0904 100644 --- a/cmds/core/mkfifo/mkfifo.go +++ b/cmds/core/mkfifo/mkfifo.go @@ -24,7 +24,7 @@ import ( ) const ( - defaultMode = 0660 | unix.S_IFIFO + defaultMode = 0o660 | unix.S_IFIFO cmd = "mkfifo [-m] NAME..." ) diff --git a/cmds/core/mkfifo/mkfifo_test.go b/cmds/core/mkfifo/mkfifo_test.go index 66ceecb013..25211bc08b 100644 --- a/cmds/core/mkfifo/mkfifo_test.go +++ b/cmds/core/mkfifo/mkfifo_test.go @@ -30,11 +30,11 @@ func TestMkfifo(t *testing.T) { // used later in testing testDir := filepath.Join(tmpDir, "mkfifoDir") - if err := os.Mkdir(testDir, 0700); err != nil { + if err := os.Mkdir(testDir, 0o700); err != nil { t.Error(err) } - var tests = []test{ + tests := []test{ { name: "no path or mode, error", flags: []string{}, @@ -65,7 +65,6 @@ func TestMkfifo(t *testing.T) { for _, path := range tt.flags { testFile, err := os.Stat(path) - if err != nil { t.Errorf("Unable to stat file %s", path) } diff --git a/cmds/core/mknod/mknod_linux.go b/cmds/core/mknod/mknod_linux.go index a9cfe1b145..9a9bd76080 100644 --- a/cmds/core/mknod/mknod_linux.go +++ b/cmds/core/mknod/mknod_linux.go @@ -13,7 +13,7 @@ import ( "golang.org/x/sys/unix" ) -const defaultPerms = 0660 +const defaultPerms = 0o660 func parseDevices(args []string, devtype string) (int, error) { if len(args) != 4 { diff --git a/cmds/core/mknod/mknod_test.go b/cmds/core/mknod/mknod_test.go index 2dc79e358b..ccd0b6adcb 100644 --- a/cmds/core/mknod/mknod_test.go +++ b/cmds/core/mknod/mknod_test.go @@ -58,7 +58,7 @@ func TestInvocationErrors(t *testing.T) { defer os.RemoveAll(tmpDir) devpath := filepath.Join(tmpDir, "testdev") - var tests = []test{ + tests := []test{ {args: []string{devpath}, expects: "mknod: usage: mknod path type [major minor]\n"}, {args: []string{""}, expects: "mknod: usage: mknod path type [major minor]\n"}, {args: []string{devpath, "p", "254", "3"}, expects: "mknod: device type p requires no other arguments\n"}, diff --git a/cmds/core/mktemp/mktemp.go b/cmds/core/mktemp/mktemp.go index 223c2228ee..194d666ec4 100644 --- a/cmds/core/mktemp/mktemp.go +++ b/cmds/core/mktemp/mktemp.go @@ -47,9 +47,7 @@ type mktempflags struct { dir string } -var ( - flags mktempflags -) +var flags mktempflags func init() { flag.BoolVarP(&flags.d, "directory", "d", false, "Make a directory") diff --git a/cmds/core/mktemp/mktemp_test.go b/cmds/core/mktemp/mktemp_test.go index c9adceba00..4f2bc603d7 100644 --- a/cmds/core/mktemp/mktemp_test.go +++ b/cmds/core/mktemp/mktemp_test.go @@ -21,8 +21,7 @@ type test struct { } func TestMkTemp(t *testing.T) { - - var tests = []test{ + tests := []test{ { flags: []string{}, out: "/tmp/", diff --git a/cmds/core/mount/mount.go b/cmds/core/mount/mount.go index eeef35d20a..e6f5f86a4e 100644 --- a/cmds/core/mount/mount.go +++ b/cmds/core/mount/mount.go @@ -82,7 +82,6 @@ func getSupportedFilesystem(originFS string) ([]string, bool, error) { returnValue = append(returnValue, n[last]) } return returnValue, known, err - } func informIfUnknownFS(originFS string) { diff --git a/cmds/core/mv/mv.go b/cmds/core/mv/mv.go index a8e6bff068..026ef50c98 100644 --- a/cmds/core/mv/mv.go +++ b/cmds/core/mv/mv.go @@ -33,7 +33,6 @@ func usage() { } func moveFile(source string, dest string) error { - if *noClobber { _, err := os.Lstat(dest) if !os.IsNotExist(err) { diff --git a/cmds/core/mv/mv_test.go b/cmds/core/mv/mv_test.go index be6d6b0d6e..5206768fb0 100644 --- a/cmds/core/mv/mv_test.go +++ b/cmds/core/mv/mv_test.go @@ -26,25 +26,25 @@ var hiFileContent = []byte("hi") var old = makeIt{ n: "old.txt", - m: 0777, + m: 0o777, c: []byte("old"), } var new = makeIt{ n: "new.txt", - m: 0777, + m: 0o777, c: []byte("new"), } var tests = []makeIt{ { n: "hi1.txt", - m: 0666, + m: 0o666, c: hiFileContent, }, { n: "hi2.txt", - m: 0777, + m: 0o777, c: hiFileContent, }, old, @@ -58,12 +58,12 @@ func setup() (string, error) { } tmpdir := filepath.Join(d, "hi.sub.dir") - if err := os.Mkdir(tmpdir, 0777); err != nil { + if err := os.Mkdir(tmpdir, 0o777); err != nil { return "", err } - for _, t := range tests { - if err := ioutil.WriteFile(filepath.Join(d, t.n), []byte(t.c), t.m); err != nil { + for _, tt := range tests { + if err := ioutil.WriteFile(filepath.Join(d, tt.n), tt.c, tt.m); err != nil { return "", err } } diff --git a/cmds/core/pci/pci.go b/cmds/core/pci/pci.go index 1d678080ea..0f6ad48d10 100644 --- a/cmds/core/pci/pci.go +++ b/cmds/core/pci/pci.go @@ -29,13 +29,11 @@ import ( "github.com/u-root/u-root/pkg/pci" ) -var ( - format = map[int]string{ - 32: "%08x:%08x", - 16: "%08x:%04x", - 8: "%08x:%02x", - } -) +var format = map[int]string{ + 32: "%08x:%08x", + 16: "%08x:%04x", + 8: "%08x:%02x", +} // maybe we need a better syntax than the standard pcitools? func registers(d pci.Devices, cmds ...string) { diff --git a/cmds/core/ps/ps.go b/cmds/core/ps/ps.go index 4eeefab865..2da5816c0b 100644 --- a/cmds/core/ps/ps.go +++ b/cmds/core/ps/ps.go @@ -25,11 +25,12 @@ package main import ( "fmt" - flag "github.com/spf13/pflag" "io" "log" "os" "sort" + + flag "github.com/spf13/pflag" ) var ( @@ -211,7 +212,6 @@ func ps(pT *ProcessTable, w io.Writer) error { } return nil - } func usage() { diff --git a/cmds/core/ps/ps_linux.go b/cmds/core/ps/ps_linux.go index 626412efe1..5adc110242 100644 --- a/cmds/core/ps/ps_linux.go +++ b/cmds/core/ps/ps_linux.go @@ -167,7 +167,6 @@ func (p Process) GetUID() (int, error) { } return -1, fmt.Errorf("no Uid string in %s", p.status) - } // Get total time stat formated hh:mm:ss @@ -227,7 +226,7 @@ func (pT *ProcessTable) doTable(statFileNames []string) error { for _, stat := range statFileNames { p := &Process{} - //log.Printf("Check %s", stat) + // log.Printf("Check %s", stat) // ps is a snapshot in time of /proc. Hence we want to grab // all the files we need in as close to an instant in time as // we can. @@ -257,7 +256,7 @@ func (pT *ProcessTable) doTable(statFileNames []string) error { // if filepath.Base is *not* proc, then use it, else // it's just the directory containing the pid. proot := filepath.Dir(d) - //log.Printf("procdir %v d %v proot %v", procdir, d, proot) + // log.Printf("procdir %v d %v proot %v", procdir, d, proot) if proot != procdir { pid = filepath.Join(filepath.Base(proot), pid) } @@ -266,7 +265,7 @@ func (pT *ProcessTable) doTable(statFileNames []string) error { return err } p.Pid = pid - //log.Printf("stat is %v p is %v", stat,p) + // log.Printf("stat is %v p is %v", stat,p) if p.Pidno == os.Getpid() { pT.mProc = p } diff --git a/cmds/core/ps/ps_test.go b/cmds/core/ps/ps_test.go index 0190e1fdc7..fc25eba0fb 100644 --- a/cmds/core/ps/ps_test.go +++ b/cmds/core/ps/ps_test.go @@ -26,8 +26,8 @@ func TestPsExecution(t *testing.T) { if err != nil { t.Fatal(err) } - //defer os.Rmdirall(d) - var tests = []struct { + // defer os.Rmdirall(d) + tests := []struct { n string pid string files map[string]string @@ -35,43 +35,55 @@ func TestPsExecution(t *testing.T) { err error }{ {n: "missing files", pid: "1", files: map[string]string{"stat": "bad status file"}}, - {n: "one process", pid: "1", files: map[string]string{"stat": "bad status file", - "status": `Name: systemd + { + n: "one process", pid: "1", files: map[string]string{ + "stat": "bad status file", + "status": `Name: systemd TracerPid: 0 Uid: 0 0 0 0 Gid: 0 0 0 0 FDSize: 128 `, - "cmdline": "/sbin/init"}, + "cmdline": "/sbin/init", + }, o: "PID PGRP SID TTY STAT TIME COMMAND \n1 ? file 00:00:00 status \n", }, // Fix things up - {n: "correct pid 1", pid: "1", files: map[string]string{"stat": "1 (systemd) S 0 1 1 0 -1 4194560 82923 51272244 88 3457 153 671 103226 39563 20 0 1 0 2 230821888 2325 18446744073709551615 1 1 0 0 0 0 671173123 4096 1260 0 0 0 17 1 0 0 69 0 0 0 0 0 0 0 0 0 0", - "status": `Name: systemd + { + n: "correct pid 1", pid: "1", files: map[string]string{ + "stat": "1 (systemd) S 0 1 1 0 -1 4194560 82923 51272244 88 3457 153 671 103226 39563 20 0 1 0 2 230821888 2325 18446744073709551615 1 1 0 0 0 0 671173123 4096 1260 0 0 0 17 1 0 0 69 0 0 0 0 0 0 0 0 0 0", + "status": `Name: systemd TracerPid: 0 Uid: 0 0 0 0 Gid: 0 0 0 0 FDSize: 128 `, - "cmdline": "/sbin/init"}, + "cmdline": "/sbin/init", + }, o: "PID PGRP SID TTY STAT TIME COMMAND \n1 1 1 ? S 00:00:08 systemd \n", }, - {n: "second process", pid: "1996", files: map[string]string{"stat": "1996 (dnsmasq) S 1 1995 1995 0 -1 4194624 64 0 0 0 1 10 0 0 20 0 1 0 1208 51163136 91 18446744073709551615 1 1 0 0 0 0 0 4096 92675 0 0 0 17 2 0 0 0 0 0 0 0 0 0 0 0 0 0", + { + n: "second process", pid: "1996", files: map[string]string{ + "stat": "1996 (dnsmasq) S 1 1995 1995 0 -1 4194624 64 0 0 0 1 10 0 0 20 0 1 0 1208 51163136 91 18446744073709551615 1 1 0 0 0 0 0 4096 92675 0 0 0 17 2 0 0 0 0 0 0 0 0 0 0 0 0 0", - "status": `Name: dnsmasq + "status": `Name: dnsmasq Umask: 0022 Uid: 110 110 110 110 `, - "cmdline": "/usr/sbin/dnsmasq\000--conf-file=/var/lib/libvirt/dnsmasq/default.conf\000--leasefile-ro\000--dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper\000"}, + "cmdline": "/usr/sbin/dnsmasq\000--conf-file=/var/lib/libvirt/dnsmasq/default.conf\000--leasefile-ro\000--dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper\000", + }, o: " PID PGRP SID TTY STAT TIME COMMAND \n 1 1 1 ? S 00:00:08 systemd \n1996 1995 1995 ? S 00:00:00 dnsmasq \n", }, - {n: "nethost process", pid: "srv/1996", files: map[string]string{"stat": "1996 (dnsmasq) S 1 1995 1995 0 -1 4194624 64 0 0 0 1 10 0 0 20 0 1 0 1208 51163136 91 18446744073709551615 1 1 0 0 0 0 0 4096 92675 0 0 0 17 2 0 0 0 0 0 0 0 0 0 0 0 0 0", + { + n: "nethost process", pid: "srv/1996", files: map[string]string{ + "stat": "1996 (dnsmasq) S 1 1995 1995 0 -1 4194624 64 0 0 0 1 10 0 0 20 0 1 0 1208 51163136 91 18446744073709551615 1 1 0 0 0 0 0 4096 92675 0 0 0 17 2 0 0 0 0 0 0 0 0 0 0 0 0 0", - "status": `Name: dnsmasq + "status": `Name: dnsmasq Umask: 0022 Uid: 110 110 110 110 `, - "cmdline": "/usr/sbin/dnsmasq\000--conf-file=/var/lib/libvirt/dnsmasq/default.conf\000--leasefile-ro\000--dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper\000"}, + "cmdline": "/usr/sbin/dnsmasq\000--conf-file=/var/lib/libvirt/dnsmasq/default.conf\000--leasefile-ro\000--dhcp-script=/usr/lib/libvirt/libvirt_leaseshelper\000", + }, o: " PID PGRP SID TTY STAT TIME COMMAND \n 1 1 1 ? S 00:00:08 systemd \n 1996 1995 1995 ? S 00:00:00 dnsmasq \nsrv/1996 1995 1995 ? S 00:00:00 dnsmasq \n", }, } @@ -79,13 +91,13 @@ Uid: 110 110 110 110 for _, tt := range tests { pd := filepath.Join(d, tt.pid) t.Logf("Create %v", pd) - if err := os.MkdirAll(pd, 0777); err != nil { + if err := os.MkdirAll(pd, 0o777); err != nil { t.Fatalf("Make proc dir: %v", err) } for n, f := range tt.files { procf := filepath.Join(pd, n) t.Logf("Write %v", procf) - if err := ioutil.WriteFile(procf, []byte(f), 0666); err != nil { + if err := ioutil.WriteFile(procf, []byte(f), 0o666); err != nil { t.Fatal(err) } } @@ -101,12 +113,11 @@ Uid: 110 110 110 110 t.Errorf("%v: got %v, want %v", tt.n, err, tt.err) } } - } // Test Parsing of stat func TestParse(t *testing.T) { - var tests = []struct { + tests := []struct { name string p *Process out string @@ -178,7 +189,8 @@ Mems_allowed: 00000000,00000000,00000000,00000000,00000000,00000000,00000000,000 Mems_allowed_list: 0 voluntary_ctxt_switches: 10168 nonvoluntary_ctxt_switches: 3746 -`}, +`, + }, err: nil, }, } diff --git a/cmds/core/readlink/readlink_test.go b/cmds/core/readlink/readlink_test.go index 4bbf45bb07..a7d29af3b5 100644 --- a/cmds/core/readlink/readlink_test.go +++ b/cmds/core/readlink/readlink_test.go @@ -31,7 +31,7 @@ func TestReadlink(t *testing.T) { // Creating here to utilize path in tests testDir := filepath.Join(tmpDir, "readLinkDir") - if err := os.Mkdir(testDir, 0700); err != nil { + if err := os.Mkdir(testDir, 0o700); err != nil { t.Error(err) } @@ -39,18 +39,20 @@ func TestReadlink(t *testing.T) { t.Error(err) } - var tests = []test{ + tests := []test{ { flags: []string{}, out: "", stdErr: "", exitStatus: 1, - }, { + }, + { flags: []string{"-v", "f1"}, out: "", stdErr: "readlink f1: invalid argument\n", exitStatus: 1, - }, { + }, + { flags: []string{"-f", "f2"}, out: "", stdErr: "", diff --git a/cmds/core/rm/rm.go b/cmds/core/rm/rm.go index a445c45cb5..d1564a1692 100644 --- a/cmds/core/rm/rm.go +++ b/cmds/core/rm/rm.go @@ -18,12 +18,13 @@ package main import ( "bufio" "fmt" - flag "github.com/spf13/pflag" "io" "os" "path" "path/filepath" "strings" + + flag "github.com/spf13/pflag" ) var ( diff --git a/cmds/core/rm/rm_test.go b/cmds/core/rm/rm_test.go index 9f46525fe4..9bbad1a91b 100644 --- a/cmds/core/rm/rm_test.go +++ b/cmds/core/rm/rm_test.go @@ -40,23 +40,22 @@ func TestRemove(t *testing.T) { mode os.FileMode isdir bool }{ - { name: "hi", - mode: 0755, + mode: 0o755, isdir: true, }, { name: "hi/one.txt", - mode: 0666, + mode: 0o666, }, { name: "hi/two.txt", - mode: 0777, + mode: 0o777, }, { name: "go.txt", - mode: 0555, + mode: 0o555, }, } nilerr = func(err error) bool { return err == nil } @@ -157,7 +156,6 @@ func TestRemove(t *testing.T) { ) for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { d, err := ioutil.TempDir(os.TempDir(), "u-root.cmds.rm") if err != nil { @@ -185,7 +183,7 @@ func TestRemove(t *testing.T) { } func testRemove(t *testing.T, dir string, tc rmTestCase) { - var files = make([]string, len(tc.files)) + files := make([]string, len(tc.files)) for i, f := range tc.files { files[i] = path.Join(dir, f.name) } diff --git a/cmds/core/rsdp/rsdp.go b/cmds/core/rsdp/rsdp.go index 817ff5619b..dab559e5cd 100644 --- a/cmds/core/rsdp/rsdp.go +++ b/cmds/core/rsdp/rsdp.go @@ -29,9 +29,7 @@ import ( "github.com/u-root/u-root/pkg/acpi" ) -var ( - cmdUsage = "Usage: rsdp" -) +var cmdUsage = "Usage: rsdp" func usage() { log.Fatalf(cmdUsage) diff --git a/cmds/core/seq/seq_test.go b/cmds/core/seq/seq_test.go index a5f2ea6d97..6c75c931ae 100644 --- a/cmds/core/seq/seq_test.go +++ b/cmds/core/seq/seq_test.go @@ -45,7 +45,7 @@ func testseq(tests []test, t *testing.T) { // test default behavior without flags func TestSeqDefault(t *testing.T) { - var tests = []test{ + tests := []test{ { []string{"1", "3"}, "1\n2\n3\n", @@ -63,7 +63,7 @@ func TestSeqDefault(t *testing.T) { func TestSeqWidthEqual(t *testing.T) { flags.widthEqual = true defer resetFlags() - var tests = []test{ + tests := []test{ { []string{"8", "10"}, "08\n09\n10\n", @@ -81,7 +81,7 @@ func TestSeqCustomFormat(t *testing.T) { flags.format = "%.2f" flags.widthEqual = true defer resetFlags() - var tests = []test{ + tests := []test{ { []string{"8", "10"}, "08.00\n09.00\n10.00\n", @@ -98,7 +98,7 @@ func TestSeqCustomFormat(t *testing.T) { func TestSeqSeparator(t *testing.T) { flags.separator = "->" defer resetFlags() - var tests = []test{ + tests := []test{ { []string{"8", "10"}, "8->9->10\n", @@ -110,5 +110,4 @@ func TestSeqSeparator(t *testing.T) { } testseq(tests, t) - } diff --git a/cmds/core/shasum/shasum.go b/cmds/core/shasum/shasum.go index 60bbbd92f7..260f515763 100644 --- a/cmds/core/shasum/shasum.go +++ b/cmds/core/shasum/shasum.go @@ -15,7 +15,6 @@ import ( ) func helpPrinter() { - fmt.Printf("Usage:\nshasum -a \n") pflag.PrintDefaults() os.Exit(0) @@ -27,7 +26,6 @@ func versionPrinter() { } func getInput(fileName string) (input []byte, err error) { - if fileName != "" { return ioutil.ReadFile(fileName) } @@ -53,7 +51,6 @@ func shaPrinter(algorithm int, data []byte) string { } func main() { - var ( algorithm int help bool diff --git a/cmds/core/shasum/shasum_test.go b/cmds/core/shasum/shasum_test.go index 2d13a4c7ea..a1e58bf258 100644 --- a/cmds/core/shasum/shasum_test.go +++ b/cmds/core/shasum/shasum_test.go @@ -11,7 +11,7 @@ import ( ) func TestCksum(t *testing.T) { - var testMatrix = []struct { + testMatrix := []struct { data []byte cksum string algorithm int @@ -27,7 +27,6 @@ func TestCksum(t *testing.T) { t.Errorf("shasum verification failed.(Expected:%s, Received:%s)", testData.cksum, shaPrinter(testData.algorithm, testData.data)) } } - } func TestMain(m *testing.M) { diff --git a/cmds/core/sleep/sleep_test.go b/cmds/core/sleep/sleep_test.go index ca0ebca077..7e369011f8 100644 --- a/cmds/core/sleep/sleep_test.go +++ b/cmds/core/sleep/sleep_test.go @@ -10,7 +10,7 @@ import ( ) func TestParseDuration(t *testing.T) { - var tests = []struct { + tests := []struct { in string out time.Duration err error diff --git a/cmds/core/sluinit/uinit_linux.go b/cmds/core/sluinit/uinit_linux.go index 32fb0882b9..918a58d8ea 100644 --- a/cmds/core/sluinit/uinit_linux.go +++ b/cmds/core/sluinit/uinit_linux.go @@ -20,9 +20,7 @@ import ( "github.com/u-root/u-root/pkg/securelaunch/tpm" ) -var ( - slDebug = flag.Bool("d", false, "enable debug logs") -) +var slDebug = flag.Bool("d", false, "enable debug logs") func checkDebugFlag() { /* diff --git a/cmds/core/sort/sort_test.go b/cmds/core/sort/sort_test.go index 3a811d0f5e..4ebb8f3f96 100644 --- a/cmds/core/sort/sort_test.go +++ b/cmds/core/sort/sort_test.go @@ -71,7 +71,7 @@ func sortWithFiles(t *testing.T, tt test, tmpDir string, inPaths := make([]string, len(inFiles)) for i, inFile := range inFiles { inPaths[i] = filepath.Join(tmpDir, inFile) - if err := ioutil.WriteFile(inPaths[i], []byte(tt.in), 0600); err != nil { + if err := ioutil.WriteFile(inPaths[i], []byte(tt.in), 0o600); err != nil { t.Error(err) return } @@ -132,14 +132,20 @@ func TestMultipleFileInputs(t *testing.T) { } defer os.RemoveAll(tmpDir) - tt := test{[]string{}, "a\nb\nc\n", - "a\na\na\na\nb\nb\nb\nb\nc\nc\nc\nc\n"} + tt := test{ + []string{}, + "a\nb\nc\n", + "a\na\na\na\nb\nb\nb\nb\nc\nc\nc\nc\n", + } sortWithFiles(t, tt, tmpDir, []string{"in1", "in2", "in3", "in4"}, "out") // Run the test again without newline terminators. - tt = test{[]string{}, "a\nb\nc", - "a\na\na\na\nb\nb\nb\nb\nc\nc\nc\nc\n"} + tt = test{ + []string{}, + "a\nb\nc", + "a\na\na\na\nb\nb\nb\nb\nc\nc\nc\nc\n", + } sortWithFiles(t, tt, tmpDir, []string{"in1", "in2", "in3", "in4"}, "out") } diff --git a/cmds/core/sshd/sshd.go b/cmds/core/sshd/sshd.go index bb34474708..bac30304ba 100644 --- a/cmds/core/sshd/sshd.go +++ b/cmds/core/sshd/sshd.go @@ -21,12 +21,12 @@ import ( // The ssh package does not define these things so we will type ( ptyReq struct { - TERM string //TERM environment variable value (e.g., vt100) + TERM string // TERM environment variable value (e.g., vt100) Col uint32 Row uint32 Xpixel uint32 Ypixel uint32 - Modes string //encoded terminal modes + Modes string // encoded terminal modes } execReq struct { Command string diff --git a/cmds/core/strings/strings.go b/cmds/core/strings/strings.go index 6cd2464e9b..3f31f9da24 100644 --- a/cmds/core/strings/strings.go +++ b/cmds/core/strings/strings.go @@ -26,9 +26,7 @@ import ( flag "github.com/spf13/pflag" ) -var ( - n = flag.Int("n", 4, "the minimum string length") -) +var n = flag.Int("n", 4, "the minimum string length") func asciiIsPrint(char byte) bool { return char >= 32 && char <= 126 diff --git a/cmds/core/strings/strings_test.go b/cmds/core/strings/strings_test.go index 426dd9e2bc..31c10a58c7 100644 --- a/cmds/core/strings/strings_test.go +++ b/cmds/core/strings/strings_test.go @@ -24,43 +24,53 @@ type test struct { var stringsTests = []test{ { "empty", - []string{}, "", "", + []string{}, + "", "", }, { "sequences are too short", - []string{}, "\n\na\nab\n\nabc\nabc\xff\n01\n", "", + []string{}, + "\n\na\nab\n\nabc\nabc\xff\n01\n", "", }, { "entire string is too short", - []string{}, "abc", "", + []string{}, + "abc", "", }, { "entire string just fits perfectly", - []string{}, "abcd", "abcd\n", + []string{}, + "abcd", "abcd\n", }, { "entire string is printable", - []string{}, "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz\n", + []string{}, + "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz\n", }, { "terminating newline", - []string{}, "abcdefghijklmnopqrstuvwxyz\n", "abcdefghijklmnopqrstuvwxyz\n", + []string{}, + "abcdefghijklmnopqrstuvwxyz\n", "abcdefghijklmnopqrstuvwxyz\n", }, { "mix of printable and non-printable sequences", - []string{}, "\n\na123456\nab\n\nabc\nabcde\xff\n01\n", "a123456\nabcde\n", + []string{}, + "\n\na123456\nab\n\nabc\nabcde\xff\n01\n", "a123456\nabcde\n", }, { "spaces are printable", - []string{}, " abcdefghijklm nopqrstuvwxyz ", " abcdefghijklm nopqrstuvwxyz \n", + []string{}, + " abcdefghijklm nopqrstuvwxyz ", " abcdefghijklm nopqrstuvwxyz \n", }, { "shorter value of n", - []string{"--n", "1"}, "\n\na\nab\n\nabc\nabc\xff\n01\n", "a\nab\nabc\nabc\n01\n", + []string{"--n", "1"}, + "\n\na\nab\n\nabc\nabc\xff\n01\n", "a\nab\nabc\nabc\n01\n", }, { "larger value of n", - []string{"--n", "6"}, "\n\na123456\nab\n\nabc\nabcde\xff\n01\n", "a123456\n", + []string{"--n", "6"}, + "\n\na123456\nab\n\nabc\nabcde\xff\n01\n", "a123456\n", }, } diff --git a/cmds/core/stty/stty.go b/cmds/core/stty/stty.go index 597af5a2c7..d56985ec0b 100644 --- a/cmds/core/stty/stty.go +++ b/cmds/core/stty/stty.go @@ -67,7 +67,6 @@ import ( func main() { t, err := termios.GTTY(0) - if err != nil { log.Fatalf("termios.GTTY: %v", err) } @@ -81,7 +80,6 @@ func main() { fmt.Printf("%v\n", t.String()) case "dump": b, err := json.MarshalIndent(t, "", "\t") - if err != nil { log.Fatalf("json marshal: %v", err) } diff --git a/cmds/core/sync/sync.go b/cmds/core/sync/sync.go index 704b1de6de..52a2c1f9b1 100644 --- a/cmds/core/sync/sync.go +++ b/cmds/core/sync/sync.go @@ -40,7 +40,7 @@ func init() { func doSyscall(syscallNum uintptr) { for _, fileName := range flag.Args() { - f, err := os.OpenFile(fileName, syscall.O_RDONLY|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0644) + f, err := os.OpenFile(fileName, syscall.O_RDONLY|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0o644) if err != nil { log.Fatal(err) } diff --git a/cmds/core/tee/tee.go b/cmds/core/tee/tee.go index c060bae6eb..ff3bff1dfd 100644 --- a/cmds/core/tee/tee.go +++ b/cmds/core/tee/tee.go @@ -53,7 +53,7 @@ func main() { files := make([]*os.File, 0, flag.NArg()) writers := make([]io.Writer, 0, flag.NArg()+1) for _, fname := range flag.Args() { - f, err := os.OpenFile(fname, oflags, 0666) + f, err := os.OpenFile(fname, oflags, 0o666) if err != nil { log.Fatalf("%s: error opening %s: %v", name, fname, err) } diff --git a/cmds/core/time/time_test.go b/cmds/core/time/time_test.go index c3b6eec105..38ee6710f6 100644 --- a/cmds/core/time/time_test.go +++ b/cmds/core/time/time_test.go @@ -27,7 +27,7 @@ func run(c *exec.Cmd) (string, string, error) { } func TestTime(t *testing.T) { - var tests = []test{ + tests := []test{ {args: []string{}, r: "real 0.000.*\nuser 0.000.*\nsys 0.000", exitok: true}, {args: []string{"date"}, r: "real [0-9][0-9]*.*\nuser [0-9][0-9]*.*\nsys [0-9][0-9]*.*", exitok: true}, {args: []string{"deadbeef"}, r: ".*exec.*deadbeef.*executable file not found .*", exitok: false}, diff --git a/cmds/core/truncate/truncate.go b/cmds/core/truncate/truncate.go index c4164d5538..06b14914f5 100644 --- a/cmds/core/truncate/truncate.go +++ b/cmds/core/truncate/truncate.go @@ -69,7 +69,7 @@ func main() { var final int64 st, err := os.Stat(fname) if os.IsNotExist(err) && !*create { - if err = ioutil.WriteFile(fname, []byte{}, 0644); err != nil { + if err = ioutil.WriteFile(fname, []byte{}, 0o644); err != nil { log.Fatalf("truncate: ERROR: %v\n", err) } if st, err = os.Stat(fname); err != nil { diff --git a/cmds/core/truncate/truncate_test.go b/cmds/core/truncate/truncate_test.go index a3f47825bf..512b410b16 100644 --- a/cmds/core/truncate/truncate_test.go +++ b/cmds/core/truncate/truncate_test.go @@ -155,14 +155,14 @@ func TestTruncate(t *testing.T) { refFile := filepath.Join(tmpDir, fmt.Sprintf("ref%d", i)) if test.genTargetFile { data := make([]byte, test.initTargetSize) - if err := ioutil.WriteFile(targetFile, data, 0600); err != nil { + if err := ioutil.WriteFile(targetFile, data, 0o600); err != nil { t.Errorf("Failed to create test file %s: %v", targetFile, err) continue } } if test.genRefFile { data := make([]byte, test.initRefSize) - if err := ioutil.WriteFile(refFile, data, 0600); err != nil { + if err := ioutil.WriteFile(refFile, data, 0o600); err != nil { t.Errorf("Failed to create test file %s: %v", targetFile, err) continue } diff --git a/cmds/core/uniq/uniq.go b/cmds/core/uniq/uniq.go index 370d9844f5..3fd754a556 100644 --- a/cmds/core/uniq/uniq.go +++ b/cmds/core/uniq/uniq.go @@ -39,12 +39,14 @@ import ( "os" ) -var uniques = flag.Bool("u", false, "print unique lines") -var duplicates = flag.Bool("d", false, "print one copy of duplicated lines") -var count = flag.Bool("c", false, "prefix a repetition count and a tab for each output line") +var ( + uniques = flag.Bool("u", false, "print unique lines") + duplicates = flag.Bool("d", false, "print one copy of duplicated lines") + count = flag.Bool("c", false, "prefix a repetition count and a tab for each output line") +) -//var fnum = flag.Int("f", 0, "ignore num fields from beginning of line") -//var cnum = flag.Int("cn", 0, "ignore num characters from beginning of line") +// var fnum = flag.Int("f", 0, "ignore num fields from beginning of line") +// var cnum = flag.Int("cn", 0, "ignore num characters from beginning of line") func uniq(f *os.File) { br := bufio.NewReader(f) diff --git a/cmds/core/uptime/uptime.go b/cmds/core/uptime/uptime.go index b7074493c9..c240890d55 100644 --- a/cmds/core/uptime/uptime.go +++ b/cmds/core/uptime/uptime.go @@ -57,6 +57,6 @@ func main() { if err != nil { log.Fatal(err) } - //Subtracted one from time.Day() because time.Add(Duration) starts counting at 1 day instead of zero days. + // Subtracted one from time.Day() because time.Add(Duration) starts counting at 1 day instead of zero days. fmt.Printf(" %s up %d days, %d hours , %d min ,loadaverage: %s \n", time.Now().Format("15:04:05"), (uptimeTime.Day() - 1), uptimeTime.Hour(), uptimeTime.Minute(), loadAverage) } diff --git a/cmds/core/uptime/uptime_test.go b/cmds/core/uptime/uptime_test.go index e14820e736..f5494bf552 100644 --- a/cmds/core/uptime/uptime_test.go +++ b/cmds/core/uptime/uptime_test.go @@ -9,9 +9,7 @@ import ( "time" ) -var ( - testTime = time.Date(0001, 1, 15, 5, 35, 49, 0, time.UTC) -) +var testTime = time.Date(0o001, 1, 15, 5, 35, 49, 0, time.UTC) func invalidDurationError(d string) string { _, err := time.ParseDuration(d) @@ -19,7 +17,7 @@ func invalidDurationError(d string) string { } func TestUptime(t *testing.T) { - var tests = []struct { + tests := []struct { name string input string uptime *time.Time @@ -65,7 +63,7 @@ func TestUptime(t *testing.T) { } func TestLoadAverage(t *testing.T) { - var tests = []struct { + tests := []struct { name string input string loadAverage string diff --git a/cmds/core/watchdog/watchdog_linux.go b/cmds/core/watchdog/watchdog_linux.go index 898b9089be..e6cc340b32 100644 --- a/cmds/core/watchdog/watchdog_linux.go +++ b/cmds/core/watchdog/watchdog_linux.go @@ -28,9 +28,7 @@ import ( "github.com/u-root/u-root/pkg/watchdog" ) -var ( - dev = flag.String("dev", "/dev/watchdog", "device") -) +var dev = flag.String("dev", "/dev/watchdog", "device") func usage() { flag.Usage() diff --git a/cmds/core/wc/wc.go b/cmds/core/wc/wc.go index 86f0a0d13c..0bd2564cb1 100644 --- a/cmds/core/wc/wc.go +++ b/cmds/core/wc/wc.go @@ -53,11 +53,13 @@ import ( "unicode/utf8" ) -var lines = flag.Bool("l", false, "count lines") -var words = flag.Bool("w", false, "count words") -var runes = flag.Bool("r", false, "count runes") -var broken = flag.Bool("b", false, "count broken") -var chars = flag.Bool("c", false, "count bytes (include partial UTF)") +var ( + lines = flag.Bool("l", false, "count lines") + words = flag.Bool("w", false, "count words") + runes = flag.Bool("r", false, "count runes") + broken = flag.Bool("b", false, "count broken") + chars = flag.Bool("c", false, "count bytes (include partial UTF)") +) type cnt struct { nline, nword, nrune, nbadr, nchar int64 diff --git a/cmds/core/wc/wc_test.go b/cmds/core/wc/wc_test.go index 7b0518ec47..1ebcaa2700 100644 --- a/cmds/core/wc/wc_test.go +++ b/cmds/core/wc/wc_test.go @@ -14,7 +14,7 @@ import ( ) func TestWc(t *testing.T) { - var tab = []struct { + tab := []struct { i string o string s int diff --git a/cmds/core/wget/wget.go b/cmds/core/wget/wget.go index 75eb895b9a..f7354391e9 100644 --- a/cmds/core/wget/wget.go +++ b/cmds/core/wget/wget.go @@ -34,9 +34,7 @@ import ( "github.com/u-root/u-root/pkg/uio" ) -var ( - outPath = flag.String("O", "", "output file") -) +var outPath = flag.String("O", "", "output file") func usage() { log.Printf("Usage: %s [ARGS] URL\n", os.Args[0]) diff --git a/cmds/core/wget/wget_test.go b/cmds/core/wget/wget_test.go index a10ca33c5c..b55a38fdbf 100644 --- a/cmds/core/wget/wget_test.go +++ b/cmds/core/wget/wget_test.go @@ -53,7 +53,8 @@ var tests = []struct { url: "http://localhost:%[1]d/200", content: content, retCode: 0, - }, { + }, + { name: "ipv4", flags: []string{}, url: "http://127.0.0.1:%[1]d/200", @@ -74,19 +75,22 @@ var tests = []struct { url: "http://localhost:%[1]d/302", content: "", retCode: 0, - }, { + }, + { name: "4xx error", flags: []string{}, url: "http://localhost:%[1]d/404", content: "", retCode: 1, - }, { + }, + { name: "5xx error", flags: []string{}, url: "http://localhost:%[1]d/500", content: "", retCode: 1, - }, { + }, + { name: "no server", flags: []string{}, url: "http://localhost:%[2]d/200", diff --git a/cmds/core/which/which_test.go b/cmds/core/which/which_test.go index 4b556b7dde..eccdf8391f 100644 --- a/cmds/core/which/which_test.go +++ b/cmds/core/which/which_test.go @@ -61,7 +61,6 @@ func setup() error { // The output of which.go has to be exactly equal to the output of which itself. func TestWhichUnique(t *testing.T) { err := setup() - if err != nil { t.Fatalf("setup has failed, %v", err) } @@ -83,7 +82,6 @@ func TestWhichUnique(t *testing.T) { // three, it should work with more commands as well. func TestWhichMultiple(t *testing.T) { err := setup() - if err != nil { t.Fatalf("setup has failed, %v", err) } diff --git a/cmds/exp/ash/parse.go b/cmds/exp/ash/parse.go index f5ecd35011..625412d21f 100644 --- a/cmds/exp/ash/parse.go +++ b/cmds/exp/ash/parse.go @@ -58,7 +58,6 @@ func pushback(b *bufio.Reader) { func one(b *bufio.Reader) byte { c, err := b.ReadByte() - //fmt.Printf("one '%v' %v\n", c, err) if err == io.EOF { return 0 } @@ -82,7 +81,6 @@ func tok(b *bufio.Reader) (string, string) { var tokType, arg string c := next(b) - //fmt.Printf("TOK %v", c) switch c { case 0: return "EOF", "" @@ -117,26 +115,21 @@ func tok(b *bufio.Reader) (string, string) { case ' ', '\t': return "white", string(c) case '\n': - //fmt.Printf("NEWLINE\n") return "EOL", "" case '|', '&': - //fmt.Printf("LINK %v\n", c) // peek ahead. We need the literal, so don't use next() nc := one(b) if nc == c { - //fmt.Printf("LINK %v\n", string(c)+string(c)) return "LINK", string(c) + string(c) } pushback(b) if c == '&' { - //fmt.Printf("BG\n") tokType = "BG" if nc == 0 { tokType = "EOL" } return "BG", tokType } - //fmt.Printf("LINK %v\n", string(c)) return "LINK", string(c) default: for { @@ -152,7 +145,6 @@ func tok(b *bufio.Reader) (string, string) { } } - } // get an ARG. It has to work. @@ -171,6 +163,7 @@ func getArg(b *bufio.Reader, what string) string { return s } } + func parsestring(b *bufio.Reader, c *Command) (*Command, string) { t, s := tok(b) if s == "\n" || t == "EOF" || t == "EOL" { @@ -203,7 +196,6 @@ func parsestring(b *bufio.Reader, c *Command) (*Command, string) { // LINK and BG are similar save that LINK requires another command. If we don't get one, well. case "LINK": c.link = s - //fmt.Printf("LINK %v %v\n", c, s) return c, t case "BG": c.bg = true @@ -218,8 +210,8 @@ func parsestring(b *bufio.Reader, c *Command) (*Command, string) { t, s = tok(b) } } + func parse(b *bufio.Reader) (*Command, string) { - //fmt.Printf("%v %v\n", t, s) c := newCommand() return parsestring(b, c) } @@ -236,7 +228,6 @@ func parsecommands(b *bufio.Reader) ([]*Command, string) { if c == nil { return cmds, t } - //fmt.Printf("cmd %v\n", *c) cmds = append(cmds, c) if t == "EOF" || t == "EOL" { return cmds, t diff --git a/cmds/exp/ash/tty_linux.go b/cmds/exp/ash/tty_linux.go index 696ce91044..50a05a9477 100644 --- a/cmds/exp/ash/tty_linux.go +++ b/cmds/exp/ash/tty_linux.go @@ -58,5 +58,4 @@ func foreground() { log.Printf("rush pid %v: Can't set foreground to %v: %v", os.Getpid(), ttypgrp, errno) } } - } diff --git a/cmds/exp/bootvars/main.go b/cmds/exp/bootvars/main.go index eae7853c21..fd338e8828 100644 --- a/cmds/exp/bootvars/main.go +++ b/cmds/exp/bootvars/main.go @@ -23,7 +23,7 @@ import ( "github.com/u-root/u-root/pkg/uefivars/boot" ) -//must run as root, as efi vars are not accessible otherwise +// must run as root, as efi vars are not accessible otherwise func main() { m := flag.Bool("m", false, "Mount FS containing boot file, print path.") flag.Parse() @@ -36,7 +36,7 @@ func main() { log.Fatalf("Unable to read var... are you root?") } if *m { - //actually mount FS, locate file + // actually mount FS, locate file exe := fp.Base(os.Args[0]) tmp, err := ioutil.TempDir("", exe) if err != nil { @@ -56,7 +56,7 @@ func main() { log.Printf("file corresponding to CurrentBoot var can be found at %s\n", path) log.Printf("you will need to unmount the filesystem, remove temp dir, etc when done.\n") } else { - //just print out elements in variable + // just print out elements in variable log.Printf("%s", bv) for _, element := range bv.FilePathList { res, err := element.Resolver() diff --git a/cmds/exp/builtin/builtin.go b/cmds/exp/builtin/builtin.go index 84e1249783..56292014f3 100644 --- a/cmds/exp/builtin/builtin.go +++ b/cmds/exp/builtin/builtin.go @@ -138,7 +138,7 @@ func main() { } // write the new elvishPath for i, v := range filemap { - if err = ioutil.WriteFile(i, v, 0600); err != nil { + if err = ioutil.WriteFile(i, v, 0o600); err != nil { log.Fatal(err) } } @@ -149,7 +149,7 @@ func main() { cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout // TODO: figure out why we get EPERM when we use this. - //cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true,} + // cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true,} if *debug { log.Printf("Run %v", cmd) } diff --git a/cmds/exp/bzimage/bzimage.go b/cmds/exp/bzimage/bzimage.go index 793e29340d..2226848cda 100644 --- a/cmds/exp/bzimage/bzimage.go +++ b/cmds/exp/bzimage/bzimage.go @@ -53,8 +53,10 @@ bzimage cfg flags:` -var debug = flag.BoolP("debug", "d", false, "enable debug printing") -var jsonOut = flag.BoolP("json", "j", false, "json output ('ver' subcommand only)") +var ( + debug = flag.BoolP("debug", "d", false, "enable debug printing") + jsonOut = flag.BoolP("json", "j", false, "json output ('ver' subcommand only)") +) func usage() { fmt.Fprintln(os.Stderr, cmdUsage) @@ -78,7 +80,7 @@ func main() { usage() } - var br = &bzimage.BzImage{} + br := &bzimage.BzImage{} var image []byte switch a[0] { case "diff", "dump", "ver": @@ -112,7 +114,7 @@ func main() { log.Printf("%s", br.Header.Diff(&br2.Header)) log.Fatalf("there is no hope") } - if err := ioutil.WriteFile(a[2], o, 0666); err != nil { + if err := ioutil.WriteFile(a[2], o, 0o666); err != nil { log.Fatalf("Writing %v: %v", a[2], err) } case "diff": @@ -120,7 +122,7 @@ func main() { if err != nil { log.Fatal(err) } - var br2 = &bzimage.BzImage{} + br2 := &bzimage.BzImage{} if err = br2.UnmarshalBinary(b2); err != nil { log.Fatal(err) } @@ -153,7 +155,7 @@ func main() { fmt.Printf("Warning: %s is nil", v.n) continue } - if err := ioutil.WriteFile(v.n, v.b, 0666); err != nil { + if err := ioutil.WriteFile(v.n, v.b, 0o666); err != nil { log.Fatalf("Writing %v: %v", v, err) } } @@ -167,7 +169,7 @@ func main() { log.Fatal(err) } - if err := ioutil.WriteFile(a[3], b, 0644); err != nil { + if err := ioutil.WriteFile(a[3], b, 0o644); err != nil { log.Fatal(err) } case "ver": diff --git a/cmds/exp/bzimage/bzimage_test.go b/cmds/exp/bzimage/bzimage_test.go index 81da2c2361..1b05e1f36d 100644 --- a/cmds/exp/bzimage/bzimage_test.go +++ b/cmds/exp/bzimage/bzimage_test.go @@ -48,10 +48,11 @@ var ( 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - ExtRamdiskImage: 00, - ExtRamdiskSize: 00, - ExtCmdlinePtr: 00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + }, + ExtRamdiskImage: 0x00, + ExtRamdiskSize: 0x00, + ExtCmdlinePtr: 0x00, SetupSects: 0x1e, RootFlags: 0x01, Syssize: 0xb51d, @@ -114,13 +115,13 @@ func TestSimple(t *testing.T) { } defer os.RemoveAll(tmpDir) - var tests = []struct { + tests := []struct { args []string name string status int out string - skip int //leading chars to skip in output when comparing - outputContinues bool //if true, only compare 'out' len of bytes; flags produce extra output. + skip int // leading chars to skip in output when comparing + outputContinues bool // if true, only compare 'out' len of bytes; flags produce extra output. }{ { args: []string{"initramfs", "bzImage", "init.cpio", "zz/zz/zz"}, diff --git a/cmds/exp/cbmem/cbmem_linux_test.go b/cmds/exp/cbmem/cbmem_linux_test.go index a5fe5be73a..b1cac989a7 100644 --- a/cmds/exp/cbmem/cbmem_linux_test.go +++ b/cmds/exp/cbmem/cbmem_linux_test.go @@ -75,7 +75,7 @@ func TestAPU2(t *testing.T) { if err != nil { t.Fatalf("Reading coreboot table: got %v, want nil", err) } - var b = &bytes.Buffer{} + b := &bytes.Buffer{} DumpMem(f, c, false, b) t.Logf("%s", b.String()) o := b.String() @@ -95,7 +95,7 @@ func TestAPU2(t *testing.T) { } // You can use this to generate new test data. It's a timesaver. if false { - ioutil.WriteFile("json", j, 0666) + ioutil.WriteFile("json", j, 0o666) } if string(j) != apu2JSON { t.Errorf("APU2 JSON: got %s, want %s", j, apu2JSON) diff --git a/cmds/exp/cbmem/const.go b/cmds/exp/cbmem/const.go index 2deb528912..6749a8c5de 100644 --- a/cmds/exp/cbmem/const.go +++ b/cmds/exp/cbmem/const.go @@ -65,6 +65,7 @@ const ( LB_TAG_OPTION_DEFAULTS = 0x00cb LB_TAG_OPTION_CHECKSUM = 0x00cc ) + const ( LB_MEM_RAM = 1 LB_MEM_RESERVED = 2 // Don't use this memory region diff --git a/cmds/exp/cbmem/gen/gen.go b/cmds/exp/cbmem/gen/gen.go index 44d4c00e29..20e60f7e56 100644 --- a/cmds/exp/cbmem/gen/gen.go +++ b/cmds/exp/cbmem/gen/gen.go @@ -6,7 +6,6 @@ package main import ( "bytes" - "flag" "fmt" "io/ioutil" @@ -31,7 +30,7 @@ func genAPU2(n string) ([]byte, error) { if err != nil { return nil, err } - var out = bytes.NewBuffer([]byte("package main\nvar apu2 = []seg {\n")) + out := bytes.NewBuffer([]byte("package main\nvar apu2 = []seg {\n")) for _, m := range []struct { offset int64 size int64 @@ -73,7 +72,7 @@ func main() { if err != nil { log.Fatal(err) } - if err := ioutil.WriteFile("apu2.go", []byte(s), 0644); err != nil { + if err := ioutil.WriteFile("apu2.go", []byte(s), 0o644); err != nil { log.Fatal(err) } os.Exit(0) diff --git a/cmds/exp/cbmem/main_linux.go b/cmds/exp/cbmem/main_linux.go index 23be97d7b3..7d087e69f4 100644 --- a/cmds/exp/cbmem/main_linux.go +++ b/cmds/exp/cbmem/main_linux.go @@ -77,7 +77,6 @@ func init() { fmt.Fprintf(os.Stderr, "%s]\n\n%s", ushort, ulong) os.Exit(1) } - } // parseCBtable looks for a coreboot table in the range address, address + size - 1 @@ -226,7 +225,7 @@ func parseCBtable(f *os.File, address int64, sz int) (*CBmem, bool, error) { // "Nobody knew consoles could be so hard." case LB_TAG_CBMEM_CONSOLE: - var c = &memconsoleEntry{Record: rec} + c := &memconsoleEntry{Record: rec} debug(" Found cbmem console(%#x), %d byte record.\n", rec, c.Size) if err := readOne(r, &c.Address, j); err != nil { return nil, found, err @@ -252,7 +251,7 @@ func parseCBtable(f *os.File, address int64, sz int) (*CBmem, bool, error) { } cbcons += int64(reflect.TypeOf(c.Cursor).Size()) debug("CSize is %#x, and Cursor is at %#x", c.CSize, c.Cursor) - //p.cur f8b4 p.si 1fff8 curs f8b4 size f8b4 + // p.cur f8b4 p.si 1fff8 curs f8b4 size f8b4 sz := int(c.Size) cr, err = newOffsetReader(f, cbcons, sz) @@ -438,8 +437,6 @@ func main() { DumpMem(f, cbmem, hexdump, os.Stdout) } if console && cbmem.MemConsole != nil { - //fmt.Printf("Console is %d bytes and cursor is at %d\n", len(cbmem.MemConsole.Data), cbmem.MemConsole.Cursor) fmt.Printf("%s%s", cbmem.MemConsole.Data[cbmem.MemConsole.Cursor:], cbmem.MemConsole.Data[0:cbmem.MemConsole.Cursor]) } - } diff --git a/cmds/exp/cbmem/timestamps.go b/cmds/exp/cbmem/timestamps.go index dbd3bbcb41..45eaecae11 100644 --- a/cmds/exp/cbmem/timestamps.go +++ b/cmds/exp/cbmem/timestamps.go @@ -278,7 +278,7 @@ func (c *CBmem) readTimeStamps(f *os.File) (*TimeStamps, error) { return nil, fmt.Errorf("failed to read TSTable: %v", err) } a += int64(unsafe.Sizeof(t)) - var stamps = make([]TS, t.NumEntries) + stamps := make([]TS, t.NumEntries) ts := &TimeStamps{TS: []TS{{EntryID: 0, EntryStamp: t.BaseTime}}, TSHeader: t} if r, err = newOffsetReader(f, a, len(stamps)*int(unsafe.Sizeof(stamps[0]))); err != nil { return nil, fmt.Errorf("newOffsetReader for %d timestamps: %v", t.NumEntries, err) diff --git a/cmds/exp/cbmem/types.go b/cmds/exp/cbmem/types.go index 5035b70484..bdc95227fb 100755 --- a/cmds/exp/cbmem/types.go +++ b/cmds/exp/cbmem/types.go @@ -65,6 +65,7 @@ type memoryRange struct { Size uint64 Mtype uint32 } + type memoryEntry struct { Record Maps []memoryRange @@ -101,6 +102,7 @@ type timeStampTableEntry struct { Record TimeStampTable uint32 } + type serialEntry struct { Record Type uint32 @@ -116,10 +118,12 @@ type memconsoleEntry struct { Cursor uint32 Data string } + type forwardEntry struct { Record Forward uint64 } + type framebufferEntry struct { Record PhysicalAddress uint64 diff --git a/cmds/exp/cksum/cksum_test.go b/cmds/exp/cksum/cksum_test.go index 4db2a459f0..b28ac96179 100644 --- a/cmds/exp/cksum/cksum_test.go +++ b/cmds/exp/cksum/cksum_test.go @@ -11,7 +11,7 @@ import ( ) func TestCksum(t *testing.T) { - var testMatrix = []struct { + testMatrix := []struct { data []byte cksum uint32 }{ diff --git a/cmds/exp/console/console.go b/cmds/exp/console/console.go index 4d9bee0459..7a2ae05282 100644 --- a/cmds/exp/console/console.go +++ b/cmds/exp/console/console.go @@ -48,7 +48,6 @@ func main() { } in, out, err := console(*serial) - if err != nil { log.Fatal(err) } @@ -65,7 +64,7 @@ func main() { go io.Copy(out, p.Ptm) go func() { - var data = make([]byte, 1) + data := make([]byte, 1) for { if _, err := in.Read(data); err != nil { fmt.Printf("kid stdin: done\n") diff --git a/cmds/exp/disk_unlock/disk_unlock.go b/cmds/exp/disk_unlock/disk_unlock.go index 2cffa3cce2..f2daffb0b7 100644 --- a/cmds/exp/disk_unlock/disk_unlock.go +++ b/cmds/exp/disk_unlock/disk_unlock.go @@ -270,5 +270,4 @@ TryAllHSS: } verboseLog(fmt.Sprintf("Found these %s unlocked partitions: %v", *disk, parts)) - } diff --git a/cmds/exp/dmidecode/dmidecode.go b/cmds/exp/dmidecode/dmidecode.go index 1d11992e9e..a32535d746 100644 --- a/cmds/exp/dmidecode/dmidecode.go +++ b/cmds/exp/dmidecode/dmidecode.go @@ -23,19 +23,17 @@ var ( // NB: When adding flags, update resetFlags in dmidecode_test. ) -var ( - typeGroups = map[string][]uint8{ - "bios": {0, 13}, - "system": {1, 12, 15, 23, 32}, - "baseboard": {2, 10, 41}, - "chassis": {3}, - "processor": {4}, - "memory": {5, 6, 16, 17}, - "cache": {7}, - "connector": {8}, - "slot": {9}, - } -) +var typeGroups = map[string][]uint8{ + "bios": {0, 13}, + "system": {1, 12, 15, 23, 32}, + "baseboard": {2, 10, 41}, + "chassis": {3}, + "processor": {4}, + "memory": {5, 6, 16, 17}, + "cache": {7}, + "connector": {8}, + "slot": {9}, +} type dmiDecodeError struct { error @@ -76,7 +74,7 @@ func dumpBin(textOut io.Writer, entryData, tableData []byte, fileName string) *d e64.StructTableAddr = 0x20 edata, _ = e64.MarshalBinary() } - f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644) + f, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0o644) if err != nil { return &dmiDecodeError{code: 1, error: fmt.Errorf("error opening file for writing: %v", err)} } diff --git a/cmds/exp/dmidecode/dmidecode_test.go b/cmds/exp/dmidecode/dmidecode_test.go index 03921ac7eb..cae0bf8261 100644 --- a/cmds/exp/dmidecode/dmidecode_test.go +++ b/cmds/exp/dmidecode/dmidecode_test.go @@ -46,7 +46,7 @@ func testOutput(t *testing.T, dumpFile string, args []string, expectedOutFile st return } if !bytes.Equal(actualOut, expectedOut) { - ioutil.WriteFile(actualOutFile, actualOut, 0644) + ioutil.WriteFile(actualOutFile, actualOut, 0o644) t.Errorf("%+v %+v %+v: output mismatch, see %s", dumpFile, args, expectedOutFile, actualOutFile) diffOut, _ := exec.Command("diff", "-u", expectedOutFile, actualOutFile).CombinedOutput() t.Errorf("%+v %+v %+v: diff:\n%s", dumpFile, args, expectedOutFile, string(diffOut)) diff --git a/cmds/exp/ectool/commands.go b/cmds/exp/ectool/commands.go index 56fe3ecd14..560b51ee83 100644 --- a/cmds/exp/ectool/commands.go +++ b/cmds/exp/ectool/commands.go @@ -1515,6 +1515,7 @@ const ( ecLedIDCount ) + const ( /* LED control flags */ ecLedFlagsQuery = (1 << iota) /* Query LED capability only */ @@ -1941,8 +1942,10 @@ type ecResponsePort80LastBoot struct { * Version 1 separates the CPU thermal limits from the fan control. */ -const ecCmdThermalSetThreshold = 0x50 -const ecCmdThermalGetThreshold = 0x51 +const ( + ecCmdThermalSetThreshold = 0x50 + ecCmdThermalGetThreshold = 0x51 +) /* TYPE */ /* The version 0 structs are opaque. You have to know what they are for @@ -2303,17 +2306,21 @@ type ecResponseHostEventMask struct { } /* These all use ecResponseHostEventMask */ -const ecCmdHostEventGetB = 0x87 -const ecCmdHostEventGetSmiMask = 0x88 -const ecCmdHostEventGetSciMask = 0x89 -const ecCmdHostEventGetWakeMask = 0x8d +const ( + ecCmdHostEventGetB = 0x87 + ecCmdHostEventGetSmiMask = 0x88 + ecCmdHostEventGetSciMask = 0x89 + ecCmdHostEventGetWakeMask = 0x8d +) /* These all use ecParamsHostEventMask */ -const ecCmdHostEventSetSmiMask = 0x8a -const ecCmdHostEventSetSciMask = 0x8b -const ecCmdHostEventClear = 0x8c -const ecCmdHostEventSetWakeMask = 0x8e -const ecCmdHostEventClearB = 0x8f +const ( + ecCmdHostEventSetSmiMask = 0x8a + ecCmdHostEventSetSciMask = 0x8b + ecCmdHostEventClear = 0x8c + ecCmdHostEventSetWakeMask = 0x8e + ecCmdHostEventClearB = 0x8f +) /*****************************************************************************/ /* Switch commands */ @@ -2589,8 +2596,10 @@ const ecI2cFlagRead = (1 << 15) /* Mask for address */ const ecI2cAddrMask = 0x3ff -const ecI2cStatusNak = (1 << 0) /* Transfer was not acknowledged */ -const ecI2cStatusTimeout = (1 << 1) /* Timeout during transfer */ +const ( + ecI2cStatusNak = (1 << 0) /* Transfer was not acknowledged */ + ecI2cStatusTimeout = (1 << 1) /* Timeout during transfer */ +) /* Any error */ const ecI2cStatusError = (ecI2cStatusNak | ecI2cStatusTimeout) @@ -2864,9 +2873,11 @@ const ( ecSbFwUpdateMax = 0x7 ) -const sbFwUpdateCmdWriteBlockSize = 32 -const sbFwUpdateCmdStatusSize = 2 -const sbFwUpdateCmdInfoSize = 8 +const ( + sbFwUpdateCmdWriteBlockSize = 32 + sbFwUpdateCmdStatusSize = 2 + sbFwUpdateCmdInfoSize = 8 +) /* TYPE */ type ecSbFwUpdateHeader struct { @@ -2910,9 +2921,11 @@ type ecParamsEnteringMode struct { vbootMode int } -const vbootModeNormal = 0 -const vbootModeDeveloper = 1 -const vbootModeRecovery = 2 +const ( + vbootModeNormal = 0 + vbootModeDeveloper = 1 + vbootModeRecovery = 2 +) /*****************************************************************************/ /* System commands */ @@ -3021,9 +3034,12 @@ type ecParamsPdStatus struct { } /* Status of PD being sent back to EC */ -const pdStatusHostEvent = (1 << 0) /* Forward host event to AP */ -const pdStatusInRw = (1 << 1) /* Running RW image */ -const pdStatusJumpedToImage = (1 << 2) /* Current image was jumped to */ +const ( + pdStatusHostEvent = (1 << 0) /* Forward host event to AP */ + pdStatusInRw = (1 << 1) /* Running RW image */ + pdStatusJumpedToImage = (1 << 2) /* Current image was jumped to */ +) + /* TYPE */ type ecResponsePdStatus struct { status uint32 /* PD MCU status */ @@ -3035,9 +3051,11 @@ type ecResponsePdStatus struct { const ecCmdPdHostEventStatus = 0x104 /* PD MCU host event status bits */ -const pdEventUpdateDevice = (1 << 0) -const pdEventPowerChange = (1 << 1) -const pdEventIdentityReceived = (1 << 2) +const ( + pdEventUpdateDevice = (1 << 0) + pdEventPowerChange = (1 << 1) + pdEventIdentityReceived = (1 << 2) +) /* TYPE */ type ecResponseHostEventStatus struct { @@ -3234,11 +3252,12 @@ type ecResponsePdLog struct { } /* The timestamp is the microsecond counter shifted to get about a ms. */ -const pdLogTimestampShift = 10 /* 1 LSB = 1024us */ - -const pdLogSizeMask = 0x1F -const pdLogPortMask = 0xE0 -const pdLogPortShift = 5 +const ( + pdLogTimestampShift = 10 /* 1 LSB = 1024us */ + pdLogSizeMask = 0x1F + pdLogPortMask = 0xE0 + pdLogPortShift = 5 +) func pdLogPortSize(port, size uint8) uint8 { return (port << pdLogPortShift) | (size & pdLogSizeMask) @@ -3247,32 +3266,39 @@ func pdLogPortSize(port, size uint8) uint8 { func pdLogPort(sizePort uint8) uint8 { return sizePort >> pdLogPortShift } + func pdLogSize(sizePort uint8) uint8 { return sizePort & pdLogSizeMask } /* PD event log : entry types */ /* PD MCU events */ -const pdEventMcuBase = 0x00 -const pdEventMcuCharge = (pdEventMcuBase + 0) -const pdEventMcuConnect = (pdEventMcuBase + 1) +const ( + pdEventMcuBase = 0x00 + pdEventMcuCharge = (pdEventMcuBase + 0) + pdEventMcuConnect = (pdEventMcuBase + 1) +) /* Reserved for custom board event */ const pdEventMcuBoardCustom = (pdEventMcuBase + 2) /* PD generic accessory events */ -const pdEventAccBase = 0x20 -const pdEventAccRwFail = (pdEventAccBase + 0) -const pdEventAccRwErase = (pdEventAccBase + 1) +const ( + pdEventAccBase = 0x20 + pdEventAccRwFail = (pdEventAccBase + 0) + pdEventAccRwErase = (pdEventAccBase + 1) +) /* PD power supply events */ const pdEventPsBase = 0x40 const pdEventPsFault = (pdEventPsBase + 0) /* PD video dongles events */ -const pdEventVideoBase = 0x60 -const pdEventVideoDpMode = (pdEventVideoBase + 0) -const pdEventVideoCodec = (pdEventVideoBase + 1) +const ( + pdEventVideoBase = 0x60 + pdEventVideoDpMode = (pdEventVideoBase + 0) + pdEventVideoCodec = (pdEventVideoBase + 1) +) /* Returned in the "type" field, when there is no entry available */ const pdEventNoEntry = 0xFF @@ -3301,10 +3327,12 @@ const chargeFlagsRoleMask = (7 << 0) /* * pdEventPsFault data field flags definition : */ -const psFaultOcp = 1 -const psFaultFastOcp = 2 -const psFaultOvp = 3 -const psFaultDisch = 4 +const ( + psFaultOcp = 1 + psFaultFastOcp = 2 + psFaultOvp = 3 + psFaultDisch = 4 +) /* TYPE */ /* @@ -3416,9 +3444,11 @@ func ecCmdPassthruMax(n uint) uint { * switch to the new names soon, as the old names may not be carried forward * forever. */ -const ecHostParamSize = ecProto2MaxParamSize -const ecLpcAddrOldParam = ecHostCmdRegion1 -const ecOldParamSize = ecHostCmdRegionSize +const ( + ecHostParamSize = ecProto2MaxParamSize + ecLpcAddrOldParam = ecHostCmdRegion1 + ecOldParamSize = ecHostCmdRegionSize +) func ecVerMask(version uint8) uint8 { /* Command version mask */ diff --git a/cmds/exp/ectool/io.go b/cmds/exp/ectool/io.go index de0c47358b..645d3e41bd 100644 --- a/cmds/exp/ectool/io.go +++ b/cmds/exp/ectool/io.go @@ -15,12 +15,12 @@ type ioport interface { Outs(ioaddr, []uint8) (int, error) // For later, at some point, we may go with this. // Not yet. - //Out(ioaddr, interface{}) (int, error) + // Out(ioaddr, interface{}) (int, error) Inb(ioaddr) (uint8, error) Inw(ioaddr) (uint16, error) Inl(ioaddr) (uint32, error) Ins(ioaddr, int) ([]uint8, error) - //In(ioaddr, interface{}) (int, error) + // In(ioaddr, interface{}) (int, error) } type debugf func(string, ...interface{}) diff --git a/cmds/exp/ed/commands.go b/cmds/exp/ed/commands.go index af5ff3129f..b812ea0037 100644 --- a/cmds/exp/ed/commands.go +++ b/cmds/exp/ed/commands.go @@ -240,7 +240,7 @@ func cmdWrite(ctx *Context) (e error) { if ctx.cmd[ctx.cmdOffset] == 'W' { oFlag = os.O_APPEND } - if f, e = os.OpenFile(file, os.O_WRONLY|os.O_CREATE|oFlag, 0666); e != nil { + if f, e = os.OpenFile(file, os.O_WRONLY|os.O_CREATE|oFlag, 0o666); e != nil { return e } defer f.Close() @@ -409,7 +409,7 @@ func cmdMove(ctx *Context) (e error) { r[0] += delt r[1] += delt } else if dest > r[1] { - //NOP + // NOP } else { return fmt.Errorf("cannot move lines to within their own range") } @@ -456,10 +456,12 @@ func cmdPrompt(ctx *Context) (e error) { return } -var rxSanitize = regexp.MustCompile(`\\.`) -var rxBackrefSanitize = regexp.MustCompile(`\\\\`) -var rxBackref = regexp.MustCompile(`\\([0-9]+)|&`) -var rxSubArgs = regexp.MustCompile(`g|l|n|p|\d+`) +var ( + rxSanitize = regexp.MustCompile(`\\.`) + rxBackrefSanitize = regexp.MustCompile(`\\\\`) + rxBackref = regexp.MustCompile(`\\([0-9]+)|&`) + rxSubArgs = regexp.MustCompile(`g|l|n|p|\d+`) +) // FIXME: this is probably more convoluted than it needs to be func cmdSub(ctx *Context) (e error) { @@ -503,7 +505,7 @@ func cmdSub(ctx *Context) (e error) { arg := cmd[idx[1]+1:] // arg processing - var count = 1 + count := 1 var printP, printL, printN, global bool parsedArgs := rxSubArgs.FindAllStringSubmatch(arg, -1) @@ -559,8 +561,8 @@ func cmdSub(ctx *Context) (e error) { oLin := 0 for _, m := range matches { nMatch++ - //fRep := rep - //offset := 0 + // fRep := rep + // offset := 0 // Fill backrefs oRep := 0 diff --git a/cmds/exp/fdtdump/fdtdump.go b/cmds/exp/fdtdump/fdtdump.go index f267a8204b..b16637f575 100644 --- a/cmds/exp/fdtdump/fdtdump.go +++ b/cmds/exp/fdtdump/fdtdump.go @@ -21,9 +21,7 @@ import ( "github.com/u-root/u-root/pkg/dt" ) -var ( - asJSON = flag.Bool("json", false, "Print json with base64 encoded values.") -) +var asJSON = flag.Bool("json", false, "Print json with base64 encoded values.") func main() { flag.Parse() diff --git a/cmds/exp/field/field.go b/cmds/exp/field/field.go index 0db1255c38..d1b0017cd2 100644 --- a/cmds/exp/field/field.go +++ b/cmds/exp/field/field.go @@ -35,19 +35,19 @@ type frange struct { end int } -const lastField = 0x7FFFFFFF -const cmd = "field [ -E | -e ] [ -F regexp ] [ -0 | -O delimiter ] [file...]" - -var ( - flags struct { - nuloutsep bool - preserveEmpty bool - discardEmpty bool - insep string - outsep string - } +const ( + lastField = 0x7FFFFFFF + cmd = "field [ -E | -e ] [ -F regexp ] [ -0 | -O delimiter ] [file...]" ) +var flags struct { + nuloutsep bool + preserveEmpty bool + discardEmpty bool + insep string + outsep string +} + func init() { defUsage := flag.Usage flag.Usage = func() { diff --git a/cmds/exp/forth/forth.go b/cmds/exp/forth/forth.go index 93b20de770..87b40d355b 100644 --- a/cmds/exp/forth/forth.go +++ b/cmds/exp/forth/forth.go @@ -19,7 +19,7 @@ import ( var debug = flag.Bool("d", false, "Turn on forth package debugging using log.Printf") func main() { - var b = make([]byte, 512) + b := make([]byte, 512) flag.Parse() if *debug { forth.Debug = log.Printf diff --git a/cmds/exp/freq/freq.go b/cmds/exp/freq/freq.go index 4223f2c1e4..95b39d1e56 100644 --- a/cmds/exp/freq/freq.go +++ b/cmds/exp/freq/freq.go @@ -32,11 +32,13 @@ import ( "unicode/utf8" ) -var utf = flag.Bool("r", false, "treat input as UTF-8") -var dec = flag.Bool("d", false, "print decimal value") -var hex = flag.Bool("x", false, "print hexadecimal value") -var oct = flag.Bool("o", false, "print octal value") -var chr = flag.Bool("c", false, "print character/rune") +var ( + utf = flag.Bool("r", false, "treat input as UTF-8") + dec = flag.Bool("d", false, "print decimal value") + hex = flag.Bool("x", false, "print hexadecimal value") + oct = flag.Bool("o", false, "print octal value") + chr = flag.Bool("c", false, "print character/rune") +) var freq [utf8.MaxRune + 1]uint64 diff --git a/cmds/exp/hdparm/hdparm.go b/cmds/exp/hdparm/hdparm.go index 63aeb2ac3f..7c212a6450 100644 --- a/cmds/exp/hdparm/hdparm.go +++ b/cmds/exp/hdparm/hdparm.go @@ -114,5 +114,4 @@ func main() { fmt.Println(s) } } - } diff --git a/cmds/exp/lsfabric/lsfabric.go b/cmds/exp/lsfabric/lsfabric.go index 8b6da5f094..6355cf9041 100644 --- a/cmds/exp/lsfabric/lsfabric.go +++ b/cmds/exp/lsfabric/lsfabric.go @@ -40,8 +40,10 @@ const ( UNKNOWN instanceType = 0xb ) -type nodeID uint8 -type fabricID uint8 +type ( + nodeID uint8 + fabricID uint8 +) const ( // BROAD is our way of saying "broadcast address" @@ -274,7 +276,7 @@ func new(n uint8) (*DataFabric, error) { Enabled: enabled, FabricID: fabricID, // but see below. I am liking Some and None ... }) - //result.components.push(FabricComponent { instance_id, instance_type, enabled, fabric_id: if fabric_id != 0 || result.components.len() == 0 { Some(fabric_id) } else { None } }).unwrap(); + // result.components.push(FabricComponent { instance_id, instance_type, enabled, fabric_id: if fabric_id != 0 || result.components.len() == 0 { Some(fabric_id) } else { None } }).unwrap(); } diff --git a/cmds/exp/netbootxyz/netbootxyz.go b/cmds/exp/netbootxyz/netbootxyz.go index 1f61654564..2e12838eaa 100644 --- a/cmds/exp/netbootxyz/netbootxyz.go +++ b/cmds/exp/netbootxyz/netbootxyz.go @@ -138,7 +138,7 @@ func (o OSEndpoint) Load() error { fmt.Printf("Commandline: %s\n", o.Commandline) } else { tmpPath := "/tmp/" + strings.ReplaceAll(o.Name, " ", "") + "/" - err := os.Mkdir(tmpPath, 0666) + err := os.Mkdir(tmpPath, 0o666) if err != nil { return err } @@ -208,7 +208,7 @@ func indexOf(element string, data []string) int { return k } } - return -1 //not found. + return -1 // not found. } // remove element from array diff --git a/cmds/exp/netbootxyz/network.go b/cmds/exp/netbootxyz/network.go index 0760b2512e..5006e3153a 100644 --- a/cmds/exp/netbootxyz/network.go +++ b/cmds/exp/netbootxyz/network.go @@ -78,7 +78,6 @@ func downloadFile(filepath string, url string) error { log.Printf("Downloading file %s from %s\n", filepath, url) headResp, err := http.Head(url) - if err != nil { return err } diff --git a/cmds/exp/newsshd/newsshd.go b/cmds/exp/newsshd/newsshd.go index 10d2dd8ebd..963a0f2bfd 100644 --- a/cmds/exp/newsshd/newsshd.go +++ b/cmds/exp/newsshd/newsshd.go @@ -63,6 +63,7 @@ func handler(s ssh.Session) { } } } + func main() { flag.Parse() publicKeyOption := func(ctx ssh.Context, key ssh.PublicKey) bool { diff --git a/cmds/exp/pflask/pflask.go b/cmds/exp/pflask/pflask.go index 82a616eedf..7fea5f87fe 100644 --- a/cmds/exp/pflask/pflask.go +++ b/cmds/exp/pflask/pflask.go @@ -17,7 +17,6 @@ import ( "strings" "syscall" "time" - "unsafe" // "github.com/u-root/u-root/pkg/termios" @@ -93,7 +92,7 @@ func (c cgroupname) Validate(s string) { } func (c cgroupname) Create(s, name string) { - if err := os.MkdirAll(filepath.Join(string(c), s, name), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(string(c), s, name), 0o755); err != nil { log.Fatal(err) } } @@ -101,7 +100,7 @@ func (c cgroupname) Create(s, name string) { func (c cgroupname) Attach(s, name string, pid int) { t := filepath.Join(string(c), s, name, "tasks") b := []byte(fmt.Sprintf("%v", pid)) - if err := ioutil.WriteFile(t, b, 0600); err != nil { + if err := ioutil.WriteFile(t, b, 0o600); err != nil { log.Fatal(err) } } @@ -130,7 +129,6 @@ type mount struct { // Add adds a mount to the global mountlist. Don't know if we need it, but we might for additional volumes? func Add(src, dst, mtype, opts string, flags uintptr, dir bool) { mounts = append(mounts, mount{src: src, dst: dst, mtype: mtype, flags: flags, opts: opts, dir: dir}) - } // One mounts one mountpoint, using base as a prefix for the destination. @@ -139,7 +137,7 @@ func Add(src, dst, mtype, opts string, flags uintptr, dir bool) { func (m *mount) One(base string) { dst := filepath.Join(base, m.dst) if m.dir { - if err := os.MkdirAll(dst, 0755); err != nil { + if err := os.MkdirAll(dst, 0o755); err != nil { log.Fatalf("One: mkdirall %v: %v", m.dst, err) } } @@ -179,7 +177,7 @@ func modedev(st os.FileInfo) (uint32, int) { // makeConsole sets the right modes for the real console, then creates // a /dev/console in the chroot. func makeConsole(base, console string, unprivileged bool) { - if err := os.Chmod(console, 0600); err != nil { + if err := os.Chmod(console, 0o600); err != nil { log.Printf("%v", err) } if err := os.Chown(console, 0, 0); err != nil { @@ -197,7 +195,7 @@ func makeConsole(base, console string, unprivileged bool) { // In unprivileged uses, we can't mknod /dev/console, however, // we can just create a file /dev/console and use bind mount on file. if _, err := os.Stat(nn); err != nil { - ioutil.WriteFile(nn, []byte{}, 0600) // best effort, ignore error + ioutil.WriteFile(nn, []byte{}, 0o600) // best effort, ignore error } } else { if err := syscall.Mknod(nn, mode, dev); err != nil { @@ -210,7 +208,6 @@ func makeConsole(base, console string, unprivileged bool) { log.Fatalf("Mount :%s: on :%s: flags %v: %v", console, nn, syscall.MS_BIND, err) } - } // copyNodes makes copies of needed nodes in the chroot. @@ -221,7 +218,8 @@ func copyNodes(base string) { "/dev/null", "/dev/zero", "/dev/random", - "/dev/urandom"} + "/dev/urandom", + } for _, n := range nodes { st, err := os.Stat(n) @@ -328,8 +326,8 @@ func main() { if syscall.Geteuid() != 0 { c.SysProcAttr.Cloneflags |= syscall.CLONE_NEWUSER // Interesting. Won't build statically? - //c.SysProcAttr.UidMappings = []syscall.SysProcIDMap{{ContainerID: 0, HostID: syscall.Getuid(), Size: 1}} - //c.SysProcAttr.GidMappings = []syscall.SysProcIDMap{{ContainerID: 0, HostID: syscall.Getgid(), Size: 1}} + // c.SysProcAttr.UidMappings = []syscall.SysProcIDMap{{ContainerID: 0, HostID: syscall.Getuid(), Size: 1}} + // c.SysProcAttr.GidMappings = []syscall.SysProcIDMap{{ContainerID: 0, HostID: syscall.Getgid(), Size: 1}} } c.Stdin = os.Stdin @@ -358,7 +356,7 @@ func main() { } a = flag.Args() - //log.Printf("greetings %v\n", a) + // log.Printf("greetings %v\n", a) a = a[:len(a)-1] controlPTY, processTTY, sname, err := ptsopen() @@ -384,11 +382,11 @@ func main() { makeConsole(*chroot, sname, unprivileged) - //umask(0022); + // umask(0022); /* TODO: drop capabilities */ - //do_user(user); + // do_user(user); e := make(map[string]string) if *keepenv { diff --git a/cmds/exp/pox/pox.go b/cmds/exp/pox/pox.go index a2f5f0d35d..893285ea1d 100644 --- a/cmds/exp/pox/pox.go +++ b/cmds/exp/pox/pox.go @@ -135,11 +135,11 @@ This can also be passed in with the POX_EXTRA variable. // When chrooting, programs often want to access various system directories: var chrootMounts = []mp{ // mount --bind /sys /chroot/sys - {"/sys", "/sys", "", mount.MS_BIND, "", 0555}, + {"/sys", "/sys", "", mount.MS_BIND, "", 0o555}, // mount -t proc /proc /chroot/proc - {"/proc", "/proc", "proc", 0, "", 0555}, + {"/proc", "/proc", "proc", 0, "", 0o555}, // mount --bind /dev /chroot/dev - {"/dev", "/dev", "", mount.MS_BIND, "", 0755}} + {"/dev", "/dev", "", mount.MS_BIND, "", 0o755}} func poxCreate(bin ...string) error { if len(bin) == 0 { @@ -185,7 +185,7 @@ func poxCreate(bin ...string) error { f = strings.TrimPrefix(f, pwd) dfile := filepath.Join(dir, f) d := filepath.Dir(dfile) - if err := os.MkdirAll(d, 0755); err != nil { + if err := os.MkdirAll(d, 0o755); err != nil { in.Close() return err } @@ -307,7 +307,7 @@ func extraMounts(mountList string) error { v("Extra mounts: %q", mountList) // We have to specify the extra directories and do the create here b/c it is a squashfs. Sorry. for _, e := range strings.Split(mountList, ",") { - m := mp{flags: mount.MS_BIND, perm: 0755} + m := mp{flags: mount.MS_BIND, perm: 0o755} mp := strings.Split(e, ":") switch len(mp) { case 1: diff --git a/cmds/exp/pox/pox_test.go b/cmds/exp/pox/pox_test.go index bc9c547eb0..28a825263f 100644 --- a/cmds/exp/pox/pox_test.go +++ b/cmds/exp/pox/pox_test.go @@ -14,9 +14,7 @@ import ( "github.com/u-root/u-root/pkg/testutil" ) -var ( - uskip = len("2018/08/10 21:20:42 ") -) +var uskip = len("2018/08/10 21:20:42 ") func TestSimple(t *testing.T) { if os.Getuid() != 0 { @@ -29,7 +27,7 @@ func TestSimple(t *testing.T) { } defer os.RemoveAll(tmpDir) f := filepath.Join(tmpDir, "x.tcz") - var tests = []struct { + tests := []struct { args []string name string status int diff --git a/cmds/exp/run/run.go b/cmds/exp/run/run.go index e229f88e31..a48c1b4c38 100644 --- a/cmds/exp/run/run.go +++ b/cmds/exp/run/run.go @@ -92,5 +92,4 @@ func main() { if err := cmd.Run(); err != nil { log.Printf("%v\n", err) } - } diff --git a/cmds/exp/run/tempfile.go b/cmds/exp/run/tempfile.go index 7987a484ac..d6104143b3 100644 --- a/cmds/exp/run/tempfile.go +++ b/cmds/exp/run/tempfile.go @@ -56,7 +56,7 @@ func TempFile(dir, format string) (f *os.File, err error) { for i := 0; i < 10000; i++ { name := fmt.Sprintf(format, nextSuffix()) name = filepath.Join(dir, name) - f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) + f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600) if os.IsExist(err) { if nconflict++; nconflict > 10 { rand = reseed() diff --git a/cmds/exp/rush/parse.go b/cmds/exp/rush/parse.go index 4a6840723d..9991cc0a3b 100644 --- a/cmds/exp/rush/parse.go +++ b/cmds/exp/rush/parse.go @@ -58,7 +58,6 @@ func pushback(b *bufio.Reader) { func one(b *bufio.Reader) byte { c, err := b.ReadByte() - //fmt.Printf("one '%v' %v\n", c, err) if err == io.EOF { return 0 } @@ -82,7 +81,6 @@ func tok(b *bufio.Reader) (string, string) { var tokType, arg string c := next(b) - //fmt.Printf("TOK %v", c) switch c { case 0, 4: return "EOF", "" @@ -117,26 +115,21 @@ func tok(b *bufio.Reader) (string, string) { case ' ', '\t': return "white", string(c) case '\n', '\r': - //fmt.Printf("NEWLINE\n") return "EOL", "" case '|', '&': - //fmt.Printf("LINK %v\n", c) // peek ahead. We need the literal, so don't use next() nc := one(b) if nc == c { - //fmt.Printf("LINK %v\n", string(c)+string(c)) return "LINK", string(c) + string(c) } pushback(b) if c == '&' { - //fmt.Printf("BG\n") tokType = "BG" if nc == 0 { tokType = "EOL" } return "BG", tokType } - //fmt.Printf("LINK %v\n", string(c)) return "LINK", string(c) default: for { @@ -152,7 +145,6 @@ func tok(b *bufio.Reader) (string, string) { } } - } // get an ARG. It has to work. @@ -171,6 +163,7 @@ func getArg(b *bufio.Reader, what string) string { return s } } + func parsestring(b *bufio.Reader, c *Command) (*Command, string) { t, s := tok(b) if s == "\n" || t == "EOF" || t == "EOL" { @@ -203,7 +196,6 @@ func parsestring(b *bufio.Reader, c *Command) (*Command, string) { // LINK and BG are similar save that LINK requires another command. If we don't get one, well. case "LINK": c.link = s - //fmt.Printf("LINK %v %v\n", c, s) return c, t case "BG": c.bg = true @@ -218,8 +210,8 @@ func parsestring(b *bufio.Reader, c *Command) (*Command, string) { t, s = tok(b) } } + func parse(b *bufio.Reader) (*Command, string) { - //fmt.Printf("%v %v\n", t, s) c := newCommand() return parsestring(b, c) } @@ -236,7 +228,6 @@ func parsecommands(b *bufio.Reader) ([]*Command, string) { if c == nil { return cmds, t } - //fmt.Printf("cmd %v\n", *c) cmds = append(cmds, c) if t == "EOF" || t == "EOL" { return cmds, t diff --git a/cmds/exp/rush/rush.go b/cmds/exp/rush/rush.go index 2a3b4d7703..07d5d95d29 100644 --- a/cmds/exp/rush/rush.go +++ b/cmds/exp/rush/rush.go @@ -118,7 +118,7 @@ func openRead(c *Command, r io.Reader, fd int) (io.Reader, error) { func openWrite(c *Command, w io.Writer, fd int) (io.Writer, error) { if c.fdmap[fd] != "" { - f, err := os.OpenFile(c.fdmap[fd], os.O_CREATE|os.O_WRONLY, 0666) + f, err := os.OpenFile(c.fdmap[fd], os.O_CREATE|os.O_WRONLY, 0o666) c.files[fd] = f return f, err } diff --git a/cmds/exp/rush/tty_linux.go b/cmds/exp/rush/tty_linux.go index 696ce91044..50a05a9477 100644 --- a/cmds/exp/rush/tty_linux.go +++ b/cmds/exp/rush/tty_linux.go @@ -58,5 +58,4 @@ func foreground() { log.Printf("rush pid %v: Can't set foreground to %v: %v", os.Getpid(), ttypgrp, errno) } } - } diff --git a/cmds/exp/smbios_transfer/smbios_transfer.go b/cmds/exp/smbios_transfer/smbios_transfer.go index a49b72de60..726800ca36 100644 --- a/cmds/exp/smbios_transfer/smbios_transfer.go +++ b/cmds/exp/smbios_transfer/smbios_transfer.go @@ -31,9 +31,7 @@ const ( sysfsPath = "/sys/firmware/dmi/tables" ) -var ( - retries = flag.Int("num_retries", 2, "Number of times to retry transferring SMBIOS tables") -) +var retries = flag.Int("num_retries", 2, "Number of times to retry transferring SMBIOS tables") func writeCommitSmbiosBlob(id string, data []uint8, h *blobs.BlobHandler) (rerr error) { sessionID, err := h.BlobOpen(id, blobs.BMC_BLOB_OPEN_FLAG_WRITE) diff --git a/cmds/exp/srvfiles/srvfiles.go b/cmds/exp/srvfiles/srvfiles.go index b8f5f9fc50..0fa34b9805 100644 --- a/cmds/exp/srvfiles/srvfiles.go +++ b/cmds/exp/srvfiles/srvfiles.go @@ -36,7 +36,6 @@ var cacheHeaders = []string{ func maxAgeHandler(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - for _, v := range cacheHeaders { if r.Header.Get(v) != "" { r.Header.Del(v) diff --git a/cmds/exp/tcz/tcz.go b/cmds/exp/tcz/tcz.go index 8b48f39cf1..71820f140b 100644 --- a/cmds/exp/tcz/tcz.go +++ b/cmds/exp/tcz/tcz.go @@ -37,12 +37,12 @@ const ( LOOP_CTL_REMOVE = 0x4C81 LOOP_CTL_GET_FREE = 0x4C82 SYS_ioctl = 16 - dirMode = 0755 + dirMode = 0o755 tinyCoreRoot = "/TinyCorePackages/tcloop" ) -//http://distro.ibiblio.org/tinycorelinux/5.x/x86_64/tcz/ -//The .dep is the name + .dep +// http://distro.ibiblio.org/tinycorelinux/5.x/x86_64/tcz/ +// The .dep is the name + .dep var ( l = log.New(os.Stdout, "tcz: ", 0) @@ -94,7 +94,7 @@ func clonetree(tree string) error { debug("Mkdir of %s failed: %v", path[lt:], err) // TODO: EEXIST should not be an error. Ignore // err for now. FIXME. - //return err + // return err } return nil } @@ -185,7 +185,7 @@ func installPackage(tczName string, deps map[string]bool) error { debug("Fetched dep ok!\n") } else { debug("No dep file found\n") - if err := ioutil.WriteFile(filepath.Join(tczLocalPackageDir, depName), []byte{}, os.FileMode(0444)); err != nil { + if err := ioutil.WriteFile(filepath.Join(tczLocalPackageDir, depName), []byte{}, os.FileMode(0o444)); err != nil { debug("Tried to write Blank file %v, failed %v\n", depName, err) } return nil @@ -220,12 +220,11 @@ func installPackage(tczName string, deps map[string]bool) error { if string(deplist) == realDepList { return nil } - if err := ioutil.WriteFile(depFullPath, []byte(realDepList), os.FileMode(0444)); err != nil { + if err := ioutil.WriteFile(depFullPath, []byte(realDepList), os.FileMode(0o444)); err != nil { debug("Tried to write deplist file %v, failed %v\n", depName, err) return err } return nil - } func setupPackages(tczName string, deps map[string]bool) error { @@ -283,7 +282,6 @@ func setupPackages(tczName string, deps map[string]bool) error { } } return nil - } func usage() string { diff --git a/cmds/exp/validate/validate_test.go b/cmds/exp/validate/validate_test.go index 0feaa7c8af..1b83d32a66 100644 --- a/cmds/exp/validate/validate_test.go +++ b/cmds/exp/validate/validate_test.go @@ -24,7 +24,7 @@ type file struct { } func TestValidate(t *testing.T) { - var data = []byte(`127.0.0.1 localhost + data := []byte(`127.0.0.1 localhost 127.0.1.1 akaros 192.168.28.16 ak 192.168.28.131 uroot @@ -34,7 +34,7 @@ func TestValidate(t *testing.T) { ff02::1 ip6-allnodes ff02::2 ip6-allrouters `) - var tests = []file{ + tests := []file{ {name: "hosts.sha1", val: []byte("3f397a3b3a7450075da91b078afa35b794cf6088 hosts"), o: "SHA1\n"}, } @@ -43,12 +43,12 @@ ff02::2 ip6-allrouters t.Fatal("TempDir failed: ", err) } defer os.RemoveAll(tmpDir) - if err := ioutil.WriteFile(filepath.Join(tmpDir, "hosts"), data, 0444); err != nil { + if err := ioutil.WriteFile(filepath.Join(tmpDir, "hosts"), data, 0o444); err != nil { t.Fatalf("Can't set up data file: %v", err) } for _, v := range tests { - if err := ioutil.WriteFile(filepath.Join(tmpDir, v.name), v.val, 0444); err != nil { + if err := ioutil.WriteFile(filepath.Join(tmpDir, v.name), v.val, 0o444); err != nil { t.Fatalf("Can't set up hash file: %v", err) } diff --git a/examples/fixmynetboot/main.go b/examples/fixmynetboot/main.go index ec1edba487..f48a615798 100644 --- a/examples/fixmynetboot/main.go +++ b/examples/fixmynetboot/main.go @@ -26,9 +26,7 @@ var emergencyShellBanner = ` ************************************************************************** ` -var ( - doEmergencyShell = flag.Bool("shell", false, "Run emergency shell if checks fail") -) +var doEmergencyShell = flag.Bool("shell", false, "Run emergency shell if checks fail") func checkInterface(ifname string) error { checklist := []checker.Check{ @@ -42,7 +40,8 @@ func checkInterface(ifname string) error { Name: fmt.Sprintf("%s link speed", ifname), Run: checker.LinkSpeed(ifname, 400000), Remediate: nil, - StopOnError: false}, + StopOnError: false, + }, { Name: fmt.Sprintf("%s link autoneg", ifname), Run: checker.LinkAutoneg(ifname, true), diff --git a/examples/uinit/uinit.go b/examples/uinit/uinit.go index b0075daf34..ef0a24bfa3 100644 --- a/examples/uinit/uinit.go +++ b/examples/uinit/uinit.go @@ -12,15 +12,13 @@ import ( "strings" ) -var ( - commands = []string{ - "/bbin/date", - "/bbin/dhclient -ipv6=false", - "/bbin/ip a", - "/bbin/elvish", - "/bbin/shutdown halt", - } -) +var commands = []string{ + "/bbin/date", + "/bbin/dhclient -ipv6=false", + "/bbin/ip a", + "/bbin/elvish", + "/bbin/shutdown halt", +} func main() { for _, line := range commands { diff --git a/go.mod b/go.mod index 3b984244e0..59f01b3254 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/u-root/u-root go 1.17 require ( - github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect github.com/beevik/ntp v0.3.0 github.com/cenkalti/backoff/v4 v4.0.2 github.com/creack/pty v1.1.11 @@ -14,48 +13,52 @@ require ( github.com/google/go-cmp v0.5.2 github.com/google/go-tpm v0.2.1-0.20200615092505-5d8a91de9ae3 github.com/google/goexpect v0.0.0-20191001010744-5b6988669ffa - github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f // indirect github.com/insomniacslk/dhcp v0.0.0-20210817203519-d82598001386 github.com/intel-go/cpuid v0.0.0-20200819041909-2aa72927c3e2 - github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c // indirect - github.com/kaey/framebuffer v0.0.0-20140402104929-7b385489a1ff // indirect - github.com/klauspost/compress v1.10.6 // indirect github.com/klauspost/pgzip v1.2.4 github.com/kr/pty v1.1.8 - github.com/mattn/go-isatty v0.0.12 // indirect - github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7 // indirect - github.com/mdlayher/netlink v1.1.1 // indirect - github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065 // indirect github.com/orangecms/go-framebuffer v0.0.0-20200613202404-a0700d90c330 github.com/pborman/getopt/v2 v2.1.0 github.com/pierrec/lz4/v4 v4.1.11 - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rck/unit v0.0.3 github.com/rekby/gpt v0.0.0-20200219180433-a930afbc6edc github.com/safchain/ethtool v0.0.0-20200218184317-f459e2d13664 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.6.1 github.com/u-root/iscsinl v0.1.1-0.20210528121423-84c32645822a - github.com/u-root/uio v0.0.0-20210528114334-82958018845c // indirect github.com/ulikunitz/xz v0.5.8 github.com/vishvananda/netlink v1.1.1-0.20211118161826-650dca95af54 - github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f // indirect github.com/vtolstov/go-ioctl v0.0.0-20151206205506-6be9cced4810 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 - golang.org/x/mod v0.4.2 // indirect - golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect golang.org/x/sys v0.0.0-20210820121016-41cdb8703e55 golang.org/x/term v0.0.0-20210317153231-de623e64d2a6 golang.org/x/text v0.3.3 golang.org/x/tools v0.1.1 - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect - google.golang.org/grpc v1.29.1 // indirect gopkg.in/yaml.v2 v2.2.2 - gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect pack.ag/tftp v1.0.1-0.20181129014014-07909dfbde3c src.elv.sh v0.16.3 ) +require ( + github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect + github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f // indirect + github.com/jsimonetti/rtnetlink v0.0.0-20201110080708-d2c240429e6c // indirect + github.com/kaey/framebuffer v0.0.0-20140402104929-7b385489a1ff // indirect + github.com/klauspost/compress v1.10.6 // indirect + github.com/mattn/go-isatty v0.0.12 // indirect + github.com/mdlayher/ethernet v0.0.0-20190606142754-0394541c37b7 // indirect + github.com/mdlayher/netlink v1.1.1 // indirect + github.com/mdlayher/raw v0.0.0-20191009151244-50f2db8cc065 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/u-root/uio v0.0.0-20210528114334-82958018845c // indirect + github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f // indirect + golang.org/x/mod v0.4.2 // indirect + golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + google.golang.org/grpc v1.29.1 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect +) + retract ( v7.0.0+incompatible v6.0.0+incompatible diff --git a/go.sum b/go.sum index 32c0f6abaa..6ac3c85b29 100644 --- a/go.sum +++ b/go.sum @@ -164,8 +164,6 @@ github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljT github.com/ulikunitz/xz v0.5.8 h1:ERv8V6GKqVi23rgu5cj9pVfVzJbOqAY2Ntl88O6c2nQ= github.com/ulikunitz/xz v0.5.8/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= -github.com/vishvananda/netlink v1.1.1-0.20200221165523-c79a4b7b4066 h1:IlMBmSoCDZ9UY3OehFgvKSIgMNnU1vbAD4Fl+y2Rbis= -github.com/vishvananda/netlink v1.1.1-0.20200221165523-c79a4b7b4066/go.mod h1:FSQhuTO7eHT34mPzX+B04SUAjiqLxtXs1et0S6l9k4k= github.com/vishvananda/netlink v1.1.1-0.20211118161826-650dca95af54 h1:8mhqcHPqTMhSPoslhGYihEgSfc77+7La1P6kiB6+9So= github.com/vishvananda/netlink v1.1.1-0.20211118161826-650dca95af54/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= diff --git a/integration/generic-tests/dhclient_test.go b/integration/generic-tests/dhclient_test.go index 72209bf993..c9ba7e4299 100644 --- a/integration/generic-tests/dhclient_test.go +++ b/integration/generic-tests/dhclient_test.go @@ -39,7 +39,7 @@ func TestDhclientQEMU4(t *testing.T) { want := "conteeent" foobarFile := filepath.Join(dir, "foobar") - if err := ioutil.WriteFile(foobarFile, []byte(want), 0644); err != nil { + if err := ioutil.WriteFile(foobarFile, []byte(want), 0o644); err != nil { t.Fatal(err) } diff --git a/integration/generic-tests/tcz_test.go b/integration/generic-tests/tcz_test.go index 6748fb8655..55eb959cd0 100644 --- a/integration/generic-tests/tcz_test.go +++ b/integration/generic-tests/tcz_test.go @@ -124,5 +124,4 @@ func TestTczclient(t *testing.T) { } } } - } diff --git a/integration/testcmd/common/common.go b/integration/testcmd/common/common.go index f7c1b16fec..6e0b35f808 100644 --- a/integration/testcmd/common/common.go +++ b/integration/testcmd/common/common.go @@ -33,12 +33,12 @@ const ( // gcovFilter filters on all files ending with a gcda or gcno extension. func gcovFilter(hdr *tar.Header) bool { if hdr.Typeflag == tar.TypeDir { - hdr.Mode = 0770 + hdr.Mode = 0o770 return true } if (filepath.Ext(hdr.Name) == ".gcda" && hdr.Typeflag == tar.TypeReg) || (filepath.Ext(hdr.Name) == ".gcno" && hdr.Typeflag == tar.TypeSymlink) { - hdr.Mode = 0660 + hdr.Mode = 0o660 return true } return false diff --git a/pkg/acpi/acpi.go b/pkg/acpi/acpi.go index 5a60499a9b..4f20582738 100644 --- a/pkg/acpi/acpi.go +++ b/pkg/acpi/acpi.go @@ -106,7 +106,6 @@ func String(t Table) string { t.OEMRevision(), t.CreatorID(), t.CreatorRevision()) - } // WriteTables writes one or more tables to an io.Writer. diff --git a/pkg/acpi/acpi_test.go b/pkg/acpi/acpi_test.go index e3d2c63ad1..e670606542 100644 --- a/pkg/acpi/acpi_test.go +++ b/pkg/acpi/acpi_test.go @@ -35,20 +35,19 @@ func TestTabWrite(t *testing.T) { if ttab == nil { ttab = tabs[0] } - var b = &bytes.Buffer{} + b := &bytes.Buffer{} if err := WriteTables(b, ttab); err != nil { t.Fatal(err) } if !reflect.DeepEqual(b.Bytes(), ttab.Data()) { t.Fatalf("Written table does not match") } - } // TestAddr tests the decoding of those stupid "use this 64-bit if set else 32 things" // that permeate ACPI func TestAddr(t *testing.T) { - var tests = []struct { + tests := []struct { n string dat []byte a64 int64 diff --git a/pkg/acpi/rsdp.go b/pkg/acpi/rsdp.go index 654eac0513..f9c5ff94fe 100644 --- a/pkg/acpi/rsdp.go +++ b/pkg/acpi/rsdp.go @@ -11,9 +11,7 @@ import ( "github.com/u-root/u-root/pkg/memio" ) -var ( - defaultRSDP = []byte("RSDP PTR U-ROOT\x02") -) +var defaultRSDP = []byte("RSDP PTR U-ROOT\x02") // RSDP is the v2 version of the ACPI RSDP struct. type RSDP struct { diff --git a/pkg/acpi/sdt.go b/pkg/acpi/sdt.go index 358beb24cd..1fbde63fd4 100644 --- a/pkg/acpi/sdt.go +++ b/pkg/acpi/sdt.go @@ -10,9 +10,7 @@ import ( "fmt" ) -var ( - sdtLen = 36 -) +var sdtLen = 36 // SDT contains information about tables. It does not differentiate 32- vs 64-bit // tables. diff --git a/pkg/acpi/tables_linux_test.go b/pkg/acpi/tables_linux_test.go index 7732f5f5a9..76a335f262 100644 --- a/pkg/acpi/tables_linux_test.go +++ b/pkg/acpi/tables_linux_test.go @@ -33,5 +33,4 @@ func TestTable(t *testing.T) { if !reflect.DeepEqual(tg, tt) { t.Fatalf("Getting table via GetTable and %q: got different(%s, %s), want same", m, tg, tt) } - } diff --git a/pkg/bb/bb.go b/pkg/bb/bb.go index 4bfd563307..7f321dcda6 100644 --- a/pkg/bb/bb.go +++ b/pkg/bb/bb.go @@ -113,7 +113,7 @@ func BuildBusybox(env golang.Environ, pkgs []string, noStrip bool, binaryPath st if err := os.RemoveAll(bbDir); err != nil { return err } - if err := os.MkdirAll(bbDir, 0755); err != nil { + if err := os.MkdirAll(bbDir, 0o755); err != nil { return err } @@ -498,7 +498,7 @@ func (p *Package) rewriteFile(f *ast.File) bool { // Rewrite rewrites p into destDir as a bb package using bbImportPath for the // bb implementation. func (p *Package) Rewrite(destDir, bbImportPath string) error { - if err := os.MkdirAll(destDir, 0755); err != nil { + if err := os.MkdirAll(destDir, 0o755); err != nil { return err } @@ -599,7 +599,7 @@ func writeGoFile(path string, code []byte) error { return fmt.Errorf("bad parse while processing imports %q: %v", path, err) } - if err := ioutil.WriteFile(path, code, 0644); err != nil { + if err := ioutil.WriteFile(path, code, 0o644); err != nil { return fmt.Errorf("error writing Go file to %q: %v", path, err) } return nil diff --git a/pkg/boot/boottest/json.go b/pkg/boot/boottest/json.go index 271df9a6ba..83d243de3f 100644 --- a/pkg/boot/boottest/json.go +++ b/pkg/boot/boottest/json.go @@ -99,7 +99,7 @@ func ToJSONFile(imgs []boot.OSImage, filename string) error { if err != nil { return err } - return ioutil.WriteFile(filename, enc, 0644) + return ioutil.WriteFile(filename, enc, 0o644) } // ImagesToJSONLike spits out a json-convertible reproducible representation of diff --git a/pkg/boot/bzimage/bzimage.go b/pkg/boot/bzimage/bzimage.go index 8f0381ac82..46f5f6fade 100644 --- a/pkg/boot/bzimage/bzimage.go +++ b/pkg/boot/bzimage/bzimage.go @@ -50,7 +50,7 @@ var ( } // String of unknown meaning. // The build script has this value: - //initRAMFStag = [4]byte{0250, 0362, 0156, 0x01} + // initRAMFStag = [4]byte{0250, 0362, 0156, 0x01} // The resultant bzd has this value: initRAMFStag = [4]byte{0xf8, 0x85, 0x21, 0x01} @@ -418,7 +418,7 @@ func (b *BzImage) Diff(b2 *BzImage) string { s = s + fmt.Sprintf("b Tailcode is %d; b2 TailCode is %d", len(b.TailCode), len(b2.TailCode)) } if b.KernelBase != b2.KernelBase { - //NOTE: this is hardcoded to 0x100000 + // NOTE: this is hardcoded to 0x100000 s = s + fmt.Sprintf("b KernelBase is %#x; b2 KernelBase is %#x", b.KernelBase, b2.KernelBase) } if b.KernelOffset != b2.KernelOffset { @@ -473,7 +473,7 @@ func (b *BzImage) InitRAMFS() (int, int, error) { return -1, -1, err } cur = x - var r = bytes.NewReader(dat[cur:]) + r := bytes.NewReader(dat[cur:]) rr := archiver.Reader(r) Debug("r.Len is %v", r.Len()) var found bool @@ -529,13 +529,13 @@ func (b *BzImage) ReadConfig() (string, error) { return "", ErrCfgNotFound } i += 8 - mb := 1024 * 1024 //read only 1 mb; arbitrary + mb := 1024 * 1024 // read only 1 mb; arbitrary buf := bytes.NewReader(b.KernelCode[i : i+mb]) gz, err := gzip.NewReader(buf) if err != nil { return "", err } - //make it stop at end of stream, since we don't know the actual size + // make it stop at end of stream, since we don't know the actual size gz.Multistream(false) cfg, err := ioutil.ReadAll(gz) if err != nil { diff --git a/pkg/boot/bzimage/bzimage_test.go b/pkg/boot/bzimage/bzimage_test.go index ba572bd398..652f72aad5 100644 --- a/pkg/boot/bzimage/bzimage_test.go +++ b/pkg/boot/bzimage/bzimage_test.go @@ -122,7 +122,7 @@ func TestAddInitRAMFS(t *testing.T) { // qemu-system-x86_64 -serial stdio -kernel /tmp/x // I mainly left this here as a memo. if true { - if err := ioutil.WriteFile("/tmp/x", d, 0644); err != nil { + if err := ioutil.WriteFile("/tmp/x", d, 0o644); err != nil { t.Fatal(err) } } @@ -146,8 +146,8 @@ func TestAddInitRAMFS(t *testing.T) { t.Logf("shrink test, want nil, got %v", err) t.Fatal(err) } - } + func TestHeaderString(t *testing.T) { Debug = t.Logf initramfsimage, err := ioutil.ReadFile("testdata/bzImage") @@ -160,6 +160,7 @@ func TestHeaderString(t *testing.T) { } t.Logf("%s", b.Header.String()) } + func TestExtract(t *testing.T) { Debug = t.Logf initramfsimage, err := ioutil.ReadFile("testdata/bzImage") @@ -218,5 +219,4 @@ func TestInitRAMFS(t *testing.T) { } t.Logf("Found %d byte initramfs@%d:%d", e-s, s, e) } - } diff --git a/pkg/boot/bzimage/header.go b/pkg/boot/bzimage/header.go index b1628bf09a..e60c604a01 100644 --- a/pkg/boot/bzimage/header.go +++ b/pkg/boot/bzimage/header.go @@ -25,7 +25,7 @@ const ( Kernel boottype = 5 ) -//Offsets and magic values. +// Offsets and magic values. const ( RamdiskStartMask = 0x07FF Prompt = 0x8000 @@ -73,8 +73,10 @@ type EDDInfo struct { EDDDeviceParams [EDDDeviceParamSize]uint8 } -type e820type uint32 -type boottype uint8 +type ( + e820type uint32 + boottype uint8 +) // E820Entry is one e820 entry. type E820Entry struct { @@ -177,11 +179,11 @@ type LinuxParams struct { Pages uint16 `offset:"0x32"` _ [12]uint8 `offset:"0x34"` //-- 0x3f reserved for future expansion - //struct apmbiosinfo apmbiosinfo; + // struct apmbiosinfo apmbiosinfo; Apmbiosinfo [0x40]uint8 `offset:"0x40"` - //struct driveinfostruct driveinfo; + // struct driveinfostruct driveinfo; Driveinfo [0x20]uint8 `offset:"0x80"` - //struct sysdesctable sysdesctable; + // struct sysdesctable sysdesctable; Sysdesctable [0x140]uint8 `offset:"0xa0"` Altmemk uint32 `offset:"0x1e0"` _ [4]uint8 `offset:"0x1e4"` @@ -243,7 +245,7 @@ var ( EtherBoot: "etherboot", Kernel: "kernel (kexec)", } - //E820 contains strings describing e820types. + // E820 contains strings describing e820types. E820 = map[e820type]string{ RAM: "RAM", Reserved: "Reserved", diff --git a/pkg/boot/bzimage/kver.go b/pkg/boot/bzimage/kver.go index a9ebeffae0..3aa5143f13 100644 --- a/pkg/boot/bzimage/kver.go +++ b/pkg/boot/bzimage/kver.go @@ -28,22 +28,22 @@ off val 526 (2 bytes, little endian) + 0x200 -> start of null-terminated version string */ -const kverMax = 1024 //arbitrary +const kverMax = 1024 // arbitrary var ( - //ErrBootSig is returned when the boot sig is missing. + // ErrBootSig is returned when the boot sig is missing. ErrBootSig = errors.New("missing 0x55AA boot sig") - //ErrBadSig is returned when the kernel header sig is missing. + // ErrBadSig is returned when the kernel header sig is missing. ErrBadSig = errors.New("missing kernel header sig") - //ErrBadOff is returned if the version string offset is null. + // ErrBadOff is returned if the version string offset is null. ErrBadOff = errors.New("null version string offset") - //ErrParse is returned on a parse error. + // ErrParse is returned on a parse error. ErrParse = errors.New("parse error") ) // KVer reads the kernel version string. See also: (*BZImage)Kver() func KVer(k io.ReadSeeker) (string, error) { - var buf = make([]byte, kverMax) + buf := make([]byte, kverMax) _, err := k.Seek(0, io.SeekStart) if err != nil { return "", err @@ -91,7 +91,7 @@ func (bz *BzImage) KVer() (string, error) { return nullterm(bz.BootCode[bcoffs:end]), nil } -//read c string from buffer +// read c string from buffer func nullterm(buf []byte) string { var i int var b byte @@ -110,15 +110,15 @@ func nullterm(buf []byte) string { // release (builder) version //maj.min.patch-localver #buildnum SMP buildtime type KInfo struct { - Release, Version string //uname -r, uname -v respectfully - Builder string //user@hostname in parenthesis, shown by `file` but not `uname` + Release, Version string // uname -r, uname -v respectfully + Builder string // user@hostname in parenthesis, shown by `file` but not `uname` - //the following are extracted from Release and Version + // the following are extracted from Release and Version BuildNum uint64 //#nnn in Version, 300 in example above - BuildTime time.Time //from Version - Maj, Min, Patch uint64 //from Release - LocalVer string //from Release + BuildTime time.Time // from Version + Maj, Min, Patch uint64 // from Release + LocalVer string // from Release } // Equal compares two KInfo structs and returns @@ -142,24 +142,24 @@ const layout = "Mon Jan 2 15:04:05 MST 2006" func ParseDesc(desc string) (KInfo, error) { var ki KInfo - //first split at # + // first split at # split := strings.Split(desc, "#") if len(split) != 2 { return KInfo{}, fmt.Errorf("%w: %s: wrong number of '#' chars", ErrParse, desc) } ki.Version = "#" + split[1] - //now split first part into release and builder + // now split first part into release and builder elements := strings.SplitN(split[0], " ", 2) if len(elements) > 2 { return KInfo{}, fmt.Errorf("%w: %s: wrong number of spaces in release/builder", ErrParse, desc) } ki.Release = elements[0] if len(elements) == 2 { - //not sure if this is _always_ present + // not sure if this is _always_ present ki.Builder = strings.Trim(elements[1], " ()") } - //split build number off version + // split build number off version elements = strings.SplitN(split[1], " ", 2) if len(elements) != 2 { return KInfo{}, fmt.Errorf("%w: %s: wrong number of spaces in build/version", ErrParse, desc) @@ -169,9 +169,9 @@ func ParseDesc(desc string) (KInfo, error) { return KInfo{}, fmt.Errorf("%s: bad uint %s: %w", desc, elements[0], err) } ki.BuildNum = i - //remove SMP if present + // remove SMP if present t := strings.TrimSpace(strings.TrimPrefix(elements[1], "SMP")) - //parse remainder as time, using reference time + // parse remainder as time, using reference time ki.BuildTime, err = time.Parse(layout, t) if err != nil { return KInfo{}, fmt.Errorf("%s: bad time %s: %w", desc, t, err) diff --git a/pkg/boot/bzimage/kver_test.go b/pkg/boot/bzimage/kver_test.go index dfbe3ce16c..2504c063d0 100644 --- a/pkg/boot/bzimage/kver_test.go +++ b/pkg/boot/bzimage/kver_test.go @@ -20,12 +20,12 @@ const ( ancient = "2.6.24.111 #606 Mon Apr 14 00:06:11 CEST 2014" ) -//func KVer(k io.ReadSeeker) (string, error) +// func KVer(k io.ReadSeeker) (string, error) func TestKVer(t *testing.T) { items := []bufItem{ - {510, []byte{0x55, 0xaa}}, //boot sig - {514, []byte("HdrS")}, //kernel header - {526, []byte{0x58, 0x30}}, //add 0x200 for offset of null-terminated string + {510, []byte{0x55, 0xaa}}, // boot sig + {514, []byte("HdrS")}, // kernel header + {526, []byte{0x58, 0x30}}, // add 0x200 for offset of null-terminated string {12870, []byte("string starting.. " + normboot + "\000 end of str")}, } f, err := sparseBuf(items) @@ -46,27 +46,27 @@ type bufItem struct { data []byte } -//return buffer filled with random data, except for listed items +// return buffer filled with random data, except for listed items func sparseBuf(items []bufItem) (io.ReadSeeker, error) { - //figure out where last byte will fall + // figure out where last byte will fall var last int for _, i := range items { if len(i.data)+i.off > last { last = len(i.data) + i.off } } - //make buffer a bit oversize + // make buffer a bit oversize buf := make([]byte, last+64) - //write random data + // write random data rand.Read(buf) - //then write items + // then write items for _, i := range items { copy(buf[i.off:], i.data) } return bytes.NewReader(buf), nil } -//func ParseDesc(desc string) KInfo +// func ParseDesc(desc string) KInfo func TestParseDesc(t *testing.T) { tmust := func(tm time.Time, err error) time.Time { if err != nil { @@ -86,7 +86,7 @@ func TestParseDesc(t *testing.T) { Version: "#300 SMP Fri Jan 25 16:32:19 UTC 2019", Builder: "user@host", BuildNum: 300, - BuildTime: tmust(time.Parse(time.RFC3339, "2019-01-25T16:32:19Z")), //equivalent + BuildTime: tmust(time.Parse(time.RFC3339, "2019-01-25T16:32:19Z")), // equivalent Maj: 4, Min: 19, Patch: 16, @@ -101,7 +101,7 @@ func TestParseDesc(t *testing.T) { Version: "#606 Mon Apr 14 00:06:11 CEST 2014", Builder: "", BuildNum: 606, - BuildTime: tmust(time.Parse(time.RFC3339, "2014-04-14T00:06:11Z")), //equivalent + BuildTime: tmust(time.Parse(time.RFC3339, "2014-04-14T00:06:11Z")), // equivalent Maj: 2, Min: 6, Patch: 24, diff --git a/pkg/boot/fit/fit.go b/pkg/boot/fit/fit.go index b3f5c1a602..513a2bee45 100644 --- a/pkg/boot/fit/fit.go +++ b/pkg/boot/fit/fit.go @@ -67,7 +67,7 @@ func ParseConfig(r io.ReadSeeker) ([]Image, error) { cn, _ := configs.ListChildNodes() for _, n := range cn { - var i = Image{name: n, Root: fdt, ConfigOverride: n} + i := Image{name: n, Root: fdt, ConfigOverride: n} kn, in, err := i.LoadConfig() diff --git a/pkg/boot/fit/fit_test.go b/pkg/boot/fit/fit_test.go index 2833fe88e7..46a5cbb003 100644 --- a/pkg/boot/fit/fit_test.go +++ b/pkg/boot/fit/fit_test.go @@ -42,7 +42,6 @@ func TestLoadConfig(t *testing.T) { } kn, rn, err := i.LoadConfig() - if err != nil { t.Fatal(err) } @@ -308,7 +307,6 @@ func TestParseConfig(t *testing.T) { } imgs, err := ParseConfig(f) - if err != nil { t.Fatal(err) } diff --git a/pkg/boot/fit/vfit.go b/pkg/boot/fit/vfit.go index 4779468dc6..27a12683a5 100644 --- a/pkg/boot/fit/vfit.go +++ b/pkg/boot/fit/vfit.go @@ -30,22 +30,20 @@ import ( "golang.org/x/crypto/openpgp" ) -var ( - algs = map[string]crypto.Hash{ - "MD4": crypto.MD4, - "MD5": crypto.MD5, - "SHA1": crypto.SHA1, - "SHA224": crypto.SHA224, - "SHA256": crypto.SHA256, - "SHA384": crypto.SHA384, - "SHA512": crypto.SHA512, - "RIPEMD160": crypto.RIPEMD160, - "SHA3_224": crypto.SHA3_224, - "SHA3_256": crypto.SHA3_256, - "SHA3_384": crypto.SHA3_384, - "SHA3_512": crypto.SHA3_512, - } -) +var algs = map[string]crypto.Hash{ + "MD4": crypto.MD4, + "MD5": crypto.MD5, + "SHA1": crypto.SHA1, + "SHA224": crypto.SHA224, + "SHA256": crypto.SHA256, + "SHA384": crypto.SHA384, + "SHA512": crypto.SHA512, + "RIPEMD160": crypto.RIPEMD160, + "SHA3_224": crypto.SHA3_224, + "SHA3_256": crypto.SHA3_256, + "SHA3_384": crypto.SHA3_384, + "SHA3_512": crypto.SHA3_512, +} // Signature defines an extendable interface for verifying images using // varying signing methods. diff --git a/pkg/boot/grub/echo_test.go b/pkg/boot/grub/echo_test.go index db6bc6aeab..29cf201865 100644 --- a/pkg/boot/grub/echo_test.go +++ b/pkg/boot/grub/echo_test.go @@ -95,7 +95,7 @@ func TestGrubTests(t *testing.T) { cmd := exec.Command("./testdata/bash_wrapper.sh", os.Args[0], file) cmd.Env = append(os.Environ(), "BE_ECHO=1") out, err = cmd.Output() - //t.Logf("%s\n", out) + // t.Logf("%s\n", out) if err != nil { t.Fatalf("process ran with err %v", err) } @@ -129,7 +129,7 @@ func TestGrubTests(t *testing.T) { } // update/create golden file on success if *update { - err := ioutil.WriteFile(golden, out, 0644) + err := ioutil.WriteFile(golden, out, 0o644) if err != nil { t.Fatalf("error writing file `%s`, %v", file, err) } diff --git a/pkg/boot/grub/grub.go b/pkg/boot/grub/grub.go index b0028515b1..cee793eec1 100644 --- a/pkg/boot/grub/grub.go +++ b/pkg/boot/grub/grub.go @@ -504,5 +504,4 @@ func (c *parser) append(ctx context.Context, config string) error { } } return nil - } diff --git a/pkg/boot/grub/grub_test.go b/pkg/boot/grub/grub_test.go index d5cd4ec17c..187d0271d5 100644 --- a/pkg/boot/grub/grub_test.go +++ b/pkg/boot/grub/grub_test.go @@ -41,7 +41,6 @@ func TestCmdlineQuote(t *testing.T) { if got != tt.want { t.Errorf("cmdlineQuote = %#v, want %#v", got, tt.want) } - }) } } diff --git a/pkg/boot/ibft/ibft.go b/pkg/boot/ibft/ibft.go index e00debdf15..12a9366871 100644 --- a/pkg/boot/ibft/ibft.go +++ b/pkg/boot/ibft/ibft.go @@ -405,8 +405,10 @@ func gencsum(b []byte) byte { return ^csum + 1 } -const lengthOffset = 4 -const checksumOffset = 9 +const ( + lengthOffset = 4 + checksumOffset = 9 +) func fixACPIHeader(b []byte) []byte { binary.LittleEndian.PutUint16(b[lengthOffset:], uint16(len(b))) diff --git a/pkg/boot/ibft/ibft_test.go b/pkg/boot/ibft/ibft_test.go index 99652393ef..1d35fe79a2 100644 --- a/pkg/boot/ibft/ibft_test.go +++ b/pkg/boot/ibft/ibft_test.go @@ -146,7 +146,7 @@ func TestMarshal(t *testing.T) { Gateway: net.IP{192, 168, 1, 1}, PrimaryDNS: net.IP{8, 8, 8, 8}, DHCPServer: net.IP{192, 168, 1, 1}, - MACAddress: net.HardwareAddr{52, 54, 00, 12, 34, 56}, + MACAddress: net.HardwareAddr{52, 54, 0o0, 12, 34, 56}, }, Target0: Target{ Valid: true, @@ -162,7 +162,7 @@ func TestMarshal(t *testing.T) { emptyHeader(), defaultControl(), initiator(1<<1|1, 4 /* len */, 0x138), - nic(1<<2|1<<1|1, net.IP{192, 168, 1, 15} /* ip */, 24 /* netmask */, net.IP{192, 168, 1, 1} /* gateway */, net.IP{8, 8, 8, 8} /* dns */, net.IP{192, 168, 1, 1} /* dhcp serv */, net.HardwareAddr{52, 54, 00, 12, 34, 56} /* mac */, 0 /* BDF */), + nic(1<<2|1<<1|1, net.IP{192, 168, 1, 15} /* ip */, 24 /* netmask */, net.IP{192, 168, 1, 1} /* gateway */, net.IP{8, 8, 8, 8} /* dns */, net.IP{192, 168, 1, 1} /* dhcp serv */, net.HardwareAddr{52, 54, 0o0, 12, 34, 56} /* mac */, 0 /* BDF */), target(1<<1|1, net.IP{192, 168, 1, 1}, 3260, 27, 0x138+5), heap([]string{"NERF", "iqn.2016-01.com.example:foo"})), ), diff --git a/pkg/boot/kexec/memory_linux_test.go b/pkg/boot/kexec/memory_linux_test.go index 17d74186f4..8077adcffa 100644 --- a/pkg/boot/kexec/memory_linux_test.go +++ b/pkg/boot/kexec/memory_linux_test.go @@ -24,16 +24,16 @@ func TestParseMemoryMap(t *testing.T) { create := func(dir string, start, end uintptr, typ RangeType) error { p := path.Join(root, dir) - if err := os.Mkdir(p, 0755); err != nil { + if err := os.Mkdir(p, 0o755); err != nil { return err } - if err := ioutil.WriteFile(path.Join(p, "start"), []byte(fmt.Sprintf("%#x\n", start)), 0655); err != nil { + if err := ioutil.WriteFile(path.Join(p, "start"), []byte(fmt.Sprintf("%#x\n", start)), 0o655); err != nil { return err } - if err := ioutil.WriteFile(path.Join(p, "end"), []byte(fmt.Sprintf("%#x\n", end)), 0655); err != nil { + if err := ioutil.WriteFile(path.Join(p, "end"), []byte(fmt.Sprintf("%#x\n", end)), 0o655); err != nil { return err } - return ioutil.WriteFile(path.Join(p, "type"), append([]byte(typ), '\n'), 0655) + return ioutil.WriteFile(path.Join(p, "type"), append([]byte(typ), '\n'), 0o655) } if err := create("0", 0, 49, RangeRAM); err != nil { diff --git a/pkg/boot/menu/menu_test.go b/pkg/boot/menu/menu_test.go index 90ef2520bc..cf2b055d82 100644 --- a/pkg/boot/menu/menu_test.go +++ b/pkg/boot/menu/menu_test.go @@ -16,9 +16,7 @@ import ( "github.com/u-root/u-root/pkg/testutil" ) -var ( - inputDelay = 500 * time.Millisecond -) +var inputDelay = 500 * time.Millisecond func TestMain(m *testing.M) { SetInitialTimeout(inputDelay * 2) @@ -156,12 +154,12 @@ func TestChoose(t *testing.T) { name: "just_hit_enter", // user just hits enter. userEntry: []ReadLine{{"", nil}}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "hit_nothing", userEntry: []ReadLine{}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "hit_1", @@ -176,26 +174,26 @@ func TestChoose(t *testing.T) { { name: "out_of_bounds", userEntry: []ReadLine{{"4", nil}}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "not_a_number", userEntry: []ReadLine{{"abc", nil}}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "editing_allowed_override", userEntry: getEditSequence(false, "1", "after"), editingAllowed: true, expectedCmds: []string{"after", "before", "before"}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "editing_allowed_append", userEntry: getEditSequence(true, "2", "after"), editingAllowed: true, expectedCmds: []string{"before", "before after", "before"}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "select_after_override", @@ -217,21 +215,21 @@ func TestChoose(t *testing.T) { userEntry: errorOn(1, getEditSequence(false, "1", "after")), editingAllowed: true, expectedCmds: []string{"before", "before", "before"}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "edit_fail_reading_2", userEntry: errorOn(2, getEditSequence(false, "1", "after")), editingAllowed: true, expectedCmds: []string{"before", "before", "before"}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, { name: "edit_fail_reading_3", userEntry: errorOn(3, getEditSequence(false, "1", "after")), editingAllowed: true, expectedCmds: []string{"before", "before", "before"}, - wantedEntry: -1, //expect nil + wantedEntry: -1, // expect nil }, } { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/boot/multiboot/multiboot.go b/pkg/boot/multiboot/multiboot.go index f3345e38c0..2254bb1723 100644 --- a/pkg/boot/multiboot/multiboot.go +++ b/pkg/boot/multiboot/multiboot.go @@ -70,15 +70,13 @@ type multiboot struct { loadedModules modules } -var ( - rangeTypes = map[kexec.RangeType]uint32{ - kexec.RangeRAM: 1, - kexec.RangeDefault: 2, - kexec.RangeACPI: 3, - kexec.RangeNVS: 4, - kexec.RangeReserved: 2, - } -) +var rangeTypes = map[kexec.RangeType]uint32{ + kexec.RangeRAM: 1, + kexec.RangeDefault: 2, + kexec.RangeACPI: 3, + kexec.RangeNVS: 4, + kexec.RangeReserved: 2, +} var sizeofMemoryMap = uint(binary.Size(MemoryMap{})) diff --git a/pkg/boot/multiboot/multiboot_test.go b/pkg/boot/multiboot/multiboot_test.go index 7e1ee4012f..8177db81ce 100644 --- a/pkg/boot/multiboot/multiboot_test.go +++ b/pkg/boot/multiboot/multiboot_test.go @@ -114,7 +114,6 @@ func TestParseHeader(t *testing.T) { t.Errorf("parseHeader() got %+v, want %+v", got.mandatory, want.mandatory) } } - }) } } diff --git a/pkg/boot/netboot/ipxe/ipxe.go b/pkg/boot/netboot/ipxe/ipxe.go index bc0c6cfba3..b9c4a822af 100644 --- a/pkg/boot/netboot/ipxe/ipxe.go +++ b/pkg/boot/netboot/ipxe/ipxe.go @@ -20,11 +20,9 @@ import ( "github.com/u-root/u-root/pkg/ulog" ) -var ( - // ErrNotIpxeScript is returned when the config file is not an - // ipxe script. - ErrNotIpxeScript = errors.New("config file is not ipxe as it does not start with #!ipxe") -) +// ErrNotIpxeScript is returned when the config file is not an +// ipxe script. +var ErrNotIpxeScript = errors.New("config file is not ipxe as it does not start with #!ipxe") // parser encapsulates a parsed ipxe configuration file. // diff --git a/pkg/boot/syslinux/syslinux.go b/pkg/boot/syslinux/syslinux.go index 48cbd95c7d..ebc7be0290 100644 --- a/pkg/boot/syslinux/syslinux.go +++ b/pkg/boot/syslinux/syslinux.go @@ -468,5 +468,4 @@ func (c *parser) append(ctx context.Context, config string) error { } } return nil - } diff --git a/pkg/boot/systembooter/booter.go b/pkg/boot/systembooter/booter.go index 67986acd2f..e768300d4f 100644 --- a/pkg/boot/systembooter/booter.go +++ b/pkg/boot/systembooter/booter.go @@ -16,8 +16,7 @@ type Booter interface { // NullBooter is a booter that does nothing. It is used when no other booter // has been found. -type NullBooter struct { -} +type NullBooter struct{} // TypeName returns the name of the booter type func (nb *NullBooter) TypeName() string { diff --git a/pkg/boot/uefi/fv.go b/pkg/boot/uefi/fv.go index 165f0115e8..aff35e006d 100644 --- a/pkg/boot/uefi/fv.go +++ b/pkg/boot/uefi/fv.go @@ -37,11 +37,13 @@ type EFIFFSFileHeader struct { State uint8 } -const EFIFFSAttribLargeFile uint8 = 0x01 -const EFICommonSectionHeaderSize int = 4 -const EFICommonSectionHeader2Size int = 8 -const EFIFFSFileHeaderSize int = 24 -const EFIFFSFileHeader2Size int = 32 +const ( + EFIFFSAttribLargeFile uint8 = 0x01 + EFICommonSectionHeaderSize int = 4 + EFICommonSectionHeader2Size int = 8 + EFIFFSFileHeaderSize int = 24 + EFIFFSFileHeader2Size int = 32 +) const ( EFISectionTypePE32 uint8 = 0x10 diff --git a/pkg/boot/uefi/fv_test.go b/pkg/boot/uefi/fv_test.go index d6de85ea52..036ac6ce60 100644 --- a/pkg/boot/uefi/fv_test.go +++ b/pkg/boot/uefi/fv_test.go @@ -58,6 +58,7 @@ func TestFFSHeaderUnmarshalBinaryFailForSize(t *testing.T) { t.Fatalf("Should be '%s', but get '%v'", want, err) } } + func TestUnmarshalBinaryFailForSize(t *testing.T) { var fvh EFIFirmwareVolumeHeader err := fvh.UnmarshalBinary([]byte{0x0}) @@ -68,7 +69,7 @@ func TestUnmarshalBinaryFailForSize(t *testing.T) { } func TestIncorrectFVHSignature(t *testing.T) { - var dat = []byte{ + dat := []byte{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0xe5, 0x8c, 0x8c, 0x3d, 0x8a, 0x1c, 0x4f, diff --git a/pkg/boot/uefi/uefi.go b/pkg/boot/uefi/uefi.go index 317f10fc84..29d749132d 100644 --- a/pkg/boot/uefi/uefi.go +++ b/pkg/boot/uefi/uefi.go @@ -20,10 +20,12 @@ import ( "github.com/u-root/u-root/pkg/smbios" ) -var kexecLoad = kexec.Load -var kexecParseMemoryMap = kexec.ParseMemoryMap -var getRSDP = acpi.GetRSDP -var getSMBIOSBase = smbios.SMBIOSBase +var ( + kexecLoad = kexec.Load + kexecParseMemoryMap = kexec.ParseMemoryMap + getRSDP = acpi.GetRSDP + getSMBIOSBase = smbios.SMBIOSBase +) // SerialPortConfig defines debug port configuration // This struct will be used to initialize SERIAL_PORT_INFO diff --git a/pkg/cmdline/cmdline.go b/pkg/cmdline/cmdline.go index 81c6580161..4e553ef8b3 100644 --- a/pkg/cmdline/cmdline.go +++ b/pkg/cmdline/cmdline.go @@ -79,7 +79,6 @@ func parse(cmdlineReader io.Reader) CmdLine { // func doParse(input string, handler func(flag, key, canonicalKey, value, trimmedValue string)) { - lastQuote := rune(0) quotedFieldsCheck := func(c rune) bool { switch { @@ -120,12 +119,10 @@ func doParse(input string, handler func(flag, key, canonicalKey, value, trimmedV // Call the user handler handler(flag, key, canonicalKey, value, trimmedValue) } - } // parseToMap turns a space-separated kernel commandline into a map func parseToMap(input string) map[string]string { - flagMap := make(map[string]string) doParse(input, func(flag, key, canonicalKey, value, trimmedValue string) { // We store the value twice, once with dash, once with underscores diff --git a/pkg/cmdline/cmdline_test.go b/pkg/cmdline/cmdline_test.go index 340a7a9ac2..3e4a61f6ab 100644 --- a/pkg/cmdline/cmdline_test.go +++ b/pkg/cmdline/cmdline_test.go @@ -10,7 +10,6 @@ import ( ) func TestCmdline(t *testing.T) { - exampleCmdLine := `BOOT_IMAGE=/vmlinuz-4.11.2 ro ` + `test-flag test2-flag=8 ` + `uroot.initflags="systemd test-flag=3 test2-flag runlevel=2" ` + @@ -70,7 +69,6 @@ func TestCmdline(t *testing.T) { if initFlagMap = GetInitFlagMap(); len(initFlagMap) != 0 { t.Errorf("initFlagMap should be empty, is actually %v", initFlagMap) } - } func TestCmdlineModules(t *testing.T) { diff --git a/pkg/complete/complete_test.go b/pkg/complete/complete_test.go index b0b7c1ece1..d55005a721 100644 --- a/pkg/complete/complete_test.go +++ b/pkg/complete/complete_test.go @@ -74,7 +74,7 @@ func TestFile(t *testing.T) { ) for _, n := range allnames { - if err := ioutil.WriteFile(filepath.Join(tempDir, n), []byte{}, 0600); err != nil { + if err := ioutil.WriteFile(filepath.Join(tempDir, n), []byte{}, 0o600); err != nil { t.Fatal(err) } t.Logf("Wrote %v", filepath.Join(tempDir, n)) @@ -141,15 +141,15 @@ func TestMulti(t *testing.T) { } ) for _, p := range []string{"bin", "sbin"} { - if err := os.MkdirAll(filepath.Join(tempDir, p), 0700); err != nil { + if err := os.MkdirAll(filepath.Join(tempDir, p), 0o700); err != nil { t.Fatal(err) } } for _, n := range allnames { - if err := ioutil.WriteFile(filepath.Join(tempDir, "bin", "a"+n), []byte{}, 0600); err != nil { + if err := ioutil.WriteFile(filepath.Join(tempDir, "bin", "a"+n), []byte{}, 0o600); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(tempDir, "sbin", "b"+n), []byte{}, 0600); err != nil { + if err := ioutil.WriteFile(filepath.Join(tempDir, "sbin", "b"+n), []byte{}, 0o600); err != nil { t.Fatal(err) } } @@ -196,7 +196,7 @@ func TestMulti(t *testing.T) { } func TestInOut(t *testing.T) { - var tests = []struct { + tests := []struct { ins []string stack string }{ @@ -219,8 +219,8 @@ func TestInOut(t *testing.T) { // TestInOut tests the InOut structures, which we don't know we want. func TestInOutRW(t *testing.T) { - var els = []string{"ab", "bc", "de", "fgh"} - var outs = []string{"ab", "abbc", "abbcde", "abbcdefgh"} + els := []string{"ab", "bc", "de", "fgh"} + outs := []string{"ab", "abbc", "abbcde", "abbcdefgh"} l := NewLine() t.Logf("%v %v %v", els, outs, l) @@ -303,7 +303,7 @@ func TestLineReader(t *testing.T) { // TestEnv tests the the environment completer. func TestEnv(t *testing.T) { - var tests = []struct { + tests := []struct { pathVal string nels int err error diff --git a/pkg/complete/prefix.go b/pkg/complete/prefix.go index 3272961e39..61f810e91f 100644 --- a/pkg/complete/prefix.go +++ b/pkg/complete/prefix.go @@ -12,7 +12,7 @@ func Prefix(s []string) string { if len(s) == 0 { return "" } - var a = s[0] + a := s[0] for _, h := range s { if len(h) < len(a) { a = h @@ -27,7 +27,6 @@ func Prefix(s []string) string { done = false break } - } } return a diff --git a/pkg/complete/prefix_test.go b/pkg/complete/prefix_test.go index 6bbd2c9a25..6753ab949d 100644 --- a/pkg/complete/prefix_test.go +++ b/pkg/complete/prefix_test.go @@ -9,7 +9,7 @@ import ( ) func TestPrefix(t *testing.T) { - var tests = []string{ + tests := []string{ "/etc/hosts.allow", "/etc/hosts.deny", "/etc/hosts", @@ -20,7 +20,7 @@ func TestPrefix(t *testing.T) { "", } - var testsout = []string{ + testsout := []string{ "/etc/hosts.allow", "/etc/hosts.", "/etc/hosts", diff --git a/pkg/cp/cp_test.go b/pkg/cp/cp_test.go index 95721bb317..544180b1d6 100644 --- a/pkg/cp/cp_test.go +++ b/pkg/cp/cp_test.go @@ -32,7 +32,7 @@ func TestSimpleCopy(t *testing.T) { // Copy a directory. origd := filepath.Join(tmpDir, "directory") - if err := os.Mkdir(origd, 0744); err != nil { + if err := os.Mkdir(origd, 0o744); err != nil { t.Fatal(err) } @@ -41,7 +41,7 @@ func TestSimpleCopy(t *testing.T) { // Copy a file. origf := filepath.Join(tmpDir, "normal-file") - if err := ioutil.WriteFile(origf, []byte("F is for fire that burns down the whole town"), 0766); err != nil { + if err := ioutil.WriteFile(origf, []byte("F is for fire that burns down the whole town"), 0o766); err != nil { t.Fatal(err) } diff --git a/pkg/cpio/const.go b/pkg/cpio/const.go index 039245e861..0773794134 100644 --- a/pkg/cpio/const.go +++ b/pkg/cpio/const.go @@ -34,16 +34,16 @@ const ( // Unix mode_t bits. const ( - modeTypeMask = 0170000 - modeSocket = 0140000 - modeSymlink = 0120000 - modeFile = 0100000 - modeBlock = 0060000 - modeDir = 0040000 - modeChar = 0020000 - modeFIFO = 0010000 - modeSUID = 0004000 - modeSGID = 0002000 - modeSticky = 0001000 - modePermissions = 0000777 + modeTypeMask = 0o170000 + modeSocket = 0o140000 + modeSymlink = 0o120000 + modeFile = 0o100000 + modeBlock = 0o060000 + modeDir = 0o040000 + modeChar = 0o020000 + modeFIFO = 0o010000 + modeSUID = 0o004000 + modeSGID = 0o002000 + modeSticky = 0o001000 + modePermissions = 0o000777 ) diff --git a/pkg/cpio/cpio.go b/pkg/cpio/cpio.go index 886f781bca..9213b563ab 100644 --- a/pkg/cpio/cpio.go +++ b/pkg/cpio/cpio.go @@ -137,7 +137,7 @@ func Format(name string) (RecordFormat, error) { } func modeFromLinux(mode uint64) os.FileMode { - m := os.FileMode(mode & 0777) + m := os.FileMode(mode & 0o777) switch mode & S_IFMT { case S_IFBLK: m |= os.ModeDevice diff --git a/pkg/cpio/fs_plan9.go b/pkg/cpio/fs_plan9.go index 9c3e551e0d..7915edbd0d 100644 --- a/pkg/cpio/fs_plan9.go +++ b/pkg/cpio/fs_plan9.go @@ -80,7 +80,7 @@ func CreateFileInRoot(f Record, rootDir string, forcePriv bool) error { // to create files in these directories, we have to make them at least // mode 755. if _, err := os.Stat(dir); os.IsNotExist(err) && len(dir) > 0 { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("CreateFileInRoot %q: %v", f.Name, err) } } diff --git a/pkg/cpio/fs_unix.go b/pkg/cpio/fs_unix.go index a8d4282d5c..8494c45031 100644 --- a/pkg/cpio/fs_unix.go +++ b/pkg/cpio/fs_unix.go @@ -116,7 +116,7 @@ func CreateFileInRoot(f Record, rootDir string, forcePriv bool) error { // to create files in these directories, we have to make them at least // mode 755. if _, err := os.Stat(dir); os.IsNotExist(err) && len(dir) > 0 { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { return fmt.Errorf("CreateFileInRoot %q: %v", f.Name, err) } } diff --git a/pkg/cpio/newc.go b/pkg/cpio/newc.go index 94c76fa95d..3d9a28ec78 100644 --- a/pkg/cpio/newc.go +++ b/pkg/cpio/newc.go @@ -21,10 +21,8 @@ const ( magicLen = 6 ) -var ( - // Newc is the newc CPIO record format. - Newc RecordFormat = newc{magic: newcMagic} -) +// Newc is the newc CPIO record format. +var Newc RecordFormat = newc{magic: newcMagic} type header struct { Ino uint32 diff --git a/pkg/cpio/newc_test.go b/pkg/cpio/newc_test.go index fb95c3154e..28874e8f48 100644 --- a/pkg/cpio/newc_test.go +++ b/pkg/cpio/newc_test.go @@ -555,20 +555,21 @@ var ( // testReproducible verifies that we can produce reproducible cpio archives for newc format. func TestReproducible(t *testing.T) { contents := []byte("LANAAAAAAAAAA") - rec := []Record{StaticRecord(contents, Info{ - Ino: 1, - Mode: syscall.S_IFREG | 2, - UID: 3, - GID: 4, - NLink: 5, - MTime: 6, - FileSize: 7, - Major: 8, - Minor: 9, - Rmajor: 10, - Rminor: 11, - Name: "foobar", - }), + rec := []Record{ + StaticRecord(contents, Info{ + Ino: 1, + Mode: syscall.S_IFREG | 2, + UID: 3, + GID: 4, + NLink: 5, + MTime: 6, + FileSize: 7, + Major: 8, + Minor: 9, + Rmajor: 10, + Rminor: 11, + Name: "foobar", + }), } // First test that it fails unless we make it reproducible diff --git a/pkg/cpio/sysinfo_plan9.go b/pkg/cpio/sysinfo_plan9.go index 33dd021a56..303e65ec01 100644 --- a/pkg/cpio/sysinfo_plan9.go +++ b/pkg/cpio/sysinfo_plan9.go @@ -9,7 +9,7 @@ import "syscall" func sysInfo(n string, sys *syscall.Dir) Info { // Similar to how the standard library converts Plan 9 Dir to os.FileInfo: // https://github.com/golang/go/blob/go1.16beta1/src/os/stat_plan9.go#L14 - mode := sys.Mode & 0777 + mode := sys.Mode & 0o777 if sys.Mode&syscall.DMDIR != 0 { mode |= modeDir } else { diff --git a/pkg/cpio/utils.go b/pkg/cpio/utils.go index 7c64ba2e6d..12234f41a3 100644 --- a/pkg/cpio/utils.go +++ b/pkg/cpio/utils.go @@ -43,7 +43,7 @@ func Symlink(name string, target string) Record { ReaderAt: strings.NewReader(target), Info: Info{ FileSize: uint64(len(target)), - Mode: S_IFLNK | 0777, + Mode: S_IFLNK | 0o777, Name: name, }, } diff --git a/pkg/crypto/ed25519.go b/pkg/crypto/ed25519.go index ef28c4bc7e..006aded097 100644 --- a/pkg/crypto/ed25519.go +++ b/pkg/crypto/ed25519.go @@ -23,9 +23,9 @@ var ( // PEMCipher is the PEM encryption algorithm PEMCipher = x509.PEMCipherAES256 // PubKeyFilePermissions are the public key file perms - PubKeyFilePermissions os.FileMode = 0644 + PubKeyFilePermissions os.FileMode = 0o644 // PrivKeyFilePermissions are the private key file perms - PrivKeyFilePermissions os.FileMode = 0600 + PrivKeyFilePermissions os.FileMode = 0o600 ) // LoadPublicKeyFromFile loads PEM formatted ED25519 public key from file. @@ -88,12 +88,12 @@ func GeneratED25519Key(password []byte, privateKeyFilePath string, publicKeyFile return err } - var privBlock = &pem.Block{ + privBlock := &pem.Block{ Type: "PRIVATE KEY", Bytes: privKey, } - var pubBlock = &pem.Block{ + pubBlock := &pem.Block{ Type: "PUBLIC KEY", Bytes: pubKey, } diff --git a/pkg/crypto/ed25519_test.go b/pkg/crypto/ed25519_test.go index 799800bf50..772a2b6d75 100644 --- a/pkg/crypto/ed25519_test.go +++ b/pkg/crypto/ed25519_test.go @@ -29,10 +29,8 @@ const ( signatureBadFile string = "tests/verify_rsa_pkcs15_sha256.signature2" ) -var ( - // password is a PEM encrypted passphrase - password = []byte{'k', 'e', 'i', 'n', 's'} -) +// password is a PEM encrypted passphrase +var password = []byte{'k', 'e', 'i', 'n', 's'} func TestLoadDERPublicKey(t *testing.T) { _, err := LoadPublicKeyFromFile(publicKeyDERFile) diff --git a/pkg/curl/schemes.go b/pkg/curl/schemes.go index fad5e4a673..a743208c6c 100644 --- a/pkg/curl/schemes.go +++ b/pkg/curl/schemes.go @@ -26,12 +26,10 @@ import ( "pack.ag/tftp" ) -var ( - // ErrNoSuchScheme is returned by Schemes.Fetch and - // Schemes.LazyFetch if there is no registered FileScheme - // implementation for the given URL scheme. - ErrNoSuchScheme = errors.New("no such scheme") -) +// ErrNoSuchScheme is returned by Schemes.Fetch and +// Schemes.LazyFetch if there is no registered FileScheme +// implementation for the given URL scheme. +var ErrNoSuchScheme = errors.New("no such scheme") // File is a reference to a file fetched through this library. type File interface { @@ -63,7 +61,6 @@ type FileScheme interface { // It may do so by fetching `u` and placing it in a buffer, or by // returning an io.ReaderAt that fetchs the file. Fetch(ctx context.Context, u *url.URL) (io.ReaderAt, error) - FetchWithoutCache(ctx context.Context, u *url.URL) (io.Reader, error) } diff --git a/pkg/curl/schemes_test.go b/pkg/curl/schemes_test.go index fdcc313b6c..0cc2343c41 100644 --- a/pkg/curl/schemes_test.go +++ b/pkg/curl/schemes_test.go @@ -219,7 +219,6 @@ func TestFetchWithoutCache(t *testing.T) { } }) } - } func TestFetch(t *testing.T) { diff --git a/pkg/dhclient/dhclient.go b/pkg/dhclient/dhclient.go index 3cf763a166..4fb8f146dc 100644 --- a/pkg/dhclient/dhclient.go +++ b/pkg/dhclient/dhclient.go @@ -87,7 +87,7 @@ func WriteDNSSettings(ns []net.IP, sl []string, domain string) error { rc.WriteString(strings.Join(sl, " ")) rc.WriteString("\n") } - return ioutil.WriteFile("/etc/resolv.conf", rc.Bytes(), 0644) + return ioutil.WriteFile("/etc/resolv.conf", rc.Bytes(), 0o644) } // Lease is a network configuration obtained by DHCP. diff --git a/pkg/fb/fb.go b/pkg/fb/fb.go index 52e99808d2..17067c3ded 100644 --- a/pkg/fb/fb.go +++ b/pkg/fb/fb.go @@ -42,7 +42,6 @@ func DrawOnBufAt( // height in pixels, the stride, and the bytes per pixel func FbInit() (int, int, int, int, error) { fbo, err := framebuffer.Init(fbdev) - if err != nil { return 0, 0, 0, 0, err } @@ -62,7 +61,7 @@ func DrawImageAt(img image.Image, posx int, posy int) error { } buf := make([]byte, width*height*bpp) DrawOnBufAt(buf, img, posx, posy, stride, bpp) - err = ioutil.WriteFile(fbdev, buf, 0600) + err = ioutil.WriteFile(fbdev, buf, 0o600) if err != nil { return fmt.Errorf("Error writing to framebuffer: %v", err) } @@ -103,7 +102,7 @@ func DrawScaledImageAt(img image.Image, posx int, posy int, factor int) error { } buf := make([]byte, width*height*bpp) DrawScaledOnBufAt(buf, img, posx, posy, factor, stride, bpp) - err = ioutil.WriteFile(fbdev, buf, 0600) + err = ioutil.WriteFile(fbdev, buf, 0o600) if err != nil { return fmt.Errorf("Error writing to framebuffer: %v", err) } diff --git a/pkg/find/find_test.go b/pkg/find/find_test.go index c437e4628a..3086d2b541 100644 --- a/pkg/find/find_test.go +++ b/pkg/find/find_test.go @@ -22,7 +22,7 @@ func TestSimple(t *testing.T) { names []string } - var testCases = []tests{ + testCases := []tests{ { name: "basic find", opts: nil, @@ -53,7 +53,7 @@ func TestSimple(t *testing.T) { }, { name: "file by mode", - opts: WithModeMatch(0444, os.ModePerm), + opts: WithModeMatch(0o444, os.ModePerm), names: []string{"/root/xyz/0777"}, }, { @@ -70,13 +70,13 @@ func TestSimple(t *testing.T) { // Make sure files are actually created with the permissions we ask for. syscall.Umask(0) - if err := os.MkdirAll(filepath.Join(d, "root/xyz"), 0775); err != nil { + if err := os.MkdirAll(filepath.Join(d, "root/xyz"), 0o775); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(d, "root/xyz/file"), nil, 0664); err != nil { + if err := ioutil.WriteFile(filepath.Join(d, "root/xyz/file"), nil, 0o664); err != nil { t.Fatal(err) } - if err := ioutil.WriteFile(filepath.Join(d, "root/xyz/0777"), nil, 0444); err != nil { + if err := ioutil.WriteFile(filepath.Join(d, "root/xyz/0777"), nil, 0o444); err != nil { t.Fatal(err) } diff --git a/pkg/flash/spimock/spimock.go b/pkg/flash/spimock/spimock.go index 4057f31e66..b856635626 100644 --- a/pkg/flash/spimock/spimock.go +++ b/pkg/flash/spimock/spimock.go @@ -102,7 +102,7 @@ func New() *MockSPI { // does not exist, it will be created. Ideally, the file's size should match // FlashSize. func NewFromFile(filename string) (*MockSPI, error) { - f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644) + f, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o644) if err != nil { return nil, err } diff --git a/pkg/forth/forth.go b/pkg/forth/forth.go index c47dd8ce2b..a6b07bcc2d 100644 --- a/pkg/forth/forth.go +++ b/pkg/forth/forth.go @@ -307,7 +307,7 @@ func newword(f Forth) { if f.Length() < int(n) { panic(fmt.Sprintf("newword %s: stack is %d elements, need %d", s, f.Length(), n)) } - var c = make([]Cell, n) + c := make([]Cell, n) for i := n; i > 0; i-- { c[i-1] = f.Pop() } diff --git a/pkg/forth/forth_test.go b/pkg/forth/forth_test.go index e6ab82cc85..a2bc2bf4bf 100644 --- a/pkg/forth/forth_test.go +++ b/pkg/forth/forth_test.go @@ -42,7 +42,6 @@ var forthTests = []forthTest{ } func TestForth(t *testing.T) { - forthTests[0].res, _ = os.Hostname() f := New() if f.Length() != 0 { @@ -89,7 +88,6 @@ func TestForth(t *testing.T) { t.Errorf("Test: %v: stack is %v and should be empty", tt, f.Empty()) } } - } func TestBadPop(t *testing.T) { diff --git a/pkg/gpio/gpio_linux_test.go b/pkg/gpio/gpio_linux_test.go index 2ab6678145..bc3b5f73e2 100644 --- a/pkg/gpio/gpio_linux_test.go +++ b/pkg/gpio/gpio_linux_test.go @@ -65,5 +65,4 @@ func TestGetPinID(t *testing.T) { if _, err := GetPinID("gpio-mockup-A", 12); err == nil { t.Errorf("GetPinID(gpio-mockup-A, 12) = nil, but wanted error") } - } diff --git a/pkg/gzip/options_test.go b/pkg/gzip/options_test.go index b9aba150e8..a742f9818a 100644 --- a/pkg/gzip/options_test.go +++ b/pkg/gzip/options_test.go @@ -62,6 +62,7 @@ func TestOptions_ParseArgs(t *testing.T) { }) } } + func TestOptions_validate(t *testing.T) { type fields struct { Blocksize int diff --git a/pkg/ipmi/ipmi.go b/pkg/ipmi/ipmi.go index 3f72cfca8d..198342f8d8 100644 --- a/pkg/ipmi/ipmi.go +++ b/pkg/ipmi/ipmi.go @@ -55,7 +55,7 @@ const ( // SEL device Commands BMC_GET_SEL_INFO Command = 0x40 - //LAN Device Commands + // LAN Device Commands BMC_GET_LAN_CONFIG Command = 0x02 IPM_WATCHDOG_NO_ACTION = 0x00 @@ -379,7 +379,6 @@ func (e *Event) marshall() ([]byte, error) { // LogSystemEvent adds an SEL (System Event Log) entry. func (i *IPMI) LogSystemEvent(e *Event) error { data, err := e.marshall() - if err != nil { return err } @@ -446,7 +445,6 @@ func (i *IPMI) SetSystemFWVersion(version string) error { func (i *IPMI) GetDeviceID() (*DevID, error) { data, err := i.SendRecv(_IPMI_NETFN_APP, BMC_GET_DEVICE_ID, nil) - if err != nil { return nil, err } @@ -481,7 +479,6 @@ func (i *IPMI) EnableSEL() (bool, error) { } data, err := i.getGlobalEnables() - if err != nil { return false, err } diff --git a/pkg/ipmi/ocp/ocp.go b/pkg/ipmi/ocp/ocp.go index f7690ad4d0..982cd03ab5 100644 --- a/pkg/ipmi/ocp/ocp.go +++ b/pkg/ipmi/ocp/ocp.go @@ -85,7 +85,7 @@ func SendOemIpmiProcessorInfo(i *ipmi.IPMI, info []ProcessorInfo) error { func SendOemIpmiDimmInfo(i *ipmi.IPMI, info []DimmInfo) error { for index := 0; index < len(info); index++ { for param := 1; param <= 6; param++ { - //If DIMM is not present, only send the information of DIMM location + // If DIMM is not present, only send the information of DIMM location if info[index].DIMMPresent != 0x01 && param >= 2 { continue } diff --git a/pkg/kexecbin/kexecbin.go b/pkg/kexecbin/kexecbin.go index fd748e0a6a..20db3827ad 100644 --- a/pkg/kexecbin/kexecbin.go +++ b/pkg/kexecbin/kexecbin.go @@ -16,11 +16,9 @@ import ( "os/exec" ) -var ( - // DeviceTreePaths is the virtual fs path for accessing device-tree - // through Linux - DeviceTreePaths = []string{"/sys/firmware/fdt", "/proc/device-tree"} -) +// DeviceTreePaths is the virtual fs path for accessing device-tree +// through Linux +var DeviceTreePaths = []string{"/sys/firmware/fdt", "/proc/device-tree"} // KexecBin uses kexec-tools binary and runtime architecture detection // to execute abritary files. diff --git a/pkg/ldd/ldd_darwin_test.go b/pkg/ldd/ldd_darwin_test.go index 5411f3f9b1..f2bf7cebdb 100644 --- a/pkg/ldd/ldd_darwin_test.go +++ b/pkg/ldd/ldd_darwin_test.go @@ -15,7 +15,7 @@ import ( // almost nothing else we can assume exists, e.g. /lib/libc.so // is a different name on almost every *ix* system. func lddOne(name string) ([]string, error) { - var libMap = make(map[string]bool) + libMap := make(map[string]bool) n, err := Ldd([]string{name}) if err != nil { return nil, fmt.Errorf("Ldd on %v: want nil, got %v", name, err) diff --git a/pkg/ldd/ldd_test.go b/pkg/ldd/ldd_test.go index 17c36f0ca2..14fec99216 100644 --- a/pkg/ldd/ldd_test.go +++ b/pkg/ldd/ldd_test.go @@ -33,7 +33,7 @@ func TestLdd(t *testing.T) { // almost nothing else we can assume exists, e.g. /lib/libc.so // is a different name on almost every *ix* system. func lddOne(name string) ([]string, error) { - var libMap = make(map[string]bool) + libMap := make(map[string]bool) n, err := Ldd([]string{name}) if err != nil { return nil, fmt.Errorf("Ldd on %v: want nil, got %v", name, err) diff --git a/pkg/libinit/proc_plan9.go b/pkg/libinit/proc_plan9.go index bdebaae9ec..a1a66708e2 100644 --- a/pkg/libinit/proc_plan9.go +++ b/pkg/libinit/proc_plan9.go @@ -15,9 +15,7 @@ import ( func WaitOrphans() uint { var numReaped uint for { - var ( - w syscall.Waitmsg - ) + var w syscall.Waitmsg err := syscall.Await(&w) if err != nil { break diff --git a/pkg/libinit/root_linux.go b/pkg/libinit/root_linux.go index b8fb90aa1e..d7c776f741 100644 --- a/pkg/libinit/root_linux.go +++ b/pkg/libinit/root_linux.go @@ -101,43 +101,43 @@ func (c cpdir) String() string { var ( // These have to be created / mounted first, so that the logging works correctly. preNamespace = []creator{ - dir{Name: "/dev", Mode: 0777}, + dir{Name: "/dev", Mode: 0o777}, // Kernel must be compiled with CONFIG_DEVTMPFS. mount{Source: "devtmpfs", Target: "/dev", FSType: "devtmpfs"}, } namespace = []creator{ - dir{Name: "/buildbin", Mode: 0777}, - dir{Name: "/ubin", Mode: 0777}, - dir{Name: "/tmp", Mode: 0777}, - dir{Name: "/env", Mode: 0777}, - dir{Name: "/tcz", Mode: 0777}, - dir{Name: "/lib", Mode: 0777}, - dir{Name: "/usr/lib", Mode: 0777}, - dir{Name: "/var/log", Mode: 0777}, - dir{Name: "/go/pkg/linux_amd64", Mode: 0777}, - - dir{Name: "/etc", Mode: 0777}, - - dir{Name: "/proc", Mode: 0555}, + dir{Name: "/buildbin", Mode: 0o777}, + dir{Name: "/ubin", Mode: 0o777}, + dir{Name: "/tmp", Mode: 0o777}, + dir{Name: "/env", Mode: 0o777}, + dir{Name: "/tcz", Mode: 0o777}, + dir{Name: "/lib", Mode: 0o777}, + dir{Name: "/usr/lib", Mode: 0o777}, + dir{Name: "/var/log", Mode: 0o777}, + dir{Name: "/go/pkg/linux_amd64", Mode: 0o777}, + + dir{Name: "/etc", Mode: 0o777}, + + dir{Name: "/proc", Mode: 0o555}, mount{Source: "proc", Target: "/proc", FSType: "proc"}, mount{Source: "tmpfs", Target: "/tmp", FSType: "tmpfs"}, - dev{Name: "/dev/tty", Mode: syscall.S_IFCHR | 0666, Dev: 0x0500}, - dev{Name: "/dev/urandom", Mode: syscall.S_IFCHR | 0444, Dev: 0x0109}, - dev{Name: "/dev/port", Mode: syscall.S_IFCHR | 0640, Dev: 0x0104}, + dev{Name: "/dev/tty", Mode: syscall.S_IFCHR | 0o666, Dev: 0x0500}, + dev{Name: "/dev/urandom", Mode: syscall.S_IFCHR | 0o444, Dev: 0x0109}, + dev{Name: "/dev/port", Mode: syscall.S_IFCHR | 0o640, Dev: 0x0104}, - dir{Name: "/dev/pts", Mode: 0777}, + dir{Name: "/dev/pts", Mode: 0o777}, mount{Source: "devpts", Target: "/dev/pts", FSType: "devpts", Opts: "newinstance,ptmxmode=666,gid=5,mode=620"}, // Note: if we mount /dev/pts with "newinstance", we *must* make "/dev/ptmx" a symlink to "/dev/pts/ptmx" symlink{NewPath: "/dev/ptmx", Target: "/dev/pts/ptmx"}, // Note: shm is required at least for Chrome. If you don't mount // it chrome throws a bogus "out of memory" error, not the more // useful "I can't open /dev/shm/whatever". SAD! - dir{Name: "/dev/shm", Mode: 0777}, + dir{Name: "/dev/shm", Mode: 0o777}, mount{Source: "tmpfs", Target: "/dev/shm", FSType: "tmpfs"}, - dir{Name: "/sys", Mode: 0555}, + dir{Name: "/sys", Mode: 0o555}, mount{Source: "sysfs", Target: "/sys", FSType: "sysfs"}, mount{Source: "securityfs", Target: "/sys/kernel/security", FSType: "securityfs"}, @@ -149,16 +149,16 @@ var ( // LinuxBoot/NERF. Some users use u-root for container stuff. cgroupsnamespace = []creator{ mount{Source: "cgroup", Target: "/sys/fs/cgroup", FSType: "tmpfs"}, - dir{Name: "/sys/fs/cgroup/memory", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/freezer", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/devices", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/cpu,cpuacct", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/blkio", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/cpuset", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/pids", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/net_cls,net_prio", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/hugetlb", Mode: 0555}, - dir{Name: "/sys/fs/cgroup/perf_event", Mode: 0555}, + dir{Name: "/sys/fs/cgroup/memory", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/freezer", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/devices", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/cpu,cpuacct", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/blkio", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/cpuset", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/pids", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/net_cls,net_prio", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/hugetlb", Mode: 0o555}, + dir{Name: "/sys/fs/cgroup/perf_event", Mode: 0o555}, symlink{NewPath: "/sys/fs/cgroup/cpu", Target: "/sys/fs/cgroup/cpu,cpuacct"}, symlink{NewPath: "/sys/fs/cgroup/cpuacct", Target: "/sys/fs/cgroup/cpu,cpuacct"}, symlink{NewPath: "/sys/fs/cgroup/net_cls", Target: "/sys/fs/cgroup/net_cls,net_prio"}, @@ -233,12 +233,10 @@ func CreateRootfs() { } } -var ( - excludedMods = map[string]bool{ - "idpf": true, - "idpf_imc": true, - } -) +var excludedMods = map[string]bool{ + "idpf": true, + "idpf_imc": true, +} // InstallAllModules installs kernel modules (.ko files) from /lib/modules. // Useful for modules that need to be loaded for boot (ie a network diff --git a/pkg/lockfile/lockfile.go b/pkg/lockfile/lockfile.go index 673e806307..55651156b1 100644 --- a/pkg/lockfile/lockfile.go +++ b/pkg/lockfile/lockfile.go @@ -57,9 +57,7 @@ var ( ErrProcessDead = errors.New("lockfile points to invalid PID") ) -var ( - errUnlocked = errors.New("file is unlocked") -) +var errUnlocked = errors.New("file is unlocked") // Lockfile is a process-based file lock. type Lockfile struct { diff --git a/pkg/ls/fileinfo_plan9.go b/pkg/ls/fileinfo_plan9.go index e37709e56a..e298dbba31 100644 --- a/pkg/ls/fileinfo_plan9.go +++ b/pkg/ls/fileinfo_plan9.go @@ -84,7 +84,6 @@ type LongStringer struct { // FileString implements Stringer.FileString. func (ls LongStringer) FileString(fi FileInfo) string { - var size string if ls.Human { size = humanize.Bytes(uint64(fi.Size)) diff --git a/pkg/mei/mei_linux.go b/pkg/mei/mei_linux.go index 279a115e98..4ab9bef1ec 100644 --- a/pkg/mei/mei_linux.go +++ b/pkg/mei/mei_linux.go @@ -63,7 +63,7 @@ type MEI struct { // See `HECIGuids` in this package. func OpenMEI(meiPath string, guid ClientGUID) (*MEI, error) { var m MEI - fd, err := syscall.Open(meiPath, os.O_RDWR, 0755) + fd, err := syscall.Open(meiPath, os.O_RDWR, 0o755) if err != nil { return nil, err } diff --git a/pkg/mei/mkhiclient_linux.go b/pkg/mei/mkhiclient_linux.go index 4f2947d5bf..e3fc3ba53e 100644 --- a/pkg/mei/mkhiclient_linux.go +++ b/pkg/mei/mkhiclient_linux.go @@ -220,7 +220,6 @@ func hmrfpoEnableResponseFromBytes(b []byte) (*hmrfpoEnableResponse, error) { // see cse_hmrfpo_enable at // https://github.com/coreboot/coreboot/blob/b8b8ec832360ada5a313f10938bb6cfc310a11eb/src/soc/intel/common/block/include/intelblocks/cse.h#L64 func (m *MKHIClient) EnableHMRFPO() error { - var hdr mkhiHdr hdr.SetGroupID(mkhiGroupIDHMRFPO) hdr.SetCommand(mkhiHMRFPOEnable) diff --git a/pkg/memio/mmap_linux.go b/pkg/memio/mmap_linux.go index 52cbbc4b30..f94339991a 100644 --- a/pkg/memio/mmap_linux.go +++ b/pkg/memio/mmap_linux.go @@ -11,9 +11,7 @@ import ( "unsafe" ) -var ( - pageSize = int64(syscall.Getpagesize()) -) +var pageSize = int64(syscall.Getpagesize()) // mmap aligns the address and maps multiple pages when needed. func mmap(f *os.File, addr int64, size int64, prot int) (mem []byte, offset int64, err error) { diff --git a/pkg/mount/gpt/gpt.go b/pkg/mount/gpt/gpt.go index f52838d596..74cbbcfd41 100644 --- a/pkg/mount/gpt/gpt.go +++ b/pkg/mount/gpt/gpt.go @@ -37,34 +37,38 @@ type GUID struct { B [8]byte } -type MBR [BlockSize]byte -type Header struct { - Signature uint64 - Revision uint32 // (for GPT version 1.0 (through at least UEFI version 2.7 (May 2017)), the value is 00h 00h 01h 00h) - HeaderSize uint32 // size in little endian (in bytes, usually 5Ch 00h 00h 00h or 92 bytes) - CRC uint32 // CRC32/zlib of header (offset +0 up to header size) in little endian, with this field zeroed during calculation - Reserved uint32 // ; must be zero - CurrentLBA uint64 // (location of this header copy) - BackupLBA uint64 // (location of the other header copy) - FirstLBA uint64 // usable LBA for partitions (primary partition table last LBA + 1) - LastLBA uint64 // usable LBA (secondary partition table first LBA - 1) - DiskGUID GUID // (also referred as UUID on UNIXes) - PartStart uint64 // LBA of array of partition entries (always 2 in primary copy) - NPart uint32 // Number of partition entries in array - PartSize uint32 // Size of a single partition entry (usually 80h or 128) - PartCRC uint32 // CRC32/zlib of partition array in little endian -} +type ( + MBR [BlockSize]byte + Header struct { + Signature uint64 + Revision uint32 // (for GPT version 1.0 (through at least UEFI version 2.7 (May 2017)), the value is 00h 00h 01h 00h) + HeaderSize uint32 // size in little endian (in bytes, usually 5Ch 00h 00h 00h or 92 bytes) + CRC uint32 // CRC32/zlib of header (offset +0 up to header size) in little endian, with this field zeroed during calculation + Reserved uint32 // ; must be zero + CurrentLBA uint64 // (location of this header copy) + BackupLBA uint64 // (location of the other header copy) + FirstLBA uint64 // usable LBA for partitions (primary partition table last LBA + 1) + LastLBA uint64 // usable LBA (secondary partition table first LBA - 1) + DiskGUID GUID // (also referred as UUID on UNIXes) + PartStart uint64 // LBA of array of partition entries (always 2 in primary copy) + NPart uint32 // Number of partition entries in array + PartSize uint32 // Size of a single partition entry (usually 80h or 128) + PartCRC uint32 // CRC32/zlib of partition array in little endian + } +) -type PartAttr uint64 -type PartName [72]byte -type Part struct { - PartGUID GUID // Partition type GUID - UniqueGUID GUID // Unique partition GUID - FirstLBA uint64 // LBA (little endian) - LastLBA uint64 // LBA (inclusive, usually odd) - Attribute PartAttr // flags (e.g. bit 60 denotes read-only) - Name PartName // Partition name (36 UTF-16LE code units) -} +type ( + PartAttr uint64 + PartName [72]byte + Part struct { + PartGUID GUID // Partition type GUID + UniqueGUID GUID // Unique partition GUID + FirstLBA uint64 // LBA (little endian) + LastLBA uint64 // LBA (inclusive, usually odd) + Attribute PartAttr // flags (e.g. bit 60 denotes read-only) + Name PartName // Partition name (36 UTF-16LE code units) + } +) type GPT struct { Header @@ -112,7 +116,6 @@ func (p *PartitionTable) String() string { log.Fatalf("Can't marshal %v", *p) } return string(b) - } func errAppend(err error, s string, a ...interface{}) error { @@ -209,7 +212,7 @@ func Table(r io.ReaderAt, off int64) (*GPT, error) { if off != BlockSize { which = "Backup" } - var g = &GPT{} + g := &GPT{} if err := binary.Read(io.NewSectionReader(r, off, HeaderSize), binary.LittleEndian, &g.Header); err != nil { return nil, err } @@ -261,7 +264,6 @@ func Table(r io.ReaderAt, off int64) (*GPT, error) { } return g, nil - } // Write writes the MBR and primary and backup GPTs to w. @@ -282,7 +284,7 @@ func Write(w io.WriterAt, p *PartitionTable) error { // Write writes the GPT to w. It generates the partition and header CRC before writing. func writeGPT(w io.WriterAt, g *GPT) error { // The maximum extent is NPart * PartSize - var h = make([]byte, uint64(g.NPart*g.PartSize)) + h := make([]byte, uint64(g.NPart*g.PartSize)) s := int64(g.PartSize) for i := int64(0); i < int64(g.NPart); i++ { var b bytes.Buffer @@ -321,8 +323,8 @@ func writeGPT(w io.WriterAt, g *GPT) error { // one or more headers AND an error. Sorry. Experience with some real USB sticks // is showing that we need to return data even if there are some things wrong. func New(r io.ReaderAt) (*PartitionTable, error) { - var p = &PartitionTable{} - var mbr = &MBR{} + p := &PartitionTable{} + mbr := &MBR{} n, err := r.ReadAt(mbr[:], 0) if n != BlockSize || err != nil { return p, err diff --git a/pkg/mount/gpt/gpt_test.go b/pkg/mount/gpt/gpt_test.go index a474aefc0b..a1c7c27520 100644 --- a/pkg/mount/gpt/gpt_test.go +++ b/pkg/mount/gpt/gpt_test.go @@ -47,7 +47,7 @@ func InstallGPT() { } func TestGPTTable(t *testing.T) { - var tests = []struct { + tests := []struct { mangle int msg string }{ @@ -64,7 +64,6 @@ func TestGPTTable(t *testing.T) { InstallGPT() if test.mangle > -1 { disk[BlockSize+test.mangle] = 0xff - } r := bytes.NewReader(disk) g, err := Table(r, BlockSize) @@ -88,7 +87,6 @@ func TestGPTTable(t *testing.T) { continue } } - } // TestGPTTtables tests whether we can match the primary and backup @@ -97,7 +95,7 @@ func TestGPTTable(t *testing.T) { // This test verifies that they match and that therefore we // are able to read the backup table and test that it is ok. func TestGPTTables(t *testing.T) { - var tests = []struct { + tests := []struct { mangle int what string }{ @@ -159,7 +157,6 @@ func TestEqualHeader(t *testing.T) { if err.Error() != equalHeaderError { t.Fatalf("TestEqualHeader: got %v, want %v", err.Error(), equalHeaderError) } - } func TestEqualParts(t *testing.T) { @@ -191,7 +188,6 @@ func TestEqualParts(t *testing.T) { if err = EqualParts(p.Primary, p.Backup); err == nil { t.Errorf("TestEqualParts: Checking number of parts: got nil, want 'Primary Number of partitions (127) differs from Backup (128)'") } - } type iodisk []byte @@ -208,7 +204,7 @@ func TestWrite(t *testing.T) { if err != nil { t.Fatalf("Reading partitions: got %v, want nil", err) } - var targ = make(iodisk, len(disk)) + targ := make(iodisk, len(disk)) if err := Write(&targ, p); err != nil { t.Fatalf("Writing: got %v, want nil", err) diff --git a/pkg/mount/loop/losetup_linux.go b/pkg/mount/loop/losetup_linux.go index 9c6392ad84..a7a742774e 100644 --- a/pkg/mount/loop/losetup_linux.go +++ b/pkg/mount/loop/losetup_linux.go @@ -32,7 +32,7 @@ const ( // FindDevice finds an unused loop device and returns its /dev/loopN path. func FindDevice() (string, error) { - cfd, err := os.OpenFile("/dev/loop-control", os.O_RDWR, 0644) + cfd, err := os.OpenFile("/dev/loop-control", os.O_RDWR, 0o644) if err != nil { return "", err } @@ -76,17 +76,17 @@ func SetFD(lfd, ffd int) error { // SetFile associates loop device "devicename" with regular file "filename" func SetFile(devicename, filename string) error { mode := os.O_RDWR - file, err := os.OpenFile(filename, mode, 0644) + file, err := os.OpenFile(filename, mode, 0o644) if err != nil { mode = os.O_RDONLY - file, err = os.OpenFile(filename, mode, 0644) + file, err = os.OpenFile(filename, mode, 0o644) if err != nil { return err } } defer file.Close() - device, err := os.OpenFile(devicename, mode, 0644) + device, err := os.OpenFile(devicename, mode, 0o644) if err != nil { return err } diff --git a/pkg/mount/loop/losetup_linux_test.go b/pkg/mount/loop/losetup_linux_test.go index cdeeb7ed16..2702981e07 100644 --- a/pkg/mount/loop/losetup_linux_test.go +++ b/pkg/mount/loop/losetup_linux_test.go @@ -61,7 +61,7 @@ func TestSetFile(t *testing.T) { t.Fatal(err) } - if err := os.MkdirAll("/tmp/disk", 0755); err != nil && !os.IsExist(err) { + if err := os.MkdirAll("/tmp/disk", 0o755); err != nil && !os.IsExist(err) { t.Fatalf("Could not create /tmp/disk: %v", err) } @@ -71,7 +71,7 @@ func TestSetFile(t *testing.T) { } defer mp.Unmount(0) //nolint:errcheck - if err := ioutil.WriteFile("/tmp/disk/foobar", []byte("Are you feeling it now Mr Krabs"), 0755); err != nil { + if err := ioutil.WriteFile("/tmp/disk/foobar", []byte("Are you feeling it now Mr Krabs"), 0o755); err != nil { t.Fatal(err) } } diff --git a/pkg/mount/magic.go b/pkg/mount/magic.go index 7cb4e64496..47272d711e 100644 --- a/pkg/mount/magic.go +++ b/pkg/mount/magic.go @@ -57,7 +57,7 @@ var ( EFIVARFS = []byte{0xde, 0x5e, 0x81, 0xe4} EFS = []byte{0x41, 0x4A, 0x53} // EXFAT seems to be a samsung file system. - //EXFAT = []byte{0x53, 0xef} + // EXFAT = []byte{0x53, 0xef} F2FS = []byte{0xF2, 0xF5, 0x20, 0x10} FUSE = []byte{0x65, 0x73, 0x55, 0x46} FUTEXFS = []byte{0xBA, 0xD1, 0xDE, 0xA} @@ -173,10 +173,10 @@ var unknownMagics = []magic{ // FindMagics finds all the magics matching a magic number. func FindMagics(blk []byte) []magic { - var b = bytes.NewReader(blk) - var matches = []magic{} + b := bytes.NewReader(blk) + matches := []magic{} for _, v := range magics { - var mag = make([]byte, len(v.magic)) + mag := make([]byte, len(v.magic)) if n, err := b.ReadAt(mag, v.off); err != nil || n < len(mag) { continue } @@ -201,7 +201,7 @@ func FSFromBlock(n string) (fs string, flags uintptr, err error) { return "", 0, err } defer f.Close() - var block = make([]byte, blocksize) + block := make([]byte, blocksize) if _, err := io.ReadAtLeast(f, block, len(block)); err != nil { return "", 0, fmt.Errorf("no suitable filesystem for %q: %v", n, err) } diff --git a/pkg/mount/mount_linux.go b/pkg/mount/mount_linux.go index 40607e6ffc..901a50606f 100644 --- a/pkg/mount/mount_linux.go +++ b/pkg/mount/mount_linux.go @@ -77,7 +77,7 @@ func (mp *MountPoint) Unmount(flags uintptr) error { // specific file system. func Mount(dev, path, fsType, data string, flags uintptr) (*MountPoint, error) { // Create the mount point if it doesn't already exist. - if err := os.MkdirAll(path, 0666); err != nil { + if err := os.MkdirAll(path, 0o666); err != nil { return nil, err } @@ -118,7 +118,7 @@ func TryMount(device, path, data string, flags uintptr) (*MountPoint, error) { // currently open files can continue to be used. When all references to files // from this file system are gone, the file system will actually be unmounted. func Unmount(path string, force, lazy bool) error { - var flags = unix.UMOUNT_NOFOLLOW + flags := unix.UMOUNT_NOFOLLOW if len(path) == 0 { return errors.New("path cannot be empty") } @@ -167,7 +167,7 @@ func (p *Pool) Mount(mounter Mounter, flags uintptr) (*MountPoint, error) { } path := filepath.Join(p.tmpDir, mounter.DevName()) - os.MkdirAll(path, 0777) + os.MkdirAll(path, 0o777) m, err := mounter.Mount(path, flags) if err != nil { // unix.Rmdir is used (instead of os.RemoveAll) because it diff --git a/pkg/mount/mtd/chips_test.go b/pkg/mount/mtd/chips_test.go index d560152648..9ee12c4bea 100644 --- a/pkg/mount/mtd/chips_test.go +++ b/pkg/mount/mtd/chips_test.go @@ -10,7 +10,7 @@ import ( ) func TestFindVendor(t *testing.T) { - var tests = []struct { + tests := []struct { id VendorID v VendorName e error @@ -35,7 +35,7 @@ func TestFindVendor(t *testing.T) { } func TestFindDevice(t *testing.T) { - var tests = []struct { + tests := []struct { v VendorName id ChipID d ChipName diff --git a/pkg/mount/mtd/dat.go b/pkg/mount/mtd/dat.go index 2741a712d7..f8874f3317 100644 --- a/pkg/mount/mtd/dat.go +++ b/pkg/mount/mtd/dat.go @@ -20,7 +20,7 @@ var vendors = []vendor{ {names: []VendorName{"PMC", "Chingis Technology Corporation"}, id: 0x7F9D}, {names: []VendorName{"NANTRONICS"}, id: 0x7F7F7F7F7F7FD5}, {names: []VendorName{"MACRONIX", "MX", "Generalplus"}, id: 0xC2}, - //ISSI Integrated Silicon Solutions, disjoint overlap with PMC + // ISSI Integrated Silicon Solutions, disjoint overlap with PMC {names: []VendorName{"ISSI"}, id: 0xD5}, {names: []VendorName{"INTEL"}, id: 0x89}, {names: []VendorName{"IMT", "Integrated Memory Technologies"}, id: 0x7F1F}, diff --git a/pkg/mount/scuzz/ata.go b/pkg/mount/scuzz/ata.go index c98227e1bf..5bb4fe881d 100644 --- a/pkg/mount/scuzz/ata.go +++ b/pkg/mount/scuzz/ata.go @@ -30,7 +30,7 @@ const ( // ataStatErr uint8 = (1 << 0) nolint:golint,unused // read uint8 = 0 nolint:golint,unused - //ataTo int32 = 1 + // ataTo int32 = 1 // ioPIO indicates we are doing programmed IO // ioPIO = 0 nolint:golint,unused @@ -99,7 +99,7 @@ func (b dataBlock) toWordBlock() (wordBlock, error) { // other than "Obsolete", "Retired", "Must be zero" or "Must be one". // We follow the practice of existing code of not naming them either. func (w wordBlock) mustLBA() error { - var check = []struct { + check := []struct { off int mask uint16 bit uint16 diff --git a/pkg/mount/scuzz/sg_linux.go b/pkg/mount/scuzz/sg_linux.go index 8b47445fe7..b9d171c692 100644 --- a/pkg/mount/scuzz/sg_linux.go +++ b/pkg/mount/scuzz/sg_linux.go @@ -209,7 +209,7 @@ func (p *packet) genCommandDataBlock() { } func (s *SGDisk) newPacket(cmd Cmd, direction direction, ataType uint8) *packet { - var p = &packet{} + p := &packet{} // These are invariant across all uses of SGDisk. p.interfaceID = 'S' p.cmdLen = uint8(len(p.command)) diff --git a/pkg/mount/scuzz/sg_linux_test.go b/pkg/mount/scuzz/sg_linux_test.go index 67bc98030a..95fbb014b6 100644 --- a/pkg/mount/scuzz/sg_linux_test.go +++ b/pkg/mount/scuzz/sg_linux_test.go @@ -109,41 +109,41 @@ func TestUnlock(t *testing.T) { // yields this header and data to ioctl(fd, SECURITY_UNLOCK, ...) // The 'want' data is derived from a modified version of hdparm (github.com/rminnich/hdparmm) // which prints the ioctl parameters as initialized go structs. - var ( - want = &packet{ - packetHeader: packetHeader{ - interfaceID: 'S', - direction: -2, - cmdLen: 16, - maxStatusBlockLen: 32, - iovCount: 0, - dataLen: 512, - data: 0, - cdb: 0, - sb: 0, - timeout: 15000, - flags: 0, - packID: 0, - usrPtr: 0, - status: 0, - maskedStatus: 0, - msgStatus: 0, - sbLen: 0, - hostStatus: 0, - driverStatus: 0, - resID: 0, - duration: 0, - info: 0, - }, - command: commandDataBlock{0x85, 0xb, 0x6, 00, 00, 00, 0x1, 00, 00, 00, 00, 00, 00, 0x40, 0xf2, 00}, - block: dataBlock{ - 0x00, 0x01, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, - 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, - 0x31, 0x32, - }, - } - //sb statusBlock - ) + + want := &packet{ + packetHeader: packetHeader{ + interfaceID: 'S', + direction: -2, + cmdLen: 16, + maxStatusBlockLen: 32, + iovCount: 0, + dataLen: 512, + data: 0, + cdb: 0, + sb: 0, + timeout: 15000, + flags: 0, + packID: 0, + usrPtr: 0, + status: 0, + maskedStatus: 0, + msgStatus: 0, + sbLen: 0, + hostStatus: 0, + driverStatus: 0, + resID: 0, + duration: 0, + info: 0, + }, + command: commandDataBlock{0x85, 0xb, 0x6, 0o0, 0o0, 0o0, 0x1, 0o0, 0o0, 0o0, 0o0, 0o0, 0o0, 0x40, 0xf2, 0o0}, + block: dataBlock{ + 0x00, 0x01, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, + 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, + 0x31, 0x32, + }, + } + // sb statusBlock + d := &SGDisk{dev: 0x40, Timeout: DefaultTimeout} p := d.unlockPacket("12345678901234567890123456789012", true) check(t, p, want) @@ -153,37 +153,37 @@ func TestIdentify(t *testing.T) { Debug = t.Logf // The 'want' data is derived from a modified version of hdparm (github.com/rminnich/hdparmm) // which prints the ioctl parameters as initialized go structs. - var ( - want = &packet{ - packetHeader: packetHeader{ - interfaceID: 'S', - direction: -3, - cmdLen: 16, - maxStatusBlockLen: 32, - iovCount: 0, - dataLen: 512, - data: 0, - cdb: 0, - sb: 0, - timeout: 15000, - flags: 0, - packID: 0, - usrPtr: 0, - status: 0, - maskedStatus: 0, - msgStatus: 0, - sbLen: 0, - hostStatus: 0, - driverStatus: 0, - resID: 0, - duration: 0, - info: 0, - }, - command: commandDataBlock{0x85, 0x08, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xec, 0x00}, - } - // TODO: check status block. Requires a qemu device that supports these operations. - //sb = statusBlock{0x70, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - ) + + want := &packet{ + packetHeader: packetHeader{ + interfaceID: 'S', + direction: -3, + cmdLen: 16, + maxStatusBlockLen: 32, + iovCount: 0, + dataLen: 512, + data: 0, + cdb: 0, + sb: 0, + timeout: 15000, + flags: 0, + packID: 0, + usrPtr: 0, + status: 0, + maskedStatus: 0, + msgStatus: 0, + sbLen: 0, + hostStatus: 0, + driverStatus: 0, + resID: 0, + duration: 0, + info: 0, + }, + command: commandDataBlock{0x85, 0x08, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xec, 0x00}, + } + // TODO: check status block. Requires a qemu device that supports these operations. + // sb = statusBlock{0x70, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} + p := (&SGDisk{dev: 0x40, Timeout: DefaultTimeout}).identifyPacket() check(t, p, want) } diff --git a/pkg/mount/switch_root_linux.go b/pkg/mount/switch_root_linux.go index 4ef85e2c3b..daf945e358 100644 --- a/pkg/mount/switch_root_linux.go +++ b/pkg/mount/switch_root_linux.go @@ -110,7 +110,7 @@ func MoveMount(oldPath string, newPath string) error { // If the target directories already exist, they must be empty. // This function skips missing mounts. func addSpecialMounts(newRoot string) error { - var mounts = []string{"/dev", "/proc", "/sys", "/run"} + mounts := []string{"/dev", "/proc", "/sys", "/run"} for _, mount := range mounts { path := filepath.Join(newRoot, mount) @@ -129,7 +129,7 @@ func addSpecialMounts(newRoot string) error { continue } // Make sure the target dir exists. - if err := os.MkdirAll(path, 0755); err != nil { + if err := os.MkdirAll(path, 0o755); err != nil { return err } if err := MoveMount(mount, path); err != nil { diff --git a/pkg/msr/msr_linux.go b/pkg/msr/msr_linux.go index c9ead6fcae..ab030d6e1e 100644 --- a/pkg/msr/msr_linux.go +++ b/pkg/msr/msr_linux.go @@ -71,7 +71,6 @@ func parseCPUs(s string) (CPUs, error) { } } return cpus, nil - } // AllCPUs searches for actual present CPUs instead of relying on the glob. @@ -141,7 +140,7 @@ func (c CPUs) String() string { } func (c CPUs) paths() []string { - var p = make([]string, len(c)) + p := make([]string, len(c)) for i, v := range c { p[i] = filepath.Join("/dev/cpu", strconv.Itoa(int(v)), "msr") @@ -152,7 +151,7 @@ func (c CPUs) paths() []string { // Read reads an MSR from a set of CPUs. func (m MSR) Read(c CPUs) ([]uint64, []error) { var hadErr bool - var regs = make([]uint64, len(c)) + regs := make([]uint64, len(c)) paths := c.paths() f, errs := openAll(paths, os.O_RDONLY) @@ -306,7 +305,6 @@ func Locked() error { return fmt.Errorf("%s: %v", vendor, allerrors) } return nil - } func openAll(m []string, o int) ([]*os.File, []error) { diff --git a/pkg/msr/msr_linux_test.go b/pkg/msr/msr_linux_test.go index 682849fb1f..16b5075b5e 100644 --- a/pkg/msr/msr_linux_test.go +++ b/pkg/msr/msr_linux_test.go @@ -11,7 +11,7 @@ import ( ) func TestParseCPUs(t *testing.T) { - var tests = []struct { + tests := []struct { name string input string cpus CPUs @@ -110,7 +110,7 @@ func TestParseCPUs(t *testing.T) { } func TestCPUsString(t *testing.T) { - var tests = []struct { + tests := []struct { name string cpus CPUs output string diff --git a/pkg/namespace/builder_test.go b/pkg/namespace/builder_test.go index 80d6ee8b22..879eca2784 100644 --- a/pkg/namespace/builder_test.go +++ b/pkg/namespace/builder_test.go @@ -48,16 +48,15 @@ func newTestBuilder(name string) func(t minimock.Tester) *Builder { } func mockNSBuilder(t minimock.Tester) args { return args{&noopNS{}} } func TestBuilder_buildNS(t *testing.T) { - tests := []struct { name string init func(t minimock.Tester) *Builder - inspect func(r *Builder, t *testing.T) //inspects *Builder after execution of buildNS + inspect func(r *Builder, t *testing.T) // inspects *Builder after execution of buildNS args func(t minimock.Tester) args wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{} files, err := ioutil.ReadDir("testdata") if err != nil { @@ -67,12 +66,12 @@ func TestBuilder_buildNS(t *testing.T) { tests = append(tests, struct { name string init func(t minimock.Tester) *Builder - inspect func(r *Builder, t *testing.T) //inspects *Builder after execution of buildNS + inspect func(r *Builder, t *testing.T) // inspects *Builder after execution of buildNS args func(t minimock.Tester) args wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{ name: file.Name(), init: newTestBuilder(file.Name()), @@ -102,7 +101,6 @@ func TestBuilder_buildNS(t *testing.T) { } else { assert.NoError(t, err) } - }) } } diff --git a/pkg/namespace/namespace_test.go b/pkg/namespace/namespace_test.go index 49071ad7fd..76dceb5c29 100644 --- a/pkg/namespace/namespace_test.go +++ b/pkg/namespace/namespace_test.go @@ -27,6 +27,7 @@ func checkArgs(t minimock.Tester, args arg, mod Modifier) error { assert.Equal(t, args.flag, call.flag, "flags are not equal") return nil } + func TestOPS_NewNS(t *testing.T) { type args struct { ns Namespace @@ -35,12 +36,12 @@ func TestOPS_NewNS(t *testing.T) { tests := []struct { name string init func(t minimock.Tester) File - inspect func(r File, t *testing.T) //inspects OPS after execution of NewNS + inspect func(r File, t *testing.T) // inspects OPS after execution of NewNS args func(t minimock.Tester) args wantErr bool - inspectErr func(err error, t *testing.T) //use for more precise error evaluation + inspectErr func(err error, t *testing.T) // use for more precise error evaluation }{ { name: "simple", @@ -88,7 +89,6 @@ func TestOPS_NewNS(t *testing.T) { } else { assert.NoError(t, err) } - }) } } diff --git a/pkg/namespace/parser.go b/pkg/namespace/parser.go index 516feb2707..9ff3bed74e 100644 --- a/pkg/namespace/parser.go +++ b/pkg/namespace/parser.go @@ -37,7 +37,6 @@ func Parse(r io.Reader) (File, error) { continue } cmd, err := ParseLine(scanner.Text()) - if err != nil { return nil, err } diff --git a/pkg/namespace/parser_test.go b/pkg/namespace/parser_test.go index b24f2b19e4..60d1274608 100644 --- a/pkg/namespace/parser_test.go +++ b/pkg/namespace/parser_test.go @@ -110,7 +110,7 @@ func TestParse(t *testing.T) { flag: REPL | AFTER, args: []string{"/srv/slashn", "/n"}, }, - //authentication + // authentication cmd{ syscall: MOUNT, flag: REPL | AFTER, diff --git a/pkg/ntpdate/ntpdate.go b/pkg/ntpdate/ntpdate.go index 49a9aa95d3..3c609ebc50 100644 --- a/pkg/ntpdate/ntpdate.go +++ b/pkg/ntpdate/ntpdate.go @@ -69,8 +69,7 @@ type timeGetterSetter interface { SetRTCTime(time.Time) error } -type realGetterSetter struct { -} +type realGetterSetter struct{} func (*realGetterSetter) GetTime(servers []string) (time.Time, string, error) { return getTime(servers) diff --git a/pkg/pci/bits_test.go b/pkg/pci/bits_test.go index 9b80100222..0242dd721d 100644 --- a/pkg/pci/bits_test.go +++ b/pkg/pci/bits_test.go @@ -7,7 +7,7 @@ package pci import "testing" func TestControlBits(t *testing.T) { - var tests = []struct { + tests := []struct { c Control w string }{ @@ -24,11 +24,10 @@ func TestControlBits(t *testing.T) { t.Errorf("Control bits for %#x: got \n%q\n, want \n%q", tt.c, s, tt.w) } } - } func TestStatusBits(t *testing.T) { - var tests = []struct { + tests := []struct { c Status w string }{ @@ -44,11 +43,10 @@ func TestStatusBits(t *testing.T) { t.Errorf("Control bits for %#x: got \n%q, want \n%q", tt.c, s, tt.w) } } - } func TestBAR(t *testing.T) { - var tests = []struct { + tests := []struct { bar string res string err string @@ -81,5 +79,4 @@ func TestBAR(t *testing.T) { t.Errorf("BAR %s: got \n%q, want \n%q", tt.bar, s, tt.res) } } - } diff --git a/pkg/pci/devices.go b/pkg/pci/devices.go index 42b1cb3b8a..659e5641f1 100644 --- a/pkg/pci/devices.go +++ b/pkg/pci/devices.go @@ -12,7 +12,7 @@ import ( "os" ) -//Devices contains a slice of one or more PCI devices +// Devices contains a slice of one or more PCI devices type Devices []*PCI // Print prints information to an io.Writer @@ -69,7 +69,6 @@ func (d Devices) Print(o io.Writer, verbose, confSize int) error { if _, err := fmt.Fprintf(o, "\tInterrupt: pin %X routed to IRQ %X\n", 9+pci.IRQPin, pci.IRQLine); err != nil { return err } - } if !pci.Bridge { for _, b := range pci.BARS { @@ -77,7 +76,6 @@ func (d Devices) Print(o io.Writer, verbose, confSize int) error { return err } } - } extraNL = true } diff --git a/pkg/pci/ids.go b/pkg/pci/ids.go index 7252c27ba9..09e929d834 100644 --- a/pkg/pci/ids.go +++ b/pkg/pci/ids.go @@ -22,12 +22,11 @@ var ids idMap // create ids since the most common use of pci will be with names, // not numbers. func newIDs() idMap { - if ids != nil { return ids } - var pciids = []byte(`0001 SafeNet (wrong ID) + pciids := []byte(`0001 SafeNet (wrong ID) 0010 Allied Telesis, Inc (Wrong ID) 8139 AT-2500TX V3 Ethernet 001c PEAK-System Technik GmbH diff --git a/pkg/pci/lookup.go b/pkg/pci/lookup.go index a4e80aa1b6..e7a25baf1a 100644 --- a/pkg/pci/lookup.go +++ b/pkg/pci/lookup.go @@ -12,7 +12,6 @@ const venDevFmt = "%04x" // readable labels for both the vendor and device. It returns the input ID value if // if label is not found in the ids map. func Lookup(ids map[uint16]Vendor, vendor uint16, device uint16) (string, string) { - if v, ok := ids[vendor]; ok { if d, ok := v.Devices[device]; ok { return v.Name, string(d) diff --git a/pkg/pci/lookup_test.go b/pkg/pci/lookup_test.go index 3648a042f3..99379da3cc 100644 --- a/pkg/pci/lookup_test.go +++ b/pkg/pci/lookup_test.go @@ -9,8 +9,7 @@ import ( ) func TestLookup(t *testing.T) { - - var idLookupTests = []*PCI{ + idLookupTests := []*PCI{ {Vendor: 0x1055, Device: 0xe420, VendorName: "Efar Microsystems", DeviceName: "LAN9420/LAN9420i"}, {Vendor: 0x8086, Device: 0x1237, VendorName: "Intel Corporation", DeviceName: "440FX - 82441FX PMC [Natoma]"}, {Vendor: 0x8086, Device: 0x7000, VendorName: "Intel Corporation", DeviceName: "82371SB PIIX3 ISA [Natoma/Triton II]"}, @@ -36,5 +35,4 @@ func TestLookup(t *testing.T) { } } }) - } diff --git a/pkg/pci/pci.go b/pkg/pci/pci.go index 61c015fbbe..b890ea0f0f 100644 --- a/pkg/pci/pci.go +++ b/pkg/pci/pci.go @@ -68,7 +68,6 @@ func (p *PCI) ReadConfig() error { c, err := ioutil.ReadFile(dev) if err != nil { return err - } p.Config = c p.Control = Control(binary.LittleEndian.Uint16(c[4:6])) @@ -136,13 +135,13 @@ func (p *PCI) WriteConfigRegister(offset, size int64, val uint64) error { case 64: err = binary.Write(w, binary.LittleEndian, &val) case 32: - var v = uint32(val) + v := uint32(val) err = binary.Write(w, binary.LittleEndian, &v) case 16: - var v = uint16(val) + v := uint16(val) err = binary.Write(w, binary.LittleEndian, &v) case 8: - var v = uint8(val) + v := uint8(val) err = binary.Write(w, binary.LittleEndian, &v) } return err diff --git a/pkg/pci/pci_linux.go b/pkg/pci/pci_linux.go index 5bd6bbbbae..9b84468c3f 100644 --- a/pkg/pci/pci_linux.go +++ b/pkg/pci/pci_linux.go @@ -86,7 +86,8 @@ func OnePCI(dir string) (*PCI, error) { Index: i, Base: b, Lim: l, - Attr: a} + Attr: a, + } switch i { case 13: pci.IO = nb @@ -137,7 +138,7 @@ func NewBusReader(globs ...string) (BusReader, error) { exp = append(exp, gg...) } // uniq - var u = map[string]struct{}{} + u := map[string]struct{}{} for _, e := range exp { u[e] = struct{}{} } diff --git a/pkg/pci/pci_linux_test.go b/pkg/pci/pci_linux_test.go index 60e676517c..d7c6a31a8a 100644 --- a/pkg/pci/pci_linux_test.go +++ b/pkg/pci/pci_linux_test.go @@ -96,7 +96,7 @@ func TestBusReadConfig(t *testing.T) { if err != nil { log.Fatalf("Read: %v", err) } - var o = &bytes.Buffer{} + o := &bytes.Buffer{} // First test is a low verbosity one that should only require 64 bytes. if err := d.Print(o, 0, 64); err != nil { log.Fatal(err) @@ -110,11 +110,10 @@ func TestBusReadConfig(t *testing.T) { if !fullread && err == nil { log.Fatalf("Doing a full config read as ! root: got nil, want %v", os.ErrPermission) } - } func testBaseLimType(t *testing.T) { - var tests = []struct { + tests := []struct { bar string r1, r2 string }{ @@ -131,5 +130,4 @@ func testBaseLimType(t *testing.T) { // t.Errorf("BAR %s: got \n(%q,%q) want \n(%q,%q)", tt.bar, r1, r2, tt.r1, tt.r2) //} } - } diff --git a/pkg/pogosh/arithmetic_test.go b/pkg/pogosh/arithmetic_test.go index 8af283375f..dc3c936923 100644 --- a/pkg/pogosh/arithmetic_test.go +++ b/pkg/pogosh/arithmetic_test.go @@ -32,73 +32,88 @@ var arithmeticPositiveTests = []struct { out *big.Int }{ // Constants - {"Zero", + { + "Zero", "0", big.NewInt(0), }, - {"Decimal", + { + "Decimal", "123", big.NewInt(123), }, - {"Octal", + { + "Octal", "0123", - big.NewInt(0123), + big.NewInt(0o123), }, - {"Hex", + { + "Hex", "0x123", big.NewInt(0x123), }, // Order of operation - {"BEDMAS1", + { + "BEDMAS1", "1+2*3", big.NewInt(7), }, - {"BEDMAS2", + { + "BEDMAS2", "(1+2)*3", big.NewInt(9), }, - {"BEDMAS3", + { + "BEDMAS3", "1*2+3", big.NewInt(5), }, - {"BEDMAS4", + { + "BEDMAS4", "-1*-2+-+-3", big.NewInt(5), }, // Associativity - {"Associativity1", + { + "Associativity1", "1-2-3", big.NewInt(-4), }, - {"Associativity2", + { + "Associativity2", "1-2*3-4", big.NewInt(-9), }, // Spacing - {"Spacing", + { + "Spacing", " 1 + 3 * 4 / 3 - 8 ", big.NewInt(-3), }, // Conditional Operator - {"Conditional", + { + "Conditional", " 0 ? 4 : 1 ? 5 : 6 ", big.NewInt(5), }, // Variables - {"Variables1", + { + "Variables1", "x", big.NewInt(1), }, - {"Variables2", + { + "Variables2", "x + y", big.NewInt(124), }, - {"Variables3", + { + "Variables3", "xyz * 2", big.NewInt(84), }, diff --git a/pkg/pogosh/exec.go b/pkg/pogosh/exec.go index a3b71adb5e..eea88d9c74 100644 --- a/pkg/pogosh/exec.go +++ b/pkg/pogosh/exec.go @@ -111,7 +111,7 @@ func searchPath(env string, cmdName string) (string, error) { fi, err := os.Stat(path) // TODO: could the permission check be more strick? - if err == nil && fi.Mode().IsRegular() && fi.Mode()&0111 != 0 { + if err == nil && fi.Mode().IsRegular() && fi.Mode()&0o111 != 0 { return path, nil } } @@ -173,7 +173,6 @@ func recursiveExpansion(s *State, word string) string { } case word[i:i+2] == "${": for j := i; j < len(word); j++ { - } default: word = parameterExpansion(s, word) @@ -239,7 +238,7 @@ func (c *simpleCommand) exec(s *State) { switch string(redirect.ioOp) { case "<": // Redirect input - f, err := os.OpenFile(string(redirect.filename), os.O_RDONLY, 0666) + f, err := os.OpenFile(string(redirect.filename), os.O_RDONLY, 0o666) defer f.Close() if err != nil { panic(err) @@ -255,7 +254,7 @@ func (c *simpleCommand) exec(s *State) { // TODO: closing files with - case ">": // Redirect output - f, err := os.OpenFile(string(redirect.filename), os.O_CREATE|os.O_WRONLY, 0666) + f, err := os.OpenFile(string(redirect.filename), os.O_CREATE|os.O_WRONLY, 0o666) defer f.Close() if err != nil { panic(err) @@ -271,7 +270,7 @@ func (c *simpleCommand) exec(s *State) { // TODO: closing files with - case ">>": // Appending redirected output - f, err := os.OpenFile(string(redirect.filename), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) + f, err := os.OpenFile(string(redirect.filename), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666) defer f.Close() if err != nil { panic(err) @@ -279,7 +278,7 @@ func (c *simpleCommand) exec(s *State) { cmd.Files[1] = f case "<>": // Open file descriptor for reading and writing - f, err := os.OpenFile(string(redirect.filename), os.O_CREATE|os.O_RDWR, 0666) + f, err := os.OpenFile(string(redirect.filename), os.O_CREATE|os.O_RDWR, 0o666) defer f.Close() if err != nil { panic(err) diff --git a/pkg/pogosh/lexer_test.go b/pkg/pogosh/lexer_test.go index 07ec1a5786..b929a59107 100644 --- a/pkg/pogosh/lexer_test.go +++ b/pkg/pogosh/lexer_test.go @@ -16,67 +16,87 @@ var lexerPositiveTests = []struct { out []token }{ // Words - {"Single Word", + { + "Single Word", `abc`, []token{{"abc", ttWord}}, }, - {"Single Character Word", + { + "Single Character Word", `a`, []token{{"a", ttWord}}, }, - {"Multiple Words", + { + "Multiple Words", `a bc`, []token{{"a", ttWord}, {"bc", ttWord}}, }, // Newlines and blanks - {"Empty input", + { + "Empty input", "", []token{}, }, - {"Blank input", + { + "Blank input", "\t \t ", []token{}, }, - {"Various whitespace", + { + "Various whitespace", " \n\t\n \n", []token{{"\n", ttNewLine}, {"\n", ttNewLine}, {"\n", ttNewLine}}, }, - {"Whitespace Word Combo", + { + "Whitespace Word Combo", " a \nb\t\nc \nd", []token{ - {"a", ttWord}, {"\n", ttNewLine}, {"b", ttWord}, {"\n", ttNewLine}, - {"c", ttWord}, {"\n", ttNewLine}, {"d", ttWord}}, + {"a", ttWord}, + {"\n", ttNewLine}, + {"b", ttWord}, + {"\n", ttNewLine}, + {"c", ttWord}, + {"\n", ttNewLine}, + {"d", ttWord}, + }, }, // Single quotes - {"Single quotes", + { + "Single quotes", "'a'", []token{{"'a'", ttWord}}, }, - {"Single quotes with spaces", + { + "Single quotes with spaces", "'a bc'", []token{{"'a bc'", ttWord}}, }, - {"Single escape", + { + "Single escape", "'\t\\\n'", []token{{"'\t\\\n'", ttWord}}, }, // Double quotes - {"Double Quote", + { + "Double Quote", `"a"`, []token{{`"a"`, ttWord}}, }, - {"Double Quotes with spaces", + { + "Double Quotes with spaces", `"a bc"`, []token{{`"a bc"`, ttWord}}, }, - {"Double Quote With Escapes", + { + "Double Quote With Escapes", `"\"a\\\$(" ")"`, []token{{`"\"a\\\$("`, ttWord}, {`")"`, ttWord}}, }, - {"Double Quote With Subexpression", + { + "Double Quote With Subexpression", `"a$(b)"`, []token{{`"a$(b)"`, ttWord}}, }, @@ -94,75 +114,139 @@ var lexerPositiveTests = []struct { // TODO // Line comments - {"Line Comment", + { + "Line Comment", `# "comment"`, []token{}, }, - {"Multiple Line Comments", + { + "Multiple Line Comments", `abc d # comment efg # comment2`, []token{{"abc", ttWord}, {"d", ttWord}, {"\n", ttNewLine}, {"efg", ttWord}}, }, - {"Line Comment Continuation", + { + "Line Comment Continuation", "# comment \\\nabc", []token{}, }, // Line continuation - {"Line Continuation", + { + "Line Continuation", "\\\n", []token{}, }, - {"Line Continuation in Token", + { + "Line Continuation in Token", "ech\\\no abc", []token{{"ech\\\no", ttWord}, {"abc", ttWord}}, }, - {"Line Continuation in Double Quote", + { + "Line Continuation in Double Quote", "echo \"ab\\\nc\"", []token{{"echo", ttWord}, {"\"ab\\\nc\"", ttWord}}, }, - {"Line Continuation in Single Quote", + { + "Line Continuation in Single Quote", "echo 'ab\\\nc'", []token{{"echo", ttWord}, {"'ab\\\nc'", ttWord}}, }, // Operators - {"Operator Single", + { + "Operator Single", ">>", []token{{">>", ttDGreat}}, }, - {"Operators Compact", + { + "Operators Compact", "a&&b||c;;d<>f<&g>&h<>i<<-j>|k", - []token{{"a", ttWord}, {"&&", ttAndIf}, {"b", ttWord}, - {"||", ttOrIf}, {"c", ttWord}, {";;", ttDSemi}, {"d", ttWord}, - {"<<", ttDLess}, {"e", ttWord}, {">>", ttDGreat}, {"f", ttWord}, - {"<&", ttLessAnd}, {"g", ttWord}, {">&", ttGreatAnd}, {"h", ttWord}, - {"<>", ttLessGreat}, {"i", ttWord}, {"<<-", ttDLessDash}, - {"j", ttWord}, {">|", ttClobber}, {"k", ttWord}}, - }, - {"Operators Whitespace", + []token{ + {"a", ttWord}, + {"&&", ttAndIf}, + {"b", ttWord}, + {"||", ttOrIf}, + {"c", ttWord}, + {";;", ttDSemi}, + {"d", ttWord}, + {"<<", ttDLess}, + {"e", ttWord}, + {">>", ttDGreat}, + {"f", ttWord}, + {"<&", ttLessAnd}, + {"g", ttWord}, + {">&", ttGreatAnd}, + {"h", ttWord}, + {"<>", ttLessGreat}, + {"i", ttWord}, + {"<<-", ttDLessDash}, + {"j", ttWord}, + {">|", ttClobber}, + {"k", ttWord}, + }, + }, + { + "Operators Whitespace", " a && b || c ;; d << e >> f <& g >& h <> i <<- j >| k ", - []token{{"a", ttWord}, {"&&", ttAndIf}, {"b", ttWord}, - {"||", ttOrIf}, {"c", ttWord}, {";;", ttDSemi}, {"d", ttWord}, - {"<<", ttDLess}, {"e", ttWord}, {">>", ttDGreat}, {"f", ttWord}, - {"<&", ttLessAnd}, {"g", ttWord}, {">&", ttGreatAnd}, {"h", ttWord}, - {"<>", ttLessGreat}, {"i", ttWord}, {"<<-", ttDLessDash}, - {"j", ttWord}, {">|", ttClobber}, {"k", ttWord}}, - }, - {"Operators Escaped", + []token{ + {"a", ttWord}, + {"&&", ttAndIf}, + {"b", ttWord}, + {"||", ttOrIf}, + {"c", ttWord}, + {";;", ttDSemi}, + {"d", ttWord}, + {"<<", ttDLess}, + {"e", ttWord}, + {">>", ttDGreat}, + {"f", ttWord}, + {"<&", ttLessAnd}, + {"g", ttWord}, + {">&", ttGreatAnd}, + {"h", ttWord}, + {"<>", ttLessGreat}, + {"i", ttWord}, + {"<<-", ttDLessDash}, + {"j", ttWord}, + {">|", ttClobber}, + {"k", ttWord}, + }, + }, + { + "Operators Escaped", ` a \&\& b \|\| c \;\; d \<\< e \>\> f \<\& g \>\& h \<\> i \<\<\- j \>\| k `, - []token{{"a", ttWord}, {`\&\&`, ttWord}, {"b", ttWord}, - {`\|\|`, ttWord}, {"c", ttWord}, {`\;\;`, ttWord}, {"d", ttWord}, - {`\<\<`, ttWord}, {"e", ttWord}, {`\>\>`, ttWord}, {"f", ttWord}, - {`\<\&`, ttWord}, {"g", ttWord}, {`\>\&`, ttWord}, {"h", ttWord}, - {`\<\>`, ttWord}, {"i", ttWord}, {`\<\<\-`, ttWord}, - {"j", ttWord}, {`\>\|`, ttWord}, {"k", ttWord}}, - }, - {"Operator Dash", + []token{ + {"a", ttWord}, + {`\&\&`, ttWord}, + {"b", ttWord}, + {`\|\|`, ttWord}, + {"c", ttWord}, + {`\;\;`, ttWord}, + {"d", ttWord}, + {`\<\<`, ttWord}, + {"e", ttWord}, + {`\>\>`, ttWord}, + {"f", ttWord}, + {`\<\&`, ttWord}, + {"g", ttWord}, + {`\>\&`, ttWord}, + {"h", ttWord}, + {`\<\>`, ttWord}, + {"i", ttWord}, + {`\<\<\-`, ttWord}, + {"j", ttWord}, + {`\>\|`, ttWord}, + {"k", ttWord}, + }, + }, + { + "Operator Dash", `\<\<- -`, []token{{`\<\<-`, ttWord}, {`-`, ttWord}}, }, - {"Operator Half Escape", + { + "Operator Half Escape", `echo \&&`, []token{{"echo", ttWord}, {`\&`, ttWord}, {"&", ttWord}}, }, diff --git a/pkg/pogosh/parser.go b/pkg/pogosh/parser.go index 1a3d92acba..340c645877 100644 --- a/pkg/pogosh/parser.go +++ b/pkg/pogosh/parser.go @@ -128,27 +128,23 @@ func parseCommand(s *State, t *tokenizer) command { // | until_clause // ; func parseCompoundCommand(s *State, t *tokenizer) { - } // subshell : '(' compound_list ') // ; func parseSubshell(s *State, t *tokenizer) { - } // compound_list : LineBreak term // | LineBreak term separator // ; func parseCompoundList(s *State, t *tokenizer) { - } // term : term separator '&&' // | '&&' // ; func parseTerm(s *State, t *tokenizer) { - } // for_clause : 'for' name do_group @@ -157,20 +153,17 @@ func parseTerm(s *State, t *tokenizer) { // | 'for' name LineBreak in wordlist sequential_sep do_group // ; func parseForClause(s *State, t *tokenizer) { - } // in : 'in' // ; func parseIn(s *State, t *tokenizer) { - } // wordlist : wordlist WORD // | WORD // ; func parseWordList(s *State, t *tokenizer) { - } // case_clause : 'case' WORD LineBreak 'in' LineBreak case_list 'esac' @@ -178,21 +171,18 @@ func parseWordList(s *State, t *tokenizer) { // | 'case' WORD LineBreak 'in' LineBreak 'esac' // ; func parseCaseClause(s *State, t *tokenizer) { - } // case_list_ns : case_list case_item_ns // | case_item_ns // ; func parseCaseListNS(s *State, t *tokenizer) { - } // case_list : case_list case_item // | case_item // ; func parseCaseList(s *State, t *tokenizer) { - } // case_item_ns : pattern ')' LineBreak @@ -201,7 +191,6 @@ func parseCaseList(s *State, t *tokenizer) { // | '(' pattern ')' compound_list // ; func parseCaseItemNS(s *State, t *tokenizer) { - } // case_item : pattern ')' ';;' LineBreak @@ -210,20 +199,17 @@ func parseCaseItemNS(s *State, t *tokenizer) { // | '(' pattern ')' ';;' compound_list // ; func parseCaseItem(s *State, t *tokenizer) { - } // pattern : WORD // | pattern '|' WORD // ; func parsePattern(s *State, t *tokenizer) { - } // if_clause : 'if' compound_list 'then' compound_list else_part 'fi' // | 'if' compound_list 'then' compound_list 'fi' func parseIfClause(s *State, t *tokenizer) { - } // else_part : 'elif' compound_list 'then' compound_list @@ -231,50 +217,42 @@ func parseIfClause(s *State, t *tokenizer) { // | 'else' compound_list // ; func parseElsePart(s *State, t *tokenizer) { - } // while_clause : 'while' compound_list do_group // ; func parseWhileClause(s *State, t *tokenizer) { - } // until_clause : 'until' compound_list do_group // ; func parseUntilClause(s *State, t *tokenizer) { - } // function_definition : fname '(' ')' LineBreak function_body // ; func parseFunctionDefinition(s *State, t *tokenizer) { - } // function_body : compound_command // | compound_command redirect_list // ; func parseFunctionBody(s *State, t *tokenizer) { - } // fname : NAME // ; func parseFName(s *State, t *tokenizer) { - } // brace_group : '{' compound_list '}' // ; func parseBraceGroup(s *State, t *tokenizer) { - } // do_group : 'do' compound_list 'done' // ; func parseDoGroup(s *State, t *tokenizer) { - } // SimpleCommand ::= CmdPrefix SimpleCommand2 | CmdName CmdSuffix @@ -333,7 +311,6 @@ func parseCmdSuffix(s *State, t *tokenizer, cmd *simpleCommand) { // | redirect_list io_redirect // ; func parseRedirectList(s *State, t *tokenizer) { - } // IORedirect ::= IORedirect2 | IO_NUMBER IORedirect2 @@ -367,13 +344,11 @@ func parseFilename(s *State, t *tokenizer) []byte { // | DLESSDASH here_end // ; func parseIOHere(s *State, t *tokenizer) { - } // here_end : WORD // ; func parseHereEnd(s *State, t *tokenizer) { - } // NewLineList ::= NEWLINE NewLineList | NEWLINE @@ -409,12 +384,10 @@ func parseSeparatorOp(s *State, t *tokenizer) { // | NewLineList // ; func parseSeparator(s *State, t *tokenizer) { - } // sequential_sep : ';' LineBreak // | NewLineList // ; func parseSequentialSep(s *State, t *tokenizer) { - } diff --git a/pkg/qemu/devices.go b/pkg/qemu/devices.go index 0f0c81dfca..1a971e864d 100644 --- a/pkg/qemu/devices.go +++ b/pkg/qemu/devices.go @@ -223,7 +223,7 @@ func (p P9Directory) KArgs() []string { } } return []string{ - //seen as an env var by the init process + // seen as an env var by the init process "UROOT_USE_9P=1", } } diff --git a/pkg/rng/entropy.go b/pkg/rng/entropy.go index 754b76b9e3..b3db24016d 100644 --- a/pkg/rng/entropy.go +++ b/pkg/rng/entropy.go @@ -89,7 +89,7 @@ func setAvailableTRNG() error { return errors.New("no TRNG found on platform") } - if err = ioutil.WriteFile(HwRandomCurrentFile, []byte(selectedRNG), 0644); err != nil { + if err = ioutil.WriteFile(HwRandomCurrentFile, []byte(selectedRNG), 0o644); err != nil { return err } @@ -147,7 +147,7 @@ func UpdateLinuxRandomness(recoverer recovery.Recoverer) error { continue } - var random = make([]byte, EntropyBlockSize) + random := make([]byte, EntropyBlockSize) length, err := hwRng.Read(random) if err != nil { recoverer.Recover("Can't open the hardware random device") diff --git a/pkg/rtc/rtc_linux.go b/pkg/rtc/rtc_linux.go index 4df7e423a8..d998ab57e2 100644 --- a/pkg/rtc/rtc_linux.go +++ b/pkg/rtc/rtc_linux.go @@ -29,7 +29,8 @@ func (r *RTC) Read() (time.Time, error) { // Set implements Set for the Linux RTC func (r *RTC) Set(tu time.Time) error { - rt := unix.RTCTime{Sec: int32(tu.Second()), + rt := unix.RTCTime{ + Sec: int32(tu.Second()), Min: int32(tu.Minute()), Hour: int32(tu.Hour()), Mday: int32(tu.Day()), @@ -37,7 +38,8 @@ func (r *RTC) Set(tu time.Time) error { Year: int32(tu.Year() - 1900), Wday: int32(0), Yday: int32(0), - Isdst: int32(0)} + Isdst: int32(0), + } return unix.IoctlSetRTCTime(int(r.file.Fd()), &rt) } diff --git a/pkg/securelaunch/eventlog/eventlog.go b/pkg/securelaunch/eventlog/eventlog.go index bc2dd3d3ba..70463ce209 100644 --- a/pkg/securelaunch/eventlog/eventlog.go +++ b/pkg/securelaunch/eventlog/eventlog.go @@ -25,12 +25,12 @@ type EventLog struct { const ( eventLogFile = "/sys/kernel/security/slaunch/eventlog" - defaultEventLogFile = "eventlog.txt" //only used if user doesn't provide any + defaultEventLogFile = "eventlog.txt" // only used if user doesn't provide any ) // Add writes event logs to sysfs file. func Add(b []byte) error { - fd, err := os.OpenFile(eventLogFile, os.O_WRONLY, 0644) + fd, err := os.OpenFile(eventLogFile, os.O_WRONLY, 0o644) if err != nil { return err } diff --git a/pkg/securelaunch/helpers.go b/pkg/securelaunch/helpers.go index fe9f0e7277..c6442fd485 100644 --- a/pkg/securelaunch/helpers.go +++ b/pkg/securelaunch/helpers.go @@ -52,7 +52,6 @@ var Debug = func(string, ...interface{}) {} // // defFileName is default dst file name, only used if user doesn't provide one. func WriteToFile(data []byte, dst, defFileName string) (string, error) { - // make sure dst is an absolute file path if !filepath.IsAbs(dst) { return "", fmt.Errorf("dst =%s Not an absolute path ", dst) @@ -68,7 +67,7 @@ func WriteToFile(data []byte, dst, defFileName string) (string, error) { } Debug("WriteToFile: target=%s", target) - err = ioutil.WriteFile(target, data, 0644) + err = ioutil.WriteFile(target, data, 0o644) if err != nil { return "", fmt.Errorf("failed to write date to file =%s, err=%v", target, err) } @@ -79,7 +78,6 @@ func WriteToFile(data []byte, dst, defFileName string) (string, error) { // persist writes data to targetPath. // targetPath is of form sda:/boot/cpuid.txt func persist(data []byte, targetPath string, defaultFile string) error { - filePath, r := GetMountedFilePath(targetPath, 0) // 0 is flag for rw mount option if r != nil { return fmt.Errorf("persist: err: input %s could NOT be located, err=%v", targetPath, r) @@ -163,7 +161,6 @@ func deleteEntryMountCache(key string) { } func setMountCache(key string, val mountCacheData) { - mountCache.mu.Lock() mountCache.m[key] = val mountCache.mu.Unlock() @@ -175,7 +172,6 @@ func setMountCache(key string, val mountCacheData) { // and clears an entry in cache if result is found with different // flags, otherwise returns the cached entry or nil. func getMountCacheData(key string, flags uintptr) (string, error) { - Debug("mountCache: Lookup with key %s", key) cachedData, ok := mountCache.m[key] if ok { @@ -202,7 +198,6 @@ func getMountCacheData(key string, flags uintptr) (string, error) { // MountDevice looks up mountCache map. if no entry is found, it // mounts a device and updates cache, otherwise returns mountPath. func MountDevice(device *block.BlockDev, flags uintptr) (string, error) { - devName := device.Name Debug("MountDevice: Checking cache first for %s", devName) diff --git a/pkg/securelaunch/launcher/launcher.go b/pkg/securelaunch/launcher/launcher.go index 04295d7260..bc64ff44d9 100644 --- a/pkg/securelaunch/launcher/launcher.go +++ b/pkg/securelaunch/launcher/launcher.go @@ -26,7 +26,6 @@ type Launcher struct { // MeasureKernel calls file collector in measurement pkg that // hashes kernel, initrd files and even store these hashes in tpm pcrs. func (l *Launcher) MeasureKernel() error { - kernel := l.Params["kernel"] initrd := l.Params["initrd"] @@ -57,7 +56,6 @@ func (l *Launcher) MeasureKernel() error { * - if kexec fails */ func (l *Launcher) Boot() error { - if l.Type != "kexec" { log.Printf("launcher: Unsupported launcher type. Exiting.") return fmt.Errorf("launcher: Unsupported launcher type. Exiting") diff --git a/pkg/securelaunch/measurement/cpuid.go b/pkg/securelaunch/measurement/cpuid.go index 5e98a1ab94..d225557d93 100644 --- a/pkg/securelaunch/measurement/cpuid.go +++ b/pkg/securelaunch/measurement/cpuid.go @@ -17,7 +17,7 @@ import ( ) const ( - defaultCPUIDFile = "cpuid.txt" //only used if user doesn't provide any + defaultCPUIDFile = "cpuid.txt" // only used if user doesn't provide any ) /* describes the "cpuid" portion of policy file */ @@ -33,7 +33,7 @@ type CPUIDCollector struct { */ func NewCPUIDCollector(config []byte) (Collector, error) { slaunch.Debug("New CPUID Collector initialized\n") - var fc = new(CPUIDCollector) + fc := new(CPUIDCollector) err := json.Unmarshal(config, &fc) if err != nil { return nil, err @@ -125,7 +125,6 @@ func measureCPUIDFile() ([]byte, error) { * 3. also keeps a copy of the result on disk at location provided in policy file. */ func (s *CPUIDCollector) Collect() error { - d, err := measureCPUIDFile() if err != nil { log.Printf("CPUID Collector: err = %v", err) diff --git a/pkg/securelaunch/measurement/dmi.go b/pkg/securelaunch/measurement/dmi.go index 9a6dea4faf..5ccef9b974 100644 --- a/pkg/securelaunch/measurement/dmi.go +++ b/pkg/securelaunch/measurement/dmi.go @@ -35,7 +35,7 @@ type DmiCollector struct { */ func NewDmiCollector(config []byte) (Collector, error) { slaunch.Debug("New DMI Collector initialized") - var dc = new(DmiCollector) + dc := new(DmiCollector) err := json.Unmarshal(config, &dc) if err != nil { return nil, err diff --git a/pkg/securelaunch/measurement/files.go b/pkg/securelaunch/measurement/files.go index 8fb86a67ce..41df8da055 100644 --- a/pkg/securelaunch/measurement/files.go +++ b/pkg/securelaunch/measurement/files.go @@ -29,7 +29,7 @@ type FileCollector struct { */ func NewFileCollector(config []byte) (Collector, error) { slaunch.Debug("New Files Collector initialized\n") - var fc = new(FileCollector) + fc := new(FileCollector) err := json.Unmarshal(config, &fc) if err != nil { return nil, err diff --git a/pkg/securelaunch/measurement/storage.go b/pkg/securelaunch/measurement/storage.go index 522e7e4328..9f955f036e 100644 --- a/pkg/securelaunch/measurement/storage.go +++ b/pkg/securelaunch/measurement/storage.go @@ -28,7 +28,7 @@ type StorageCollector struct { */ func NewStorageCollector(config []byte) (Collector, error) { slaunch.Debug("New Storage Collector initialized\n") - var sc = new(StorageCollector) + sc := new(StorageCollector) err := json.Unmarshal(config, &sc) if err != nil { return nil, err @@ -46,7 +46,6 @@ func NewStorageCollector(config []byte) (Collector, error) { * - error if Reading the block device fails. */ func measureStorageDevice(blkDevicePath string) error { - log.Printf("Storage Collector: Measuring block device %s\n", blkDevicePath) file, err := os.Open(blkDevicePath) if err != nil { @@ -64,7 +63,6 @@ func measureStorageDevice(blkDevicePath string) error { * package which further hashes this buffer and extends pcr. */ func (s *StorageCollector) Collect() error { - for _, inputVal := range s.Paths { device, e := slaunch.GetStorageDevice(inputVal) // inputVal is blkDevicePath e.g UUID or sda if e != nil { diff --git a/pkg/securelaunch/policy/policy.go b/pkg/securelaunch/policy/policy.go index af6738da8b..2f7d0ca9f3 100644 --- a/pkg/securelaunch/policy/policy.go +++ b/pkg/securelaunch/policy/policy.go @@ -46,7 +46,6 @@ type Policy struct { * e.g 4qccd342-12zr-4e99-9ze7-1234cb1234c4:/foo/securelaunch.policy */ func scanKernelCmdLine() []byte { - slaunch.Debug("scanKernelCmdLine: scanning kernel cmd line for *sl_policy* flag") val, ok := cmdline.Flag("sl_policy") if !ok { @@ -81,10 +80,9 @@ func scanKernelCmdLine() []byte { * respectively for each iteration of loop over SearchRoots slice. */ func scanBlockDevice(mountPath string) []byte { - log.Printf("scanBlockDevice") // scan for securelaunch.policy under /, /efi, or /boot - var SearchRoots = []string{"/", "/efi", "/boot"} + SearchRoots := []string{"/", "/efi", "/boot"} for _, c := range SearchRoots { searchPath := filepath.Join(mountPath, c, "securelaunch.policy") @@ -119,7 +117,6 @@ func scanBlockDevice(mountPath string) []byte { * 3 Read in policy file */ func locate() ([]byte, error) { - d := scanKernelCmdLine() if d != nil { return d, nil diff --git a/pkg/securelaunch/tpm/tpm.go b/pkg/securelaunch/tpm/tpm.go index cb86738827..7febf278b1 100644 --- a/pkg/securelaunch/tpm/tpm.go +++ b/pkg/securelaunch/tpm/tpm.go @@ -20,12 +20,13 @@ import ( "github.com/u-root/u-root/pkg/tss" ) -var hashAlgo = tpm2.AlgSHA256 -var tpmHandle *tss.TPM +var ( + hashAlgo = tpm2.AlgSHA256 + tpmHandle *tss.TPM +) // marshalPcrEvent writes structure fields piecemeal to buffer. func marshalPcrEvent(pcr uint32, h []byte, eventDesc []byte) ([]byte, error) { - const baseTypeTXT = 0x400 // TXT specification base event value for DRTM values const slaunchType = uint32(baseTypeTXT + 0x102) // Secure Launch event log entry type. count := uint32(1) @@ -70,7 +71,6 @@ func marshalPcrEvent(pcr uint32, h []byte, eventDesc []byte) ([]byte, error) { // sendEventToSysfs marshals measurement events and writes them to sysfs. func sendEventToSysfs(pcr uint32, h []byte, eventDesc []byte) { - b, err := marshalPcrEvent(pcr, h, eventDesc) if err != nil { log.Println(err) @@ -85,7 +85,6 @@ func sendEventToSysfs(pcr uint32, h []byte, eventDesc []byte) { * hashReader calculates the sha256 sum of an io reader. */ func hashReader(f io.Reader) []byte { - h := sha256.New() if _, err := io.Copy(h, f); err != nil { log.Fatal(err) diff --git a/pkg/shlex/shlex_test.go b/pkg/shlex/shlex_test.go index eebc986b47..4ef0778e68 100644 --- a/pkg/shlex/shlex_test.go +++ b/pkg/shlex/shlex_test.go @@ -67,7 +67,6 @@ func TestArgv(t *testing.T) { if !reflect.DeepEqual(got, tt.want) { t.Errorf("Argv = %#v, want %#v", got, tt.want) } - }) } } diff --git a/pkg/smbios/struct_parser.go b/pkg/smbios/struct_parser.go index 7cf9c5fb49..de2f37a135 100644 --- a/pkg/smbios/struct_parser.go +++ b/pkg/smbios/struct_parser.go @@ -28,14 +28,14 @@ func parseStruct(t *Table, off int, complete bool, sp interface{}) (int, error) sv = reflect.Indirect(reflect.ValueOf(sp)) // must be a pointer to struct then, dereference it } svtn := sv.Type().Name() - //fmt.Printf("t %s\n", svtn) + // fmt.Printf("t %s\n", svtn) i := 0 for ; i < sv.NumField() && off < t.Len(); i++ { f := sv.Type().Field(i) fv := sv.Field(i) ft := fv.Type() tags := f.Tag.Get(fieldTagKey) - //fmt.Printf("XX %02Xh f %s t %s k %s %s\n", off, f.Name, f.Type.Name(), fv.Kind(), tags) + // fmt.Printf("XX %02Xh f %s t %s k %s %s\n", off, f.Name, f.Type.Name(), fv.Kind(), tags) // Check tags first ignore := false for _, tag := range strings.Split(tags, ",") { diff --git a/pkg/strace/internal/abi/flag_test.go b/pkg/strace/internal/abi/flag_test.go index 6d4986d114..1fd19aedb2 100644 --- a/pkg/strace/internal/abi/flag_test.go +++ b/pkg/strace/internal/abi/flag_test.go @@ -14,18 +14,19 @@ import ( // Bits Content Notes // 63-57 Unused // 56 Successful Boot Flag -//Set to 1 the first time the system has successfully booted from this partition (see the File System/Autoupdate design document for the definition of success). +// Set to 1 the first time the system has successfully booted from this partition (see the File System/Autoupdate design document for the definition of success). // 55-52 Tries Remaining Number of times to attempt booting this partition. Used only when the Successful Boot Flag is 0. // 51-48 Priority 4-bit number: 15 = highest, 1 = lowest, 0 = not bootable. // 47-0 Reserved by EFI Spec func TestCrosGPT(t *testing.T) { - var tests = []struct { + tests := []struct { n string f FlagSet v uint64 o string }{ - {n: "Basic ChromeOS GPT flags", + { + n: "Basic ChromeOS GPT flags", f: FlagSet{ &BitFlag{Name: "Suc", Value: 1 << 56}, &Field{Name: "Tries", BitMask: 15 << 52, Shift: 52}, @@ -34,7 +35,8 @@ func TestCrosGPT(t *testing.T) { v: 1<<56 | 8<<52 | 3<<48, o: "Suc|Tries=0x8|prio=0x3", }, - {n: "Basic ChromeOS GPT flags with standard GPT value", + { + n: "Basic ChromeOS GPT flags with standard GPT value", f: FlagSet{ &BitFlag{Name: "Suc", Value: 1 << 56}, &Field{Name: "Tries", BitMask: 15 << 52, Shift: 52}, @@ -43,7 +45,8 @@ func TestCrosGPT(t *testing.T) { v: 1<<56 | 8<<52 | 3<<48 | 1, o: "Suc|Tries=0x8|prio=0x3|0x1", }, - {n: "Simple system call", + { + n: "Simple system call", f: FlagSet{ &Value{Name: "write", Value: unix.SYS_WRITE}, }, diff --git a/pkg/strace/socket.go b/pkg/strace/socket.go index 1a77faa29b..b376518b40 100644 --- a/pkg/strace/socket.go +++ b/pkg/strace/socket.go @@ -208,8 +208,8 @@ func sockAddr(t Task, addr Addr, length uint32) string { return fmt.Sprintf("%#x {Family: %s, Addr: %#02x, Port: %d}", addr, familyStr, []byte(fa.Addr), fa.Port) case unix.AF_NETLINK: - //sa, err := netlink.ExtractSockAddr(b) - //if err != nil { + // sa, err := netlink.ExtractSockAddr(b) + // if err != nil { return fmt.Sprintf("%#x {Family: %s, error extracting address: %v}", addr, familyStr, err) //} //return fmt.Sprintf("%#x {Family: %s, PortID: %d, Groups: %d}", addr, familyStr, sa.PortID, sa.Groups) diff --git a/pkg/strace/syscall_linux.go b/pkg/strace/syscall_linux.go index b13e793851..aa410b7744 100644 --- a/pkg/strace/syscall_linux.go +++ b/pkg/strace/syscall_linux.go @@ -304,7 +304,6 @@ func (i *SyscallInfo) printEnter(t Task, args SyscallArguments) string { default: return fmt.Sprintf("%s E %s(%s, %s, %s, %s, %s, %s, ...)", t.Name(), i.name, o[0], o[1], o[2], o[3], o[4], o[5]) } - } func SysCallEnter(t Task, s *SyscallEvent) string { diff --git a/pkg/strace/syscall_linux_amd64.go b/pkg/strace/syscall_linux_amd64.go index 65a48928e1..0a8f182806 100644 --- a/pkg/strace/syscall_linux_amd64.go +++ b/pkg/strace/syscall_linux_amd64.go @@ -357,7 +357,8 @@ func (s *SyscallEvent) FillArgs() { {uintptr(s.Regs.Rdx)}, {uintptr(s.Regs.R10)}, {uintptr(s.Regs.R8)}, - {uintptr(s.Regs.R9)}} + {uintptr(s.Regs.R9)}, + } s.Sysno = int(uint32(s.Regs.Orig_rax)) } diff --git a/pkg/tarutil/tar.go b/pkg/tarutil/tar.go index 932af4f27f..f99719fc85 100644 --- a/pkg/tarutil/tar.go +++ b/pkg/tarutil/tar.go @@ -244,11 +244,11 @@ func VerboseLogFilter(hdr *tar.Header) bool { // It also sets appropriate permissions. func SafeFilter(hdr *tar.Header) bool { if hdr.Typeflag == tar.TypeDir { - hdr.Mode = 0770 + hdr.Mode = 0o770 return true } if hdr.Typeflag == tar.TypeReg { - hdr.Mode = 0660 + hdr.Mode = 0o660 return true } return false diff --git a/pkg/tarutil/tar_test.go b/pkg/tarutil/tar_test.go index faef9a5a3c..4da67a6cdf 100644 --- a/pkg/tarutil/tar_test.go +++ b/pkg/tarutil/tar_test.go @@ -44,7 +44,7 @@ func extractAndCompare(t *testing.T, tarFile string, files []struct{ name, body } func TestExtractDir(t *testing.T) { - var files = []struct { + files := []struct { name, body string }{ {"a.txt", "hello\n"}, @@ -168,7 +168,7 @@ func TestCreateTarProcfsFile(t *testing.T) { t.Fatal(err) } - var expected = []struct { + expected := []struct { name, body string }{ {procfsFile, string(contents)}, diff --git a/pkg/termios/sgtty.go b/pkg/termios/sgtty.go index 84e62275d7..84bdff0ef5 100644 --- a/pkg/termios/sgtty.go +++ b/pkg/termios/sgtty.go @@ -28,7 +28,7 @@ func GTTY(fd int) (*TTY, error) { return nil, err } - var t = TTY{Opts: make(map[string]bool), CC: make(map[string]uint8)} + t := TTY{Opts: make(map[string]bool), CC: make(map[string]uint8)} for n, b := range boolFields { val := uint32(reflect.ValueOf(term).Elem().Field(b.word).Uint()) & b.mask t.Opts[n] = val != 0 diff --git a/pkg/termios/termios_darwin.go b/pkg/termios/termios_darwin.go index 718009fc1d..a19de42f82 100644 --- a/pkg/termios/termios_darwin.go +++ b/pkg/termios/termios_darwin.go @@ -39,7 +39,7 @@ func NewWithDev(device string) (*TTYIO, error) { // NewTTYS returns a new TTYIO. func NewTTYS(port string) (*TTYIO, error) { - f, err := os.OpenFile(filepath.Join("/dev", port), unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0620) + f, err := os.OpenFile(filepath.Join("/dev", port), unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0o620) if err != nil { return nil, err } @@ -154,7 +154,7 @@ func MakeSerialDefault(term *Termios) *Termios { t.Cc[unix.VMIN] = 1 /* no timeout (reads block forever) */ t.Cc[unix.VTIME] = 0 - //t.Line = 0 + // t.Line = 0 return &t } diff --git a/pkg/termios/termios_linux.go b/pkg/termios/termios_linux.go index aacc8bd844..ac86d871f5 100644 --- a/pkg/termios/termios_linux.go +++ b/pkg/termios/termios_linux.go @@ -44,7 +44,7 @@ func NewWithDev(device string) (*TTYIO, error) { // NewTTYS returns a new TTYIO. func NewTTYS(port string) (*TTYIO, error) { - f, err := os.OpenFile(filepath.Join("/dev", port), unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0620) + f, err := os.OpenFile(filepath.Join("/dev", port), unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0o620) if err != nil { return nil, err } diff --git a/pkg/termios/termios_plan9.go b/pkg/termios/termios_plan9.go index fdb785faf1..96459a7821 100644 --- a/pkg/termios/termios_plan9.go +++ b/pkg/termios/termios_plan9.go @@ -14,8 +14,7 @@ import ( ) // Termios is used to manipulate the control channel of a kernel. -type Termios struct { -} +type Termios struct{} // Winsize holds the window size information, it is modeled on unix.Winsize. type Winsize struct { @@ -46,7 +45,7 @@ func NewWithDev(device string) (*TTYIO, error) { // NewTTYS returns a new TTYIO. func NewTTYS(port string) (*TTYIO, error) { - f, err := os.OpenFile(filepath.Join("/dev", port), os.O_RDWR, 0620) + f, err := os.OpenFile(filepath.Join("/dev", port), os.O_RDWR, 0o620) if err != nil { return nil, err } diff --git a/pkg/termios/termios_test.go b/pkg/termios/termios_test.go index 030723e4a5..16c824619f 100644 --- a/pkg/termios/termios_test.go +++ b/pkg/termios/termios_test.go @@ -103,7 +103,6 @@ func TestNew(t *testing.T) { } else if err != nil { t.Errorf("TestNew: want nil, got %v", err) } - } func TestRaw(t *testing.T) { @@ -158,7 +157,6 @@ func TestString(t *testing.T) { } } - } func TestSet(t *testing.T) { @@ -249,5 +247,4 @@ func TestSet(t *testing.T) { t.Errorf("Setting %q: got nil, want err", set) } } - } diff --git a/pkg/termios/var_darwin.go b/pkg/termios/var_darwin.go index fac8c824ab..771edd19f7 100644 --- a/pkg/termios/var_darwin.go +++ b/pkg/termios/var_darwin.go @@ -8,26 +8,24 @@ import ( "golang.org/x/sys/unix" ) -var ( - // baud2unixB convert a baudrate to the corresponding unix const. - baud2unixB = map[int]uint64{ - 50: unix.B50, - 75: unix.B75, - 110: unix.B110, - 134: unix.B134, - 150: unix.B150, - 200: unix.B200, - 300: unix.B300, - 600: unix.B600, - 1200: unix.B1200, - 1800: unix.B1800, - 2400: unix.B2400, - 4800: unix.B4800, - 9600: unix.B9600, - 19200: unix.B19200, - 38400: unix.B38400, - 57600: unix.B57600, - 115200: unix.B115200, - 230400: unix.B230400, - } -) +// baud2unixB convert a baudrate to the corresponding unix const. +var baud2unixB = map[int]uint64{ + 50: unix.B50, + 75: unix.B75, + 110: unix.B110, + 134: unix.B134, + 150: unix.B150, + 200: unix.B200, + 300: unix.B300, + 600: unix.B600, + 1200: unix.B1200, + 1800: unix.B1800, + 2400: unix.B2400, + 4800: unix.B4800, + 9600: unix.B9600, + 19200: unix.B19200, + 38400: unix.B38400, + 57600: unix.B57600, + 115200: unix.B115200, + 230400: unix.B230400, +} diff --git a/pkg/termios/var_linux.go b/pkg/termios/var_linux.go index 6c11096a97..bfe8cacd69 100644 --- a/pkg/termios/var_linux.go +++ b/pkg/termios/var_linux.go @@ -10,45 +10,43 @@ import ( "golang.org/x/sys/unix" ) -var ( - // baud2unixB convert a baudrate to the corresponding unix const. - baud2unixB = map[int]uint32{ - 50: unix.B50, - 75: unix.B75, - 110: unix.B110, - 134: unix.B134, - 150: unix.B150, - 200: unix.B200, - 300: unix.B300, - 600: unix.B600, - 1200: unix.B1200, - 1800: unix.B1800, - 2400: unix.B2400, - 4800: unix.B4800, - 9600: unix.B9600, - 19200: unix.B19200, - 38400: unix.B38400, - 57600: unix.B57600, - 115200: unix.B115200, - 230400: unix.B230400, - 460800: unix.B460800, - 500000: unix.B500000, - 576000: unix.B576000, - 921600: unix.B921600, - 1000000: unix.B1000000, - 1152000: unix.B1152000, - 1500000: unix.B1500000, - 2000000: unix.B2000000, - 2500000: unix.B2500000, - 3000000: unix.B3000000, - 3500000: unix.B3500000, - 4000000: unix.B4000000, - } -) +// baud2unixB convert a baudrate to the corresponding unix const. +var baud2unixB = map[int]uint32{ + 50: unix.B50, + 75: unix.B75, + 110: unix.B110, + 134: unix.B134, + 150: unix.B150, + 200: unix.B200, + 300: unix.B300, + 600: unix.B600, + 1200: unix.B1200, + 1800: unix.B1800, + 2400: unix.B2400, + 4800: unix.B4800, + 9600: unix.B9600, + 19200: unix.B19200, + 38400: unix.B38400, + 57600: unix.B57600, + 115200: unix.B115200, + 230400: unix.B230400, + 460800: unix.B460800, + 500000: unix.B500000, + 576000: unix.B576000, + 921600: unix.B921600, + 1000000: unix.B1000000, + 1152000: unix.B1152000, + 1500000: unix.B1500000, + 2000000: unix.B2000000, + 2500000: unix.B2500000, + 3000000: unix.B3000000, + 3500000: unix.B3500000, + 4000000: unix.B4000000, +} // init adds constants that are linux-specific func init() { - var extra = map[string]*bit{ + extra := map[string]*bit{ "iuclc": {word: I, mask: syscall.IUCLC}, "olcuc": {word: O, mask: syscall.OLCUC}, "xcase": {word: L, mask: syscall.XCASE}, diff --git a/pkg/termios/var_unix.go b/pkg/termios/var_unix.go index b62a12980e..185b4be771 100644 --- a/pkg/termios/var_unix.go +++ b/pkg/termios/var_unix.go @@ -41,7 +41,7 @@ var ( "imaxbel": {word: I, mask: syscall.IMAXBEL}, "iutf8": {word: I, mask: syscall.IUTF8}, - //Outputprocessing + // Outputprocessing "opost": {word: O, mask: syscall.OPOST}, "onlcr": {word: O, mask: syscall.ONLCR}, "ocrnl": {word: O, mask: syscall.OCRNL}, @@ -50,7 +50,7 @@ var ( "ofill": {word: O, mask: syscall.OFILL}, "ofdel": {word: O, mask: syscall.OFDEL}, - //Localprocessing + // Localprocessing "isig": {word: L, mask: syscall.ISIG}, "icanon": {word: L, mask: syscall.ICANON}, "echo": {word: L, mask: syscall.ECHO}, @@ -66,7 +66,7 @@ var ( "pendin": {word: L, mask: syscall.PENDIN}, "iexten": {word: L, mask: syscall.IEXTEN}, - //Controlprocessing + // Controlprocessing "cstopb": {word: C, mask: syscall.CSTOPB}, "cread": {word: C, mask: syscall.CREAD}, diff --git a/pkg/testutil/stdin.go b/pkg/testutil/stdin.go index 18e33ccfc6..2f97f2c1bc 100644 --- a/pkg/testutil/stdin.go +++ b/pkg/testutil/stdin.go @@ -14,7 +14,7 @@ type FakeStdin struct { // NewFakeStdin creates new FakeStdin value with given answers. func NewFakeStdin(answers ...string) *FakeStdin { - var fs = FakeStdin{answers: make([]string, len(answers))} + fs := FakeStdin{answers: make([]string, len(answers))} for i, a := range answers { fs.answers[i] = a + "\n" } diff --git a/pkg/tss/capabilities.go b/pkg/tss/capabilities.go index f0995f1a28..4e0c4ce5ea 100644 --- a/pkg/tss/capabilities.go +++ b/pkg/tss/capabilities.go @@ -16,7 +16,6 @@ import ( ) func readTPM12Information(rwc io.ReadWriter) (TPMInfo, error) { - manufacturerRaw, err := tpm1.GetManufacturer(rwc) if err != nil { return TPMInfo{}, err diff --git a/pkg/tss/nvram.go b/pkg/tss/nvram.go index 1f64864bc3..d2a1310b6b 100644 --- a/pkg/tss/nvram.go +++ b/pkg/tss/nvram.go @@ -15,7 +15,7 @@ import ( ) func nvRead12(rwc io.ReadWriteCloser, index, offset, len uint32, auth string) ([]byte, error) { - var ownAuth [20]byte //owner well known + var ownAuth [20]byte // owner well known if auth != "" { ownAuth = sha1.Sum([]byte(auth)) } diff --git a/pkg/tss/structures.go b/pkg/tss/structures.go index 3296bf2ddf..ee7c11c3b6 100644 --- a/pkg/tss/structures.go +++ b/pkg/tss/structures.go @@ -14,7 +14,6 @@ import ( type TCGVendorID uint32 func (id TCGVendorID) String() string { - s, ok := vendors[id] if !ok { return fmt.Sprintf("unknown TPM vendor (%d)", id) diff --git a/pkg/txtlog/txtlog.go b/pkg/txtlog/txtlog.go index 9311fe0f5e..72ad3bdb2c 100644 --- a/pkg/txtlog/txtlog.go +++ b/pkg/txtlog/txtlog.go @@ -183,7 +183,7 @@ func readTPM2Log(firmware FirmwareType) (*PCRLog, error) { } func getTaggedEvent(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var taggedEvent TCGPCClientTaggedEvent if err := binary.Read(eventReader, binary.LittleEndian, &taggedEvent.taggedEventID); err != nil { @@ -204,7 +204,7 @@ func getTaggedEvent(eventData []byte) (*string, error) { } func getHandoffTablePointers(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var handoffTablePointers EFIHandoffTablePointers if err := binary.Read(eventReader, binary.LittleEndian, &handoffTablePointers.numberOfTables); err != nil { @@ -247,7 +247,7 @@ func getHandoffTablePointers(eventData []byte) (*string, error) { } func getPlatformFirmwareBlob(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var platformFirmwareBlob EFIPlatformFirmwareBlob if err := binary.Read(eventReader, binary.LittleEndian, &platformFirmwareBlob.blobBase); err != nil { @@ -263,7 +263,7 @@ func getPlatformFirmwareBlob(eventData []byte) (*string, error) { } func getGPTEventString(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var gptEvent EFIGptData if err := binary.Read(eventReader, binary.LittleEndian, &gptEvent.uefiPartitionHeader.Signature); err != nil { @@ -310,7 +310,7 @@ func getGPTEventString(eventData []byte) (*string, error) { } func getImageLoadEventString(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var imageLoadEvent EFIImageLoadEvent if err := binary.Read(eventReader, binary.LittleEndian, &imageLoadEvent.imageLocationInMemory); err != nil { @@ -338,7 +338,7 @@ func getImageLoadEventString(eventData []byte) (*string, error) { } func getVariableDataString(eventData []byte) (*string, error) { - var eventReader = bytes.NewReader(eventData) + eventReader := bytes.NewReader(eventData) var variableData EFIVariableData if err := binary.Read(eventReader, binary.LittleEndian, &variableData.variableName.blockA); err != nil { diff --git a/pkg/uefivars/boot/boot.go b/pkg/uefivars/boot/boot.go index d0419e1ed1..b16a438d58 100644 --- a/pkg/uefivars/boot/boot.go +++ b/pkg/uefivars/boot/boot.go @@ -24,7 +24,7 @@ const ( // BootEntryVar is a boot entry. It will have the name BootXXXX where XXXX is // hexadecimal. type BootEntryVar struct { - Number uint16 //from the var name + Number uint16 // from the var name EfiLoadOption } @@ -77,7 +77,7 @@ func (b BootEntryVar) String() string { // BootCurrent, BootOptionSupport, BootNext, BootOrder, etc do not count as // boot entries. func AllBootEntryVars() BootEntryVars { - //BootEntries() is somewhat redundant, but parses the vars into BootEntryVar{} + // BootEntries() is somewhat redundant, but parses the vars into BootEntryVar{} return BootEntries(uefivars.ReadVars(BootEntryFilter)) } @@ -107,7 +107,7 @@ func BootEntryFilter(uuid, name string) bool { return false } // Boot entries begin with BootXXXX-, where XXXX is hex. - //First, check for the dash. + // First, check for the dash. if len(name) != 8 { return false } @@ -127,7 +127,7 @@ func BootVar(v uefivars.EfiVar) (b *BootEntryVar) { b.Attributes = binary.LittleEndian.Uint32(v.Data[:4]) b.FilePathListLength = binary.LittleEndian.Uint16(v.Data[4:6]) - //Description is null-terminated utf16 + // Description is null-terminated utf16 var i uint16 for i = 6; ; i += 2 { if v.Data[i] == 0 { diff --git a/pkg/uefivars/boot/boot_test.go b/pkg/uefivars/boot/boot_test.go index f3bfc4d79c..962c9a2dab 100644 --- a/pkg/uefivars/boot/boot_test.go +++ b/pkg/uefivars/boot/boot_test.go @@ -27,7 +27,7 @@ func TestMain(m *testing.M) { os.Exit(m.Run()) } -//func ReadBootVar(num uint16) (b BootVar) +// func ReadBootVar(num uint16) (b BootVar) func TestReadBootVar(t *testing.T) { var n uint16 var strs []string @@ -45,7 +45,7 @@ func TestReadBootVar(t *testing.T) { } } -//func AllBootEntryVars() (list []BootEntryVar) +// func AllBootEntryVars() (list []BootEntryVar) func TestAllBootEntryVars(t *testing.T) { bevs := AllBootEntryVars() if len(bevs) != 11 { @@ -56,7 +56,7 @@ func TestAllBootEntryVars(t *testing.T) { } } -//func AllBootVars() (list EfiVars) +// func AllBootVars() (list EfiVars) func TestAllBootVars(t *testing.T) { n := 14 bvs := AllBootVars() @@ -67,7 +67,7 @@ func TestAllBootVars(t *testing.T) { if len(be) != n-3 { t.Errorf("expected %d entries, got %d", n-3, len(be)) } - //find boot vars that are not boot entries + // find boot vars that are not boot entries nbe := bvs.Filter(uefivars.NotFilter(BootEntryFilter)) want := []string{"BootCurrent", "BootOptionSupport", "BootOrder"} if len(nbe) != len(want) { @@ -81,7 +81,7 @@ func TestAllBootVars(t *testing.T) { } } -//func ReadCurrentBootVar() (b *BootEntryVar) +// func ReadCurrentBootVar() (b *BootEntryVar) func TestReadCurrentBootVar(t *testing.T) { v, err := ReadCurrentBootVar() if err != nil { @@ -99,7 +99,7 @@ func TestReadCurrentBootVar(t *testing.T) { } } -//func BootCurrent(vars uefivars.EfiVars) *BootCurrentVar +// func BootCurrent(vars uefivars.EfiVars) *BootCurrentVar func TestBootCurrent(t *testing.T) { bc := BootCurrent(AllBootVars()) if bc == nil { diff --git a/pkg/uefivars/boot/efiDevicePathProtocol.go b/pkg/uefivars/boot/efiDevicePathProtocol.go index f8349decb4..a658863963 100644 --- a/pkg/uefivars/boot/efiDevicePathProtocol.go +++ b/pkg/uefivars/boot/efiDevicePathProtocol.go @@ -134,7 +134,7 @@ loop: return nil, err } case DppTypeEnd: - //should be last item on list + // should be last item on list reachedEnd = true st := EfiDppEndSubType(h.ProtoSubType) if st != DppETypeEndEntire { @@ -215,11 +215,11 @@ type EfiDevicePathProtocolHdr struct { type EfiDevPathProtoType uint8 const ( - DppTypeHw EfiDevPathProtoType = iota + 1 //0x01, pg 288 - DppTypeACPI //0x02, pg 290 - DppTypeMessaging //0x03, pg 293 - DppTypeMedia //0x04, pg 319 - DppTypeBBS //0x05, pg 287 + DppTypeHw EfiDevPathProtoType = iota + 1 // 0x01, pg 288 + DppTypeACPI // 0x02, pg 290 + DppTypeMessaging // 0x03, pg 293 + DppTypeMedia // 0x04, pg 319 + DppTypeBBS // 0x05, pg 287 DppTypeEnd EfiDevPathProtoType = 0x7f ) @@ -247,8 +247,8 @@ type EfiDevPathProtoSubType uint8 type EfiDppEndSubType EfiDevPathProtoSubType const ( - //DppTypeEnd, pg 287-288 - DppETypeEndStartNew EfiDppEndSubType = 0x01 //only for DppTypeHw? + // DppTypeEnd, pg 287-288 + DppETypeEndStartNew EfiDppEndSubType = 0x01 // only for DppTypeHw? DppETypeEndEntire EfiDppEndSubType = 0xff ) diff --git a/pkg/uefivars/boot/efiDevicePathProtocol_test.go b/pkg/uefivars/boot/efiDevicePathProtocol_test.go index 3d33b3eeb6..b054a34b8d 100644 --- a/pkg/uefivars/boot/efiDevicePathProtocol_test.go +++ b/pkg/uefivars/boot/efiDevicePathProtocol_test.go @@ -26,7 +26,7 @@ var boot7 = []byte{ 0x49, 0x00, 0x00, 0x00, 0x7f, 0xff, 0x04, 0x00, 0x00, 0x00, 0x42, 0x4f, } -//func ParseFilePathList(in []byte) (EfiDevicePathProtocolList, error) +// func ParseFilePathList(in []byte) (EfiDevicePathProtocolList, error) func TestParseFilePathList(t *testing.T) { // When this test runs, you will see log entries like // "Skipping loop0: open /dev/loop0: permission denied" @@ -39,7 +39,7 @@ func TestParseFilePathList(t *testing.T) { } b := BootVar(e) - //same as efibootmgr output, except using forward slashes + // same as efibootmgr output, except using forward slashes wantpath := "HD(1,GPT,81635ccd-1b4f-4d3f-b7b8-f78a5b029f35,0x40,0xf000)/File(/EFI/BOOT/BOOTX64.EFI)" gotpath := b.FilePathList.String() if gotpath != wantpath { diff --git a/pkg/uefivars/boot/efiDppACPI.go b/pkg/uefivars/boot/efiDppACPI.go index b9407113ad..8123de1d45 100644 --- a/pkg/uefivars/boot/efiDppACPI.go +++ b/pkg/uefivars/boot/efiDppACPI.go @@ -39,7 +39,7 @@ func (e EfiDppACPISubType) String() string { // DppAcpiDevPath is an acpi device path. type DppAcpiDevPath struct { Hdr EfiDevicePathProtocolHdr - HID, UID []byte //both length 4; not sure of endianness + HID, UID []byte // both length 4; not sure of endianness } var _ EfiDevicePathProtocol = (*DppAcpiDevPath)(nil) @@ -72,7 +72,7 @@ func (e *DppAcpiDevPath) Resolver() (EfiPathSegmentResolver, error) { return nil // DppAcpiExDevPath is an expanded dpp acpi device path. type DppAcpiExDevPath struct { Hdr EfiDevicePathProtocolHdr - HID, UID, CID []byte //all length 4; not sure of endianness + HID, UID, CID []byte // all length 4; not sure of endianness HIDSTR, UIDSTR, CIDSTR string } diff --git a/pkg/uefivars/boot/efiDppACPI_test.go b/pkg/uefivars/boot/efiDppACPI_test.go index ffb42da02d..bc89d06e16 100644 --- a/pkg/uefivars/boot/efiDppACPI_test.go +++ b/pkg/uefivars/boot/efiDppACPI_test.go @@ -11,14 +11,14 @@ import ( "testing" ) -//func ParseDppAcpiExDevPath(h EfiDevicePathProtocolHdr, b []byte) (*DppAcpiExDevPath, error) +// func ParseDppAcpiExDevPath(h EfiDevicePathProtocolHdr, b []byte) (*DppAcpiExDevPath, error) func TestParseDppAcpiExDevPath(t *testing.T) { in := []byte{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, } - //not sure what's supposed to go into these fields, so use made-up values + // not sure what's supposed to go into these fields, so use made-up values in = append(in, cstr("HIDSTR")...) in = append(in, cstr("UIDSTR")...) in = append(in, cstr("CIDSTR")...) @@ -47,7 +47,7 @@ func TestParseDppAcpiExDevPath(t *testing.T) { func cstr(s string) []byte { return append([]byte(s), 0) } -//func ParseDppAcpiDevPath(h EfiDevicePathProtocolHdr, b []byte) (*DppAcpiDevPath, error) +// func ParseDppAcpiDevPath(h EfiDevicePathProtocolHdr, b []byte) (*DppAcpiDevPath, error) func TestParseDppAcpiDevPath(t *testing.T) { in := []byte{ 0, 0, 0, 1, diff --git a/pkg/uefivars/boot/efiDppHardware_test.go b/pkg/uefivars/boot/efiDppHardware_test.go index 938bd8373a..08e4e5bb59 100644 --- a/pkg/uefivars/boot/efiDppHardware_test.go +++ b/pkg/uefivars/boot/efiDppHardware_test.go @@ -11,7 +11,7 @@ import ( "testing" ) -//func ParseDppHwPci(h EfiDevicePathProtocolHdr, b []byte) (*DppHwPci, error) +// func ParseDppHwPci(h EfiDevicePathProtocolHdr, b []byte) (*DppHwPci, error) func TestParseDppHwPci(t *testing.T) { in := []byte{3, 4} hdr := EfiDevicePathProtocolHdr{ diff --git a/pkg/uefivars/boot/efiDppMedia.go b/pkg/uefivars/boot/efiDppMedia.go index 31ac9337fe..0ff6fd5183 100644 --- a/pkg/uefivars/boot/efiDppMedia.go +++ b/pkg/uefivars/boot/efiDppMedia.go @@ -22,16 +22,16 @@ import ( type EfiDppMediaSubType EfiDevPathProtoSubType const ( - //DppTypeMedia, pg 319 + - DppMTypeHdd EfiDppMediaSubType = iota + 1 //0x01 - DppMTypeCd //0x02 - DppMTypeVendor //0x03 - DppMTypeFilePath //0x04 //p321 - DppMTypeMedia //0x05 //media protocol i.e. filesystem format?? - DppMTypePIWGFF //0x06 - DppMTypePIWGFV //0x07 - DppMTypeRelOff //0x08 - DppMTypeRAM //0x09 + // DppTypeMedia, pg 319 + + DppMTypeHdd EfiDppMediaSubType = iota + 1 // 0x01 + DppMTypeCd // 0x02 + DppMTypeVendor // 0x03 + DppMTypeFilePath // 0x04 //p321 + DppMTypeMedia // 0x05 //media protocol i.e. filesystem format?? + DppMTypePIWGFF // 0x06 + DppMTypePIWGFV // 0x07 + DppMTypeRelOff // 0x08 + DppMTypeRAM // 0x09 ) var efiDppMediaSubTypeStrings = map[EfiDppMediaSubType]string{ @@ -57,12 +57,12 @@ func (e EfiDppMediaSubType) String() string { type DppMediaHDD struct { Hdr EfiDevicePathProtocolHdr - PartNum uint32 //index into partition table for MBR or GPT; 0 indicates entire disk - PartStart uint64 //starting LBA. only used for MBR? - PartSize uint64 //size in LB's. only used for MBR? - PartSig uefivars.MixedGUID //format determined by SigType below. unused bytes must be 0x0. - PartFmt uint8 //0x01 for MBR, 0x02 for GPT - SigType uint8 //0x00 - none; 0x01 - 32bit MBR sig (@ 0x1b8); 0x02 - GUID + PartNum uint32 // index into partition table for MBR or GPT; 0 indicates entire disk + PartStart uint64 // starting LBA. only used for MBR? + PartSize uint64 // size in LB's. only used for MBR? + PartSig uefivars.MixedGUID // format determined by SigType below. unused bytes must be 0x0. + PartFmt uint8 // 0x01 for MBR, 0x02 for GPT + SigType uint8 // 0x00 - none; 0x01 - 32bit MBR sig (@ 0x1b8); 0x02 - GUID } var _ EfiDevicePathProtocol = (*DppMediaHDD)(nil) @@ -77,7 +77,7 @@ func ParseDppMediaHdd(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaHDD, error PartNum: binary.LittleEndian.Uint32(b[:4]), PartStart: binary.LittleEndian.Uint64(b[4:12]), PartSize: binary.LittleEndian.Uint64(b[12:20]), - //PartSig: b[20:36], //cannot assign slice to array + // PartSig: b[20:36], //cannot assign slice to array PartFmt: b[36], SigType: b[37], } @@ -125,7 +125,7 @@ func (e *DppMediaHDD) Resolver() (EfiPathSegmentResolver, error) { return &HddResolver{BlockDev: blocks[0]}, nil } -//return the partition table type as a string +// return the partition table type as a string func (e *DppMediaHDD) pttype() string { switch e.PartFmt { case 1: @@ -137,12 +137,12 @@ func (e *DppMediaHDD) pttype() string { } } -//return the signature as a string +// return the signature as a string func (e *DppMediaHDD) sig() string { switch e.SigType { - case 1: //32-bit MBR sig + case 1: // 32-bit MBR sig return fmt.Sprintf("%x", binary.LittleEndian.Uint32(e.PartSig[:4])) - case 2: //GUID + case 2: // GUID return e.PartSig.ToStdEnc().String() default: return "(NO SIG)" @@ -155,7 +155,7 @@ func (e *DppMediaHDD) sig() string { type DppMediaFilePath struct { Hdr EfiDevicePathProtocolHdr - PathNameDecoded string //stored as utf16 + PathNameDecoded string // stored as utf16 } var _ EfiDevicePathProtocol = (*DppMediaFilePath)(nil) @@ -168,7 +168,7 @@ func ParseDppMediaFilePath(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaFileP if err != nil { return nil, err } - //remove null termination byte, replace windows slashes + // remove null termination byte, replace windows slashes path = strings.TrimSuffix(path, "\000") path = strings.Replace(path, "\\", string(os.PathSeparator), -1) fp := &DppMediaFilePath{ @@ -196,7 +196,7 @@ func (e *DppMediaFilePath) Resolver() (EfiPathSegmentResolver, error) { return &pr, nil } -//struct in EfiDevicePathProtocol for DppMTypePIWGFV +// struct in EfiDevicePathProtocol for DppMTypePIWGFV type DppMediaPIWGFV struct { Hdr EfiDevicePathProtocolHdr Fv []byte @@ -234,7 +234,7 @@ func (e *DppMediaPIWGFV) Resolver() (EfiPathSegmentResolver, error) { return nil, ErrUnimpl } -//struct in EfiDevicePathProtocol for DppMTypePIWGFF +// struct in EfiDevicePathProtocol for DppMTypePIWGFF type DppMediaPIWGFF struct { Hdr EfiDevicePathProtocolHdr Ff []byte diff --git a/pkg/uefivars/boot/efiDppMedia_test.go b/pkg/uefivars/boot/efiDppMedia_test.go index d4786fc725..3381f4f965 100644 --- a/pkg/uefivars/boot/efiDppMedia_test.go +++ b/pkg/uefivars/boot/efiDppMedia_test.go @@ -13,7 +13,7 @@ import ( "unicode/utf16" ) -//func ParseDppMediaHdd(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaHDD, error) +// func ParseDppMediaHdd(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaHDD, error) func TestParseDppMediaHdd(t *testing.T) { in := []byte{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, @@ -41,10 +41,10 @@ func TestParseDppMediaHdd(t *testing.T) { } } -//func ParseDppMediaFilePath(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaFilePath, error) +// func ParseDppMediaFilePath(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaFilePath, error) func TestParseDppMediaFilePath(t *testing.T) { str := `blah\blah\blah.efi` - //convert to utf16 ([]uint16) + // convert to utf16 ([]uint16) u16 := utf16.Encode([]rune(str)) //...and then to []byte var in []byte @@ -72,7 +72,7 @@ func TestParseDppMediaFilePath(t *testing.T) { } } -//func ParseDppMediaPIWGFV(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaPIWGFV, error) +// func ParseDppMediaPIWGFV(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaPIWGFV, error) func TestParseDppMediaPIWGFV(t *testing.T) { in := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} hdr := EfiDevicePathProtocolHdr{ @@ -96,7 +96,7 @@ func TestParseDppMediaPIWGFV(t *testing.T) { } } -//func ParseDppMediaPIWGFF(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaPIWGFF, error) +// func ParseDppMediaPIWGFF(h EfiDevicePathProtocolHdr, b []byte) (*DppMediaPIWGFF, error) func TestParseDppMediaPIWGFF(t *testing.T) { in := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} hdr := EfiDevicePathProtocolHdr{ diff --git a/pkg/uefivars/boot/efiDppMessage.go b/pkg/uefivars/boot/efiDppMessage.go index 692482dbb4..bd4f586b11 100644 --- a/pkg/uefivars/boot/efiDppMessage.go +++ b/pkg/uefivars/boot/efiDppMessage.go @@ -16,38 +16,38 @@ type EfiDppMsgSubType EfiDevPathProtoSubType const ( DppMsgTypeATAPI EfiDppMsgSubType = iota + 1 - DppMsgTypeSCSI //2 - DppMsgTypeFibreCh //3 - DppMsgTypeFirewire //4 - DppMsgTypeUSB //5 - DppMsgTypeIIO //6 - _ //7 - _ //8 - DppMsgTypeInfiniband //9 - DppMsgTypeVendor //10 //uart flow control, sas are subtypes - DppMsgTypeMAC //11 - DppMsgTypeIP4 //12 - DppMsgTypeIP6 //13 - DppMsgTypeUART //14 - DppMsgTypeUSBClass //15 - DppMsgTypeUSBWWID //16 - DppMsgTypeDevLU //17 - DppMsgTypeSATA //18 - DppMsgTypeISCSI //19 - DppMsgTypeVLAN //20 - _ //21 - DppMsgTypeSASEx //22 - DppMsgTypeNVME //23 - DppMsgTypeURI //24 - DppMsgTypeUFS //25 - DppMsgTypeSD //26 - DppMsgTypeBT //27 - DppMsgTypeWiFi //28 - DppMsgTypeeMMC //29 - DppMsgTypeBLE //30 - DppMsgTypeDNS //31 - DppMsgTypeNVDIMM //32 - DppMsgTypeRest //documented as 32, likely 33 + DppMsgTypeSCSI // 2 + DppMsgTypeFibreCh // 3 + DppMsgTypeFirewire // 4 + DppMsgTypeUSB // 5 + DppMsgTypeIIO // 6 + _ // 7 + _ // 8 + DppMsgTypeInfiniband // 9 + DppMsgTypeVendor // 10 //uart flow control, sas are subtypes + DppMsgTypeMAC // 11 + DppMsgTypeIP4 // 12 + DppMsgTypeIP6 // 13 + DppMsgTypeUART // 14 + DppMsgTypeUSBClass // 15 + DppMsgTypeUSBWWID // 16 + DppMsgTypeDevLU // 17 + DppMsgTypeSATA // 18 + DppMsgTypeISCSI // 19 + DppMsgTypeVLAN // 20 + _ // 21 + DppMsgTypeSASEx // 22 + DppMsgTypeNVME // 23 + DppMsgTypeURI // 24 + DppMsgTypeUFS // 25 + DppMsgTypeSD // 26 + DppMsgTypeBT // 27 + DppMsgTypeWiFi // 28 + DppMsgTypeeMMC // 29 + DppMsgTypeBLE // 30 + DppMsgTypeDNS // 31 + DppMsgTypeNVDIMM // 32 + DppMsgTypeRest // documented as 32, likely 33 ) var efiDppMsgSubTypeStrings = map[EfiDppMsgSubType]string{ @@ -135,8 +135,8 @@ func (e *DppMsgATAPI) Resolver() (EfiPathSegmentResolver, error) { // pg 300 type DppMsgMAC struct { Hdr EfiDevicePathProtocolHdr - Mac [32]byte //0-padded - IfType uint8 //RFC3232; seems ethernet is 6 + Mac [32]byte // 0-padded + IfType uint8 // RFC3232; seems ethernet is 6 } // ParseDppMsgMAC parses input into a DppMsgMAC. @@ -146,7 +146,7 @@ func ParseDppMsgMAC(h EfiDevicePathProtocolHdr, b []byte) (*DppMsgMAC, error) { } mac := &DppMsgMAC{ Hdr: h, - //Mac: b[:32], + // Mac: b[:32], IfType: b[32], } copy(mac.Mac[:], b[:32]) diff --git a/pkg/uefivars/boot/efiDppMessage_test.go b/pkg/uefivars/boot/efiDppMessage_test.go index 68d311dee5..1082e8354a 100644 --- a/pkg/uefivars/boot/efiDppMessage_test.go +++ b/pkg/uefivars/boot/efiDppMessage_test.go @@ -11,7 +11,7 @@ import ( "testing" ) -//func ParseDppMsgATAPI(h EfiDevicePathProtocolHdr, b []byte) (*DppMsgATAPI, error) +// func ParseDppMsgATAPI(h EfiDevicePathProtocolHdr, b []byte) (*DppMsgATAPI, error) func TestParseDppMsgATAPI(t *testing.T) { in := []byte{0, 1, 2, 3} hdr := EfiDevicePathProtocolHdr{ @@ -35,7 +35,7 @@ func TestParseDppMsgATAPI(t *testing.T) { } } -//func ParseDppMsgMAC(h EfiDevicePathProtocolHdr, b []byte) (*DppMsgMAC, error) +// func ParseDppMsgMAC(h EfiDevicePathProtocolHdr, b []byte) (*DppMsgMAC, error) func TestParseDppMsgMAC(t *testing.T) { in := []byte{ 0x00, 0x26, 0xfd, 0x00, 0x26, 0xfd, 0x00, 0x00, diff --git a/pkg/uefivars/boot/efiDppResolver.go b/pkg/uefivars/boot/efiDppResolver.go index fbc13cc581..b7874ea0ff 100644 --- a/pkg/uefivars/boot/efiDppResolver.go +++ b/pkg/uefivars/boot/efiDppResolver.go @@ -19,19 +19,19 @@ import ( ) type EfiPathSegmentResolver interface { - //Returns description, does not require cleanup + // Returns description, does not require cleanup String() string - //Mount fs, etc. You must call Cleanup() eventually. + // Mount fs, etc. You must call Cleanup() eventually. Resolve(suggestedBasePath string) (string, error) - //For devices, returns BlockDev. Returns nil otherwise. + // For devices, returns BlockDev. Returns nil otherwise. BlockInfo() *block.BlockDev - //For mounted devices, returns MountPoint. Returns nil otherwise. + // For mounted devices, returns MountPoint. Returns nil otherwise. MntPoint() *mount.MountPoint - //Unmount fs, free resources, etc + // Unmount fs, free resources, etc Cleanup() error } @@ -62,7 +62,7 @@ func (r *HddResolver) Resolve(basePath string) (string, error) { if err != nil { return "", err } - err = os.MkdirAll(basePath, 0755) + err = os.MkdirAll(basePath, 0o755) if err != nil { return "", err } diff --git a/pkg/uefivars/boot/fuzz.go b/pkg/uefivars/boot/fuzz.go index 73a8dd6cfc..9fdebbb8b5 100644 --- a/pkg/uefivars/boot/fuzz.go +++ b/pkg/uefivars/boot/fuzz.go @@ -27,15 +27,15 @@ go-fuzz -bin=./boot-fuzz.zip -workdir=fuzz var tmpdir = "/tmp/fuzz-resolve-workdir" func init() { - //divert logging - greatly increases exec speed - null, err := os.OpenFile("/dev/null", os.O_WRONLY, 0200) + // divert logging - greatly increases exec speed + null, err := os.OpenFile("/dev/null", os.O_WRONLY, 0o200) if err != nil { panic(err) } log.SetOutput(null) log.SetFlags(0) - err = os.MkdirAll(tmpdir, 0755) + err = os.MkdirAll(tmpdir, 0o755) if err != nil { panic(err) } diff --git a/pkg/uefivars/boot/fuzz_test.go b/pkg/uefivars/boot/fuzz_test.go index 232647f294..9b1e1d08b6 100644 --- a/pkg/uefivars/boot/fuzz_test.go +++ b/pkg/uefivars/boot/fuzz_test.go @@ -32,12 +32,12 @@ func TestFuzzInputs(t *testing.T) { // it is very low value, essentially inflating the coverage numbers. t.Skip("this test will inflate coverage") } - //restore log behavior at end + // restore log behavior at end logOut := log.Writer() defer log.SetOutput(logOut) - //no logging output for this test, to increase speed - null, err := os.OpenFile("/dev/null", os.O_WRONLY, 0200) + // no logging output for this test, to increase speed + null, err := os.OpenFile("/dev/null", os.O_WRONLY, 0o200) if err != nil { panic(err) } @@ -60,7 +60,7 @@ func TestFuzzInputs(t *testing.T) { if err != nil { t.Error(err) } - //ignore any errors - just catch crashes + // ignore any errors - just catch crashes list, err := ParseFilePathList(data) if err != nil { return diff --git a/pkg/uefivars/vars.go b/pkg/uefivars/vars.go index 4b57925389..ff941f0cd3 100644 --- a/pkg/uefivars/vars.go +++ b/pkg/uefivars/vars.go @@ -19,7 +19,7 @@ import ( "unicode/utf8" ) -//http://kurtqiao.github.io/uefi/2015/01/13/uefi-boot-manager.html +// http://kurtqiao.github.io/uefi/2015/01/13/uefi-boot-manager.html // EfiVarDir is the sysfs /sys/firmware/efi/vars directory, which can be overridden for testing. var EfiVarDir = "/sys/firmware/efi/vars" diff --git a/pkg/uefivars/vars_test.go b/pkg/uefivars/vars_test.go index f69971eccf..8a3de1126b 100644 --- a/pkg/uefivars/vars_test.go +++ b/pkg/uefivars/vars_test.go @@ -11,7 +11,7 @@ import ( "testing" ) -//func AllVars() EfiVars +// func AllVars() EfiVars func TestAllVars(t *testing.T) { n := 32 vars := AllVars() @@ -20,7 +20,7 @@ func TestAllVars(t *testing.T) { } } -//func DecodeUTF16(b []byte) (string, error) +// func DecodeUTF16(b []byte) (string, error) func TestDecodeUTF16(t *testing.T) { want := "TEST" got, err := DecodeUTF16([]byte{84, 0, 69, 0, 83, 0, 84, 0}) @@ -32,7 +32,7 @@ func TestDecodeUTF16(t *testing.T) { } } -//func (vars EfiVars) Filter(filt VarFilter) EfiVars +// func (vars EfiVars) Filter(filt VarFilter) EfiVars func TestFilter(t *testing.T) { filt := func(_, _ string) bool { return true } v := AllVars() diff --git a/pkg/uio/reader.go b/pkg/uio/reader.go index 8dd75eba2c..15ebc6267d 100644 --- a/pkg/uio/reader.go +++ b/pkg/uio/reader.go @@ -53,7 +53,7 @@ func ReaderAtEqual(r1, r2 io.ReaderAt) bool { // If the file at given path does not exist, a new file will be created. // If the file exists at the given path, but not empty, it will be truncated. func ReadIntoFile(r io.Reader, p string) error { - f, err := os.OpenFile(p, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644) + f, err := os.OpenFile(p, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0o644) if err != nil { return err } diff --git a/pkg/uio/reader_test.go b/pkg/uio/reader_test.go index c22367b5dc..1740e30f41 100644 --- a/pkg/uio/reader_test.go +++ b/pkg/uio/reader_test.go @@ -40,7 +40,7 @@ func TestReadIntoFile(t *testing.T) { // Write to a file already exist. p := filepath.Join(dir, "uio-out") // Expect net effect to be creating a new empty file: "uio-out". - f, err := os.OpenFile(p, os.O_RDONLY|os.O_CREATE|os.O_TRUNC, 0755) + f, err := os.OpenFile(p, os.O_RDONLY|os.O_CREATE|os.O_TRUNC, 0o755) if err != nil { t.Fatal(err) } @@ -55,7 +55,7 @@ func TestReadIntoFile(t *testing.T) { // Write to an existing file that has pre-existing content. p = filepath.Join(dir, "uio-out-prexist-content") - f, err = os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) + f, err = os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755) if err != nil { t.Fatal(err) } diff --git a/pkg/ulog/log_linux_test.go b/pkg/ulog/log_linux_test.go index af01825ede..4c2212d4ed 100644 --- a/pkg/ulog/log_linux_test.go +++ b/pkg/ulog/log_linux_test.go @@ -27,5 +27,4 @@ func TestKernelLog(t *testing.T) { if got := string(b[:n]); strings.Contains(got, want) { t.Errorf("kernel log read = %v (len %d), want it to include %v", got, n, want) } - } diff --git a/pkg/upath/symlink_test.go b/pkg/upath/symlink_test.go index 2c9c2b18c9..8cb0292150 100644 --- a/pkg/upath/symlink_test.go +++ b/pkg/upath/symlink_test.go @@ -19,11 +19,11 @@ func TestSymlink(t *testing.T) { } for _, n := range []string{"bin", "buildbin"} { p := filepath.Join(td, n) - if err := os.Mkdir(p, 0777); err != nil { + if err := os.Mkdir(p, 0o777); err != nil { log.Fatal(err) } } - var tab = []struct { + tab := []struct { s, t, v string }{ {filepath.Join(td, "bin/ash"), "sh", filepath.Join(td, "buildbin/elvish")}, @@ -50,7 +50,7 @@ func TestSymlink(t *testing.T) { } // test to make sure a plain file gives a reasonable result. ic := filepath.Join(td, "x") - if err := ioutil.WriteFile(ic, nil, 0666); err != nil { + if err := ioutil.WriteFile(ic, nil, 0o666); err != nil { t.Fatalf("WriteFile %v: got %v, want nil", ic, err) } v := ResolveUntilLastSymlink(ic) @@ -58,5 +58,4 @@ func TestSymlink(t *testing.T) { if v != ic { t.Errorf("ResolveUntilLastSymlink %v: got %v want %v", ic, v, ic) } - } diff --git a/pkg/upath/urootpath_test.go b/pkg/upath/urootpath_test.go index 56ee62c856..c46a6bd531 100644 --- a/pkg/upath/urootpath_test.go +++ b/pkg/upath/urootpath_test.go @@ -9,7 +9,7 @@ import ( ) func TestUrootPath(t *testing.T) { - var tests = []struct { + tests := []struct { name string urootRoot string out string diff --git a/pkg/uroot/builder/bb.go b/pkg/uroot/builder/bb.go index c54807f08c..4ac2b3dea7 100644 --- a/pkg/uroot/builder/bb.go +++ b/pkg/uroot/builder/bb.go @@ -71,7 +71,7 @@ func (b BBBuilder) Build(af *initramfs.Files, opts Opts) error { // Or add a #! file if b.ShellBang is set ... if b.ShellBang { b := path.Base(pkg) - if err := af.AddRecord(cpio.StaticFile(filepath.Join(opts.BinaryDir, b), "#!/bbin/bb #!"+b+"\n", 0755)); err != nil { + if err := af.AddRecord(cpio.StaticFile(filepath.Join(opts.BinaryDir, b), "#!/bbin/bb #!"+b+"\n", 0o755)); err != nil { return err } } else if err := af.AddRecord(cpio.Symlink(filepath.Join(opts.BinaryDir, path.Base(pkg)), "bb")); err != nil { diff --git a/pkg/uroot/builder/bb_test.go b/pkg/uroot/builder/bb_test.go index ff9617a422..7a74cd0501 100644 --- a/pkg/uroot/builder/bb_test.go +++ b/pkg/uroot/builder/bb_test.go @@ -35,7 +35,7 @@ func TestBBBuild(t *testing.T) { t.Error(err) } - var mustContain = []string{ + mustContain := []string{ "bbin/elvish", "bbin/foo", } @@ -44,5 +44,4 @@ func TestBBBuild(t *testing.T) { t.Errorf("expected files to include %q; archive: %v", name, af) } } - } diff --git a/pkg/uroot/initramfs/cpio.go b/pkg/uroot/initramfs/cpio.go index 251794b426..5559051f1d 100644 --- a/pkg/uroot/initramfs/cpio.go +++ b/pkg/uroot/initramfs/cpio.go @@ -24,7 +24,7 @@ func (ca CPIOArchiver) OpenWriter(l ulog.Logger, path string) (Writer, error) { if len(path) == 0 { return nil, fmt.Errorf("path is required") } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return nil, err } diff --git a/pkg/uroot/initramfs/dir.go b/pkg/uroot/initramfs/dir.go index 6c15b93d66..1c2cb88bb8 100644 --- a/pkg/uroot/initramfs/dir.go +++ b/pkg/uroot/initramfs/dir.go @@ -36,7 +36,7 @@ func (da DirArchiver) OpenWriter(l ulog.Logger, path string) (Writer, error) { if _, err := os.Stat(path); os.IsExist(err) { return nil, fmt.Errorf("path %q already exists", path) } - if err := os.MkdirAll(path, 0755); err != nil { + if err := os.MkdirAll(path, 0o755); err != nil { return nil, err } } diff --git a/pkg/uroot/initramfs/files.go b/pkg/uroot/initramfs/files.go index 52c62135a6..906b893105 100644 --- a/pkg/uroot/initramfs/files.go +++ b/pkg/uroot/initramfs/files.go @@ -177,7 +177,7 @@ func (af *Files) addParent(name string) { return } if !af.Contains(parent) { - af.AddRecord(cpio.Directory(parent, 0755)) + af.AddRecord(cpio.Directory(parent, 0o755)) } af.addParent(parent) } diff --git a/pkg/uroot/initramfs/files_test.go b/pkg/uroot/initramfs/files_test.go index ff1494928f..7396e45566 100644 --- a/pkg/uroot/initramfs/files_test.go +++ b/pkg/uroot/initramfs/files_test.go @@ -388,13 +388,13 @@ func TestFilesfillInParent(t *testing.T) { { af: &Files{ Records: map[string]cpio.Record{ - "foo/bar": cpio.Directory("foo/bar", 0777), + "foo/bar": cpio.Directory("foo/bar", 0o777), }, }, result: &Files{ Records: map[string]cpio.Record{ - "foo/bar": cpio.Directory("foo/bar", 0777), - "foo": cpio.Directory("foo", 0755), + "foo/bar": cpio.Directory("foo/bar", 0o777), + "foo": cpio.Directory("foo", 0o755), }, }, }, @@ -404,7 +404,7 @@ func TestFilesfillInParent(t *testing.T) { "baz/baz/baz": "/somewhere", }, Records: map[string]cpio.Record{ - "foo/bar": cpio.Directory("foo/bar", 0777), + "foo/bar": cpio.Directory("foo/bar", 0o777), }, }, result: &Files{ @@ -412,10 +412,10 @@ func TestFilesfillInParent(t *testing.T) { "baz/baz/baz": "/somewhere", }, Records: map[string]cpio.Record{ - "foo/bar": cpio.Directory("foo/bar", 0777), - "foo": cpio.Directory("foo", 0755), - "baz": cpio.Directory("baz", 0755), - "baz/baz": cpio.Directory("baz/baz", 0755), + "foo/bar": cpio.Directory("foo/bar", 0o777), + "foo": cpio.Directory("foo", 0o755), + "baz": cpio.Directory("baz", 0o755), + "baz/baz": cpio.Directory("baz/baz", 0o755), }, }, }, @@ -508,14 +508,14 @@ func TestOptsWrite(t *testing.T) { ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.Directory("etc", 0777), - cpio.Directory("etc/nginx", 0777), + cpio.Directory("etc", 0o777), + cpio.Directory("etc/nginx", 0o777), }, }, want: Records{ "foo": cpio.Symlink("foo", "elsewhere"), - "etc": cpio.Directory("etc", 0777), - "etc/nginx": cpio.Directory("etc/nginx", 0777), + "etc": cpio.Directory("etc", 0o777), + "etc/nginx": cpio.Directory("etc/nginx", 0o777), }, }, { @@ -530,7 +530,7 @@ func TestOptsWrite(t *testing.T) { ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.Directory("etc", 0777), + cpio.Directory("etc", 0o777), }, }, want: Records{ @@ -550,8 +550,8 @@ func TestOptsWrite(t *testing.T) { Records: make(Records), }, want: Records{ - "foo": cpio.Directory("foo", 0755), - "foo/bar": cpio.Directory("foo/bar", 0755), + "foo": cpio.Directory("foo", 0o755), + "foo/bar": cpio.Directory("foo/bar", 0o755), "foo/bar/baz": cpio.Symlink("foo/bar/baz", "elsewhere"), }, }, @@ -560,7 +560,7 @@ func TestOptsWrite(t *testing.T) { opts: &Opts{ Files: &Files{ Records: map[string]cpio.Record{ - "foo/bar": cpio.Directory("foo/bar", 0444), + "foo/bar": cpio.Directory("foo/bar", 0o444), "foo/bar/baz": cpio.Symlink("foo/bar/baz", "elsewhere"), }, }, @@ -569,8 +569,8 @@ func TestOptsWrite(t *testing.T) { Records: make(Records), }, want: Records{ - "foo": cpio.Directory("foo", 0755), - "foo/bar": cpio.Directory("foo/bar", 0444), + "foo": cpio.Directory("foo", 0o755), + "foo/bar": cpio.Directory("foo/bar", 0o444), "foo/bar/baz": cpio.Symlink("foo/bar/baz", "elsewhere"), }, }, @@ -580,22 +580,22 @@ func TestOptsWrite(t *testing.T) { Files: &Files{ Records: map[string]cpio.Record{ "foo/bar": cpio.Symlink("foo/bar", "elsewhere"), - "exists": cpio.Directory("exists", 0777), + "exists": cpio.Directory("exists", 0o777), }, }, }, ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.Directory("etc", 0755), - cpio.Directory("foo", 0444), + cpio.Directory("etc", 0o755), + cpio.Directory("foo", 0o444), cpio.Directory("exists", 0), }, }, want: Records{ - "etc": cpio.Directory("etc", 0755), - "exists": cpio.Directory("exists", 0777), - "foo": cpio.Directory("foo", 0444), + "etc": cpio.Directory("etc", 0o755), + "exists": cpio.Directory("exists", 0o777), + "foo": cpio.Directory("foo", 0o444), "foo/bar": cpio.Symlink("foo/bar", "elsewhere"), }, }, @@ -609,11 +609,11 @@ func TestOptsWrite(t *testing.T) { ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.StaticFile("init", "boo", 0555), + cpio.StaticFile("init", "boo", 0o555), }, }, want: Records{ - "init": cpio.StaticFile("init", "boo", 0555), + "init": cpio.StaticFile("init", "boo", 0o555), }, }, { @@ -621,19 +621,19 @@ func TestOptsWrite(t *testing.T) { opts: &Opts{ Files: &Files{ Records: map[string]cpio.Record{ - "init": cpio.StaticFile("init", "bar", 0444), + "init": cpio.StaticFile("init", "bar", 0o444), }, }, }, ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.StaticFile("init", "boo", 0555), + cpio.StaticFile("init", "boo", 0o555), }, }, want: Records{ - "init": cpio.StaticFile("init", "bar", 0444), - "inito": cpio.StaticFile("inito", "boo", 0555), + "init": cpio.StaticFile("init", "bar", 0o444), + "inito": cpio.StaticFile("inito", "boo", 0o555), }, }, { @@ -647,11 +647,11 @@ func TestOptsWrite(t *testing.T) { ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.StaticFile("init", "boo", 0555), + cpio.StaticFile("init", "boo", 0o555), }, }, want: Records{ - "init": cpio.StaticFile("init", "boo", 0555), + "init": cpio.StaticFile("init", "boo", 0o555), }, }, { @@ -659,7 +659,7 @@ func TestOptsWrite(t *testing.T) { opts: &Opts{ Files: &Files{ Records: map[string]cpio.Record{ - "init": cpio.StaticFile("init", "huh", 0111), + "init": cpio.StaticFile("init", "huh", 0o111), }, }, UseExistingInit: true, @@ -667,12 +667,12 @@ func TestOptsWrite(t *testing.T) { ma: &MockArchiver{ Records: make(Records), BaseArchive: []cpio.Record{ - cpio.StaticFile("init", "boo", 0555), + cpio.StaticFile("init", "boo", 0o555), }, }, want: Records{ - "init": cpio.StaticFile("init", "boo", 0555), - "inito": cpio.StaticFile("inito", "huh", 0111), + "init": cpio.StaticFile("init", "boo", 0o555), + "inito": cpio.StaticFile("inito", "huh", 0o111), }, }, } { diff --git a/pkg/uroot/uroot.go b/pkg/uroot/uroot.go index 6faff0e2a1..b7a81d642e 100644 --- a/pkg/uroot/uroot.go +++ b/pkg/uroot/uroot.go @@ -44,31 +44,31 @@ func DefaultRamfs() *cpio.Archive { switch golang.Default().GOOS { case "linux": return cpio.ArchiveFromRecords([]cpio.Record{ - cpio.Directory("bin", 0755), - cpio.Directory("dev", 0755), - cpio.Directory("env", 0755), - cpio.Directory("etc", 0755), - cpio.Directory("lib64", 0755), - cpio.Directory("proc", 0755), - cpio.Directory("sys", 0755), - cpio.Directory("tcz", 0755), - cpio.Directory("tmp", 0777), - cpio.Directory("ubin", 0755), - cpio.Directory("usr", 0755), - cpio.Directory("usr/lib", 0755), - cpio.Directory("var/log", 0777), - cpio.CharDev("dev/console", 0600, 5, 1), - cpio.CharDev("dev/tty", 0666, 5, 0), - cpio.CharDev("dev/null", 0666, 1, 3), - cpio.CharDev("dev/port", 0640, 1, 4), - cpio.CharDev("dev/urandom", 0666, 1, 9), - cpio.StaticFile("etc/resolv.conf", nameserver, 0644), - cpio.StaticFile("etc/localtime", gmt0, 0644), + cpio.Directory("bin", 0o755), + cpio.Directory("dev", 0o755), + cpio.Directory("env", 0o755), + cpio.Directory("etc", 0o755), + cpio.Directory("lib64", 0o755), + cpio.Directory("proc", 0o755), + cpio.Directory("sys", 0o755), + cpio.Directory("tcz", 0o755), + cpio.Directory("tmp", 0o777), + cpio.Directory("ubin", 0o755), + cpio.Directory("usr", 0o755), + cpio.Directory("usr/lib", 0o755), + cpio.Directory("var/log", 0o777), + cpio.CharDev("dev/console", 0o600, 5, 1), + cpio.CharDev("dev/tty", 0o666, 5, 0), + cpio.CharDev("dev/null", 0o666, 1, 3), + cpio.CharDev("dev/port", 0o640, 1, 4), + cpio.CharDev("dev/urandom", 0o666, 1, 9), + cpio.StaticFile("etc/resolv.conf", nameserver, 0o644), + cpio.StaticFile("etc/localtime", gmt0, 0o644), }) default: return cpio.ArchiveFromRecords([]cpio.Record{ - cpio.Directory("ubin", 0755), - cpio.Directory("bbin", 0755), + cpio.Directory("ubin", 0o755), + cpio.Directory("bbin", 0o755), }) } } @@ -275,7 +275,7 @@ func CreateInitramfs(logger ulog.Logger, opts Opts) error { return fmt.Errorf("%v: specify -uinitcmd=\"\" to ignore this error and build without a uinit", err) } if len(opts.UinitArgs) > 0 { - if err := archive.AddRecord(cpio.StaticFile("etc/uinit.flags", uflag.ArgvToFile(opts.UinitArgs), 0444)); err != nil { + if err := archive.AddRecord(cpio.StaticFile("etc/uinit.flags", uflag.ArgvToFile(opts.UinitArgs), 0o444)); err != nil { return fmt.Errorf("%v: could not add uinit arguments from UinitArgs (-uinitcmd) to initramfs", err) } } diff --git a/pkg/uroot/uroot_test.go b/pkg/uroot/uroot_test.go index 3c1da1689a..0e66a65e97 100644 --- a/pkg/uroot/uroot_test.go +++ b/pkg/uroot/uroot_test.go @@ -178,7 +178,7 @@ func TestCreateInitramfs(t *testing.T) { syscall.Umask(0) tmp777 := filepath.Join(dir, "tmp777") - if err := os.MkdirAll(tmp777, 0777); err != nil { + if err := os.MkdirAll(tmp777, 0o777); err != nil { t.Error(err) } diff --git a/pkg/uzip/uzip.go b/pkg/uzip/uzip.go index 136901e4eb..161958a90e 100644 --- a/pkg/uzip/uzip.go +++ b/pkg/uzip/uzip.go @@ -143,7 +143,7 @@ func FromZip(src, dir string) error { return err } - if err = os.MkdirAll(dir, 0755); err != nil { + if err = os.MkdirAll(dir, 0o755); err != nil { return err } diff --git a/pkg/uzip/uzip_test.go b/pkg/uzip/uzip_test.go index 5f12294bd9..f95162a5c9 100644 --- a/pkg/uzip/uzip_test.go +++ b/pkg/uzip/uzip_test.go @@ -5,11 +5,12 @@ package uzip import ( - "github.com/stretchr/testify/require" "io/ioutil" "os" "path/filepath" "testing" + + "github.com/stretchr/testify/require" ) func TestFromZip(t *testing.T) { diff --git a/pkg/vfile/vfile_test.go b/pkg/vfile/vfile_test.go index ace3d88735..f377f38fac 100644 --- a/pkg/vfile/vfile_test.go +++ b/pkg/vfile/vfile_test.go @@ -29,7 +29,7 @@ type signedFile struct { } func (s signedFile) write(path string) error { - f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600) + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o600) if err != nil { return err } @@ -39,7 +39,7 @@ func (s signedFile) write(path string) error { return err } - sigf, err := os.OpenFile(fmt.Sprintf("%s.sig", path), os.O_RDWR|os.O_CREATE, 0600) + sigf, err := os.OpenFile(fmt.Sprintf("%s.sig", path), os.O_RDWR|os.O_CREATE, 0o600) if err != nil { return err } @@ -57,12 +57,12 @@ type normalFile struct { } func (n normalFile) write(path string) error { - return ioutil.WriteFile(path, []byte(n.content), 0600) + return ioutil.WriteFile(path, []byte(n.content), 0o600) } func writeHashedFile(path, content string) ([]byte, error) { c := []byte(content) - if err := ioutil.WriteFile(path, c, 0600); err != nil { + if err := ioutil.WriteFile(path, c, 0o600); err != nil { return nil, err } hash := sha256.Sum256(c) @@ -77,7 +77,7 @@ func TestOpenSignedFile(t *testing.T) { t.Run("EntityGenerate", func(t *testing.T) { t.Skip("uncomment this to generate the entities") - if err := os.MkdirAll("testdata", 0777); err != nil { + if err := os.MkdirAll("testdata", 0o777); err != nil { t.Fatal(err) } @@ -162,7 +162,7 @@ func TestOpenSignedFile(t *testing.T) { } normalPath := filepath.Join(dir, "unsigned") - if err := ioutil.WriteFile(normalPath, []byte("foo"), 0777); err != nil { + if err := ioutil.WriteFile(normalPath, []byte("foo"), 0o777); err != nil { t.Fatal(err) } diff --git a/pkg/vmtest/gotest.go b/pkg/vmtest/gotest.go index 1d2d9940cc..d58b109ce4 100644 --- a/pkg/vmtest/gotest.go +++ b/pkg/vmtest/gotest.go @@ -51,7 +51,7 @@ func GolangTest(t *testing.T, pkgs []string, o *Options) { testDir := filepath.Join(o.TmpDir, "tests") for _, pkg := range pkgs { pkgDir := filepath.Join(testDir, pkg) - if err := os.MkdirAll(pkgDir, 0755); err != nil { + if err := os.MkdirAll(pkgDir, 0o755); err != nil { t.Fatal(err) } diff --git a/pkg/vmtest/integration.go b/pkg/vmtest/integration.go index bdcf82edd8..5b593a7f68 100644 --- a/pkg/vmtest/integration.go +++ b/pkg/vmtest/integration.go @@ -177,7 +177,7 @@ func saveCoverage(t *testing.T, path string) error { // Move coverage to common directory. uniqueCoveragePath := filepath.Join(coveragePath, t.Name(), fmt.Sprintf("%d", instance[t.Name()])) instance[t.Name()]++ - if err := os.MkdirAll(uniqueCoveragePath, 0770); err != nil { + if err := os.MkdirAll(uniqueCoveragePath, 0o770); err != nil { return err } if err := os.Rename(path, filepath.Join(uniqueCoveragePath, filepath.Base(path))); err != nil { @@ -263,7 +263,7 @@ func QEMU(o *Options) (*qemu.Options, error) { testFile := filepath.Join(o.TmpDir, "test.elv") if err := ioutil.WriteFile( - testFile, []byte(strings.Join(o.TestCmds, "\n")), 0777); err != nil { + testFile, []byte(strings.Join(o.TestCmds, "\n")), 0o777); err != nil { return nil, err } } diff --git a/pkg/vpd/vpd.go b/pkg/vpd/vpd.go index 2c79019f46..1385504467 100644 --- a/pkg/vpd/vpd.go +++ b/pkg/vpd/vpd.go @@ -73,7 +73,7 @@ func (r *Reader) Get(key string, readOnly bool) ([]byte, error) { func (r *Reader) Set(key string, value []byte, readOnly bool) error { // NOTE this is not implemented yet in the kernel interface, and will always // return a permission denied error - return ioutil.WriteFile(path.Join(r.getBaseDir(readOnly), key), value, 0644) + return ioutil.WriteFile(path.Join(r.getBaseDir(readOnly), key), value, 0o644) } // GetAll reads all the VPD variables and returns a map contaiing each diff --git a/pkg/watchdogd/watchdogd.go b/pkg/watchdogd/watchdogd.go index 0ab2550514..b2c6690de4 100644 --- a/pkg/watchdogd/watchdogd.go +++ b/pkg/watchdogd/watchdogd.go @@ -350,7 +350,6 @@ func sendAndCheckResult(c *net.UnixConn, op int) error { b := make([]byte, 1) if _, err := io.ReadAtLeast(c, b, 1); err != nil { log.Printf("Failed to read operation bit from server: %v", err) - } r := int(b[0]) if r != OpResultOk { diff --git a/tools/mkinitramfs/main.go b/tools/mkinitramfs/main.go index c970058dcb..086dba97a3 100644 --- a/tools/mkinitramfs/main.go +++ b/tools/mkinitramfs/main.go @@ -15,9 +15,7 @@ import ( "github.com/u-root/u-root/pkg/uroot/initramfs" ) -var ( - outputFile = flag.String("o", "initramfs.cpio", "Initramfs output file") -) +var outputFile = flag.String("o", "initramfs.cpio", "Initramfs output file") func main() { flag.Parse() diff --git a/tools/testramfs/testramfs.go b/tools/testramfs/testramfs.go index 056f7c2dee..7c367d0d0f 100644 --- a/tools/testramfs/testramfs.go +++ b/tools/testramfs/testramfs.go @@ -27,7 +27,7 @@ const ( // making newpid work will be more tricky, // since none of my CLs to fix go runtime for // it ever got in. - //syscall.CLONE_NEWPID | + // syscall.CLONE_NEWPID | syscall.CLONE_NEWUTS | 0 ) @@ -147,5 +147,4 @@ func main() { if err := cmd.Wait(); err != nil { log.Fatal(err) } - } diff --git a/tools/vpdbootmanager/add_test.go b/tools/vpdbootmanager/add_test.go index c48da1204f..552dbee960 100644 --- a/tools/vpdbootmanager/add_test.go +++ b/tools/vpdbootmanager/add_test.go @@ -133,7 +133,7 @@ func TestAddBootEntry(t *testing.T) { if err != nil { log.Fatal(err) } - os.MkdirAll(path.Join(vpdDir, "rw"), 0700) + os.MkdirAll(path.Join(vpdDir, "rw"), 0o700) defer os.RemoveAll(vpdDir) err = addBootEntry(&systembooter.LocalBooter{ Method: "grub", @@ -152,7 +152,7 @@ func TestAddBootEntryMultiple(t *testing.T) { if err != nil { log.Fatal(err) } - os.MkdirAll(path.Join(vpdDir, "rw"), 0700) + os.MkdirAll(path.Join(vpdDir, "rw"), 0o700) defer os.RemoveAll(vpdDir) for i := 1; i < 5; i++ { err = addBootEntry(&systembooter.LocalBooter{ diff --git a/tools/vpdbootmanager/main_test.go b/tools/vpdbootmanager/main_test.go index 75fc1cf99c..4e663ccc43 100644 --- a/tools/vpdbootmanager/main_test.go +++ b/tools/vpdbootmanager/main_test.go @@ -36,7 +36,7 @@ func TestAddNetbootEntryFull(t *testing.T) { if err != nil { log.Fatal(err) } - os.MkdirAll(path.Join(dir, "rw"), 0700) + os.MkdirAll(path.Join(dir, "rw"), 0o700) defer os.RemoveAll(dir) err = cli([]string{ "add", @@ -61,7 +61,7 @@ func TestAddLocalbootEntryFull(t *testing.T) { if err != nil { log.Fatal(err) } - os.MkdirAll(path.Join(dir, "rw"), 0700) + os.MkdirAll(path.Join(dir, "rw"), 0o700) defer os.RemoveAll(dir) err = cli([]string{ "add", diff --git a/u-root.go b/u-root.go index 40df35c2e3..3efe7b29d8 100644 --- a/u-root.go +++ b/u-root.go @@ -116,7 +116,7 @@ func writeBuildStats(stats buildStats, path string) error { if err != nil { return err } - if err := ioutil.WriteFile(*statsOutputPath, data, 0644); err != nil { + if err := ioutil.WriteFile(*statsOutputPath, data, 0o644); err != nil { return err } return nil @@ -248,7 +248,7 @@ func Main() error { } defer os.RemoveAll(tempDir) } else if _, err := os.Stat(tempDir); os.IsNotExist(err) { - if err := os.MkdirAll(tempDir, 0755); err != nil { + if err := os.MkdirAll(tempDir, 0o755); err != nil { return fmt.Errorf("temporary directory %q did not exist; tried to mkdir but failed: %v", tempDir, err) } } diff --git a/uroot_test.go b/uroot_test.go index 76c9ce99b5..062a9f22c5 100644 --- a/uroot_test.go +++ b/uroot_test.go @@ -136,10 +136,10 @@ func TestUrootCmdline(t *testing.T) { if err != nil { t.Fatal(err) } - if err = ioutil.WriteFile(filepath.Join(sampledir, "foo"), nil, 0644); err != nil { + if err = ioutil.WriteFile(filepath.Join(sampledir, "foo"), nil, 0o644); err != nil { t.Fatal(err) } - if err = ioutil.WriteFile(filepath.Join(sampledir, "bar"), nil, 0644); err != nil { + if err = ioutil.WriteFile(filepath.Join(sampledir, "bar"), nil, 0o644); err != nil { t.Fatal(err) } defer os.RemoveAll(sampledir) @@ -207,7 +207,7 @@ func TestUrootCmdline(t *testing.T) { // so these can be removed once we no longer support Go < 1.15. "-github.com/u-root/u-root/cmds/exp/builtin", "-github.com/u-root/u-root/cmds/exp/run", - //TODO(MDr164): Find a solution for upstream elvish + // TODO(MDr164): Find a solution for upstream elvish "-github.com/u-root/u-root/cmds/core/elvish", }, err: nil,