trans-alfred/trans/trans.go

104 lines
2.2 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-10-13 15:05:27 +00:00
Word string
Language string
Translator func(string, string, string) (string, error)
2019-10-13 15:51:30 +00:00
Identifier func(string) (string, error)
2019-04-05 22:37:17 +00:00
}
2019-10-13 15:05:27 +00:00
func New(word string) Translation {
return Translation{
2019-10-13 15:05:27 +00:00
Word: word,
Language: "",
Translator: executeTrans,
2019-10-13 15:51:30 +00:00
Identifier: executeIdentify,
2019-04-05 22:30:10 +00:00
}
}
2019-10-13 15:05:27 +00:00
func executeTrans(word, fromLang, toLang string) (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-13 15:05:27 +00:00
fmt.Sprintf("%s:%s", fromLang, toLang),
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
}
2019-10-13 15:05:27 +00:00
func (t Translation) Translate(toLang string) []string {
output, err := t.Translator(t.Word, t.Language, toLang)
if err != nil {
panic(err)
}
2019-10-13 15:05:27 +00:00
return 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
}
2019-10-13 15:05:27 +00:00
return uniqueSlice(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
}
2019-10-13 15:51:30 +00:00
func executeIdentify(word string) (string, error) {
config := []string{
"-no-ansi",
"-id",
word,
}
outBytes, err := exec.Command("trans", config...).Output()
return string(outBytes), err
}
func (t Translation) Identify() string {
output, err := t.Identifier(t.Word)
if err != nil {
panic(err)
}
return parseTransIdentifyOutput(output)
}
func parseTransIdentifyOutput(out string) string {
re := regexp.MustCompile(`(?m)^Code\s+(\w+)$`)
result := ""
matches := re.FindStringSubmatch(out)
if (len(matches) >= 2) {
result = matches[1]
}
return result
}