-
Notifications
You must be signed in to change notification settings - Fork 87
/
cmd.go
103 lines (80 loc) · 1.83 KB
/
cmd.go
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
package rsync
import (
"errors"
"fmt"
"strconv"
"strings"
)
type Cmd struct {
Port int
NoChown bool
Delete bool
SrcUseSSH bool
DestUseSSH bool
Command string
SrcSSHUser string
SrcSSHHost string
SrcPath string
DestSSHUser string
DestSSHHost string
DestPath string
Compress bool
}
func (c *Cmd) Build() (string, error) {
if c.SrcUseSSH && c.DestUseSSH {
return "", errors.New("cannot use ssh on both source and destination")
}
cmd := "rsync"
if c.Command != "" {
cmd = c.Command
}
sshArgs := []string{
"ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null",
"-o", "ConnectTimeout=5",
}
if c.Port != 0 {
sshArgs = append(sshArgs, "-p", strconv.Itoa(c.Port))
}
sshArgsStr := fmt.Sprintf("\"%s\"", strings.Join(sshArgs, " "))
rsyncArgs := []string{
"-av", "--info=progress2,misc0,flist0",
"--no-inc-recursive", "-e", sshArgsStr,
}
if c.Compress {
rsyncArgs = append(rsyncArgs, "-z")
}
if c.NoChown {
rsyncArgs = append(rsyncArgs, "--no-o", "--no-g")
}
if c.Delete {
rsyncArgs = append(rsyncArgs, "--delete")
}
rsyncArgsStr := strings.Join(rsyncArgs, " ")
src := c.buildSrc()
dest := c.buildDest()
return fmt.Sprintf("%s %s %s %s", cmd, rsyncArgsStr, src, dest), nil
}
func (c *Cmd) buildSrc() string {
var src strings.Builder
if c.SrcUseSSH {
sshDestUser := "root"
if c.SrcSSHUser != "" {
sshDestUser = c.SrcSSHUser
}
src.WriteString(fmt.Sprintf("%s@%s:", sshDestUser, c.SrcSSHHost))
}
src.WriteString(c.SrcPath)
return src.String()
}
func (c *Cmd) buildDest() string {
var dest strings.Builder
if c.DestUseSSH {
sshDestUser := "root"
if c.DestSSHUser != "" {
sshDestUser = c.DestSSHUser
}
dest.WriteString(fmt.Sprintf("%s@%s:", sshDestUser, c.DestSSHHost))
}
dest.WriteString(c.DestPath)
return dest.String()
}