source: code/trunk/cmd/root.go@ 32

Last change on this file since 32 was 32, checked in by yakumo.izuru, 4 weeks ago

水蛙神

File size: 2.1 KB
RevLine 
[31]1/*
2Copyright © 2025 Izuru Yakumo <eternal-servant@yakumo.dev>
3*/
4package cmd
5
6import (
7 "encoding/json"
8 "fmt"
9 "log"
10 "net/http"
11 "net/url"
12 "os"
13 "strings"
14
15 "github.com/spf13/cobra"
16 "gopkg.in/ini.v1"
17)
18
19var (
20 cfgFile string
21 input string
22 output string
23)
24
25var conf struct {
26 endpoint string
27 engine string
28}
29
30type Translate struct {
31 Output string `json:"translated_text"`
32}
33
34var rootCmd = &cobra.Command{
35 Use: "suwako",
36 Short: "A client for SimplyTranslate with illusionary origins",
37 Args: cobra.MinimumNArgs(1),
38 Run: func(cmd *cobra.Command, args []string) {
[32]39 text_to_split := fmt.Sprint(args)
40 text := fmt.Sprint(strings.Trim(text_to_split, "[]"))
[31]41 var translate Translate
42 encInput := url.PathEscape(text)
43 queryURL := conf.endpoint + "/api/translate" + "?engine=" + conf.engine + "&from=" + input + "&to=" + output + "&text=" + encInput
44 resp, err := http.Get(queryURL)
[32]45 cobra.CheckErr(err)
[31]46 defer resp.Body.Close()
47
48 _ = json.NewDecoder(resp.Body).Decode(&translate)
[32]49 cobra.CheckErr(err)
[31]50 if len(translate.Output) == 0 {
51 log.Fatalf("\033[1;31m%s\033[0m\n", "There was no output, maybe the endpoint is down?")
52 } else {
53 fmt.Printf("%v\n", translate.Output)
54 }
55 },
[32]56 Version: "3.0.1",
[31]57}
58func Execute() {
59 err := rootCmd.Execute()
60 if err != nil {
61 os.Exit(1)
62 }
63}
64func init() {
65 cobra.OnInitialize(initConfig)
[32]66 rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file (default is $XDG_CONFIG_HOME/suwako.ini)")
67 rootCmd.PersistentFlags().StringVarP(&input, "from", "f", "auto", "language to translate from")
[31]68 rootCmd.PersistentFlags().StringVarP(&output, "to", "t", "", "target language")
69}
70func parseConfig(file string) error {
71 cfg, err := ini.Load(file)
[32]72 cobra.CheckErr(err)
[31]73
74 conf.endpoint = cfg.Section("suwako").Key("endpoint").String()
75 conf.engine = cfg.Section("suwako").Key("engine").String()
76
77 return nil
78}
79func initConfig() {
80 if cfgFile != "" {
81 parseConfig(cfgFile)
82
83 } else {
[32]84 xdg_config_home, err := os.UserConfigDir()
85 cobra.CheckErr(err)
86 defaultCfgPath := xdg_config_home + "/suwako.ini"
[31]87 parseConfig(defaultCfgPath)
88 }
89
90}
Note: See TracBrowser for help on using the repository browser.