pymcsc 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.
pymcsc-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: pymcsc
3
+ Version: 0.1.0
4
+ Summary: Create, run and manage Minecraft servers (Vanilla, Paper, Forge) from Python
5
+ Author: ddavidel
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: requests
9
+ Requires-Dist: psutil
10
+ Requires-Dist: pyyaml
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest; extra == "dev"
13
+ Requires-Dist: pytest-asyncio; extra == "dev"
14
+
15
+ # mcsc
16
+
17
+ Python library to create, run and manage Minecraft servers (Vanilla, Paper, Forge 1.17+).
18
+ It is the server-management core of [Minecraft Server Creator](https://github.com/ddavidel/minecraft-server-creator),
19
+ with no GUI dependency: no NiceGUI, no translations, no telemetry. Hook those up in the app
20
+ through listeners and exceptions.
21
+
22
+ Requires Python 3.12+ and Java on the machine that runs the servers.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pip install pymcsc
28
+ ```
29
+
30
+ The package is published on PyPI as `pymcsc`, but it is imported as `mcsc`.
31
+
32
+ For development:
33
+
34
+ ```bash
35
+ pip install -e ".[dev]"
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ ```python
41
+ import asyncio
42
+ from mcsc import ServerManager, ServerType
43
+
44
+ manager = ServerManager("data/servers") # registry: data/servers/servers.json
45
+ manager.load()
46
+
47
+ server = manager.create(
48
+ "Survival", "1.21.4", ServerType.PAPER,
49
+ accept_eula=True, ram_gb=4,
50
+ )
51
+
52
+ async def main():
53
+ server.add_output_listener(lambda srv, line: print(line))
54
+ server.add_state_listener(lambda srv, old, new: print(f"{old} -> {new}"))
55
+
56
+ await server.start() # returns once the process is spawned
57
+ await server.send_command("say hello")
58
+ await server.stop() # "stop", then kill after the timeout
59
+
60
+ asyncio.run(main())
61
+ ```
62
+
63
+ ### Main pieces
64
+
65
+ | Module | What it does |
66
+ |---|---|
67
+ | `ServerManager` | Registry of servers: `load`, `save`, `create` / `create_async`, `register`, `get`, `find`, `delete`, `stop_all` |
68
+ | `MinecraftServer` (`VanillaServer`, `PaperServer`, `ForgeServer`) | One server: `install`, `start`, `stop`, `kill`, `restart`, `wait`, `send_command`, `state`, `output`, `monitor`, config files |
69
+ | `ServerConfig` | Persistent settings (dataclass); `to_dict` / `from_dict` (also reads the legacy `servers.json`) |
70
+ | `ServerType`, `ServerState` | Enums. `ServerType` values match the legacy `jar_type` |
71
+ | `VersionCatalog` | Available versions and download URLs per server type |
72
+ | `ProcessMonitor` / `ResourceUsage` | RAM/CPU/disk usage of the server process tree (`server.monitor.usage`) |
73
+ | `mcsc.files` | Read/write `.properties`, `.yml`, `.json` |
74
+ | `mcsc.system` | `total_ram_gb`, `suggested_ram_gb` |
75
+ | `mcsc.exceptions` | `MCSCError` and subclasses |
76
+
77
+ ### Server lifecycle
78
+
79
+ `STOPPED -> STARTING -> RUNNING -> STOPPING -> STOPPED`. `RUNNING` is reached when the
80
+ server prints its `Done (...)!` line. `start()` refuses to run until the EULA is accepted
81
+ (`EulaNotAcceptedError`).
82
+
83
+ Forge servers are launched with Java directly using the installer's argument files
84
+ (the same thing `run.bat`/`run.sh` do), so they work on every OS and `ram_gb` is always applied.
85
+
86
+ ### Config files
87
+
88
+ ```python
89
+ server.available_config_files() # e.g. ["server.properties", "bukkit.yml", "spigot.yml"]
90
+ props = server.read_properties()
91
+ props["motd"] = "Hello"
92
+ server.write_properties(props)
93
+ data = server.read_config("spigot.yml")
94
+ server.write_config("spigot.yml", data)
95
+ ```
96
+
97
+ ### Logging
98
+
99
+ The library logs on the `mcsc` logger and installs no handlers. Configure it from the app:
100
+
101
+ ```python
102
+ import logging
103
+ logging.getLogger("mcsc").setLevel(logging.INFO)
104
+ ```
105
+
106
+ ## Migrating from minecraft-server-creator
107
+
108
+ | Old (`mcsc.modules...`) | New |
109
+ |---|---|
110
+ | `servers.models.MinecraftServer` | `mcsc.MinecraftServer` |
111
+ | `servers.java.JavaServer` | `mcsc.VanillaServer` |
112
+ | `servers.utils.TYPE_TO_CLASS` | `mcsc.servers.SERVER_CLASSES` / `server_from_config` |
113
+ | `server_list`, `global_settings`, `get_server_list()` | `ServerManager` instance |
114
+ | `servers.utils.load_servers()` | `ServerManager(SERVER_DIR, SERVERS_JSON_PATH).load()` |
115
+ | `servers.utils.create_server(settings)` | `manager.create(...)` / `await manager.create_async(...)` |
116
+ | `get_server_by_uuid(uuid)` | `manager.get(id)` / `manager.find(id)` |
117
+ | `full_stop()` | `await manager.stop_all()` |
118
+ | `server.delete(delete_dir)` | `manager.delete(server, delete_files=...)` |
119
+ | `server.save()` | `manager.save()` after editing `server.config` |
120
+ | `server.settings["dedicated_ram"]`, `["jar_type"]`, `["uuid"]`, `["folder_path"]` | `server.config.ram_gb`, `.server_type`, `.id`, `.path` |
121
+ | `server.running` / `starting` / `stopping`, `status` | `server.state` (`ServerState`), `server.is_active` |
122
+ | `server.log = ui.log` | `server.add_output_listener(lambda s, line: log.push(line))`; history in `server.output` |
123
+ | `server.console_writer(cmd)` | `await server.send_command(cmd)` |
124
+ | `await server.start()` (returned at exit) | `await server.start()` (returns at spawn) + `await server.wait()` |
125
+ | `server.monitor.ram_usage` | `server.monitor.usage.ram_mb` (also `cpu_percent`, `disk_read_mb`, `disk_write_mb`) |
126
+ | `load_server_properties()` / `save_server_properties(editor)` | `read_properties()` / `write_properties(dict)` |
127
+ | `PaperServer.load_yml` / `save_yml(filename, editor)` | `read_config(name)` / `write_config(name, data)` |
128
+ | `modules.utils.JarUrl`, `load_*_versions()` | `VersionCatalog` (`versions`, `latest`, `download_url`) |
129
+ | `get_system_total_ram`, `get_suggested_ram` | `mcsc.total_ram_gb`, `mcsc.suggested_ram_gb` |
130
+ | `modules.classes.ProcessMonitor` | `mcsc.ProcessMonitor` |
131
+
132
+ Telemetry (`server_start`, `server_stop`, ...) moves to the app: send it from a state listener.
pymcsc-0.1.0/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # mcsc
2
+
3
+ Python library to create, run and manage Minecraft servers (Vanilla, Paper, Forge 1.17+).
4
+ It is the server-management core of [Minecraft Server Creator](https://github.com/ddavidel/minecraft-server-creator),
5
+ with no GUI dependency: no NiceGUI, no translations, no telemetry. Hook those up in the app
6
+ through listeners and exceptions.
7
+
8
+ Requires Python 3.12+ and Java on the machine that runs the servers.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ pip install pymcsc
14
+ ```
15
+
16
+ The package is published on PyPI as `pymcsc`, but it is imported as `mcsc`.
17
+
18
+ For development:
19
+
20
+ ```bash
21
+ pip install -e ".[dev]"
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ```python
27
+ import asyncio
28
+ from mcsc import ServerManager, ServerType
29
+
30
+ manager = ServerManager("data/servers") # registry: data/servers/servers.json
31
+ manager.load()
32
+
33
+ server = manager.create(
34
+ "Survival", "1.21.4", ServerType.PAPER,
35
+ accept_eula=True, ram_gb=4,
36
+ )
37
+
38
+ async def main():
39
+ server.add_output_listener(lambda srv, line: print(line))
40
+ server.add_state_listener(lambda srv, old, new: print(f"{old} -> {new}"))
41
+
42
+ await server.start() # returns once the process is spawned
43
+ await server.send_command("say hello")
44
+ await server.stop() # "stop", then kill after the timeout
45
+
46
+ asyncio.run(main())
47
+ ```
48
+
49
+ ### Main pieces
50
+
51
+ | Module | What it does |
52
+ |---|---|
53
+ | `ServerManager` | Registry of servers: `load`, `save`, `create` / `create_async`, `register`, `get`, `find`, `delete`, `stop_all` |
54
+ | `MinecraftServer` (`VanillaServer`, `PaperServer`, `ForgeServer`) | One server: `install`, `start`, `stop`, `kill`, `restart`, `wait`, `send_command`, `state`, `output`, `monitor`, config files |
55
+ | `ServerConfig` | Persistent settings (dataclass); `to_dict` / `from_dict` (also reads the legacy `servers.json`) |
56
+ | `ServerType`, `ServerState` | Enums. `ServerType` values match the legacy `jar_type` |
57
+ | `VersionCatalog` | Available versions and download URLs per server type |
58
+ | `ProcessMonitor` / `ResourceUsage` | RAM/CPU/disk usage of the server process tree (`server.monitor.usage`) |
59
+ | `mcsc.files` | Read/write `.properties`, `.yml`, `.json` |
60
+ | `mcsc.system` | `total_ram_gb`, `suggested_ram_gb` |
61
+ | `mcsc.exceptions` | `MCSCError` and subclasses |
62
+
63
+ ### Server lifecycle
64
+
65
+ `STOPPED -> STARTING -> RUNNING -> STOPPING -> STOPPED`. `RUNNING` is reached when the
66
+ server prints its `Done (...)!` line. `start()` refuses to run until the EULA is accepted
67
+ (`EulaNotAcceptedError`).
68
+
69
+ Forge servers are launched with Java directly using the installer's argument files
70
+ (the same thing `run.bat`/`run.sh` do), so they work on every OS and `ram_gb` is always applied.
71
+
72
+ ### Config files
73
+
74
+ ```python
75
+ server.available_config_files() # e.g. ["server.properties", "bukkit.yml", "spigot.yml"]
76
+ props = server.read_properties()
77
+ props["motd"] = "Hello"
78
+ server.write_properties(props)
79
+ data = server.read_config("spigot.yml")
80
+ server.write_config("spigot.yml", data)
81
+ ```
82
+
83
+ ### Logging
84
+
85
+ The library logs on the `mcsc` logger and installs no handlers. Configure it from the app:
86
+
87
+ ```python
88
+ import logging
89
+ logging.getLogger("mcsc").setLevel(logging.INFO)
90
+ ```
91
+
92
+ ## Migrating from minecraft-server-creator
93
+
94
+ | Old (`mcsc.modules...`) | New |
95
+ |---|---|
96
+ | `servers.models.MinecraftServer` | `mcsc.MinecraftServer` |
97
+ | `servers.java.JavaServer` | `mcsc.VanillaServer` |
98
+ | `servers.utils.TYPE_TO_CLASS` | `mcsc.servers.SERVER_CLASSES` / `server_from_config` |
99
+ | `server_list`, `global_settings`, `get_server_list()` | `ServerManager` instance |
100
+ | `servers.utils.load_servers()` | `ServerManager(SERVER_DIR, SERVERS_JSON_PATH).load()` |
101
+ | `servers.utils.create_server(settings)` | `manager.create(...)` / `await manager.create_async(...)` |
102
+ | `get_server_by_uuid(uuid)` | `manager.get(id)` / `manager.find(id)` |
103
+ | `full_stop()` | `await manager.stop_all()` |
104
+ | `server.delete(delete_dir)` | `manager.delete(server, delete_files=...)` |
105
+ | `server.save()` | `manager.save()` after editing `server.config` |
106
+ | `server.settings["dedicated_ram"]`, `["jar_type"]`, `["uuid"]`, `["folder_path"]` | `server.config.ram_gb`, `.server_type`, `.id`, `.path` |
107
+ | `server.running` / `starting` / `stopping`, `status` | `server.state` (`ServerState`), `server.is_active` |
108
+ | `server.log = ui.log` | `server.add_output_listener(lambda s, line: log.push(line))`; history in `server.output` |
109
+ | `server.console_writer(cmd)` | `await server.send_command(cmd)` |
110
+ | `await server.start()` (returned at exit) | `await server.start()` (returns at spawn) + `await server.wait()` |
111
+ | `server.monitor.ram_usage` | `server.monitor.usage.ram_mb` (also `cpu_percent`, `disk_read_mb`, `disk_write_mb`) |
112
+ | `load_server_properties()` / `save_server_properties(editor)` | `read_properties()` / `write_properties(dict)` |
113
+ | `PaperServer.load_yml` / `save_yml(filename, editor)` | `read_config(name)` / `write_config(name, data)` |
114
+ | `modules.utils.JarUrl`, `load_*_versions()` | `VersionCatalog` (`versions`, `latest`, `download_url`) |
115
+ | `get_system_total_ram`, `get_suggested_ram` | `mcsc.total_ram_gb`, `mcsc.suggested_ram_gb` |
116
+ | `modules.classes.ProcessMonitor` | `mcsc.ProcessMonitor` |
117
+
118
+ Telemetry (`server_start`, `server_stop`, ...) moves to the app: send it from a state listener.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "pymcsc"
7
+ version = "0.1.0"
8
+ description = "Create, run and manage Minecraft servers (Vanilla, Paper, Forge) from Python"
9
+ authors = [{ name = "ddavidel" }]
10
+ readme = "README.md"
11
+ requires-python = ">=3.12"
12
+ dependencies = ["requests", "psutil", "pyyaml"]
13
+
14
+ [project.optional-dependencies]
15
+ dev = ["pytest", "pytest-asyncio"]
16
+
17
+ [tool.setuptools]
18
+ package-dir = { "" = "src" }
19
+
20
+ [tool.setuptools.packages.find]
21
+ where = ["src"]
22
+
23
+ [tool.setuptools.package-data]
24
+ mcsc = ["py.typed"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
28
+ asyncio_mode = "auto"
29
+ asyncio_default_fixture_loop_scope = "function"
pymcsc-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,79 @@
1
+ """mcsc - create, run and manage Minecraft servers.
2
+
3
+ Quick start::
4
+
5
+ import asyncio
6
+ from mcsc import ServerManager, ServerType
7
+
8
+ manager = ServerManager("servers")
9
+ manager.load()
10
+ server = manager.create("My server", "1.21.4", ServerType.PAPER, accept_eula=True)
11
+
12
+ async def main():
13
+ server.add_output_listener(lambda srv, line: print(line))
14
+ await server.start()
15
+ ...
16
+ await server.stop()
17
+
18
+ asyncio.run(main())
19
+ """
20
+
21
+ import logging
22
+
23
+ from mcsc.config import ServerConfig, ServerState, ServerType
24
+ from mcsc.exceptions import (
25
+ DownloadError,
26
+ EulaNotAcceptedError,
27
+ InstallError,
28
+ JavaNotFoundError,
29
+ MCSCError,
30
+ ServerNotFoundError,
31
+ ServerNotRunningError,
32
+ ServerRunningError,
33
+ ServerStateError,
34
+ UnsupportedVersionError,
35
+ VersionNotFoundError,
36
+ )
37
+ from mcsc.manager import ServerManager
38
+ from mcsc.monitor import ProcessMonitor, ResourceUsage
39
+ from mcsc.servers import (
40
+ ForgeServer,
41
+ MinecraftServer,
42
+ PaperServer,
43
+ VanillaServer,
44
+ server_from_config,
45
+ )
46
+ from mcsc.system import suggested_ram_gb, total_ram_gb
47
+ from mcsc.versions import VersionCatalog
48
+
49
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
50
+
51
+ __version__ = "0.1.0"
52
+
53
+ __all__ = [
54
+ "DownloadError",
55
+ "EulaNotAcceptedError",
56
+ "ForgeServer",
57
+ "InstallError",
58
+ "JavaNotFoundError",
59
+ "MCSCError",
60
+ "MinecraftServer",
61
+ "PaperServer",
62
+ "ProcessMonitor",
63
+ "ResourceUsage",
64
+ "ServerConfig",
65
+ "ServerManager",
66
+ "ServerNotFoundError",
67
+ "ServerNotRunningError",
68
+ "ServerRunningError",
69
+ "ServerState",
70
+ "ServerStateError",
71
+ "ServerType",
72
+ "UnsupportedVersionError",
73
+ "VanillaServer",
74
+ "VersionCatalog",
75
+ "VersionNotFoundError",
76
+ "server_from_config",
77
+ "suggested_ram_gb",
78
+ "total_ram_gb",
79
+ ]
@@ -0,0 +1,91 @@
1
+ """Server configuration model."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field, fields
6
+ from enum import IntEnum, StrEnum
7
+ from pathlib import Path
8
+ from typing import Any
9
+ from uuid import uuid4
10
+
11
+
12
+ class ServerType(IntEnum):
13
+ """Supported server distributions.
14
+
15
+ Values match the legacy ``jar_type`` integers used by minecraft-server-creator.
16
+ """
17
+
18
+ VANILLA = 0
19
+ PAPER = 1
20
+ FORGE = 2
21
+
22
+ @property
23
+ def label(self) -> str:
24
+ """Display name of the server type."""
25
+ return self.name.capitalize()
26
+
27
+
28
+ class ServerState(StrEnum):
29
+ """Lifecycle state of a server process."""
30
+
31
+ STOPPED = "stopped"
32
+ STARTING = "starting"
33
+ RUNNING = "running"
34
+ STOPPING = "stopping"
35
+
36
+
37
+ # Legacy keys (minecraft-server-creator servers.json) -> ServerConfig fields
38
+ _LEGACY_KEYS = {
39
+ "jar_type": "server_type",
40
+ "dedicated_ram": "ram_gb",
41
+ "folder_path": "path",
42
+ "uuid": "id",
43
+ }
44
+
45
+
46
+ @dataclass
47
+ class ServerConfig:
48
+ """Persistent settings of a single server.
49
+
50
+ ``path`` is the server's root folder. It is assigned by
51
+ :class:`mcsc.ServerManager` when the server is created.
52
+ """
53
+
54
+ name: str
55
+ version: str
56
+ server_type: ServerType = ServerType.VANILLA
57
+ ram_gb: int = 2
58
+ port: int = 25565
59
+ address: str | None = None
60
+ java_path: str = "java"
61
+ jvm_args: list[str] = field(default_factory=list)
62
+ id: str = field(default_factory=lambda: str(uuid4()))
63
+ path: Path | None = None
64
+
65
+ def __post_init__(self) -> None:
66
+ self.server_type = ServerType(self.server_type)
67
+ self.ram_gb = int(self.ram_gb)
68
+ self.port = int(self.port)
69
+ if self.path is not None:
70
+ self.path = Path(self.path)
71
+ if self.address in ("", "default"):
72
+ self.address = None
73
+
74
+ def to_dict(self) -> dict[str, Any]:
75
+ """JSON-serializable representation."""
76
+ data = asdict(self)
77
+ data["server_type"] = int(self.server_type)
78
+ data["path"] = str(self.path) if self.path is not None else None
79
+ return data
80
+
81
+ @classmethod
82
+ def from_dict(cls, data: dict[str, Any]) -> ServerConfig:
83
+ """Build a config from :meth:`to_dict` output or a legacy servers.json entry.
84
+
85
+ Unknown keys are ignored.
86
+ """
87
+ normalized: dict[str, Any] = {}
88
+ for key, value in data.items():
89
+ normalized.setdefault(_LEGACY_KEYS.get(key, key), value)
90
+ known = {f.name for f in fields(cls)}
91
+ return cls(**{k: v for k, v in normalized.items() if k in known})
@@ -0,0 +1,38 @@
1
+ """HTTP download helper."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import requests
10
+
11
+ from mcsc.exceptions import DownloadError
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def download_file(url: str, destination: Path, *, timeout: float = 30) -> Path:
17
+ """Stream ``url`` to ``destination``.
18
+
19
+ Writes to a temporary file first, so a failed download never leaves a
20
+ truncated file at ``destination``.
21
+ """
22
+ destination = Path(destination)
23
+ tmp = destination.with_name(destination.name + ".part")
24
+ try:
25
+ with requests.get(url, stream=True, timeout=timeout) as response:
26
+ response.raise_for_status()
27
+ with open(tmp, "wb") as file:
28
+ for chunk in response.iter_content(chunk_size=64 * 1024):
29
+ file.write(chunk)
30
+ os.replace(tmp, destination)
31
+ except requests.RequestException as e:
32
+ tmp.unlink(missing_ok=True)
33
+ raise DownloadError(f"Error downloading {url}: {e}") from e
34
+ except OSError:
35
+ tmp.unlink(missing_ok=True)
36
+ raise
37
+ logger.info("Downloaded %s to %s", url, destination)
38
+ return destination
@@ -0,0 +1,49 @@
1
+ """Exceptions raised by mcsc.
2
+
3
+ Messages are plain English; applications that need localized messages
4
+ should catch these types and translate them.
5
+ """
6
+
7
+
8
+ class MCSCError(Exception):
9
+ """Base class for every error raised by mcsc."""
10
+
11
+
12
+ class ServerNotFoundError(MCSCError, KeyError):
13
+ """No server with the requested id is registered."""
14
+
15
+
16
+ class ServerStateError(MCSCError):
17
+ """The operation is not allowed in the server's current state."""
18
+
19
+
20
+ class ServerRunningError(ServerStateError):
21
+ """The operation requires the server to be stopped."""
22
+
23
+
24
+ class ServerNotRunningError(ServerStateError):
25
+ """The operation requires the server to be running."""
26
+
27
+
28
+ class EulaNotAcceptedError(ServerStateError):
29
+ """The server cannot start until the Minecraft EULA is accepted."""
30
+
31
+
32
+ class JavaNotFoundError(MCSCError, FileNotFoundError):
33
+ """The configured Java executable could not be found."""
34
+
35
+
36
+ class VersionNotFoundError(MCSCError, LookupError):
37
+ """The requested Minecraft version is not available for the server type."""
38
+
39
+
40
+ class UnsupportedVersionError(MCSCError):
41
+ """The version is known, but mcsc cannot install or run it."""
42
+
43
+
44
+ class DownloadError(MCSCError):
45
+ """A file could not be downloaded."""
46
+
47
+
48
+ class InstallError(MCSCError):
49
+ """Server installation failed."""
@@ -0,0 +1,81 @@
1
+ """Readers and writers for server configuration files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+
12
+ def read_properties(path: Path) -> dict[str, str]:
13
+ """Parse a Java ``.properties`` file (``key=value`` lines, ``#`` comments)."""
14
+ result: dict[str, str] = {}
15
+ with open(path, encoding="utf-8") as file:
16
+ for raw in file:
17
+ line = raw.strip()
18
+ if not line or line.startswith(("#", "!")):
19
+ continue
20
+ key, sep, value = line.partition("=")
21
+ if sep:
22
+ result[key.strip()] = value.strip()
23
+ return result
24
+
25
+
26
+ def write_properties(path: Path, values: dict[str, Any]) -> None:
27
+ """Write ``values`` as ``key=value`` lines, keeping the file's leading comments."""
28
+ path = Path(path)
29
+ header: list[str] = []
30
+ if path.exists():
31
+ with open(path, encoding="utf-8") as file:
32
+ for line in file:
33
+ if not line.startswith("#"):
34
+ break
35
+ header.append(line.rstrip("\n"))
36
+ with open(path, "w", encoding="utf-8") as file:
37
+ for line in header:
38
+ file.write(line + "\n")
39
+ for key, value in values.items():
40
+ if isinstance(value, bool):
41
+ value = str(value).lower()
42
+ file.write(f"{key}={value}\n")
43
+
44
+
45
+ def read_yaml(path: Path) -> Any:
46
+ """Load a YAML document (``{}`` for an empty file)."""
47
+ with open(path, encoding="utf-8") as file:
48
+ return yaml.safe_load(file) or {}
49
+
50
+
51
+ def write_yaml(path: Path, data: Any) -> None:
52
+ """Dump ``data`` as YAML, preserving key order."""
53
+ with open(path, "w", encoding="utf-8") as file:
54
+ yaml.safe_dump(data, file, sort_keys=False, allow_unicode=True)
55
+
56
+
57
+ def read_config_file(path: Path) -> Any:
58
+ """Read a config file, choosing the format from the extension."""
59
+ suffix = Path(path).suffix.lower()
60
+ if suffix == ".properties":
61
+ return read_properties(path)
62
+ if suffix in (".yml", ".yaml"):
63
+ return read_yaml(path)
64
+ if suffix == ".json":
65
+ with open(path, encoding="utf-8") as file:
66
+ return json.load(file)
67
+ raise ValueError(f"Unsupported config file type: {path}")
68
+
69
+
70
+ def write_config_file(path: Path, data: Any) -> None:
71
+ """Write a config file, choosing the format from the extension."""
72
+ suffix = Path(path).suffix.lower()
73
+ if suffix == ".properties":
74
+ write_properties(path, data)
75
+ elif suffix in (".yml", ".yaml"):
76
+ write_yaml(path, data)
77
+ elif suffix == ".json":
78
+ with open(path, "w", encoding="utf-8") as file:
79
+ json.dump(data, file, indent=2)
80
+ else:
81
+ raise ValueError(f"Unsupported config file type: {path}")