trans-alfred/trans/trans.go

80 lines
1.6 KiB
Go

package trans
import (
"fmt"
"os/exec"
"strings"
"log"
)
type Translation struct {
job TransJob
Executor func(TransJob) ([]byte, error)
}
type TransJob struct {
word string
fromLang string
toLang string
}
func New(word, fromLang, toLang string) Translation {
return Translation{
job: TransJob{
word: word,
fromLang: fromLang,
toLang: toLang,
},
Executor: executeTransShell,
}
}
func executeTransShell(tj TransJob) ([]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 (t Translation) Translate() []string {
outBytes, err := t.Executor(t.job)
if err != nil {
log.Fatalf("Failed to execute command 'trans': %v", err)
}
return uniqueSlice(parseTransOutput(string(outBytes)))
}
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
}