librebots-kit 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.
Files changed (42) hide show
  1. librebots_kit-0.1.0/.coderabbit.yaml +114 -0
  2. librebots_kit-0.1.0/.github/release.yml +10 -0
  3. librebots_kit-0.1.0/.github/workflows/ci.yml +47 -0
  4. librebots_kit-0.1.0/.github/workflows/release.yml +65 -0
  5. librebots_kit-0.1.0/.gitignore +8 -0
  6. librebots_kit-0.1.0/.python-version +1 -0
  7. librebots_kit-0.1.0/LICENSE +21 -0
  8. librebots_kit-0.1.0/Makefile +10 -0
  9. librebots_kit-0.1.0/PKG-INFO +42 -0
  10. librebots_kit-0.1.0/README.md +25 -0
  11. librebots_kit-0.1.0/mise.toml +3 -0
  12. librebots_kit-0.1.0/pyproject.toml +60 -0
  13. librebots_kit-0.1.0/renovate.json +4 -0
  14. librebots_kit-0.1.0/src/librebots/kit/__init__.py +26 -0
  15. librebots_kit-0.1.0/src/librebots/kit/bot.py +18 -0
  16. librebots_kit-0.1.0/src/librebots/kit/config.py +128 -0
  17. librebots_kit-0.1.0/src/librebots/kit/ext/__init__.py +1 -0
  18. librebots_kit-0.1.0/src/librebots/kit/ext/errors.py +100 -0
  19. librebots_kit-0.1.0/src/librebots/kit/ext/guilds.py +76 -0
  20. librebots_kit-0.1.0/src/librebots/kit/ext/info.py +75 -0
  21. librebots_kit-0.1.0/src/librebots/kit/ext/privacy.py +374 -0
  22. librebots_kit-0.1.0/src/librebots/kit/guilds.py +101 -0
  23. librebots_kit-0.1.0/src/librebots/kit/hub.py +176 -0
  24. librebots_kit-0.1.0/src/librebots/kit/i18n.py +209 -0
  25. librebots_kit-0.1.0/src/librebots/kit/locales/de/kit.ftl +55 -0
  26. librebots_kit-0.1.0/src/librebots/kit/locales/en-US/kit.ftl +58 -0
  27. librebots_kit-0.1.0/src/librebots/kit/privacy.py +126 -0
  28. librebots_kit-0.1.0/src/librebots/kit/py.typed +0 -0
  29. librebots_kit-0.1.0/tests/guild_fakes.py +89 -0
  30. librebots_kit-0.1.0/tests/hub_server.py +31 -0
  31. librebots_kit-0.1.0/tests/privacy_fakes.py +99 -0
  32. librebots_kit-0.1.0/tests/test_config.py +237 -0
  33. librebots_kit-0.1.0/tests/test_ext_errors.py +236 -0
  34. librebots_kit-0.1.0/tests/test_ext_guilds.py +172 -0
  35. librebots_kit-0.1.0/tests/test_ext_info.py +194 -0
  36. librebots_kit-0.1.0/tests/test_ext_privacy.py +428 -0
  37. librebots_kit-0.1.0/tests/test_guilds.py +258 -0
  38. librebots_kit-0.1.0/tests/test_hub.py +276 -0
  39. librebots_kit-0.1.0/tests/test_i18n.py +242 -0
  40. librebots_kit-0.1.0/tests/test_import.py +8 -0
  41. librebots_kit-0.1.0/tests/test_privacy.py +274 -0
  42. librebots_kit-0.1.0/uv.lock +1148 -0
@@ -0,0 +1,114 @@
1
+ # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
2
+ language: en-US
3
+ tone_instructions: >-
4
+ Be direct and specific. Name the file and line, the input or state that breaks, and what goes wrong as a result.
5
+ Skip praise and do not restate the diff.
6
+ early_access: false
7
+
8
+ reviews:
9
+ profile: assertive
10
+ auto_approvals:
11
+ enabled: true
12
+ min_blocking_severity: major
13
+ high_level_summary: true
14
+ review_status: true
15
+ review_details: true
16
+ commit_status: true
17
+ fail_commit_status: true
18
+ collapse_walkthrough: true
19
+ changed_files_summary: true
20
+ sequence_diagrams: false
21
+ estimate_code_review_effort: false
22
+ poem: false
23
+ in_progress_fortune: false
24
+ suggested_labels: false
25
+ suggested_reviewers: false
26
+ abort_on_close: true
27
+ auto_review:
28
+ enabled: true
29
+ drafts: false
30
+ auto_incremental_review: true
31
+ auto_pause_after_reviewed_commits: 0
32
+ pre_merge_checks:
33
+ title:
34
+ mode: warning
35
+ requirements: >-
36
+ A plain imperative sentence in sentence case, such as "Add the hub foundation". No type prefix such as
37
+ "feat:" or "fix:", no scope in brackets, no issue number and no trailing period.
38
+ description:
39
+ mode: warning
40
+ tools:
41
+ markdownlint:
42
+ enabled: false
43
+ yamllint:
44
+ enabled: false
45
+ pylint:
46
+ enabled: false
47
+ flake8:
48
+ enabled: false
49
+ path_instructions:
50
+ - path: "**/*.{py,go}"
51
+ instructions: >-
52
+ Comments: flag any comment that restates what the code does, describes a change ("now uses", "fixed",
53
+ "changed to", "updated to") or runs longer than two lines. A comment is only justified for a reason the code
54
+ cannot show, such as a workaround, a non-obvious constraint or a reference to an issue. Docstrings belong
55
+ only on public API and say what a caller needs to know, not how it works inside. Linter directives such as
56
+ noqa, nolint and type: ignore are fine.
57
+ - path: "**/*.py"
58
+ instructions: >-
59
+ Python 3.12, checked by pyright in strict mode and by ruff, so leave formatting and import order to them.
60
+ Flag Any leaking into public signatures, casts and "type: ignore" without a stated reason, and missing return
61
+ types. In async code flag blocking calls (time.sleep, synchronous file or network I/O, subprocess.run),
62
+ tasks created without keeping a reference or handling their exceptions, and locks held across awaits that
63
+ call the network. Flag "except Exception" or bare except that hides failures, mutable default arguments,
64
+ and work done at import time. Tests check behaviour through public interfaces, not private attributes, and
65
+ never wait on wall-clock time without a timeout.
66
+ - path: ".github/workflows/**"
67
+ instructions: >-
68
+ GitHub Actions. Every third-party action and every reusable workflow is pinned to a full 40-character commit
69
+ SHA with the version as a trailing comment (uses: owner/repo@<sha> # v1.2.3); flag tags, branches and short
70
+ SHAs. The workflow sets "permissions: {}" at the top and each job grants only what it needs; flag anything
71
+ broader. No ${{ }} expression is expanded inside a run: script; values reach the shell through env:. Every
72
+ actions/checkout sets persist-credentials: false unless a later step pushes. The CI workflow ends with a
73
+ job named "CI Done" that needs every other job and passes toJSON(needs) to the shared ci-done action; flag a
74
+ job missing from its needs. Pull request runs may cancel each other, runs on main must not.
75
+ - path: "**/*.md"
76
+ instructions: >-
77
+ Documentation is short, plain English for someone who runs or uses the project. Flag statements that no
78
+ longer match the code or workflows in the same pull request, commands that would not work as written, and
79
+ promotional language.
80
+ - path: "src/librebots/kit/**"
81
+ instructions: >-
82
+ The shared toolbox every Libre Bot uses, published as librebots-kit. It is not a framework: nothing may run
83
+ at import time or in the background unless the bot calls it or loads an extension by name. Public functions
84
+ and classes are typed and have short docstrings. User-facing text comes from the Fluent catalogs, never from
85
+ hard-coded strings, and every key exists in every language. Replies are Components V2 containers built with
86
+ risa directly, with no kit helper in between, and look like every other bot's: an accent bar in the bot's
87
+ colour (#E24B4A for errors), a ### title, one or two sentences, at most one row of buttons at the bottom, and
88
+ set-up replies, errors and confirmations visible to the caller only. A process acts only for the guilds of
89
+ its own shards; flag code that assumes one process sees every guild. Only Discord ids are stored or sent to
90
+ the hub; flag logging or storing message contents, user names or tokens. Changes to public names need a
91
+ major version once 1.0 is out.
92
+ - path: "src/librebots/kit/ext/**"
93
+ instructions: >-
94
+ Extensions keep their logic in the command, listener or handler itself; a separate function only when
95
+ several of them share it. Their tests drive them through lightbulb's and risa's real paths with mocked
96
+ Discord objects; flag tests that reach Discord or the network.
97
+ - path: "tests/**"
98
+ instructions: >-
99
+ Tests run against an in-process fake of the hub, never against Discord or the network. Flag sleeps used for
100
+ synchronisation and tests that only assert that a call did not raise.
101
+
102
+ chat:
103
+ art: false
104
+
105
+ knowledge_base:
106
+ learnings:
107
+ scope: global
108
+ web_search:
109
+ enabled: true
110
+ linked_repositories:
111
+ - repository: libre-bots/hub
112
+ instructions: >-
113
+ The kit calls the hub through the librebots-hub client. Check calls, request fields and error handling
114
+ against the service definitions in proto/ and the client in clients/python.
@@ -0,0 +1,10 @@
1
+ changelog:
2
+ categories:
3
+ - title: New
4
+ labels: [feature]
5
+ - title: Fixed
6
+ labels: [fix]
7
+ - title: Dependencies
8
+ labels: [dependencies]
9
+ - title: Other
10
+ labels: ["*"]
@@ -0,0 +1,47 @@
1
+ name: ci
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions: {}
9
+
10
+ concurrency:
11
+ group: ci-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
12
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
13
+
14
+ jobs:
15
+ lint:
16
+ runs-on: ubuntu-latest
17
+ permissions:
18
+ contents: read
19
+ steps:
20
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
21
+ with:
22
+ persist-credentials: false
23
+ - uses: jdx/mise-action@924e7c586e33d7d4bae9c14e26c5d22e2beb6e78 # v5.3.0
24
+ - run: make lint
25
+
26
+ test:
27
+ runs-on: ubuntu-latest
28
+ permissions:
29
+ contents: read
30
+ steps:
31
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
32
+ with:
33
+ persist-credentials: false
34
+ - uses: jdx/mise-action@924e7c586e33d7d4bae9c14e26c5d22e2beb6e78 # v5.3.0
35
+ - run: make test
36
+
37
+ ci-done:
38
+ name: CI Done
39
+ if: ${{ always() }}
40
+ needs: [lint, test]
41
+ runs-on: ubuntu-latest
42
+ permissions: {}
43
+ steps:
44
+ - name: Check the results
45
+ uses: libre-bots/.github/actions/ci-done@4ceec5ca66f3e4ad2b85a03f24d14b281bbede0e # v0.1.0
46
+ with:
47
+ needs: ${{ toJSON(needs) }}
@@ -0,0 +1,65 @@
1
+ name: release
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ bump:
7
+ description: Version bump.
8
+ type: choice
9
+ options: [patch, minor, major]
10
+ default: patch
11
+ prerelease:
12
+ description: Create a release candidate.
13
+ type: boolean
14
+ default: false
15
+
16
+ concurrency: release
17
+
18
+ permissions: {}
19
+
20
+ jobs:
21
+ prepare:
22
+ permissions:
23
+ contents: write
24
+ packages: write
25
+ checks: read
26
+ uses: libre-bots/.github/.github/workflows/release-prepare.yml@4ceec5ca66f3e4ad2b85a03f24d14b281bbede0e # v0.1.0
27
+ with:
28
+ bump: ${{ inputs.bump }}
29
+ prerelease: ${{ inputs.prerelease }}
30
+ python-projects: .:librebots.kit
31
+
32
+ pypi:
33
+ needs: prepare
34
+ runs-on: ubuntu-latest
35
+ environment: release
36
+ permissions:
37
+ id-token: write
38
+ steps:
39
+ - name: Download the distributions
40
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
41
+ with:
42
+ name: python-dist
43
+ path: dist
44
+
45
+ - name: Publish to PyPI
46
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
47
+ with:
48
+ skip-existing: true
49
+
50
+ finish:
51
+ needs: [prepare, pypi]
52
+ permissions:
53
+ contents: write
54
+ packages: write
55
+ id-token: write
56
+ attestations: write
57
+ uses: libre-bots/.github/.github/workflows/release-finish.yml@4ceec5ca66f3e4ad2b85a03f24d14b281bbede0e # v0.1.0
58
+ with:
59
+ tag: ${{ needs.prepare.outputs.tag }}
60
+ version: ${{ needs.prepare.outputs.version }}
61
+ python-version: ${{ needs.prepare.outputs.python-version }}
62
+ previous-tag: ${{ needs.prepare.outputs.previous-tag }}
63
+ prerelease: ${{ needs.prepare.outputs.prerelease }}
64
+ images: ${{ needs.prepare.outputs.images }}
65
+ python-distributions: librebots-kit
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ __pycache__/
3
+ .DS_Store
4
+ .idea/
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Libre Bots
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,10 @@
1
+ .PHONY: lint test
2
+
3
+ lint:
4
+ uv run --locked ruff check .
5
+ uv run --locked ruff format --check .
6
+ uv run --locked pyright
7
+ actionlint
8
+
9
+ test:
10
+ uv run --locked pytest
@@ -0,0 +1,42 @@
1
+ Metadata-Version: 2.5
2
+ Name: librebots-kit
3
+ Version: 0.1.0
4
+ Summary: Shared functions and extensions every Libre Bot uses
5
+ Project-URL: Source, https://github.com/libre-bots/kit
6
+ Author: Libre Bots
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Python: >=3.12
10
+ Requires-Dist: fluent-runtime>=0.4.0
11
+ Requires-Dist: hikari-lightbulb[crontrigger]>=3.2.7
12
+ Requires-Dist: hikari-risa>=1.4.0
13
+ Requires-Dist: hikari>=2.6.0
14
+ Requires-Dist: librebots-hub>=0.1.1
15
+ Requires-Dist: msgspec>=0.22.0
16
+ Description-Content-Type: text/markdown
17
+
18
+ # Libre Bots kit
19
+
20
+ The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations,
21
+ guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code,
22
+ and nothing in it runs unless the bot names it.
23
+
24
+ ```sh
25
+ pip install librebots-kit
26
+ ```
27
+
28
+ ## Development
29
+
30
+ You need [mise](https://mise.jdx.dev).
31
+
32
+ ```sh
33
+ mise install
34
+ ```
35
+
36
+ - `make lint`: ruff, pyright and `actionlint`
37
+ - `make test`: the tests
38
+
39
+ ## Releases
40
+
41
+ A maintainer runs `release` in the Actions tab on `main` and chooses `patch`, `minor` or `major`, optionally as a
42
+ release candidate. The run publishes the package to PyPI.
@@ -0,0 +1,25 @@
1
+ # Libre Bots kit
2
+
3
+ The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations,
4
+ guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code,
5
+ and nothing in it runs unless the bot names it.
6
+
7
+ ```sh
8
+ pip install librebots-kit
9
+ ```
10
+
11
+ ## Development
12
+
13
+ You need [mise](https://mise.jdx.dev).
14
+
15
+ ```sh
16
+ mise install
17
+ ```
18
+
19
+ - `make lint`: ruff, pyright and `actionlint`
20
+ - `make test`: the tests
21
+
22
+ ## Releases
23
+
24
+ A maintainer runs `release` in the Actions tab on `main` and chooses `patch`, `minor` or `major`, optionally as a
25
+ release candidate. The run publishes the package to PyPI.
@@ -0,0 +1,3 @@
1
+ [tools]
2
+ uv = "0.13.10"
3
+ actionlint = "1.7.12"
@@ -0,0 +1,60 @@
1
+ [project]
2
+ name = "librebots-kit"
3
+ version = "0.1.0"
4
+ description = "Shared functions and extensions every Libre Bot uses"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Libre Bots" }]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "fluent-runtime>=0.4.0",
12
+ "hikari>=2.6.0",
13
+ "hikari-lightbulb[crontrigger]>=3.2.7",
14
+ "hikari-risa>=1.4.0",
15
+ "librebots-hub>=0.1.1",
16
+ "msgspec>=0.22.0",
17
+ ]
18
+
19
+ [project.urls]
20
+ Source = "https://github.com/libre-bots/kit"
21
+
22
+ [dependency-groups]
23
+ dev = [
24
+ "pyright",
25
+ "pytest",
26
+ "pytest-asyncio",
27
+ "ruff",
28
+ # 1.85.0.20261122 needs _typeshed.FloatInt, which the newest pyright does not ship yet
29
+ "types-grpcio<1.85.0.20261122",
30
+ ]
31
+
32
+ [build-system]
33
+ requires = ["hatchling"]
34
+ build-backend = "hatchling.build"
35
+
36
+ [tool.hatch.build.targets.wheel]
37
+ packages = ["src/librebots"]
38
+
39
+ [tool.pytest.ini_options]
40
+ asyncio_mode = "auto"
41
+ asyncio_default_fixture_loop_scope = "function"
42
+ testpaths = ["tests"]
43
+
44
+ [tool.ruff]
45
+ line-length = 120
46
+ target-version = "py312"
47
+
48
+ [tool.ruff.lint]
49
+ select = ["E", "F", "I", "UP", "B"]
50
+
51
+ [tool.ruff.lint.isort]
52
+ required-imports = ["from __future__ import annotations"]
53
+
54
+ [tool.pyright]
55
+ pythonVersion = "3.12"
56
+ typeCheckingMode = "strict"
57
+ include = ["src/librebots/kit", "tests"]
58
+ extraPaths = ["src"]
59
+ venvPath = "."
60
+ venv = ".venv"
@@ -0,0 +1,4 @@
1
+ {
2
+ "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3
+ "extends": ["github>libre-bots/.github//renovate/default"]
4
+ }
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from librebots.kit.bot import BotInfo
4
+ from librebots.kit.config import Config, ConfigError
5
+ from librebots.kit.guilds import GuildReporter, SyncResult
6
+ from librebots.kit.hub import Hub, HubError, HubRequestError, HubUnavailableError, call_hub, connect_hub
7
+ from librebots.kit.i18n import LOCALES, Catalog, CatalogError
8
+ from librebots.kit.privacy import Privacy
9
+
10
+ __all__ = [
11
+ "LOCALES",
12
+ "BotInfo",
13
+ "Catalog",
14
+ "CatalogError",
15
+ "Config",
16
+ "ConfigError",
17
+ "GuildReporter",
18
+ "Hub",
19
+ "HubError",
20
+ "HubRequestError",
21
+ "HubUnavailableError",
22
+ "Privacy",
23
+ "SyncResult",
24
+ "call_hub",
25
+ "connect_hub",
26
+ ]
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ import msgspec
4
+
5
+ __all__ = ["BotInfo"]
6
+
7
+
8
+ class BotInfo(msgspec.Struct, frozen=True, kw_only=True):
9
+ """What `/info` shows about the bot. Its one-line description is the text `bot-description` in the bot's files.
10
+
11
+ `hub_name` is the bot's name in the hub's `HUB_BOT_TOKENS`, such as `"starboard"`.
12
+ """
13
+
14
+ name: str
15
+ hub_name: str
16
+ version: str
17
+ accent_color: int
18
+ source_url: str
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+ from pathlib import Path
6
+ from typing import Annotated, Literal, Self
7
+ from urllib.parse import urlsplit
8
+
9
+ import msgspec
10
+
11
+ __all__ = ["Config", "ConfigError", "LogLevel"]
12
+
13
+ LogLevel = Literal["TRACE_HIKARI", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
14
+
15
+ _UINT32_MAX = 2**32 - 1
16
+ _ShardId = Annotated[int, msgspec.Meta(ge=0, le=_UINT32_MAX)]
17
+ _ShardCount = Annotated[int, msgspec.Meta(ge=1, le=_UINT32_MAX)]
18
+
19
+ _SECRETS = frozenset({"discord_token", "hub_token"})
20
+
21
+
22
+ class ConfigError(Exception):
23
+ """The environment does not describe a valid configuration."""
24
+
25
+
26
+ class Config(msgspec.Struct, frozen=True, kw_only=True, rename="upper"):
27
+ """The settings of one bot process, each field read from the environment variable of the same name in upper case."""
28
+
29
+ discord_token: str
30
+ hub_address: str
31
+ hub_token: str
32
+ hub_tls: bool
33
+ hub_ca_file: str | None = None
34
+ shard_ids: tuple[_ShardId, ...] | None = None
35
+ shard_count: _ShardCount | None = None
36
+ operator_name: str
37
+ operator_contact: str
38
+ privacy_policy_url: str
39
+ support_url: str | None = None
40
+ rest_url: str | None = None
41
+ log_level: LogLevel = "INFO"
42
+
43
+ @classmethod
44
+ def from_env(cls, environ: Mapping[str, str] | None = None) -> Self:
45
+ """Read the configuration from `environ`, by default `os.environ`.
46
+
47
+ `DISCORD_TOKEN` and `HUB_TOKEN` can instead be read from the file a `_FILE` variable names. Raises
48
+ `ConfigError` on the first problem.
49
+ """
50
+ values = _collect(os.environ if environ is None else environ)
51
+ try:
52
+ return msgspec.convert(values, cls, strict=False)
53
+ except msgspec.ValidationError as exc:
54
+ raise ConfigError(str(exc)) from exc
55
+
56
+ def __post_init__(self) -> None:
57
+ if (self.shard_ids is None) != (self.shard_count is None):
58
+ raise ValueError("Set SHARD_IDS and SHARD_COUNT together, or neither")
59
+ if self.shard_ids is not None and self.shard_count is not None:
60
+ if len(set(self.shard_ids)) != len(self.shard_ids):
61
+ raise ValueError("SHARD_IDS names a shard twice")
62
+ if max(self.shard_ids) >= self.shard_count:
63
+ raise ValueError("Every id in SHARD_IDS must be below SHARD_COUNT")
64
+ if self.hub_ca_file is not None and not self.hub_tls:
65
+ raise ValueError("HUB_CA_FILE needs HUB_TLS=true")
66
+ for name, url in (
67
+ ("PRIVACY_POLICY_URL", self.privacy_policy_url),
68
+ ("SUPPORT_URL", self.support_url),
69
+ ("REST_URL", self.rest_url),
70
+ ):
71
+ if url is not None and not _is_http_url(url):
72
+ raise ValueError(f"{name} must be an http or https URL with a host")
73
+
74
+ def __repr__(self) -> str:
75
+ fields = ", ".join(f"{name}={value!r}" for name, value in self.__rich_repr__())
76
+ return f"{type(self).__name__}({fields})"
77
+
78
+ def __rich_repr__(self) -> list[tuple[str, object]]:
79
+ return [(name, "***" if name in _SECRETS else getattr(self, name)) for name in self.__struct_fields__]
80
+
81
+
82
+ def _collect(environ: Mapping[str, str]) -> dict[str, str | list[str]]:
83
+ values: dict[str, str | list[str]] = {}
84
+ for field in msgspec.structs.fields(Config):
85
+ name = field.encode_name
86
+ value = _read_secret(environ, name) if field.name in _SECRETS else _clean(environ.get(name))
87
+ if value is None:
88
+ continue
89
+ if name == "SHARD_IDS":
90
+ values[name] = [part.strip() for part in value.split(",")]
91
+ elif name == "LOG_LEVEL":
92
+ values[name] = value.upper()
93
+ else:
94
+ values[name] = value
95
+ return values
96
+
97
+
98
+ def _read_secret(environ: Mapping[str, str], name: str) -> str | None:
99
+ value = _clean(environ.get(name))
100
+ path = _clean(environ.get(f"{name}_FILE"))
101
+ if path is None:
102
+ return value
103
+ if value is not None:
104
+ raise ConfigError(f"Set {name} or {name}_FILE, not both")
105
+ try:
106
+ content = Path(path).read_text(encoding="utf-8")
107
+ except (OSError, UnicodeDecodeError) as exc:
108
+ raise ConfigError(f"Cannot read {name}_FILE: {exc}") from exc
109
+ secret = _clean(content)
110
+ if secret is None:
111
+ raise ConfigError(f"{name}_FILE names an empty file")
112
+ return secret
113
+
114
+
115
+ def _is_http_url(url: str) -> bool:
116
+ if any(char.isspace() for char in url):
117
+ return False
118
+ try:
119
+ parts = urlsplit(url)
120
+ return parts.scheme in {"http", "https"} and bool(parts.hostname) and (parts.port is None or parts.port > 0)
121
+ except ValueError:
122
+ return False
123
+
124
+
125
+ def _clean(value: str | None) -> str | None:
126
+ if value is None:
127
+ return None
128
+ return value.strip() or None
@@ -0,0 +1 @@
1
+ from __future__ import annotations