Skip to content

Commit

Permalink
Makes golangling happy
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Oct 15, 2023
1 parent ac956b3 commit a5a7aa8
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 60 deletions.
4 changes: 1 addition & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ linters:
disable-all: true
enable:
- bodyclose
- deadcode
- dogsled
- dupl
- errcheck
Expand All @@ -48,14 +47,13 @@ linters:
- predeclared
- revive
- staticcheck
- structcheck
- stylecheck
- thelper
- tparallel
- typecheck
- unconvert
- unparam
- varcheck
- unused
- whitespace
- wsl

Expand Down
5 changes: 4 additions & 1 deletion cmd/wsget/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func init() {

if outputFile != nil && *outputFile != "" {
var err error

OutputFH, err = os.Create(*outputFile)
if err != nil {
log.Fatal(err)
Expand All @@ -40,10 +41,12 @@ func init() {

func main() {
fmt.Println("Connecting to", wsURL, "...")

wsInsp, err := ws.NewWS(wsURL)
if err != nil {
log.Fatal(err)
}

defer wsInsp.Close()

fmt.Println("Connected")
Expand All @@ -64,6 +67,6 @@ func main() {

err = client.Run(OutputFH)
if err != nil {
log.Fatal(err)
log.Println("Error:", err)
}
}
61 changes: 34 additions & 27 deletions pkg/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,34 @@ import (
)

const (
LINE_UP = "\033[1A"
LINE_CLEAR = "\x1b[2K"
LineUp = "\033[1A"
LineClear = "\x1b[2K"

HISTORY_FILE = ".wsget_history"
HISTORY_LIMIT = 100
HistoryFilename = ".wsget_history"
HistoryLimit = 100

MACOS_DELETE_KEY = 127
MacOSDeleteKey = 127

KEYBOARD_BUFFER_SIZE = 10
KeyboardBufferSize = 10
)

type CLI struct {
formater *formater.Formater
history *History
wsConn *ws.WSConnection
wsConn *ws.Connection
}

func NewCLI(wsConn *ws.WSConnection) *CLI {
func NewCLI(wsConn *ws.Connection) *CLI {
currentUser, err := user.Current()
if err != nil {
log.Fatal(err)
}

homeDir := currentUser.HomeDir

return &CLI{
formater: formater.NewFormatter(),
history: NewHistory(homeDir+"/"+HISTORY_FILE, HISTORY_LIMIT),
history: NewHistory(homeDir+"/"+HistoryFilename, HistoryLimit),
wsConn: wsConn,
}
}
Expand All @@ -49,9 +50,14 @@ func (c *CLI) Run(outputFile *os.File) error {
return err
}
defer keyboard.Close()
defer c.history.SaveToFile()
defer func() {
err := c.history.SaveToFile()
if err != nil {
fmt.Println("Fail to save history:", err)
}
}()

keysEvents, err := keyboard.GetKeys(KEYBOARD_BUFFER_SIZE)
keysEvents, err := keyboard.GetKeys(KeyboardBufferSize)
if err != nil {
return err
}
Expand All @@ -61,15 +67,14 @@ func (c *CLI) Run(outputFile *os.File) error {
for {
select {
case event := <-keysEvents:
//nolint:gomnd
switch event.Key {
case keyboard.KeyCtrlC, keyboard.KeyCtrlD:
return nil

case keyboard.KeyEsc:
fmt.Println("Request Mode: Type your API request and press Ctrl+S to send it. Press ESC to cancel request")
req, err := c.requestMode(keysEvents)

req, err := c.requestMode(keysEvents)
if err != nil {
if err.Error() == "interrupted" {
return nil
Expand All @@ -91,7 +96,6 @@ func (c *CLI) Run(outputFile *os.File) error {
}

case msg := <-c.wsConn.Messages:

output, err := c.formater.FormatMessage(msg)
if err != nil {
log.Printf("Fail to format message: %s, %s\n", err, msg.Data)
Expand All @@ -104,6 +108,7 @@ func (c *CLI) Run(outputFile *os.File) error {
if err != nil {
log.Printf("Fail to format message for file: %s, %s\n", err, msg.Data)
}

fmt.Fprintln(outputFile, output)
}
}
Expand All @@ -120,50 +125,52 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) {
return buffer, e.Err
}

//nolint:gomnd
switch e.Key {
case keyboard.KeyCtrlC, keyboard.KeyCtrlD:
return buffer, fmt.Errorf("interrupted")
case keyboard.KeyCtrlS:
if buffer == "" {
return buffer, fmt.Errorf("cannot send empty request")
}

requet := strings.TrimSpace(buffer)

c.history.AddRequest(requet)

return requet, nil
case keyboard.KeyEsc:
return "", nil

case keyboard.KeySpace:
fmt.Print(" ")
buffer += " "
continue

buffer += " "
case keyboard.KeyEnter:
fmt.Print("\n")
buffer += "\n"
continue

case keyboard.KeyBackspace, keyboard.KeyDelete, MACOS_DELETE_KEY:
if len(buffer) == 0 {
buffer += "\n"
case keyboard.KeyBackspace, keyboard.KeyDelete, MacOSDeleteKey:
if buffer == "" {
continue
}

if buffer[len(buffer)-1] == '\n' {
buffer = buffer[:len(buffer)-1]
fmt.Print(LINE_UP)

fmt.Print(LineUp)

startPrevLine := strings.LastIndex(buffer, "\n")
if startPrevLine == -1 {
startPrevLine = 0
} else {
startPrevLine++
}

fmt.Print(buffer[startPrevLine:])
} else {
fmt.Print("\b \b")
buffer = buffer[:len(buffer)-1]
}
continue
case keyboard.KeyArrowUp:
historyIndex++
req := c.history.GetRequst(historyIndex)
Expand All @@ -177,7 +184,6 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) {

fmt.Print(req)
buffer = req
continue
case keyboard.KeyArrowDown:
historyIndex--
req := c.history.GetRequst(historyIndex)
Expand All @@ -191,12 +197,13 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) {

fmt.Print(req)
buffer = req
continue
default:
if e.Key > 0 {
continue
}

fmt.Print(string(e.Rune))

buffer += string(e.Rune)
}
}
Expand All @@ -207,8 +214,8 @@ func (c *CLI) requestMode(keyStream <-chan keyboard.KeyEvent) (string, error) {
func (c *CLI) clearInput(buffer string) {
for i := 0; i < len(buffer); i++ {
if buffer[i] == '\n' {
fmt.Print(LINE_UP)
fmt.Print(LINE_CLEAR)
fmt.Print(LineUp)
fmt.Print(LineClear)
} else {
fmt.Print("\b \b")
}
Expand Down
15 changes: 10 additions & 5 deletions pkg/cli/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import (
"strings"
)

const (
HistoryFileRigths = 0o644
)

type History struct {
requests []string
fileName string
requests []string
limit uint
}

Expand All @@ -20,13 +24,13 @@ func NewHistory(fileName string, limit uint) *History {
requests: make([]string, 0),
}

h.loadFromFile()
_ = h.loadFromFile()

return h
}

func (h *History) loadFromFile() error {
fileHandler, err := os.OpenFile(h.fileName, os.O_RDONLY|os.O_CREATE, 0644)
fileHandler, err := os.OpenFile(h.fileName, os.O_RDONLY|os.O_CREATE, HistoryFileRigths)
if err != nil {
log.Println("Error opening history file:", err)
return err
Expand Down Expand Up @@ -57,9 +61,8 @@ func (h *History) loadFromFile() error {
}

func (h *History) SaveToFile() error {
fileHandler, err := os.OpenFile(h.fileName, os.O_WRONLY|os.O_CREATE, 0644)
fileHandler, err := os.OpenFile(h.fileName, os.O_WRONLY|os.O_CREATE, HistoryFileRigths)
if err != nil {
log.Println("Error opening history file:", err)
return err
}

Expand All @@ -79,7 +82,9 @@ func (h *History) SaveToFile() error {
if request == "" {
continue
}

request = strings.ReplaceAll(request, "\n", "\\n")

_, err := writer.WriteString(request + "\n")
if err != nil {
return err
Expand Down
18 changes: 9 additions & 9 deletions pkg/formater/formater.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import (
// Formater is a struct that contains two formatters, one for text and one for JSON.
type Formater struct {
text *TextFormater
json *JsonFormater
json *JSONFormater
}

// NewFormatter creates a new instance of Formater struct.
func NewFormatter() *Formater {
return &Formater{
text: NewTextFormater(),
json: NewJsonFormater(),
json: NewJSONFormater(),
}
}

Expand All @@ -27,13 +27,13 @@ func NewFormatter() *Formater {
func (f *Formater) FormatMessage(wsMsg ws.Message) (string, error) {
wsMsgData := wsMsg.Data

obj, ok := f.parseJson(wsMsgData)
obj, ok := f.parseJSON(wsMsgData)

if !ok {
return f.formatTestMessage(wsMsg.Type, wsMsgData)
}

return f.formatJsonMessage(wsMsg.Type, obj)
return f.formatJSONMessage(wsMsg.Type, obj)
}

// FormatForFile formats the given WebSocket message for a file.
Expand All @@ -42,7 +42,7 @@ func (f *Formater) FormatMessage(wsMsg ws.Message) (string, error) {
func (f *Formater) FormatForFile(wsMsg ws.Message) (string, error) {
wsMsgData := wsMsg.Data

obj, ok := f.parseJson(wsMsgData)
obj, ok := f.parseJSON(wsMsgData)

if !ok {
return f.text.FormatForFile(wsMsgData)
Expand All @@ -65,8 +65,8 @@ func (f *Formater) formatTestMessage(msgType ws.MessageType, data string) (strin
}
}

// formatJsonMessage formats the given WebSocket message data as JSON based on its type.
func (f *Formater) formatJsonMessage(msgType ws.MessageType, data any) (string, error) {
// formatJSONMessage formats the given WebSocket message data as JSON based on its type.
func (f *Formater) formatJSONMessage(msgType ws.MessageType, data any) (string, error) {
switch msgType {
case ws.Request:
return f.json.FormatRequest(data)
Expand All @@ -79,9 +79,9 @@ func (f *Formater) formatJsonMessage(msgType ws.MessageType, data any) (string,
}
}

// parseJson parses the given string as JSON and returns the parsed object.
// parseJSON parses the given string as JSON and returns the parsed object.
// If the string is not a valid JSON, it returns false as the second value.
func (f *Formater) parseJson(data string) (any, bool) {
func (f *Formater) parseJSON(data string) (any, bool) {
var obj any
err := json.Unmarshal([]byte(data), &obj)

Expand Down
Loading

0 comments on commit a5a7aa8

Please sign in to comment.