Skip to content

Commit

Permalink
Merge pull request #766 from SuffolkLITLab/languages-fix
Browse files Browse the repository at this point in the history
Safer loading of YAML file with language names
  • Loading branch information
nonprofittechy authored Sep 23, 2023
2 parents 8c71547 + 8233d50 commit d77be96
Showing 1 changed file with 30 additions and 3 deletions.
33 changes: 30 additions & 3 deletions docassemble/AssemblyLine/language.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# coding=utf-8
import os
from typing import List, Optional, Tuple
from docassemble.base.util import url_action, path_and_mimetype
import yaml
Expand All @@ -13,6 +14,32 @@
]


def _package_name(package_name: Optional[str] = None):
"""Get package name without the name of the given module. By default this is `docassemble.AssemblyLine.language`"""
if not package_name:
package_name = __name__
try:
return ".".join(package_name.split(".")[:-1])
except:
return package_name


def get_local_languages_yaml():
try:
local_yaml = path_and_mimetype("data/sources/languages.yml")[0]
except:
local_yaml = None

if local_yaml and os.path.isfile(local_yaml):
return local_yaml

al_package_name = _package_name()
this_yaml = path_and_mimetype(f"{al_package_name}:data/sources/languages.yml")[
0
]
return this_yaml


def get_tuples(
lang_codes: List[str], languages_path: Optional[str] = None
) -> List[Tuple[str, str]]:
Expand All @@ -31,7 +58,7 @@ def get_tuples(
"""
if not languages_path:
languages_path = path_and_mimetype("data/sources/languages.yml")[0]
languages_path = get_local_languages_yaml()

if languages_path is not None:
with open(languages_path, "r", encoding="utf-8") as stream:
Expand Down Expand Up @@ -91,7 +118,7 @@ def get_language_list_dropdown(
</li>
"""
if not languages_path:
languages_path = path_and_mimetype("data/sources/languages.yml")[0]
languages_path = get_local_languages_yaml()
languages = get_tuples(lang_codes, languages_path=languages_path)

for language in languages:
Expand Down Expand Up @@ -152,7 +179,7 @@ def get_language_list(
A string containing the HTML for an unordered inline list of language selection.
"""
if not languages_path:
languages_path = path_and_mimetype("data/sources/languages.yml")[0]
languages_path = get_local_languages_yaml()
if not languages:
if not lang_codes:
raise ValueError("Either languages or lang_codes must be provided")
Expand Down

0 comments on commit d77be96

Please sign in to comment.