-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
134 lines (107 loc) · 2.39 KB
/
main.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/spf13/cobra"
)
type GlobalOptions struct {
DryRun bool
Verbose bool
Debug bool
Target string
Base string
}
var globalOpts GlobalOptions
func init() {
defaultTarget := os.Getenv("TARGET")
if defaultTarget == "" {
defaultTarget = os.Getenv("HOME")
}
fs := cmdRoot.PersistentFlags()
fs.StringVar(&globalOpts.Target, "target", defaultTarget, "set target directory")
fs.StringVar(&globalOpts.Base, "base", "", "set base directory")
fs.BoolVar(&globalOpts.DryRun, "dry-run", false, "only print actions, do not execute them")
fs.BoolVar(&globalOpts.Verbose, "verbose", false, "be verbose")
fs.BoolVar(&globalOpts.Debug, "debug", false, "print debugging information")
}
var cmdRoot = &cobra.Command{
Use: "dab",
Short: "manage dotfiles and bundles",
SilenceErrors: true,
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) (err error) {
if globalOpts.Base == "" {
globalOpts.Base, err = findBasedir()
if err != nil {
return err
}
}
if globalOpts.Base == "" {
return fmt.Errorf("unable to find basedir")
}
return nil
},
}
func findBasedir() (string, error) {
exe := os.Args[0]
dir, err := filepath.Abs(filepath.Dir(exe))
ok(err)
fi, err := os.Lstat(exe)
ok(err)
if isSymlink(fi) {
dir = readlink(exe)
}
v("looking for basedir in %v\n", dir)
for {
if filepath.Dir(dir) == dir {
return "", errors.New("unable to find bundles.json, pass base directory with `--base`")
}
filename := filepath.Join(dir, "bundles.json")
fi, err = os.Stat(filename)
if err == nil {
v("found basedir: %v\n", dir)
return dir, nil
}
if err != nil && os.IsNotExist(err) {
dir = filepath.Dir(dir)
continue
}
ok(err)
}
}
func ok(err error) {
if err == nil {
return
}
fmt.Fprintf(os.Stderr, "error: %+v\n", err)
os.Exit(1)
}
func v(s string, args ...interface{}) {
if !globalOpts.Verbose {
return
}
fmt.Printf(s, args...)
}
func d(s string, args ...interface{}) {
if !globalOpts.Debug {
return
}
fmt.Printf(s, args...)
}
func msg(s string, args ...interface{}) {
fmt.Printf(s, args...)
}
func warn(s string, args ...interface{}) {
fmt.Fprintf(os.Stderr, s, args...)
}
func main() {
err := cmdRoot.Execute()
var exitCode int
if err != nil {
fmt.Fprintf(os.Stderr, "%+v\n", err)
exitCode = 1
}
os.Exit(exitCode)
}