mcward-cli 1.5.0__tar.gz → 2.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.
Files changed (41) hide show
  1. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/PKG-INFO +4 -3
  2. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/README.md +1 -1
  3. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/pyproject.toml +9 -6
  4. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/__init__.py +0 -1
  5. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/commands/__init__.py +0 -2
  6. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/commands/bench.py +14 -3
  7. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/commands/daemon.py +4 -6
  8. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/commands/install.py +0 -2
  9. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/commands/list.py +0 -2
  10. mcward_cli-2.0.0/src/mcward/cli/commands/test.py +67 -0
  11. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/datapacks.py +2 -9
  12. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/environments.py +26 -2
  13. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/reporters/github.py +6 -2
  14. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/reporters/live.py +13 -3
  15. mcward_cli-2.0.0/src/mcward/cli/session.py +190 -0
  16. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/ui.py +6 -2
  17. mcward_cli-2.0.0/src/mcward/cli/watch.py +178 -0
  18. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/__init__.py +26 -4
  19. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/html.py +1 -2
  20. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/lcov.py +1 -5
  21. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/test_bench.py +25 -1
  22. mcward_cli-2.0.0/tests/test_cli.py +121 -0
  23. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/test_coverage_report.py +1 -2
  24. mcward_cli-2.0.0/tests/test_environments.py +144 -0
  25. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/test_github.py +23 -0
  26. mcward_cli-2.0.0/tests/test_watch.py +141 -0
  27. mcward_cli-1.5.0/tests/test_reports.py → mcward_cli-2.0.0/tests/test_writers.py +30 -7
  28. mcward_cli-1.5.0/src/mcward/cli/commands/test.py +0 -94
  29. mcward_cli-1.5.0/src/mcward/cli/session.py +0 -62
  30. mcward_cli-1.5.0/tests/test_cli.py +0 -58
  31. mcward_cli-1.5.0/tests/test_environments.py +0 -19
  32. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/.gitignore +0 -0
  33. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/reporters/__init__.py +0 -0
  34. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/reporters/bench.py +0 -0
  35. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/src/mcward/cli/reporters/coverage.py +0 -0
  36. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/coverage.css +0 -0
  37. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/coverage.js +0 -0
  38. {mcward_cli-1.5.0/src/mcward/cli/reports → mcward_cli-2.0.0/src/mcward/cli/writers}/junit.py +0 -0
  39. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/conftest.py +0 -0
  40. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/test_discovery.py +0 -0
  41. {mcward_cli-1.5.0 → mcward_cli-2.0.0}/tests/test_live.py +0 -0
@@ -1,15 +1,16 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mcward-cli
3
- Version: 1.5.0
3
+ Version: 2.0.0
4
4
  Summary: Command-line interface for Ward, a testing framework for Minecraft datapacks using mcfunction.
5
5
  Author-email: Aksiome <54895777+aksiome@users.noreply.github.com>
6
6
  License: MPL-2.0
7
7
  Requires-Python: >=3.14
8
8
  Requires-Dist: click>=8.4.0
9
- Requires-Dist: mcward-core
9
+ Requires-Dist: mcward==2.0.0
10
10
  Requires-Dist: questionary>=2.1.1
11
11
  Requires-Dist: rich-click>=1.8.0
12
12
  Requires-Dist: rich>=15.0.0
13
+ Requires-Dist: watchfiles>=1.3.0
13
14
  Description-Content-Type: text/markdown
14
15
 
15
16
  # mcward-cli
@@ -18,7 +19,7 @@ Command-line interface for [Ward](https://github.com/mcbookshelf/ward), a testin
18
19
  framework for Minecraft datapacks using mcfunction.
19
20
 
20
21
  Provides the `mcward` command: install and manage test server versions, run
21
- datapack tests with a live display, and control the Ward daemon. Most users
22
+ datapack tests with a live display, and control the test servers. Most users
22
23
  want the [`mcward`](https://pypi.org/project/mcward/) package instead:
23
24
 
24
25
  ```
@@ -4,7 +4,7 @@ Command-line interface for [Ward](https://github.com/mcbookshelf/ward), a testin
4
4
  framework for Minecraft datapacks using mcfunction.
5
5
 
6
6
  Provides the `mcward` command: install and manage test server versions, run
7
- datapack tests with a live display, and control the Ward daemon. Most users
7
+ datapack tests with a live display, and control the test servers. Most users
8
8
  want the [`mcward`](https://pypi.org/project/mcward/) package instead:
9
9
 
10
10
  ```
@@ -10,16 +10,22 @@ readme = "README.md"
10
10
  requires-python = ">=3.14"
11
11
  license = { text = "MPL-2.0" }
12
12
  authors = [{ name = "Aksiome", email = "54895777+aksiome@users.noreply.github.com" }]
13
+ # The mcward pin follows the version: `just bump python` rewrites it
13
14
  dependencies = [
14
- "mcward-core",
15
+ "mcward==2.0.0",
15
16
  "click>=8.4.0",
17
+ "questionary>=2.1.1",
16
18
  "rich>=15.0.0",
17
19
  "rich-click>=1.8.0",
18
- "questionary>=2.1.1",
20
+ "watchfiles>=1.3.0",
19
21
  ]
20
22
 
23
+ [project.scripts]
24
+ mcward = "mcward.cli:main"
25
+ ward = "mcward.cli:main"
26
+
21
27
  [tool.uv.sources]
22
- mcward-core = { workspace = true }
28
+ mcward = { workspace = true }
23
29
 
24
30
  [tool.hatch.version]
25
31
  path = "../../pyproject.toml"
@@ -27,6 +33,3 @@ pattern = '^version = "(?P<version>[^"]+)"$'
27
33
 
28
34
  [tool.hatch.build.targets.wheel]
29
35
  packages = ["src/mcward"]
30
-
31
- [tool.pytest.ini_options]
32
- addopts = "--import-mode=importlib"
@@ -33,7 +33,6 @@ class DefaultCommandGroup(click.RichGroup):
33
33
  )
34
34
  def cli() -> None:
35
35
  """Ward, testing framework for Minecraft datapacks."""
36
- pass
37
36
 
38
37
 
39
38
  cli.add_command(bench)
@@ -1,5 +1,3 @@
1
- """CLI commands."""
2
-
3
1
  from .bench import bench
4
2
  from .daemon import start, status, stop
5
3
  from .install import clean, install
@@ -1,5 +1,3 @@
1
- """The bench command."""
2
-
3
1
  import json
4
2
  import sys
5
3
  from pathlib import Path
@@ -11,6 +9,7 @@ from mcward import BenchReport, WardError, run_bench
11
9
  from ..datapacks import DEFAULT_PATTERNS, discover_datapacks, format_range
12
10
  from ..environments import manager, select_compatible, start_environments
13
11
  from ..reporters.bench import render_report, render_summary
12
+ from ..session import check_features, load_config
14
13
  from ..ui import console
15
14
 
16
15
 
@@ -54,6 +53,12 @@ from ..ui import console
54
53
  default=None,
55
54
  help="Write the results, with every sample, to a JSON file",
56
55
  )
56
+ @click.option(
57
+ "--world",
58
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
59
+ default=None,
60
+ help="Bench in a copy of this world save instead of a flat world",
61
+ )
57
62
  @click.argument("commands", nargs=-1, required=True)
58
63
  def bench(
59
64
  versions: tuple[str, ...],
@@ -62,9 +67,11 @@ def bench(
62
67
  prepare: tuple[str, ...],
63
68
  batch: int | None,
64
69
  json_path: Path | None,
70
+ world: Path | None,
65
71
  commands: tuple[str, ...],
66
72
  ) -> None:
67
73
  """Time commands on a test server and compare them."""
74
+ config = load_config(world)
68
75
  datapacks = discover_datapacks(packs if packs else DEFAULT_PATTERNS)
69
76
  if not datapacks and not versions:
70
77
  raise click.ClickException("Datapack not found. Without a pack, give a version with -v")
@@ -76,6 +83,7 @@ def bench(
76
83
 
77
84
  try:
78
85
  envs = start_environments([manager.get(v) for v in selected])
86
+ check_features(envs, worlds=config.world)
79
87
  for env in envs:
80
88
  console.print()
81
89
  if len(envs) > 1:
@@ -83,7 +91,10 @@ def bench(
83
91
 
84
92
  reports: list[BenchReport] = []
85
93
  with console.status("Running the benchmarks"):
86
- for report in run_bench(paths, env, commands, setup, prepare, batch or 0):
94
+ run = run_bench(
95
+ paths, env, commands, setup, prepare, batch or 0, world=config.world
96
+ )
97
+ for report in run:
87
98
  reports.append(report)
88
99
  for line in render_report(len(reports), report):
89
100
  console.print(line, highlight=False)
@@ -1,5 +1,3 @@
1
- """The start, stop and status commands."""
2
-
3
1
  from concurrent.futures import ThreadPoolExecutor, as_completed
4
2
 
5
3
  import rich_click as click
@@ -22,7 +20,7 @@ from ..ui import console, print_note, print_success, print_warning
22
20
  @click.command()
23
21
  @click.argument("version", required=False)
24
22
  def start(version: str | None) -> None:
25
- """Start the Ward daemon for a specific version."""
23
+ """Start the test server of a version."""
26
24
  env = get_environment(version or select_installed("Select a version to start:"))
27
25
  if isinstance(env, RunningEnvironment):
28
26
  print_warning(f"Version {env.version.name} is already running {env.process}")
@@ -34,7 +32,7 @@ def start(version: str | None) -> None:
34
32
  @click.argument("version", required=False)
35
33
  @click.option("--all", "-a", is_flag=True, help="Stop all running versions.")
36
34
  def stop(version: str | None, all: bool = False) -> None:
37
- """Stop the Ward daemon."""
35
+ """Stop a test server."""
38
36
  if not all:
39
37
  env = get_environment(version or select_running("Select a version to stop:"))
40
38
  if isinstance(env, RunningEnvironment):
@@ -71,13 +69,13 @@ def stop(version: str | None, all: bool = False) -> None:
71
69
 
72
70
  @click.command()
73
71
  def status() -> None:
74
- """Show status of running daemons."""
72
+ """Show the running test servers."""
75
73
  envs = manager.running_environments()
76
74
  if not envs:
77
75
  print_note("No versions running")
78
76
  return
79
77
 
80
- table = Table(title="Running Ward Daemons", box=box.SIMPLE)
78
+ table = Table(title="Running servers", box=box.SIMPLE)
81
79
  table.add_column("Version", style="")
82
80
  table.add_column("PID", style="dim")
83
81
  table.add_column("Port", style="dim")
@@ -1,5 +1,3 @@
1
- """The install and clean commands."""
2
-
3
1
  import rich_click as click
4
2
 
5
3
  from mcward import RunningEnvironment, UninstalledEnvironment
@@ -1,5 +1,3 @@
1
- """The list command."""
2
-
3
1
  import rich_click as click
4
2
 
5
3
  from mcward import Version
@@ -0,0 +1,67 @@
1
+ import sys
2
+ from collections.abc import Sequence
3
+ from pathlib import Path
4
+
5
+ import rich_click as click
6
+
7
+ from mcward import TestSession
8
+
9
+ from ..datapacks import DEFAULT_PATTERNS, discover_datapacks
10
+ from ..session import check_watch, load_config, rerunnable, run_session, test_options
11
+ from ..watch import watch as watch_tests
12
+ from ..writers import is_report_file, parse_coverage_report
13
+
14
+
15
+ @click.command()
16
+ @click.option(
17
+ "--pack",
18
+ "-p",
19
+ "packs",
20
+ multiple=True,
21
+ help="Datapack paths or glob patterns",
22
+ )
23
+ @test_options
24
+ def test(
25
+ versions: tuple[str, ...],
26
+ packs: tuple[str, ...],
27
+ reporter: str,
28
+ coverage: bool,
29
+ coverage_reports: tuple[str, ...],
30
+ coverage_min: float | None,
31
+ junit_xml: Path | None,
32
+ verbose: bool,
33
+ watch: bool,
34
+ world: Path | None,
35
+ selector: str,
36
+ ) -> None:
37
+ """Run datapack tests."""
38
+ check_watch(watch, reporter)
39
+ config = load_config(world)
40
+ datapacks = discover_datapacks(packs if packs else DEFAULT_PATTERNS)
41
+ if not datapacks:
42
+ raise click.ClickException("Datapack not found")
43
+ specs = [parse_coverage_report(value) for value in coverage_reports]
44
+
45
+ def run_once(selector: str, versions: Sequence[str]) -> TestSession:
46
+ return run_session(
47
+ datapacks,
48
+ versions=versions,
49
+ reporter=reporter,
50
+ selector=selector,
51
+ coverage=coverage,
52
+ coverage_specs=specs,
53
+ coverage_min=coverage_min,
54
+ junit_xml=junit_xml,
55
+ verbose=verbose,
56
+ config=config,
57
+ )
58
+
59
+ run = rerunnable(versions, run_once)
60
+ if watch:
61
+ watched = [datapack.path for datapack in datapacks]
62
+ paths = [*watched, config.world] if config.world else watched
63
+ watch_tests(
64
+ run, selector, paths, ignore=lambda path: is_report_file(path, specs, junit_xml)
65
+ )
66
+ elif run(selector).failed:
67
+ sys.exit(1)
@@ -63,11 +63,7 @@ def format_range(datapacks: Sequence[DataPack]) -> tuple[int, int]:
63
63
 
64
64
 
65
65
  def pack_resolver(datapacks: Sequence[Path]) -> FileResolver:
66
- """Resolve resources against the datapack directories themselves.
67
-
68
- Zipped datapacks never resolve: there is no file to point at inside an
69
- archive, so their failures render without a path.
70
- """
66
+ """Resolve resources to files of the pack directories; zipped packs have none."""
71
67
 
72
68
  def resolve(folder: str, resource: str) -> str | None:
73
69
  if ":" not in resource:
@@ -91,10 +87,7 @@ def workspace_path(file: Path) -> str | None:
91
87
 
92
88
 
93
89
  def _is_datapack(path: Path) -> bool:
94
- """A directory or a zip with a pack.mcmeta and a data folder at its root.
95
-
96
- The data folder tells a datapack from a resource pack, which has the same pack.mcmeta.
97
- """
90
+ """A directory or zip with a pack.mcmeta and a data folder (a resource pack has none)."""
98
91
  if path.is_dir():
99
92
  return (path / "pack.mcmeta").is_file() and (path / "data").is_dir()
100
93
  if path.suffix == ".zip" and zipfile.is_zipfile(path):
@@ -1,5 +1,6 @@
1
1
  """Environment selection and startup shared by the commands."""
2
2
 
3
+ import sys
3
4
  from collections.abc import Iterable, Sequence
4
5
  from concurrent.futures import ThreadPoolExecutor
5
6
  from itertools import groupby
@@ -11,15 +12,18 @@ from mcward import (
11
12
  Environment,
12
13
  EnvironmentManager,
13
14
  InstalledEnvironment,
15
+ InstallError,
14
16
  RunningEnvironment,
15
17
  UninstalledEnvironment,
16
18
  Version,
17
19
  VersionNotFoundError,
20
+ on_lock_wait,
18
21
  )
19
22
 
20
- from .ui import Option, console, print_note, print_success, select
23
+ from .ui import Option, console, print_note, print_success, print_warning, select
21
24
 
22
25
  manager = EnvironmentManager()
26
+ on_lock_wait(lambda directory: print_note(f"Waiting for another mcward using {directory.name}"))
23
27
 
24
28
 
25
29
  def curate_versions(versions: Iterable[Version]) -> list[Version]:
@@ -59,7 +63,8 @@ def select_installed(message: str) -> str:
59
63
 
60
64
  def select_running(message: str) -> str:
61
65
  """Prompt for a running version, skipping the prompt when only one fits."""
62
- return _select_version(manager.list_running(), message, "No versions running")
66
+ running = [env.version for env in manager.running_environments()]
67
+ return _select_version(running, message, "No versions running")
63
68
 
64
69
 
65
70
  def select_available(message: str) -> str:
@@ -85,6 +90,10 @@ def select_compatible(min_format: int, max_format: int) -> list[str]:
85
90
  if len(versions) == 1:
86
91
  return [versions[0].name]
87
92
 
93
+ if not sys.stdin.isatty():
94
+ print_note(f"Pack format range supports several major versions, testing on {len(versions)}")
95
+ return [v.name for v in versions]
96
+
88
97
  print_note("Pack format range supports multiple major versions")
89
98
  options = [Option("Use all versions", "(Recommended)", value="all")]
90
99
  options.extend(Option(f"Use {v.name} only", value=v.name) for v in versions)
@@ -113,6 +122,19 @@ def _select_version(versions: list[Version], message: str, empty: str) -> str:
113
122
  return select(message, [v.name for v in versions])
114
123
 
115
124
 
125
+ def _update_mod(env: InstalledEnvironment, installed: str, newest: str, progress: Progress) -> None:
126
+ """Bring the mod to the one a fresh install gets; a failed download keeps the old one."""
127
+ name = env.version.name
128
+ task = progress.add_task(f"Updating Ward for {name}", total=None)
129
+ try:
130
+ if env.update():
131
+ print_success(f"Updated Ward for {name}: {installed} to {newest}")
132
+ except InstallError as e:
133
+ print_warning(f"Could not update Ward for {name}, running {installed}: {e}")
134
+ finally:
135
+ progress.remove_task(task)
136
+
137
+
116
138
  def _start_environment(env: Environment, progress: Progress) -> RunningEnvironment:
117
139
  """Start a single environment, reporting steps to the shared progress."""
118
140
  if isinstance(env, UninstalledEnvironment):
@@ -120,6 +142,8 @@ def _start_environment(env: Environment, progress: Progress) -> RunningEnvironme
120
142
  env = env.install()
121
143
  progress.remove_task(task)
122
144
  print_success(f"Installed version {env.version.name}")
145
+ elif isinstance(env, InstalledEnvironment) and (outdated := manager.outdated_mod(env)):
146
+ _update_mod(env, *outdated, progress)
123
147
  if isinstance(env, InstalledEnvironment):
124
148
  task = progress.add_task(f"Starting version {env.version.name}", total=None)
125
149
  env = env.start()
@@ -25,6 +25,8 @@ def run(
25
25
  coverage: bool = False,
26
26
  verbose: bool = False,
27
27
  resolve: FileResolver | None = None,
28
+ world: Path | None = None,
29
+ origin: tuple[int, int] | None = None,
28
30
  ) -> TestSession:
29
31
  """Run tests, printing the final results view and GitHub annotations."""
30
32
  versions = [env.version for env in environments]
@@ -32,7 +34,9 @@ def run(
32
34
  resolve = resolve or pack_resolver(datapacks)
33
35
 
34
36
  # Consume the stream without rendering; it always yields a starting frame
35
- *_, session = run_tests(datapacks, environments, selector=selector, coverage=coverage)
37
+ *_, session = run_tests(
38
+ datapacks, environments, selector=selector, coverage=coverage, world=world, origin=origin
39
+ )
36
40
  console.print(render_session(session, resolve, verbose))
37
41
 
38
42
  for command in annotations(session, resolve):
@@ -70,7 +74,7 @@ def _annotate_test(result: TestResult, resolve: FileResolver) -> str:
70
74
  word = "failed" if failed else "skipped"
71
75
  title = f"{result.name} {word} on {', '.join(v.name for v in versions)}"
72
76
 
73
- file = resolve("test", result.name)
77
+ file = resolve("test", result.source)
74
78
  line = outcome.line if file else None
75
79
  level = "error" if failed else "warning"
76
80
  logs = [describe_log(log) for log in result.logs.get(versions[0], [])]
@@ -44,6 +44,8 @@ def run(
44
44
  coverage: bool = False,
45
45
  verbose: bool = False,
46
46
  resolve: FileResolver | None = None,
47
+ world: Path | None = None,
48
+ origin: tuple[int, int] | None = None,
47
49
  ) -> TestSession:
48
50
  """Run tests across running environments with a live Rich display."""
49
51
  versions = [env.version for env in environments]
@@ -53,7 +55,15 @@ def run(
53
55
  session = TestSession(versions) # rebound by every frame; bound even if none arrives
54
56
  rendered = 0.0
55
57
  with Live(console=console, refresh_per_second=10) as live:
56
- frames = run_tests(datapacks, environments, selector=selector, coverage=coverage, tick=0.1)
58
+ frames = run_tests(
59
+ datapacks,
60
+ environments,
61
+ selector=selector,
62
+ coverage=coverage,
63
+ tick=0.1,
64
+ world=world,
65
+ origin=origin,
66
+ )
57
67
  for session in frames:
58
68
  # Events can outpace the display many times over; render at frame rate
59
69
  if (now := monotonic()) - rendered < 0.1:
@@ -231,7 +241,7 @@ def _render_result(text: Text, result: TestResult, resolve: FileResolver | None
231
241
 
232
242
 
233
243
  def _render_logs(text: Text, result: TestResult, resolve: FileResolver | None = None) -> None:
234
- file = resolve("test", result.name) if resolve and result.logs else None
244
+ file = resolve("test", result.source) if resolve and result.logs else None
235
245
  for version in result.versions:
236
246
  prefix = f"{version.name}: " if len(result.versions) > 1 else ""
237
247
  for log in result.logs.get(version, ()):
@@ -246,7 +256,7 @@ def _render_failure(
246
256
  style: str,
247
257
  resolve: FileResolver | None = None,
248
258
  ) -> None:
249
- file = resolve("test", result.name) if resolve else None
259
+ file = resolve("test", result.source) if resolve else None
250
260
 
251
261
  if len(result.versions) == 1:
252
262
  message = describe_failure(result.outcomes[versions[0]], file)
@@ -0,0 +1,190 @@
1
+ """The test run that mcward test and beet test share."""
2
+
3
+ from collections.abc import Callable, Sequence
4
+ from dataclasses import replace
5
+ from pathlib import Path
6
+
7
+ import rich_click as click
8
+
9
+ from mcward import (
10
+ MissingFeatureError,
11
+ RunningEnvironment,
12
+ TestSession,
13
+ WardConfig,
14
+ WardError,
15
+ check_world,
16
+ )
17
+
18
+ from .datapacks import DataPack, FileResolver, format_range
19
+ from .environments import manager, select_compatible, start_environments
20
+ from .reporters import github, live
21
+ from .ui import console
22
+ from .writers import report_session
23
+
24
+ type Run = Callable[[str, Sequence[str]], TestSession]
25
+
26
+ OPTIONS = (
27
+ click.option(
28
+ "--version",
29
+ "-v",
30
+ "versions",
31
+ multiple=True,
32
+ help="Minecraft version(s) to test on",
33
+ ),
34
+ click.option(
35
+ "--reporter",
36
+ type=click.Choice(["live", "github"]),
37
+ default="live",
38
+ help="Result output: interactive live display, or GitHub Actions annotations",
39
+ ),
40
+ click.option(
41
+ "--coverage",
42
+ is_flag=True,
43
+ help="Record which function commands run and report line coverage",
44
+ ),
45
+ click.option(
46
+ "--coverage-report",
47
+ "coverage_reports",
48
+ multiple=True,
49
+ metavar="FORMAT[:PATH]",
50
+ help="Write coverage as 'lcov' or 'html', with an optional path (repeatable); "
51
+ "implies --coverage",
52
+ ),
53
+ click.option(
54
+ "--coverage-min",
55
+ type=click.FloatRange(0, 100),
56
+ default=None,
57
+ metavar="PERCENT",
58
+ help="Fail the run when coverage is below this percentage; implies --coverage",
59
+ ),
60
+ click.option(
61
+ "--junit-xml",
62
+ type=click.Path(dir_okay=False, writable=True, path_type=Path),
63
+ default=None,
64
+ help="Write test results as JUnit XML",
65
+ ),
66
+ click.option(
67
+ "--verbose",
68
+ is_flag=True,
69
+ help="List every test and coverage row instead of collapsing large runs",
70
+ ),
71
+ click.option(
72
+ "--watch",
73
+ "-w",
74
+ is_flag=True,
75
+ help="Run again when a file changes, with keys to rerun or filter",
76
+ ),
77
+ click.option(
78
+ "--world",
79
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
80
+ default=None,
81
+ help="Run in a copy of this world save instead of a flat world",
82
+ ),
83
+ click.argument("selector", default="*:*"),
84
+ )
85
+
86
+
87
+ def test_options[F: Callable[..., object]](command: F) -> F:
88
+ """The options and the selector that mcward test and beet test share."""
89
+ for option in reversed(OPTIONS):
90
+ command = option(command)
91
+ return command
92
+
93
+
94
+ def check_watch(watch: bool, reporter: str) -> None:
95
+ if watch and reporter == "github":
96
+ raise click.UsageError("--watch only works with the live reporter")
97
+
98
+
99
+ def load_config(world: Path | None) -> WardConfig:
100
+ """Read ward.toml, ``--world`` replacing its world, and reject a folder that is no world."""
101
+ try:
102
+ config = WardConfig.load()
103
+ if world is not None:
104
+ config = replace(config, world=world)
105
+ if config.world is not None:
106
+ check_world(config.world)
107
+ except WardError as e:
108
+ raise click.ClickException(str(e)) from e
109
+ return config
110
+
111
+
112
+ def rerunnable(versions: Sequence[str], run: Run) -> Callable[[str], TestSession]:
113
+ """Run with the given versions, then with the ones picked, so reruns ask only once."""
114
+ chosen = list(versions)
115
+
116
+ def rerun(selector: str) -> TestSession:
117
+ session = run(selector, chosen)
118
+ chosen[:] = [version.name for version in session.versions]
119
+ return session
120
+
121
+ return rerun
122
+
123
+
124
+ def run_session(
125
+ datapacks: Sequence[DataPack],
126
+ *,
127
+ config: WardConfig,
128
+ versions: Sequence[str] = (),
129
+ reporter: str = "live",
130
+ selector: str = "*:*",
131
+ coverage: bool = False,
132
+ coverage_specs: Sequence[tuple[str, Path]] = (),
133
+ coverage_min: float | None = None,
134
+ junit_xml: Path | None = None,
135
+ verbose: bool = False,
136
+ resolve: FileResolver | None = None,
137
+ ) -> TestSession:
138
+ """Pick versions, start them, run and report; ``coverage_min`` overrides ward.toml."""
139
+ low, high = format_range(datapacks)
140
+ selected = versions or select_compatible(low, high)
141
+ paths = [datapack.path for datapack in datapacks]
142
+ coverage = coverage or bool(coverage_specs) or coverage_min is not None
143
+ run = github.run if reporter == "github" else live.run
144
+
145
+ try:
146
+ minimum = config.coverage.minimum
147
+ if coverage_min is not None:
148
+ minimum = replace(minimum, total=coverage_min)
149
+ envs = start_environments([manager.get(v) for v in selected])
150
+ check_features(envs, worlds=config.world, origin=config.origin)
151
+ console.print()
152
+ session = run(
153
+ paths,
154
+ envs,
155
+ selector,
156
+ coverage=coverage,
157
+ verbose=verbose,
158
+ resolve=resolve,
159
+ world=config.world,
160
+ origin=config.origin,
161
+ )
162
+ report_session(
163
+ session,
164
+ paths,
165
+ specs=coverage_specs,
166
+ junit_xml=junit_xml,
167
+ verbose=verbose,
168
+ selector=selector,
169
+ ignores=config.coverage.ignores,
170
+ coverage=coverage,
171
+ minimum=minimum,
172
+ )
173
+ except WardError as e:
174
+ raise click.ClickException(str(e)) from e
175
+ return session
176
+
177
+
178
+ def check_features(envs: Sequence[RunningEnvironment], **features: object) -> None:
179
+ """Name the fix when a server lacks what the run needs: a restart, or none."""
180
+ for env in envs:
181
+ try:
182
+ env.require(**features)
183
+ except MissingFeatureError as e:
184
+ if not manager.outdated_mod(env):
185
+ raise
186
+ name = env.version.name
187
+ raise click.ClickException(
188
+ f"The server of {name} runs an older Ward mod that cannot {e.what}. "
189
+ f"Stop it with `mcward stop {name}`, and the next run updates it"
190
+ ) from e
@@ -5,6 +5,7 @@ import sys
5
5
  from collections.abc import Sequence
6
6
  from dataclasses import dataclass
7
7
 
8
+ import rich_click as click
8
9
  from rich.console import Console
9
10
 
10
11
  for _stream in (sys.stdout, sys.stderr):
@@ -54,9 +55,12 @@ def confirm(message: str, default: bool = False) -> bool:
54
55
 
55
56
 
56
57
  def select(message: str, options: Sequence[str | Option]) -> str:
57
- """Show a selection prompt; a cancelled prompt exits cleanly."""
58
+ """Show a selection prompt; a cancelled prompt exits like Ctrl+C."""
58
59
  import questionary
59
60
 
61
+ if not sys.stdin.isatty():
62
+ raise click.UsageError(f"No terminal to answer {message!r}, pass the value instead")
63
+
60
64
  choices = []
61
65
  for option in options:
62
66
  if isinstance(option, str):
@@ -66,5 +70,5 @@ def select(message: str, options: Sequence[str | Option]) -> str:
66
70
  choices.append(questionary.Choice(title, value=option.value or option.title))
67
71
  answer = questionary.select(message, choices, style=questionary.Style(_STYLE)).ask()
68
72
  if answer is None:
69
- sys.exit(0)
73
+ sys.exit(130)
70
74
  return answer