-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
413 lines (353 loc) · 15.6 KB
/
main.py
File metadata and controls
413 lines (353 loc) · 15.6 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import csv
import json
import logging
import os
import requests
import yaml
log = logging.getLogger("mkdocs.macros.translations")
# Friendly names for the locale codes we expect to encounter. Anything not
# listed here will fall back to its bare locale code as the display name.
LANGUAGE_NAMES = {
"zh-CN": "Chinois, Chine",
"zh-HK": "Chinois, Hong Kong",
"zh-TW": "Chinois, Taïwan",
"hr": "Croate",
"cs": "Tchèque",
"nl": "Néerlandais",
"fr": "Français",
"de": "Allemand",
"hu": "Hongrois",
"id": "Indonésien",
"it": "Italien",
"ja": "Japonais",
"ko": "Coréen",
"lv": "Letton",
"pl": "Polonais",
"pt": "Portugais",
"pt-BR": "Portugais, Brésil",
"en-GB": "Anglais, Royaume-Uni",
"es-ES": "Espagnol, Espagne",
"fr-FR": "Français, France",
"ro": "Roumain",
"ru": "Russe",
"es": "Espagnol",
"tr": "Turc",
"uk": "Ukrainien",
"vi": "Vietnamien",
}
# Module-level cache so each (repo, branch) is fetched at most once per build,
# even though several pages may reference the same repo.
_translations_cache: dict = {}
GITHUB_ORG = "BentoBoxWorld"
LOCALES_PATH = "src/main/resources/locales"
ENGLISH_FILE = "en-US.yml"
def _gh_session():
s = requests.Session()
s.headers.update({"Accept": "application/vnd.github+json"})
token = os.environ.get("GITHUB_TOKEN")
if token:
s.headers["Authorization"] = f"token {token}"
return s
def _flatten_yaml(data, prefix=""):
"""Flatten a nested YAML mapping into {dotted.key: leaf_value}."""
out = {}
if isinstance(data, dict):
for k, v in data.items():
key = f"{prefix}.{k}" if prefix else str(k)
out.update(_flatten_yaml(v, key))
elif isinstance(data, list):
# Treat the whole list as a single leaf — translators usually
# translate the list as a unit.
out[prefix] = "\n".join(str(x) for x in data)
else:
out[prefix] = data
return out
def _is_translated(value, english_value) -> bool:
"""A key counts as translated if it has a non-empty string value that
differs from the English source."""
if value is None:
return False
if isinstance(value, str) and not value.strip():
return False
return value != english_value
def _fetch_translation_status(repo: str, branch: str):
"""Return a list of dicts: {code, name, url, percent} for every locale
file in the repo (excluding en-US.yml). On failure returns None."""
cache_key = (repo, branch)
if cache_key in _translations_cache:
return _translations_cache[cache_key]
session = _gh_session()
api_url = (
f"https://api.github.com/repos/{GITHUB_ORG}/{repo}/contents/"
f"{LOCALES_PATH}?ref={branch}"
)
try:
r = session.get(api_url, timeout=15)
if r.status_code == 404:
# The repo has no locales/ directory at all — distinct from a
# transient failure so callers can render an accurate message.
_translations_cache[cache_key] = "missing"
return "missing"
if r.status_code != 200:
log.warning(
"translations(%s): GitHub listing returned %s", repo, r.status_code
)
_translations_cache[cache_key] = None
return None
listing = r.json()
except Exception as e: # network errors, JSON errors, etc.
log.warning("translations(%s): listing failed: %s", repo, e)
_translations_cache[cache_key] = None
return None
yml_files = [
item for item in listing
if isinstance(item, dict)
and item.get("type") == "file"
and item.get("name", "").endswith(".yml")
]
en_entry = next((f for f in yml_files if f["name"] == ENGLISH_FILE), None)
if en_entry is None:
log.warning("translations(%s): no %s in repo", repo, ENGLISH_FILE)
_translations_cache[cache_key] = None
return None
def _raw(file_entry):
url = file_entry.get("download_url")
if not url:
return None
try:
rr = session.get(url, timeout=15)
if rr.status_code != 200:
return None
return rr.text
except Exception:
return None
en_text = _raw(en_entry)
if en_text is None:
log.warning("translations(%s): could not fetch %s", repo, ENGLISH_FILE)
_translations_cache[cache_key] = None
return None
try:
en_flat = _flatten_yaml(yaml.safe_load(en_text) or {})
except yaml.YAMLError as e:
log.warning("translations(%s): could not parse %s: %s", repo, ENGLISH_FILE, e)
_translations_cache[cache_key] = None
return None
total = len([k for k, v in en_flat.items() if v not in (None, "")])
if total == 0:
total = len(en_flat) or 1
results = []
for entry in yml_files:
name = entry["name"]
if name == ENGLISH_FILE:
continue
code = name[:-4] # strip .yml
text = _raw(entry)
percent = None
if text is not None:
try:
flat = _flatten_yaml(yaml.safe_load(text) or {})
translated = sum(
1 for k, en_v in en_flat.items()
if _is_translated(flat.get(k), en_v)
)
percent = round(translated * 100 / total)
except yaml.YAMLError as e:
log.warning("translations(%s): could not parse %s: %s", repo, name, e)
results.append({
"code": code,
"name": LANGUAGE_NAMES.get(code, code),
"url": (
f"https://github.com/{GITHUB_ORG}/{repo}/blob/{branch}/"
f"{LOCALES_PATH}/{name}"
),
"percent": percent,
})
# Sort by display name for stable, readable output.
results.sort(key=lambda x: x["name"].lower())
_translations_cache[cache_key] = results
return results
def define_env(env):
@env.macro
def translations(repo: str, branch: str = "develop"):
intro = (
'!!! note "Aidez-nous à maintenir des traductions précises"\n'
" La plupart des traductions de BentoBox et de ses extensions sont\n"
" désormais générées avec l'aide de l'IA, donc l'essentiel du travail\n"
" est déjà fait — mais **l'IA n'est pas parfaite**. Ce dont nous avons\n"
" vraiment besoin de la part de la communauté, ce sont des **rapports\n"
" d'erreurs et des corrections**.\n"
"\n"
" * Vous avez repéré une erreur ou une formulation maladroite ? Ouvrez\n"
" une issue ou une PR sur le dépôt concerné via\n"
" [bentobox.world](https://bentobox.world) (un lien court vers notre\n"
" organisation GitHub), ou prévenez-nous sur\n"
" [Discord](https://discord.bentobox.world).\n"
" * Vous voulez ajouter une toute nouvelle langue ? Ouvrez une PR\n"
" ajoutant un nouveau fichier de locale dans\n"
" `src/main/resources/locales/` du dépôt concerné, ou demandez sur\n"
" Discord et nous vous aiderons à démarrer.\n"
"\n"
)
en_url = (
f"https://github.com/{GITHUB_ORG}/{repo}/blob/{branch}/"
f"{LOCALES_PATH}/{ENGLISH_FILE}"
)
header = (
"| Langue | Code de langue | Progression |\n"
"| ---------- | --- | ----------- |\n"
f"| [Anglais (États-Unis)]({en_url}) | `en-US` | 100% (Par défaut) |\n"
)
rows = _fetch_translation_status(repo, branch)
if rows == "missing":
# No locales/ directory in the repo — this addon currently has
# no translatable strings.
note = (
f"\n_Ce projet n'a pas encore de fichiers de locale traduisibles. "
f"Seul l'anglais est livré pour le moment._\n"
)
return intro + header + note
if rows is None:
# Network/parse failure — render a graceful fallback that still
# links to the locales directory on GitHub.
locales_url = (
f"https://github.com/{GITHUB_ORG}/{repo}/tree/{branch}/"
f"{LOCALES_PATH}"
)
fallback = (
f"\n_L'état des traductions est actuellement indisponible. "
f"Parcourez les fichiers de locale directement sur "
f"[GitHub]({locales_url})._\n"
)
return intro + header + fallback
body = ""
for row in rows:
pct = f"{row['percent']}%" if row["percent"] is not None else "?"
body += (
f"| [{row['name']}]({row['url']}) | `{row['code']}` | {pct} |\n"
)
return intro + header + body
@env.macro
def addon_description(addon_name:str, beta:bool=False):
result = ""
if beta:
result += f"""!!! warning
**{addon_name}** is currently in **Beta**.\n
Keep in mind that **you are more likely to encounter bugs** and **some features might not be stable**.\n\n"""
result += f"""!!! info "Useful links"
- [GitHub repository](https://github.com/BentoBoxWorld/{addon_name})
([Releases](https://github.com/BentoBoxWorld/{addon_name}/releases))
- [Issue tracker](https://github.com/BentoBoxWorld/{addon_name}/issues)
- [Development builds](https://ci.codemc.io/job/BentoBoxWorld/job/{addon_name})
([Latest stable build](https://ci.codemc.io/job/BentoBoxWorld/job/{addon_name}/lastStableBuild/))"""
return result
@env.macro
def placeholders_bundle(gamemode_name:str):
result = ""
source = ""
# Let's read the csv file
with open('data/placeholders.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Analyze the source
if (row['source'] != source):
if ("[gamemode]" in row['placeholder'] or gamemode_name in row['placeholder']):
# We are in a new "source" so we have to put the header
source = row['source']
result += f"""\n## {source} placeholders
| Placeholder | Description | {source} version
| ---------- | ---------- | ---------- |
"""
if ("[gamemode]" in row['placeholder'] or gamemode_name in row['placeholder']):
result += f"| `%{row['placeholder'].replace('[gamemode]',gamemode_name)}%` | {row['desc']} | {row['version']} |\n"
return result
# Adds placeholder table to the addon pages.
@env.macro
def placeholders_source(source:str):
result = f"""!!! tip "Tip"\n
`[gamemode]` is a prefix that differs depending on the gamemode you are running.\n
The prefix is the lowercased name of the gamemode, i.e. if you are using BSkyBlock, the prefix is `bskyblock`.\n\n
Properly translated placeholders for each gamemode can be found:\n
- [AcidIsland](/en/latest/gamemodes/AcidIsland/Placeholders)
- [AOneBlock](/en/latest/gamemodes/AOneBlock/Placeholders)
- [Boxed](/en/latest/gamemodes/Boxed/Placeholders)
- [BSkyBlock](/en/latest/gamemodes/BSkyBlock/Placeholders)
- [CaveBlock](/en/latest/gamemodes/CaveBlock/Placeholders)
- [SkyGrid](/en/latest/gamemodes/SkyGrid/Placeholders).\n
Please read the main [Placeholders page](/en/latest/BentoBox/Placeholders).\n\n"""
result += f"""\n
| Placeholder | Description | {source} version
| ---------- | ---------- | ---------- |
"""
# Let's read the csv file
with open('data/placeholders.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Analyze the source
if (row['source'] == source):
# We are in our plugin, populate rows
result += f"| `%{row['placeholder']}%` | {row['desc']} | {row['version']} |\n"
return result
# Creates a table of requested flags type.
@env.macro
def flags_bundle(type:str):
result = ""
source = ""
# Let's read the csv file
with open('data/flags.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Analyze the source
if (row['source'] != source):
# We are in a new "source" so we have to put the header
source = row['source']
if (row['type'] == type) or (type == "WORLD_DEFAULT_PROTECTION" and row['type'] == "PROTECTION"):
if (type == "PROTECTION"):
result += f"""\n## {source} {type.replace("_", " ").capitalize()} flags
| | Flag ID | Flag | Description | Default | Min Rank | Max Rank |
| - | ---------- | ---------- | ---------- | ---------- | ---------- | ---------- |
"""
else:
result += f"""\n## {source} {type.replace("_", " ").capitalize()} flags
| | Flag ID | Flag | Description | Default |
| - | ---------- | ---------- | ---------- | ---------- |
"""
if (row['type'] == type) or (type == "WORLD_DEFAULT_PROTECTION" and row['type'] == "PROTECTION"):
if (type == "PROTECTION"):
result += f"| <span class='icon-minecraft {icon_css(row['icon'])}'></span> | {row['flag']} | {row['name']} | {row['description']} | {row['default']} | {row['min']} | {row['max']} |\n"
else:
result += f"| <span class='icon-minecraft {icon_css(row['icon'])}'></span> | {row['flag']} | {row['name']} | {row['description']} | {row['default']} |\n"
return result
# Creates a table of requested flags type.
@env.macro
def flags_source(source:str, type:str):
result = ""
# Let's read the csv file
with open('data/flags.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Analyze the source
if (row['source'] == source):
# We are in a new "source" so we have to put the header
if (row['type'] == type) or (type == "WORLD_DEFAULT_PROTECTION" and row['type'] == "PROTECTION"):
if (type == "PROTECTION"):
result += f"""\n## {source} {type.replace("_", " ").capitalize()} flags
| | Flag ID | Flag | Description | Default | Min Rank | Max Rank |
| - | ---------- | ---------- | ---------- | ---------- | ---------- | ---------- |
"""
result += f"| <span class='icon-minecraft {icon_css(row['icon'])}'></span> | {row['flag']} | {row['name']} | {row['description']} | {row['default']} | {row['min']} | {row['max']} |\n"
else:
result += f"""\n## {source} {type.replace("_", " ").capitalize()} flags
| | Flag ID | Flag | Description | Default |
| - | ---------- | ---------- | ---------- | ---------- |
"""
result += f"| <span class='icon-minecraft {icon_css(row['icon'])}'></span> | {row['flag']} | {row['name']} | {row['description']} | {row['default']} |\n"
return result
# Creates a table of requested flags type.
@env.macro
def icon_css(icon:str):
with open("data/minecraft-block-and-entity.json", 'r') as j:
contents = json.loads(j.read())
for entry in contents:
if icon.lower() == entry['name']:
return entry['css']
return ""