fastws-cli 0.0.34__tar.gz → 0.0.36__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.
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/PKG-INFO +15 -4
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/README.md +14 -3
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/__init__.py +3 -1
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/cargo.py +154 -31
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/core.py +42 -27
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/PKG-INFO +15 -4
- fastws_cli-0.0.36/tests/test_build.py +166 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_integrate.py +8 -1
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_procs.py +11 -4
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_sync.py +16 -9
- fastws_cli-0.0.34/tests/test_build.py +0 -96
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/LICENSE +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/_toml.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/build_backend.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/integrate.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/news.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/procs.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/releases.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/store.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws/timelock.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/SOURCES.txt +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/dependency_links.txt +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/entry_points.txt +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/requires.txt +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/fastws_cli.egg-info/top_level.txt +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/pyproject.toml +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/setup.cfg +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_build_backend.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_news.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_releases.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_setup.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_store.py +0 -0
- {fastws_cli-0.0.34 → fastws_cli-0.0.36}/tests/test_timelock.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastws-cli
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.36
|
|
4
4
|
Summary: Fast workspace tools for multi-repo management
|
|
5
5
|
Author: Jeremy Howard
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -210,6 +210,12 @@ cargo develop --profile quick
|
|
|
210
210
|
|
|
211
211
|
Run from the project root, or give its directory with `--path`. The command reads `python-source`, `module-name`, `manifest-path` and features from `[tool.maturin]`. `[tool.fastws] dev-profile = "quick"` selects a project's default for both `cargo develop` and `fastws.cargo.run_tests`. Without that setting they use `test`. An explicit `--profile NAME` overrides the project default. The project must produce a `cdylib` and set `python-source`. Define the selected profile in `Cargo.toml` and keep incremental compilation enabled for the local crate.
|
|
212
212
|
|
|
213
|
+
The workspace's `[tool.fastws] cargo = "/path/to/cargo"` optionally selects one explicit Cargo executable for fastws builds, checks, metadata and tests, including nextest's subordinate Cargo calls. A missing executable fails without falling back. With no selection, subprocess uses its normal PATH and working-directory rules. Upstream Cargo stays installed and usable; manifests, profiles, features and package selection are unchanged.
|
|
214
|
+
|
|
215
|
+
Optional workspace `cargo-target-dir` passes through Cargo's `CARGO_TARGET_DIR`. The path is absolute or relative to the fastws workspace; explicit caller/environment values win. Cargo's own `[unstable] root-dir` sets the actual common parent of local source repositories. Enable it with `fastws.core.cargo_setup(workspace, root_dir=True)`; later setup calls and integration snapshots keep it at their actual root, including sibling repositories. Cargo command-line/environment overrides keep their normal precedence. Sharing path-crate artifacts needs a Cargo that uses this root for metadata and source paths and tracks manifest-path dependencies: ordinary Cargo's `-Zroot-dir` alone is insufficient. A source root is not a virtual alias for another checkout.
|
|
216
|
+
|
|
217
|
+
Set `FASTWS_CARGO_LOG` to a file to append the raw Cargo output already captured by builds, checks and test-compilation/listing calls; no log is created by default.
|
|
218
|
+
|
|
213
219
|
Make the initial editable installation through `ws-sync` or maturin. Repeat that installation when package metadata or entry points change. Running Python processes keep the extension they loaded.
|
|
214
220
|
|
|
215
221
|
Cargo must already build a loadable Python extension. For PyO3 extension-module builds on macOS, configure the linker in `build.rs` with `pyo3_build_config::add_extension_module_link_args()`. This command does not inject maturin's extra compiler flags.
|
|
@@ -256,7 +262,11 @@ Use it when another process's unfinished edits stop the workspace compiling, suc
|
|
|
256
262
|
|
|
257
263
|
### Rust builds and tests from Python
|
|
258
264
|
|
|
259
|
-
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation.
|
|
265
|
+
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation. Outside `FASTWS_JOB`, a timed-out binary is reported as a failed suite with `timed_out` set. Inside a marked job, its timeout raises so the job owner can clean up descendants. Source edits between building and running do not trigger another build: the results describe the compiled build, not necessarily the latest working tree. It supports directly runnable native tests, not cross-target runners.
|
|
266
|
+
|
|
267
|
+
Where a root has `.config/nextest.toml`, preparation uses `cargo nextest list` to build the tests and capture Cargo and binary metadata. The metadata graph includes all features at the native platform, independently of the features selected for compilation. Each `cargo nextest run` consumes that metadata without building or waiting for Cargo's target lock. Nextest runs each test in its own process, every binary at once, with the config's slow-test timeouts and groups. `profiles` lists the nextest profiles to run one after another, `('default',)` unless given. `timeout` bounds each profile's execution, and each binary's results come from nextest's JUnit report, which lists no ignored tests. `--profile NAME` passes to the build as `--cargo-profile NAME`, and `test_args` follow `--`.
|
|
268
|
+
|
|
269
|
+
`root` can also be a list of roots, which build one after another. Roots without nextest then run their binaries in turn. Each profile then runs at the same time in every root whose config defines it: tests in different roots share a phase, and no phase starts before the previous one ends. Suite names start with the root's directory name, and with several profiles also with the profile, as in `app timed: tests/speed.rs`. A failure ends the run after its profile unless `--no-fail-fast` is given.
|
|
260
270
|
|
|
261
271
|
The default profile is `[tool.fastws].dev-profile`, or `test` when unset. Explicit `--profile NAME`, `--profile=NAME`, `--release` and `-r` override it. Pass Cargo build/selection options positionally, and test filters and harness options in `test_args`. A failed binary stops the run unless `--no-fail-fast` is given. Results contain compiler diagnostics and each binary's outcomes and captured failures.
|
|
262
272
|
|
|
@@ -265,6 +275,7 @@ from fastws.cargo import run_tests
|
|
|
265
275
|
|
|
266
276
|
native = run_tests('.', '--no-fail-fast')
|
|
267
277
|
focused = run_tests('.', '--test', 'core', test_args=('test_name', '--nocapture'))
|
|
278
|
+
phased = run_tests(['app', 'lib'], profiles=('untimed', 'timed'))
|
|
268
279
|
```
|
|
269
280
|
|
|
270
281
|
Doctests are deliberately not run; keep executable examples in ordinary Rust tests. `run_tests` accepts `env` overrides and `timeout=None` to disable its watchdog. It takes no timing lock around the run: rustc's wrapper owns its shared holds, and tests that time own their exclusive holds.
|
|
@@ -314,7 +325,7 @@ Fastws maintains `tool.uv.workspace.exclude`. It excludes unlisted top-level dir
|
|
|
314
325
|
|
|
315
326
|
Existing globs, entries for missing directories, and entries for checkouts that are still not Python projects are retained. Use `exclude = [...]` under `[tool.fastws]` to specify exclusions the scan cannot infer, such as keeping a valid project out of the workspace. Adding members preserves hand-written `[tool.uv.sources]` entries, including path and Git sources.
|
|
316
327
|
|
|
317
|
-
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members,
|
|
328
|
+
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members, that some local manifest requires from crates.io: by version alone, without `path`, `git` or `workspace`, in any dependency table or `[workspace.dependencies]`. Git dependencies that name local crates get entries under the matching URL. Builds under the workspace root use these local checkouts. Entries pointing outside the root and other configuration sections are preserved.
|
|
318
329
|
|
|
319
330
|
Sync also defaults `[term] quiet = true` in that file to suppress routine Cargo output and warnings. An explicit `quiet = false` is preserved.
|
|
320
331
|
|
|
@@ -336,7 +347,7 @@ After `uv sync`, fastws runs `cargo develop` in each mixed Rust/Python project.
|
|
|
336
347
|
|
|
337
348
|
Fastws then runs `<tool> install` at the workspace root. It runs `<tool> run build` in each JavaScript package containing both `Cargo.toml` and a `build` script. Cargo handles incremental compilation. Other build steps still run.
|
|
338
349
|
|
|
339
|
-
For npm, sync hides
|
|
350
|
+
For npm, sync hides successful install output and build-command banners. Installs use error-only logging, so npm warnings are hidden while errors and failure output remain visible. Run `npm audit` at the workspace root to inspect audit findings. Build scripts retain their own output; configure their tools to suppress routine progress. Other package managers retain their normal output.
|
|
340
351
|
|
|
341
352
|
When Rust-backed JavaScript builds are present, fastws checks before dependency installation that `rustc` and `cargo` on `PATH` are rustup's proxies. Install rustup from https://rustup.rs and select a stable toolchain with `rustup default stable` if not already configured. If another Rust installation shadows rustup, put its bin directory first on `PATH` after Homebrew's shell setup: `export PATH="$HOME/.cargo/bin:$PATH"` (use `$CARGO_HOME/bin` for a custom Cargo home), then open a new shell. Homebrew Rust can remain installed for Homebrew's own use. Fastws reports missing or shadowed rustup without changing your shell or installing a different toolchain. Packages using wasm-pack can then install their WASM target and matching binding tools automatically as part of their build.
|
|
342
353
|
|
|
@@ -182,6 +182,12 @@ cargo develop --profile quick
|
|
|
182
182
|
|
|
183
183
|
Run from the project root, or give its directory with `--path`. The command reads `python-source`, `module-name`, `manifest-path` and features from `[tool.maturin]`. `[tool.fastws] dev-profile = "quick"` selects a project's default for both `cargo develop` and `fastws.cargo.run_tests`. Without that setting they use `test`. An explicit `--profile NAME` overrides the project default. The project must produce a `cdylib` and set `python-source`. Define the selected profile in `Cargo.toml` and keep incremental compilation enabled for the local crate.
|
|
184
184
|
|
|
185
|
+
The workspace's `[tool.fastws] cargo = "/path/to/cargo"` optionally selects one explicit Cargo executable for fastws builds, checks, metadata and tests, including nextest's subordinate Cargo calls. A missing executable fails without falling back. With no selection, subprocess uses its normal PATH and working-directory rules. Upstream Cargo stays installed and usable; manifests, profiles, features and package selection are unchanged.
|
|
186
|
+
|
|
187
|
+
Optional workspace `cargo-target-dir` passes through Cargo's `CARGO_TARGET_DIR`. The path is absolute or relative to the fastws workspace; explicit caller/environment values win. Cargo's own `[unstable] root-dir` sets the actual common parent of local source repositories. Enable it with `fastws.core.cargo_setup(workspace, root_dir=True)`; later setup calls and integration snapshots keep it at their actual root, including sibling repositories. Cargo command-line/environment overrides keep their normal precedence. Sharing path-crate artifacts needs a Cargo that uses this root for metadata and source paths and tracks manifest-path dependencies: ordinary Cargo's `-Zroot-dir` alone is insufficient. A source root is not a virtual alias for another checkout.
|
|
188
|
+
|
|
189
|
+
Set `FASTWS_CARGO_LOG` to a file to append the raw Cargo output already captured by builds, checks and test-compilation/listing calls; no log is created by default.
|
|
190
|
+
|
|
185
191
|
Make the initial editable installation through `ws-sync` or maturin. Repeat that installation when package metadata or entry points change. Running Python processes keep the extension they loaded.
|
|
186
192
|
|
|
187
193
|
Cargo must already build a loadable Python extension. For PyO3 extension-module builds on macOS, configure the linker in `build.rs` with `pyo3_build_config::add_extension_module_link_args()`. This command does not inject maturin's extra compiler flags.
|
|
@@ -228,7 +234,11 @@ Use it when another process's unfinished edits stop the workspace compiling, suc
|
|
|
228
234
|
|
|
229
235
|
### Rust builds and tests from Python
|
|
230
236
|
|
|
231
|
-
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation.
|
|
237
|
+
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation. Outside `FASTWS_JOB`, a timed-out binary is reported as a failed suite with `timed_out` set. Inside a marked job, its timeout raises so the job owner can clean up descendants. Source edits between building and running do not trigger another build: the results describe the compiled build, not necessarily the latest working tree. It supports directly runnable native tests, not cross-target runners.
|
|
238
|
+
|
|
239
|
+
Where a root has `.config/nextest.toml`, preparation uses `cargo nextest list` to build the tests and capture Cargo and binary metadata. The metadata graph includes all features at the native platform, independently of the features selected for compilation. Each `cargo nextest run` consumes that metadata without building or waiting for Cargo's target lock. Nextest runs each test in its own process, every binary at once, with the config's slow-test timeouts and groups. `profiles` lists the nextest profiles to run one after another, `('default',)` unless given. `timeout` bounds each profile's execution, and each binary's results come from nextest's JUnit report, which lists no ignored tests. `--profile NAME` passes to the build as `--cargo-profile NAME`, and `test_args` follow `--`.
|
|
240
|
+
|
|
241
|
+
`root` can also be a list of roots, which build one after another. Roots without nextest then run their binaries in turn. Each profile then runs at the same time in every root whose config defines it: tests in different roots share a phase, and no phase starts before the previous one ends. Suite names start with the root's directory name, and with several profiles also with the profile, as in `app timed: tests/speed.rs`. A failure ends the run after its profile unless `--no-fail-fast` is given.
|
|
232
242
|
|
|
233
243
|
The default profile is `[tool.fastws].dev-profile`, or `test` when unset. Explicit `--profile NAME`, `--profile=NAME`, `--release` and `-r` override it. Pass Cargo build/selection options positionally, and test filters and harness options in `test_args`. A failed binary stops the run unless `--no-fail-fast` is given. Results contain compiler diagnostics and each binary's outcomes and captured failures.
|
|
234
244
|
|
|
@@ -237,6 +247,7 @@ from fastws.cargo import run_tests
|
|
|
237
247
|
|
|
238
248
|
native = run_tests('.', '--no-fail-fast')
|
|
239
249
|
focused = run_tests('.', '--test', 'core', test_args=('test_name', '--nocapture'))
|
|
250
|
+
phased = run_tests(['app', 'lib'], profiles=('untimed', 'timed'))
|
|
240
251
|
```
|
|
241
252
|
|
|
242
253
|
Doctests are deliberately not run; keep executable examples in ordinary Rust tests. `run_tests` accepts `env` overrides and `timeout=None` to disable its watchdog. It takes no timing lock around the run: rustc's wrapper owns its shared holds, and tests that time own their exclusive holds.
|
|
@@ -286,7 +297,7 @@ Fastws maintains `tool.uv.workspace.exclude`. It excludes unlisted top-level dir
|
|
|
286
297
|
|
|
287
298
|
Existing globs, entries for missing directories, and entries for checkouts that are still not Python projects are retained. Use `exclude = [...]` under `[tool.fastws]` to specify exclusions the scan cannot infer, such as keeping a valid project out of the workspace. Adding members preserves hand-written `[tool.uv.sources]` entries, including path and Git sources.
|
|
288
299
|
|
|
289
|
-
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members,
|
|
300
|
+
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members, that some local manifest requires from crates.io: by version alone, without `path`, `git` or `workspace`, in any dependency table or `[workspace.dependencies]`. Git dependencies that name local crates get entries under the matching URL. Builds under the workspace root use these local checkouts. Entries pointing outside the root and other configuration sections are preserved.
|
|
290
301
|
|
|
291
302
|
Sync also defaults `[term] quiet = true` in that file to suppress routine Cargo output and warnings. An explicit `quiet = false` is preserved.
|
|
292
303
|
|
|
@@ -308,7 +319,7 @@ After `uv sync`, fastws runs `cargo develop` in each mixed Rust/Python project.
|
|
|
308
319
|
|
|
309
320
|
Fastws then runs `<tool> install` at the workspace root. It runs `<tool> run build` in each JavaScript package containing both `Cargo.toml` and a `build` script. Cargo handles incremental compilation. Other build steps still run.
|
|
310
321
|
|
|
311
|
-
For npm, sync hides
|
|
322
|
+
For npm, sync hides successful install output and build-command banners. Installs use error-only logging, so npm warnings are hidden while errors and failure output remain visible. Run `npm audit` at the workspace root to inspect audit findings. Build scripts retain their own output; configure their tools to suppress routine progress. Other package managers retain their normal output.
|
|
312
323
|
|
|
313
324
|
When Rust-backed JavaScript builds are present, fastws checks before dependency installation that `rustc` and `cargo` on `PATH` are rustup's proxies. Install rustup from https://rustup.rs and select a stable toolchain with `rustup default stable` if not already configured. If another Rust installation shadows rustup, put its bin directory first on `PATH` after Homebrew's shell setup: `export PATH="$HOME/.cargo/bin:$PATH"` (use `$CARGO_HOME/bin` for a custom Cargo home), then open a new shell. Homebrew Rust can remain installed for Homebrew's own use. Fastws reports missing or shadowed rustup without changing your shell or installing a different toolchain. Packages using wasm-pack can then install their WASM target and matching binding tools automatically as part of their build.
|
|
314
325
|
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
r"Build, test and install Cargo artifacts for mixed Rust/Python projects."
|
|
2
|
-
import json, os, re, shutil, signal, subprocess, sys, sysconfig, time
|
|
2
|
+
import json, os, re, shutil, signal, subprocess, sys, sysconfig, tempfile, time
|
|
3
3
|
from collections import Counter
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
4
5
|
from dataclasses import dataclass, field
|
|
5
6
|
from pathlib import Path
|
|
6
7
|
from typing import NamedTuple
|
|
8
|
+
from xml.etree import ElementTree
|
|
7
9
|
from . import store
|
|
8
|
-
from .procs import bounded
|
|
10
|
+
from .procs import bounded, JOB_ENV
|
|
9
11
|
from ._toml import tomllib
|
|
10
12
|
|
|
11
13
|
|
|
@@ -22,9 +24,21 @@ def _dev_profile(root):
|
|
|
22
24
|
return settings(root).get('fastws', {}).get('dev-profile', 'test') if (root/'pyproject.toml').exists() else 'test'
|
|
23
25
|
|
|
24
26
|
|
|
25
|
-
def
|
|
27
|
+
def _cargo_command(*args, env=None):
|
|
28
|
+
"One Cargo and optional shared paths for every launch, including nextest's subordinate Cargo calls."
|
|
29
|
+
from .core import _fastws_cfg, _ws_root
|
|
30
|
+
environment = os.environ | (env or {})
|
|
31
|
+
workspace = _ws_root()
|
|
32
|
+
cfg = _fastws_cfg(workspace)
|
|
33
|
+
configured = cfg.get('cargo')
|
|
34
|
+
executable = str(workspace/Path(configured).expanduser()) if configured else 'cargo'
|
|
35
|
+
if 'cargo-target-dir' in cfg: environment.setdefault('CARGO_TARGET_DIR', str(workspace/Path(cfg['cargo-target-dir']).expanduser()))
|
|
36
|
+
return [executable, *args], environment | {'CARGO': executable}
|
|
37
|
+
|
|
38
|
+
def cargo(root, *args, env=None):
|
|
26
39
|
"Run Cargo in the project and return its standard output. A failure raises `CalledProcessError`, holding Cargo's standard error."
|
|
27
|
-
|
|
40
|
+
cmd, env = _cargo_command(*args, env=env)
|
|
41
|
+
return subprocess.run(cmd, cwd=Path(root).expanduser(), env=env, text=True, capture_output=True, check=True).stdout
|
|
28
42
|
|
|
29
43
|
|
|
30
44
|
def members(root):
|
|
@@ -45,19 +59,25 @@ class Diagnostic(NamedTuple):
|
|
|
45
59
|
|
|
46
60
|
def _run(root, args, env=None, diagnostics=True):
|
|
47
61
|
"Run the Cargo subcommand and options `args` in `root`, with the environment variables `env` set: its exit status, its output, each `Diagnostic` once, and Cargo's other JSON messages, such as artifacts. With `diagnostics`, Cargo writes JSON messages and the output renders each compiler message short; without, the output is as Cargo printed it."
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
62
|
+
nextest = args[0] == 'nextest'
|
|
63
|
+
flags = (('--cargo-message-format=json,json-diagnostic-short' if nextest else '--message-format=json-diagnostic-short'),) if diagnostics else ()
|
|
64
|
+
at = 2 if nextest else 1
|
|
65
|
+
cmd, env = _cargo_command(*args[:at], *flags, *args[at:], env=env)
|
|
66
|
+
# nextest's final JSON can lack a newline; stderr must not join its records.
|
|
67
|
+
p = bounded(cmd, seconds=None, merge=False, cwd=root, env=env)
|
|
68
|
+
if log := env.get('FASTWS_CARGO_LOG'):
|
|
69
|
+
with Path(log).expanduser().open('a') as capture: capture.write(p.stdout + '\n' + p.stderr)
|
|
70
|
+
if not diagnostics: return p.returncode, p.stdout + p.stderr, [], []
|
|
51
71
|
text, found, rest = [], [], []
|
|
52
72
|
for line in p.stdout.splitlines(keepends=True):
|
|
53
73
|
if not line.startswith('{'): text.append(line); continue
|
|
54
74
|
m = json.loads(line)
|
|
55
|
-
if m
|
|
75
|
+
if m.get('reason') != 'compiler-message': rest.append(m); continue
|
|
56
76
|
msg = m['message']
|
|
57
77
|
text.append(msg['rendered'])
|
|
58
78
|
if s := next((s for s in msg['spans'] if s['is_primary']), None):
|
|
59
79
|
found.append(Diagnostic(s['file_name'], s['line_start'], s['column_start'], msg['level'], msg['message'], (msg['code'] or {}).get('code')))
|
|
60
|
-
return p.returncode, ''.join(text), list(dict.fromkeys(found)), rest
|
|
80
|
+
return p.returncode, ''.join(text) + p.stderr, list(dict.fromkeys(found)), rest
|
|
61
81
|
|
|
62
82
|
|
|
63
83
|
def _lines(text, n=20, tail=False):
|
|
@@ -143,32 +163,132 @@ def check(
|
|
|
143
163
|
return Results(args[0], *_run(Path(root).expanduser(), args, env, diagnostics)[:3])
|
|
144
164
|
|
|
145
165
|
|
|
146
|
-
def
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
166
|
+
def _bounded(cmd, timeout, **kwargs):
|
|
167
|
+
"`bounded(cmd, timeout, merge=True, **kwargs)`, and whether it ran out of time. Outside `FASTWS_JOB`, a timeout gives a killed process's result; inside a marked job, it raises so the job's owner can clean up descendants."
|
|
168
|
+
try: return bounded(cmd, timeout, merge=True, **kwargs), False
|
|
169
|
+
except TimeoutError as e:
|
|
170
|
+
if os.environ.get(JOB_ENV): raise
|
|
171
|
+
return subprocess.CompletedProcess(cmd, -signal.SIGKILL, f'{e}\n'), True
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _suite_name(m):
|
|
175
|
+
"The `Suite` name of the test binary that Cargo artifact `m` describes: its target's source, prefixed `unittests ` unless it's an integration test."
|
|
176
|
+
name = Path(m['target']['src_path']).relative_to(Path(m['manifest_path']).parent).as_posix()
|
|
177
|
+
return name if 'test' in m['target']['kind'] else 'unittests ' + name
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _binary_id(m, packages):
|
|
181
|
+
"nextest's id for the test binary that Cargo artifact `m` describes, such as `app`, `app::more` or `app::bin/app`. `packages` maps package ids to names."
|
|
182
|
+
pkg, kind, name = packages[m['package_id']], m['target']['kind'][0], m['target']['name']
|
|
183
|
+
if kind == 'test': return f'{pkg}::{name}'
|
|
184
|
+
return f'{pkg}::{kind}/{name}' if kind in ('bin', 'example', 'bench') else pkg
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _junit(path, names):
|
|
188
|
+
"Each binary's `Suite` from nextest's JUnit report at `path`. `names` maps nextest's binary ids to suite names. Ignored tests don't appear."
|
|
189
|
+
suites = []
|
|
190
|
+
for ts in ElementTree.parse(path).getroot().iter('testsuite'):
|
|
191
|
+
tests, failures, late = {}, {}, False
|
|
192
|
+
for tc in ts.iter('testcase'):
|
|
193
|
+
t, bad = tc.get('name'), next(iter(tc.findall('failure') + tc.findall('error')), None)
|
|
194
|
+
tests[t] = 'ok' if bad is None else 'FAILED'
|
|
195
|
+
if bad is None: continue
|
|
196
|
+
failures[t] = '\n'.join(s for s in (tc.findtext('system-out', '').strip('\n'), tc.findtext('system-err', '').strip('\n') or bad.text or '') if s)
|
|
197
|
+
late |= 'timeout' in bad.get('type', '')
|
|
198
|
+
suites.append(Suite(names.get(ts.get('name'), ts.get('name')), '\n\n'.join(failures.values()), tests, failures, '', bool(failures), late))
|
|
199
|
+
return suites
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _nextest(root, args, test_args, env, timeout, artifacts, reuse, profile='default'):
|
|
203
|
+
"Run captured test binaries without entering Cargo's build phase, under the profile's execution timeout."
|
|
204
|
+
metadata, binaries = reuse
|
|
205
|
+
packages = {p['id']: p['name'] for p in metadata['packages']}
|
|
206
|
+
names = {_binary_id(m, packages): _suite_name(m) for m in artifacts}
|
|
207
|
+
with tempfile.TemporaryDirectory() as d:
|
|
208
|
+
report, tool = Path(d)/'junit.xml', Path(d)/'fastws.toml'
|
|
209
|
+
cargo_meta, binary_meta = Path(d)/'cargo.json', Path(d)/'binaries.json'
|
|
210
|
+
cargo_meta.write_text(json.dumps(metadata))
|
|
211
|
+
binary_meta.write_text(json.dumps(binaries))
|
|
212
|
+
tool.write_text(f'[profile.{profile}.junit]\npath = {json.dumps(str(report))}\n')
|
|
213
|
+
flags = ('--no-fail-fast',) if '--no-fail-fast' in args else ()
|
|
214
|
+
cmd, env = _cargo_command('nextest', 'run', '--cargo-metadata', cargo_meta, '--binaries-metadata', binary_meta,
|
|
215
|
+
'--tool-config-file', f'fastws:{tool}', '--profile', profile, '--show-progress=none', '--color=never', *flags,
|
|
216
|
+
*(('--', *test_args) if test_args else ()), env=env)
|
|
217
|
+
start = time.monotonic()
|
|
218
|
+
p, late = _bounded(cmd, timeout, cwd=root, env=env)
|
|
219
|
+
suites = _junit(report, names) if report.exists() else [Suite('nextest', p.stdout, {}, {}, '', True, late)]
|
|
220
|
+
return p.returncode, p.stdout, suites, time.monotonic() - start
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _libtest(root, args, test_args, env, timeout, artifacts):
|
|
224
|
+
"Run each built test binary in turn from its package directory under `timeout`: the first failing exit status, the output and each binary's `Suite`. Without `--no-fail-fast` in `args`, the first failing binary ends the run."
|
|
225
|
+
code, text, suites = 0, '', []
|
|
161
226
|
for m in artifacts:
|
|
162
|
-
package = Path(m['manifest_path']).parent
|
|
163
|
-
|
|
164
|
-
if 'test' not in m['target']['kind']: name = 'unittests ' + name
|
|
165
|
-
try: p, late = bounded([m['executable'], *test_args], timeout, merge=True, cwd=package, env=os.environ | env | {'CARGO_MANIFEST_DIR': str(package)}), False
|
|
166
|
-
except TimeoutError as e: p, late = subprocess.CompletedProcess(m['executable'], -signal.SIGKILL, f'{e}\n'), True
|
|
227
|
+
package, name = Path(m['manifest_path']).parent, _suite_name(m)
|
|
228
|
+
p, late = _bounded([m['executable'], *test_args], timeout, cwd=package, env=os.environ | env | {'CARGO_MANIFEST_DIR': str(package)})
|
|
167
229
|
suites.append(Suite.read(name, p.stdout.splitlines(), p.returncode, late))
|
|
168
230
|
text += f' Running {name} ({m["executable"]})\n' + p.stdout
|
|
169
231
|
if p.returncode:
|
|
170
|
-
code = p.returncode
|
|
232
|
+
code = code or p.returncode
|
|
171
233
|
if '--no-fail-fast' not in args: break
|
|
234
|
+
return code, text, suites
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _nextest_profiles(root):
|
|
238
|
+
"The nextest profiles that `root`'s `.config/nextest.toml` defines, `default` included, or None without that file."
|
|
239
|
+
config = root/'.config/nextest.toml'
|
|
240
|
+
return {'default', *tomllib.loads(config.read_text()).get('profile', {})} if config.exists() else None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def run_tests(
|
|
244
|
+
root, # A Cargo package or workspace (expands `~`), or a list of them
|
|
245
|
+
*args, # Cargo build/selection options, such as `'--test', 'core'` or `'--profile', 'checked'`; `--no-fail-fast` runs every binary
|
|
246
|
+
test_args=(), # Arguments passed directly to each test binary, such as `('name', '--nocapture')`; nextest gets them after `--`
|
|
247
|
+
env:dict=None, # Environment variables to set for the run, such as `{'BASEDPL_COSTS': '1'}`
|
|
248
|
+
timeout:float=30, # Seconds that each native test binary, or each nextest run of one profile in one root, may take after building; None: no limit
|
|
249
|
+
profiles:tuple=('default',) # The nextest profiles to run in turn, each at once in every root whose `.config/nextest.toml` defines it
|
|
250
|
+
)->Results:
|
|
251
|
+
"Build native tests once per root, with no time limit, then run Cargo's reported executables directly from their package directories. Where a root has `.config/nextest.toml`, `cargo nextest run` runs them instead, each test in its own process, once for each of `profiles` that its config defines, and each binary's results come from nextest's JUnit report. Several roots build in turn. Roots without nextest then run in turn, and each profile then runs in every root that defines it at once. Without `--no-fail-fast`, a failure ends the run after its binary, or after its profile. With several roots, each suite's name starts with its root's directory name, and with several profiles, with the profile. Source edits after building cannot trigger another build; results describe the compiled build, not the latest working tree. `timeout` bounds each binary, or each root's run of a profile, excluding compilation. Outside `FASTWS_JOB`, a run that runs out of time is reported as a failed suite with `timed_out` set. Inside a marked job, the timeout raises so its owner can clean up descendants. An omitted Cargo profile uses each root's tool.fastws.dev-profile, or test. Doctests are not run. This takes no timing lock: rustc's wrapper and tests that time own their holds."
|
|
252
|
+
roots = [Path(r).expanduser().resolve() for r in (root if isinstance(root, (list, tuple)) else [root])]
|
|
253
|
+
env = {'CARGO_TERM_QUIET': 'false', 'CARGO_TERM_COLOR': 'never'} | (env or {})
|
|
254
|
+
has_profile = any(a in ('-r', '--release', '--profile') or isinstance(a, str) and a.startswith('--profile=') for a in args)
|
|
255
|
+
text, found, built = '', [], []
|
|
256
|
+
for r in roots:
|
|
257
|
+
rargs = args if has_profile else (*args, '--profile', _dev_profile(r))
|
|
258
|
+
defined, reuse = _nextest_profiles(r), None
|
|
259
|
+
if defined is None: code, out, diags, rest = _run(r, ('test', '--no-run', *rargs), env)
|
|
260
|
+
else:
|
|
261
|
+
flags = [re.sub(r'^--profile(?==|$)', '--cargo-profile', str(a)) for a in rargs if a != '--no-fail-fast']
|
|
262
|
+
code, out, diags, rest = _run(r, ('nextest', 'list', '--list-type=binaries-only', '--message-format=json', '--ignore-default-filter', *flags), env)
|
|
263
|
+
if not code:
|
|
264
|
+
binaries, = (m for m in rest if 'reason' not in m)
|
|
265
|
+
host = binaries['rust-build-meta']['platforms']['host']['platform']['triple']
|
|
266
|
+
# Package filters use nextest's all-feature graph, not the features selected for compilation.
|
|
267
|
+
try: metadata = json.loads(cargo(r, 'metadata', '--format-version', '1', '--all-features', '--filter-platform', host, env=env))
|
|
268
|
+
except subprocess.CalledProcessError as e: return Results('test', e.returncode, text + out + e.stderr, found + diags)
|
|
269
|
+
reuse = metadata, binaries
|
|
270
|
+
text, found = text + out, found + diags
|
|
271
|
+
if code: return Results('test', code, text, found)
|
|
272
|
+
artifacts = [m for m in rest if m.get('reason') == 'compiler-artifact' and m['profile']['test'] and m.get('executable')]
|
|
273
|
+
built.append((r, rargs, artifacts, defined, reuse))
|
|
274
|
+
def named(r, p, suites):
|
|
275
|
+
"`suites`, freshly read, renamed for root `r` and profile `p` where several roots or profiles ran"
|
|
276
|
+
t = ' '.join(x for x in (r.name if len(roots) > 1 else '', p if p and len(profiles) > 1 else '') if x)
|
|
277
|
+
for s in suites: s.name = f'{t}: {s.name}' if t else s.name
|
|
278
|
+
return t, suites
|
|
279
|
+
fail_fast, code, suites, start = '--no-fail-fast' not in args, 0, [], time.monotonic()
|
|
280
|
+
for r, rargs, artifacts, defined, reuse in built:
|
|
281
|
+
if defined is not None: continue
|
|
282
|
+
c, out, ss = _libtest(r, rargs, test_args, env, timeout, artifacts)
|
|
283
|
+
text, suites, code = text + out, suites + named(r, None, ss)[1], code or c
|
|
284
|
+
if code and fail_fast: return Results('test', code, text, found, suites, time.monotonic() - start)
|
|
285
|
+
for p in profiles:
|
|
286
|
+
jobs = [(r, rargs, artifacts, reuse) for r, rargs, artifacts, defined, reuse in built if p in (defined or ())]
|
|
287
|
+
with ThreadPoolExecutor(max(len(jobs), 1)) as ex: runs = list(ex.map(lambda j: _nextest(j[0], j[1], test_args, env, timeout, j[2], j[3], p), jobs))
|
|
288
|
+
for (r, _, _, _), (c, out, ss, _) in zip(jobs, runs):
|
|
289
|
+
t, ss = named(r, p, ss)
|
|
290
|
+
text, suites, code = text + (f' Nextest profile {p} in {r}\n' if t else '') + out, suites + ss, code or c
|
|
291
|
+
if code and fail_fast: break
|
|
172
292
|
return Results('test', code, text, found, suites, time.monotonic() - start)
|
|
173
293
|
|
|
174
294
|
|
|
@@ -226,7 +346,10 @@ def build(
|
|
|
226
346
|
for flag, active in [('all-features', all_features), ('no-default-features', no_default_features)]:
|
|
227
347
|
if active or cfg.get(flag): cmd.append('--' + flag)
|
|
228
348
|
extra, env = _maturin_flags(target, os.environ) if for_maturin else ([], None)
|
|
229
|
-
|
|
349
|
+
cmd, env = _cargo_command(*cmd, *extra, env=env)
|
|
350
|
+
result = subprocess.run(cmd, cwd=root, stdout=subprocess.PIPE, text=True, env=env)
|
|
351
|
+
if log := env.get('FASTWS_CARGO_LOG'):
|
|
352
|
+
with Path(log).expanduser().open('a') as capture: capture.write(result.stdout)
|
|
230
353
|
messages = [json.loads(line) for line in result.stdout.splitlines()]
|
|
231
354
|
for m in messages:
|
|
232
355
|
if m.get('reason') != 'compiler-message': continue
|
|
@@ -265,9 +265,9 @@ def _replace_array(content: str, table: str, key: str, values: list[str]) -> str
|
|
|
265
265
|
return content[:start] + section + content[end:]
|
|
266
266
|
|
|
267
267
|
def _table_span(content: str, name: str) -> tuple[int,int]|None:
|
|
268
|
-
m = re.search(rf"(?m)
|
|
268
|
+
m = re.search(rf"(?m)^[ \t]*\[{re.escape(name)}\][ \t]*(?:#[^\r\n]*)?\r?$", content)
|
|
269
269
|
if not m: return None
|
|
270
|
-
n = re.search(r"(?m)
|
|
270
|
+
n = re.search(r"(?m)^[ \t]*\[", content[m.end():])
|
|
271
271
|
end = m.end()+n.start() if n else len(content)
|
|
272
272
|
return m.start(), end
|
|
273
273
|
|
|
@@ -684,20 +684,31 @@ def _cargo_patches(root: Path):
|
|
|
684
684
|
patches[(_repo_key(url), name)] = path if path.is_absolute() else (config.parent/path).resolve()
|
|
685
685
|
return patches, config
|
|
686
686
|
|
|
687
|
-
def
|
|
688
|
-
"(`
|
|
687
|
+
def _crate_manifests(d: Path):
|
|
688
|
+
"(parsed `Cargo.toml`, dir) for the crate or workspace at `d` and each of its cargo workspace members"
|
|
689
689
|
try: data = tomllib.loads((d/"Cargo.toml").read_text())
|
|
690
690
|
except tomllib.TOMLDecodeError: return
|
|
691
|
-
|
|
691
|
+
yield data, d
|
|
692
692
|
for m in _project_dirs(d, "Cargo.toml", data.get("workspace", {}).get("members", [])):
|
|
693
693
|
try: sub = tomllib.loads((m/"Cargo.toml").read_text())
|
|
694
694
|
except tomllib.TOMLDecodeError: continue
|
|
695
|
-
|
|
695
|
+
yield sub, m
|
|
696
|
+
|
|
697
|
+
def _crate_pkgs(d: Path):
|
|
698
|
+
"(`[package]` table, dir) for the crate at `d` and its cargo workspace members"
|
|
699
|
+
for data, m in _crate_manifests(d):
|
|
700
|
+
if "name" in (pkg := data.get("package", {})): yield pkg, m
|
|
696
701
|
|
|
697
702
|
def _local_crates(root: Path) -> list[tuple[dict, Path]]:
|
|
698
703
|
"(`[package]` table, dir) for every crate under `root`, nested cargo workspace members included"
|
|
699
704
|
return [p for crate in _crate_dirs(root) for p in _crate_pkgs(crate)]
|
|
700
705
|
|
|
706
|
+
def _registry_requirements(root: Path) -> set[str]:
|
|
707
|
+
"Packages that some manifest under `root` requires from crates.io: a version with no `path`, `git`, `registry` or `workspace` key"
|
|
708
|
+
return {spec.get("package", name) if isinstance(spec, dict) else name
|
|
709
|
+
for crate in _crate_dirs(root) for data, _ in _crate_manifests(crate) for deps in _cargo_dep_tables(data, every=True)
|
|
710
|
+
for name, spec in deps.items() if isinstance(spec, str) or isinstance(spec, dict) and not {"path", "git", "registry", "workspace"} & spec.keys()}
|
|
711
|
+
|
|
701
712
|
def _git_dep_tables(root: Path, crates: dict[str, Path]) -> dict[str, dict[str, Path]]:
|
|
702
713
|
"Git URL -> {package: local dir} for members' git deps that name a local crate"
|
|
703
714
|
res = {}
|
|
@@ -732,29 +743,36 @@ def _entry_changes(current, new):
|
|
|
732
743
|
"Added and removed keys, in the order supplied."
|
|
733
744
|
return [k for k in new if k not in current], [k for k in current if k not in new]
|
|
734
745
|
|
|
735
|
-
def cargo_setup(root):
|
|
736
|
-
"Regenerate local Cargo patches and the compile-lock wrapper without pulling or building."
|
|
746
|
+
def cargo_setup(root, *, root_dir=False):
|
|
747
|
+
"Regenerate local Cargo patches and the compile-lock wrapper without pulling or building; root_dir enables Cargo's common source root."
|
|
737
748
|
root = Path(root).expanduser().resolve()
|
|
738
749
|
_sync_cargo_wrapper(root)
|
|
739
|
-
return _sync_cargo_patches(root)
|
|
750
|
+
return _sync_cargo_patches(root, root_dir=root_dir)
|
|
740
751
|
|
|
741
|
-
def _sync_cargo_patches(root: Path) -> tuple[list[str], list[str]]:
|
|
752
|
+
def _sync_cargo_patches(root: Path, root_dir=False) -> tuple[list[str], list[str]]:
|
|
742
753
|
"""Regenerate workspace Cargo patches, default to quiet output, and return (added, removed).
|
|
743
754
|
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
then use the checkouts: the cargo analog of editable installs. Only
|
|
747
|
-
managed; entries pointing elsewhere (and any other config sections) are
|
|
748
|
-
over a generated one of the same name.
|
|
755
|
+
A local crate gets a `[patch.crates-io]` entry only where some local manifest requires it from crates.io
|
|
756
|
+
(`_registry_requirements`); Cargo uses no other patch. A member's git dep on a local crate gets an entry under
|
|
757
|
+
that URL. Builds anywhere under `root` then use the checkouts: the cargo analog of editable installs. Only
|
|
758
|
+
entries whose path is inside `root` are managed; entries pointing elsewhere (and any other config sections) are
|
|
759
|
+
kept as-is, and a kept entry wins over a generated one of the same name. An enabled `[unstable] root-dir`
|
|
760
|
+
follows the actual root; `root_dir` enables it."""
|
|
749
761
|
root = root.resolve()
|
|
750
762
|
pkgs = _local_crates(root)
|
|
751
763
|
crates = {pkg["name"]: d for pkg, d in pkgs}
|
|
752
|
-
|
|
764
|
+
required = _registry_requirements(root)
|
|
765
|
+
desired = {"crates-io": {name: str(d) for name, d in crates.items() if name in required}}
|
|
753
766
|
for url, entries in _git_dep_tables(root, crates).items(): desired[url] = {name: str(d) for name, d in entries.items()}
|
|
754
767
|
config = root/".cargo"/"config.toml"
|
|
755
768
|
original = content = config.read_text() if config.exists() else ""
|
|
756
769
|
data = tomllib.loads(content) if content else {}
|
|
757
770
|
old = data.get("patch", {})
|
|
771
|
+
if root_dir or 'root-dir' in data.get('unstable', {}):
|
|
772
|
+
span = _table_span(content, 'unstable')
|
|
773
|
+
body = content[span[0]:span[1]].partition('\n')[2] if span else ''
|
|
774
|
+
body = re.sub(r'(?m)^[ \t]*root-dir[ \t]*=.*(?:\n|$)', '', body)
|
|
775
|
+
content = _replace_table(content, 'unstable', f'root-dir = {json.dumps(str(root))}\n{body}')
|
|
758
776
|
if "quiet" not in data.get("term", {}):
|
|
759
777
|
if match := re.search(r"(?m)^\[term\][^\n]*(?:\n|$)", content):
|
|
760
778
|
content = content[:match.end()].rstrip("\n") + "\nquiet = true\n" + content[match.end():]
|
|
@@ -816,10 +834,13 @@ def _sync_cargo_wrapper(root: Path):
|
|
|
816
834
|
config.parent.mkdir(exist_ok=True)
|
|
817
835
|
config.write_text(new)
|
|
818
836
|
|
|
819
|
-
def _cargo_dep_tables(data):
|
|
820
|
-
|
|
837
|
+
def _cargo_dep_tables(data, every=False):
|
|
838
|
+
"A manifest's dependency and build-dependency tables, top-level and per target; with `every`, its dev-dependency tables and `[workspace.dependencies]` too"
|
|
839
|
+
names = ("dependencies", "build-dependencies", "dev-dependencies")[:3 if every else 2]
|
|
840
|
+
for name in names: yield data.get(name, {})
|
|
821
841
|
for target in data.get("target", {}).values():
|
|
822
|
-
for name in
|
|
842
|
+
for name in names: yield target.get(name, {})
|
|
843
|
+
if every: yield data.get("workspace", {}).get("dependencies", {})
|
|
823
844
|
|
|
824
845
|
def _patched_cargo_deps(crate: Path, patches):
|
|
825
846
|
data = tomllib.loads((crate/"Cargo.toml").read_text())
|
|
@@ -933,17 +954,11 @@ def _check_rustup():
|
|
|
933
954
|
"Homebrew Rust can remain installed. Open a new shell and rerun ws-sync.")
|
|
934
955
|
|
|
935
956
|
def _npm_install(root: Path):
|
|
936
|
-
"Hide npm
|
|
937
|
-
try:
|
|
957
|
+
"Hide successful npm install output and warnings, but retain errors and failure diagnostics."
|
|
958
|
+
try: subprocess.run(["npm", "install", "--loglevel=error"], check=True, cwd=root, stdout=subprocess.PIPE, text=True)
|
|
938
959
|
except subprocess.CalledProcessError as e:
|
|
939
960
|
if e.stdout: print(e.stdout, file=sys.stderr, end="")
|
|
940
961
|
raise
|
|
941
|
-
try: data = json.loads(res.stdout)
|
|
942
|
-
except json.JSONDecodeError:
|
|
943
|
-
print(res.stdout, file=sys.stderr, end="")
|
|
944
|
-
raise
|
|
945
|
-
if data.get("audit", {}).get("vulnerabilities", {}).get("total") or data.get("unreviewedScripts"):
|
|
946
|
-
print(f"npm install findings ({root}):\n{res.stdout}", file=sys.stderr, end="")
|
|
947
962
|
|
|
948
963
|
def _sync_js(root: Path, members: list[Path]) -> list[Path]:
|
|
949
964
|
"Install the JS workspace, run every native member's build script, and return those members. Cargo handles incremental compilation."
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: fastws-cli
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.36
|
|
4
4
|
Summary: Fast workspace tools for multi-repo management
|
|
5
5
|
Author: Jeremy Howard
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -210,6 +210,12 @@ cargo develop --profile quick
|
|
|
210
210
|
|
|
211
211
|
Run from the project root, or give its directory with `--path`. The command reads `python-source`, `module-name`, `manifest-path` and features from `[tool.maturin]`. `[tool.fastws] dev-profile = "quick"` selects a project's default for both `cargo develop` and `fastws.cargo.run_tests`. Without that setting they use `test`. An explicit `--profile NAME` overrides the project default. The project must produce a `cdylib` and set `python-source`. Define the selected profile in `Cargo.toml` and keep incremental compilation enabled for the local crate.
|
|
212
212
|
|
|
213
|
+
The workspace's `[tool.fastws] cargo = "/path/to/cargo"` optionally selects one explicit Cargo executable for fastws builds, checks, metadata and tests, including nextest's subordinate Cargo calls. A missing executable fails without falling back. With no selection, subprocess uses its normal PATH and working-directory rules. Upstream Cargo stays installed and usable; manifests, profiles, features and package selection are unchanged.
|
|
214
|
+
|
|
215
|
+
Optional workspace `cargo-target-dir` passes through Cargo's `CARGO_TARGET_DIR`. The path is absolute or relative to the fastws workspace; explicit caller/environment values win. Cargo's own `[unstable] root-dir` sets the actual common parent of local source repositories. Enable it with `fastws.core.cargo_setup(workspace, root_dir=True)`; later setup calls and integration snapshots keep it at their actual root, including sibling repositories. Cargo command-line/environment overrides keep their normal precedence. Sharing path-crate artifacts needs a Cargo that uses this root for metadata and source paths and tracks manifest-path dependencies: ordinary Cargo's `-Zroot-dir` alone is insufficient. A source root is not a virtual alias for another checkout.
|
|
216
|
+
|
|
217
|
+
Set `FASTWS_CARGO_LOG` to a file to append the raw Cargo output already captured by builds, checks and test-compilation/listing calls; no log is created by default.
|
|
218
|
+
|
|
213
219
|
Make the initial editable installation through `ws-sync` or maturin. Repeat that installation when package metadata or entry points change. Running Python processes keep the extension they loaded.
|
|
214
220
|
|
|
215
221
|
Cargo must already build a loadable Python extension. For PyO3 extension-module builds on macOS, configure the linker in `build.rs` with `pyo3_build_config::add_extension_module_link_args()`. This command does not inject maturin's extra compiler flags.
|
|
@@ -256,7 +262,11 @@ Use it when another process's unfinished edits stop the workspace compiling, suc
|
|
|
256
262
|
|
|
257
263
|
### Rust builds and tests from Python
|
|
258
264
|
|
|
259
|
-
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation.
|
|
265
|
+
`fastws.cargo.run_tests` builds native tests once with Cargo, without a time limit, then runs the executables that Cargo reports directly from their package directories. Each binary gets its own `timeout`, 30 seconds by default, excluding compilation. Outside `FASTWS_JOB`, a timed-out binary is reported as a failed suite with `timed_out` set. Inside a marked job, its timeout raises so the job owner can clean up descendants. Source edits between building and running do not trigger another build: the results describe the compiled build, not necessarily the latest working tree. It supports directly runnable native tests, not cross-target runners.
|
|
266
|
+
|
|
267
|
+
Where a root has `.config/nextest.toml`, preparation uses `cargo nextest list` to build the tests and capture Cargo and binary metadata. The metadata graph includes all features at the native platform, independently of the features selected for compilation. Each `cargo nextest run` consumes that metadata without building or waiting for Cargo's target lock. Nextest runs each test in its own process, every binary at once, with the config's slow-test timeouts and groups. `profiles` lists the nextest profiles to run one after another, `('default',)` unless given. `timeout` bounds each profile's execution, and each binary's results come from nextest's JUnit report, which lists no ignored tests. `--profile NAME` passes to the build as `--cargo-profile NAME`, and `test_args` follow `--`.
|
|
268
|
+
|
|
269
|
+
`root` can also be a list of roots, which build one after another. Roots without nextest then run their binaries in turn. Each profile then runs at the same time in every root whose config defines it: tests in different roots share a phase, and no phase starts before the previous one ends. Suite names start with the root's directory name, and with several profiles also with the profile, as in `app timed: tests/speed.rs`. A failure ends the run after its profile unless `--no-fail-fast` is given.
|
|
260
270
|
|
|
261
271
|
The default profile is `[tool.fastws].dev-profile`, or `test` when unset. Explicit `--profile NAME`, `--profile=NAME`, `--release` and `-r` override it. Pass Cargo build/selection options positionally, and test filters and harness options in `test_args`. A failed binary stops the run unless `--no-fail-fast` is given. Results contain compiler diagnostics and each binary's outcomes and captured failures.
|
|
262
272
|
|
|
@@ -265,6 +275,7 @@ from fastws.cargo import run_tests
|
|
|
265
275
|
|
|
266
276
|
native = run_tests('.', '--no-fail-fast')
|
|
267
277
|
focused = run_tests('.', '--test', 'core', test_args=('test_name', '--nocapture'))
|
|
278
|
+
phased = run_tests(['app', 'lib'], profiles=('untimed', 'timed'))
|
|
268
279
|
```
|
|
269
280
|
|
|
270
281
|
Doctests are deliberately not run; keep executable examples in ordinary Rust tests. `run_tests` accepts `env` overrides and `timeout=None` to disable its watchdog. It takes no timing lock around the run: rustc's wrapper owns its shared holds, and tests that time own their exclusive holds.
|
|
@@ -314,7 +325,7 @@ Fastws maintains `tool.uv.workspace.exclude`. It excludes unlisted top-level dir
|
|
|
314
325
|
|
|
315
326
|
Existing globs, entries for missing directories, and entries for checkouts that are still not Python projects are retained. Use `exclude = [...]` under `[tool.fastws]` to specify exclusions the scan cannot infer, such as keeping a valid project out of the workspace. Adding members preserves hand-written `[tool.uv.sources]` entries, including path and Git sources.
|
|
316
327
|
|
|
317
|
-
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members,
|
|
328
|
+
Each sync regenerates Cargo overrides in the workspace's `.cargo/config.toml`. `[patch.crates-io]` gets an entry for each local crate, including nested Cargo workspace members, that some local manifest requires from crates.io: by version alone, without `path`, `git` or `workspace`, in any dependency table or `[workspace.dependencies]`. Git dependencies that name local crates get entries under the matching URL. Builds under the workspace root use these local checkouts. Entries pointing outside the root and other configuration sections are preserved.
|
|
318
329
|
|
|
319
330
|
Sync also defaults `[term] quiet = true` in that file to suppress routine Cargo output and warnings. An explicit `quiet = false` is preserved.
|
|
320
331
|
|
|
@@ -336,7 +347,7 @@ After `uv sync`, fastws runs `cargo develop` in each mixed Rust/Python project.
|
|
|
336
347
|
|
|
337
348
|
Fastws then runs `<tool> install` at the workspace root. It runs `<tool> run build` in each JavaScript package containing both `Cargo.toml` and a `build` script. Cargo handles incremental compilation. Other build steps still run.
|
|
338
349
|
|
|
339
|
-
For npm, sync hides
|
|
350
|
+
For npm, sync hides successful install output and build-command banners. Installs use error-only logging, so npm warnings are hidden while errors and failure output remain visible. Run `npm audit` at the workspace root to inspect audit findings. Build scripts retain their own output; configure their tools to suppress routine progress. Other package managers retain their normal output.
|
|
340
351
|
|
|
341
352
|
When Rust-backed JavaScript builds are present, fastws checks before dependency installation that `rustc` and `cargo` on `PATH` are rustup's proxies. Install rustup from https://rustup.rs and select a stable toolchain with `rustup default stable` if not already configured. If another Rust installation shadows rustup, put its bin directory first on `PATH` after Homebrew's shell setup: `export PATH="$HOME/.cargo/bin:$PATH"` (use `$CARGO_HOME/bin` for a custom Cargo home), then open a new shell. Homebrew Rust can remain installed for Homebrew's own use. Fastws reports missing or shadowed rustup without changing your shell or installing a different toolchain. Packages using wasm-pack can then install their WASM target and matching binding tools automatically as part of their build.
|
|
342
353
|
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import json, shutil, subprocess, pytest, fastws.core as core
|
|
2
|
+
from fastws.cargo import build, check, run_tests, Suite
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _mk_proj(root, name, extra=''):
|
|
6
|
+
d = root/name
|
|
7
|
+
d.mkdir()
|
|
8
|
+
(d/'pyproject.toml').write_text(fr'''[project]
|
|
9
|
+
name = "{name}"
|
|
10
|
+
{extra}
|
|
11
|
+
''')
|
|
12
|
+
return d
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_build_dependency_selection(tmp_path):
|
|
16
|
+
root = tmp_path/'ws'
|
|
17
|
+
root.mkdir()
|
|
18
|
+
_mk_proj(root, 'app', r'''dependencies = ["My.Lib>=1"]''')
|
|
19
|
+
_mk_proj(root, 'my-lib', r'''[build-system]
|
|
20
|
+
requires = ["external"]''')
|
|
21
|
+
external = _mk_proj(tmp_path, 'external', r'''dependencies = ["app", "published-only"]''')
|
|
22
|
+
_mk_proj(root, 'unrelated')
|
|
23
|
+
(root/'repos-local.txt').write_text(f'owner/external {external}')
|
|
24
|
+
assert {n for n,d in core._build_projects(root, 'repos.txt', 'APP')} == {'app', 'my-lib', 'external'}
|
|
25
|
+
with pytest.raises(SystemExit, match='No workspace project'): core._build_projects(root, 'repos.txt', 'missing')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@pytest.mark.parametrize('body, diagnostic', [('', ''), ('let unused = 1;', 'warning'), ('compile_error!("broken");', 'error')])
|
|
29
|
+
def test_build_diagnostics(tmp_path, capfd, monkeypatch, body, diagnostic):
|
|
30
|
+
(tmp_path/'pyproject.toml').write_text('[tool.maturin]\n[tool.fastws]\ncargo = '+json.dumps(shutil.which('cargo'))+'\n')
|
|
31
|
+
monkeypatch.delenv('UV_PROJECT_ENVIRONMENT', raising=False)
|
|
32
|
+
monkeypatch.setenv('VIRTUAL_ENV', str(tmp_path/'.venv'))
|
|
33
|
+
(tmp_path/'Cargo.toml').write_text('[package]\nname = "app"\nversion = "0.1.0"\n[dependencies]\ndep = { path = "dep" }\n')
|
|
34
|
+
(tmp_path/'src').mkdir()
|
|
35
|
+
(tmp_path/'src/lib.rs').write_text('extern crate dep; pub use dep::run;')
|
|
36
|
+
(tmp_path/'dep/src').mkdir(parents=True)
|
|
37
|
+
(tmp_path/'dep/Cargo.toml').write_text('[package]\nname = "dep"\nversion = "0.1.0"\n')
|
|
38
|
+
(tmp_path/'dep/src/lib.rs').write_text(f'pub fn run() {{ {body} }}')
|
|
39
|
+
(tmp_path/'.cargo').mkdir()
|
|
40
|
+
(tmp_path/'.cargo/config.toml').write_text('[term]\nquiet = true\n')
|
|
41
|
+
if diagnostic == 'error':
|
|
42
|
+
with pytest.raises(subprocess.CalledProcessError): build(tmp_path)
|
|
43
|
+
else: assert [m['target']['name'] for m in build(tmp_path)] == ['app']
|
|
44
|
+
stderr = capfd.readouterr().err
|
|
45
|
+
if diagnostic: assert f'[dep] dep/src/lib.rs:1:' in stderr and f': {diagnostic}:' in stderr
|
|
46
|
+
else: assert 'lib.rs:' not in stderr
|
|
47
|
+
checked = check(tmp_path)
|
|
48
|
+
assert checked.ok == (diagnostic != 'error') and [(d.path, d.level) for d in checked.diagnostics] == ([('dep/src/lib.rs', diagnostic)] if diagnostic else [])
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _test_crate(root):
|
|
52
|
+
(root/'Cargo.toml').write_text('[package]\nname = "app"\nversion = "0.1.0"\nedition = "2021"\n')
|
|
53
|
+
(root/'src').mkdir()
|
|
54
|
+
(root/'src/lib.rs').write_text('''pub fn unused() { let x = 1; }
|
|
55
|
+
pub fn two() -> i32 { 2 }
|
|
56
|
+
#[cfg(test)] mod t {
|
|
57
|
+
#[test] fn passes() {}
|
|
58
|
+
#[test] fn fails() { panic!("broken"); }
|
|
59
|
+
#[test] #[ignore] fn skipped() {
|
|
60
|
+
println!("started slow test");
|
|
61
|
+
std::thread::sleep(std::time::Duration::from_secs(60));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
''')
|
|
65
|
+
(root/'tests').mkdir()
|
|
66
|
+
(root/'tests/more.rs').write_text('#[test] fn other() { assert_eq!(app::two(), 2); }\n')
|
|
67
|
+
(root/'.cargo').mkdir()
|
|
68
|
+
(root/'.cargo/config.toml').write_text('[term]\nquiet = true\n')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_run_tests(tmp_path):
|
|
72
|
+
_test_crate(tmp_path)
|
|
73
|
+
r = run_tests(tmp_path, '--no-fail-fast')
|
|
74
|
+
assert not r.ok
|
|
75
|
+
assert [(d.path, d.line, d.level, d.code) for d in r.diagnostics] == [('src/lib.rs', 1, 'warning', 'unused_variables')]
|
|
76
|
+
suites = {s.name: s for s in r.suites}
|
|
77
|
+
unit, more = suites['unittests src/lib.rs'], suites['tests/more.rs']
|
|
78
|
+
assert len(suites) == 2
|
|
79
|
+
assert unit.tests == {'t::passes': 'ok', 't::fails': 'FAILED', 't::skipped': 'ignored'} and unit.failed
|
|
80
|
+
assert 'broken' in unit.failures['t::fails'] and list(unit.failures) == ['t::fails']
|
|
81
|
+
assert more.tests == {'other': 'ok'} and not more.failed
|
|
82
|
+
slow = run_tests(tmp_path, '--lib', test_args=('skipped', '--ignored', '--nocapture'), timeout=.5)
|
|
83
|
+
s, = slow.suites
|
|
84
|
+
assert not slow.ok and s.failed and s.timed_out and 'started slow test' in s.output
|
|
85
|
+
assert str(s) == 'unittests src/lib.rs: ran out of time'
|
|
86
|
+
|
|
87
|
+
(tmp_path/'pyproject.toml').write_text(r'tool.fastws.dev-profile = "missing"')
|
|
88
|
+
r = run_tests(tmp_path, '--test', 'more')
|
|
89
|
+
assert not r.ok and not r.suites and 'missing' in r.text
|
|
90
|
+
for args in [('--profile', 'test'), ('--profile=test',), ('--release',), ('-r',)]:
|
|
91
|
+
assert run_tests(tmp_path, '--test', 'more', *args).ok
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@pytest.mark.skipif(not shutil.which('cargo-nextest'), reason='needs cargo-nextest')
|
|
95
|
+
def test_run_tests_nextest(tmp_path, monkeypatch):
|
|
96
|
+
_test_crate(tmp_path)
|
|
97
|
+
(tmp_path/'pyproject.toml').write_text('[tool.fastws]\ncargo = '+json.dumps(shutil.which('cargo'))+'\n')
|
|
98
|
+
monkeypatch.delenv('UV_PROJECT_ENVIRONMENT', raising=False)
|
|
99
|
+
monkeypatch.setenv('VIRTUAL_ENV', str(tmp_path/'.venv'))
|
|
100
|
+
(tmp_path/'.config').mkdir()
|
|
101
|
+
(tmp_path/'.config/nextest.toml').write_text('[profile.default]\nfail-fast = false\n')
|
|
102
|
+
r = run_tests(tmp_path)
|
|
103
|
+
assert not r.ok and [(d.path, d.level) for d in r.diagnostics] == [('src/lib.rs', 'warning')]
|
|
104
|
+
suites = {s.name: s for s in r.suites}
|
|
105
|
+
unit, more = suites['unittests src/lib.rs'], suites['tests/more.rs']
|
|
106
|
+
assert unit.tests == {'t::passes': 'ok', 't::fails': 'FAILED'} and unit.failed and 'broken' in unit.failures['t::fails']
|
|
107
|
+
assert more.tests == {'other': 'ok'} and not more.failed
|
|
108
|
+
assert run_tests(tmp_path, '--test', 'more', '--profile', 'test').ok
|
|
109
|
+
slow = run_tests(tmp_path, '--lib', test_args=('skipped', '--ignored'), timeout=5)
|
|
110
|
+
s, = slow.suites
|
|
111
|
+
assert not slow.ok and s.timed_out and str(s) == 'nextest: ran out of time'
|
|
112
|
+
|
|
113
|
+
# Editing the working tree after capture must not trigger another Cargo build.
|
|
114
|
+
import fastws.cargo as cargo
|
|
115
|
+
captured = cargo._nextest
|
|
116
|
+
def edit_then_run(*args, **kwargs):
|
|
117
|
+
(tmp_path/'src/lib.rs').write_text('compile_error!("changed after capture");')
|
|
118
|
+
return captured(*args, **kwargs)
|
|
119
|
+
monkeypatch.setattr(cargo, '_nextest', edit_then_run)
|
|
120
|
+
assert run_tests(tmp_path, '--test', 'more').ok
|
|
121
|
+
(tmp_path/'Cargo.toml').write_text('[package]')
|
|
122
|
+
assert not run_tests(tmp_path).ok
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@pytest.mark.skipif(not shutil.which('cargo-nextest'), reason='needs cargo-nextest')
|
|
126
|
+
def test_run_tests_profiles(tmp_path):
|
|
127
|
+
a, b = tmp_path/'a', tmp_path/'b'
|
|
128
|
+
for d in a, b: (d/'.config').mkdir(parents=True)
|
|
129
|
+
_test_crate(a)
|
|
130
|
+
(a/'.config/nextest.toml').write_text('[profile.one]\ndefault-filter = "test(passes) | test(other)"\n[profile.two]\ndefault-filter = "test(fails)"\n')
|
|
131
|
+
(b/'Cargo.toml').write_text('[package]\nname = "b"\nversion = "0.1.0"\nedition = "2021"\n')
|
|
132
|
+
(b/'src').mkdir()
|
|
133
|
+
(b/'src/lib.rs').write_text('')
|
|
134
|
+
(b/'tests').mkdir()
|
|
135
|
+
(b/'tests/fine.rs').write_text('#[test] fn fine() {}\n')
|
|
136
|
+
# Package filters use the all-feature graph, including dependencies disabled in this build.
|
|
137
|
+
dep = b/'optional'
|
|
138
|
+
(dep/'src').mkdir(parents=True)
|
|
139
|
+
(dep/'Cargo.toml').write_text((b/'Cargo.toml').read_text().replace('name = "b"', 'name = "optional"'))
|
|
140
|
+
(dep/'src/lib.rs').write_text('')
|
|
141
|
+
with (b/'Cargo.toml').open('a') as f: f.write(r'''[workspace]
|
|
142
|
+
members = ["optional"]
|
|
143
|
+
default-members = ["."]
|
|
144
|
+
[dependencies]
|
|
145
|
+
optional = { path = "optional", optional = true }
|
|
146
|
+
''')
|
|
147
|
+
(b/'.config/nextest.toml').write_text(r'''[profile.one]
|
|
148
|
+
default-filter = "rdeps(optional)"
|
|
149
|
+
''')
|
|
150
|
+
r = run_tests([a, b], profiles=('one', 'two'))
|
|
151
|
+
tests = {s.name: s.tests for s in r.suites if s.tests}
|
|
152
|
+
assert not r.ok and tests == {'a one: unittests src/lib.rs': {'t::passes': 'ok'}, 'a one: tests/more.rs': {'other': 'ok'},
|
|
153
|
+
'b one: tests/fine.rs': {'fine': 'ok'}, 'a two: unittests src/lib.rs': {'t::fails': 'FAILED'}}, r.text
|
|
154
|
+
first = run_tests([a, b], profiles=('two', 'one'))
|
|
155
|
+
assert not first.ok and {s.name for s in first.suites if s.tests} == {'a two: unittests src/lib.rs'}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_captured_test_output():
|
|
159
|
+
for failed in (False, True):
|
|
160
|
+
lines = ['test passes ... ok', 'successes:', '---- passes stdout ----', 'printed', 'successes:', 'passes']
|
|
161
|
+
if failed:
|
|
162
|
+
lines[1:1] = ['test fails ... FAILED']
|
|
163
|
+
lines += ['failures:', '---- fails stdout ----', 'broken', 'failures:', 'fails']
|
|
164
|
+
lines.append(f'test result: {"FAILED" if failed else "ok"}. 1 passed; {int(failed)} failed; 0 ignored')
|
|
165
|
+
s = Suite.read('unit', lines, int(failed))
|
|
166
|
+
assert s.failures == ({'fails': 'broken'} if failed else {}) and 'printed' in s.output
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import subprocess
|
|
1
|
+
import json, subprocess
|
|
2
2
|
from fastws._toml import tomllib
|
|
3
3
|
from fastws.integrate import _config, code_lines, owners, snapshot
|
|
4
|
+
from fastws.core import _replace_table
|
|
4
5
|
|
|
5
6
|
|
|
6
7
|
def git(repo, *args): return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True).stdout
|
|
@@ -25,12 +26,18 @@ def test_config_points_only_the_roots_crates_at_the_root(tmp_path):
|
|
|
25
26
|
(workspace/".cargo").mkdir(parents=True)
|
|
26
27
|
(workspace/".cargo"/"config.toml").write_text(
|
|
27
28
|
f'[build]\nrustc-wrapper = "/lock"\n\n[patch.crates-io]\na = {{ path = "{workspace}/a" }}\nb = {{ path = "{workspace}/b" }}\n')
|
|
29
|
+
source = workspace/".cargo"/"config.toml"
|
|
30
|
+
content = _replace_table(source.read_text(), "unstable", f" root-dir = {json.dumps(str(workspace))}")
|
|
31
|
+
source.write_text(content.replace("[unstable]", "[unstable] # common source root"))
|
|
28
32
|
(root/"a").mkdir(parents=True)
|
|
29
33
|
(root/"a"/"Cargo.toml").write_text('[package]\nname = "a"\nversion = "0.1.0"\n')
|
|
34
|
+
(root/"c").mkdir()
|
|
35
|
+
(root/"c"/"Cargo.toml").write_text('[package]\nname = "c"\nversion = "0.1.0"\n\n[dependencies]\na = "0.1"\n')
|
|
30
36
|
_config(root, workspace)
|
|
31
37
|
config = tomllib.loads((root/".cargo"/"config.toml").read_text())
|
|
32
38
|
assert config["build"]["rustc-wrapper"] == "/lock"
|
|
33
39
|
assert config["patch"]["crates-io"] == {"a": {"path": str(root/"a")}, "b": {"path": f"{workspace}/b"}}
|
|
40
|
+
assert config["unstable"]["root-dir"] == str(root)
|
|
34
41
|
|
|
35
42
|
|
|
36
43
|
def test_code_lines_skips_blanks_and_comments(tmp_path):
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import fcntl, os, subprocess, sys, pytest
|
|
1
|
+
import fcntl, os, subprocess, sys, threading, pytest
|
|
2
2
|
from fastws.procs import JOB_ENV, kill_group
|
|
3
3
|
|
|
4
4
|
|
|
@@ -25,10 +25,17 @@ time.sleep(60)
|
|
|
25
25
|
'''
|
|
26
26
|
with subprocess.Popen([sys.executable, '-c', job], start_new_session=True, env=os.environ | {JOB_ENV: '1'},
|
|
27
27
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) as p:
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
lines, survived = [], threading.Event()
|
|
29
|
+
def read():
|
|
30
|
+
for line in p.stdout:
|
|
31
|
+
lines.append(line)
|
|
32
|
+
if line.startswith('job survived inner timeout'): survived.set()
|
|
33
|
+
reader = threading.Thread(target=read, daemon=True)
|
|
34
|
+
reader.start()
|
|
35
|
+
try: assert survived.wait(10), ''.join(lines)
|
|
30
36
|
finally: kill_group(p)
|
|
31
|
-
|
|
37
|
+
reader.join(2)
|
|
38
|
+
output = ''.join(lines)
|
|
32
39
|
group = output.split('job group ')[1].split()[0]
|
|
33
40
|
assert f'child group {group} 1' in output and f'descendant group {group}' in output
|
|
34
41
|
assert 'job survived inner timeout' in output
|
|
@@ -171,24 +171,31 @@ def test_sync_cargo_patches_generates_and_preserves(tmp_path):
|
|
|
171
171
|
config = tmp_path/'.cargo'/'config.toml'
|
|
172
172
|
config.write_text('[term]\nquiet = true\n\n[patch.crates-io]\n'
|
|
173
173
|
f'foreign = {{ path = "/elsewhere/foreign" }}\ngone = {{ path = "{tmp_path}/gone" }}\n')
|
|
174
|
-
|
|
175
|
-
crate1
|
|
176
|
-
|
|
174
|
+
config.write_text(core._replace_table(config.read_text(), 'unstable', 'checksum-freshness = true'))
|
|
175
|
+
crate1, helper = tmp_path/'crate1', tmp_path/'helper'
|
|
176
|
+
crate1.mkdir(); helper.mkdir()
|
|
177
|
+
(crate1/'Cargo.toml').write_text('[package]\nname = "crate1"\nversion = "0.1.0"\n\n[dependencies]\nfamily = { git = "https://example.com/family" }\n'
|
|
178
|
+
'\n[dev-dependencies]\nfamily-sub = { version = "0.1" }\n')
|
|
179
|
+
(helper/'Cargo.toml').write_text('[package]\nname = "helper"\nversion = "0.1.0"\n')
|
|
177
180
|
family = tmp_path/'family'
|
|
178
181
|
(family/'sub').mkdir(parents=True)
|
|
179
|
-
(family/'Cargo.toml').write_text('[package]\nname = "family"\nversion = "0.1.0"\npublish = false\n\n[workspace]\nmembers = ["sub"]\n'
|
|
182
|
+
(family/'Cargo.toml').write_text('[package]\nname = "family"\nversion = "0.1.0"\npublish = false\n\n[workspace]\nmembers = ["sub"]\n'
|
|
183
|
+
'\n[workspace.dependencies]\nhelper = "0.1"\ncrate1 = { path = "../crate1", version = "0.1" }\n')
|
|
180
184
|
(family/'sub'/'Cargo.toml').write_text('[package]\nname = "family-sub"\nversion = "0.1.0"\n')
|
|
181
185
|
|
|
182
|
-
added, removed = core._sync_cargo_patches(tmp_path)
|
|
186
|
+
added, removed = core._sync_cargo_patches(tmp_path, root_dir=True)
|
|
183
187
|
data = core.tomllib.loads(config.read_text())
|
|
184
188
|
cio = data['patch']['crates-io']
|
|
185
|
-
assert set(cio) == {'foreign', '
|
|
189
|
+
assert set(cio) == {'foreign', 'family-sub', 'helper'} # only crates that a local manifest requires from crates.io; `crate1` is required by path
|
|
186
190
|
assert cio['foreign']['path'] == '/elsewhere/foreign' # entries pointing outside the root are kept as-is
|
|
187
|
-
assert cio['
|
|
188
|
-
assert cio['
|
|
191
|
+
assert cio['family-sub']['path'] == str(family/'sub') # required as a dev-dependency
|
|
192
|
+
assert cio['helper']['path'] == str(helper) # required in `[workspace.dependencies]`
|
|
189
193
|
assert data['patch']['https://example.com/family']['family']['path'] == str(family) # git deps on local crates get their URL table, published or not
|
|
190
194
|
assert data['term']['quiet'] is True # other sections untouched
|
|
191
|
-
assert set(added) == {'
|
|
195
|
+
assert set(added) == {'family', 'family-sub', 'helper'} and removed == ['gone']
|
|
196
|
+
assert data['unstable'] == {'root-dir': str(tmp_path), 'checksum-freshness': True}
|
|
197
|
+
before = config.read_text()
|
|
198
|
+
assert core._sync_cargo_patches(tmp_path) == ([], []) and config.read_text() == before
|
|
192
199
|
|
|
193
200
|
|
|
194
201
|
def test_sync_ws_package_json_preserves_local_and_merges_shared(tmp_path):
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
import subprocess, pytest, fastws.core as core
|
|
2
|
-
from fastws.cargo import build, check, run_tests, Suite
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
def _mk_proj(root, name, extra=''):
|
|
6
|
-
d = root/name
|
|
7
|
-
d.mkdir()
|
|
8
|
-
(d/'pyproject.toml').write_text(fr'''[project]
|
|
9
|
-
name = "{name}"
|
|
10
|
-
{extra}
|
|
11
|
-
''')
|
|
12
|
-
return d
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
def test_build_dependency_selection(tmp_path):
|
|
16
|
-
root = tmp_path/'ws'
|
|
17
|
-
root.mkdir()
|
|
18
|
-
_mk_proj(root, 'app', r'''dependencies = ["My.Lib>=1"]''')
|
|
19
|
-
_mk_proj(root, 'my-lib', r'''[build-system]
|
|
20
|
-
requires = ["external"]''')
|
|
21
|
-
external = _mk_proj(tmp_path, 'external', r'''dependencies = ["app", "published-only"]''')
|
|
22
|
-
_mk_proj(root, 'unrelated')
|
|
23
|
-
(root/'repos-local.txt').write_text(f'owner/external {external}')
|
|
24
|
-
assert {n for n,d in core._build_projects(root, 'repos.txt', 'APP')} == {'app', 'my-lib', 'external'}
|
|
25
|
-
with pytest.raises(SystemExit, match='No workspace project'): core._build_projects(root, 'repos.txt', 'missing')
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
@pytest.mark.parametrize('body, diagnostic', [('', ''), ('let unused = 1;', 'warning'), ('compile_error!("broken");', 'error')])
|
|
29
|
-
def test_build_diagnostics(tmp_path, capfd, body, diagnostic):
|
|
30
|
-
(tmp_path/'pyproject.toml').write_text('[tool.maturin]\n')
|
|
31
|
-
(tmp_path/'Cargo.toml').write_text('[package]\nname = "app"\nversion = "0.1.0"\n[dependencies]\ndep = { path = "dep" }\n')
|
|
32
|
-
(tmp_path/'src').mkdir()
|
|
33
|
-
(tmp_path/'src/lib.rs').write_text('extern crate dep; pub use dep::run;')
|
|
34
|
-
(tmp_path/'dep/src').mkdir(parents=True)
|
|
35
|
-
(tmp_path/'dep/Cargo.toml').write_text('[package]\nname = "dep"\nversion = "0.1.0"\n')
|
|
36
|
-
(tmp_path/'dep/src/lib.rs').write_text(f'pub fn run() {{ {body} }}')
|
|
37
|
-
(tmp_path/'.cargo').mkdir()
|
|
38
|
-
(tmp_path/'.cargo/config.toml').write_text('[term]\nquiet = true\n')
|
|
39
|
-
if diagnostic == 'error':
|
|
40
|
-
with pytest.raises(subprocess.CalledProcessError): build(tmp_path)
|
|
41
|
-
else: assert [m['target']['name'] for m in build(tmp_path)] == ['app']
|
|
42
|
-
stderr = capfd.readouterr().err
|
|
43
|
-
if diagnostic: assert f'[dep] dep/src/lib.rs:1:' in stderr and f': {diagnostic}:' in stderr
|
|
44
|
-
else: assert 'lib.rs:' not in stderr
|
|
45
|
-
checked = check(tmp_path)
|
|
46
|
-
assert checked.ok == (diagnostic != 'error') and [(d.path, d.level) for d in checked.diagnostics] == ([('dep/src/lib.rs', diagnostic)] if diagnostic else [])
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
def test_run_tests(tmp_path):
|
|
50
|
-
(tmp_path/'Cargo.toml').write_text('[package]\nname = "app"\nversion = "0.1.0"\nedition = "2021"\n')
|
|
51
|
-
(tmp_path/'src').mkdir()
|
|
52
|
-
(tmp_path/'src/lib.rs').write_text('''pub fn unused() { let x = 1; }
|
|
53
|
-
pub fn two() -> i32 { 2 }
|
|
54
|
-
#[cfg(test)] mod t {
|
|
55
|
-
#[test] fn passes() {}
|
|
56
|
-
#[test] fn fails() { panic!("broken"); }
|
|
57
|
-
#[test] #[ignore] fn skipped() {
|
|
58
|
-
println!("started slow test");
|
|
59
|
-
std::thread::sleep(std::time::Duration::from_secs(60));
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
''')
|
|
63
|
-
(tmp_path/'tests').mkdir()
|
|
64
|
-
(tmp_path/'tests/more.rs').write_text('#[test] fn other() { assert_eq!(app::two(), 2); }\n')
|
|
65
|
-
(tmp_path/'.cargo').mkdir()
|
|
66
|
-
(tmp_path/'.cargo/config.toml').write_text('[term]\nquiet = true\n')
|
|
67
|
-
r = run_tests(tmp_path, '--no-fail-fast')
|
|
68
|
-
assert not r.ok
|
|
69
|
-
assert [(d.path, d.line, d.level, d.code) for d in r.diagnostics] == [('src/lib.rs', 1, 'warning', 'unused_variables')]
|
|
70
|
-
suites = {s.name: s for s in r.suites}
|
|
71
|
-
unit, more = suites['unittests src/lib.rs'], suites['tests/more.rs']
|
|
72
|
-
assert len(suites) == 2
|
|
73
|
-
assert unit.tests == {'t::passes': 'ok', 't::fails': 'FAILED', 't::skipped': 'ignored'} and unit.failed
|
|
74
|
-
assert 'broken' in unit.failures['t::fails'] and list(unit.failures) == ['t::fails']
|
|
75
|
-
assert more.tests == {'other': 'ok'} and not more.failed
|
|
76
|
-
slow = run_tests(tmp_path, '--lib', test_args=('skipped', '--ignored', '--nocapture'), timeout=.5)
|
|
77
|
-
s, = slow.suites
|
|
78
|
-
assert not slow.ok and s.failed and s.timed_out and 'started slow test' in s.output
|
|
79
|
-
assert str(s) == 'unittests src/lib.rs: ran out of time'
|
|
80
|
-
|
|
81
|
-
(tmp_path/'pyproject.toml').write_text(r'tool.fastws.dev-profile = "missing"')
|
|
82
|
-
r = run_tests(tmp_path, '--test', 'more')
|
|
83
|
-
assert not r.ok and not r.suites and 'missing' in r.text
|
|
84
|
-
for args in [('--profile', 'test'), ('--profile=test',), ('--release',), ('-r',)]:
|
|
85
|
-
assert run_tests(tmp_path, '--test', 'more', *args).ok
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def test_captured_test_output():
|
|
89
|
-
for failed in (False, True):
|
|
90
|
-
lines = ['test passes ... ok', 'successes:', '---- passes stdout ----', 'printed', 'successes:', 'passes']
|
|
91
|
-
if failed:
|
|
92
|
-
lines[1:1] = ['test fails ... FAILED']
|
|
93
|
-
lines += ['failures:', '---- fails stdout ----', 'broken', 'failures:', 'fails']
|
|
94
|
-
lines.append(f'test result: {"FAILED" if failed else "ok"}. 1 passed; {int(failed)} failed; 0 ignored')
|
|
95
|
-
s = Suite.read('unit', lines, int(failed))
|
|
96
|
-
assert s.failures == ({'fails': 'broken'} if failed else {}) and 'printed' in s.output
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|