github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/ioutil/ioutil_wrap.go (about)

     1  // Copyright 2016 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package ioutil
     6  
     7  import (
     8  	"io"
     9  	"io/fs"
    10  	"os"
    11  
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // ReadAll wraps ReadAll from "io".
    16  func ReadAll(r io.Reader) ([]byte, error) {
    17  	buf, err := io.ReadAll(r)
    18  	if err != nil {
    19  		return nil, errors.Wrapf(
    20  			err, "failed to read all from reader %v", r)
    21  	}
    22  
    23  	return buf, nil
    24  }
    25  
    26  // ReadDir wraps ReadDir from "os".
    27  func ReadDir(dirname string) ([]os.FileInfo, error) {
    28  	entries, err := os.ReadDir(dirname)
    29  	if err != nil {
    30  		return nil, errors.Wrapf(err, "failed to read dir %q", dirname)
    31  	}
    32  	infos := make([]fs.FileInfo, 0, len(entries))
    33  	for _, entry := range entries {
    34  		info, err := entry.Info()
    35  		if err != nil {
    36  			return nil, errors.Wrapf(err, "failed to read dir %q", dirname)
    37  		}
    38  		infos = append(infos, info)
    39  	}
    40  	return infos, nil
    41  }
    42  
    43  // ReadFile wraps ReadFile from "os".
    44  func ReadFile(filename string) ([]byte, error) {
    45  	buf, err := os.ReadFile(filename)
    46  	if err != nil {
    47  		return nil, errors.Wrapf(err, "failed to read file %q", filename)
    48  	}
    49  	return buf, nil
    50  }
    51  
    52  // TempDir wraps MkdirTemp from "os".
    53  func TempDir(dir, prefix string) (name string, err error) {
    54  	name, err = os.MkdirTemp(dir, prefix)
    55  	if err != nil {
    56  		return "", errors.Wrapf(err,
    57  			"failed to make temp dir in %q with prefix %q",
    58  			dir, prefix)
    59  	}
    60  	return name, nil
    61  }
    62  
    63  // WriteFile wraps WriteFile from "os".
    64  func WriteFile(filename string, data []byte, perm os.FileMode) error {
    65  	err := os.WriteFile(filename, data, perm)
    66  	if err != nil {
    67  		return errors.Wrapf(err, "failed to write file %q", filename)
    68  	}
    69  	return nil
    70  }