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

yaml literals #70

Merged
merged 26 commits into from
Dec 3, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ console_scripts =

[options.extras_require]
toml = tomli
yaml = pyyaml

[scriv]
version = literal: src/scriv/__init__.py: __version__
Expand Down
31 changes: 31 additions & 0 deletions src/scriv/literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
except ImportError: # pragma: no cover
tomli = None # type: ignore

try:
import yaml
except ImportError: # pragma: no cover
yaml = None # type: ignore

def find_literal(file_name: str, literal_name: str) -> Optional[str]:
"""
Expand All @@ -35,6 +39,16 @@ def find_literal(file_name: str, literal_name: str) -> Optional[str]:
with open(file_name, encoding="utf-8") as f:
data = tomli.loads(f.read())
return find_toml_value(data, literal_name)
elif ext == ".yml" or ext == ".yaml":
if yaml is None:
msg = (
"Can't read {!r} without yaml support. "
+ "Install with [yaml] extra"
).format(file_name)
raise Exception(msg)
with open(file_name, encoding="utf-8") as f:
data = yaml.safe_load(f.read())
fkuep marked this conversation as resolved.
Show resolved Hide resolved
return find_yaml_value(data, literal_name)
else:
raise Exception(f"Can't read literals from files like {file_name!r}")

Expand Down Expand Up @@ -98,3 +112,20 @@ def find_toml_value(data: MutableMapping[str, Any], name: str) -> Optional[str]:
if isinstance(current_object, str):
return current_object
return None

def find_yaml_value(data: MutableMapping[str, Any], name: str) -> Optional[str]:
fkuep marked this conversation as resolved.
Show resolved Hide resolved
"""
Use a period-separated name to traverse a dictionary.

Only string values are supported.
"""
current_object = data
for key in name.split("."):
try:
current_object = current_object[key]
except (KeyError, TypeError):
return None

if isinstance(current_object, str):
return current_object
return None