Skip to content

Commit

Permalink
Convert 'default', 'choices', 'sample' to type; change booleans to 't…
Browse files Browse the repository at this point in the history
…rue' and 'false' (#19)

* Normalize booleans to 'true' and 'false' instead of 'yes' and 'no'.

* Began with default / sample / choices format adjustment.

* Vendor code from ansible/ansible.

* Add changelog fragment.

* Fix tests.
  • Loading branch information
felixfontein authored Aug 15, 2022
1 parent 878eebb commit d567311
Show file tree
Hide file tree
Showing 9 changed files with 631 additions and 30 deletions.
8 changes: 8 additions & 0 deletions LICENSES/BSD-2-Clause.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

3 changes: 3 additions & 0 deletions changelogs/fragments/19-type-conversion-booleans.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
minor_changes:
- "Ensure that values for ``default``, ``choices``, and ``sample`` use the types specified for the option / return value (https://github.com/ansible-community/antsibull-docs/pull/19)."
- "Use ``true`` and ``false`` for booleans instead of ``yes`` and ``no`` (https://github.com/ansible-community/community-topics/issues/116, https://github.com/ansible-community/antsibull-docs/pull/19)."
28 changes: 14 additions & 14 deletions src/antsibull_docs/data/docsite/macros/parameters.rst.j2
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@

{% endfor %}
{# default / choices #}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if value['default'] is sameas true %}
{% set _x = value.update({'default': 'yes'}) %}
{% set _x = value.update({'default': 'true'}) %}
{% elif value['default'] is not none and value['default'] is sameas false %}
{% set _x = value.update({'default': 'no'}) %}
{% set _x = value.update({'default': 'false'}) %}
{% endif %}
{% if value['type'] == 'bool' %}
{% set _x = value.update({'choices': ['no', 'yes']}) %}
{% set _x = value.update({'choices': ['false', 'true']}) %}
{% endif %}
{# Show possible choices and highlight details #}
{% if value['choices'] %}
Expand All @@ -93,11 +93,11 @@
:ansible-option-choices:`Choices:`

{% for choice in value['choices'] %}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if choice is sameas true %}
{% set choice = 'yes' %}
{% set choice = 'true' %}
{% elif choice is sameas false %}
{% set choice = 'no' %}
{% set choice = 'false' %}
{% endif %}
{% if (value['default'] is not list and value['default'] == choice) or (value['default'] is list and choice in value['default']) %}
- :ansible-option-default-bold:`@{ choice | rst_escape(escape_ending_whitespace=true) }@` :ansible-option-default:`← (default)`
Expand Down Expand Up @@ -226,25 +226,25 @@
<p>@{ desc | html_ify | indent(6, blank=true) }@</p>
{% endfor %}
{# default / choices #}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if value['default'] is sameas true %}
{% set _x = value.update({'default': 'yes'}) %}
{% set _x = value.update({'default': 'true'}) %}
{% elif value['default'] is not none and value['default'] is sameas false %}
{% set _x = value.update({'default': 'no'}) %}
{% set _x = value.update({'default': 'false'}) %}
{% endif %}
{% if value['type'] == 'bool' %}
{% set _x = value.update({'choices': ['no', 'yes']}) %}
{% set _x = value.update({'choices': ['false', 'true']}) %}
{% endif %}
{# Show possible choices and highlight details #}
{% if value['choices'] %}
<p class="ansible-option-line"><span class="ansible-option-choices">Choices:</span></p>
<ul class="simple">
{% for choice in value['choices'] %}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if choice is sameas true %}
{% set choice = 'yes' %}
{% set choice = 'true' %}
{% elif choice is sameas false %}
{% set choice = 'no' %}
{% set choice = 'false' %}
{% endif %}
{% if (value['default'] is not list and value['default'] == choice) or (value['default'] is list and choice in value['default']) %}
<li><p><span class="ansible-option-default-bold">@{ choice | escape }@</span> <span class="ansible-option-default">← (default)</span></p></li>
Expand Down
12 changes: 6 additions & 6 deletions src/antsibull_docs/data/docsite/macros/returnvalues.rst.j2
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@
:ansible-option-choices:`Can only return:`

{% for choice in value['choices'] %}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if choice is sameas true %}
{% set choice = 'yes' %}
{% set choice = 'true' %}
{% elif choice is sameas false %}
{% set choice = 'no' %}
{% set choice = 'false' %}
{% endif %}
{% if (value['default'] is not list and value['default'] == choice) or (value['default'] is list and choice in value['default']) %}
- :ansible-option-default-bold:`@{ choice | rst_escape }@` :ansible-option-default:`← (default)`
Expand Down Expand Up @@ -152,11 +152,11 @@
<p class="ansible-option-line"><span class="ansible-option-choices">Can only return:</span></p>
<ul class="simple">
{% for choice in value['choices'] %}
{# Turn boolean values in 'yes' and 'no' values #}
{# Turn boolean values in 'true' and 'false' values #}
{% if choice is sameas true %}
{% set choice = 'yes' %}
{% set choice = 'true' %}
{% elif choice is sameas false %}
{% set choice = 'no' %}
{% set choice = 'false' %}
{% endif %}
{% if (value['default'] is not list and value['default'] == choice) or (value['default'] is list and choice in value['default']) %}
<li><p><span class="ansible-option-default-bold">@{ choice | escape }@</span> <span class="ansible-option-default">← (default)</span></p></li>
Expand Down
87 changes: 82 additions & 5 deletions src/antsibull_docs/schemas/docs/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,20 @@ def handle_renamed_attribute(cls, values):
import pydantic as p
import yaml

from antsibull_docs.vendored.ansible import (
check_type_bits,
check_type_bool,
check_type_bytes,
check_type_dict,
check_type_float,
check_type_int,
check_type_jsonarg,
check_type_list,
check_type_raw,
check_type_str,
)


_SENTINEL = object()


Expand Down Expand Up @@ -271,6 +285,62 @@ def normalize_return_type_names(obj):
return obj


TYPE_CHECKERS = {
'str': check_type_str,
'list': check_type_list,
'dict': check_type_dict,
'bool': check_type_bool,
'int': check_type_int,
'float': check_type_float,
'path': check_type_str, # we intentionally use check_type_str here
'tmppath': check_type_str, # we intentionally use check_type_str here
'raw': check_type_raw,
'jsonarg': check_type_jsonarg,
'json': check_type_jsonarg,
'bytes': check_type_bytes,
'bits': check_type_bits,
}


def normalize_value(values: t.Dict[str, t.Any], field: str, # noqa: C901
is_list_of_values: bool = False) -> None:
if 'type' not in values or values.get(field) is None:
return

value = values[field]
type_name = normalize_option_type_names(values['type'])
type_checker = TYPE_CHECKERS.get(type_name)
if type_checker is None:
return

elements_name = normalize_option_type_names(values.get('elements'))
elements_checker = TYPE_CHECKERS.get(elements_name)

if not is_list_of_values:
value = [value]
elif not isinstance(value, list):
return

for i, v in enumerate(value):
try:
v = type_checker(v)
except Exception as exc:
# pylint:disable-next=raise-missing-from
raise ValueError(f'Invalid value {v!r} for "{field}": {exc}')
if type_name == 'list' and elements_checker is not None:
for j, vv in enumerate(v):
try:
v[j] = elements_checker(vv)
except Exception as exc:
# pylint:disable-next=raise-missing-from
raise ValueError(f'Invalid value {vv!r} for "{field}[{i}]": {exc}')
value[i] = v

if not is_list_of_values:
value = value[0]
values[field] = value


class LocalConfig:
"""Settings we want on all of our models."""

Expand Down Expand Up @@ -394,11 +464,6 @@ def is_json_value(cls, obj):
raise ValueError('`default` must be a JSON value')
return obj

@p.validator('type', 'elements', pre=True)
# pylint:disable=no-self-argument,no-self-use
def normalize_option_type(cls, obj):
return normalize_option_type_names(obj)

@p.root_validator(pre=True)
# pylint:disable=no-self-argument,no-self-use
def get_rid_of_name(cls, values):
Expand Down Expand Up @@ -435,6 +500,18 @@ def merge_typo_names(cls, values):

return values

@p.validator('type', 'elements', pre=True)
# pylint:disable=no-self-argument,no-self-use
def normalize_option_type(cls, obj):
return normalize_option_type_names(obj)

@p.root_validator(pre=True)
# pylint:disable=no-self-argument,no-self-use
def normalize_default_choices(cls, values):
normalize_value(values, 'default')
normalize_value(values, 'choices', is_list_of_values=values.get('type') != 'list')
return values


class SeeAlsoModSchema(BaseModel):
module: str
Expand Down
12 changes: 11 additions & 1 deletion src/antsibull_docs/schemas/docs/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
from .base import (REQUIRED_CLI_F, REQUIRED_ENV_VAR_F, RETURN_TYPE_F,
COLLECTION_NAME_F, BaseModel, DeprecationSchema, DocSchema,
LocalConfig, OptionsSchema, list_from_scalars, is_json_value,
normalize_return_type_names, transform_return_docs)
normalize_return_type_names, transform_return_docs,
normalize_value)

_SENTINEL = object()

Expand Down Expand Up @@ -123,6 +124,15 @@ def remove_example(cls, values):

return values

@p.root_validator(pre=True)
# pylint:disable=no-self-argument,no-self-use
def normalize_sample(cls, values):
try:
normalize_value(values, 'sample')
except ValueError:
pass
return values


class InnerReturnSchema(ReturnSchema):
"""Nested return schema which allows leaving out description."""
Expand Down
Loading

0 comments on commit d567311

Please sign in to comment.