Debian Codegraph @

common/hugio/copy.go

raw ◀ ▶
1 Debian patch touch this file
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
45 if err != nil {
46 return err
47 }
48 }
49
50 return nil
51 }
52
53 // CopyDir copies a directory.
54 func CopyDir(fs afero.Fs, from, to string, shouldCopy func(filename string) bool) error {
55 fi, err := fs.Stat(from)
56 if err != nil {
57 return err
58 }
59
60 if !fi.IsDir() {
61 return fmt.Errorf("%q is not a directory", from)
62 }
63
64 err = fs.MkdirAll(to, 0o777) // before umask
65 if err != nil {
66 return err
67 }
68
69 d, err := fs.Open(from)
70 if err != nil {
71 return err
72 }
73 entries, _ := d.(iofs.ReadDirFile).ReadDir(-1)
74 for _, entry := range entries {
75 fromFilename := filepath.Join(from, entry.Name())
76 toFilename := filepath.Join(to, entry.Name())
77 if entry.IsDir() {
78 if shouldCopy != nil && !shouldCopy(fromFilename) {
79 continue
80 }
81 if err := CopyDir(fs, fromFilename, toFilename, shouldCopy); err != nil {
82 return err
83 }
84 } else {
•85 if shouldCopy != nil && !shouldCopy(fromFilename) {
86 continue
87 }
88 if err := CopyFile(fs, fromFilename, toFilename); err != nil {
89 return err
90 }
91 }
92
93 }
94
95 return nil
96 }