trans-alfred/trans/trans.go

76 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-11 20:08:06 +00:00
Translator func(*Translation) (string, 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,
2019-10-11 20:08:06 +00:00
Translator: executeTransShell,
2019-04-05 22:30:10 +00:00
}
}
2019-10-11 20:08:06 +00:00
func executeTransShell(t *Translation) (string, 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
}
2019-10-11 20:08:06 +00:00
outBytes, err := exec.Command("trans", config...).Output()
return string(outBytes), err
2019-04-05 22:30:10 +00:00
}
func (t Translation) Translate() []string {
2019-10-11 20:08:06 +00:00
output, err := t.Translator(&t)
if err != nil {
panic(err)
}
2019-10-11 20:08:06 +00:00
return uniqueSlice(parseTransOutput(output))
}
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
}