dict/dict.go

103 lines
1.9 KiB
Go

package main
import (
"bufio"
"fmt"
"net/http"
"os"
"regexp"
"strings"
)
const (
BASE = "dict.cc/?s="
VAR1 = "var c1Arr = new Array("
VAR2 = "var c2Arr = new Array("
SUFF = ");"
)
// is going to be set in winsize.go, if run on unix
var Width = 80
func main() {
if len(os.Args) < 2 || os.Args[1][0] == '-' {
println("usage:", os.Args[0], "word [{de|es|fr|en...}{de|es|fr|en|...}]")
return
}
fromto := ""
if len(os.Args) > 2 {
fromto = os.Args[2] + "."
}
r, err := http.Get("http://" + fromto + BASE + os.Args[1])
if err != nil {
println("error:", err.Error())
return
}
defer r.Body.Close()
byline := bufio.NewScanner(r.Body)
var left, right []string
for byline.Scan() {
line := byline.Text()
if strings.HasPrefix(line, VAR1) {
line = strings.TrimPrefix(line, VAR1)
line = strings.TrimSuffix(line, SUFF)
left = strings.Split(line, `","`)
} else if strings.HasPrefix(line, VAR2) {
line = strings.TrimPrefix(line, VAR2)
line = strings.TrimSuffix(line, SUFF)
right = strings.Split(line, `","`)
break
}
}
if len(left) != len(right) {
println("error: arrays of different length")
fmt.Println(strings.Join(left, "\n"), len(left))
fmt.Println(strings.Join(right, "\n"), len(right))
return
}
ml := 25
for _, v := range right {
if len(v) > ml {
ml = len(v)
}
}
if ml > (Width / 2) {
ml = Width / 2
}
re := regexp.MustCompile(`\\(['"„])`)
for i, _ := range right {
a := strings.Trim(right[i], `„"`)
b := strings.Trim(left[i], `„"`)
a = re.ReplaceAllString(a, `$1`)
b = re.ReplaceAllString(b, `$1`)
if a == "" {
continue
}
if len(a) > ml {
if i := strings.LastIndex(a[:ml], " "); i > 0 {
fmt.Printf("%*s\n", ml, a[:i])
a = a[i:]
}
}
if len(b) > ml {
if i := strings.LastIndex(b[:ml], " "); i > 0 {
fmt.Printf("%*s\n", ml, a[:i])
a = a[i:]
}
}
// TODO: wrap when len(a) > ml
fmt.Printf("%*s → %s\n", ml, a, b)
}
}