/
handler.go
205 lines (192 loc) · 5.35 KB
/
handler.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
195
196
197
198
199
200
201
202
203
204
205
/* This file defines the handlers for different command.
Login
Install
List
Repo
and etc. */
package main
import (
"bufio"
"errors"
"fmt"
"github.com/fatih/color"
"github.com/getsentry/raven-go"
"github.com/manifoldco/promptui"
"github.com/mitchellh/go-homedir"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
)
// Run Repo Response Struct
type RunRepoResponse struct {
Code string `json:"code"`
Port string `json:"port"`
}
// Handle User Login
func LoginHandler(c *cli.Context) User {
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Username: ")
username, _ := reader.ReadString('\n')
username = strings.TrimSpace(username)
fmt.Printf("Password: ")
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
password := strings.TrimSpace(string(bytePassword))
u := User{username, password, ""}
currentUser := u.login()
return currentUser
}
// Handle installation
func InstallHandler(c *cli.Context) {
config := readConfig()
localFolder := config.Local.LocalFolder
remoteURL := c.Args().Get(0)
if remoteURL == "cvpm:py" {
color.Cyan("Installing... Please wait patiently")
pip([]string{"install", "cvpm", "--user"})
return
} else if remoteURL == "webui" {
InstallWebUi()
} else {
color.Cyan("Installing to " + localFolder)
}
// Download Codebase
if strings.HasPrefix(remoteURL, "https://github.com") {
InstallFromGit(remoteURL)
}
}
// Handle List
func listRepos(c *cli.Context) {
config := readConfig()
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"No.", "Name", "Vendor", "Path"})
for i, repo := range config.Repositories {
table.Append([]string{strconv.Itoa(i), repo.Name, repo.Vendor, repo.LocalFolder})
}
table.Render()
}
// Handle Daemon Related
func DaemonHandler(c *cli.Context) {
params := c.Args().Get(0)
switch params {
case "install":
InstallService()
case "uninstall":
UninstallService()
case "run":
runServer(DaemonPort)
default:
color.Red("Unsupported command")
}
}
// Handle Repo Related Command
func RepoHandler(c *cli.Context) {
taskParams := c.Args().Get(0)
switch taskParams {
case "run":
solverstring := c.Args().Get(1)
runningPort := c.Args().Get(2)
runParams := strings.Split(solverstring, "/")
color.Cyan("Running " + runParams[0] + "/" + runParams[1] + "/" + runParams[2])
requestParams := map[string]string{
"vendor": runParams[0],
"name": runParams[1],
"solver": runParams[2],
"port": runningPort,
}
resp := ClientPost("repo/running", requestParams)
var respJson RunRepoResponse
log.Println(resp.JSON(respJson))
color.Red("No port is specified, solver will running on" + respJson.Port)
case "ps":
requestParams := map[string]string{}
ClientGet("repos", requestParams)
case "init":
InitHandler(c)
default:
color.Red("Command Not Supported!")
}
}
// Handle Config Related Command
// validate if python/pip/others exists or does not change
func validateIfProgramAllowed(rawInput string) error {
input := strings.TrimSpace(rawInput)
if input == "y" || input == "Y" || input == "Yes" || input == "" {
return nil
} else {
if _, err := os.Stat(input); os.IsNotExist(err) {
return errors.New(input + " not exists")
} else {
return nil
}
}
}
// trigger and parse input filepath
func InputAndParseConfigContent(label string, validate promptui.ValidateFunc) string {
prompt := promptui.Prompt{
Label: label,
Validate: validate,
}
result, err := prompt.Run()
if err != nil {
fmt.Printf("%v\n", err)
return ""
}
return result
}
func ConfigHandler(c *cli.Context) {
homepath, _ := homedir.Dir()
configFilePath := filepath.Join(homepath, "cvpm", "config.toml")
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
// config file not exists, create it
file, err := os.Create(configFilePath)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
color.Red("An error occurred!")
}
defer file.Close()
// config file not exists, write default to it
writeConfig(getDefaultConfig())
}
prevConfig := readConfig()
var nextConfig cvpmConfig
nextConfig.Local.LocalFolder = prevConfig.Local.LocalFolder
// Handle Python Location
fmt.Println("Original Python Location: " + prevConfig.Local.Python)
newPyLocation := InputAndParseConfigContent("Python(3)", validateIfProgramAllowed)
newPyLocation = strings.TrimSpace(newPyLocation)
if newPyLocation == "y" || newPyLocation == "Y" || newPyLocation == "Yes" || newPyLocation == "" {
newPyLocation = prevConfig.Local.Python
}
nextConfig.Local.Python = newPyLocation
// Handle Pypi Location
fmt.Println("Original Pip Location: " + prevConfig.Local.Pip)
newPipLocation := InputAndParseConfigContent("Pip(3)", validateIfProgramAllowed)
newPipLocation = strings.TrimSpace(newPipLocation)
if newPipLocation == "y" || newPipLocation == "Y" || newPipLocation == "Yes" || newPipLocation == "" {
newPipLocation = prevConfig.Local.Pip
}
nextConfig.Local.Pip = newPipLocation
writeConfig(nextConfig)
}
func InitHandler(c *cli.Context) {
prompt := promptui.Prompt{
Label: "Your Package Name",
}
result, err := prompt.Run()
if err != nil {
panic(err)
}
InitNewRepo(result)
// rename {package_name} to real package name
pyFolderName := filepath.Join(result, "{package_name}")
err = os.Rename(pyFolderName, filepath.Join(result, result))
if err != nil {
fmt.Println(err)
}
}