red-tidegear 1.0.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,7 @@
1
+ .data/
2
+ .direnv/
3
+ .venv/
4
+ dist/
5
+ .ruff_cache/
6
+ **/__pycache__/
7
+ **/version.py
@@ -0,0 +1,207 @@
1
+ # Mozilla Public License Version 2.0 (MPL-2.0)
2
+
3
+ (Copied from [Mozilla Public License Version 2.0](https://www.mozilla.org/MPL/2.0/) and converted to markdown on 2023-01-06 (see: [licenses.markdown](https://codeberg.org/yelosan/licenses.markdown)).)
4
+
5
+ ---
6
+
7
+ ## 1. Definitions
8
+
9
+ ### 1.1. "Contributor"
10
+
11
+ means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
12
+
13
+ ### 1.2. "Contributor Version"
14
+
15
+ means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution.
16
+
17
+ ### 1.3. "Contribution"
18
+
19
+ means Covered Software of a particular Contributor.
20
+
21
+ ### 1.4. "Covered Software"
22
+
23
+ means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
24
+
25
+ ### 1.5. "Incompatible With Secondary Licenses"
26
+
27
+ means
28
+
29
+ a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
30
+
31
+ b. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
32
+
33
+ ### 1.6. "Executable Form"
34
+
35
+ means any form of the work other than Source Code Form.
36
+
37
+ ### 1.7. "Larger Work"
38
+
39
+ means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
40
+
41
+ ### 1.8. "License"
42
+
43
+ means this document.
44
+
45
+ ### 1.9. "Licensable"
46
+
47
+ means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
48
+
49
+ ### 1.10. "Modifications"
50
+
51
+ means any of the following:
52
+
53
+ a. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
54
+
55
+ b. any new file in Source Code Form that contains any Covered Software.
56
+
57
+ ### 1.11. "Patent Claims" of a Contributor
58
+
59
+ means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
60
+
61
+ ### 1.12. "Secondary License"
62
+
63
+ means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
64
+
65
+ ### 1.13. "Source Code Form"
66
+
67
+ means the form of the work preferred for making modifications.
68
+
69
+ ### 1.14. "You" (or "Your")
70
+
71
+ means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
72
+
73
+ ## 2. License Grants and Conditions
74
+
75
+ ### 2.1. Grants
76
+
77
+ Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
78
+
79
+ a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
80
+
81
+ b. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
82
+
83
+ ### 2.2. Effective Date
84
+
85
+ The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.
86
+
87
+ ### 2.3. Limitations on Grant Scope
88
+
89
+ The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:
90
+
91
+ a. for any code that a Contributor has removed from Covered Software; or
92
+
93
+ b. for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
94
+
95
+ c. under Patent Claims infringed by Covered Software in the absence of its Contributions.
96
+
97
+ This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).
98
+
99
+ ### 2.4. Subsequent Licenses
100
+
101
+ No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).
102
+
103
+ ### 2.5. Representation
104
+
105
+ Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.
106
+
107
+ ### 2.6. Fair Use
108
+
109
+ This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.
110
+
111
+ ### 2.7. Conditions
112
+
113
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
114
+
115
+ ## 3. Responsibilities
116
+
117
+ ### 3.1. Distribution of Source Form
118
+
119
+ All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form.
120
+
121
+ ### 3.2. Distribution of Executable Form
122
+
123
+ If You distribute Covered Software in Executable Form then:
124
+
125
+ a. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
126
+
127
+ b. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License.
128
+
129
+ ### 3.3. Distribution of a Larger Work
130
+
131
+ You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).
132
+
133
+ ### 3.4. Notices
134
+
135
+ You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.
136
+
137
+ ### 3.5. Application of Additional Terms
138
+
139
+ You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
140
+
141
+ ## 4. Inability to Comply Due to Statute or Regulation
142
+
143
+ If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
144
+
145
+ ## 5. Termination
146
+
147
+ ### 5.1
148
+
149
+ The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
150
+
151
+ ### 5.2
152
+
153
+ If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
154
+
155
+ ### 5.3
156
+
157
+ In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
158
+
159
+ ## 6. Disclaimer of Warranty
160
+
161
+ > Covered Software is provided under this License on an "as is" basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
162
+
163
+ ## 7. Limitation of Liability
164
+
165
+ > Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
166
+
167
+ ## 8. Litigation
168
+
169
+ Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims.
170
+
171
+ ## 9. Miscellaneous
172
+
173
+ This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
174
+
175
+ ## 10. Versions of the License
176
+
177
+ ### 10.1. New Versions
178
+
179
+ Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
180
+
181
+ ### 10.2. Effect of New Versions
182
+
183
+ You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
184
+
185
+ ### 10.3. Modified Versions
186
+
187
+ If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).
188
+
189
+ ### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
190
+
191
+ If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
192
+
193
+ ## Exhibit A - Source Code Form License Notice
194
+
195
+ > This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
196
+
197
+ If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
198
+
199
+ You may add additional accurate notices of copyright ownership.
200
+
201
+ ## Exhibit B - "Incompatible With Secondary Licenses" Notice
202
+
203
+ > This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
204
+
205
+ ---
206
+
207
+ (Copied from [Mozilla Public License Version 2.0](https://www.mozilla.org/MPL/2.0/) and converted to markdown on 2023-01-06 (see: [licenses.markdown](https://codeberg.org/yelosan/licenses.markdown)).)
@@ -0,0 +1,75 @@
1
+ Metadata-Version: 2.4
2
+ Name: red-tidegear
3
+ Version: 1.0.0
4
+ Project-URL: Homepage, https://c.csw.im/cswimr/tidegear
5
+ Project-URL: Issues, https://c.csw.im/cswimr/tidegear/issues
6
+ Project-URL: source_archive, https://c.csw.im/cswimr/tidegear/archive/7755d63a9a2e99222c342c1cc0b41456ac819bd3.tar.gz
7
+ License-Expression: MPL-2.0
8
+ License-File: LICENSE.md
9
+ Requires-Python: <3.12,>=3.9
10
+ Requires-Dist: furl>=2.1.4
11
+ Requires-Dist: pip
12
+ Requires-Dist: red-discordbot>=3.5.6
13
+ Provides-Extra: pydantic
14
+ Requires-Dist: pydantic>=2.11.0; extra == 'pydantic'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Tidegear
18
+
19
+ [![Discord](https://img.shields.io/discord/1070058354925383681?logo=discord&color=%235661f6)](https://discord.gg/eMUMe77Yb8)
20
+ ![Python Versions](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fc.csw.im%2Fcswimr%2FCogUtils%2Fraw%2Fbranch%2Fmain%2Fpyproject.toml&logo=python)
21
+
22
+ A collection of utilities for use with [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot), made for [SeaCogs](https://c.csw.im/cswimr/SeaCogs).
23
+
24
+ ## Metadata File
25
+
26
+ The cog class provided by [`tidegear.Cog`](./tidegear/cog.py) requires consuming cogs to have a `meta.json` file in your cog's bundled data directory. The `meta.json` file must match the schema provided in [`schema/meta/meta.json`](./schema/meta/meta.json). An example file is located at [`scheme/meta/meta.example.json`](./schema/meta/meta.example.json). Additional keys are disallowed by the schema but will not cause errors.
27
+
28
+ ## Developing
29
+
30
+ You'll need some prerequisites before you can start working on CogUtils.
31
+ [git](https://git-scm.com) - [uv](https://docs.astral.sh/uv)
32
+ Additionally, I recommend a code editor of some variety. [Visual Studio Code](https://code.visualstudio.com) is a good, beginner-friendly option.
33
+
34
+ ### Installing Prerequisites
35
+
36
+ _This section of the guide only applies to Windows systems.
37
+ If you're on Linux, refer to the documentation of the projects listed above. I also offer a [Nix Flake](./flake.nix) that contains all of the required prerequisites, if you're a Nix user._
38
+
39
+ #### [`git`](https://git-scm.com)
40
+
41
+ You can download git from the [git download page](https://git-scm.com/downloads/win).
42
+
43
+ Alternatively, you can use `winget`:
44
+
45
+ ```ps1
46
+ winget install --id=Git.Git -e --source=winget
47
+ ```
48
+
49
+ #### [`uv`](https://docs.astral.sh/uv)
50
+
51
+ You can install uv with the following Powershell command:
52
+
53
+ ```ps1
54
+ powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
55
+ ```
56
+
57
+ Alternatively, you can use `winget`:
58
+
59
+ ```ps1
60
+ winget install --id=astral-sh.uv -e
61
+ ```
62
+
63
+ ### Getting the Source Code
64
+
65
+ Once you have [`git`](https://git-scm.com) installed, you can use the `git clone` command to get a copy of the repository on your system.
66
+
67
+ ```bash
68
+ git clone https://c.csw.im/cswimr/tidegear.git
69
+ ```
70
+
71
+ Then, you can use `uv` to install the Python dependencies required for development.
72
+
73
+ ```bash
74
+ uv sync --all-groups --all-extras --frozen
75
+ ```
@@ -0,0 +1,59 @@
1
+ # Tidegear
2
+
3
+ [![Discord](https://img.shields.io/discord/1070058354925383681?logo=discord&color=%235661f6)](https://discord.gg/eMUMe77Yb8)
4
+ ![Python Versions](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fc.csw.im%2Fcswimr%2FCogUtils%2Fraw%2Fbranch%2Fmain%2Fpyproject.toml&logo=python)
5
+
6
+ A collection of utilities for use with [Red-DiscordBot](https://github.com/Cog-Creators/Red-DiscordBot), made for [SeaCogs](https://c.csw.im/cswimr/SeaCogs).
7
+
8
+ ## Metadata File
9
+
10
+ The cog class provided by [`tidegear.Cog`](./tidegear/cog.py) requires consuming cogs to have a `meta.json` file in your cog's bundled data directory. The `meta.json` file must match the schema provided in [`schema/meta/meta.json`](./schema/meta/meta.json). An example file is located at [`scheme/meta/meta.example.json`](./schema/meta/meta.example.json). Additional keys are disallowed by the schema but will not cause errors.
11
+
12
+ ## Developing
13
+
14
+ You'll need some prerequisites before you can start working on CogUtils.
15
+ [git](https://git-scm.com) - [uv](https://docs.astral.sh/uv)
16
+ Additionally, I recommend a code editor of some variety. [Visual Studio Code](https://code.visualstudio.com) is a good, beginner-friendly option.
17
+
18
+ ### Installing Prerequisites
19
+
20
+ _This section of the guide only applies to Windows systems.
21
+ If you're on Linux, refer to the documentation of the projects listed above. I also offer a [Nix Flake](./flake.nix) that contains all of the required prerequisites, if you're a Nix user._
22
+
23
+ #### [`git`](https://git-scm.com)
24
+
25
+ You can download git from the [git download page](https://git-scm.com/downloads/win).
26
+
27
+ Alternatively, you can use `winget`:
28
+
29
+ ```ps1
30
+ winget install --id=Git.Git -e --source=winget
31
+ ```
32
+
33
+ #### [`uv`](https://docs.astral.sh/uv)
34
+
35
+ You can install uv with the following Powershell command:
36
+
37
+ ```ps1
38
+ powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
39
+ ```
40
+
41
+ Alternatively, you can use `winget`:
42
+
43
+ ```ps1
44
+ winget install --id=astral-sh.uv -e
45
+ ```
46
+
47
+ ### Getting the Source Code
48
+
49
+ Once you have [`git`](https://git-scm.com) installed, you can use the `git clone` command to get a copy of the repository on your system.
50
+
51
+ ```bash
52
+ git clone https://c.csw.im/cswimr/tidegear.git
53
+ ```
54
+
55
+ Then, you can use `uv` to install the Python dependencies required for development.
56
+
57
+ ```bash
58
+ uv sync --all-groups --all-extras --frozen
59
+ ```
@@ -0,0 +1,115 @@
1
+ [project]
2
+ name = "red-tidegear"
3
+ requires-python = ">=3.9,<3.12"
4
+ readme = "README.md"
5
+ license = "MPL-2.0"
6
+ license-files = ["LICEN[CS]E*"]
7
+ dependencies = [
8
+ "pip", # Red-DiscordBot depends on pip but doesn't list it as a dependency. Ensure it's installed; version is irrelevant.
9
+ "furl>=2.1.4",
10
+ "red-discordbot>=3.5.6",
11
+ ]
12
+ dynamic = ["version", "urls"]
13
+
14
+ [project.optional-dependencies]
15
+ pydantic = ["pydantic>=2.11.0"]
16
+
17
+ [dependency-groups]
18
+ dev = ["basedpyright>=1.29.4", "ruff>=0.12.0"]
19
+
20
+ [tool.hatch.build]
21
+ include = ["/tidegear"]
22
+
23
+ [tool.hatch.version]
24
+ source = "vcs"
25
+
26
+ [tool.hatch.build.hooks.vcs]
27
+ version-file = "tidegear/version.py"
28
+ template = """
29
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
30
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
31
+ # © 2025 cswimr
32
+
33
+ # This file is automatically generated on build, do not edit!
34
+ # Do not commit this file to source control!
35
+
36
+ from furl import furl
37
+
38
+ from .metadata import Repository, SemVer, TidegearMeta
39
+
40
+ meta = TidegearMeta(
41
+ version=SemVer(*{version_tuple}),
42
+ repository=Repository(
43
+ owner="cswimr",
44
+ name="tidegear",
45
+ url=furl("https://c.csw.im/cswimr/tidegear"),
46
+ ),
47
+ )
48
+
49
+ version = meta.version
50
+ __version__ = str(meta.version)
51
+ """
52
+
53
+ [tool.hatch.metadata.hooks.vcs.urls]
54
+ Homepage = "https://c.csw.im/cswimr/tidegear"
55
+ Issues = "https://c.csw.im/cswimr/tidegear/issues"
56
+ source_archive = "https://c.csw.im/cswimr/tidegear/archive/{commit_hash}.tar.gz"
57
+
58
+ [build-system]
59
+ requires = ["hatchling", "hatch-vcs"]
60
+ build-backend = "hatchling.build"
61
+
62
+ [tool.basedpyright]
63
+ typeCheckingMode = "standard"
64
+ reportImplicitOverride = "warning"
65
+
66
+ [tool.ruff]
67
+ line-length = 150
68
+ indent-width = 4
69
+ target-version = "py39"
70
+
71
+ [tool.ruff.lint]
72
+ select = [
73
+ "I",
74
+ "N",
75
+ "F",
76
+ "W",
77
+ "E",
78
+ "G",
79
+ "A",
80
+ "COM",
81
+ "INP",
82
+ "T20",
83
+ "PLC",
84
+ "PLE",
85
+ "PLW",
86
+ "PLR",
87
+ "LOG",
88
+ "SLF",
89
+ "ERA",
90
+ "FIX",
91
+ "PERF",
92
+ "C4",
93
+ "EM",
94
+ "RET",
95
+ "RSE",
96
+ ]
97
+ ignore = [
98
+ "PLR0911",
99
+ "PLR0912",
100
+ "PLR0915",
101
+ "PLR2004",
102
+ "PLR0913",
103
+ "EM101",
104
+ "COM812",
105
+ ]
106
+ fixable = ["ALL"]
107
+ unfixable = []
108
+
109
+ [tool.ruff.format]
110
+ quote-style = "double"
111
+ indent-style = "space"
112
+ skip-magic-trailing-comma = false
113
+ line-ending = "auto"
114
+ docstring-code-format = true
115
+ docstring-code-line-length = "dynamic"
@@ -0,0 +1,8 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+ from .cog import Cog
5
+ from .metadata import CogMetadata
6
+ from .version import __version__, meta, version
7
+
8
+ __all__ = ["__version__", "Cog", "CogMetadata", "meta", "version"]
@@ -0,0 +1,79 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ from typing import List
6
+
7
+ from discord import Guild, User
8
+ from red_commons.logging import RedTraceLogger, getLogger
9
+ from redbot.core import commands, data_manager
10
+ from redbot.core.bot import Red
11
+ from redbot.core.utils.chat_formatting import bold, humanize_list
12
+ from typing_extensions import override
13
+
14
+ from .metadata import CogMetadata
15
+ from .version import meta
16
+
17
+
18
+ class Cog(commands.Cog):
19
+ def __init__(self, bot: Red) -> None:
20
+ super().__init__()
21
+ self.bot: Red = bot
22
+ # this is fine because Red itself will fail if the client isn't logged in way before this cog would be loaded
23
+ self.me: User = bot.get_user(bot.user.id) # pyright: ignore[reportAttributeAccessIssue, reportOptionalMemberAccess]
24
+ path = data_manager.bundled_data_path(self) / "meta.json"
25
+ if not path.exists():
26
+ msg = f"There is no metadata file located at {path}!"
27
+ raise FileNotFoundError(msg)
28
+ self.metadata: CogMetadata = CogMetadata.from_json(self.__cog_name__, path)
29
+ self.logger: RedTraceLogger = getLogger(f"red.{self.metadata.repository.name}.{self.__cog_name__}")
30
+
31
+ @override
32
+ def format_help_for_context(self, ctx: commands.Context) -> str:
33
+ base = (super().format_help_for_context(ctx) or "").rstrip("\n") + "\n"
34
+ parts: List[str] = [base]
35
+ parts.append(f"{bold('Cog Version:')} [{self.metadata.version}]({self.metadata.repository.url})")
36
+ author_label = "Authors:" if len(self.metadata.authors) >= 2 else "Author:"
37
+ parts.append(f"{bold(author_label)} {humanize_list([author.markdown for author in self.metadata.authors])}")
38
+ if self.metadata.documentation is not None:
39
+ parts.append(f"{bold('Documentation:')} {self.metadata.documentation}")
40
+ parts.append(f"{bold('Tidegear Version:')} {meta.markdown}")
41
+ return "\n".join(parts)
42
+
43
+ async def get_or_fetch_user(self, user_id: int) -> User:
44
+ """Retrieve a user from the internal cache, or fetch it if it cannot be found.
45
+ Use this sparingly, as the `fetch_user` endpoint has a strict ratelimit.
46
+
47
+ Args:
48
+ user_id (int): The ID of the user to retrieve.
49
+
50
+ Raises:
51
+ discord.NotFound: If the user does not exist.
52
+ discord.HTTPException: Fetching the user failed.
53
+
54
+ Returns:
55
+ User: The retrieved user.
56
+ """
57
+ user = self.bot.get_user(user_id)
58
+ if not user:
59
+ user = await self.bot.fetch_user(user_id)
60
+ return user
61
+
62
+ async def get_or_fetch_guild(self, guild_id: int) -> Guild:
63
+ """Retrieve a guild from the internal cache, or fetch it if it cannot be found.
64
+ Use this sparingly, as the `fetch_guild` endpoint has a strict ratelimit.
65
+
66
+ Args:
67
+ guild_id (int): The ID of the guild to retrieve.
68
+
69
+ Raises:
70
+ discord.NotFound: If the guild does not exist or the bot does not have access to it.
71
+ discord.HTTPException: Fetching the guild failed.
72
+
73
+ Returns:
74
+ Guild: The retrieved guild.
75
+ """
76
+ guild = self.bot.get_guild(guild_id)
77
+ if not guild:
78
+ guild = await self.bot.fetch_guild(guild_id)
79
+ return guild
@@ -0,0 +1,124 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import List, Optional
9
+
10
+ import orjson
11
+ from furl import furl
12
+ from typing_extensions import override
13
+
14
+
15
+ @dataclass
16
+ class SemVer:
17
+ major: int
18
+ minor: int
19
+ patch: int
20
+ extra: Optional[str] = None
21
+ commit: Optional[str] = None
22
+
23
+ @override
24
+ def __str__(self) -> str:
25
+ string = f"{self.major}.{self.minor}.{self.patch}"
26
+ if self.extra:
27
+ string += self.extra
28
+ if self.commit:
29
+ string += f"+{self.commit}"
30
+ return string
31
+
32
+ @classmethod
33
+ def from_str(cls, version: str, /) -> "SemVer":
34
+ """
35
+ Parse a version string of the form `MAJOR.MINOR.PATCH[EXTRA]`, where `EXTRA` is any string (often things like '-alpha.1' or '+build.123').
36
+ """
37
+ pattern = r"^(\d+)\.(\d+)\.(\d+)([-+].+)?$"
38
+ m = re.match(pattern, version)
39
+ if not m:
40
+ msg = f"Invalid SemVer string: {version!r}"
41
+ raise ValueError(msg)
42
+ major, minor, patch, extra = m.groups()
43
+ return cls(int(major), int(minor), int(patch), extra)
44
+
45
+
46
+ @dataclass
47
+ class User:
48
+ name: str
49
+ profile: furl
50
+
51
+ @override
52
+ def __str__(self) -> str:
53
+ return self.name
54
+
55
+ @property
56
+ def markdown(self) -> str:
57
+ return f"[{self.name}]({self.profile})"
58
+
59
+
60
+ @dataclass
61
+ class Repository:
62
+ owner: str
63
+ name: str
64
+ url: furl
65
+
66
+ @override
67
+ def __str__(self) -> str:
68
+ return self.name
69
+
70
+ @property
71
+ def slug(self) -> str:
72
+ return self.name.lower()
73
+
74
+ @property
75
+ def issues(self) -> furl:
76
+ return self.url / "issues"
77
+
78
+ @property
79
+ def markdown(self) -> str:
80
+ return f"[{self.owner}/{self.name}]({self.url})"
81
+
82
+
83
+ @dataclass
84
+ class CogMetadata:
85
+ name: str
86
+ version: SemVer
87
+ authors: List[User]
88
+ repository: Repository
89
+ documentation: Optional[furl] = None
90
+
91
+ @classmethod
92
+ def from_json(cls, cog_name: str, file: Path) -> "CogMetadata":
93
+ """Load cog metadata from a JSON file.
94
+
95
+ Args:
96
+ cog_name (str): The name of the cog.
97
+ file (Path): The file path of the JSON file to load from.
98
+
99
+ Returns:
100
+ CogMetadata: The constructed metadata object.
101
+ """
102
+ with open(file, "rb") as f:
103
+ obj = orjson.loads(f.read())
104
+
105
+ authors = [User(name=author["name"], profile=furl(author["url"])) for author in obj["authors"]]
106
+ repository = Repository(owner=obj["repository"]["owner"], name=obj["repository"]["name"], url=furl(obj["repository"]["url"]))
107
+ if (documentation := obj.get("documentation", None)) is not None:
108
+ documentation = furl(documentation)
109
+ version = SemVer.from_str(obj["version"])
110
+ return cls(name=cog_name, version=version, authors=authors, repository=repository, documentation=documentation)
111
+
112
+
113
+ @dataclass
114
+ class TidegearMeta:
115
+ version: SemVer
116
+ repository: Repository
117
+
118
+ @override
119
+ def __str__(self) -> str:
120
+ return str(self.version)
121
+
122
+ @property
123
+ def markdown(self) -> str:
124
+ return f"[{self.version}]({self.repository.url})"
@@ -0,0 +1,15 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ from importlib.util import find_spec
6
+
7
+ if not find_spec("pydantic"):
8
+ raise ImportError(
9
+ "pydantic is not installed, but the `cogutils.pydantic` module was imported! Did you install cogutils with the `pydantic` extra?"
10
+ )
11
+
12
+ from .basemodel import BaseModel, CogModel
13
+ from .httpurl import HttpUrl
14
+
15
+ __all__ = ["BaseModel", "CogModel", "HttpUrl"]
@@ -0,0 +1,299 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ from typing import Any, Callable, Dict, List, Literal, Optional, TypeVar, Union, overload
6
+
7
+ import orjson
8
+ from discord import Colour, Embed
9
+ from pydantic import BaseModel as PydanticBaseModel
10
+ from pydantic import ConfigDict, Field, ValidationError
11
+ from pydantic.main import IncEx
12
+ from pydantic_core import ErrorDetails
13
+ from red_commons.logging import RedTraceLogger
14
+ from redbot.core import commands
15
+ from redbot.core.utils.chat_formatting import bold, error, inline
16
+ from redbot.core.utils.views import _ACCEPTABLE_PAGE_TYPES, SimpleMenu
17
+ from typing_extensions import Self, override
18
+
19
+ from ..cog import Cog
20
+ from ..metadata import CogMetadata
21
+
22
+ R = TypeVar("R")
23
+
24
+
25
+ class BaseModel(PydanticBaseModel):
26
+ model_config = ConfigDict(validate_assignment=True, arbitrary_types_allowed=True)
27
+
28
+ @overload
29
+ @classmethod
30
+ def validate_field(cls, field_name: str, field_value: Any, converter: Callable[[Any], R]) -> R: ...
31
+
32
+ @overload
33
+ @classmethod
34
+ def validate_field(cls, field_name: str, field_value: Any, converter: None = None) -> Any: ...
35
+
36
+ @classmethod
37
+ def validate_field(cls, field_name: str, field_value: Any, converter: Optional[Callable[[Any], R]] = None) -> Union[R, Any]:
38
+ """Wraps internal Pydantic methods to allow validating a single field without running validation for an entire model.
39
+
40
+ Args:
41
+ field_name (str): The name of the field to validate your input against.
42
+ field_value (Any): The input value to validate.
43
+ converter (Callable[[Any], R] | None): A function to use to convert the resulting value.
44
+
45
+ Returns:
46
+ R | Any: The validated input value.
47
+ """
48
+ model: Self = cls.__pydantic_validator__.validate_assignment(cls.model_construct(), field_name, field_value) # pyright: ignore[reportAssignmentType]
49
+ attribute = getattr(model, field_name)
50
+ if converter:
51
+ return converter(attribute)
52
+ return attribute
53
+
54
+ @overload
55
+ def json(
56
+ self,
57
+ /,
58
+ *,
59
+ include: IncEx = ...,
60
+ exclude: IncEx = ...,
61
+ remove_token: bool = ...,
62
+ string: Literal[False] = False,
63
+ encoding: str = ...,
64
+ indent: bool = ...,
65
+ ) -> Dict[str, Any]: ...
66
+
67
+ @overload
68
+ def json(
69
+ self,
70
+ /,
71
+ *,
72
+ include: IncEx = ...,
73
+ exclude: IncEx = ...,
74
+ remove_token: bool = ...,
75
+ string: Literal[True],
76
+ encoding: str = ...,
77
+ indent: bool = ...,
78
+ ) -> str: ...
79
+
80
+ @override
81
+ def json( # pyright: ignore[reportIncompatibleMethodOverride]
82
+ self,
83
+ /,
84
+ *,
85
+ include: IncEx = set(),
86
+ exclude: IncEx = set(),
87
+ remove_token: bool = True,
88
+ string: bool = False,
89
+ encoding: str = "utf-8",
90
+ indent: bool = False,
91
+ ) -> Union[Dict[str, Any], str]:
92
+ """Dumps the contents of the model to a JSON-serializable dictionary.
93
+
94
+ Set an attribute's default value to `Field(exclude=True)` to exclude it from this function's output automatically.
95
+
96
+ Args:
97
+ include (pydantic.IncEx): A set of fields to include in the model dump.
98
+ exclude (pydantic.IncEx): A set of fields to exclude from the model dump.
99
+ remove_token (bool): Whether or not to recursively remove keys named `token` from the output object.
100
+ string (bool): Whether or not to use `orjson.dumps()` to convert the resulting dictionary to a string.
101
+ encoding (str): The encoding to use to decode the bytes returned by `orjson.dumps()`.
102
+ indent (bool): Whether or not to pretty-print the output. This is slower and should only be used when an end user is seeing the output.
103
+
104
+ Returns:
105
+ `dict[str, Any]`: A Dictionary containing only JSON-serializable attributes, if `string` is `False`.
106
+ `str`: A string representation of the Dictionary mentioned previously, converted using `orjson.dumps()`.
107
+ """
108
+ params = {"exclude": exclude, "mode": "json"}
109
+ if include:
110
+ params["include"] = include
111
+
112
+ obj = self.model_dump(**params)
113
+
114
+ if remove_token:
115
+ obj = self._recurse_modify(obj, "token", lambda token: "*" * 6 if token else None)
116
+
117
+ if string:
118
+ opts: Optional[int] = None
119
+ if indent:
120
+ opts = orjson.OPT_INDENT_2
121
+ return orjson.dumps(obj, option=opts).decode(encoding)
122
+
123
+ return obj
124
+
125
+ def _recurse_modify(self, obj: Any, key: str, modify_fn: Callable[..., Any]) -> Any:
126
+ """
127
+ Returns a deep-copied version of obj where every dict-key matching `key` has its value replaced by modify_fn(old_value).
128
+ """
129
+ if isinstance(obj, dict):
130
+ new_dict = {}
131
+ for k, v in obj.items():
132
+ if k == key:
133
+ new_dict[k] = modify_fn(v)
134
+ else:
135
+ new_dict[k] = self._recurse_modify(v, key, modify_fn)
136
+ return new_dict
137
+ if isinstance(obj, list):
138
+ return [self._recurse_modify(item, key, modify_fn) for item in obj]
139
+ if isinstance(obj, tuple):
140
+ return tuple(self._recurse_modify(item, key, modify_fn) for item in obj)
141
+ if isinstance(obj, set):
142
+ return {self._recurse_modify(item, key, modify_fn) for item in obj}
143
+ return obj
144
+
145
+ @staticmethod
146
+ def _custom_validation_messages() -> Dict[str, Union[str, Dict[str, str]]]:
147
+ return {
148
+ "string_pattern_mismatch": {
149
+ r"^[\w\-]+$": "String may only contain letters, numbers, underscores, and hyphens.",
150
+ },
151
+ }
152
+
153
+ @classmethod
154
+ def _replace_error_messages(cls, validation_error: ValidationError, /) -> List[ErrorDetails]:
155
+ """Replace a few error messages with more human-readable variants.
156
+
157
+ Args:
158
+ err (ValidationError): The Pydantic ValidationError to convert the messages of.
159
+
160
+ Returns:
161
+ list[ErrorDetails]: The converted messages.
162
+ """
163
+
164
+ new_errors: List[ErrorDetails] = []
165
+ for err in validation_error.errors():
166
+ err_type = err.get("type")
167
+ custom_message = cls._custom_validation_messages().get(err_type)
168
+
169
+ if err_type == "string_pattern_mismatch":
170
+ if not isinstance(custom_message, dict):
171
+ msg = f"Invalid type for {err_type}!"
172
+ raise TypeError(msg)
173
+
174
+ if not (ctx := err.get("ctx")) or not (pattern := ctx.get("pattern")):
175
+ raise ValueError("Error details do not contain a regex pattern!")
176
+
177
+ for k, v in custom_message.items():
178
+ if pattern == k:
179
+ err["msg"] = v.format(**ctx)
180
+
181
+ elif isinstance(custom_message, str):
182
+ ctx = err.get("ctx")
183
+ err["msg"] = custom_message.format(**ctx) if ctx else custom_message
184
+
185
+ new_errors.append(err)
186
+ return new_errors
187
+
188
+ @classmethod
189
+ async def validation_error_menu(
190
+ cls,
191
+ err: ValidationError,
192
+ ctx: Optional[commands.Context] = None,
193
+ *,
194
+ class_name: Optional[str] = None,
195
+ metadata: Optional[CogMetadata] = None,
196
+ logger: Optional[RedTraceLogger] = None,
197
+ title: str = "🚫 Validation Error",
198
+ color: Union[Colour, int] = Colour.red(),
199
+ per_page: int = 5,
200
+ ) -> Optional[SimpleMenu]:
201
+ """
202
+ Take a Pydantic ValidationError, split its .errors() into pages, and create a SimpleMenu from them.
203
+
204
+ Args:
205
+ err (ValidationError): The ValidationError to create an error embed from.
206
+ ctx (Commands.Context, optional): The context to use to provide additional help when the error occurred within a command.
207
+ class_name (str, optional): The name of the class to show in the resulting embed's description.
208
+ This only needs to be provided if the class you're validating against doesn't inherit from `BaseModel`.
209
+ metadata (CogMetaData, optional): Cog metadata to use to populate the resulting embed.
210
+ logger (RedTraceLogger, optional): A logger to log the exception to.
211
+ title (str, optional): The title of the created embeds. Defaults to `🚫 Validation Error`.
212
+ color (discord.Colour | int, optional): The color of the created embeds. Defaults to `discord.Colour.red()`.
213
+ per_page (int, optional): How many validation errors to list per page. Defaults to `5`.
214
+
215
+ Returns:
216
+ SimpleMenu: The created SimpleMenu, which you can then start with `await SimpleMenu.start(ctx)`.
217
+ None: If `ctx` is provided and the bot cannot post embeds in the context channel,
218
+ or if the `ValidationError` exception doesn't provide any errors.
219
+
220
+ Example Usage (Red `[p]eval`):
221
+ ```python
222
+ from typing import Annotated
223
+ from pydantic import StringConstraints, ValidationError
224
+ from .cogutils.pydantic import BaseModel
225
+
226
+
227
+ class ExampleModel(BaseModel):
228
+ string: Annotated[str, StringConstraints(min_length=3)]
229
+
230
+
231
+ try:
232
+ ExampleModel(string="hi")
233
+ except ValidationError as err: # String should have at least 3 characters (string_too_short)
234
+ if menu := await ExampleModel.validation_error_menu(err, ctx):
235
+ await menu.start(ctx)
236
+ ```
237
+ """
238
+ lines: List[Optional[str]] = [
239
+ f"Validation error encountered for the {inline(class_name or err.title)} class!",
240
+ (f"Please check {inline(f'{ctx.clean_prefix}help {ctx.command.qualified_name}')} to ensure you are passing the correct arguments.")
241
+ if (ctx and ctx.command)
242
+ else None,
243
+ f"If this is unexpected or you're having trouble working around this error, please report it [here]({metadata.repository.issues})."
244
+ if metadata
245
+ else None,
246
+ ]
247
+ description = "\n".join(line for line in lines if line is not None)
248
+
249
+ if logger:
250
+ logger.exception(lines[0], exc_info=err)
251
+
252
+ if ctx:
253
+ if not await ctx.embed_requested():
254
+ await ctx.send(
255
+ f"{error('Tried to post an issue embed, but I cannot post embeds in this channel or embeds are disabled!')}\n\n{description}"
256
+ )
257
+ return None
258
+
259
+ problems = cls._replace_error_messages(err)
260
+ total = len(problems)
261
+ if total == 0:
262
+ return None
263
+
264
+ footer_text = ""
265
+
266
+ if tb := err.__traceback__:
267
+ module = tb.tb_frame.f_globals.get("__name__", "unknown")
268
+ line = tb.tb_lineno
269
+ function = tb.tb_frame.f_code.co_name
270
+ footer_text = f"• Exception in module '{module}' in function '{function}' at line #{line}\n"
271
+
272
+ pages: List[_ACCEPTABLE_PAGE_TYPES] = []
273
+ total_pages = (total - 1) // per_page + 1
274
+
275
+ for i in range(0, total, per_page):
276
+ embed = Embed(title=title, color=color, description=description)
277
+ embed.set_footer(text=footer_text + f"• Page {i // per_page + 1}/{total_pages}")
278
+
279
+ for problem in problems[i : i + per_page]:
280
+ loc = ".".join(str(x) for x in problem["loc"])
281
+ msg: str = problem.get("msg", "").replace("'", "`")
282
+ input_value = problem.get("input", "UNKNOWN")
283
+
284
+ if code := problem.get("type", ""):
285
+ if code_url := problem.get("url"):
286
+ code = f"[{inline(code)}]({code_url})"
287
+ else:
288
+ code = "UNKNOWN"
289
+
290
+ field_value = f"{bold('Message:')} {msg}\n{bold('Input: ')} {inline(input_value)}\n{bold('Code:')} {code}"
291
+ embed.add_field(name=f"Field: {inline(loc or 'base')}", value=field_value, inline=False)
292
+
293
+ pages.append(embed)
294
+
295
+ return SimpleMenu(pages)
296
+
297
+
298
+ class CogModel(BaseModel):
299
+ cog: Cog = Field(exclude=True)
@@ -0,0 +1,83 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ from typing import Optional
6
+
7
+ from discord.utils import MISSING
8
+ from pydantic import HttpUrl as PydanticHttpUrl
9
+ from typing_extensions import Self
10
+
11
+
12
+ class HttpUrl(PydanticHttpUrl):
13
+ """
14
+ A subclass of `pydantic.HttpUrl` that adds some useful methods and operator overloads for more ergonomic path manipulation and URL composition.
15
+
16
+ Operations:
17
+ - `url / "segment"` - returns a new HttpUrl with "segment" appended to the path
18
+ - `url /= "segment"` - in-place append of "segment" to the path
19
+
20
+ Examples:
21
+ >>> u = HttpUrl("https://example.com/api")
22
+ >>> u2 = u / "v1" / "users"
23
+ >>> print(u2)
24
+ https://example.com/api/v1/users
25
+
26
+ >>> u2 /= "123"
27
+ >>> print(u2)
28
+ https://example.com/api/v1/users/123
29
+ """
30
+
31
+ def __truediv__(self, other: str) -> Self:
32
+ return self.join(other)
33
+
34
+ def __itruediv__(self, other: str) -> Self:
35
+ return self.__truediv__(other)
36
+
37
+ @property
38
+ def base(self) -> Self:
39
+ """Wrapper around `HttpUrl.join()` that returns the base URL (scheme, host, etc.).
40
+
41
+ Returns:
42
+ Self: The new HttpUrl object pointing to the base URL of the source HttpUrl object.
43
+ """
44
+ return self.join(None, query=None, fragment=None)
45
+
46
+ def join(self, path: Optional[str] = MISSING, /, *, query: Optional[str] = MISSING, fragment: Optional[str] = MISSING) -> Self:
47
+ """Create a new HttpUrl object using `HttpUrl.build()`.
48
+
49
+ Args:
50
+ path (str): The path to add to this HttpUrl's path.
51
+ Defaults to MISSING, will replace the original path if set to `None`.
52
+ query (str | None): The query to replace this HttpUrl's query with.
53
+ Defaults to MISSING, will replace the original query if set to `None`.
54
+ fragment (str | None): The fragment to replace this HttpUrl's fragment with.
55
+ Defaults to MISSING, will replace the original fragment if set to `None`.
56
+
57
+ Returns:
58
+ Self: The new HttpUrl object.
59
+ """
60
+
61
+ def _strip(s: str, /) -> str:
62
+ return s.lstrip("/").rstrip("/")
63
+
64
+ base = _strip(self.path or "")
65
+
66
+ if path is MISSING:
67
+ new_path = base
68
+ elif path is None:
69
+ new_path = ""
70
+ else:
71
+ seg = _strip(path)
72
+ new_path = f"{base}/{seg}" if base else seg
73
+
74
+ return self.build(
75
+ scheme=self.scheme,
76
+ username=self.username,
77
+ password=self.password,
78
+ host=self.host or "",
79
+ port=self.port,
80
+ path=new_path,
81
+ query=self.query if query is MISSING else query,
82
+ fragment=self.fragment if fragment is MISSING else fragment,
83
+ )
@@ -0,0 +1,22 @@
1
+ # This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
2
+ # If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
3
+ # © 2025 cswimr
4
+
5
+ # This file is automatically generated on build, do not edit!
6
+ # Do not commit this file to source control!
7
+
8
+ from furl import furl
9
+
10
+ from .metadata import Repository, SemVer, TidegearMeta
11
+
12
+ meta = TidegearMeta(
13
+ version=SemVer(*(1, 0, 0)),
14
+ repository=Repository(
15
+ owner="cswimr",
16
+ name="tidegear",
17
+ url=furl("https://c.csw.im/cswimr/tidegear"),
18
+ ),
19
+ )
20
+
21
+ version = meta.version
22
+ __version__ = str(meta.version)