resforge 0.1.0__tar.gz

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.
@@ -0,0 +1,29 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.12", "3.13", "3.14"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v5
18
+
19
+ - name: Set up Python ${{ matrix.python-version }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+
24
+ - name: Install dependencies
25
+ run: |
26
+ pip install -e ".[dev]"
27
+
28
+ - name: Run tests
29
+ run: pytest tests/ -v
@@ -0,0 +1,29 @@
1
+ name: Publish
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+
11
+ environment: pypi
12
+ permissions:
13
+ id-token: write
14
+
15
+ steps:
16
+ - uses: actions/checkout@v5
17
+
18
+ - name: Set up Python
19
+ uses: actions/setup-python@v5
20
+ with:
21
+ python-version: "3.12"
22
+
23
+ - name: Build
24
+ run: |
25
+ pip install build
26
+ python -m build
27
+
28
+ - name: Publish to PyPI
29
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,209 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+ pyrightconfig.json
resforge-0.1.0/LICENSE ADDED
@@ -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.
@@ -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,85 @@
1
+ # resforge
2
+
3
+ A fluent Python library for generating Android XML resource files.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install resforge
9
+ ```
10
+
11
+ ## Android
12
+
13
+ ```python
14
+ from resforge.android import PluralValues, ValuesWriter, dp, sp
15
+
16
+ with ValuesWriter("res/values/resources.xml") as res:
17
+ res.comment("Strings")
18
+ res.string(
19
+ app_name="My App",
20
+ welcome_message="Welcome to My App!",
21
+ )
22
+
23
+ res.comment("Booleans")
24
+ res.boolean(
25
+ feature_enabled=True,
26
+ dark_mode=False,
27
+ )
28
+
29
+ res.comment("Colors")
30
+ res.color(
31
+ primary="#FF6200EE",
32
+ secondary="#FF03DAC5",
33
+ accent=0x6200EE,
34
+ )
35
+
36
+ res.comment("Dimensions")
37
+ res.dimension(
38
+ padding_small=dp(8),
39
+ padding_large=dp(24),
40
+ text_body=sp(16),
41
+ text_heading=sp(24),
42
+ )
43
+
44
+ res.comment("Integers")
45
+ res.integer(
46
+ max_retries=3,
47
+ timeout_seconds=30,
48
+ )
49
+
50
+ res.comment("Resource IDs")
51
+ res.res_id("btn_submit", "tv_title", "iv_logo")
52
+
53
+ res.comment("String arrays")
54
+ res.string_array("planets", ["Mercury", "Venus", "Earth", "Mars"])
55
+
56
+ res.comment("Integer arrays")
57
+ res.integer_array("fibonacci", [1, 1, 2, 3, 5, 8, 13])
58
+
59
+ res.comment("Typed arrays")
60
+ res.typed_array(
61
+ "icons", ["@drawable/home", "@drawable/settings", "@drawable/logout"]
62
+ )
63
+
64
+ res.comment("Plurals")
65
+ res.plurals(
66
+ item_count=PluralValues(one="%d item", other="%d items"),
67
+ file_count=PluralValues(one="%d file", other="%d files"),
68
+ )
69
+
70
+ res.comment("Styles")
71
+ res.style(
72
+ "AppTheme",
73
+ parent="Theme.MaterialComponents.DayNight",
74
+ colorPrimary="@color/primary",
75
+ colorSecondary="@color/secondary",
76
+ )
77
+ ```
78
+
79
+ ## iOS
80
+
81
+ Coming in v0.2.0.
82
+
83
+ ## License
84
+
85
+ MIT
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "resforge"
7
+ version = "0.1.0"
8
+ description = "Fluent builder for Android resources"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Ondrej Kipila", email = "ondrej@kipila.dev" }]
13
+ keywords = [
14
+ "android",
15
+ "resources",
16
+ "mobile",
17
+ "tooling",
18
+ "asset",
19
+ "builder",
20
+ "pipeline",
21
+ "ci",
22
+ ]
23
+ classifiers = [
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
28
+ "License :: OSI Approved :: MIT License",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ dev = ["pytest"]
33
+
34
+ [project.urls]
35
+ Homepage = "https://kipila.dev"
36
+ Repository = "https://github.com/ok100/resforge"
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
File without changes
@@ -0,0 +1,275 @@
1
+ import xml.etree.ElementTree as ET
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from resforge.android import (PluralValues, ValuesWriter, dp, inch, mm, pt, px,
7
+ sp)
8
+
9
+
10
+ class TestDimension:
11
+ def test_str(self):
12
+ assert str(dp(8)) == "8dp"
13
+ assert str(sp(16)) == "16sp"
14
+
15
+ def test_str_strips_trailing_zeros(self):
16
+ assert str(dp(8.0)) == "8dp"
17
+ assert str(dp(8.5)) == "8.5dp"
18
+
19
+ def test_repr(self):
20
+ assert repr(dp(8)) == "Dimension(value=8, unit='dp')"
21
+
22
+ def test_mul(self):
23
+ assert dp(8) * 2 == dp(16)
24
+
25
+ def test_rmul(self):
26
+ assert 2 * dp(8) == dp(16)
27
+
28
+ def test_mul_float(self):
29
+ assert dp(8) * 1.5 == dp(12.0)
30
+
31
+ def test_mul_invalid(self):
32
+ assert dp(8).__mul__("x") is NotImplemented
33
+
34
+ def test_eq(self):
35
+ assert dp(8) == dp(8)
36
+ assert dp(8) != sp(8)
37
+ assert dp(8) != dp(16)
38
+
39
+ def test_eq_non_dimension(self):
40
+ assert dp(8) != "8dp"
41
+
42
+ def test_all_units(self):
43
+ assert str(dp(1)) == "1dp"
44
+ assert str(sp(1)) == "1sp"
45
+ assert str(px(1)) == "1px"
46
+ assert str(pt(1)) == "1pt"
47
+ assert str(mm(1)) == "1mm"
48
+ assert str(inch(1)) == "1in"
49
+
50
+
51
+ @pytest.fixture
52
+ def xml_path(tmp_path) -> Path:
53
+ return tmp_path / "res" / "values" / "test.xml"
54
+
55
+
56
+ def parse(path: Path) -> ET.Element:
57
+ return ET.parse(path).getroot()
58
+
59
+
60
+ class TestValuesWriterContextManager:
61
+ def test_creates_file(self, xml_path: Path):
62
+ with ValuesWriter(xml_path) as res:
63
+ res.string(foo="bar")
64
+ assert xml_path.exists()
65
+
66
+ def test_creates_parent_dirs(self, xml_path: Path):
67
+ with ValuesWriter(xml_path) as res:
68
+ res.string(foo="bar")
69
+ assert xml_path.parent.exists()
70
+
71
+ def test_no_write_on_exception(self, xml_path: Path):
72
+ with pytest.raises(ValueError):
73
+ with ValuesWriter(xml_path) as _:
74
+ raise ValueError("oops")
75
+ assert not xml_path.exists()
76
+
77
+ def test_runtime_error_outside_context(self, xml_path: Path):
78
+ res = ValuesWriter(xml_path)
79
+ with pytest.raises(RuntimeError):
80
+ res.string(foo="bar")
81
+
82
+
83
+ class TestString:
84
+ def test_single(self, xml_path: Path):
85
+ with ValuesWriter(xml_path) as res:
86
+ res.string(app_name="My App")
87
+ root = parse(xml_path)
88
+ elem = root.find("string[@name='app_name']")
89
+ assert elem is not None
90
+ assert elem.text == "My App"
91
+
92
+ def test_multiple(self, xml_path: Path):
93
+ with ValuesWriter(xml_path) as res:
94
+ res.string(foo="Foo", bar="Bar")
95
+ root = parse(xml_path)
96
+ foo = root.find("string[@name='foo']")
97
+ bar = root.find("string[@name='bar']")
98
+ assert foo is not None
99
+ assert bar is not None
100
+ assert foo.text == "Foo"
101
+ assert bar.text == "Bar"
102
+
103
+ def test_escapes_apostrophe(self, xml_path: Path):
104
+ with ValuesWriter(xml_path) as res:
105
+ res.string(msg="it's here")
106
+ root = parse(xml_path)
107
+ elem = root.find("string[@name='msg']")
108
+ assert elem is not None
109
+ assert "\\'" in elem.text # type: ignore[operator]
110
+
111
+ def test_escapes_at_sign(self, xml_path: Path):
112
+ with ValuesWriter(xml_path) as res:
113
+ res.string(msg="@hello")
114
+ root = parse(xml_path)
115
+ elem = root.find("string[@name='msg']")
116
+ assert elem is not None
117
+ assert elem.text is not None
118
+ assert elem.text.startswith("\\")
119
+
120
+ def test_duplicate_raises(self, xml_path: Path):
121
+ with pytest.raises(ValueError, match="Duplicate"):
122
+ with ValuesWriter(xml_path) as res:
123
+ res.string(foo="a")
124
+ res.string(foo="b")
125
+
126
+ def test_invalid_name_raises(self, xml_path: Path):
127
+ with pytest.raises(ValueError, match="Invalid"):
128
+ with ValuesWriter(xml_path) as res:
129
+ res.string(**{"Invalid Name": "val"})
130
+
131
+
132
+ class TestBoolean:
133
+ def test_true(self, xml_path: Path):
134
+ with ValuesWriter(xml_path) as res:
135
+ res.boolean(flag=True)
136
+ elem = parse(xml_path).find("bool[@name='flag']")
137
+ assert elem is not None
138
+ assert elem.text == "true"
139
+
140
+ def test_false(self, xml_path: Path):
141
+ with ValuesWriter(xml_path) as res:
142
+ res.boolean(flag=False)
143
+ elem = parse(xml_path).find("bool[@name='flag']")
144
+ assert elem is not None
145
+ assert elem.text == "false"
146
+
147
+
148
+ class TestColor:
149
+ def test_hex_string(self, xml_path: Path):
150
+ with ValuesWriter(xml_path) as res:
151
+ res.color(primary="#FF6200EE")
152
+ elem = parse(xml_path).find("color[@name='primary']")
153
+ assert elem is not None
154
+ assert elem.text == "#FF6200EE"
155
+
156
+ def test_int_rgb(self, xml_path: Path):
157
+ with ValuesWriter(xml_path) as res:
158
+ res.color(primary=0x6200EE)
159
+ elem = parse(xml_path).find("color[@name='primary']")
160
+ assert elem is not None
161
+ assert elem.text == "#FF6200EE"
162
+
163
+ def test_int_argb(self, xml_path: Path):
164
+ with ValuesWriter(xml_path) as res:
165
+ res.color(primary=0xFF6200EE)
166
+ elem = parse(xml_path).find("color[@name='primary']")
167
+ assert elem is not None
168
+ assert elem.text == "#FF6200EE"
169
+
170
+ def test_invalid_string_raises(self, xml_path: Path):
171
+ with pytest.raises(ValueError):
172
+ with ValuesWriter(xml_path) as res:
173
+ res.color(primary="notacolor")
174
+
175
+ def test_invalid_int_raises(self, xml_path: Path):
176
+ with pytest.raises(ValueError):
177
+ with ValuesWriter(xml_path) as res:
178
+ res.color(primary=-1)
179
+
180
+
181
+ class TestDimensionWriter:
182
+ def test_dp(self, xml_path: Path):
183
+ with ValuesWriter(xml_path) as res:
184
+ res.dimension(padding=dp(8))
185
+ elem = parse(xml_path).find("dimen[@name='padding']")
186
+ assert elem is not None
187
+ assert elem.text == "8dp"
188
+
189
+ def test_sp(self, xml_path: Path):
190
+ with ValuesWriter(xml_path) as res:
191
+ res.dimension(text=sp(16))
192
+ elem = parse(xml_path).find("dimen[@name='text']")
193
+ assert elem is not None
194
+ assert elem.text == "16sp"
195
+
196
+
197
+ class TestInteger:
198
+ def test_value(self, xml_path: Path):
199
+ with ValuesWriter(xml_path) as res:
200
+ res.integer(retries=3)
201
+ elem = parse(xml_path).find("integer[@name='retries']")
202
+ assert elem is not None
203
+ assert elem.text == "3"
204
+
205
+
206
+ class TestResId:
207
+ def test_creates_id(self, xml_path: Path):
208
+ with ValuesWriter(xml_path) as res:
209
+ res.res_id("btn_ok")
210
+ elem = parse(xml_path).find("item[@name='btn_ok']")
211
+ assert elem is not None
212
+ assert elem.get("type") == "id"
213
+
214
+
215
+ class TestArrays:
216
+ def test_string_array(self, xml_path: Path):
217
+ with ValuesWriter(xml_path) as res:
218
+ res.string_array("planets", ["Earth", "Mars"])
219
+ items = parse(xml_path).findall("string-array[@name='planets']/item")
220
+ assert [i.text for i in items] == ["Earth", "Mars"]
221
+
222
+ def test_integer_array(self, xml_path: Path):
223
+ with ValuesWriter(xml_path) as res:
224
+ res.integer_array("nums", [1, 2, 3])
225
+ items = parse(xml_path).findall("integer-array[@name='nums']/item")
226
+ assert [i.text for i in items] == ["1", "2", "3"]
227
+
228
+ def test_typed_array_preserves_references(self, xml_path: Path):
229
+ with ValuesWriter(xml_path) as res:
230
+ res.typed_array("icons", ["@drawable/home"])
231
+ item = parse(xml_path).find("array[@name='icons']/item")
232
+ assert item is not None
233
+ assert item.text == "@drawable/home"
234
+
235
+
236
+ class TestPlurals:
237
+ def test_quantities(self, xml_path: Path):
238
+ with ValuesWriter(xml_path) as res:
239
+ res.plurals(count=PluralValues(one="%d item", other="%d items"))
240
+ root = parse(xml_path)
241
+ one = root.find("plurals[@name='count']/item[@quantity='one']")
242
+ other = root.find("plurals[@name='count']/item[@quantity='other']")
243
+ assert one is not None
244
+ assert other is not None
245
+ assert one.text == "%d item"
246
+ assert other.text == "%d items"
247
+
248
+
249
+ class TestStyle:
250
+ def test_style(self, xml_path: Path):
251
+ with ValuesWriter(xml_path) as res:
252
+ res.style("AppTheme", parent="Theme.Material", colorPrimary="@color/red")
253
+ root = parse(xml_path)
254
+ style = root.find("style[@name='AppTheme']")
255
+ assert style is not None
256
+ assert style.get("parent") == "Theme.Material"
257
+ item = style.find("item[@name='colorPrimary']")
258
+ assert item is not None
259
+ assert item.text == "@color/red"
260
+
261
+ def test_style_no_parent(self, xml_path: Path):
262
+ with ValuesWriter(xml_path) as res:
263
+ res.style("MyStyle")
264
+ style = parse(xml_path).find("style[@name='MyStyle']")
265
+ assert style is not None
266
+ assert style.get("parent") is None
267
+
268
+
269
+ class TestComment:
270
+ def test_comment_sanitizes_double_dash(self, xml_path: Path):
271
+ with ValuesWriter(xml_path) as res:
272
+ res.comment("hello -- world")
273
+ res.string(foo="bar")
274
+ content = xml_path.read_text()
275
+ assert "<!-- hello - - world -->" in content