github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/common/hugio/copy.go (about) 1 // Copyright 2019 The Hugo Authors. All rights reserved. 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 at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package hugio 15 16 import ( 17 "fmt" 18 "io" 19 "path/filepath" 20 21 "github.com/spf13/afero" 22 ) 23 24 // CopyFile copies a file. 25 func CopyFile(fs afero.Fs, from, to string) error { 26 sf, err := fs.Open(from) 27 if err != nil { 28 return err 29 } 30 defer sf.Close() 31 df, err := fs.Create(to) 32 if err != nil { 33 return err 34 } 35 defer df.Close() 36 _, err = io.Copy(df, sf) 37 if err != nil { 38 return err 39 } 40 si, err := fs.Stat(from) 41 if err != nil { 42 err = fs.Chmod(to, si.Mode()) 43 44 if err != nil { 45 return err 46 } 47 } 48 49 return nil 50 } 51 52 // CopyDir copies a directory. 53 func CopyDir(fs afero.Fs, from, to string, shouldCopy func(filename string) bool) error { 54 fi, err := fs.Stat(from) 55 if err != nil { 56 return err 57 } 58 59 if !fi.IsDir() { 60 return fmt.Errorf("%q is not a directory", from) 61 } 62 63 err = fs.MkdirAll(to, 0777) // before umask 64 if err != nil { 65 return err 66 } 67 68 entries, _ := afero.ReadDir(fs, from) 69 for _, entry := range entries { 70 fromFilename := filepath.Join(from, entry.Name()) 71 toFilename := filepath.Join(to, entry.Name()) 72 if entry.IsDir() { 73 if shouldCopy != nil && !shouldCopy(fromFilename) { 74 continue 75 } 76 if err := CopyDir(fs, fromFilename, toFilename, shouldCopy); err != nil { 77 return err 78 } 79 } else { 80 if err := CopyFile(fs, fromFilename, toFilename); err != nil { 81 return err 82 } 83 } 84 85 } 86 87 return nil 88 }