1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2025-12-17 14:37:02 +00:00

Replace uses of ioutil

ioutil package was deprecated in Go 1.16, replace all uses with their
respective replacements.

This patch was generated with a combination of `gofmt -r`, `eg`, and
manually (for `ioutil.ReadDir`).
This commit is contained in:
Alberto Bertogli
2022-11-12 20:02:52 +00:00
parent 008367d320
commit 3ebe5c5173
22 changed files with 42 additions and 61 deletions

View File

@@ -9,7 +9,6 @@ import (
"expvar" "expvar"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"math/rand" "math/rand"
"net" "net"
"os" "os"
@@ -112,13 +111,13 @@ func main() {
// The structure matches letsencrypt's, to make it easier for that case. // The structure matches letsencrypt's, to make it easier for that case.
log.Infof("Loading certificates") log.Infof("Loading certificates")
for _, info := range mustReadDir("certs/") { for _, info := range mustReadDir("certs/") {
name := info.Name() if !info.IsDir() {
dir := filepath.Join("certs/", name)
if fi, err := os.Stat(dir); err == nil && !fi.IsDir() {
// Skip non-directories. // Skip non-directories.
continue continue
} }
name := info.Name()
dir := filepath.Join("certs/", name)
log.Infof(" %s", name) log.Infof(" %s", name)
certPath := filepath.Join(dir, "fullchain.pem") certPath := filepath.Join(dir, "fullchain.pem")
@@ -291,8 +290,8 @@ func loadDovecot(s *smtpsrv.Server, userdb, client string) {
} }
// Read a directory, which must have at least some entries. // Read a directory, which must have at least some entries.
func mustReadDir(path string) []os.FileInfo { func mustReadDir(path string) []os.DirEntry {
dirs, err := ioutil.ReadDir(path) dirs, err := os.ReadDir(path)
if err != nil { if err != nil {
log.Fatalf("Error reading %q directory: %v", path, err) log.Fatalf("Error reading %q directory: %v", path, err)
} }

View File

@@ -9,7 +9,6 @@ package main
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
@@ -229,7 +228,7 @@ func aliasesResolve() {
r.SuffixSep = *conf.SuffixSeparators r.SuffixSep = *conf.SuffixSeparators
r.DropChars = *conf.DropCharacters r.DropChars = *conf.DropCharacters
domainDirs, err := ioutil.ReadDir("domains/") domainDirs, err := os.ReadDir("domains/")
if err != nil { if err != nil {
Fatalf("Error reading domains/ directory: %v", err) Fatalf("Error reading domains/ directory: %v", err)
} }
@@ -237,8 +236,8 @@ func aliasesResolve() {
Fatalf("No domains found in config") Fatalf("No domains found in config")
} }
for _, info := range domainDirs { for _, entry := range domainDirs {
name := info.Name() name := entry.Name()
aliasfile := "domains/" + name + "/aliases" aliasfile := "domains/" + name + "/aliases"
r.AddDomain(name) r.AddDomain(name)
err := r.AddAliasesFile(name, aliasfile) err := r.AddAliasesFile(name, aliasfile)

View File

@@ -2,7 +2,6 @@ package aliases
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"reflect" "reflect"
@@ -276,7 +275,7 @@ func TestTooMuchRecursionOnCatchAll(t *testing.T) {
} }
func mustWriteFile(t *testing.T, content string) string { func mustWriteFile(t *testing.T, content string) string {
f, err := ioutil.TempFile("", "aliases_test") f, err := os.CreateTemp("", "aliases_test")
if err != nil { if err != nil {
t.Fatalf("failed to get temp file: %v", err) t.Fatalf("failed to get temp file: %v", err)
} }

View File

@@ -6,7 +6,6 @@ package config
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"blitiri.com.ar/go/log" "blitiri.com.ar/go/log"
@@ -39,7 +38,7 @@ func Load(path, overrides string) (*Config, error) {
c := proto.Clone(defaultConfig).(*Config) c := proto.Clone(defaultConfig).(*Config)
// Load from the path. // Load from the path.
buf, err := ioutil.ReadFile(path) buf, err := os.ReadFile(path)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read config at %q: %v", path, err) return nil, fmt.Errorf("failed to read config at %q: %v", path, err)
} }

View File

@@ -2,7 +2,6 @@ package config
import ( import (
"io" "io"
"io/ioutil"
"os" "os"
"testing" "testing"
@@ -16,7 +15,7 @@ import (
func mustCreateConfig(t *testing.T, contents string) (string, string) { func mustCreateConfig(t *testing.T, contents string) (string, string) {
tmpDir := testlib.MustTempDir(t) tmpDir := testlib.MustTempDir(t)
confStr := []byte(contents) confStr := []byte(contents)
err := ioutil.WriteFile(tmpDir+"/chasquid.conf", confStr, 0600) err := os.WriteFile(tmpDir+"/chasquid.conf", confStr, 0600)
if err != nil { if err != nil {
t.Fatalf("Failed to write tmp config: %v", err) t.Fatalf("Failed to write tmp config: %v", err)
} }
@@ -138,7 +137,7 @@ func TestBrokenOverride(t *testing.T) {
// Run LogConfig, overriding the default logger first. This exercises the // Run LogConfig, overriding the default logger first. This exercises the
// code, we don't yet validate the output, but it is an useful sanity check. // code, we don't yet validate the output, but it is an useful sanity check.
func testLogConfig(c *Config) { func testLogConfig(c *Config) {
l := log.New(nopWCloser{ioutil.Discard}) l := log.New(nopWCloser{io.Discard})
log.Default = l log.Default = l
LogConfig(c) LogConfig(c)
} }

View File

@@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"io/ioutil"
"net" "net"
"net/textproto" "net/textproto"
"os" "os"
@@ -62,7 +61,7 @@ func (s *FakeServer) rootCA() *x509.CertPool {
s.t.Helper() s.t.Helper()
pool := x509.NewCertPool() pool := x509.NewCertPool()
path := s.tmpDir + "/cert.pem" path := s.tmpDir + "/cert.pem"
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
s.t.Fatalf("error reading cert %q: %v", path, err) s.t.Fatalf("error reading cert %q: %v", path, err)
} }

View File

@@ -2,7 +2,6 @@ package courier
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@@ -25,7 +24,7 @@ func TestMDA(t *testing.T) {
t.Fatalf("Deliver: %v", err) t.Fatalf("Deliver: %v", err)
} }
data, err := ioutil.ReadFile(dir + "/to") data, err := os.ReadFile(dir + "/to")
if err != nil || !bytes.Equal(data, []byte("data")) { if err != nil || !bytes.Equal(data, []byte("data")) {
t.Errorf("Invalid data: %q - %v", string(data), err) t.Errorf("Invalid data: %q - %v", string(data), err)
} }

View File

@@ -2,7 +2,7 @@ package expvarom
import ( import (
"expvar" "expvar"
"io/ioutil" "io"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@@ -111,7 +111,7 @@ func TestHandler(t *testing.T) {
MetricsHandler(w, req) MetricsHandler(w, req)
resp := w.Result() resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body) body, _ := io.ReadAll(resp.Body)
if diff := cmp.Diff(expected, string(body)); diff != "" { if diff := cmp.Diff(expected, string(body)); diff != "" {
t.Errorf("MetricsHandler() mismatch (-want +got):\n%s", diff) t.Errorf("MetricsHandler() mismatch (-want +got):\n%s", diff)

View File

@@ -4,7 +4,6 @@ package maillog
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log/syslog" "log/syslog"
"net" "net"
"sync" "sync"
@@ -148,7 +147,7 @@ type nopCloser struct {
func (nopCloser) Close() error { return nil } func (nopCloser) Close() error { return nil }
// Default logger, used in the following top-level functions. // Default logger, used in the following top-level functions.
var Default *Logger = New(nopCloser{ioutil.Discard}) var Default *Logger = New(nopCloser{io.Discard})
// Listening logs that the daemon is listening on the given address. // Listening logs that the daemon is listening on the given address.
func Listening(a string) { func Listening(a string) {

View File

@@ -2,7 +2,6 @@
package protoio package protoio
import ( import (
"io/ioutil"
"net/url" "net/url"
"os" "os"
"strings" "strings"
@@ -16,7 +15,7 @@ import (
// ReadMessage reads a protocol buffer message from fname, and unmarshalls it // ReadMessage reads a protocol buffer message from fname, and unmarshalls it
// into pb. // into pb.
func ReadMessage(fname string, pb proto.Message) error { func ReadMessage(fname string, pb proto.Message) error {
in, err := ioutil.ReadFile(fname) in, err := os.ReadFile(fname)
if err != nil { if err != nil {
return err return err
} }
@@ -26,7 +25,7 @@ func ReadMessage(fname string, pb proto.Message) error {
// ReadTextMessage reads a text format protocol buffer message from fname, and // ReadTextMessage reads a text format protocol buffer message from fname, and
// unmarshalls it into pb. // unmarshalls it into pb.
func ReadTextMessage(fname string, pb proto.Message) error { func ReadTextMessage(fname string, pb proto.Message) error {
in, err := ioutil.ReadFile(fname) in, err := os.ReadFile(fname)
if err != nil { if err != nil {
return err return err
} }
@@ -98,7 +97,7 @@ func (s *Store) Get(id string, m proto.Message) (bool, error) {
func (s *Store) ListIDs() ([]string, error) { func (s *Store) ListIDs() ([]string, error) {
ids := []string{} ids := []string{}
entries, err := ioutil.ReadDir(s.dir) entries, err := os.ReadDir(s.dir)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@@ -3,7 +3,6 @@
package safeio package safeio
import ( import (
"io/ioutil"
"os" "os"
"path" "path"
"syscall" "syscall"
@@ -14,7 +13,7 @@ type FileOp func(fname string) error
// WriteFile writes data to a file named by filename, atomically. // WriteFile writes data to a file named by filename, atomically.
// //
// It's a wrapper to ioutil.WriteFile, but provides atomicity (and increased // It's a wrapper to os.WriteFile, but provides atomicity (and increased
// safety) by writing to a temporary file and renaming it at the end. // safety) by writing to a temporary file and renaming it at the end.
// //
// Before the final rename, the given ops (if any) are called. They can be // Before the final rename, the given ops (if any) are called. They can be
@@ -28,7 +27,7 @@ func WriteFile(filename string, data []byte, perm os.FileMode, ops ...FileOp) er
// would have no expectation of Rename being atomic. // would have no expectation of Rename being atomic.
// We make the file names start with "." so there's no confusion with the // We make the file names start with "." so there's no confusion with the
// originals. // originals.
tmpf, err := ioutil.TempFile(path.Dir(filename), "."+path.Base(filename)) tmpf, err := os.CreateTemp(path.Dir(filename), "."+path.Base(filename))
if err != nil { if err != nil {
return err return err
} }

View File

@@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strings" "strings"
"testing" "testing"
@@ -19,7 +18,7 @@ func testWriteFile(fname string, data []byte, perm os.FileMode, ops ...FileOp) e
} }
// Read and compare the contents. // Read and compare the contents.
c, err := ioutil.ReadFile(fname) c, err := os.ReadFile(fname)
if err != nil { if err != nil {
return fmt.Errorf("error reading: %v", err) return fmt.Errorf("error reading: %v", err)
} }

View File

@@ -8,7 +8,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
"net" "net"
"net/mail" "net/mail"
@@ -637,7 +636,7 @@ func (c *Conn) DATA(params string) (code int, msg string) {
// Create a dot reader, limited to the maximum size. // Create a dot reader, limited to the maximum size.
dotr := textproto.NewReader(bufio.NewReader( dotr := textproto.NewReader(bufio.NewReader(
io.LimitReader(c.reader, c.maxDataSize))).DotReader() io.LimitReader(c.reader, c.maxDataSize))).DotReader()
c.data, err = ioutil.ReadAll(dotr) c.data, err = io.ReadAll(dotr)
if err != nil { if err != nil {
if err == io.ErrUnexpectedEOF { if err == io.ErrUnexpectedEOF {
// Message is too big already. But we need to keep reading until we see // Message is too big already. But we need to keep reading until we see

View File

@@ -17,7 +17,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"math/big" "math/big"
"net" "net"
"net/textproto" "net/textproto"
@@ -235,7 +234,7 @@ func init() {
log.Default.Level = log.Error log.Default.Level = log.Error
// Generate certificates in a temporary directory. // Generate certificates in a temporary directory.
tmpDir, err := ioutil.TempDir("", "chasquid_smtpsrv_fuzz:") tmpDir, err := os.MkdirTemp("", "chasquid_smtpsrv_fuzz:")
if err != nil { if err != nil {
panic(fmt.Errorf("Failed to create temp dir: %v\n", tmpDir)) panic(fmt.Errorf("Failed to create temp dir: %v\n", tmpDir))
} }

View File

@@ -4,7 +4,6 @@ import (
"crypto/tls" "crypto/tls"
"flag" "flag"
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/smtp" "net/smtp"
"os" "os"
@@ -568,7 +567,7 @@ func realMain(m *testing.M) int {
} }
} else { } else {
// Generate certificates in a temporary directory. // Generate certificates in a temporary directory.
tmpDir, err := ioutil.TempDir("", "chasquid_test:") tmpDir, err := os.MkdirTemp("", "chasquid_test:")
if err != nil { if err != nil {
fmt.Printf("Failed to create temp dir: %v\n", tmpDir) fmt.Printf("Failed to create temp dir: %v\n", tmpDir)
return 1 return 1

View File

@@ -13,7 +13,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"mime" "mime"
"net" "net"
"net/http" "net/http"
@@ -266,7 +265,7 @@ func httpGet(ctx context.Context, url string) ([]byte, error) {
// Read but up to 10k; policies should be way smaller than that, and // Read but up to 10k; policies should be way smaller than that, and
// having a limit prevents abuse/accidents with very large replies. // having a limit prevents abuse/accidents with very large replies.
return ioutil.ReadAll(&io.LimitedReader{R: resp.Body, N: 10 * 1024}) return io.ReadAll(&io.LimitedReader{R: resp.Body, N: 10 * 1024})
} }
var errRejectRedirect = errors.New("redirects not allowed in MTA-STS") var errRejectRedirect = errors.New("redirects not allowed in MTA-STS")
@@ -385,7 +384,7 @@ func (c *PolicyCache) load(domain string) (*Policy, error) {
return nil, errExpired return nil, errExpired
} }
data, err := ioutil.ReadFile(fname) data, err := os.ReadFile(fname)
if err != nil { if err != nil {
cacheIOErrors.Add(1) cacheIOErrors.Add(1)
return nil, err return nil, err
@@ -486,7 +485,7 @@ func (c *PolicyCache) refresh(ctx context.Context) {
tr := trace.New("STSCache.Refresh", c.dir) tr := trace.New("STSCache.Refresh", c.dir)
defer tr.Finish() defer tr.Finish()
entries, err := ioutil.ReadDir(c.dir) entries, err := os.ReadDir(c.dir)
if err != nil { if err != nil {
tr.Errorf("failed to list directory %q: %v", c.dir, err) tr.Errorf("failed to list directory %q: %v", c.dir, err)
return return

View File

@@ -8,7 +8,6 @@ import (
"crypto/x509" "crypto/x509"
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"io/ioutil"
"math/big" "math/big"
"net" "net"
"os" "os"
@@ -20,7 +19,7 @@ import (
// MustTempDir creates a temporary directory, or dies trying. // MustTempDir creates a temporary directory, or dies trying.
func MustTempDir(t *testing.T) string { func MustTempDir(t *testing.T) string {
dir, err := ioutil.TempDir("", "testlib_") dir, err := os.MkdirTemp("", "testlib_")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -55,7 +54,7 @@ func Rewrite(t *testing.T, path, contents string) error {
panic("invalid/dangerous path") panic("invalid/dangerous path")
} }
err := ioutil.WriteFile(path, []byte(contents), 0600) err := os.WriteFile(path, []byte(contents), 0600)
if err != nil { if err != nil {
t.Errorf("failed to rewrite file: %v", err) t.Errorf("failed to rewrite file: %v", err)
} }

View File

@@ -1,7 +1,6 @@
package testlib package testlib
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
"time" "time"
@@ -9,7 +8,7 @@ import (
func TestBasic(t *testing.T) { func TestBasic(t *testing.T) {
dir := MustTempDir(t) dir := MustTempDir(t)
if err := ioutil.WriteFile(dir+"/file", nil, 0660); err != nil { if err := os.WriteFile(dir+"/file", nil, 0660); err != nil {
t.Fatalf("could not create file in %s: %v", dir, err) t.Fatalf("could not create file in %s: %v", dir, err)
} }

View File

@@ -2,7 +2,6 @@ package userdb
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"reflect" "reflect"
"strings" "strings"
@@ -26,7 +25,7 @@ func removeIfSuccessful(t *testing.T, fname string) {
// Create a database with the given content on a temporary filename. Return // Create a database with the given content on a temporary filename. Return
// the filename, or an error if there were errors creating it. // the filename, or an error if there were errors creating it.
func mustCreateDB(t *testing.T, content string) string { func mustCreateDB(t *testing.T, content string) string {
f, err := ioutil.TempFile("", "userdb_test") f, err := os.CreateTemp("", "userdb_test")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -244,7 +243,7 @@ func TestReload(t *testing.T) {
// Add a valid line to the file. // Add a valid line to the file.
content += "users:< key: 'u2' value:< plain:< password: 'pass' >>>" content += "users:< key: 'u2' value:< plain:< password: 'pass' >>>"
ioutil.WriteFile(fname, []byte(content), 0660) os.WriteFile(fname, []byte(content), 0660)
err := db.Reload() err := db.Reload()
if err != nil { if err != nil {
@@ -256,7 +255,7 @@ func TestReload(t *testing.T) {
// And now a broken one. // And now a broken one.
content += "users:< invalid >" content += "users:< invalid >"
ioutil.WriteFile(fname, []byte(content), 0660) os.WriteFile(fname, []byte(content), 0660)
err = db.Reload() err = db.Reload()
if err == nil { if err == nil {

View File

@@ -12,7 +12,7 @@ package main
import ( import (
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"time" "time"
@@ -29,7 +29,7 @@ var (
func main() { func main() {
flag.Parse() flag.Parse()
data, err := ioutil.ReadAll(os.Stdin) data, err := io.ReadAll(os.Stdin)
if err != nil { if err != nil {
fmt.Printf("error reading data: %v\n", err) fmt.Printf("error reading data: %v\n", err)
os.Exit(1) os.Exit(1)

View File

@@ -10,7 +10,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"html/template" "html/template"
"io/ioutil"
"math" "math"
"os" "os"
"strings" "strings"
@@ -50,7 +49,7 @@ func main() {
totals.Add(p) totals.Add(p)
fname := strings.Join(strings.Split(p.FileName, "/")[*strip:], "/") fname := strings.Join(strings.Split(p.FileName, "/")[*strip:], "/")
src, err := ioutil.ReadFile(fname) src, err := os.ReadFile(fname)
if err != nil { if err != nil {
errorf("Failed to read %q: %v", fname, err) errorf("Failed to read %q: %v", fname, err)
} }

View File

@@ -11,7 +11,7 @@ import (
"crypto/x509" "crypto/x509"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"regexp" "regexp"
@@ -70,13 +70,13 @@ func main() {
fatalf("error getting %q: %v\n", url, err) fatalf("error getting %q: %v\n", url, err)
} }
defer resp.Body.Close() defer resp.Body.Close()
rbody, err := ioutil.ReadAll(resp.Body) rbody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
errorf("error reading body: %v\n", err) errorf("error reading body: %v\n", err)
} }
if *save != "" { if *save != "" {
err = ioutil.WriteFile(*save, rbody, 0664) err = os.WriteFile(*save, rbody, 0664)
if err != nil { if err != nil {
errorf("error writing body to file %q: %v\n", *save, err) errorf("error writing body to file %q: %v\n", *save, err)
} }
@@ -170,7 +170,7 @@ func mkTransport(caCert string) http.RoundTripper {
return nil return nil
} }
certs, err := ioutil.ReadFile(caCert) certs, err := os.ReadFile(caCert)
if err != nil { if err != nil {
fatalf("error reading CA file %q: %v\n", caCert, err) fatalf("error reading CA file %q: %v\n", caCert, err)
} }