This repository was archived by the owner on Oct 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
182 lines (155 loc) · 4.7 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/urfave/cli/v2"
"log"
"net/http"
"os"
"os/exec"
"strings"
)
var token string
func main() {
var sourceLanguage string
var translationKey string
var targetLanguages cli.StringSlice
var syncTranslations bool
app := &cli.App{
Name: "translazy",
Usage: "Help you add new translations to your projects. It expects to find a DeepL API key in the file ~/.config/translazy/token.",
Action: func(context *cli.Context) error {
input := context.Args().First()
translations := []Translation{
{
Lang: sourceLanguage,
Text: input,
},
}
for _, lang := range targetLanguages.Value() {
translation, err := translate(input, sourceLanguage, lang)
if err != nil {
log.Fatal(err)
}
translations = append(translations, translation)
}
persistToLocaleFiles(translations, translationKey)
if syncTranslations {
syncPnpmLocales()
}
outputResults(translationKey, translations)
return nil
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "source-lang",
Aliases: []string{"s"},
Value: "en",
Usage: "The language of the source text. This is a required parameter.",
Destination: &sourceLanguage,
},
&cli.StringSliceFlag{
Name: "target-langs",
Value: cli.NewStringSlice("sv", "nb"),
Usage: "The languages to translate the source text to. This is a required parameter.",
Destination: &targetLanguages,
},
&cli.StringFlag{
Name: "key",
Aliases: []string{"k"},
Required: true,
Usage: "The translation key to output translations to. This is a required parameter.",
Destination: &translationKey,
},
&cli.BoolFlag{
Name: "sync",
Usage: "If set, the translations will be synced using the locale:import pnpm script.",
Destination: &syncTranslations,
},
&cli.StringFlag{
Name: "token",
Usage: "The DeepL API key. If not set, the program will look for the key in the file ~/.config/translazy/token.",
EnvVars: []string{"DEEPL_API_KEY"},
Destination: &token,
FilePath: os.Getenv("HOME") + "/.config/translazy/token",
Required: true,
},
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func outputResults(translationKey string, translations []Translation) {
fmt.Printf("Translations done for key \"%s\"\n", translationKey)
for _, translation := range translations {
fmt.Printf(" %s: %s\n", translation.Lang, translation.Text)
}
}
func syncPnpmLocales() {
err := exec.Command("pnpm", "run", "locale:import").Run()
if err != nil {
log.Fatal(err)
}
}
type Translation struct {
Lang string
Text string `json:"text"`
}
type DeepLAPIInput struct {
Text []string `json:"text"`
TargetLang string `json:"target_lang"`
SourceLang string `json:"source_lang"`
}
type DeepLAPITranslation struct {
DetectedSourceLanguage string `json:"detected_source_language"`
Text string `json:"text"`
}
type DeepLAPIOutput struct {
Translations []DeepLAPITranslation `json:"translations"`
}
func translate(text string, fromLang string, toLang string) (Translation, error) {
postBody, _ := json.Marshal(DeepLAPIInput{
Text: []string{text},
TargetLang: toLang,
SourceLang: fromLang,
})
responseBody := bytes.NewBuffer(postBody)
request, _ := http.NewRequest("POST", "https://api-free.deepl.com/v2/translate", responseBody)
request.Header.Add("Authorization", "DeepL-Auth-Key "+strings.TrimSpace(token))
request.Header.Add("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return Translation{}, err
}
// parse response body to expected type
var translation DeepLAPIOutput
_ = json.NewDecoder(response.Body).Decode(&translation)
if len(translation.Translations) == 0 {
return Translation{}, fmt.Errorf("no translations found")
}
return Translation{
Text: translation.Translations[0].Text,
Lang: toLang,
}, nil
}
func persistToLocaleFiles(translations []Translation, key string) {
for _, translation := range translations {
outputPath := "locale/" + norwegianConfusionHack(translation.Lang) + ".json"
fileContent, _ := os.ReadFile(outputPath)
var existingTranslations map[string]string
_ = json.Unmarshal(fileContent, &existingTranslations)
existingTranslations[key] = translation.Text
updatedFileContent, _ := json.MarshalIndent(existingTranslations, "", " ")
_ = os.WriteFile(outputPath, updatedFileContent, 0644)
}
}
// We've called the file "no" in our codebase, even though "nb" is more correct
func norwegianConfusionHack(lang string) string {
if lang == "nb" {
return "no"
}
return lang
}