-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply.go
More file actions
97 lines (90 loc) · 2.04 KB
/
Copy pathapply.go
File metadata and controls
97 lines (90 loc) · 2.04 KB
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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
)
func cmdApply(args []string) int {
fs := flag.NewFlagSet("apply", flag.ExitOnError)
var o opts
registerFlags(fs, &o)
fs.Parse(args)
if len(o.files) == 0 {
fmt.Fprintln(os.Stderr, "error: -f required")
fs.Usage()
return 1
}
cfg, err := loadConfigs(o.files)
if err != nil {
fmt.Fprintf(os.Stderr, "error loading config: %v\n", err)
return 1
}
names := collectNames(o.names)
exit := 0
for _, s := range collectStatuses(cfg, names) {
if !matchType(s, o.types) || !matchState(s.state, o.states) {
continue
}
var newState entryState
var err error
switch s.kind {
case "dotfile":
newState, err = applyDotfile(s)
case "repo":
newState, err = applyRepo(s)
default:
continue
}
if err != nil {
fmt.Fprintf(os.Stderr, "error %s: %v\n", s.name, err)
exit = 1
continue
}
s.state = newState
outputEntry(s, o.fields)
}
return exit
}
// applyDotfile creates a symlink for the entry if needed.
// Returns the resulting state and any error.
func applyDotfile(s entryStatus) (entryState, error) {
switch s.state {
case stateOK:
return stateOK, nil
case stateBlocked, stateSrcMissing:
return s.state, nil
case stateEmpty:
if err := os.MkdirAll(filepath.Dir(s.dest), 0o755); err != nil {
return stateBlocked, err
}
if err := os.Symlink(s.src, s.dest); err != nil {
return stateBlocked, err
}
return stateChanged, nil
}
return stateOK, nil
}
// applyRepo clones the repo if not already present.
// Returns the resulting state and any error.
func applyRepo(s entryStatus) (entryState, error) {
switch s.state {
case stateOK:
return stateOK, nil
case stateBlocked:
return stateBlocked, nil
case stateEmpty:
if err := os.MkdirAll(filepath.Dir(s.dest), 0o755); err != nil {
return stateBlocked, err
}
cmd := exec.Command("git", "clone", s.url, s.dest)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return stateBlocked, err
}
return stateChanged, nil
}
return stateOK, nil
}