Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Safer loading of YAML file with language names #766

Merged
merged 3 commits into from
Sep 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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