forked from type-challenges/type-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.ts
74 lines (59 loc) · 2.25 KB
/
translate.ts
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
import path from 'path'
import translate from 'google-translate-open-api'
import fs from 'fs-extra'
import { QUIZ_ROOT, loadQuizByNo, loadQuizes } from './loader'
import { resolveFilePath } from './utils/resolve'
import type { Quiz } from './types'
import type { SupportedLocale } from './locales'
import { t } from './locales'
export async function TranslateQuizByNo(no: number, from: SupportedLocale, to: SupportedLocale) {
const quiz = await loadQuizByNo(no)
if (!quiz)
throw new Error(`Quiz #${no} not founded`)
return await TranslateQuiz(quiz, from, to)
}
export async function TranslateQuiz(quiz: Quiz, from: SupportedLocale, to: SupportedLocale) {
let translatedReadme = await translateMarkdown(quiz.readme[from], from, to)
if (!translatedReadme)
throw new Error(`Quiz #${quiz.no} empty translation`)
translatedReadme = `> ${t(to, 'readme.google-translated')}\n\n${translatedReadme.trim()}`
const readmePath = resolveFilePath(path.join(QUIZ_ROOT, quiz.path), 'README', 'md', to)
await fs.writeFile(readmePath, translatedReadme, 'utf-8')
console.log(`Translated [${quiz.no}] ${from} → ${to} | saved to ${readmePath}`)
}
export async function translateMarkdown(code: string, from: SupportedLocale, to: SupportedLocale) {
// to replace the code blocks intro a placeholder then feed it into translator
// then replace back for the results
const code_blocks: string[] = []
const source = code
.replace(/```[\s\S\n]+?```/g, (v) => {
const placeholder = `__${code_blocks.length}__`
code_blocks.push(v)
return placeholder
})
.replace(/`[\s\S\n]+?`/g, (v) => {
const placeholder = `__${code_blocks.length}__`
code_blocks.push(v)
return placeholder
})
const { data: rawResult } = await translate(source, {
tld: 'com',
from,
to,
})
if (!rawResult)
return
const result = (rawResult as string)
.replace(/__\s*?(\d+?)\s*?__/g, (_, i) => code_blocks[+i])
return result
}
export async function TranslateAllQuizes(from: SupportedLocale, to: SupportedLocale) {
const quizes = await loadQuizes()
for (const quiz of quizes) {
if (quiz.readme[to] || !quiz.readme[from]) {
console.log(`Skipped [${quiz.no}]`)
continue
}
await TranslateQuiz(quiz, from, to)
}
}