copy.go (1948B)
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 "io/ioutil"
20 "os"
21 "path/filepath"
22
23 "github.com/spf13/afero"
24 )
25
26 // CopyFile copies a file.
27 func CopyFile(fs afero.Fs, from, to string) error {
28 sf, err := fs.Open(from)
29 if err != nil {
30 return err
31 }
32 defer sf.Close()
33 df, err := fs.Create(to)
34 if err != nil {
35 return err
36 }
37 defer df.Close()
38 _, err = io.Copy(df, sf)
39 if err != nil {
40 return err
41 }
42 si, err := fs.Stat(from)
43 if err != nil {
44 err = fs.Chmod(to, si.Mode())
45
46 if err != nil {
47 return err
48 }
49 }
50
51 return nil
52 }
53
54 // CopyDir copies a directory.
55 func CopyDir(fs afero.Fs, from, to string, shouldCopy func(filename string) bool) error {
56 fi, err := os.Stat(from)
57 if err != nil {
58 return err
59 }
60
61 if !fi.IsDir() {
62 return fmt.Errorf("%q is not a directory", from)
63 }
64
65 err = fs.MkdirAll(to, 0777) // before umask
66 if err != nil {
67 return err
68 }
69
70 entries, _ := ioutil.ReadDir(from)
71 for _, entry := range entries {
72 fromFilename := filepath.Join(from, entry.Name())
73 toFilename := filepath.Join(to, entry.Name())
74 if entry.IsDir() {
75 if shouldCopy != nil && !shouldCopy(fromFilename) {
76 continue
77 }
78 if err := CopyDir(fs, fromFilename, toFilename, shouldCopy); err != nil {
79 return err
80 }
81 } else {
82 if err := CopyFile(fs, fromFilename, toFilename); err != nil {
83 return err
84 }
85 }
86
87 }
88
89 return nil
90 }