67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package trans
|
|
|
|
import (
|
|
"fmt"
|
|
"os/exec"
|
|
"strings"
|
|
"log"
|
|
)
|
|
|
|
|
|
type transJob struct {
|
|
word string
|
|
fromLang string
|
|
toLang string
|
|
}
|
|
|
|
func New(word, fromLang, toLang string) transJob {
|
|
return transJob{word: word, fromLang: fromLang, toLang: toLang}
|
|
}
|
|
|
|
func (tj transJob) Translate() []string {
|
|
outBytes, err := tj.execTrans()
|
|
if err != nil {
|
|
log.Fatal("Failed to execute command 'trans'!")
|
|
}
|
|
return uniqueSlice(parseTransOutput(string(outBytes)))
|
|
}
|
|
|
|
func (tj transJob) execTrans() ([]byte, error) {
|
|
config := []string{
|
|
"-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
|
|
}
|