i18n_subsites.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. """i18n_subsites plugin creates i18n-ized subsites of the default site
  2. This plugin is designed for Pelican 3.4 and later
  3. """
  4. import os
  5. import six
  6. import logging
  7. import posixpath
  8. from copy import copy
  9. from itertools import chain
  10. from operator import attrgetter
  11. try:
  12. from collections.abc import OrderedDict
  13. except ImportError:
  14. from collections import OrderedDict
  15. from contextlib import contextmanager
  16. from six.moves.urllib.parse import urlparse
  17. import gettext
  18. import locale
  19. from pelican import signals
  20. from pelican.generators import ArticlesGenerator, PagesGenerator
  21. from pelican.settings import configure_settings
  22. try:
  23. from pelican.contents import Draft
  24. except ImportError:
  25. from pelican.contents import Article as Draft
  26. # Global vars
  27. _MAIN_SETTINGS = None # settings dict of the main Pelican instance
  28. _MAIN_LANG = None # lang of the main Pelican instance
  29. _MAIN_SITEURL = None # siteurl of the main Pelican instance
  30. _MAIN_STATIC_FILES = None # list of Static instances the main Pelican
  31. _SUBSITE_QUEUE = {} # map: lang -> settings overrides
  32. _SITE_DB = OrderedDict() # OrderedDict: lang -> siteurl
  33. _SITES_RELPATH_DB = {} # map: (lang, base_lang) -> relpath
  34. # map: generator -> list of removed contents that need interlinking
  35. _GENERATOR_DB = {}
  36. _NATIVE_CONTENT_URL_DB = {} # map: source_path -> content in its native lang
  37. _LOGGER = logging.getLogger(__name__)
  38. @contextmanager
  39. def temporary_locale(temp_locale=None):
  40. '''Enable code to run in a context with a temporary locale
  41. Resets the locale back when exiting context.
  42. Can set a temporary locale if provided
  43. '''
  44. orig_locale = locale.setlocale(locale.LC_ALL)
  45. if temp_locale is not None:
  46. locale.setlocale(locale.LC_ALL, temp_locale)
  47. yield
  48. locale.setlocale(locale.LC_ALL, orig_locale)
  49. def initialize_dbs(settings):
  50. '''Initialize internal DBs using the Pelican settings dict
  51. This clears the DBs for e.g. autoreload mode to work
  52. '''
  53. global _MAIN_SETTINGS, _MAIN_SITEURL, _MAIN_LANG, _SUBSITE_QUEUE
  54. _MAIN_SETTINGS = settings
  55. _MAIN_LANG = settings['DEFAULT_LANG']
  56. _MAIN_SITEURL = settings['SITEURL']
  57. _SUBSITE_QUEUE = settings.get('I18N_SUBSITES', {}).copy()
  58. prepare_site_db_and_overrides()
  59. # clear databases in case of autoreload mode
  60. _SITES_RELPATH_DB.clear()
  61. _NATIVE_CONTENT_URL_DB.clear()
  62. _GENERATOR_DB.clear()
  63. def prepare_site_db_and_overrides():
  64. '''Prepare overrides and create _SITE_DB
  65. _SITE_DB.keys() need to be ready for filter_translations
  66. '''
  67. _SITE_DB.clear()
  68. _SITE_DB[_MAIN_LANG] = _MAIN_SITEURL
  69. # make sure it works for both root-relative and absolute
  70. main_siteurl = ('/' if _MAIN_SITEURL == '' else _MAIN_SITEURL)
  71. for (lang, overrides) in _SUBSITE_QUEUE.items():
  72. if 'SITEURL' not in overrides:
  73. overrides['SITEURL'] = posixpath.join(main_siteurl, lang)
  74. _SITE_DB[lang] = overrides['SITEURL']
  75. # default subsite hierarchy
  76. if 'OUTPUT_PATH' not in overrides:
  77. overrides['OUTPUT_PATH'] = \
  78. os.path.join(_MAIN_SETTINGS['OUTPUT_PATH'], lang)
  79. if 'CACHE_PATH' not in overrides:
  80. overrides['CACHE_PATH'] = \
  81. os.path.join(_MAIN_SETTINGS['CACHE_PATH'], lang)
  82. if 'STATIC_PATHS' not in overrides:
  83. overrides['STATIC_PATHS'] = []
  84. if 'THEME' not in overrides and 'THEME_STATIC_DIR' \
  85. not in overrides and 'THEME_STATIC_PATHS' not in overrides:
  86. relpath = relpath_to_site(lang, _MAIN_LANG)
  87. overrides['THEME_STATIC_DIR'] = posixpath.join(
  88. relpath, _MAIN_SETTINGS['THEME_STATIC_DIR'])
  89. overrides['THEME_STATIC_PATHS'] = []
  90. # to change what is perceived as translations
  91. overrides['DEFAULT_LANG'] = lang
  92. def subscribe_filter_to_signals(settings):
  93. '''Subscribe content filter to requested signals'''
  94. for sig in settings.get('I18N_FILTER_SIGNALS', []):
  95. sig.connect(filter_contents_translations)
  96. def initialize_plugin(pelican_obj):
  97. '''Initialize plugin variables and Pelican settings'''
  98. if _MAIN_SETTINGS is None:
  99. initialize_dbs(pelican_obj.settings)
  100. subscribe_filter_to_signals(pelican_obj.settings)
  101. def get_site_path(url):
  102. '''Get the path component of an url, excludes siteurl
  103. also normalizes '' to '/' for relpath to work,
  104. otherwise it could be interpreted as a relative filesystem path
  105. '''
  106. path = urlparse(url).path
  107. if path == '':
  108. path = '/'
  109. return path
  110. def relpath_to_site(lang, target_lang):
  111. '''Get relative path from siteurl of lang to siteurl of base_lang
  112. the output is cached in _SITES_RELPATH_DB
  113. '''
  114. path = _SITES_RELPATH_DB.get((lang, target_lang), None)
  115. if path is None:
  116. siteurl = _SITE_DB.get(lang, _MAIN_SITEURL)
  117. target_siteurl = _SITE_DB.get(target_lang, _MAIN_SITEURL)
  118. path = posixpath.relpath(get_site_path(target_siteurl),
  119. get_site_path(siteurl))
  120. _SITES_RELPATH_DB[(lang, target_lang)] = path
  121. return path
  122. def save_generator(generator):
  123. '''Save the generator for later use
  124. initialize the removed content list
  125. '''
  126. _GENERATOR_DB[generator] = []
  127. def article2draft(article):
  128. '''Transform an Article to Draft'''
  129. draft = Draft(article._content, article.metadata, article.settings,
  130. article.source_path, article._context)
  131. draft.status = 'draft'
  132. return draft
  133. def page2hidden_page(page):
  134. '''Transform a Page to a hidden Page'''
  135. page.status = 'hidden'
  136. return page
  137. class GeneratorInspector(object):
  138. '''Inspector of generator instances'''
  139. generators_info = {
  140. ArticlesGenerator: {
  141. 'translations_lists': ['translations', 'drafts_translations'],
  142. 'contents_lists': [('articles', 'drafts')],
  143. 'hiding_func': article2draft,
  144. 'policy': 'I18N_UNTRANSLATED_ARTICLES',
  145. },
  146. PagesGenerator: {
  147. 'translations_lists': ['translations', 'hidden_translations'],
  148. 'contents_lists': [('pages', 'hidden_pages')],
  149. 'hiding_func': page2hidden_page,
  150. 'policy': 'I18N_UNTRANSLATED_PAGES',
  151. },
  152. }
  153. def __init__(self, generator):
  154. '''Identify the best known class of the generator instance
  155. The class '''
  156. self.generator = generator
  157. self.generators_info.update(generator.settings.get(
  158. 'I18N_GENERATORS_INFO', {}))
  159. for cls in generator.__class__.__mro__:
  160. if cls in self.generators_info:
  161. self.info = self.generators_info[cls]
  162. break
  163. else:
  164. self.info = {}
  165. def translations_lists(self):
  166. '''Iterator over lists of content translations'''
  167. return (getattr(self.generator, name) for name in
  168. self.info.get('translations_lists', []))
  169. def contents_list_pairs(self):
  170. '''Iterator over pairs of normal and hidden contents'''
  171. return (tuple(getattr(self.generator, name) for name in names)
  172. for names in self.info.get('contents_lists', []))
  173. def hiding_function(self):
  174. '''Function for transforming content to a hidden version'''
  175. hiding_func = self.info.get('hiding_func', lambda x: x)
  176. return hiding_func
  177. def untranslated_policy(self, default):
  178. '''Get the policy for untranslated content'''
  179. return self.generator.settings.get(self.info.get('policy', None),
  180. default)
  181. def all_contents(self):
  182. '''Iterator over all contents'''
  183. translations_iterator = chain(*self.translations_lists())
  184. return chain(translations_iterator,
  185. *(pair[i] for pair in self.contents_list_pairs()
  186. for i in (0, 1)))
  187. def filter_contents_translations(generator):
  188. '''Filter the content and translations lists of a generator
  189. Filters out
  190. 1) translations which will be generated in a different site
  191. 2) content that is not in the language of the currently
  192. generated site but in that of a different site, content in a
  193. language which has no site is generated always. The filtering
  194. method bay be modified by the respective untranslated policy
  195. '''
  196. inspector = GeneratorInspector(generator)
  197. current_lang = generator.settings['DEFAULT_LANG']
  198. langs_with_sites = _SITE_DB.keys()
  199. removed_contents = _GENERATOR_DB[generator]
  200. for translations in inspector.translations_lists():
  201. for translation in translations[:]: # copy to be able to remove
  202. if translation.lang in langs_with_sites:
  203. translations.remove(translation)
  204. removed_contents.append(translation)
  205. hiding_func = inspector.hiding_function()
  206. untrans_policy = inspector.untranslated_policy(default='hide')
  207. for (contents, other_contents) in inspector.contents_list_pairs():
  208. for content in other_contents: # save any hidden native content first
  209. if content.lang == current_lang: # in native lang
  210. # save the native URL attr formatted in the current locale
  211. _NATIVE_CONTENT_URL_DB[content.source_path] = content.url
  212. for content in contents[:]: # copy for removing in loop
  213. if content.lang == current_lang: # in native lang
  214. # save the native URL attr formatted in the current locale
  215. _NATIVE_CONTENT_URL_DB[content.source_path] = content.url
  216. elif content.lang in langs_with_sites and untrans_policy != 'keep':
  217. contents.remove(content)
  218. if untrans_policy == 'hide':
  219. other_contents.append(hiding_func(content))
  220. elif untrans_policy == 'remove':
  221. removed_contents.append(content)
  222. def install_templates_translations(generator):
  223. '''Install gettext translations in the jinja2.Environment
  224. Only if the 'jinja2.ext.i18n' jinja2 extension is enabled
  225. the translations for the current DEFAULT_LANG are installed.
  226. '''
  227. if 'JINJA_ENVIRONMENT' in generator.settings: # pelican 3.7+
  228. jinja_extensions = generator.settings['JINJA_ENVIRONMENT'].get(
  229. 'extensions', [])
  230. else:
  231. jinja_extensions = generator.settings['JINJA_EXTENSIONS']
  232. if 'jinja2.ext.i18n' in jinja_extensions:
  233. domain = generator.settings.get('I18N_GETTEXT_DOMAIN', 'messages')
  234. localedir = generator.settings.get('I18N_GETTEXT_LOCALEDIR')
  235. if localedir is None:
  236. localedir = os.path.join(generator.theme, 'translations')
  237. current_lang = generator.settings['DEFAULT_LANG']
  238. if current_lang == generator.settings.get('I18N_TEMPLATES_LANG',
  239. _MAIN_LANG):
  240. translations = gettext.NullTranslations()
  241. else:
  242. langs = [current_lang]
  243. try:
  244. translations = gettext.translation(domain, localedir, langs)
  245. except (IOError, OSError):
  246. _LOGGER.error((
  247. "Cannot find translations for language '{}' in '{}' with "
  248. "domain '{}'. Installing NullTranslations.").format(
  249. langs[0], localedir, domain))
  250. translations = gettext.NullTranslations()
  251. newstyle = generator.settings.get('I18N_GETTEXT_NEWSTYLE', True)
  252. generator.env.install_gettext_translations(translations, newstyle)
  253. def add_variables_to_context(generator):
  254. '''Adds useful iterable variables to template context'''
  255. context = generator.context # minimize attr lookup
  256. context['relpath_to_site'] = relpath_to_site
  257. context['main_siteurl'] = _MAIN_SITEURL
  258. context['main_lang'] = _MAIN_LANG
  259. context['lang_siteurls'] = _SITE_DB
  260. current_lang = generator.settings['DEFAULT_LANG']
  261. extra_siteurls = _SITE_DB.copy()
  262. extra_siteurls.pop(current_lang)
  263. context['extra_siteurls'] = extra_siteurls
  264. def interlink_translations(content):
  265. '''Link content to translations in their main language
  266. so the URL (including localized month names) of the different subsites
  267. will be honored
  268. '''
  269. lang = content.lang
  270. # sort translations by lang
  271. content.translations.sort(key=attrgetter('lang'))
  272. for translation in content.translations:
  273. relpath = relpath_to_site(lang, translation.lang)
  274. url = _NATIVE_CONTENT_URL_DB[translation.source_path]
  275. translation.override_url = posixpath.join(relpath, url)
  276. def interlink_translated_content(generator):
  277. '''Make translations link to the native locations
  278. for generators that may contain translated content
  279. '''
  280. inspector = GeneratorInspector(generator)
  281. for content in inspector.all_contents():
  282. interlink_translations(content)
  283. def interlink_removed_content(generator):
  284. '''For all contents removed from generation queue update interlinks
  285. link to the native location
  286. '''
  287. current_lang = generator.settings['DEFAULT_LANG']
  288. for content in _GENERATOR_DB[generator]:
  289. url = _NATIVE_CONTENT_URL_DB[content.source_path]
  290. relpath = relpath_to_site(current_lang, content.lang)
  291. content.override_url = posixpath.join(relpath, url)
  292. def interlink_static_files(generator):
  293. '''Add links to static files in the main site if necessary'''
  294. if generator.settings['STATIC_PATHS'] != []:
  295. return # customized STATIC_PATHS
  296. try: # minimize attr lookup
  297. static_content = generator.context['static_content']
  298. except KeyError:
  299. static_content = generator.context['filenames']
  300. relpath = relpath_to_site(generator.settings['DEFAULT_LANG'], _MAIN_LANG)
  301. for staticfile in _MAIN_STATIC_FILES:
  302. if staticfile.get_relative_source_path() not in static_content:
  303. staticfile = copy(staticfile) # prevent override in main site
  304. staticfile.override_url = posixpath.join(relpath, staticfile.url)
  305. try:
  306. generator.add_source_path(staticfile, static=True)
  307. except TypeError:
  308. generator.add_source_path(staticfile)
  309. def save_main_static_files(static_generator):
  310. '''Save the static files generated for the main site'''
  311. global _MAIN_STATIC_FILES
  312. # test just for current lang as settings change in autoreload mode
  313. if static_generator.settings['DEFAULT_LANG'] == _MAIN_LANG:
  314. _MAIN_STATIC_FILES = static_generator.staticfiles
  315. def update_generators():
  316. '''Update the context of all generators
  317. Ads useful variables and translations into the template context
  318. and interlink translations
  319. '''
  320. for generator in _GENERATOR_DB.keys():
  321. install_templates_translations(generator)
  322. add_variables_to_context(generator)
  323. interlink_static_files(generator)
  324. interlink_removed_content(generator)
  325. interlink_translated_content(generator)
  326. def get_pelican_cls(settings):
  327. '''Get the Pelican class requested in settings'''
  328. cls = settings['PELICAN_CLASS']
  329. if isinstance(cls, six.string_types):
  330. module, cls_name = cls.rsplit('.', 1)
  331. module = __import__(module)
  332. cls = getattr(module, cls_name)
  333. return cls
  334. def create_next_subsite(pelican_obj):
  335. '''Create the next subsite using the lang-specific config
  336. If there are no more subsites in the generation queue, update all
  337. the generators (interlink translations and removed content, add
  338. variables and translations to template context). Otherwise get the
  339. language and overrides for next the subsite in the queue and apply
  340. overrides. Then generate the subsite using a PELICAN_CLASS
  341. instance and its run method. Finally, restore the previous locale.
  342. '''
  343. global _MAIN_SETTINGS
  344. if len(_SUBSITE_QUEUE) == 0:
  345. _LOGGER.debug(
  346. 'i18n: Updating cross-site links and context of all generators.')
  347. update_generators()
  348. _MAIN_SETTINGS = None # to initialize next time
  349. else:
  350. with temporary_locale():
  351. settings = _MAIN_SETTINGS.copy()
  352. lang, overrides = _SUBSITE_QUEUE.popitem()
  353. settings.update(overrides)
  354. settings = configure_settings(settings) # to set LOCALE, etc.
  355. cls = get_pelican_cls(settings)
  356. new_pelican_obj = cls(settings)
  357. _LOGGER.debug(("Generating i18n subsite for language '{}' "
  358. "using class {}").format(lang, cls))
  359. new_pelican_obj.run()
  360. # map: signal name -> function name
  361. _SIGNAL_HANDLERS_DB = {
  362. 'get_generators': initialize_plugin,
  363. 'article_generator_pretaxonomy': filter_contents_translations,
  364. 'page_generator_finalized': filter_contents_translations,
  365. 'get_writer': create_next_subsite,
  366. 'static_generator_finalized': save_main_static_files,
  367. 'generator_init': save_generator,
  368. }
  369. def register():
  370. '''Register the plugin only if required signals are available'''
  371. for sig_name in _SIGNAL_HANDLERS_DB.keys():
  372. if not hasattr(signals, sig_name):
  373. _LOGGER.error((
  374. 'The i18n_subsites plugin requires the {} '
  375. 'signal available for sure in Pelican 3.4.0 and later, '
  376. 'plugin will not be used.').format(sig_name))
  377. return
  378. for sig_name, handler in _SIGNAL_HANDLERS_DB.items():
  379. sig = getattr(signals, sig_name)
  380. sig.connect(handler)