aboutsummaryrefslogtreecommitdiffstats
path: root/models/unittest/fscopy.go
blob: 4d7ee2151dc29fa03682222d758fb9cc0f8f80c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package unittest

import (
	"os"
	"path/filepath"
	"strings"

	"code.gitea.io/gitea/modules/util"
)

// Copy copies file from source to target path.
func Copy(src, dest string) error {
	// Gather file information to set back later.
	si, err := os.Lstat(src)
	if err != nil {
		return err
	}

	// Handle symbolic link.
	if si.Mode()&os.ModeSymlink != 0 {
		target, err := os.Readlink(src)
		if err != nil {
			return err
		}
		// NOTE: os.Chmod and os.Chtimes don't recognize symbolic link,
		// which will lead "no such file or directory" error.
		return os.Symlink(target, dest)
	}

	return util.CopyFile(src, dest)
}

// Sync synchronizes the two files. This is skipped if both files
// exist and the size, modtime, and mode match.
func Sync(srcPath, destPath string) error {
	dest, err := os.Stat(destPath)
	if err != nil {
		if os.IsNotExist(err) {
			return Copy(srcPath, destPath)
		}
		return err
	}

	src, err := os.Stat(srcPath)
	if err != nil {
		return err
	}

	if src.Size() == dest.Size() &&
		src.ModTime() == dest.ModTime() &&
		src.Mode() == dest.Mode() {
		return nil
	}

	return Copy(srcPath, destPath)
}

// SyncDirs synchronizes files recursively from source to target directory.
// It returns error when error occurs in underlying functions.
func SyncDirs(srcPath, destPath string) error {
	err := os.MkdirAll(destPath, os.ModePerm)
	if err != nil {
		return err
	}

	// find and delete all untracked files
	destFiles, err := util.StatDir(destPath, true)
	if err != nil {
		return err
	}
	for _, destFile := range destFiles {
		destFilePath := filepath.Join(destPath, destFile)
		if _, err = os.Stat(filepath.Join(srcPath, destFile)); err != nil {
			if os.IsNotExist(err) {
				// if src file does not exist, remove dest file
				if err = os.RemoveAll(destFilePath); err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	// sync src files to dest
	srcFiles, err := util.StatDir(srcPath, true)
	if err != nil {
		return err
	}
	for _, srcFile := range srcFiles {
		destFilePath := filepath.Join(destPath, srcFile)
		// util.StatDir appends a slash to the directory name
		if strings.HasSuffix(srcFile, "/") {
			err = os.MkdirAll(destFilePath, os.ModePerm)
		} else {
			err = Sync(filepath.Join(srcPath, srcFile), destFilePath)
		}
		if err != nil {
			return err
		}
	}
	return nil
}