91 lines
2.1 KiB
Go
91 lines
2.1 KiB
Go
/*
|
|
Copyright © 2025 Izuru Yakumo <eternal-servant@yakumo.dev>
|
|
*/
|
|
package cmd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/spf13/cobra"
|
|
"gopkg.in/ini.v1"
|
|
)
|
|
|
|
var (
|
|
cfgFile string
|
|
input string
|
|
output string
|
|
)
|
|
|
|
var conf struct {
|
|
endpoint string
|
|
engine string
|
|
}
|
|
|
|
type Translate struct {
|
|
Output string `json:"translated_text"`
|
|
}
|
|
|
|
var rootCmd = &cobra.Command{
|
|
Use: "suwako",
|
|
Short: "A client for SimplyTranslate with illusionary origins",
|
|
Args: cobra.MinimumNArgs(1),
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
text_to_split := fmt.Sprint(args)
|
|
text := fmt.Sprint(strings.Trim(text_to_split, "[]"))
|
|
var translate Translate
|
|
encInput := url.PathEscape(text)
|
|
queryURL := conf.endpoint + "/api/translate" + "?engine=" + conf.engine + "&from=" + input + "&to=" + output + "&text=" + encInput
|
|
resp, err := http.Get(queryURL)
|
|
cobra.CheckErr(err)
|
|
defer resp.Body.Close()
|
|
|
|
_ = json.NewDecoder(resp.Body).Decode(&translate)
|
|
cobra.CheckErr(err)
|
|
if len(translate.Output) == 0 {
|
|
log.Fatalf("\033[1;31m%s\033[0m\n", "There was no output, maybe the endpoint is down?")
|
|
} else {
|
|
fmt.Printf("%v\n", translate.Output)
|
|
}
|
|
},
|
|
Version: "3.0.1",
|
|
}
|
|
func Execute() {
|
|
err := rootCmd.Execute()
|
|
if err != nil {
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
func init() {
|
|
cobra.OnInitialize(initConfig)
|
|
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $XDG_CONFIG_HOME/suwako.ini)")
|
|
rootCmd.PersistentFlags().StringVarP(&input, "from", "f", "auto", "language to translate from")
|
|
rootCmd.PersistentFlags().StringVarP(&output, "to", "t", "", "target language")
|
|
}
|
|
func parseConfig(file string) error {
|
|
cfg, err := ini.Load(file)
|
|
cobra.CheckErr(err)
|
|
|
|
conf.endpoint = cfg.Section("suwako").Key("endpoint").String()
|
|
conf.engine = cfg.Section("suwako").Key("engine").String()
|
|
|
|
return nil
|
|
}
|
|
func initConfig() {
|
|
if cfgFile != "" {
|
|
parseConfig(cfgFile)
|
|
|
|
} else {
|
|
xdg_config_home, err := os.UserConfigDir()
|
|
cobra.CheckErr(err)
|
|
defaultCfgPath := xdg_config_home + "/suwako.ini"
|
|
parseConfig(defaultCfgPath)
|
|
}
|
|
|
|
}
|