Skip to content

Commit 6a5efba

Browse files
Access sections by both ID and name (#531)
Access sections by both ID and name Fixes #417. Reviewed-by: gemini-code-assist[bot] Reviewed-by: Maja Massarini
2 parents 1985392 + 6340688 commit 6a5efba

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

specfile/sections.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import collections
55
import copy
66
import re
7-
from typing import TYPE_CHECKING, List, Optional, Union, cast, overload
7+
from typing import TYPE_CHECKING, List, Optional, Union, overload
88

99
from specfile.constants import (
1010
SCRIPT_SECTIONS,
@@ -173,7 +173,13 @@ def __contains__(self, id: object) -> bool:
173173
data = super().__getattribute__("data")
174174
except AttributeError:
175175
return False
176-
return any(s.normalized_id == cast(str, id).lower() for s in data)
176+
if isinstance(id, str):
177+
id_lower = id.lower()
178+
return any(
179+
s.normalized_id == id_lower or s.normalized_name == id_lower
180+
for s in data
181+
)
182+
return id in data
177183

178184
def __getattr__(self, id: str) -> Section:
179185
if id not in self:
@@ -209,8 +215,9 @@ def get(self, id: str) -> Section:
209215
return self.data[self.find(id)]
210216

211217
def find(self, id: str) -> int:
218+
id_lower = id.lower()
212219
for i, section in enumerate(self.data):
213-
if section.normalized_id == id.lower():
220+
if section.normalized_id == id_lower or section.normalized_name == id_lower:
214221
return i
215222
raise ValueError
216223

tests/unit/test_sections.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,23 @@ def test_get():
3939
sections.get("package foo")
4040

4141

42+
def test_contains_and_getattr():
43+
sections = Sections(
44+
[
45+
Section("package"),
46+
Section("package", Options([Token(TokenType.DEFAULT, "baz")]), " "),
47+
Section("install", delimiter=" "),
48+
]
49+
)
50+
assert "package" in sections
51+
assert "install" in sections
52+
assert "install " in sections
53+
assert sections.package == sections[0]
54+
assert getattr(sections, "package baz") == sections[1]
55+
assert sections.install == sections[-1]
56+
assert getattr(sections, "install ") == sections[-1]
57+
58+
4259
@pytest.mark.parametrize(
4360
"id, existing, name, options, content",
4461
[

0 commit comments

Comments
 (0)