trans-alfred/trans/trans.go

75 lines
1.5 KiB
Go
Raw Normal View History

2019-04-05 23:02:12 +00:00
package trans
2019-04-05 22:30:10 +00:00
import (
"fmt"
"os/exec"
"strings"
"regexp"
2019-04-05 22:30:10 +00:00
)
type Translation struct {
2019-04-05 22:37:17 +00:00
word string
fromLang string
toLang string
2019-10-10 23:56:22 +00:00
Executor func(*Translation) ([]byte, error)
2019-04-05 22:37:17 +00:00
}
func New(word, fromLang, toLang string) Translation {
return Translation{
2019-10-10 23:56:22 +00:00
word: word,
fromLang: fromLang,
toLang: toLang,
Executor: executeTransShell,
2019-04-05 22:30:10 +00:00
}
}
2019-10-10 23:56:22 +00:00
func executeTransShell(t *Translation) ([]byte, error) {
2019-04-05 22:30:10 +00:00
config := []string{
"-no-ansi",
2019-04-05 22:30:10 +00:00
"-show-original", "n",
"-show-original-phonetics", "n",
"-show-dictionary", "y",
2019-04-05 22:30:10 +00:00
"-show-languages", "n",
"-show-prompt-message", "n",
2019-10-10 23:56:22 +00:00
fmt.Sprintf("%s:%s", t.fromLang, t.toLang),
t.word,
2019-04-05 22:30:10 +00:00
}
return exec.Command("trans", config...).Output()
}
func (t Translation) Translate() []string {
2019-10-10 23:56:22 +00:00
outBytes, err := t.Executor(&t)
if err != nil {
panic(err)
}
return uniqueSlice(parseTransOutput(string(outBytes)))
}
2019-04-05 22:30:10 +00:00
func parseTransOutput(out string) []string {
re := regexp.MustCompile(`(?m)^\s{4}\w.*$`)
lineMatches := re.FindAllString(out, -1)
2019-04-05 22:30:10 +00:00
results := []string{strings.Split(out, "\n")[0]}
for _, line := range lineMatches {
for _, word := range strings.Split(strings.TrimSpace(line), ",") {
results = append(results, strings.TrimSpace(word))
}
2019-04-05 22:30:10 +00:00
}
return results
2019-04-05 22:30:10 +00:00
}
func uniqueSlice(items []string) []string {
encountered := map[string]bool{}
uniqueSlice := []string{}
for _, item := range items {
if !encountered[item] {
encountered[item] = true
uniqueSlice = append(uniqueSlice, item)
}
}
return uniqueSlice
}