aboutsummaryrefslogtreecommitdiffstats
path: root/sync.go
blob: 293f20bf5dcf33811b30ae0c29553ce0c5f100a0 (plain) (blame)
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
package main

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

	ignore "github.com/sabhiram/go-gitignore"
)

type FileMeta struct {
	Size     int64
	Mode     os.FileMode
	Symlink  string
}

type Manifest struct {
	Files map[string]FileMeta
}

func initialSync(hostDir, dataDir string, rules *ignore.GitIgnore, dryRun bool) (*Manifest, error) {
	manifest := &Manifest{Files: make(map[string]FileMeta)}

	err := filepath.Walk(hostDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		relPath, err := filepath.Rel(hostDir, path)
		if err != nil {
			return err
		}

		if relPath == "." {
			return nil
		}

		if relPath == ".git" || strings.HasPrefix(relPath, ".git"+string(filepath.Separator)) {
			return filepath.SkipDir
		}

		if rules.MatchesPath(relPath) {
			if info.IsDir() {
				return filepath.SkipDir
			}
			return nil
		}

		destPath := filepath.Join(dataDir, relPath)

		linkTarget := ""
		if info.Mode()&os.ModeSymlink != 0 {
			linkTarget, err = os.Readlink(path)
			if err != nil {
				return err
			}
		}

		meta := FileMeta{
			Size:    info.Size(),
			Mode:    info.Mode(),
			Symlink: linkTarget,
		}
		manifest.Files[relPath] = meta

		if dryRun {
			log.Printf("[dry-run] would sync: %s", relPath)
			return nil
		}

		if info.IsDir() {
			return os.MkdirAll(destPath, info.Mode())
		}

		if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
			return err
		}

		if linkTarget != "" {
			return os.Symlink(linkTarget, destPath)
		}

		return copyFile(path, destPath, info.Mode())
	})

	return manifest, err
}

func copyFile(src, dst string, mode os.FileMode) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}