From 98fb0b328ed500d64ec307227ed26b50f72f8454 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 17 Jun 2026 10:12:34 -0700 Subject: [PATCH 1/5] fix(http-client-python): keep Sphinx docstring annotations out of trailing code blocks Append annotations like Required. as their own paragraph after a trailing RST code block, and skip the sentence-ending period when a description ends with a code block so it no longer lands inside the rendered literal block. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...quired-trailing-period-2026-6-17-10-5-0.md | 7 + .../generator/pygen/codegen/models/utils.py | 25 +- .../generator/pygen/preprocess/__init__.py | 220 +++++++++++++----- .../generator/pygen/utils.py | 40 +++- .../tests/unit/test_add_to_description.py | 96 +++++++- 5 files changed, 310 insertions(+), 78 deletions(-) create mode 100644 .chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md diff --git a/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md b/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md new file mode 100644 index 00000000000..65bcbe70509 --- /dev/null +++ b/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@typespec/http-client-python" +--- + +Place docstring annotations such as `Required.` on their own paragraph after a trailing RST code block and stop appending a sentence period inside the block. Previously the period landed on the code block's last line (e.g. `].`) and `Required.` was jammed onto the lead-in sentence, both of which broke Sphinx rendering. diff --git a/packages/http-client-python/generator/pygen/codegen/models/utils.py b/packages/http-client-python/generator/pygen/codegen/models/utils.py index 8fff852a049..9f2c30e7638 100644 --- a/packages/http-client-python/generator/pygen/codegen/models/utils.py +++ b/packages/http-client-python/generator/pygen/codegen/models/utils.py @@ -7,23 +7,20 @@ from enum import Enum +from ...utils import description_ends_with_code_block + T = TypeVar("T") OrderedSet = dict[T, None] -CODE_BLOCK_MARKER = ".. code-block::" - - def add_to_description(description: str, entry: str) -> str: if not description: return entry - # When the description contains a code block, the entry (e.g. "Required.") must be - # inserted into the prose *before* the code block. Appending it after the code block - # (e.g. "]. Required.") leaves it dangling at the end of the rendered block and breaks - # Sphinx rendering. - if CODE_BLOCK_MARKER in description: - prose, _, code_block = description.partition(CODE_BLOCK_MARKER) - return f"{prose.rstrip()} {entry}\n\n{CODE_BLOCK_MARKER}{code_block}" + # When the description ends with a code block, append the entry (e.g. "Required.") as a + # new paragraph after the block. Appending it inline (e.g. "]. Required.") leaves it + # inside the rendered literal block and breaks Sphinx rendering. + if description_ends_with_code_block(description): + return f"{description.rstrip()}\n\n{entry}" return f"{description} {entry}" @@ -44,6 +41,10 @@ class NamespaceType(str, Enum): LOCALS_LENGTH_LIMIT = 25 -REQUEST_BUILDER_BODY_VARIABLES_LENGTH = 6 # how many body variables are present in a request builder +REQUEST_BUILDER_BODY_VARIABLES_LENGTH = ( + 6 # how many body variables are present in a request builder +) -OPERATION_BODY_VARIABLES_LENGTH = 14 # how many body variables are present in an operation +OPERATION_BODY_VARIABLES_LENGTH = ( + 14 # how many body variables are present in an operation +) diff --git a/packages/http-client-python/generator/pygen/preprocess/__init__.py b/packages/http-client-python/generator/pygen/preprocess/__init__.py index 30eedc28d3b..8a2e30cdc87 100644 --- a/packages/http-client-python/generator/pygen/preprocess/__init__.py +++ b/packages/http-client-python/generator/pygen/preprocess/__init__.py @@ -22,6 +22,7 @@ get_body_type_for_description, JSON_REGEXP, KNOWN_TYPES, + description_ends_with_code_block, ) @@ -35,14 +36,18 @@ def update_overload_section( if overload_s.get("type"): overload_s["type"] = original_s["type"] if overload_s.get("headers"): - for overload_h, original_h in zip(overload_s["headers"], original_s["headers"]): + for overload_h, original_h in zip( + overload_s["headers"], original_s["headers"] + ): if overload_h.get("type"): overload_h["type"] = original_h["type"] except KeyError as exc: raise ValueError(overload["name"]) from exc -def add_overload(yaml_data: dict[str, Any], body_type: dict[str, Any], for_flatten_params=False): +def add_overload( + yaml_data: dict[str, Any], body_type: dict[str, Any], for_flatten_params=False +): overload = copy.deepcopy(yaml_data) overload["isOverload"] = True overload["bodyParameter"]["type"] = body_type @@ -54,7 +59,9 @@ def add_overload(yaml_data: dict[str, Any], body_type: dict[str, Any], for_flatt if for_flatten_params: overload["bodyParameter"]["flattened"] = True else: - overload["parameters"] = [p for p in overload["parameters"] if not p.get("inFlattenedBody")] + overload["parameters"] = [ + p for p in overload["parameters"] if not p.get("inFlattenedBody") + ] # for yaml sync, we need to make sure all of the responses, parameters, and exceptions' types have the same yaml id for overload_p, original_p in zip(overload["parameters"], yaml_data["parameters"]): overload_p["type"] = original_p["type"] @@ -62,7 +69,9 @@ def add_overload(yaml_data: dict[str, Any], body_type: dict[str, Any], for_flatt update_overload_section(overload, yaml_data, "exceptions") # update content type to be an overloads content type - content_type_param = next(p for p in overload["parameters"] if p["wireName"].lower() == "content-type") + content_type_param = next( + p for p in overload["parameters"] if p["wireName"].lower() == "content-type" + ) content_type_param["inOverload"] = True content_type_param["inDocstring"] = True body_type_description = get_body_type_for_description(overload["bodyParameter"]) @@ -85,16 +94,25 @@ def add_overloads_for_body_param(yaml_data: dict[str, Any]) -> None: body_parameter = yaml_data["bodyParameter"] if not ( body_parameter["type"]["type"] == "combined" - and len(yaml_data["bodyParameter"]["type"]["types"]) > len(yaml_data["overloads"]) + and len(yaml_data["bodyParameter"]["type"]["types"]) + > len(yaml_data["overloads"]) ): return for body_type in body_parameter["type"]["types"]: - if any(o for o in yaml_data["overloads"] if id(o["bodyParameter"]["type"]) == id(body_type)): + if any( + o + for o in yaml_data["overloads"] + if id(o["bodyParameter"]["type"]) == id(body_type) + ): continue if body_type.get("type") == "model" and body_type.get("base") == "json": - yaml_data["overloads"].append(add_overload(yaml_data, body_type, for_flatten_params=True)) + yaml_data["overloads"].append( + add_overload(yaml_data, body_type, for_flatten_params=True) + ) yaml_data["overloads"].append(add_overload(yaml_data, body_type)) - content_type_param = next(p for p in yaml_data["parameters"] if p["wireName"].lower() == "content-type") + content_type_param = next( + p for p in yaml_data["parameters"] if p["wireName"].lower() == "content-type" + ) content_type_param["inOverload"] = False content_type_param["inOverridden"] = True content_type_param["inDocstring"] = True @@ -104,11 +122,19 @@ def add_overloads_for_body_param(yaml_data: dict[str, Any]) -> None: content_type_param["optional"] = True -def update_description(description: Optional[str], default_description: str = "") -> str: +def update_description( + description: Optional[str], default_description: str = "" +) -> str: if not description: description = default_description description.rstrip(" ") - if description and description[-1] != ".": + # Don't append a trailing period when the description ends with a code block: the + # period would land inside the rendered literal block (e.g. "]." ) and break Sphinx. + if ( + description + and description[-1] != "." + and not description_ends_with_code_block(description) + ): description += "." return description @@ -171,7 +197,9 @@ def _get_etag_role(parameter: dict[str, Any]) -> Optional[str]: return parameter.get("etagRole") -def _pick_etag_slot(candidates: list[dict[str, Any]], standard_wire_name: str) -> Optional[dict[str, Any]]: +def _pick_etag_slot( + candidates: list[dict[str, Any]], standard_wire_name: str +) -> Optional[dict[str, Any]]: """Choose which etag-typed header should be promoted to the etag/match_condition slot. When more than one etag-typed header is present in an operation, prefer the @@ -199,16 +227,25 @@ def _resolve_etag_pair( Returns (property_if_match, property_if_none_match) — both None when there are no etag candidates. """ - property_if_match = _pick_etag_slot(if_match_candidates, STANDARD_IF_MATCH_WIRE_NAME) - property_if_none_match = _pick_etag_slot(if_none_match_candidates, STANDARD_IF_NONE_MATCH_WIRE_NAME) + property_if_match = _pick_etag_slot( + if_match_candidates, STANDARD_IF_MATCH_WIRE_NAME + ) + property_if_none_match = _pick_etag_slot( + if_none_match_candidates, STANDARD_IF_NONE_MATCH_WIRE_NAME + ) # Ensure the promoted pair come from the same family. When one slot is # standard and the other custom (cross-family), replace the custom slot # with a synthetic standard partner. Also synthesize the missing partner # when only one side is present. if property_if_match and property_if_none_match: - match_is_std = get_wire_name_lower(property_if_match) == STANDARD_IF_MATCH_WIRE_NAME - none_match_is_std = get_wire_name_lower(property_if_none_match) == STANDARD_IF_NONE_MATCH_WIRE_NAME + match_is_std = ( + get_wire_name_lower(property_if_match) == STANDARD_IF_MATCH_WIRE_NAME + ) + none_match_is_std = ( + get_wire_name_lower(property_if_none_match) + == STANDARD_IF_NONE_MATCH_WIRE_NAME + ) if match_is_std and not none_match_is_std: property_if_none_match = property_if_match.copy() property_if_none_match["wireName"] = STANDARD_IF_NONE_MATCH_WIRE_NAME @@ -256,11 +293,15 @@ def _process_operation_etag_headers( elif role == "ifNoneMatch": if_none_match_candidates.append(p) - property_if_match, property_if_none_match = _resolve_etag_pair(if_match_candidates, if_none_match_candidates) + property_if_match, property_if_none_match = _resolve_etag_pair( + if_match_candidates, if_none_match_candidates + ) if property_if_match and property_if_none_match: etag_params = {id(property_if_match), id(property_if_none_match)} - operation["parameters"] = [item for item in operation["parameters"] if id(item) not in etag_params] + [ + operation["parameters"] = [ + item for item in operation["parameters"] if id(item) not in etag_params + ] + [ property_if_match, property_if_none_match, ] @@ -279,7 +320,9 @@ def has_json_content_type(yaml_data: dict[str, Any]) -> bool: def has_multi_part_content_type(yaml_data: dict[str, Any]) -> bool: - return any(ct for ct in yaml_data.get("contentTypes", []) if ct == "multipart/form-data") + return any( + ct for ct in yaml_data.get("contentTypes", []) if ct == "multipart/form-data" + ) class PreProcessPlugin(YamlUpdatePlugin): @@ -310,13 +353,18 @@ def add_body_param_type( if ( # pylint: disable=too-many-boolean-expressions body_parameter and body_parameter["type"]["type"] in ("model", "dict", "list") - and (has_json_content_type(body_parameter) or (self.is_tsp and has_multi_part_content_type(body_parameter))) + and ( + has_json_content_type(body_parameter) + or (self.is_tsp and has_multi_part_content_type(body_parameter)) + ) and not body_parameter["type"].get("xmlMetadata") and not any(t for t in ["flattened", "groupedBy"] if body_parameter.get(t)) ): origin_type = body_parameter["type"]["type"] model_type = ( - body_parameter["type"] if origin_type == "model" else body_parameter["type"].get("elementType", {}) + body_parameter["type"] + if origin_type == "model" + else body_parameter["type"].get("elementType", {}) ) is_dpg_model = model_type.get("base") == "dpg" body_parameter["type"] = { @@ -333,19 +381,26 @@ def add_body_param_type( else: # dict or list # copy the original dict / list type - any_obj_list_or_dict = copy.deepcopy(body_parameter["type"]["types"][0]) + any_obj_list_or_dict = copy.deepcopy( + body_parameter["type"]["types"][0] + ) any_obj_list_or_dict["elementType"] = KNOWN_TYPES["any-object"] body_parameter["type"]["types"].insert(1, any_obj_list_or_dict) code_model["types"].append(body_parameter["type"]) - def pad_reserved_words(self, name: str, pad_type: PadType, yaml_type: dict[str, Any]) -> str: + def pad_reserved_words( + self, name: str, pad_type: PadType, yaml_type: dict[str, Any] + ) -> str: # we want to pad hidden variables as well if not name: # we'll pass in empty operation groups sometime etc. return name if self.is_tsp: - reserved_words = {k: (v + TSP_RESERVED_WORDS.get(k, [])) for k, v in RESERVED_WORDS.items()} + reserved_words = { + k: (v + TSP_RESERVED_WORDS.get(k, [])) + for k, v in RESERVED_WORDS.items() + } else: reserved_words = RESERVED_WORDS name = pad_special_chars(name) @@ -362,18 +417,24 @@ def pad_reserved_words(self, name: str, pad_type: PadType, yaml_type: dict[str, def update_types(self, yaml_data: list[dict[str, Any]]) -> None: for type in yaml_data: for property in type.get("properties", []): - property["description"] = update_description(property.get("description", "")) + property["description"] = update_description( + property.get("description", "") + ) if not property.get("isExactName", False): property["clientName"] = self.pad_reserved_words( property["clientName"].lower(), PadType.PROPERTY, property ) add_redefined_builtin_info(property["clientName"], property) if type.get("name"): - pad_type = PadType.MODEL if type["type"] == "model" else PadType.ENUM_CLASS + pad_type = ( + PadType.MODEL if type["type"] == "model" else PadType.ENUM_CLASS + ) if type["type"] != "enumvalue": name = self.pad_reserved_words(type["name"], pad_type, type) type["name"] = name[0].upper() + name[1:] - type["description"] = update_description(type.get("description", ""), type["name"]) + type["description"] = update_description( + type.get("description", ""), type["name"] + ) type["snakeCaseName"] = to_snake_case(type["name"]) if type.get("values"): # we're enums - enum values are UPPER_CASE so no padding needed for reserved words @@ -391,16 +452,24 @@ def update_types(self, yaml_data: list[dict[str, Any]]) -> None: yaml_data.append(CLOUD_SETTING["type"]) # type: ignore def update_client(self, yaml_data: dict[str, Any]) -> None: - yaml_data["description"] = update_description(yaml_data["description"], default_description=yaml_data["name"]) + yaml_data["description"] = update_description( + yaml_data["description"], default_description=yaml_data["name"] + ) yaml_data["legacyFilename"] = to_snake_case(yaml_data["name"].replace(" ", "_")) parameters = yaml_data["parameters"] for parameter in parameters: self.update_parameter(parameter) if parameter["clientName"] == "credential": policy = parameter["type"].get("policy") - if policy and policy["type"] == "BearerTokenCredentialPolicy" and self.azure_arm: + if ( + policy + and policy["type"] == "BearerTokenCredentialPolicy" + and self.azure_arm + ): policy["type"] = "ARMChallengeAuthenticationPolicy" - policy["credentialScopes"] = ["https://management.azure.com/.default"] + policy["credentialScopes"] = [ + "https://management.azure.com/.default" + ] if ( (not self.version_tolerant or self.azure_arm) and parameters @@ -420,7 +489,9 @@ def update_client(self, yaml_data: dict[str, Any]) -> None: if self.azure_arm and yaml_data["parameters"]: yaml_data["parameters"].append(CLOUD_SETTING) - def get_operation_updater(self, yaml_data: dict[str, Any]) -> Callable[[dict[str, Any], dict[str, Any]], None]: + def get_operation_updater( + self, yaml_data: dict[str, Any] + ) -> Callable[[dict[str, Any], dict[str, Any]], None]: if yaml_data["discriminator"] == "lropaging": return self.update_lro_paging_operation if yaml_data["discriminator"] == "lro": @@ -432,7 +503,8 @@ def get_operation_updater(self, yaml_data: dict[str, Any]) -> Callable[[dict[str def update_parameter(self, yaml_data: dict[str, Any]) -> None: yaml_data["description"] = update_description(yaml_data.get("description", "")) if not yaml_data.get("isExactName", False) and not ( - yaml_data["location"] == "header" and yaml_data["clientName"] in ("content_type", "accept") + yaml_data["location"] == "header" + and yaml_data["clientName"] in ("content_type", "accept") ): yaml_data["clientName"] = self.pad_reserved_words( yaml_data["clientName"].lower(), PadType.PARAMETER, yaml_data @@ -448,13 +520,16 @@ def update_parameter(self, yaml_data: dict[str, Any]) -> None: prop: ( param_name if prop in exact_name_props - else self.pad_reserved_words(param_name, PadType.PARAMETER, yaml_data).lower() + else self.pad_reserved_words( + param_name, PadType.PARAMETER, yaml_data + ).lower() ) for prop, param_name in yaml_data["propertyToParameterName"].items() } wire_name_lower = (yaml_data.get("wireName") or "").lower() if yaml_data["location"] == "header" and ( - wire_name_lower in HEADERS_HIDE_IN_METHOD or yaml_data.get("clientDefaultValue") == "multipart/form-data" + wire_name_lower in HEADERS_HIDE_IN_METHOD + or yaml_data.get("clientDefaultValue") == "multipart/form-data" ): yaml_data["hideInMethod"] = True if self.version_tolerant and yaml_data["location"] == "header": @@ -463,7 +538,10 @@ def update_parameter(self, yaml_data: dict[str, Any]) -> None: headers_convert(yaml_data, ETAG_MATCH_DATA) elif role == "ifNoneMatch": headers_convert(yaml_data, ETAG_NONE_MATCH_DATA) - if wire_name_lower in ["$host", "content-type", "accept"] and yaml_data["type"]["type"] == "constant": + if ( + wire_name_lower in ["$host", "content-type", "accept"] + and yaml_data["type"]["type"] == "constant" + ): yaml_data["clientDefaultValue"] = yaml_data["type"]["value"] def update_operation( @@ -473,24 +551,36 @@ def update_operation( *, is_overload: bool = False, ) -> None: - yaml_data["groupName"] = self.pad_reserved_words(yaml_data["groupName"], PadType.OPERATION_GROUP, yaml_data) + yaml_data["groupName"] = self.pad_reserved_words( + yaml_data["groupName"], PadType.OPERATION_GROUP, yaml_data + ) yaml_data["groupName"] = to_snake_case(yaml_data["groupName"]) if yaml_data.get("isExactName", False): # exact() client name: keep the operation name as-is without lowercasing, # snake-casing, or padding reserved words. if yaml_data.get("isLroInitialOperation") is True: - yaml_data["name"] = "_" + extract_original_name(yaml_data["name"]) + "_initial" + yaml_data["name"] = ( + "_" + extract_original_name(yaml_data["name"]) + "_initial" + ) else: yaml_data["name"] = yaml_data["name"].lower() if yaml_data.get("isLroInitialOperation") is True: yaml_data["name"] = ( "_" - + self.pad_reserved_words(extract_original_name(yaml_data["name"]), PadType.METHOD, yaml_data) + + self.pad_reserved_words( + extract_original_name(yaml_data["name"]), + PadType.METHOD, + yaml_data, + ) + "_initial" ) else: - yaml_data["name"] = self.pad_reserved_words(yaml_data["name"], PadType.METHOD, yaml_data) - yaml_data["description"] = update_description(yaml_data["description"], yaml_data["name"]) + yaml_data["name"] = self.pad_reserved_words( + yaml_data["name"], PadType.METHOD, yaml_data + ) + yaml_data["description"] = update_description( + yaml_data["description"], yaml_data["name"] + ) yaml_data["summary"] = update_description(yaml_data.get("summary", "")) body_parameter = yaml_data.get("bodyParameter") for parameter in yaml_data["parameters"]: @@ -511,8 +601,12 @@ def update_operation( def _update_lro_operation_helper(self, yaml_data: dict[str, Any]) -> None: for response in yaml_data.get("responses", []): response["discriminator"] = "lro" - response["pollerSync"] = response.get("pollerSync") or "azure.core.polling.LROPoller" - response["pollerAsync"] = response.get("pollerAsync") or "azure.core.polling.AsyncLROPoller" + response["pollerSync"] = ( + response.get("pollerSync") or "azure.core.polling.LROPoller" + ) + response["pollerAsync"] = ( + response.get("pollerAsync") or "azure.core.polling.AsyncLROPoller" + ) if not response.get("pollingMethodSync"): response["pollingMethodSync"] = ( "azure.mgmt.core.polling.arm_polling.ARMPolling" @@ -534,7 +628,9 @@ def update_lro_paging_operation( item_type: Optional[dict[str, Any]] = None, ) -> None: self.update_lro_operation(code_model, yaml_data, is_overload=is_overload) - self.update_paging_operation(code_model, yaml_data, is_overload=is_overload, item_type=item_type) + self.update_paging_operation( + code_model, yaml_data, is_overload=is_overload, item_type=item_type + ) yaml_data["discriminator"] = "lropaging" for response in yaml_data.get("responses", []): response["discriminator"] = "lropaging" @@ -557,12 +653,16 @@ def convert_initial_operation_response_type(data: dict[str, Any]) -> None: response["type"] = KNOWN_TYPES["binary"] self.update_operation(code_model, yaml_data, is_overload=is_overload) - self.update_operation(code_model, yaml_data["initialOperation"], is_overload=is_overload) + self.update_operation( + code_model, yaml_data["initialOperation"], is_overload=is_overload + ) convert_initial_operation_response_type(yaml_data["initialOperation"]) self._update_lro_operation_helper(yaml_data) for overload in yaml_data.get("overloads", []): self._update_lro_operation_helper(overload) - self.update_operation(code_model, overload["initialOperation"], is_overload=True) + self.update_operation( + code_model, overload["initialOperation"], is_overload=True + ) convert_initial_operation_response_type(overload["initialOperation"]) def update_paging_operation( @@ -576,9 +676,13 @@ def update_paging_operation( item_type = item_type or yaml_data["itemType"]["elementType"] if yaml_data.get("nextOperation"): yaml_data["nextOperation"]["groupName"] = self.pad_reserved_words( - yaml_data["nextOperation"]["groupName"], PadType.OPERATION_GROUP, yaml_data["nextOperation"] + yaml_data["nextOperation"]["groupName"], + PadType.OPERATION_GROUP, + yaml_data["nextOperation"], + ) + yaml_data["nextOperation"]["groupName"] = to_snake_case( + yaml_data["nextOperation"]["groupName"] ) - yaml_data["nextOperation"]["groupName"] = to_snake_case(yaml_data["nextOperation"]["groupName"]) for response in yaml_data["nextOperation"].get("responses", []): update_paging_response(response) response["itemType"] = item_type @@ -586,9 +690,13 @@ def update_paging_operation( update_paging_response(response) response["itemType"] = item_type for overload in yaml_data.get("overloads", []): - self.update_paging_operation(code_model, overload, is_overload=True, item_type=item_type) + self.update_paging_operation( + code_model, overload, is_overload=True, item_type=item_type + ) - def update_operation_groups(self, code_model: dict[str, Any], client: dict[str, Any]) -> None: + def update_operation_groups( + self, code_model: dict[str, Any], client: dict[str, Any] + ) -> None: operation_groups_yaml_data = client.get("operationGroups", []) for operation_group in operation_groups_yaml_data: operation_group["identifyName"] = self.pad_reserved_words( @@ -596,11 +704,17 @@ def update_operation_groups(self, code_model: dict[str, Any], client: dict[str, PadType.OPERATION_GROUP, operation_group, ) - operation_group["identifyName"] = to_snake_case(operation_group["identifyName"]) + operation_group["identifyName"] = to_snake_case( + operation_group["identifyName"] + ) operation_group["propertyName"] = self.pad_reserved_words( - operation_group["propertyName"], PadType.OPERATION_GROUP, operation_group + operation_group["propertyName"], + PadType.OPERATION_GROUP, + operation_group, + ) + operation_group["propertyName"] = to_snake_case( + operation_group["propertyName"] ) - operation_group["propertyName"] = to_snake_case(operation_group["propertyName"]) operation_group["className"] = update_operation_group_class_name( client["name"], operation_group["className"] ) @@ -624,4 +738,6 @@ def update_yaml(self, yaml_data: dict[str, Any]) -> None: if __name__ == "__main__": # TSP pipeline will call this args, unknown_args = parse_args() - PreProcessPlugin(output_folder=args.output_folder, tsp_file=args.tsp_file, **unknown_args).process() + PreProcessPlugin( + output_folder=args.output_folder, tsp_file=args.tsp_file, **unknown_args + ).process() diff --git a/packages/http-client-python/generator/pygen/utils.py b/packages/http-client-python/generator/pygen/utils.py index e5733a38968..c96d8ca7582 100644 --- a/packages/http-client-python/generator/pygen/utils.py +++ b/packages/http-client-python/generator/pygen/utils.py @@ -11,8 +11,29 @@ TYPESPEC_PACKAGE_MODE = ["azure-mgmt", "azure-dataplane", "generic"] VALID_PACKAGE_MODE = SWAGGER_PACKAGE_MODE + TYPESPEC_PACKAGE_MODE +CODE_BLOCK_MARKER = ".. code-block::" + + +def description_ends_with_code_block(description: str) -> bool: + """Return True when the description's trailing content is an RST code block. + + The code block is the trailing content when, after the ``.. code-block::`` directive's + first line (its language argument), every remaining line is either blank or indented + (i.e. still part of the literal block), with no unindented prose paragraph following it. + """ + marker_index = description.rfind(CODE_BLOCK_MARKER) + if marker_index == -1: + return False + after_marker = description[marker_index + len(CODE_BLOCK_MARKER) :] + for line in after_marker.splitlines()[1:]: + if line.strip() and not line.startswith((" ", "\t")): + return False + return True + -def update_enum_value(name: str, value: Any, description: str, enum_type: dict[str, Any]) -> dict[str, Any]: +def update_enum_value( + name: str, value: Any, description: str, enum_type: dict[str, Any] +) -> dict[str, Any]: return { "name": name, "type": "enumvalue", @@ -39,7 +60,12 @@ def replace_upper_characters(m) -> str: and len(name) - next_non_upper_case_char_location > 1 and name[next_non_upper_case_char_location].isalpha() ): - return prefix + match_str[: len(match_str) - 1] + "_" + match_str[len(match_str) - 1] + return ( + prefix + + match_str[: len(match_str) - 1] + + "_" + + match_str[len(match_str) - 1] + ) return prefix + match_str @@ -86,7 +112,9 @@ def _get_value(value: Any) -> Any: return value unknown_args_ret = { - ua.strip("--").split("=", maxsplit=1)[0]: _get_value(ua.strip("--").split("=", maxsplit=1)[1]) + ua.strip("--").split("=", maxsplit=1)[0]: _get_value( + ua.strip("--").split("=", maxsplit=1)[1] + ) for ua in unknown_args } return args, unknown_args_ret @@ -128,7 +156,11 @@ def build_policies( "self._config.user_agent_policy", "self._config.proxy_policy", "policies.ContentDecodePolicy(**kwargs)", - (f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy()" if is_arm else None), + ( + f"{async_prefix}ARMAutoResourceProviderRegistrationPolicy()" + if is_arm + else None + ), "self._config.redirect_policy", "self._config.retry_policy", "self._config.authentication_policy", diff --git a/packages/http-client-python/tests/unit/test_add_to_description.py b/packages/http-client-python/tests/unit/test_add_to_description.py index 7ba4e11acd7..93d742d189f 100644 --- a/packages/http-client-python/tests/unit/test_add_to_description.py +++ b/packages/http-client-python/tests/unit/test_add_to_description.py @@ -5,6 +5,7 @@ # -------------------------------------------------------------------------- """Tests for add_to_description code-block handling.""" from pygen.codegen.models.utils import add_to_description +from pygen.preprocess import update_description def test_add_to_description_empty() -> None: @@ -15,34 +16,109 @@ def test_add_to_description_plain() -> None: assert add_to_description("The tools.", "Required.") == "The tools. Required." -def test_add_to_description_inserts_before_code_block() -> None: +def test_add_to_description_appends_after_code_block() -> None: description = "The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]" result = add_to_description(description, "Required.") + # The annotation lands as its own paragraph after the block, not inline with the + # block's contents and not jammed onto the lead-in sentence before the block. assert result == ( - "The tools to use. Required.\n\n.. code-block:: json\n\n [\n 1\n ]" + "The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]\n\nRequired." ) - # The annotation must not be appended after the closing of the code block. - assert not result.rstrip().endswith("Required.") + # The block content must not be followed inline by the annotation. + assert "]. Required." not in result + assert "]\n\nRequired." in result -def test_add_to_description_chained_annotations_stay_before_code_block() -> None: +def test_add_to_description_chained_annotations_after_code_block() -> None: # Mirrors parameter.py, where add_to_description is called repeatedly on the - # same description (known values, Required., default value, ...). + # same description (known values, Required., default value, ...). The first call + # after a trailing code block opens a new paragraph; subsequent annotations group + # inline onto that paragraph. description = "The tools to use.\n\n.. code-block:: json\n\n [1]" description = add_to_description(description, "Known values are X and None.") description = add_to_description(description, "Required.") description = add_to_description(description, "Default value is None.") assert description == ( - "The tools to use. Known values are X and None. Required. Default value is None." - "\n\n.. code-block:: json\n\n [1]" + "The tools to use.\n\n.. code-block:: json\n\n [1]" + "\n\nKnown values are X and None. Required. Default value is None." ) -def test_add_to_description_multiple_code_blocks_inserts_before_first() -> None: +def test_add_to_description_multiple_code_blocks_appends_after_last() -> None: description = ( "Prose.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" ) result = add_to_description(description, "Required.") assert result == ( - "Prose. Required.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" + "Prose.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]\n\nRequired." ) + + +def test_add_to_description_code_block_followed_by_prose_appends_at_end() -> None: + # When prose follows the code block, the block is not the trailing content, so the + # annotation is appended inline at the very end as usual. + description = "Intro.\n\n.. code-block:: json\n\n [1]\n\nMore prose." + result = add_to_description(description, "Required.") + assert result == ( + "Intro.\n\n.. code-block:: json\n\n [1]\n\nMore prose. Required." + ) + + +def test_multiple_required_params_in_one_docstring_are_independent() -> None: + # A single method/model docstring is assembled from several params/properties, + # each built from its OWN description (see builder_serializer.param_description and + # the model templates). This verifies that a code-block param and a plain required + # param placed in the same docstring do not interfere: each "Required." is anchored + # to its own description, and the code-block param ends cleanly with the block. + tools_desc = add_to_description( + "A list of tool definitions.\n\n.. code-block:: json\n\n [1]", "Required." + ) + mode_desc = add_to_description("Constrains the tools available.", "Required.") + + docstring_lines = [ + f":ivar tools: {tools_desc}", + ":vartype tools: list[dict[str, any]]", + f":ivar mode: {mode_desc}", + ":vartype mode: str", + ] + docstring = "\n".join(docstring_lines) + + # The code-block param keeps "Required." as its own paragraph after the block. + assert ( + ":ivar tools: A list of tool definitions.\n\n.. code-block:: json\n\n [1]\n\nRequired." + in docstring + ) + # The plain required param is unaffected and still gets its trailing "Required.". + assert ":ivar mode: Constrains the tools available. Required." in docstring + # No "Required." dangles inline right after a code block's contents. + assert "[1]. Required." not in docstring + + +def test_update_description_no_period_inside_trailing_code_block() -> None: + # preprocess.update_description normally appends a trailing "." so descriptions end + # in a sentence. When the description ends with a code block, that "." would land on + # the block's last content line (e.g. "].") and break Sphinx, so it must be skipped. + description = "The tools.\n\n.. code-block:: json\n\n [\n 1\n ]" + assert update_description(description) == description + assert "]." not in update_description(description) + + +def test_update_description_full_pipeline_with_code_block() -> None: + # Mirrors the real flow: preprocess.update_description runs first, then + # property/parameter add "Required." via add_to_description. + raw = ( + "A list of tool definitions might look like:\n\n.. code-block:: json\n\n [1]" + ) + preprocessed = update_description(raw) + result = add_to_description(preprocessed, "Required.") + assert result == ( + "A list of tool definitions might look like:\n\n.. code-block:: json\n\n [1]\n\nRequired." + ) + # The block stays clean: no period and no annotation jammed onto its last line. + assert "]." not in result + assert "]\n\nRequired." in result + + +def test_update_description_still_adds_period_for_plain_text() -> None: + assert update_description("The tools") == "The tools." + assert update_description("The tools.") == "The tools." From 5a9cae472b0d1762967dd54a7f6df38e6fce72bc Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 17 Jun 2026 10:25:06 -0700 Subject: [PATCH 2/5] fix(http-client-python): harden trailing code-block detection against inline marker mentions Require the .. code-block:: directive to start its own line so an inline mention in prose is not mistaken for a trailing code block. Add tests covering multiple code blocks and the inline-mention case. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../generator/pygen/utils.py | 12 ++++-- .../tests/unit/test_add_to_description.py | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/packages/http-client-python/generator/pygen/utils.py b/packages/http-client-python/generator/pygen/utils.py index c96d8ca7582..9cbf49778ef 100644 --- a/packages/http-client-python/generator/pygen/utils.py +++ b/packages/http-client-python/generator/pygen/utils.py @@ -17,13 +17,19 @@ def description_ends_with_code_block(description: str) -> bool: """Return True when the description's trailing content is an RST code block. - The code block is the trailing content when, after the ``.. code-block::`` directive's - first line (its language argument), every remaining line is either blank or indented - (i.e. still part of the literal block), with no unindented prose paragraph following it. + The code block is the trailing content when the last ``.. code-block::`` directive + starts its own line and every line after the directive's first line (its language + argument) is either blank or indented (i.e. still part of the literal block), with no + unindented prose paragraph following it. """ marker_index = description.rfind(CODE_BLOCK_MARKER) if marker_index == -1: return False + # The marker must start its own line (an RST directive), not be an inline mention of + # ".. code-block::" inside a sentence. + line_start = description.rfind("\n", 0, marker_index) + 1 + if description[line_start:marker_index].strip(): + return False after_marker = description[marker_index + len(CODE_BLOCK_MARKER) :] for line in after_marker.splitlines()[1:]: if line.strip() and not line.startswith((" ", "\t")): diff --git a/packages/http-client-python/tests/unit/test_add_to_description.py b/packages/http-client-python/tests/unit/test_add_to_description.py index 93d742d189f..5ec2ff75546 100644 --- a/packages/http-client-python/tests/unit/test_add_to_description.py +++ b/packages/http-client-python/tests/unit/test_add_to_description.py @@ -122,3 +122,45 @@ def test_update_description_full_pipeline_with_code_block() -> None: def test_update_description_still_adds_period_for_plain_text() -> None: assert update_description("The tools") == "The tools." assert update_description("The tools.") == "The tools." + + +def test_add_to_description_two_blocks_back_to_back_appends_after_last() -> None: + description = ( + "Intro:\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" + ) + result = add_to_description(description, "Required.") + assert result == ( + "Intro:\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]\n\nRequired." + ) + + +def test_add_to_description_prose_between_blocks_last_trailing() -> None: + # Prose separates the two blocks, but the description still ends with a block, so the + # annotation is appended after the last block. + description = ( + "First:\n\n.. code-block:: json\n\n [1]\n\n" + "Then second:\n\n.. code-block:: json\n\n [2]" + ) + result = add_to_description(description, "Required.") + assert result.endswith(" [2]\n\nRequired.") + assert "]. Required." not in result + + +def test_add_to_description_prose_after_last_block_appends_inline() -> None: + # Multiple blocks, but prose follows the last one, so it is not the trailing content + # and the annotation is appended inline at the very end. + description = ( + "First:\n\n.. code-block:: json\n\n [1]\n\n" + "Second:\n\n.. code-block:: json\n\n [2]\n\nFinal prose." + ) + result = add_to_description(description, "Required.") + assert result == description + " Required." + + +def test_inline_code_block_mention_is_not_treated_as_trailing_block() -> None: + # ".. code-block::" mentioned inline in a sentence is not a real directive, so the + # description does not "end" with a code block: the trailing period is still added and + # the annotation is appended inline. + description = "Use .. code-block:: json directives in your text" + assert update_description(description) == description + "." + assert add_to_description(description, "Required.") == description + " Required." From 3d405d98db9e208f85de7249c10d67bcc0f20f2a Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 17 Jun 2026 10:28:56 -0700 Subject: [PATCH 3/5] refactor(http-client-python): streamline trailing code-block detection Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../generator/pygen/codegen/models/utils.py | 10 +++---- .../generator/pygen/utils.py | 30 ++++++++----------- 2 files changed, 17 insertions(+), 23 deletions(-) diff --git a/packages/http-client-python/generator/pygen/codegen/models/utils.py b/packages/http-client-python/generator/pygen/codegen/models/utils.py index 9f2c30e7638..b694a6206b5 100644 --- a/packages/http-client-python/generator/pygen/codegen/models/utils.py +++ b/packages/http-client-python/generator/pygen/codegen/models/utils.py @@ -16,12 +16,10 @@ def add_to_description(description: str, entry: str) -> str: if not description: return entry - # When the description ends with a code block, append the entry (e.g. "Required.") as a - # new paragraph after the block. Appending it inline (e.g. "]. Required.") leaves it - # inside the rendered literal block and breaks Sphinx rendering. - if description_ends_with_code_block(description): - return f"{description.rstrip()}\n\n{entry}" - return f"{description} {entry}" + # Put the entry (e.g. "Required.") on its own paragraph after a trailing code block; + # appending inline (e.g. "]. Required.") would land it inside the block and break Sphinx. + separator = "\n\n" if description_ends_with_code_block(description) else " " + return f"{description.rstrip()}{separator}{entry}" def add_to_pylint_disable(curr_str: str, entry: str) -> str: diff --git a/packages/http-client-python/generator/pygen/utils.py b/packages/http-client-python/generator/pygen/utils.py index 9cbf49778ef..fc198e148b1 100644 --- a/packages/http-client-python/generator/pygen/utils.py +++ b/packages/http-client-python/generator/pygen/utils.py @@ -15,26 +15,22 @@ def description_ends_with_code_block(description: str) -> bool: - """Return True when the description's trailing content is an RST code block. + """Return True when the description's trailing content is an RST ``.. code-block::``. - The code block is the trailing content when the last ``.. code-block::`` directive - starts its own line and every line after the directive's first line (its language - argument) is either blank or indented (i.e. still part of the literal block), with no - unindented prose paragraph following it. + True when the last ``.. code-block::`` directive (starting its own line, so inline + mentions are ignored) is followed only by blank or indented lines, i.e. the literal + block runs to the end of the description. """ - marker_index = description.rfind(CODE_BLOCK_MARKER) - if marker_index == -1: + lines = description.rstrip().splitlines() + directives = [ + i for i, line in enumerate(lines) if line.lstrip().startswith(CODE_BLOCK_MARKER) + ] + if not directives: return False - # The marker must start its own line (an RST directive), not be an inline mention of - # ".. code-block::" inside a sentence. - line_start = description.rfind("\n", 0, marker_index) + 1 - if description[line_start:marker_index].strip(): - return False - after_marker = description[marker_index + len(CODE_BLOCK_MARKER) :] - for line in after_marker.splitlines()[1:]: - if line.strip() and not line.startswith((" ", "\t")): - return False - return True + return all( + not line.strip() or line.startswith((" ", "\t")) + for line in lines[directives[-1] + 1 :] + ) def update_enum_value( From 2fece3bba6b8c15fdc681d93feae3243af1a5fe6 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 18 Jun 2026 10:46:32 -0700 Subject: [PATCH 4/5] fix: prepend Required. before code-block descriptions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...quired-trailing-period-2026-6-17-10-5-0.md | 2 +- .../generator/pygen/codegen/models/utils.py | 12 ++- .../tests/unit/test_add_to_description.py | 84 +++++-------------- 3 files changed, 32 insertions(+), 66 deletions(-) diff --git a/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md b/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md index 65bcbe70509..02f34f22471 100644 --- a/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md +++ b/.chronus/changes/fix-sphinx-required-trailing-period-2026-6-17-10-5-0.md @@ -4,4 +4,4 @@ packages: - "@typespec/http-client-python" --- -Place docstring annotations such as `Required.` on their own paragraph after a trailing RST code block and stop appending a sentence period inside the block. Previously the period landed on the code block's last line (e.g. `].`) and `Required.` was jammed onto the lead-in sentence, both of which broke Sphinx rendering. +Place docstring annotations such as `Required.` in front of the description when it ends with an RST code block, and stop appending a sentence period inside the block. Previously the period landed on the code block's last line (e.g. `].`) and `Required.` was appended after the block (`]. Required.`), both of which broke Sphinx rendering. diff --git a/packages/http-client-python/generator/pygen/codegen/models/utils.py b/packages/http-client-python/generator/pygen/codegen/models/utils.py index b694a6206b5..3e39f47099c 100644 --- a/packages/http-client-python/generator/pygen/codegen/models/utils.py +++ b/packages/http-client-python/generator/pygen/codegen/models/utils.py @@ -16,10 +16,14 @@ def add_to_description(description: str, entry: str) -> str: if not description: return entry - # Put the entry (e.g. "Required.") on its own paragraph after a trailing code block; - # appending inline (e.g. "]. Required.") would land it inside the block and break Sphinx. - separator = "\n\n" if description_ends_with_code_block(description) else " " - return f"{description.rstrip()}{separator}{entry}" + # When the description ends with a code block, prepend the entry (e.g. "Required.") so + # it appears before the prose instead of after the block. Appending inline (e.g. + # "]. Required.") would land it inside the rendered literal block and break Sphinx, and a + # trailing paragraph reads awkwardly. The code block stays at the very end where it renders + # cleanly. (Code-block descriptions only ever carry a single annotation in practice.) + if description_ends_with_code_block(description): + return f"{entry} {description.lstrip()}" + return f"{description} {entry}" def add_to_pylint_disable(curr_str: str, entry: str) -> str: diff --git a/packages/http-client-python/tests/unit/test_add_to_description.py b/packages/http-client-python/tests/unit/test_add_to_description.py index 5ec2ff75546..b785b7d2c66 100644 --- a/packages/http-client-python/tests/unit/test_add_to_description.py +++ b/packages/http-client-python/tests/unit/test_add_to_description.py @@ -16,41 +16,25 @@ def test_add_to_description_plain() -> None: assert add_to_description("The tools.", "Required.") == "The tools. Required." -def test_add_to_description_appends_after_code_block() -> None: +def test_add_to_description_prepends_before_code_block_description() -> None: description = "The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]" result = add_to_description(description, "Required.") - # The annotation lands as its own paragraph after the block, not inline with the - # block's contents and not jammed onto the lead-in sentence before the block. + # The annotation goes in front of the description so the code block stays at the very + # end where it renders cleanly, instead of inline after the block ("]. Required."). assert result == ( - "The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]\n\nRequired." + "Required. The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]" ) - # The block content must not be followed inline by the annotation. + assert result.startswith("Required. ") assert "]. Required." not in result - assert "]\n\nRequired." in result - - -def test_add_to_description_chained_annotations_after_code_block() -> None: - # Mirrors parameter.py, where add_to_description is called repeatedly on the - # same description (known values, Required., default value, ...). The first call - # after a trailing code block opens a new paragraph; subsequent annotations group - # inline onto that paragraph. - description = "The tools to use.\n\n.. code-block:: json\n\n [1]" - description = add_to_description(description, "Known values are X and None.") - description = add_to_description(description, "Required.") - description = add_to_description(description, "Default value is None.") - assert description == ( - "The tools to use.\n\n.. code-block:: json\n\n [1]" - "\n\nKnown values are X and None. Required. Default value is None." - ) -def test_add_to_description_multiple_code_blocks_appends_after_last() -> None: +def test_add_to_description_multiple_code_blocks_prepends() -> None: description = ( "Prose.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" ) result = add_to_description(description, "Required.") assert result == ( - "Prose.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]\n\nRequired." + "Required. Prose.\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" ) @@ -64,12 +48,23 @@ def test_add_to_description_code_block_followed_by_prose_appends_at_end() -> Non ) +def test_add_to_description_prose_after_last_block_appends_inline() -> None: + # Multiple blocks, but prose follows the last one, so it is not the trailing content + # and the annotation is appended inline at the very end. + description = ( + "First:\n\n.. code-block:: json\n\n [1]\n\n" + "Second:\n\n.. code-block:: json\n\n [2]\n\nFinal prose." + ) + result = add_to_description(description, "Required.") + assert result == description + " Required." + + def test_multiple_required_params_in_one_docstring_are_independent() -> None: # A single method/model docstring is assembled from several params/properties, # each built from its OWN description (see builder_serializer.param_description and # the model templates). This verifies that a code-block param and a plain required # param placed in the same docstring do not interfere: each "Required." is anchored - # to its own description, and the code-block param ends cleanly with the block. + # to its own description, and the code-block param keeps the block at its end. tools_desc = add_to_description( "A list of tool definitions.\n\n.. code-block:: json\n\n [1]", "Required." ) @@ -83,9 +78,9 @@ def test_multiple_required_params_in_one_docstring_are_independent() -> None: ] docstring = "\n".join(docstring_lines) - # The code-block param keeps "Required." as its own paragraph after the block. + # The code-block param gets "Required." in front, before the prose and block. assert ( - ":ivar tools: A list of tool definitions.\n\n.. code-block:: json\n\n [1]\n\nRequired." + ":ivar tools: Required. A list of tool definitions.\n\n.. code-block:: json\n\n [1]" in docstring ) # The plain required param is unaffected and still gets its trailing "Required.". @@ -112,11 +107,11 @@ def test_update_description_full_pipeline_with_code_block() -> None: preprocessed = update_description(raw) result = add_to_description(preprocessed, "Required.") assert result == ( - "A list of tool definitions might look like:\n\n.. code-block:: json\n\n [1]\n\nRequired." + "Required. A list of tool definitions might look like:\n\n.. code-block:: json\n\n [1]" ) # The block stays clean: no period and no annotation jammed onto its last line. assert "]." not in result - assert "]\n\nRequired." in result + assert result.startswith("Required. ") def test_update_description_still_adds_period_for_plain_text() -> None: @@ -124,39 +119,6 @@ def test_update_description_still_adds_period_for_plain_text() -> None: assert update_description("The tools.") == "The tools." -def test_add_to_description_two_blocks_back_to_back_appends_after_last() -> None: - description = ( - "Intro:\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]" - ) - result = add_to_description(description, "Required.") - assert result == ( - "Intro:\n\n.. code-block:: json\n\n [1]\n\n.. code-block:: json\n\n [2]\n\nRequired." - ) - - -def test_add_to_description_prose_between_blocks_last_trailing() -> None: - # Prose separates the two blocks, but the description still ends with a block, so the - # annotation is appended after the last block. - description = ( - "First:\n\n.. code-block:: json\n\n [1]\n\n" - "Then second:\n\n.. code-block:: json\n\n [2]" - ) - result = add_to_description(description, "Required.") - assert result.endswith(" [2]\n\nRequired.") - assert "]. Required." not in result - - -def test_add_to_description_prose_after_last_block_appends_inline() -> None: - # Multiple blocks, but prose follows the last one, so it is not the trailing content - # and the annotation is appended inline at the very end. - description = ( - "First:\n\n.. code-block:: json\n\n [1]\n\n" - "Second:\n\n.. code-block:: json\n\n [2]\n\nFinal prose." - ) - result = add_to_description(description, "Required.") - assert result == description + " Required." - - def test_inline_code_block_mention_is_not_treated_as_trailing_block() -> None: # ".. code-block::" mentioned inline in a sentence is not a real directive, so the # description does not "end" with a code block: the trailing period is still added and From d11cbae99bd6e0fdec11eb87bd30a44a18058677 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 18 Jun 2026 12:40:44 -0700 Subject: [PATCH 5/5] fix: avoid leading space when prepending empty entry to code-block description Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../generator/pygen/codegen/models/utils.py | 2 ++ .../tests/unit/test_add_to_description.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/packages/http-client-python/generator/pygen/codegen/models/utils.py b/packages/http-client-python/generator/pygen/codegen/models/utils.py index 3e39f47099c..cc980eff4d2 100644 --- a/packages/http-client-python/generator/pygen/codegen/models/utils.py +++ b/packages/http-client-python/generator/pygen/codegen/models/utils.py @@ -16,6 +16,8 @@ def add_to_description(description: str, entry: str) -> str: if not description: return entry + if not entry: + return description # When the description ends with a code block, prepend the entry (e.g. "Required.") so # it appears before the prose instead of after the block. Appending inline (e.g. # "]. Required.") would land it inside the rendered literal block and break Sphinx, and a diff --git a/packages/http-client-python/tests/unit/test_add_to_description.py b/packages/http-client-python/tests/unit/test_add_to_description.py index b785b7d2c66..70e2408badf 100644 --- a/packages/http-client-python/tests/unit/test_add_to_description.py +++ b/packages/http-client-python/tests/unit/test_add_to_description.py @@ -12,6 +12,13 @@ def test_add_to_description_empty() -> None: assert add_to_description("", "Required.") == "Required." +def test_add_to_description_empty_entry_returns_description_unchanged() -> None: + # An empty entry (e.g. an empty type_description) must not introduce a leading/trailing space. + description = "The tools to use.\n\n.. code-block:: json\n\n [\n 1\n ]" + assert add_to_description(description, "") == description + assert add_to_description("The tools.", "") == "The tools." + + def test_add_to_description_plain() -> None: assert add_to_description("The tools.", "Required.") == "The tools. Required."