diff --git a/.gitignore b/.gitignore index dcc6883..d8db0d2 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,4 @@ Thumbs.db cmd/config.yaml /client log.ttrace +build/ diff --git a/Makefile b/Makefile index 90aaf0e..69078c9 100644 --- a/Makefile +++ b/Makefile @@ -6,6 +6,10 @@ devtools: go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.1 go install mvdan.cc/gofumpt@latest +## Building +build-cli: + go build -o ./build/ttrace ./cmd/main.go + ### Testing unit_test: go test $(PACKAGES) diff --git a/cmd/commands/repl.go b/cmd/commands/repl.go new file mode 100644 index 0000000..d99c2f8 --- /dev/null +++ b/cmd/commands/repl.go @@ -0,0 +1,75 @@ +package commands + +import ( + "bufio" + "errors" + "fmt" + "net" + "os" + "strings" + "time" + + cobra "github.com/spf13/cobra" +) + +const PROMPT = "\n>> " + +func REPLCommand(parentCmd *cobra.Command) { + connect := &cobra.Command{ + Use: "connect", + Short: "Connects you to a time trace instance and you can interact with it in a REPL interface.", + } + parentCmd.AddCommand(connect) + + address := connect.Flags().StringP("address", "a", "localhost:7070", "remote address of your time trace instance.") + username := connect.Flags().StringP("username", "u", "root", "username of the user you are going to connect with.") + password := connect.Flags().StringP("password", "p", "", "password of user trying to connect with.") + + connect.Run = func(cmd *cobra.Command, args []string) { + conn, err := net.Dial("tcp", *address) + if err != nil { + dead(cmd, err) + } + defer conn.Close() + + conQuery := fmt.Sprintf("CON %v %v", *username, *password) + + response := do(conn, conQuery) + if response == "DONE" { + reader := bufio.NewReader(os.Stdin) + + for { + fmt.Print(PROMPT) + + input, _ := reader.ReadString('\n') + input = strings.TrimSuffix(input, "\n") + + if input == "exit" { + break + } + + cmd.Print(do(conn, input)) + } + } else { + dead(cmd, errors.New(response)) //nolint + } + } +} + +func do(conn net.Conn, q string) string { + resBuf := make([]byte, 1024) + + _, err := conn.Write([]byte(q)) + if err != nil { + return err.Error() + } + + time.Sleep(time.Second * 1) + + n, err := conn.Read(resBuf) + if err != nil { + return err.Error() + } + + return string(resBuf[:n]) +} diff --git a/cmd/main.go b/cmd/main.go index 548afff..bac612b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -8,11 +8,12 @@ import ( func main() { rootCmd := &cobra.Command{ - Use: "time-trace", + Use: "ttrace", Version: timetrace.StringVersion(), } commands.RunCommand(rootCmd) + commands.REPLCommand(rootCmd) err := rootCmd.Execute() if err != nil { diff --git a/utils/errors/errors.go b/utils/errors/errors.go index 1654358..520df83 100644 --- a/utils/errors/errors.go +++ b/utils/errors/errors.go @@ -10,4 +10,7 @@ var ( // server. ErrAuth = errors.New("authentication error") + + // CLI. + ErrInvalidUserOrPassword = errors.New("user or user information you provided is invalid") )