forked from Nxer/Twist-Space-Technology-Mod
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaddon.gradle
300 lines (260 loc) · 11.6 KB
/
addon.gradle
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import java.util.regex.Matcher
def searchSourceFiles(SourceDirectorySet javaFiles, Map<String, String> en_lang, Map<String, Map<String, String>> langMap) {
// Source File Search Start
// 源文件搜索使用的状态变量
String state = null
Matcher trMatch = null
def colorCodeMap = project.ext.colorCodeMap
javaFiles.each { file ->
def content = file.getText("UTF-8")
content.eachLine { line ->
switch (state) {
case 'tr':
// 如果上一行匹配了#tr模式
def matcher = line =~ /\/\/\s*#([a-z]{2}_[A-Z]{2})?\s+(.+)/
if (matcher) {
logger.debug("Match line: $line")
def groupCount = matcher.groupCount()
// 如果匹配到一组或两组
if (groupCount == 1 || groupCount == 2) {
if (groupCount == 1) {
def key = trMatch.group(1) as String
def value = matcher.group(1)
en_lang[key] = value
} else {
def lang = matcher.group(1)
if (lang == null || lang == '') {
lang = 'en_US'
}
def key = trMatch.group(1) as String
def value = matcher.group(2)
def lang1 = langMap[lang]
if (lang1 == null) {
lang1 = new HashMap<String, String>()
langMap[lang] = lang1
}
// 替换颜色代码
def value1 = value.replaceAll("\\{\\\\([A-Z_]+)\\}", { match ->
def colorValue = match[1]
def replacement = colorCodeMap[colorValue]
return replacement ?: match
})
if(lang1.containsKey(key)) { // warn if a key is reassigned
def originalText = lang1[key]
if(originalText == value1) {
logger.warn("[Key Overwrite|Duplicated] Key '${key}' is reassigned with same text in file '${file}'")
}
else {
logger.warn("[Key Overwrite|Overwrited] Key '${key}' is reassigned from '${lang1[key]}' to '${value1}' in file '${file}'")
}
}
if(!checkFormatPattern(value1)) {
logger.warn("[Invalid Formatter] Key '${key}' has an invalid formatter string from '${lang}' in '${file.name}': ${value1}")
}
lang1[key] = value1
}
} else {
trMatch = null
state = null
logger.warn("Waring: The wrong format has been captured: $line")
}
break
} else {
trMatch = null
state = null
}
default:
def matcher = line =~ /\/\/\s*#tr\s+([a-zA-Z0-9._]+)\s*(.+)?\s*/
// 检查是否匹配了#tr模式
if (matcher) {
logger.debug("Match line: $line")
def groupCount = matcher.groupCount()
// 如果匹配到一组或两组
if (groupCount == 1) {
state = 'tr'
trMatch = matcher
} else if (groupCount == 2) {
def value = matcher.group(2)
if (value == null) {
state = 'tr'
trMatch = matcher
} else {
def key = matcher.group(1)
def value1 = value.replaceAll("\\{\\\\([A-Z_]+)\\}", { match ->
def colorValue = match[1]
def replacement = colorCodeMap[colorValue]
return replacement ?: match
})
en_lang[key] = value1
}
} else {
logger.warn("Waring: The wrong format has been captured: $line")
}
}
break
}
}
}
}
def searchLanguageFiles(namespace, sort, langMap) {
def resourceFiles = fileTree(dir: "src/main/resources/assets/$namespace/lang").include("*.lang")
// 遍历资源文件
resourceFiles.each { file ->
def fileName = file.name.substring(0, 5)
def needSort = false
if (fileName == 'en_US') needSort = true
// 读取文件内容
file.withReader { reader ->
def lang1 = langMap[fileName] as Map
if (lang1 == null) {
lang1 = [:]
langMap[fileName] = lang1
}
reader.eachLine { line ->
if (line.startsWith("#") || line.trim().empty) {
if (needSort) sort.add('//' + line)
} else {
// 使用正则表达式按第一个等号分割每一行
def parts = line.split('=', 2)
// 分割结果数组的长度为2,第一个元素为key,第二个元素为value
if (parts.size() == 2) {
def key = parts[0].trim()
def value = parts[1]
if (needSort) sort.add(key)
if (lang1.containsKey(key)) {
if (value != lang1[key]) {
logger.info("The key: $key is already defined in the code! The Lang file will be overwritten!")
logger.info("Code: ${lang1[key]} Lang file: $value")
}
} else {
lang1[key] = value
}
}
}
}
}
}
// Language File Search Finish
}
def writeLanguageFiles(String namespace, Set<String> sort, Map<String, Map<String, String>> langMap, boolean ignoreKeyInFile, Set<String> onlyFile, Map<String, String> en_lang) {
langMap.each { fileName, innerMap ->
def outputFile = new File("src/main/resources/assets/$namespace/lang/${fileName}.lang")
outputFile.getParentFile().mkdirs()
outputFile.withWriter("UTF-8") { writer ->
if (!sort.empty) {
sort.each { line ->
if (line.startsWith('//'))
writer.write(line.substring(2) + '\n')
else {
if (innerMap.containsKey(line)) {
if (ignoreKeyInFile && onlyFile.contains(line)) {
logger.info("Ignore the $line, because it only exists in the language file!")
} else {
writer.write("${line}=${innerMap[line]}\n")
}
} else {
logger.warn("[Translation Missing] The $fileName file does not contain the $line")
writer.write("${line}=${en_lang[line]}\n")
}
}
}
} else {
innerMap.each { key, value ->
writer.write("$key=$value\n")
}
}
}
}
}
static checkFormatPattern(String str) {
def parseMethod = Formatter.metaClass.pickMethod("parse", String.class)
// println(parseMethod)
try {
if (parseMethod.isStatic()) {
parseMethod.invoke(null, str)
} else {
parseMethod.invoke(new Formatter(), str)
}
return true
} catch(IllegalFormatException ignored) {
return false
}
}
ext {
colorCodeMap = [
"BLACK" : "\u00a70",
"DARK_BLUE" : "\u00a71",
"DARK_GREEN" : "\u00a72",
"DARK_AQUA" : "\u00a73",
"DARK_RED" : "\u00a74",
"DARK_PURPLE" : "\u00a75",
"GOLD" : "\u00a76",
"GRAY" : "\u00a77",
"DARK_GRAY" : "\u00a78",
"BLUE" : "\u00a79",
"GREEN" : "\u00a7a",
"AQUA" : "\u00a7b",
"RED" : "\u00a7c",
"LIGHT_PURPLE" : "\u00a7d",
"YELLOW" : "\u00a7e",
"WHITE" : "\u00a7f",
"OBFUSCATED" : "\u00a7k",
"BOLD" : "\u00a7l",
"STRIKETHROUGH": "\u00a7m",
"UNDERLINE" : "\u00a7n",
"ITALIC" : "\u00a7o",
"RESET" : "\u00a7r",
"SPACE" : " ",
"NULL" : ""
]
}
tasks.register('preprocessLangInJavaFiles') {
group = 'preprocessing'
description = 'Preprocesses Java files.'
doLast {
def namespace = 'gtnhcommunitymod'
def ignoreKeyInFile = false
// Function Body Start
// 搜索源文件
def javaFiles = sourceSets.main.java
Map<String, Map<String, String>> langMaps = [:]
Map<String, String> en_lang = [:]
langMaps['en_US'] = en_lang
Set<String> allLangKeys = [] as Set
searchSourceFiles(javaFiles, en_lang, langMaps)
// 收集所有源文件中的键
langMaps.each { name, map ->
allLangKeys.addAll(map.keySet())
}
logger.debug("LangMap: $langMaps")
// check if the translation values exist in other languages
en_lang.keySet().each { String key ->
langMaps.each { langName, langMap ->
if(!langMap.containsKey(key)) {
getLogger().warn("[Translation Missing] Key '${key}' is missing in language '${langName}' (en_US = ${en_lang[key]})".toString())
}
}
}
// Language File Search Start
Set<String> enUsKeys = [] // en_US的键序
// 获取所有资源文件
searchLanguageFiles(namespace, enUsKeys, langMaps)
// Source File Search Finish
// 只存在于语言文件中的键
Set<String> keysOnlyInLangFiles = []
keysOnlyInLangFiles.addAll(enUsKeys)
keysOnlyInLangFiles.removeAll(allLangKeys)
if (!keysOnlyInLangFiles.empty) {
keysOnlyInLangFiles.each {
logger.warn("[#tr Missing] Key '${it}' only exists in language files, but not code comments. (en_US = ${langMaps["en_US"][it]}, zh_CN = ${langMaps["zh_CN"][it]})")
}
}
allLangKeys.removeAll(enUsKeys) // 只存在代码中的键
enUsKeys.addAll(allLangKeys) // 将只存在代码中的键添加到最后
logger.debug("File key sequence: $enUsKeys")
writeLanguageFiles(namespace, enUsKeys, langMaps, ignoreKeyInFile, keysOnlyInLangFiles, en_lang)
}
}
tasks.processResources {
dependsOn(tasks.preprocessLangInJavaFiles)
}