2
* ALR - Any Linux Repository
3
* Copyright (C) 2024 Евгений Храмов
5
* This program is free software: you can redistribute it and/or modify
6
* it under the terms of the GNU General Public License as published by
7
* the Free Software Foundation, either version 3 of the License, or
8
* (at your option) any later version.
10
* This program 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
13
* GNU General Public License for more details.
15
* You should have received a copy of the GNU General Public License
16
* along with this program. If not, see <http://www.gnu.org/licenses/>.
27
// Move attempts to use os.Rename and if that fails (such as for a cross-device move),
28
// it instead copies the source to the destination and then removes the source.
29
func Move(sourcePath, destPath string) error {
30
// Try to rename the source to the destination
31
err := os.Rename(sourcePath, destPath)
33
return nil // Successful move
36
// Rename failed, so copy the source to the destination
37
err = copyDirOrFile(sourcePath, destPath)
42
// Copy successful, remove the original source
43
err = os.RemoveAll(sourcePath)
51
func copyDirOrFile(sourcePath, destPath string) error {
52
sourceInfo, err := os.Stat(sourcePath)
57
if sourceInfo.IsDir() {
58
return copyDir(sourcePath, destPath, sourceInfo)
59
} else if sourceInfo.Mode().IsRegular() {
60
return copyFile(sourcePath, destPath, sourceInfo)
62
// ignore non-regular files
67
func copyDir(sourcePath, destPath string, sourceInfo os.FileInfo) error {
68
err := os.MkdirAll(destPath, sourceInfo.Mode())
73
entries, err := os.ReadDir(sourcePath)
78
for _, entry := range entries {
79
sourceEntry := filepath.Join(sourcePath, entry.Name())
80
destEntry := filepath.Join(destPath, entry.Name())
82
err = copyDirOrFile(sourceEntry, destEntry)
91
func copyFile(sourcePath, destPath string, sourceInfo os.FileInfo) error {
92
sourceFile, err := os.Open(sourcePath)
96
defer sourceFile.Close()
98
destFile, err := os.OpenFile(destPath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, sourceInfo.Mode())
102
defer destFile.Close()
104
_, err = io.Copy(destFile, sourceFile)