Path: blob/main/vendor/github.com/spf13/afero/ioutil.go
2875 views
// Copyright ©2015 The Go Authors1// Copyright ©2015 Steve Francia <[email protected]>2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package afero1617import (18"bytes"19"io"20"os"21"path/filepath"22"sort"23"strconv"24"strings"25"sync"26"time"27)2829// byName implements sort.Interface.30type byName []os.FileInfo3132func (f byName) Len() int { return len(f) }33func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }34func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }3536// ReadDir reads the directory named by dirname and returns37// a list of sorted directory entries.38func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {39return ReadDir(a.Fs, dirname)40}4142func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) {43f, err := fs.Open(dirname)44if err != nil {45return nil, err46}47list, err := f.Readdir(-1)48f.Close()49if err != nil {50return nil, err51}52sort.Sort(byName(list))53return list, nil54}5556// ReadFile reads the file named by filename and returns the contents.57// A successful call returns err == nil, not err == EOF. Because ReadFile58// reads the whole file, it does not treat an EOF from Read as an error59// to be reported.60func (a Afero) ReadFile(filename string) ([]byte, error) {61return ReadFile(a.Fs, filename)62}6364func ReadFile(fs Fs, filename string) ([]byte, error) {65f, err := fs.Open(filename)66if err != nil {67return nil, err68}69defer f.Close()70// It's a good but not certain bet that FileInfo will tell us exactly how much to71// read, so let's try it but be prepared for the answer to be wrong.72var n int647374if fi, err := f.Stat(); err == nil {75// Don't preallocate a huge buffer, just in case.76if size := fi.Size(); size < 1e9 {77n = size78}79}80// As initial capacity for readAll, use n + a little extra in case Size is zero,81// and to avoid another allocation after Read has filled the buffer. The readAll82// call will read into its allocated internal buffer cheaply. If the size was83// wrong, we'll either waste some space off the end or reallocate as needed, but84// in the overwhelmingly common case we'll get it just right.85return readAll(f, n+bytes.MinRead)86}8788// readAll reads from r until an error or EOF and returns the data it read89// from the internal buffer allocated with a specified capacity.90func readAll(r io.Reader, capacity int64) (b []byte, err error) {91buf := bytes.NewBuffer(make([]byte, 0, capacity))92// If the buffer overflows, we will get bytes.ErrTooLarge.93// Return that as an error. Any other panic remains.94defer func() {95e := recover()96if e == nil {97return98}99if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {100err = panicErr101} else {102panic(e)103}104}()105_, err = buf.ReadFrom(r)106return buf.Bytes(), err107}108109// ReadAll reads from r until an error or EOF and returns the data it read.110// A successful call returns err == nil, not err == EOF. Because ReadAll is111// defined to read from src until EOF, it does not treat an EOF from Read112// as an error to be reported.113func ReadAll(r io.Reader) ([]byte, error) {114return readAll(r, bytes.MinRead)115}116117// WriteFile writes data to a file named by filename.118// If the file does not exist, WriteFile creates it with permissions perm;119// otherwise WriteFile truncates it before writing.120func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {121return WriteFile(a.Fs, filename, data, perm)122}123124func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error {125f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)126if err != nil {127return err128}129n, err := f.Write(data)130if err == nil && n < len(data) {131err = io.ErrShortWrite132}133if err1 := f.Close(); err == nil {134err = err1135}136return err137}138139// Random number state.140// We generate random temporary file names so that there's a good141// chance the file doesn't exist yet - keeps the number of tries in142// TempFile to a minimum.143var (144randNum uint32145randmu sync.Mutex146)147148func reseed() uint32 {149return uint32(time.Now().UnixNano() + int64(os.Getpid()))150}151152func nextRandom() string {153randmu.Lock()154r := randNum155if r == 0 {156r = reseed()157}158r = r*1664525 + 1013904223 // constants from Numerical Recipes159randNum = r160randmu.Unlock()161return strconv.Itoa(int(1e9 + r%1e9))[1:]162}163164// TempFile creates a new temporary file in the directory dir,165// opens the file for reading and writing, and returns the resulting *os.File.166// The filename is generated by taking pattern and adding a random167// string to the end. If pattern includes a "*", the random string168// replaces the last "*".169// If dir is the empty string, TempFile uses the default directory170// for temporary files (see os.TempDir).171// Multiple programs calling TempFile simultaneously172// will not choose the same file. The caller can use f.Name()173// to find the pathname of the file. It is the caller's responsibility174// to remove the file when no longer needed.175func (a Afero) TempFile(dir, pattern string) (f File, err error) {176return TempFile(a.Fs, dir, pattern)177}178179func TempFile(fs Fs, dir, pattern string) (f File, err error) {180if dir == "" {181dir = os.TempDir()182}183184var prefix, suffix string185if pos := strings.LastIndex(pattern, "*"); pos != -1 {186prefix, suffix = pattern[:pos], pattern[pos+1:]187} else {188prefix = pattern189}190191nconflict := 0192for i := 0; i < 10000; i++ {193name := filepath.Join(dir, prefix+nextRandom()+suffix)194f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o600)195if os.IsExist(err) {196if nconflict++; nconflict > 10 {197randmu.Lock()198randNum = reseed()199randmu.Unlock()200}201continue202}203break204}205return206}207208// TempDir creates a new temporary directory in the directory dir209// with a name beginning with prefix and returns the path of the210// new directory. If dir is the empty string, TempDir uses the211// default directory for temporary files (see os.TempDir).212// Multiple programs calling TempDir simultaneously213// will not choose the same directory. It is the caller's responsibility214// to remove the directory when no longer needed.215func (a Afero) TempDir(dir, prefix string) (name string, err error) {216return TempDir(a.Fs, dir, prefix)217}218219func TempDir(fs Fs, dir, prefix string) (name string, err error) {220if dir == "" {221dir = os.TempDir()222}223224nconflict := 0225for i := 0; i < 10000; i++ {226try := filepath.Join(dir, prefix+nextRandom())227err = fs.Mkdir(try, 0o700)228if os.IsExist(err) {229if nconflict++; nconflict > 10 {230randmu.Lock()231randNum = reseed()232randmu.Unlock()233}234continue235}236if err == nil {237name = try238}239break240}241return242}243244245