resforge 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
resforge/__init__.py ADDED
File without changes
@@ -0,0 +1,15 @@
1
+ from .dimension import Dimension, dp, inch, mm, pt, px, sp
2
+ from .plural import PluralValues
3
+ from .values import ValuesWriter
4
+
5
+ __all__ = [
6
+ "Dimension",
7
+ "dp",
8
+ "inch",
9
+ "mm",
10
+ "pt",
11
+ "px",
12
+ "sp",
13
+ "PluralValues",
14
+ "ValuesWriter",
15
+ ]
@@ -0,0 +1,61 @@
1
+ from typing import Any, Callable, Literal
2
+
3
+ DimensionUnit = Literal["dp", "sp", "px", "pt", "mm", "in"]
4
+
5
+
6
+ class Dimension:
7
+ """Represents an Android dimension value (e.g., '16dp', '12sp')."""
8
+
9
+ value: int | float
10
+ unit: DimensionUnit
11
+
12
+ def __init__(self, value: int | float, unit: DimensionUnit):
13
+ """
14
+ Args:
15
+ value: The numeric dimension value. Negative values are permitted
16
+ to support negative margins/offsets, though they are
17
+ typically ignored by padding and size attributes.
18
+ unit: The unit of measure (dp, sp, px, pt, mm, in).
19
+ """
20
+ self.value = value
21
+ self.unit = unit
22
+
23
+ def __str__(self) -> str:
24
+ return f"{self.value:g}{self.unit}"
25
+
26
+ def __repr__(self) -> str:
27
+ return f"Dimension(value={self.value!r}, unit={self.unit!r})"
28
+
29
+ def __eq__(self, other: object) -> bool:
30
+ if not isinstance(other, Dimension):
31
+ return NotImplemented
32
+ return self.value == other.value and self.unit == other.unit
33
+
34
+ def __mul__(self, other: Any) -> "Dimension":
35
+ if not isinstance(other, (int, float)):
36
+ return NotImplemented
37
+ return Dimension(self.value * other, self.unit)
38
+
39
+ def __rmul__(self, other: Any) -> "Dimension":
40
+ return self.__mul__(other)
41
+
42
+
43
+ def _make_unit_func(
44
+ unit: DimensionUnit, doc: str
45
+ ) -> Callable[[int | float], Dimension]:
46
+ def f(value: int | float) -> Dimension:
47
+ return Dimension(value, unit)
48
+
49
+ f.__name__ = unit
50
+ f.__doc__ = doc
51
+ return f
52
+
53
+
54
+ dp = _make_unit_func("dp", "Create a dimension in density-independent pixels (dp).")
55
+ sp = _make_unit_func(
56
+ "sp", "Create a dimension in scale-independent pixels (sp). Use for text sizes."
57
+ )
58
+ px = _make_unit_func("px", "Create a dimension in pixels (px).")
59
+ pt = _make_unit_func("pt", "Create a dimension in points (pt).")
60
+ mm = _make_unit_func("mm", "Create a dimension in millimeters (mm).")
61
+ inch = _make_unit_func("in", "Create a dimension in inches (in).")
@@ -0,0 +1,22 @@
1
+ from typing import NotRequired, TypedDict
2
+
3
+
4
+ class PluralValues(TypedDict):
5
+ """
6
+ Represents the quantity-based strings for an Android plurals resource.
7
+
8
+ Attributes:
9
+ zero: String for quantity 0 (optional).
10
+ one: String for quantity 1 (optional).
11
+ two: String for quantity 2 (optional).
12
+ few: String for quantity 'few' (optional).
13
+ many: String for quantity 'many' (optional).
14
+ other: The default fallback string (required).
15
+ """
16
+
17
+ zero: NotRequired[str]
18
+ one: NotRequired[str]
19
+ two: NotRequired[str]
20
+ few: NotRequired[str]
21
+ many: NotRequired[str]
22
+ other: str
@@ -0,0 +1,239 @@
1
+ import re
2
+ import xml.etree.ElementTree as ET
3
+ from pathlib import Path
4
+ from typing import Pattern, Self
5
+
6
+ from .dimension import Dimension
7
+ from .plural import PluralValues
8
+
9
+ _NAME_PATTERN = re.compile(r"^[a-z_][a-z0-9_]*$")
10
+ _STYLE_NAME_PATTERN = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_\.]*$")
11
+ _COLOR_PATTERN = re.compile(
12
+ r"^#([A-Fa-f0-9]{3}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$"
13
+ )
14
+
15
+
16
+ class ValuesWriter:
17
+ """
18
+ A fluent context manager for generating Android XML resource files.
19
+
20
+ Provides a type-safe interface for creating strings, dimensions, colors,
21
+ and arrays. Validates resource names and color formats at runtime.
22
+
23
+ Example:
24
+ >>> with ValuesWriter("res/values/my_values.xml") as res:
25
+ ... res.dimension(padding_small=dp(8)).color(primary=0xFF0000)
26
+ """
27
+
28
+ def __init__(self, path: str | Path):
29
+ """
30
+ Args:
31
+ path: The filesystem path where the XML will be saved.
32
+ """
33
+ self._path = Path(path)
34
+ self._root: ET.Element | None = None
35
+ self._seen_names: dict[str, set[str]] = {}
36
+
37
+ def __enter__(self) -> Self:
38
+ self._root = ET.Element("resources")
39
+ self._seen_names = {}
40
+ return self
41
+
42
+ def __exit__(self, exc_type, *_) -> None:
43
+ try:
44
+ if exc_type is None and self._root is not None:
45
+ self._path.parent.mkdir(parents=True, exist_ok=True)
46
+
47
+ ET.indent(self._root, space=" ", level=0)
48
+
49
+ tree = ET.ElementTree(self._root)
50
+ tree.write(
51
+ self._path,
52
+ encoding="utf-8",
53
+ xml_declaration=True,
54
+ short_empty_elements=True,
55
+ )
56
+ finally:
57
+ self._root = None
58
+ self._seen_names.clear()
59
+
60
+ def _prepare_text(self, text: str) -> str:
61
+ text = text.replace("'", r"\'")
62
+ text = text.replace('"', r"\"")
63
+ text = text.replace("\n", r"\n")
64
+ if text.startswith(("@", "?")):
65
+ text = "\\" + text
66
+ return text
67
+
68
+ def _append(
69
+ self,
70
+ tag: str,
71
+ name: str,
72
+ text: str | None = None,
73
+ attrs: dict[str, str] | None = None,
74
+ name_validation_pattern: Pattern[str] = _NAME_PATTERN,
75
+ ) -> ET.Element:
76
+ if self._root is None:
77
+ raise RuntimeError("ValuesWriter must be used as a context manager.")
78
+
79
+ if not name_validation_pattern.match(name):
80
+ raise ValueError(f"Invalid resource name '{name}'.")
81
+
82
+ seen_for_tag = self._seen_names.setdefault(tag, set())
83
+ if name in seen_for_tag:
84
+ raise ValueError(
85
+ f"Duplicate resource name '{name}' for tag <{tag}>. "
86
+ f"The name '{name}' has already been defined with this type."
87
+ )
88
+ seen_for_tag.add(name)
89
+
90
+ all_attrs = {"name": name}
91
+ if attrs:
92
+ all_attrs.update(attrs)
93
+ elem = ET.SubElement(self._root, tag, attrib=all_attrs)
94
+ if text is not None:
95
+ elem.text = text
96
+ return elem
97
+
98
+ def comment(self, text: str) -> Self:
99
+ """Appends an XML comment to group or annotate resources."""
100
+ if self._root is None:
101
+ raise RuntimeError("ValuesWriter must be used as a context manager.")
102
+ sanitized = text.replace("--", "- -")
103
+ self._root.append(ET.Comment(f" {sanitized} "))
104
+ return self
105
+
106
+ def string(self, **values: str) -> Self:
107
+ """
108
+ Appends one or more <string> resources.
109
+ """
110
+ for name, val in values.items():
111
+ self._append("string", name, self._prepare_text(val))
112
+ return self
113
+
114
+ def boolean(self, **values: bool) -> Self:
115
+ """
116
+ Appends one or more <bool> resources.
117
+ Converts Python booleans to lowercase 'true'/'false'.
118
+ """
119
+ for name, val in values.items():
120
+ self._append("bool", name, str(val).lower())
121
+ return self
122
+
123
+ def color(self, **values: str | int) -> Self:
124
+ """
125
+ Appends one or more <color> resources.
126
+
127
+ Supports hex integers (0xAARRGGBB) and
128
+ standard Android hex strings (#RGB, #ARGB, #RRGGBB, #AARRGGBB).
129
+
130
+ Raises:
131
+ ValueError: If the integer range is invalid or string format is incorrect.
132
+ """
133
+ for name, val in values.items():
134
+ if isinstance(val, int):
135
+ if 0 <= val <= 0xFFFFFF:
136
+ color_str = f"#FF{val:06X}"
137
+ elif 0xFFFFFF < val <= 0xFFFFFFFF:
138
+ color_str = f"#{val:08X}"
139
+ else:
140
+ raise ValueError(
141
+ f"Color '{name}' has invalid integer value: {val:#x}"
142
+ )
143
+
144
+ elif isinstance(val, str):
145
+ if not _COLOR_PATTERN.match(val):
146
+ raise ValueError(
147
+ f"Color '{name}' has invalid format: '{val}'. "
148
+ "Expected #RGB, #ARGB, #RRGGBB, or #AARRGGBB."
149
+ )
150
+ color_str = val
151
+
152
+ else:
153
+ raise TypeError(
154
+ f"Color '{name}' must be str or int, got {type(val).__name__}"
155
+ )
156
+
157
+ self._append("color", name, color_str.upper())
158
+ return self
159
+
160
+ def dimension(self, **values: Dimension) -> Self:
161
+ """
162
+ Appends one or more <dimen> resources using Dimension objects.
163
+ """
164
+ for name, val in values.items():
165
+ self._append("dimen", name, str(val))
166
+ return self
167
+
168
+ def res_id(self, *values: str) -> Self:
169
+ """
170
+ Appends one or more <item type="id"> resources.
171
+ Typically used in ids.xml to pre-declare resource IDs.
172
+ """
173
+ for name in values:
174
+ self._append("item", name, attrs={"type": "id"})
175
+ return self
176
+
177
+ def integer(self, **values: int) -> Self:
178
+ """Appends one or more <integer> resources."""
179
+ for name, val in values.items():
180
+ self._append("integer", name, str(val))
181
+ return self
182
+
183
+ def _array(
184
+ self, tag: str, name: str, values: list[int] | list[str], escape: bool = False
185
+ ) -> Self:
186
+ parent = self._append(tag, name)
187
+ for val in values:
188
+ item = ET.SubElement(parent, "item")
189
+ sanitized = self._prepare_text(str(val)) if escape else str(val)
190
+ item.text = str(val).lower() if isinstance(val, bool) else sanitized
191
+ return self
192
+
193
+ def typed_array(self, name: str, values: list[str]) -> Self:
194
+ """
195
+ Appends a generic <array> (Typed Array).
196
+ Used for arrays of references (e.g., drawables or colors).
197
+ """
198
+ return self._array("array", name, values)
199
+
200
+ def integer_array(self, name: str, values: list[int]) -> Self:
201
+ """Appends an <integer-array> resource."""
202
+ return self._array("integer-array", name, values)
203
+
204
+ def string_array(self, name: str, values: list[str]) -> Self:
205
+ """Appends a <string-array> resource."""
206
+ return self._array("string-array", name, values)
207
+
208
+ def plurals(self, **values: PluralValues) -> Self:
209
+ """
210
+ Appends a <plurals> resource with quantity-specific strings.
211
+
212
+ Args:
213
+ name: The resource name.
214
+ values: A dictionary of quantities (zero, one, etc.) to strings.
215
+ """
216
+ for name, val in values.items():
217
+ parent = self._append("plurals", name)
218
+ for quantity, text in val.items():
219
+ item = ET.SubElement(parent, "item", attrib={"quantity": quantity})
220
+ item.text = self._prepare_text(str(text))
221
+ return self
222
+
223
+ def style(self, name: str, parent: str | None = None, **items: str) -> Self:
224
+ """
225
+ Appends a <style> resource.
226
+
227
+ Example:
228
+ writer.style("AppTheme", parent="Theme.Material", colorPrimary="@color/blue")
229
+ """
230
+ attrs = {}
231
+ if parent:
232
+ attrs["parent"] = parent
233
+
234
+ style_elem = self._append(
235
+ "style", name, attrs=attrs, name_validation_pattern=_STYLE_NAME_PATTERN
236
+ )
237
+ for attr_name, val in items.items():
238
+ ET.SubElement(style_elem, "item", attrib={"name": attr_name}).text = val
239
+ return self
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: resforge
3
+ Version: 0.1.0
4
+ Summary: Fluent builder for Android resources
5
+ Project-URL: Homepage, https://kipila.dev
6
+ Project-URL: Repository, https://github.com/ok100/resforge
7
+ Author-email: Ondrej Kipila <ondrej@kipila.dev>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: android,asset,builder,ci,mobile,pipeline,resources,tooling
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.12
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == 'dev'
19
+ Description-Content-Type: text/markdown
20
+
21
+ # resforge
22
+
23
+ A fluent Python library for generating Android XML resource files.
24
+
25
+ ## Installation
26
+
27
+ ```bash
28
+ pip install resforge
29
+ ```
30
+
31
+ ## Android
32
+
33
+ ```python
34
+ from resforge.android import PluralValues, ValuesWriter, dp, sp
35
+
36
+ with ValuesWriter("res/values/resources.xml") as res:
37
+ res.comment("Strings")
38
+ res.string(
39
+ app_name="My App",
40
+ welcome_message="Welcome to My App!",
41
+ )
42
+
43
+ res.comment("Booleans")
44
+ res.boolean(
45
+ feature_enabled=True,
46
+ dark_mode=False,
47
+ )
48
+
49
+ res.comment("Colors")
50
+ res.color(
51
+ primary="#FF6200EE",
52
+ secondary="#FF03DAC5",
53
+ accent=0x6200EE,
54
+ )
55
+
56
+ res.comment("Dimensions")
57
+ res.dimension(
58
+ padding_small=dp(8),
59
+ padding_large=dp(24),
60
+ text_body=sp(16),
61
+ text_heading=sp(24),
62
+ )
63
+
64
+ res.comment("Integers")
65
+ res.integer(
66
+ max_retries=3,
67
+ timeout_seconds=30,
68
+ )
69
+
70
+ res.comment("Resource IDs")
71
+ res.res_id("btn_submit", "tv_title", "iv_logo")
72
+
73
+ res.comment("String arrays")
74
+ res.string_array("planets", ["Mercury", "Venus", "Earth", "Mars"])
75
+
76
+ res.comment("Integer arrays")
77
+ res.integer_array("fibonacci", [1, 1, 2, 3, 5, 8, 13])
78
+
79
+ res.comment("Typed arrays")
80
+ res.typed_array(
81
+ "icons", ["@drawable/home", "@drawable/settings", "@drawable/logout"]
82
+ )
83
+
84
+ res.comment("Plurals")
85
+ res.plurals(
86
+ item_count=PluralValues(one="%d item", other="%d items"),
87
+ file_count=PluralValues(one="%d file", other="%d files"),
88
+ )
89
+
90
+ res.comment("Styles")
91
+ res.style(
92
+ "AppTheme",
93
+ parent="Theme.MaterialComponents.DayNight",
94
+ colorPrimary="@color/primary",
95
+ colorSecondary="@color/secondary",
96
+ )
97
+ ```
98
+
99
+ ## iOS
100
+
101
+ Coming in v0.2.0.
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,9 @@
1
+ resforge/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ resforge/android/__init__.py,sha256=xh8272LaiOtlFFrii40QLJlzDFBlwOLTu9cHYfqmA_w,259
3
+ resforge/android/dimension.py,sha256=ES-EZTWUV8DJnMXBPs-PNKaT1A2TCqMKAp1XNV2Y5FU,2021
4
+ resforge/android/plural.py,sha256=npUGImwJkog1v3-GyDJ9dnM-2NzP2dCNbZhulStqDDs,632
5
+ resforge/android/values.py,sha256=Eertoq2bkPXwWuVUC2rC4cZ9e2ug2hYK1oHXQ9kHp6Q,8267
6
+ resforge-0.1.0.dist-info/METADATA,sha256=uywEDGSqxZ3gw5UuwoGzsvXzH9GaUWNezoLruLmE910,2488
7
+ resforge-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ resforge-0.1.0.dist-info/licenses/LICENSE,sha256=Vww-ranhESd4qdCVuImsBMy79L9mSNcGq9NOgujpJQI,1070
9
+ resforge-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ondrej Kipila
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.