From 634068829dab69013f69d63e9f5499eb06d34653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Forr=C3=B3?= Date: Wed, 8 Apr 2026 15:58:55 +0200 Subject: [PATCH] Access sections by both ID and name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Nikola Forró Assisted-by: Claude Opus 4.6 via Claude Code Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- specfile/sections.py | 13 ++++++++++--- tests/unit/test_sections.py | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/specfile/sections.py b/specfile/sections.py index 37d0ff88..312c4793 100644 --- a/specfile/sections.py +++ b/specfile/sections.py @@ -4,7 +4,7 @@ import collections import copy import re -from typing import TYPE_CHECKING, List, Optional, Union, cast, overload +from typing import TYPE_CHECKING, List, Optional, Union, overload from specfile.constants import ( SCRIPT_SECTIONS, @@ -173,7 +173,13 @@ def __contains__(self, id: object) -> bool: data = super().__getattribute__("data") except AttributeError: return False - return any(s.normalized_id == cast(str, id).lower() for s in data) + if isinstance(id, str): + id_lower = id.lower() + return any( + s.normalized_id == id_lower or s.normalized_name == id_lower + for s in data + ) + return id in data def __getattr__(self, id: str) -> Section: if id not in self: @@ -209,8 +215,9 @@ def get(self, id: str) -> Section: return self.data[self.find(id)] def find(self, id: str) -> int: + id_lower = id.lower() for i, section in enumerate(self.data): - if section.normalized_id == id.lower(): + if section.normalized_id == id_lower or section.normalized_name == id_lower: return i raise ValueError diff --git a/tests/unit/test_sections.py b/tests/unit/test_sections.py index 87bc8550..84440935 100644 --- a/tests/unit/test_sections.py +++ b/tests/unit/test_sections.py @@ -39,6 +39,23 @@ def test_get(): sections.get("package foo") +def test_contains_and_getattr(): + sections = Sections( + [ + Section("package"), + Section("package", Options([Token(TokenType.DEFAULT, "baz")]), " "), + Section("install", delimiter=" "), + ] + ) + assert "package" in sections + assert "install" in sections + assert "install " in sections + assert sections.package == sections[0] + assert getattr(sections, "package baz") == sections[1] + assert sections.install == sections[-1] + assert getattr(sections, "install ") == sections[-1] + + @pytest.mark.parametrize( "id, existing, name, options, content", [