github.com/e154/smart-home@v0.17.2-0.20240311175135-e530a6e5cd45/system/backup/dir.go (about) 1 // This file is part of the Smart Home 2 // Program complex distribution https://github.com/e154/smart-home 3 // Copyright (C) 2016-2023, Filippov Alex 4 // 5 // This library is free software: you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 3 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Library General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library. If not, see 17 // <https://www.gnu.org/licenses/>. 18 19 package backup 20 21 import ( 22 "io" 23 "os" 24 "path" 25 ) 26 27 // File copies a single file from src to dst 28 func CopyFile(src, dst string) error { 29 var err error 30 var srcfd *os.File 31 var dstfd *os.File 32 var srcinfo os.FileInfo 33 34 if srcfd, err = os.Open(src); err != nil { 35 return err 36 } 37 defer srcfd.Close() 38 39 if dstfd, err = os.Create(dst); err != nil { 40 return err 41 } 42 defer dstfd.Close() 43 44 if _, err = io.Copy(dstfd, srcfd); err != nil { 45 return err 46 } 47 if srcinfo, err = os.Stat(src); err != nil { 48 return err 49 } 50 return os.Chmod(dst, srcinfo.Mode()) 51 } 52 53 // Dir copies a whole directory recursively 54 func Copy(src string, dst string) error { 55 var err error 56 var fds []os.DirEntry 57 var srcinfo os.FileInfo 58 59 if srcinfo, err = os.Stat(src); err != nil { 60 return err 61 } 62 63 if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil { 64 return err 65 } 66 67 if fds, err = os.ReadDir(src); err != nil { 68 return err 69 } 70 for _, fd := range fds { 71 srcfp := path.Join(src, fd.Name()) 72 dstfp := path.Join(dst, fd.Name()) 73 74 if fd.IsDir() { 75 if err = Copy(srcfp, dstfp); err != nil { 76 return err 77 } 78 } else { 79 if err = CopyFile(srcfp, dstfp); err != nil { 80 return err 81 } 82 } 83 } 84 return nil 85 }