forked from go-flutter-desktop/hover
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
194 lines (168 loc) · 5.22 KB
/
common.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package cmd
import (
"bufio"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/pkg/errors"
"github.com/sudonims/hover/internal/build"
"github.com/sudonims/hover/internal/log"
"github.com/sudonims/hover/internal/pubspec"
"github.com/sudonims/hover/internal/version"
)
// assertInFlutterProject asserts this command is executed in a flutter project
func assertInFlutterProject() {
pubspec.GetPubSpec()
}
// assertInFlutterPluginProject asserts this command is executed in a flutter plugin project
func assertInFlutterPluginProject() {
if _, ok := pubspec.GetPubSpec().Flutter["plugin"]; !ok {
log.Errorf("The directory doesn't appear to contain a plugin package.\nTo create a new plugin, first run `%s`, then run `%s`.", log.Au().Magenta("flutter create --template=plugin"), log.Au().Magenta("hover init-plugin"))
os.Exit(1)
}
}
func assertHoverInitialized() {
_, err := os.Stat(build.BuildPath)
if os.IsNotExist(err) {
if hoverMigrateDesktopToGo() {
return
}
log.Errorf("Directory '%s' is missing. Please init go-flutter first: %s", build.BuildPath, log.Au().Magenta("hover init"))
os.Exit(1)
}
if err != nil {
log.Errorf("Failed to detect directory desktop: %v", err)
os.Exit(1)
}
}
func checkFlutterChannel() {
channel := version.FlutterChannel()
ignoreWarning := os.Getenv("HOVER_IGNORE_CHANNEL_WARNING")
if channel != "beta" && ignoreWarning != "true" {
log.Warnf("⚠ The go-flutter project tries to stay compatible with the beta channel of Flutter.")
log.Warnf("⚠ It's advised to use the beta channel: `%s`", log.Au().Magenta("flutter channel beta"))
}
}
// hoverMigrateDesktopToGo migrates from old hover buildPath directory to the new one ("desktop" -> "go")
func hoverMigrateDesktopToGo() bool {
oldBuildPath := "desktop"
file, err := os.Open(filepath.Join(oldBuildPath, "go.mod"))
if err != nil {
return false
}
defer file.Close()
log.Warnf("⚠ Found older hover directory layout, hover is now expecting a 'go' directory instead of 'desktop'.")
log.Warnf("⚠ To migrate, rename the 'desktop' directory to 'go'.")
log.Warnf(" Let hover do the migration? ")
if askForConfirmation() {
err := os.Rename(oldBuildPath, build.BuildPath)
if err != nil {
log.Warnf("Migration failed: %v", err)
return false
}
log.Infof("Migration success")
return true
}
return false
}
// askForConfirmation asks the user for confirmation.
func askForConfirmation() bool {
fmt.Print(log.Au().Bold(log.Au().Cyan("hover: ")).String() + "[y/N]? ")
if len(os.Getenv("HOVER_DISABLE_INTERACTIONS")) > 0 {
fmt.Println(log.Au().Bold(log.Au().Yellow("Interactions disabled, assuming 'no'.")).String())
return false
}
in := bufio.NewReader(os.Stdin)
s, err := in.ReadString('\n')
if err != nil {
panic(err)
}
s = strings.TrimSpace(s)
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return true
}
return false
}
var camelcaseRegex = regexp.MustCompile("(^[A-Za-z])|_([A-Za-z])")
// toCamelCase take a snake_case string and converts it to camelcase
func toCamelCase(str string) string {
return camelcaseRegex.ReplaceAllStringFunc(str, func(s string) string {
return strings.ToUpper(strings.Replace(s, "_", "", -1))
})
}
// initializeGoModule uses the golang binary to initialize the go module
func initializeGoModule(projectPath string) {
wd, err := os.Getwd()
if err != nil {
log.Errorf("Failed to get working dir: %v\n", err)
os.Exit(1)
}
cmdGoModInit := exec.Command(build.GoBin(), "mod", "init", projectPath+"/"+build.BuildPath)
cmdGoModInit.Dir = filepath.Join(wd, build.BuildPath)
cmdGoModInit.Env = append(os.Environ(),
"GO111MODULE=on",
)
cmdGoModInit.Stderr = os.Stderr
cmdGoModInit.Stdout = os.Stdout
err = cmdGoModInit.Run()
if err != nil {
log.Errorf("Go mod init failed: %v\n", err)
os.Exit(1)
}
cmdGoModTidy := exec.Command(build.GoBin(), "mod", "tidy")
cmdGoModTidy.Dir = filepath.Join(wd, build.BuildPath)
log.Infof("You can add the '%s' directory to git.", cmdGoModTidy.Dir)
cmdGoModTidy.Env = append(os.Environ(),
"GO111MODULE=on",
)
cmdGoModTidy.Stderr = os.Stderr
cmdGoModTidy.Stdout = os.Stdout
err = cmdGoModTidy.Run()
if err != nil {
log.Errorf("Go mod tidy failed: %v\n", err)
os.Exit(1)
}
}
// findPubcachePath returns the absolute path for the pub-cache or an error.
func findPubcachePath() (string, error) {
var path string
switch runtime.GOOS {
case "darwin", "linux":
home, err := os.UserHomeDir()
if err != nil {
return "", errors.Wrap(err, "failed to resolve user home dir")
}
path = filepath.Join(home, ".pub-cache")
case "windows":
path = filepath.Join(os.Getenv("APPDATA"), "Pub", "Cache")
}
return path, nil
}
// shouldRunPluginGet checks if the pubspec.yaml file is older than the
// .packages file, if it is the case, prompt the user for a hover plugin get.
func shouldRunPluginGet() (bool, error) {
file1Info, err := os.Stat("pubspec.yaml")
if err != nil {
return false, err
}
file2Info, err := os.Stat(".packages")
if err != nil {
if os.IsNotExist(err) {
return true, nil
}
return false, err
}
modTime1 := file1Info.ModTime()
modTime2 := file2Info.ModTime()
diff := modTime1.Sub(modTime2)
if diff > (time.Duration(0) * time.Second) {
return true, nil
}
return false, nil
}