Skip to content

Commit

Permalink
Valid input text
Browse files Browse the repository at this point in the history
  • Loading branch information
candy12t committed Sep 11, 2021
1 parent 7e00947 commit db3fdc3
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 12 deletions.
4 changes: 1 addition & 3 deletions cmd/deepl-cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,5 @@ func main() {
flag.Parse()
fmt.Printf("Translate text from %s to %s\n", sourceLang, targetLang)

if err := repl.Repl(sourceLang, targetLang); err != nil {
log.Fatal(err)
}
repl.Repl(sourceLang, targetLang)
}
29 changes: 20 additions & 9 deletions internal/repl/repl.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,40 @@ package repl
import (
"bufio"
"fmt"
"io"
"os"
"strings"

"github.com/candy12t/deepl-cli/api"
)

const PROMPT = ">> "

func Repl(sourceLang, targetLang string) error {
func Repl(sourceLang, targetLang string) {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Printf(PROMPT)
if scanned := scanner.Scan(); !scanned {
return fmt.Errorf("can not scan")
return
}

text := scanner.Text()
tr, err := api.Translate(text, sourceLang, targetLang)
if err != nil {
return err
if validedText, err := validText(text); err != nil {
fmt.Println(err)
} else {
tr, err := api.Translate(validedText, sourceLang, targetLang)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(tr.TranslatedText())
}
out := os.Stdout
io.WriteString(out, tr.TranslatedText())
io.WriteString(out, "\n")
}
}

func validText(text string) (string, error) {
validedText := strings.TrimSpace(text)
if len(validedText) == 0 {
return "", fmt.Errorf("Error: text length is 0")
}
return validedText, nil
}
26 changes: 26 additions & 0 deletions internal/repl/repl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package repl

import (
"testing"
)

func TestVaildText(t *testing.T) {
tests := []struct {
input string
expectedText string
}{
{"\thello\t", "hello"},
{" hello world ", "hello world"},
{"\t hoge fuga \t", "hoge fuga"},
{"\t\n", ""},
{" ", ""},
}

for _, tt := range tests {
text, _ := validText(tt.input)

if tt.expectedText != text {
t.Fatalf("validText() got=%q, expectedText=%q", text, tt.expectedText)
}
}
}

0 comments on commit db3fdc3

Please sign in to comment.