trans-alfred/trans/trans.go

71 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"
2019-04-05 22:37:17 +00:00
"log"
2019-04-05 22:30:10 +00:00
)
type Translator interface {
Translate() []string
}
2019-04-05 22:37:17 +00:00
type transJob struct {
word string
fromLang string
toLang string
}
func New(word, fromLang, toLang string) Translator {
2019-04-05 22:37:17 +00:00
return transJob{word: word, fromLang: fromLang, toLang: toLang}
}
func (tj transJob) Translate() []string {
outBytes, err := tj.execTrans()
2019-04-05 22:30:10 +00:00
if err != nil {
log.Fatalf("Failed to execute command 'trans': %v", err)
2019-04-05 22:30:10 +00:00
}
2019-04-05 22:37:17 +00:00
return uniqueSlice(parseTransOutput(string(outBytes)))
2019-04-05 22:30:10 +00:00
}
2019-04-05 22:37:17 +00:00
func (tj transJob) execTrans() ([]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", "n",
"-show-languages", "n",
"-show-prompt-message", "n",
2019-04-05 22:37:17 +00:00
fmt.Sprintf("%s:%s", tj.fromLang, tj.toLang),
tj.word,
2019-04-05 22:30:10 +00:00
}
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
}