1 /* 2 Copyright 2016 Google LLC 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 https://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 // Package file provides utility file operations. 18 package file 19 20 import ( 21 "fmt" 22 "io" 23 "io/ioutil" 24 "os" 25 ) 26 27 // ReadFile can be updated from the caller to change the API 28 // for reading a file. 29 var ReadFile = readFile 30 // WriteFile can be updated from the caller to change the API 31 // for writing a file. 32 var WriteFile = writeFile 33 // OpenReadFile can be updated from the caller to change the API 34 // for opening a file. 35 var OpenReadFile = openReadFile 36 37 // readFile is like ioutil.ReadFile. 38 func readFile(name string) ([]byte, os.FileInfo, error) { 39 fi, err := os.Stat(name) 40 if err != nil { 41 return nil, nil, err 42 } 43 44 data, err := ioutil.ReadFile(name) 45 return data, fi, err 46 } 47 48 // writeFile is like ioutil.WriteFile. 49 func writeFile(name string, data []byte) error { 50 return ioutil.WriteFile(name, data, 0644) 51 } 52 53 // openReadFile is like os.Open. 54 func openReadFile(name string) io.ReadCloser { 55 f, err := os.Open(name) 56 if err != nil { 57 fmt.Fprintf(os.Stderr, "Could not open %s\n", name) 58 os.Exit(1) 59 } 60 return f 61 } 62