Skip to content

Commit 1d771af

Browse files
authored
Allow to translate description from metadata (#47)
* Allow to translate description from metadata * Add tests
1 parent 14fc745 commit 1d771af

File tree

9 files changed

+231
-45
lines changed

9 files changed

+231
-45
lines changed

docs/src/useful-recipes.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ use them directly [as a command line interface][mdpo-cli] or through is
4848
=== "`md2po2md` command line interface"
4949

5050
```bash
51-
md2po2md README.md -l es -l fr -o locale/{lang}
51+
md2po2md README.md -l es fr -o locale/{lang}
5252
```
5353

5454
=== "pre-commit hook configuration"

examples/material-theme/docs/locale/es/foo.md.po

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
msgid ""
33
msgstr ""
44

5-
msgid "Foo"
6-
msgstr "Foo es"
5+
msgid "Some description"
6+
msgstr "Algo de descripción"
77

88
msgid "Bar"
99
msgstr "Bar es"
1010

1111
msgid "Baz"
1212
msgstr "Baz es"
13+
14+
msgid "Foo"
15+
msgstr "Foo es"

examples/material-theme/docs/locale/es/index.md.po

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
msgid ""
33
msgstr ""
44

5-
msgid "Home"
6-
msgstr "Inicio"
7-
85
msgid "Welcome to MkDocs"
96
msgstr "Bienvenido a Mkdocs"
7+
8+
msgid "Home"
9+
msgstr "Inicio"

examples/material-theme/docs/locale/fr/foo.md.po

+6-3
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22
msgid ""
33
msgstr ""
44

5-
msgid "Foo"
6-
msgstr "Foo fr"
7-
85
msgid "Bar"
96
msgstr "Bar fr"
107

118
msgid "Baz"
129
msgstr "Baz fr"
10+
11+
msgid "Some description"
12+
msgstr "Une description"
13+
14+
msgid "Foo"
15+
msgstr "Foo fr"

examples/material-theme/docs/locale/fr/index.md.po

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
msgid ""
33
msgstr ""
44

5-
msgid "Home"
6-
msgstr "Accueil"
7-
85
msgid "Welcome to MkDocs"
96
msgstr "Bienvenue sur mkdocs"
7+
8+
msgid "Home"
9+
msgstr "Accueil"

examples/material-theme/docs/src/foo.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
---
2+
description: Some description
3+
---
4+
15
# Bar
26

37
Baz

mkdocs_mdpo_plugin/plugin.py

+111-32
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import logging
55
import math
66
import os
7+
import re
78
import sys
89
from urllib.parse import urljoin
910

@@ -295,6 +296,9 @@ def on_page_markdown(self, markdown, page, config, files):
295296
#
296297
# translate title
297298
translated_page_title, _title_in_pofile = (None, False)
299+
# translated custom description
300+
page_meta_description = page.meta.get('description')
301+
translated_page_desc, _desc_in_pofile = (None, False)
298302

299303
# translate site_name and site_description
300304
translated_config_settings = {
@@ -304,15 +308,52 @@ def on_page_markdown(self, markdown, page, config, files):
304308
key: False for key in self.config['translate']
305309
}
306310

307-
for entry in po:
308-
if entry.msgid == page.title:
309-
# matching title found
310-
entry.obsolete = False
311-
translated_page_title = entry.msgstr
312-
_title_in_pofile = True
313-
_translated_entries_msgids.append(page.title)
314-
if entry.msgstr:
315-
_translated_entries_msgstrs.append(page.title)
311+
if page_meta_description:
312+
for entry in po:
313+
if entry.msgid == page.title:
314+
# matching title found
315+
entry.obsolete = False
316+
translated_page_title = entry.msgstr
317+
_title_in_pofile = True
318+
if entry.msgstr:
319+
_translated_entries_msgstrs.append(
320+
entry.msgstr,
321+
)
322+
323+
if entry.msgid == page_meta_description:
324+
# matching description found
325+
entry.obsolete = False
326+
translated_page_desc = entry.msgstr
327+
_desc_in_pofile = True
328+
if entry.msgstr:
329+
_translated_entries_msgstrs.append(
330+
page_meta_description,
331+
)
332+
333+
# add description to PO file if not added
334+
if not _desc_in_pofile:
335+
po.insert(
336+
0,
337+
polib.POEntry(
338+
msgid=page_meta_description,
339+
msgstr='',
340+
),
341+
)
342+
343+
_translated_entries_msgids.append(
344+
page_meta_description,
345+
)
346+
else:
347+
for entry in po:
348+
if entry.msgid == page.title:
349+
# matching title found
350+
entry.obsolete = False
351+
translated_page_title = entry.msgstr
352+
_title_in_pofile = True
353+
if entry.msgstr:
354+
_translated_entries_msgstrs.append(
355+
entry.msgstr,
356+
)
316357

317358
for entry in compendium_pofile:
318359
for setting in translated_config_settings:
@@ -381,6 +422,19 @@ def on_page_markdown(self, markdown, page, config, files):
381422
events=po2md_events,
382423
wrapwidth=math.inf, # ignore line wrapping
383424
)
425+
if page_meta_description:
426+
po2md.translated_entries.append(
427+
polib.POEntry(
428+
msgid=page_meta_description,
429+
msgstr='',
430+
),
431+
)
432+
po2md.translated_entries.append(
433+
polib.POEntry(
434+
msgid=page.title,
435+
msgstr='',
436+
),
437+
)
384438
content = po2md.translate(markdown)
385439

386440
_disabled_msgids = [
@@ -395,6 +449,7 @@ def on_page_markdown(self, markdown, page, config, files):
395449
# mock variables if the file is excluded from being translated
396450
content = markdown
397451
translated_page_title = None
452+
translated_page_desc = None
398453
_disabled_msgids = []
399454
_translated_entries_msgstrs = []
400455
_translated_entries_msgids = []
@@ -427,6 +482,8 @@ def on_page_markdown(self, markdown, page, config, files):
427482
new_file,
428483
config,
429484
)
485+
if translated_page_desc:
486+
new_page.meta['description'] = translated_page_desc
430487

431488
# overwrite the edit uri for the translated page targetting
432489
# the PO file located in the repository
@@ -459,6 +516,15 @@ def on_page_markdown(self, markdown, page, config, files):
459516
self.translations.config_settings[language] = (
460517
translated_config_settings
461518
)
519+
if language not in self.translations.page_metas:
520+
self.translations.page_metas[language] = {}
521+
if (
522+
new_file.src_path
523+
not in self.translations.page_metas[language]
524+
):
525+
self.translations.page_metas[
526+
language
527+
][new_file.src_path] = new_page.meta
462528

463529
# change file url
464530
url = removesuffix(new_page.file.url, '.md') + '.html'
@@ -601,28 +667,43 @@ def on_post_page(self, output, page, config):
601667
f'{config["site_name"]}</title>',
602668
f'{tr_settings["site_name"]}</title>',
603669
)
604-
if tr_settings.get('site_description'):
605-
# insert site_description into description meta tag
606-
# if the file is a translated index, only for
607-
# readthedocs and mkdocs themes
608-
if (
609-
config['theme'].name in {'mkdocs', 'readthedocs'} and
610-
removepreffix(page.file.url, language).count('/') == 1
611-
):
670+
671+
meta_description = self.translations.page_metas[
672+
language
673+
][page.file.src_path].get('description')
674+
675+
if (
676+
meta_description or
677+
tr_settings.get('site_description') or
678+
config.get('site_description')
679+
):
680+
if meta_description:
681+
tr_description = meta_description
682+
elif tr_settings.get('site_description'):
683+
tr_description = tr_settings['site_description']
684+
elif config.get('site_description'):
685+
tr_description = config['site_description']
686+
687+
if '<meta name="description"' not in output:
612688
output = output.replace(
613689
'/title>',
614690
(
615691
'/title><meta name="description"'
616-
f' content="{tr_settings["site_description"]}"'
617-
' />'
692+
' content="">'
618693
),
619694
)
620-
else:
621-
# mkdocs-material theme includes the description
622-
# in all pages
623-
output = output.replace(
624-
f'content="{config["site_description"]}"',
625-
f'content="{tr_settings["site_description"]}"',
695+
696+
if not (
697+
config['theme'].name in {'mkdocs', 'readthedocs'} and
698+
removepreffix(page.file.url, language).count('/') > 1
699+
):
700+
output = re.sub(
701+
r'<meta name="description" content="[^"]*"',
702+
(
703+
'<meta name="description"'
704+
f' content="{tr_description}"'
705+
),
706+
output,
626707
)
627708

628709
# write translated HTML file to 'site' directory
@@ -709,9 +790,8 @@ def on_post_build(self, config):
709790

710791
_msgids_appended_to_compendium = []
711792
for translation in translations:
712-
po = polib.pofile(translation.po_filepath)
713793
_entry_found = None
714-
for entry in po:
794+
for entry in translation.po:
715795
if entry.msgid == repeated_msgid:
716796
if (
717797
repeated_msgid not in
@@ -725,8 +805,8 @@ def on_post_build(self, config):
725805
_entry_found = entry
726806
break
727807
if _entry_found:
728-
po.remove(_entry_found)
729-
po.save(translation.po_filepath)
808+
translation.po.remove(_entry_found)
809+
translation.po.save(translation.po_filepath)
730810

731811
for entry in compendium_pofile:
732812
if entry.msgid not in repeated_msgids:
@@ -752,11 +832,10 @@ def on_post_build(self, config):
752832
# po_filepath is None if the file has been excluded from
753833
# translations using 'exclude' config setting
754834
if translation.po_filepath is not None:
755-
po = polib.pofile(translation.po_filepath)
756-
for entry in po:
835+
for entry in translation.po:
757836
if entry.msgid not in translation.translated_msgids:
758837
entry.obsolete = True
759-
po.save(translation.po_filepath)
838+
translation.po.save(translation.po_filepath)
760839

761840
# reset mkdocs build instance
762841
MkdocsBuild._instance = None

mkdocs_mdpo_plugin/translations.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ class Translations:
5757
'locations',
5858
'stats',
5959
'config_settings',
60+
'page_metas',
6061
}
6162

6263
def __init__(self):
@@ -100,6 +101,10 @@ def __init__(self):
100101
# {lang: {site_name: str, site_description: str}}
101102
self.config_settings = {}
102103

104+
# translated page metadatas by language
105+
# {lang: {page.file.src_path: {...meta...}}}
106+
self.page_metas = {}
107+
103108
def __str__(self): # pragma: no cover
104109
current = 'None' if self.current is None else 'Translation(...)'
105110
return (
@@ -111,6 +116,7 @@ def __str__(self): # pragma: no cover
111116
f'{str(self.compendium_msgstrs_tr)},'
112117
f' current={current},'
113118
f' locations={str(self.locations)},'
114-
f' config_settings={str(self.config_settings)}'
119+
f' config_settings={str(self.config_settings)},'
120+
f' page_metas={str(self.page_metas)}'
115121
')'
116122
)

0 commit comments

Comments
 (0)