trans-alfred/trans/trans.go

71 lines
1.5 KiB
Go

package trans
import (
"fmt"
"os/exec"
"strings"
"log"
)
type Translator interface {
Translate() []string
}
type transJob struct {
word string
fromLang string
toLang string
}
func New(word, fromLang, toLang string) Translator {
return transJob{word: word, fromLang: fromLang, toLang: toLang}
}
func (tj transJob) Translate() []string {
outBytes, err := tj.execTrans()
if err != nil {
log.Fatalf("Failed to execute command 'trans': %v", err)
}
return uniqueSlice(parseTransOutput(string(outBytes)))
}
func (tj transJob) execTrans() ([]byte, error) {
config := []string{
"-no-ansi",
"-show-original", "n",
"-show-original-phonetics", "n",
"-show-dictionary", "n",
"-show-languages", "n",
"-show-prompt-message", "n",
fmt.Sprintf("%s:%s", tj.fromLang, tj.toLang),
tj.word,
}
return exec.Command("trans", config...).Output()
}
func parseTransOutput(out string) []string {
outLines := strings.Split(out, "\n")
translation := outLines[0]
additionalTranslations := strings.Split(outLines[len(outLines)-2], ",")
for i, translation := range additionalTranslations {
additionalTranslations[i] = strings.TrimSpace(translation)
}
return append([]string{translation}, additionalTranslations...)
}
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
}