github.com/neohugo/neohugo@v0.123.8/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 iofs "io/fs" 20 "path/filepath" 21 22 "github.com/spf13/afero" 23 ) 24 25 // CopyFile copies a file. 26 func CopyFile(fs afero.Fs, from, to string) error { 27 sf, err := fs.Open(from) 28 if err != nil { 29 return err 30 } 31 defer sf.Close() 32 df, err := fs.Create(to) 33 if err != nil { 34 return err 35 } 36 defer df.Close() 37 _, err = io.Copy(df, sf) 38 if err != nil { 39 return err 40 } 41 si, err := fs.Stat(from) 42 if err != nil { 43 err = fs.Chmod(to, si.Mode()) 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, 0o777) // before umask 64 if err != nil { 65 return err 66 } 67 68 d, err := fs.Open(from) 69 if err != nil { 70 return err 71 } 72 entries, _ := d.(iofs.ReadDirFile).ReadDir(-1) 73 for _, entry := range entries { 74 fromFilename := filepath.Join(from, entry.Name()) 75 toFilename := filepath.Join(to, entry.Name()) 76 if entry.IsDir() { 77 if shouldCopy != nil && !shouldCopy(fromFilename) { 78 continue 79 } 80 if err := CopyDir(fs, fromFilename, toFilename, shouldCopy); err != nil { 81 return err 82 } 83 } else { 84 if err := CopyFile(fs, fromFilename, toFilename); err != nil { 85 return err 86 } 87 } 88 89 } 90 91 return nil 92 }