github.com/Schaudge/grailbase@v0.0.0-20240223061707-44c758a471c0/file/util.go (about) 1 // Copyright 2018 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 package file 6 7 import ( 8 "context" 9 "fmt" 10 "io/ioutil" 11 12 "golang.org/x/sync/errgroup" 13 ) 14 15 // ReadFile reads the given file and returns the contents. A successful call 16 // returns err == nil, not err == EOF. Arg opts is passed to file.Open. 17 func ReadFile(ctx context.Context, path string, opts ...Opts) ([]byte, error) { 18 in, err := Open(ctx, path, opts...) 19 if err != nil { 20 return nil, err 21 } 22 data, err := ioutil.ReadAll(in.Reader(ctx)) 23 if err != nil { 24 in.Close(ctx) // nolint: errcheck 25 return nil, err 26 } 27 return data, in.Close(ctx) 28 } 29 30 // WriteFile writes data to the given file. If the file does not exist, 31 // WriteFile creates it; otherwise WriteFile truncates it before writing. 32 func WriteFile(ctx context.Context, path string, data []byte) error { 33 out, err := Create(ctx, path) 34 if err != nil { 35 return err 36 } 37 n, err := out.Writer(ctx).Write(data) 38 if n != len(data) && err == nil { 39 err = fmt.Errorf("writefile %s: requested to write %d bytes, actually wrote %d bytes", path, len(data), n) 40 } 41 if err != nil { 42 out.Close(ctx) // nolint: errcheck 43 return err 44 } 45 return out.Close(ctx) 46 } 47 48 // RemoveAll removes path and any children it contains. It is unspecified 49 // whether empty directories are removed by this function. It removes 50 // everything it can but returns the first error it encounters. If the path does 51 // not exist, RemoveAll returns nil. 52 func RemoveAll(ctx context.Context, path string) error { 53 g, ectx := errgroup.WithContext(ctx) 54 l := List(ectx, path, true) 55 for l.Scan() { 56 if !l.IsDir() { 57 path := l.Path() 58 g.Go(func() error { return Remove(ectx, path) }) 59 } 60 } 61 return g.Wait() 62 }