From a488d8865053a400333744f43953c63c18d5f80e Mon Sep 17 00:00:00 2001 From: tison Date: Fri, 4 Dec 2026 14:30:21 +0800 Subject: [PATCH] chore: add structured changelog and release automation Hand-maintaining a single prose `CHANGELOG.md` across 18 publishable crates creates merge conflicts on concurrent pull requests, repeats affected crate names in prose, and requires manually syncing version tables and hardcoded `docs.rs` links during partial releases. Introduce a structured changelog ledger under `changes/` paired with `cargo x changelog` and `cargo x release prepare`: - Record unreleased changes as per-topic TOML fragments under `changes/unreleased/.toml` and archive released batches in `changes/releases.toml`, deterministically rendering root `CHANGELOG.md` (verified in `cargo x lint`) and supporting per-crate slice views via `cargo x changelog --crate`. - Automate partial and workspace-wide release preparation via `cargo x release prepare`, enforcing SemVer and RFC 1105 dependency propagation, computing topological publish order (including versioned dev-dependencies), and rewriting manifest versions, `docs.rs` versioned URLs, and root `README.md` MSRV metadata. - Archive the `v0.31.0 (2026-12-03)` release notes into `CHANGELOG-OLD.md`, remove leftover `cargo-release` metadata, and align `AGENTS.md` and `.agents/skills/release/SKILL.md` with the new workflow. Signed-off-by: tison --- .agents/skills/release/SKILL.md | 49 ++- AGENTS.md | 17 +- CHANGELOG-OLD.md | 113 +++++ CHANGELOG.md | 117 +---- Cargo.lock | 178 ++++---- Cargo.toml | 10 +- changes/releases.toml | 2 + changes/unreleased/.gitkeep | 0 examples/Cargo.toml | 3 - licenserc.toml | 1 + tests-integration/Cargo.toml | 3 - xtask/Cargo.toml | 10 +- xtask/src/changelog.rs | 636 +++++++++++++++++++++++++++ xtask/src/lint.rs | 2 + xtask/src/main.rs | 11 + xtask/src/release.rs | 752 ++++++++++++++++++++++++++++++++ xtask/src/test.rs | 2 +- xtask/src/workspace.rs | 192 ++++++++ 18 files changed, 1863 insertions(+), 235 deletions(-) create mode 100644 changes/releases.toml create mode 100644 changes/unreleased/.gitkeep create mode 100644 xtask/src/changelog.rs create mode 100644 xtask/src/release.rs create mode 100644 xtask/src/workspace.rs diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md index 86985673..2d036532 100644 --- a/.agents/skills/release/SKILL.md +++ b/.agents/skills/release/SKILL.md @@ -10,28 +10,30 @@ Use this skill when planning, preparing, verifying, or publishing a Logforth rel ## Core Invariants - **Four-tier publishable DAG**: Logforth publishes 18 crates across four dependency tiers (`libs/*` -> `logforth-core` -> peripheral `0.x` crates -> `logforth` facade; workspace-only `examples`, `tests-integration`, and `xtask` are never published). -- **Partial releases by default**: Bump and publish only crates with user-observable changes or SemVer-propagated dependency updates rather than bumping the entire workspace in lockstep, unless `logforth-core` itself introduces a breaking change. -- **Single frozen `RELEASE_COMMIT`**: Prepare all version bumps, documentation updates, `Cargo.lock` refreshes, and undated changelog sections in one reviewed pull request merged to `main`; never generate per-crate version-bump commits directly on `main`. +- **Partial releases by default**: Bump and publish only crates with user-observable changes or SemVer-propagated dependency updates rather than bumping the entire workspace in lockstep, unless `logforth-core` itself introduces a breaking change or a workspace-wide MSRV increase applies. Do not bump `logforth` solely to create a changelog heading when releasing underlying or standalone crates compatibly. +- **Single frozen `RELEASE_COMMIT`**: Prepare all version bumps, documentation updates, `Cargo.lock` refreshes, and undated structured release entries in one reviewed pull request merged to `main`; never generate per-crate version-bump commits directly on `main`. - **Three-component caret bounds without `=`**: Keep `version = "X.Y.Z"` caret requirements in `[workspace.dependencies]` (never exact `=X.Y.Z` pins on stable releases), and raise external library dependency floors in `[workspace.dependencies]` only when Logforth requires a newly added upstream API or bug fix. - **Explicit authorization for irreversible steps**: Preparing branches, running checks, and drafting pull requests are safe, whereas `cargo publish` and pushing Git tags are irreversible and require explicit maintainer authorization. ## 1. Scope the Release and Choose Target Versions -Sync `origin/main` and existing tags before inspecting diffs: +Sync `origin/main` and existing tags before inspecting diffs and pending fragments: ```shell git fetch origin main --tags git status --short --branch +cargo x changelog +cargo x release prepare ``` -Compare each publishable crate against its own latest `-v` tag (`git log -v..origin/main -- `) alongside `## Unreleased` in `CHANGELOG.md`, then propagate versions up the DAG using pre-`1.0` SemVer (`0.x` minor for breaking changes, patch for compatible features or fixes) and Rust [RFC 1105](https://rust-lang.github.io/rfcs/1105-api-evolution.html) public-dependency rules: +Compare each candidate crate against its own latest `-v` tag (`git log -v..origin/main -- `) alongside `changes/unreleased/*.toml`, then choose target `CRATE=VERSION` pairs using pre-`1.0` SemVer (`0.x` minor for breaking changes, patch for compatible features or fixes) and Rust [RFC 1105](https://rust-lang.github.io/rfcs/1105-api-evolution.html) public-dependency rules: | Tier | Crates | Versioning and Propagation Rule | | :----------------------- | :-------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 1. Standalone libraries | `logforth-logfmt`, `logforth-syslog` | Independent `0.x` tracks with no `logforth-core` dependency. A breaking `0.x` bump in `logforth-logfmt` (private dependency of `logforth-layout-logfmt`) requires only a patch bump in `logforth-layout-logfmt`, whereas a breaking `0.x` bump in `logforth-syslog` (publicly re-exported by `logforth-append-syslog`) propagates breaking `0.x` bumps to `logforth-append-syslog` and `logforth`. | | 2. Core | `logforth-core` | Compatible fixes or additions bump patch (`0.5.x`). A breaking `0.x` bump propagates breaking bumps across all 14 peripheral crates and `logforth`. | | 3. Peripheral extensions | `appenders/*`, `layouts/*`, `filters/*`, `diagnostics/*`, `bridges/*` | Independent `0.x` tracks. A breaking `0.x` bump in any peripheral crate requires a breaking `0.x` minor bump in `logforth` (which publicly re-exports it behind a feature flag) while leaving `logforth-core` and unaffected peripheral crates untouched. | -| 4. Umbrella facade | `logforth` | Bumps `0.x` minor on facade API breaks, MSRV increases, or breaking updates to any re-exported crate; bumps patch on compatible facade changes or when raising `[workspace.dependencies]` floors for underlying fixes and additions so each release train has a canonical `## vX.Y.Z` changelog anchor (unless releasing a standalone `libs/*` crate out-of-band). | +| 4. Umbrella facade | `logforth` | Bumps `0.x` minor on facade API breaks, MSRV increases, or breaking updates to any re-exported crate; bumps patch on compatible facade changes or when intentionally raising `[workspace.dependencies]` floors to guarantee underlying fixes or additions. | For every crate receiving a patch bump (or left unbumped despite source changes), verify SemVer compatibility against the published crates.io baseline: @@ -39,16 +41,25 @@ For every crate receiving a patch bump (or left unbumped despite source changes) cargo semver-checks check-release --package ``` +Preview the explicit release plan and topological publish order before mutating files: + +```shell +cargo x release prepare = ... +``` + ## 2. Prepare the Release Pull Request -Create a single release-preparation branch and pull request (`chore: prepare for releasing `) updating: +Create a single release-preparation branch and pull request (`chore: prepare for releasing `) and apply the release plan: + +```shell +cargo x release prepare = ... --apply +``` + +`cargo x release prepare ... --apply` updates: -1. **Manifests and lockfile**: Update `version` in each bumped `/Cargo.toml` and the matching `version` entries under `[workspace.dependencies]` in root `Cargo.toml` (leaving unchanged crates at their existing versions), then refresh `Cargo.lock` with `cargo check --workspace --all-targets --all-features`. -2. **Versioned `docs.rs` links and badges**: Update hardcoded `https://docs.rs///...` URLs (and the MSRV badge in `README.md` if `rust-version` changed) for every crate whose version changed: - - Root `README.md` (`logforth` links when `logforth` bumps, plus component reference links at the bottom of `README.md` for bumped crates). - - `bridges/log/src/lib.rs` (`https://docs.rs/logforth//...` rustdoc links when `logforth` bumps). - - Affected `/README.md` files (each bumped crate's own `docs.rs` links, plus cross-crate `docs.rs` links pointing at bumped crates). -3. **`CHANGELOG.md`**: Insert `## vX.Y.Z` **without a date** immediately below `## Unreleased` (keeping `## Unreleased` empty at the top), add the aligned 18-crate version matrix table recording the snapshot version of every publishable crate, and finalize user-visible entries against each crate's latest release tag per `AGENTS.md`. +1. **Manifests and lockfile**: Updates `version` in each bumped `/Cargo.toml` and matching entries under `[workspace.dependencies]` in root `Cargo.toml` (leaving unchanged crates untouched), then runs `cargo update --workspace` to refresh `Cargo.lock`. +2. **Versioned `docs.rs` links and MSRV badges**: Rewrites `https://docs.rs///...` URLs across tracked `README.md`, `/README.md`, and `.rs` files (and syncs the MSRV badge and prose in root `README.md` with `rust-version`). +3. **Structured release ledger and `CHANGELOG.md`**: Consumes matching `changes/unreleased/*.toml` fragments into a new undated `[[release]]` entry at the top of `changes/releases.toml` (preserving unrelated fragments for future releases) and regenerates root `CHANGELOG.md`. Review the generated `changes/releases.toml` and `CHANGELOG.md` diff against each crate's latest release tag per `AGENTS.md` to ensure cohesive, user-facing entries. Run the full repository validation suite locally before opening or updating the pull request: @@ -82,26 +93,26 @@ RUSTUP_TOOLCHAIN= cargo x check RUSTUP_TOOLCHAIN= cargo x test ``` -For each crate scheduled for publication, inspect its packaged file manifest to confirm `LICENSE`, `README.md`, and expected source files are present with no stray files: +For each crate scheduled for publication, inspect its packaged file manifest to confirm `README.md` and expected source files are present with no stray files: ```shell cargo package --list --locked --package ``` -When a release bumps only leaf crates whose workspace dependencies are already published on crates.io, also run `cargo publish --dry-run --locked --package `. When both an upstream workspace crate (such as `logforth-core`) and a downstream crate (such as `logforth`) bump in the same release, live-registry `--dry-run` on the downstream crate cannot resolve the unpublished upstream version until the upstream tier is uploaded; run `--dry-run` per tier right after its upstream tier finishes publishing (or validate against a local static registry index). +When a release bumps only leaf crates whose workspace dependencies are already published on crates.io, also run `cargo publish --dry-run --locked --package `. When both an upstream workspace crate (such as `logforth-core` or `logforth-layout-json`) and a downstream crate (such as `logforth` or an appender with a versioned `logforth-layout-json` dev-dependency) bump in the same release, live-registry `--dry-run` on the downstream crate cannot resolve the unpublished upstream version until the upstream crate is uploaded; run `--dry-run` right after its upstream dependencies finish publishing. If any check fails, land the fix through a new reviewed pull request on `main` and advance `RELEASE_COMMIT` before publishing or tagging. ## 4. Publish Updated Crates in Topological Order -Once authorized to publish, upload **only** crates whose `(name, version)` in `Cargo.toml` is not yet published on crates.io, proceeding strictly tier by tier from the detached `RELEASE_COMMIT` checkout: +Once authorized to publish, upload **only** crates whose `(name, version)` in `Cargo.toml` is not yet published on crates.io, proceeding strictly in the topological publish order printed by `cargo x release prepare` from the detached `RELEASE_COMMIT` checkout: 1. **Tier 1 (Standalone libraries)**: `logforth-logfmt`, `logforth-syslog` 2. **Tier 2 (Core)**: `logforth-core` -3. **Tier 3 (Peripheral extensions)**: `logforth-append-async`, `logforth-append-fastrace`, `logforth-append-file`, `logforth-append-journald`, `logforth-append-opentelemetry`, `logforth-append-syslog`, `logforth-bridge-log`, `logforth-diagnostic-fastrace`, `logforth-diagnostic-task-local`, `logforth-filter-rustlog`, `logforth-layout-google-cloud-logging`, `logforth-layout-json`, `logforth-layout-logfmt`, `logforth-layout-text` +3. **Tier 3 (Peripheral extensions)**: Publish `logforth-layout-json` before `logforth-append-file` and `logforth-append-opentelemetry` (which carry versioned `logforth-layout-json` dev-dependencies); publish remaining bumped peripheral crates in deterministic order. 4. **Tier 4 (Umbrella facade)**: `logforth` -For each crate in tier order, check crates.io before publishing so reruns after rate limits or transient network errors remain idempotent: +For each crate in topological order, check crates.io before publishing so reruns after rate limits or transient network errors remain idempotent: ```shell if cargo info "@" --registry crates-io >/dev/null 2>&1; then @@ -113,7 +124,7 @@ fi ## 5. Tag Published Crates and Record the Release Date -Create GPG-signed annotated Git tags on `RELEASE_COMMIT` **strictly for the crates published in this release**, matching the `-v` naming and message format in `[workspace.metadata.release]`: +Create GPG-signed annotated Git tags on `RELEASE_COMMIT` **strictly for the crates published in this release**: ```shell test "$(git rev-parse HEAD)" = "${RELEASE_COMMIT}" @@ -129,4 +140,4 @@ After verifying every new tag signature and target commit (`test "$(git rev-pars git push origin ... ``` -Confirm crates.io availability (`cargo info @ --registry crates-io`) and docs.rs builds for the published crates, remove the temporary detached worktree (`git worktree remove "${RELEASE_DIR}/checkout" && rm -rf "${RELEASE_DIR}"`), and open a follow-up pull request adding the actual UTC publication date (`## vX.Y.Z (YYYY-MM-DD)`) to `CHANGELOG.md`. +Confirm crates.io availability (`cargo info @ --registry crates-io`) and docs.rs builds for the published crates, remove the temporary detached worktree (`git worktree remove "${RELEASE_DIR}/checkout" && rm -rf "${RELEASE_DIR}"`), and open a follow-up pull request setting `date = "YYYY-MM-DD"` (actual UTC publication date) on the new `[[release]]` record in `changes/releases.toml` and regenerating `CHANGELOG.md` with `cargo x changelog --write`. diff --git a/AGENTS.md b/AGENTS.md index fb445214..886a11f2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,10 @@ Use `cargo x` as the single entrypoint for repository checks and automation (rea cargo x build # Compile all workspace packages and targets with all features cargo x check # Check workspace packages across feature configurations cargo x test # Run workspace tests with all features enabled (--no-capture supported) -cargo x lint # Run nightly clippy, rustfmt, taplo, typos, hawkeye, and docsrs rustdoc checks -cargo x lint --fix # Automatically apply clippy, rustfmt, taplo, and hawkeye fixes +cargo x lint # Run nightly clippy, rustfmt, changelog check, taplo, typos, hawkeye, and rustdoc +cargo x lint --fix # Automatically apply clippy, rustfmt, changelog, taplo, and hawkeye fixes +cargo x changelog # Preview unreleased and released changelogs (--check, --write, --crate supported) +cargo x release prepare # Inspect release candidates or apply explicit CRATE=VERSION bumps (--apply) ``` `cargo x lint` requires a `nightly` toolchain with `rustfmt` and `clippy`. CI also verifies both `stable` and the workspace MSRV (`rust-version` in `Cargo.toml`) across Linux, macOS, and Windows. @@ -61,13 +63,12 @@ Use the shared [release skill](.agents/skills/release/SKILL.md) to prepare, veri ## Changelog -- Update `CHANGELOG.md` in the same pull request for significant user-visible changes by comparing the final behavior with the affected crate's latest release tag rather than recording the sequence of commits that produced it. -- Before adding a breaking-change or bug-fix entry, verify from the latest release tag that the previous or faulty behavior was shipped. If the affected API or behavior in an existing crate is itself unreleased, or if a new crate has not yet been released, describe only its final contract in the relevant feature or migration entry and omit development-only corrections. +- Record significant user-visible changes in the same pull request by adding or updating a topic fragment under `changes/unreleased/.toml` (`` uses lowercase ASCII letters, digits, and hyphens), comparing the final behavior with each affected crate's latest `-v` release tag rather than recording the sequence of commits that produced it. Do not hand-edit `CHANGELOG.md` or commit rendered unreleased sections in feature pull requests; preview locally with `cargo x changelog`. +- Before adding a breaking-change or bug-fix entry, verify from the latest release tag that the previous or faulty behavior was shipped. Check existing files in `changes/unreleased/` before creating a new fragment: if a subsequent pull request refines or reverts an unreleased change, update or remove the existing `.toml` file in place so only the final shipped contract is described. - Include public API migrations, new capabilities, correctness or compatibility changes, and meaningful performance improvements. Exclude tests, internal refactors, documentation, CI, tooling, and dependency maintenance unless they change user-observable behavior relative to the latest release or resolve security advisories. -- Keep the permanent `## Unreleased` section at the top. Group entries under `### Breaking changes`, `### Notable changes`, `### New features`, `### Improvements`, `### Performance improvements`, and `### Bug fixes` in that order, adding only categories that contain entries. -- Within each category, order entries from workspace-wide changes down through `logforth-core`, `logforth`, layouts, appenders, filters, diagnostics, bridges, and standalone libraries, keeping one coherent user-observable outcome per bullet instead of chaining unrelated crates or APIs together. -- Write concise, single-line bullets using consistent phrasing (`Remove ...`, `Replace ...`, `Rename ...`, `Upgrade ...`, or ` now ...` for breaking changes, `Add ...` for new features, imperative verbs for improvements, `Speed up ...`, `Reduce ...`, or `Avoid ...` for performance improvements, and ` now ...` or ` no longer ...` for bug fixes). Name the affected crate and public API, give required migration steps for breaking changes, and omit pull request numbers, issue numbers, repository file links, discarded intermediate designs, and internal implementation mechanics. -- During release preparation, insert `## vX.Y.Z` without a date immediately below `## Unreleased` and move the accumulated entries into it. Add the actual UTC release date in `YYYY-MM-DD` format after publication; do not guess it in advance or remove `## Unreleased`. +- Each fragment file contains one or more `[[change]]` tables with `category` (`"breaking"`, `"notable"`, `"feature"`, `"improvement"`, `"performance"`, or `"fix"`), `crates` (complete publishable package names whose own public contract changed, such as `["logforth-core"]`; list `"logforth"` only for `starter_log`, facade re-export, or feature-flag changes, and use `workspace = true` without `crates` for workspace-wide changes such as MSRV updates), and a single-line `text` string. +- Keep one coherent user-observable outcome per `[[change]]` entry instead of chaining unrelated APIs together. Write concise, single-line `text` values without a leading bullet or repeated crate names (`cargo x changelog` renders bold component labels and canonical ordering automatically), using consistent phrasing (`Remove ...`, `Replace ...`, `Rename ...`, `Upgrade ...`, or ` now ...` for breaking changes, `Add ...` for new features, imperative verbs for improvements, `Speed up ...`, `Reduce ...`, or `Avoid ...` for performance improvements, and ` now ...` or ` no longer ...` for bug fixes), giving required migration steps for breaking changes, and omitting pull request numbers, issue numbers, repository file links, discarded intermediate designs, and internal implementation mechanics. +- During release preparation, run `cargo x release prepare = ... --apply` to move matching unreleased fragments into `changes/releases.toml` without a `date` and regenerate `CHANGELOG.md` (releases up to `v0.31.0` remain archived in `CHANGELOG-OLD.md`). After publication, record the actual UTC release date (`date = "YYYY-MM-DD"`) on the `[[release]]` entry in `changes/releases.toml` and run `cargo x changelog --write`. ## Pull Requests diff --git a/CHANGELOG-OLD.md b/CHANGELOG-OLD.md index ddfe3c6d..6c732b27 100644 --- a/CHANGELOG-OLD.md +++ b/CHANGELOG-OLD.md @@ -1,5 +1,118 @@ # Historical Changelog +## v0.31.0 (2026-12-03) + +| Crate | Version | +| :------------------------------------- | :------- | +| `logforth` | `0.31.0` | +| `logforth-core` | `0.5.0` | +| `logforth-logfmt` | `0.1.0` | +| `logforth-syslog` | `0.1.0` | +| `logforth-append-async` | `0.5.0` | +| `logforth-append-fastrace` | `0.5.0` | +| `logforth-append-file` | `0.5.0` | +| `logforth-append-journald` | `0.5.0` | +| `logforth-append-opentelemetry` | `0.5.0` | +| `logforth-append-syslog` | `0.5.0` | +| `logforth-bridge-log` | `0.5.0` | +| `logforth-diagnostic-fastrace` | `0.5.0` | +| `logforth-diagnostic-task-local` | `0.5.0` | +| `logforth-filter-rustlog` | `0.5.0` | +| `logforth-layout-google-cloud-logging` | `0.5.0` | +| `logforth-layout-json` | `0.5.0` | +| `logforth-layout-logfmt` | `0.5.0` | +| `logforth-layout-text` | `0.5.0` | + +### Breaking changes + +* Raise the minimum supported Rust version (MSRV) from `1.89.0` to `1.91.0`. +* Upgrade `jiff` from `0.2` to `1.0` in `logforth-append-file`, `logforth-layout-json`, `logforth-layout-logfmt`, and `logforth-layout-text`. +* Remove `anyhow` from `logforth-core` and redesign `Error`: `Error::new` now accepts `impl Into>`, `Error::with_source` accepts `impl Into>` and replaces any existing source instead of panicking, and `Error::{with_context, sources, from_io_error, from_fmt_error}` are removed; walk `.source()` for causal chains and construct descriptive `Error::new(...).with_source(...)` values at call sites. +* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`; configure runtime error handling via `LoggerBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log::LogStarter::error_sink`. +* Remove the `const APPEND: bool` generic parameter from `DispatchBuilder` in `logforth-core`; `DispatchBuilder::append` now returns `Self` in any order, and dispatches configured with no appenders are skipped when registered on `LoggerBuilder`. +* Replace `Filter::{enabled, matches}` and `FilterCriteria` in `logforth-core` with `Filter::{filter_level(&self, level: Level) -> FilterResult, filter(&self, record: &Record, diags: &dyn Diagnostic) -> FilterResult}`, precomputing level bitmasks across `Level::ALL` at `Logger` build time and changing `Logger::enabled` to accept `Level` instead of `&FilterCriteria`. +* Mark `record::LevelFilter` as `#[non_exhaustive]` in `logforth-core`; use `LevelFilter::test` or add a wildcard arm when matching. +* Replace `&[Box]` with `&dyn Diagnostic` across `Filter::filter`, `Layout::format`, `Append::append`, and `MakeBody::create` in `logforth-core`, `logforth`, and peripheral crates, and relax the `'static` supertrait bound on `Diagnostic` to the `Box` registration boundary; traverse diagnostics via `diags.visit(&mut visitor)` and pass `&()` for an empty context. +* Change `Layout::format` in `logforth-core` and built-in layouts to append formatted bytes into a caller-supplied `&mut Vec` and return `Result<(), Error>` instead of `Result, Error>`. +* Remove `Record::{target, target_static}` and `RecordBuilder::{target, target_static}` from `logforth-core`, updating `PlainTextLayout`, `TextLayout`, `JsonLayout` (now serializing `"module_path"`), and `LogfmtLayout` to read `Record::module_path`, stopping `OpentelemetryLog` from calling `LogRecord::set_target` (preserving the configured `InstrumentationScope` name), and omitting the non-standard `TARGET` field in `Journald`. +* Change `Record::filename` from `Cow<'a, str>` to `Option<&'a str>`, change `Record::key_values` from `&KeyValues<'a>` to `KeyValues<'a>` by value, and replace `Record::builder` with `RecordBuilder::new` in `logforth-core`; unwrap or match `Record::filename` when a fallback string is needed. +* Require `Sync` on `kv::Value::{debug, display}` in `logforth-core` so `Value<'a>` implements `Send + Sync` (local formatters over non-`Sync` values can construct `kv::DebugValue::new` and `kv::DisplayValue::new` directly), change `ValueOwned::bytes` to accept `impl Into>`, replace `ValueOwned::{from_vec, from_hash_map}` with insertion-ordered `ValueOwned::{list, map}`, and resolve duplicate keys in `KeyValues::get` and `MapValue::get` using last-entry-wins order. +* Change `StaticDiagnostic` and `ThreadLocalDiagnostic` in `logforth-core` to store `(KeyOwned, ValueOwned)` instead of `(String, String)`: `StaticDiagnostic::new` now accepts `IntoIterator`, `StaticDiagnostic::insert` accepts `K: Into` and `V: Into`, and `ThreadLocalDiagnostic::{insert, remove}` are replaced by `ThreadLocalDiagnostic::scope` returning a `!Send` `ThreadLocalDiagnosticGuard`. +* Remove `Copy` from `ThreadLocalDiagnostic` in `logforth-core`, `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`, and `FastraceDiagnostic` in `logforth-diagnostic-fastrace`. +* Reserve the `logforth.` key prefix in key-value pairs for Logforth (`"logforth.log_target"` carries explicit `log` target overrides from `LogBridge` into `RustLogFilter`). +* Promote `Logger`, `LoggerBuilder`, `DispatchBuilder`, and `builder` to the `logforth` crate root (removing `logforth::core`), remove `starter_log::builder` and `LogStarterBuilder`, unify `LogStarterTestingBuilder` and `LogStarterStdStreamBuilder` into `starter_log::LogStarter`, and replace `apply` / `try_apply` with `starter_log::LogStarterExt::{install, try_install}` (implemented for `Logger`, `LoggerBuilder`, `LogStarter`, and `LogBridge`). +* Replace `colored` with `anstyle` in `logforth-layout-text`: `TextLayout::{fatal_color, error_color, warn_color, info_color, debug_color, trace_color}` now accept `impl Into` (re-exported via `logforth_layout_text::anstyle`), and `TextLayout` emits ANSI colors deterministically without per-record heap allocations unless `TextLayout::no_color` is set. +* Remove `{TextLayout, JsonLayout}::timestamp_format` in `logforth-layout-text` and `logforth-layout-json`; configure timestamps declaratively with `.timezone(tz)` (`+HH:MM`), `.utc()` (`Z`), `.precision(u8)` (default `6` for microseconds), or `TextLayout::no_timestamp()`, and implement `Layout` directly for custom timestamp formats. +* Rename `JsonLayout`'s structured record key-value and diagnostic sub-objects in `logforth-layout-json` from `"kvs"` and `"diags"` to `"attributes"` and `"context"`. +* Align `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` with Google Cloud Structured Logging: map all 24 `Level` severities to canonical `LogSeverity` strings (`DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`, and `EMERGENCY`), format `logging.googleapis.com/labels` values as JSON strings, omit `logging.googleapis.com/sourceLocation` when `file`, `line`, and `module_path` are all unset, and extract Cloud Trace correlation fields only from `Diagnostic` `("trace_id", "span_id", "sampled")` entries (removing the `"trace_sampled"` diagnostic alias and keeping `Record::key_values()` entries as ordinary payload or label fields). +* Replace `AsyncBuilder::buffered_lines_limit(Option)` with `AsyncBuilder::max_buffered_records(NonZeroUsize)` and change `AsyncBuilder::build` to return `Result` in `logforth-append-async`, returning `Err` instead of panicking when `thread_name` contains NUL bytes or OS thread creation fails; pass a `NonZeroUsize` limit when bounding buffered records (omit `max_buffered_records` for unbounded buffering) and handle the `Result` from `build`. +* `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover: unrotated output remains `[.]`, time-only rotation writes `.[.]`, size rotation numbers segments in ascending order from `1` (oldest) as `[.].[.]`, `max_log_files` counts the active file toward the retention limit, and files from the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed. +* `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after, and `FileBuilder::build` now returns `Err` when `filename` is empty or when `filename` or `filename_suffix` is `.` or `..` or contains path separators or NUL bytes; update callers to pass `NonZeroU64` and valid filename components. +* Remove the redundant `"timestamp"` event property (and `jiff` dependency) from `FastraceEvent` in `logforth-append-fastrace` and require an active sampled `SpanContext::current_local_parent()` before recording events (skipping parentless `LocalCollector::start()` scopes); read event timestamps from `fastrace::collector::EventRecord::timestamp_unix_ns` instead. +* Broaden `Journald::with_syslog_identifier` in `logforth-append-journald` from `String` to `impl Into`; pass string literals directly without `.into()` where type inference would otherwise be ambiguous. +* Upgrade `opentelemetry` and `opentelemetry_sdk` from `0.32.0` to `0.33.1` (re-exporting both crates), remove the mandatory `opentelemetry-otlp` dependency, and replace `OpentelemetryLogBuilder` (including `OpentelemetryLogBuilder::{label, labels}`) with `OpentelemetryLog::{new, with_make_body}` over `(InstrumentationScope, SdkLoggerProvider)` in `logforth-append-opentelemetry` so multiple channels can share a provider, custom `Resource` attributes, and custom `LogProcessor` pipelines without premature shutdown on `Drop`. +* `OpentelemetryLog` in `logforth-append-opentelemetry` now emits source location attributes under `code.module.name` (`Record::module_path`), `code.file.path`, `code.line.number`, and `code.column.number` instead of `module_path`, `file`, `line`, and `column`; update queries and processors matching the previous attribute names. +* Replace `fasyslog` with `logforth-syslog` in `logforth-append-syslog` and remove the `rustls` and `native-tls` Cargo features from `logforth-append-syslog` and `logforth`: `Syslog` and `SyslogBuilder` are renamed to `SocketSyslog` and `SocketSyslogBuilder` (re-exported as `logforth::append::SocketSyslog`), and `Facility`, `Severity`, `ParseError`, `SyslogContext`, `Framing`, and `jiff` are exported at the crate root. +* Mark `SyslogFormat` as `#[non_exhaustive]` in `logforth-append-syslog` and rename its variants `{RFC3164, RFC5424}` to `{Rfc3164, Rfc5424}`. +* Replace `{tcp_well_known, udp_well_known, broadcast_well_known, rustls*, native_tls*, new}` on `SocketSyslogBuilder` in `logforth-append-syslog` with fallible constructors returning `Result` (preserving `io::Error` via `.source()`), auto-binding `udp(remote)` (use `udp_bind` or `udp_socket` for explicit sockets), `tcp_tls(addr, handshake)` over caller-supplied TLS closures (defaulting to `Rfc5424` with RFC 5425 `Framing::OctetCounting`), and unbuffered `Framing::LineFeed` (`\n`) with lazy reconnection instead of buffered `\r\n` on stream transports. +* `RustLogFilterBuilder::{from_default_env, from_default_env_or, from_env, from_env_or, from_spec}` in `logforth-filter-rustlog` now return `Result` and fail fast on malformed directives or non-UTF-8 environment variables instead of printing warnings to standard error, `RustLogFilterBuilder::{filter_level, filter_module}` are renamed to `{fallback, prefix}`, `RustLogFilterBuilder::try_from_spec` is removed, and `From<&str>` for `RustLogFilter` is replaced with `TryFrom<&str>`. +* `FutureExt::with_task_local_context` in `logforth-diagnostic-task-local` now accepts `IntoIterator` where `K: Into` and `V: Into` instead of `IntoIterator` and returns the named `TaskLocalFuture` wrapper, preserving typed values instead of converting them to strings and shadowing outer entries for the same key in nested scopes; pass keys and values directly without `.into()` where type inference would otherwise be ambiguous. +* `LogBridge::new` in `logforth-bridge-log` now accepts `Logger` by value instead of `impl Into>` (pass `logger.clone()` when retaining another handle), and `Deref` is replaced with explicit `LogBridge::{logger, into_logger}` accessors so `Log::{enabled, log}` no longer collide with `Logger::{enabled, log}`. + +### New features + +* Add native structured logging macros (`log!`, `trace!`, `debug!`, `info!`, `warn!`, `error!`, and `fatal!`) in `logforth-core` and `logforth` supporting bracketed `"key" = value` fields on explicit `Logger` handles. +* Add `Level::ALL` and `RecordBuilder::time` in `logforth-core` to enumerate all 24 severities and construct records with an explicit observed timestamp. +* Add `ValueOwned::{from_serde, try_from_serde}` and `kv::ValueSerde` (`new`, `Deref`, and `LogValue`, behind the `serde` feature) in `logforth-core` to convert `serde::Serialize` values into `ValueOwned` snapshots without panicking or capture them as lazy structured fields. +* Add `kv::LogValue`, `Value::{owned, lazy_owned, to_owned}`, `Key::{as_str, to_owned}`, `KeyOwned::as_str`, `DebugValue::new`, `DisplayValue::new`, `KeyView::to_static_str`, and `ValueView::{is_none, to_bytes}` in `logforth-core`, and implement `From` on `kv::{KeyOwned, ValueOwned}` across scalars (including `NonZero*` integers), strings, byte slices, `Option`, and borrowed `kv::{Key, KeyView, Value, ValueView}`. +* Add `ThreadLocalDiagnostic::scope` and `ThreadLocalDiagnosticGuard` in `logforth-core` for `!Send` RAII scoped thread-local diagnostics that restore shadowed entries on drop. +* Add `Error::message` and `LoggerBuilder::error_sink` in `logforth-core` (plus `starter_log::LogStarter::error_sink` in `logforth`) to inspect an error's own message and configure runtime error handling. +* Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline, and add `const fn Logger::noop()`, `LoggerBuilder::new()` and `RecordBuilder::new()` (with `Default`), `const fn new()` on `PlainTextLayout`, `ThreadLocalDiagnostic`, `StderrErrorSink`, and `BlackHoleErrorSink`, and `new()` on `Stdout`, `Stderr`, and `Testing` in `logforth-core`. +* Implement `Append`, `ErrorSink`, `Filter`, and `Layout` in `logforth-core`, and `MakeBody` in `logforth-append-opentelemetry`, for `Arc` and `&'static T` where `T: ?Sized`, and implement `Diagnostic` for `&T`, `Arc`, `()`, `Option`, slices, arrays, and `Vec` (including non-`'static` boxed trait objects). +* Add `starter_log::{LogStarterExt, LogStarter::try_build}` (with `Debug` for `LogStarter`), `layout::{json, logfmt}` module re-exports, and the `serde` feature (`logforth-core/serde`) in `logforth`. +* Add `const fn new()` on `GoogleCloudLoggingLayout`, `new()` on `TextLayout`, `LogfmtLayout`, and `JsonLayout`, `TextLayout::{no_timestamp, no_module_path, no_file}`, and `.utc()` / `.precision(u8)` across `TextLayout`, `LogfmtLayout`, and `JsonLayout` for zero-allocation RFC 3339 timestamp formatting. +* Emit `Record::column` across built-in layouts and omit unset location segments when `filename` or `module_path` is unset instead of formatting empty or `0` placeholders: `PlainTextLayout`, `TextLayout`, and `LogfmtLayout` format locations as `filename:line:column` (defaulting unset line or column numbers to `0` when `filename` is present), and `JsonLayout` emits `"column"` when set. +* Add `FileBuilder::timezone` and re-export `jiff` in `logforth-append-file` to configure the timezone used for rotation boundaries and segment filenames, defaulting to the system timezone. +* Add `Journald::{from_socket_path, socket_path}` in `logforth-append-journald`. +* Extract valid `Diagnostic` `("trace_id", "span_id")` pairs and optional boolean `"sampled"` flags into `LogRecord::set_trace_context` in `logforth-append-opentelemetry`. +* Add `PosixSyslog`, `PosixSyslogBuilder`, `{PosixSyslogOptions, posix_openlog, posix_closelog}` (`cfg(unix)`), and `SocketSyslogBuilder::{udp_socket, framing, timezone}` in `logforth-append-syslog` (re-exporting `PosixSyslog` as `logforth::append::PosixSyslog`). +* Add `const fn new()` on `FastraceEvent` in `logforth-append-fastrace`, `FastraceDiagnostic` in `logforth-diagnostic-fastrace`, and `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`. +* Add `LogBridge::{max_level, logger, into_logger, try_install, install}`, `Clone`, `Default`, `From`, and `pub extern crate log` in `logforth-bridge-log`, updating `log::set_max_level` automatically from enabled logger levels on installation. +* Add the standalone `#![no_std]` (`alloc`) `logforth-logfmt` crate providing a zero-dependency `logfmt` `Encoder` and zero-copy `Decoder`, and back `LogfmtLayout` in `logforth-layout-logfmt` with it. +* Add the standalone `logforth-syslog` crate providing RFC 3164 and RFC 5424 formatters (`SyslogContext`, `SdElement`, `SdParam`, `format_rfc3164`, `format_rfc5424`), datagram and reconnectable stream senders (`UdpSender`, `TcpSender`, `TcpTlsSender`, `UnixDatagramSender`, `UnixStreamSender`, `Sender`, `Framing`), and a Unix POSIX `` backend (`posix::{LogOptions, openlog, syslog, closelog}`). + +### Improvements + +* Make `LevelFilter::test`, `Record` field accessors, and `Record::to_builder` `const fn`, return the closure result from `RecordOwned::with`, and implement `Hash` for `FilterResult` in `logforth-core`. +* Implement `Copy` for `kv::{Key, KeyView, Value, ValueView}`, `AsRef` for `kv::{Key, KeyOwned, KeyView}`, `IntoIterator` for `kv::{KeyValues, ListValue, MapValue}`, `serde::Serialize` for `kv::{KeyValues, DebugValue, DisplayValue}` (behind `serde`), `Clone` and `Debug` for `kv::KeyValuesIter`, and `kv::Visitor` for `FnMut(KeyView, ValueView) -> Result<(), Error>` closures in `logforth-core`. +* Perform lossless checked range conversions across integer variants in `ValueView::{to_i64, to_u64, to_i128, to_u128}` in `logforth-core`. +* Write `kv::ValueView::Bytes` as raw binary field payloads in `logforth-append-journald`. +* Map `kv::ValueView::Bytes` to `AnyValue::Bytes` and omit empty default message bodies (leaving `SdkLogRecord::body` unset) in `logforth-append-opentelemetry`. +* Derive `PartialEq`, `Eq`, `Hash`, and `Default` (`Rfc3164`) for `SyslogFormat` in `logforth-append-syslog`. +* Implement `Clone` for `RustLogFilter` and `Clone` plus `const fn new()` for `RustLogFilterBuilder` in `logforth-filter-rustlog`, and normalize empty prefixes (`""` and `=level`) to the fallback rule. + +### Performance improvements + +* Avoid per-record intermediate value, string, and map allocations when formatting records in `JsonLayout`, `LogfmtLayout`, `GoogleCloudLoggingLayout`, `FastraceDiagnostic`, and `Journald` (preserving `Record::key_values` insertion order in `JsonLayout`). +* Avoid formatting message payloads and event properties in `FastraceEvent` when no sampled local parent span is active. +* Speed up level filtering in `RustLogFilter` by short-circuiting levels that are rejected or unconditionally accepted across all directives before prefix matching. + +### Bug fixes + +* `ValueView`'s `Display` implementation in `logforth-core` now formats list and map entries as values and string keys instead of internal wrapper representations. +* `Logger::log` and `Logger::flush` in `logforth-core` no longer panic when writing internal error reports to standard error fails. +* `PlainTextLayout` and `TextLayout` now omit the message separator space when the formatted payload is empty and return `Err` without modifying the output buffer instead of panicking when formatting fails. +* `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `GoogleCloudLoggingLayout` now return `Err` instead of panicking on out-of-range record timestamps. +* `JsonLayout` and `GoogleCloudLoggingLayout` now serialize 128-bit integers outside 64-bit bounds as JSON numbers instead of degrading values or enclosing containers to strings. +* `LogfmtLayout` in `logforth-layout-logfmt` now escapes quoted strings with standard `\"`/`\\`/`\n`/`\r`/`\t`/`\u00XX` escapes instead of Rust debug escapes, encodes `ValueView::None` as `null` and literal `"null"` as `"\"null\""`, strips invalid characters from keys, and returns `Err` on empty keys. +* `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` now gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. +* `Async` in `logforth-append-async` now flushes inner appenders on `Drop` after draining queued records, isolates panics in inner appenders and `ErrorSink` during `append`, `flush`, and shutdown instead of terminating the worker thread or panicking in `Drop`, and waits for full bounded queues to drain during `flush` under `overflow_drop_incoming`. +* `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, and no longer panics or truncates timestamps and file sizes on matching prefix/suffix edge cases, out-of-range timestamps, or 32-bit targets. +* `OpentelemetryLog` in `logforth-append-opentelemetry` now deduplicates top-level log attribute keys by default (giving explicit `Record` key-values precedence over `Diagnostic` entries and `Diagnostic` entries precedence over `code.*` source location attributes); call `OpentelemetryLog::allow_duplicate_keys` to forward repeated keys unmodified. +* `OpentelemetryLog` in `logforth-append-opentelemetry` now sets `LogRecord::set_timestamp` from `Record::time()` instead of overwriting the event timestamp with `SystemTime::now()`. +* `SocketSyslog` in `logforth-append-syslog` now formats syslog header timestamps from `Record::time()` instead of overwriting them with `SystemTime::now()`, and omits the RFC 3164 `HOSTNAME` token on local Unix socket builders (`SocketSyslogBuilder::{unix, unix_datagram, unix_stream}`) so `systemd-journald` and `rsyslog` parse `TAG[PID]` accurately. +* `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` no longer panic when logging during thread-local teardown, degrading to an empty context instead. + ## v0.30.1 (2026-06-03) ### Improvements diff --git a/CHANGELOG.md b/CHANGELOG.md index cd0f165e..98a1344e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,118 +1,7 @@ # Changelog -All significant changes to this project will be documented in this file. +All significant changes to this project are documented in this file. Unreleased change fragments live in [`changes/unreleased`](changes/unreleased); run `cargo x changelog` to preview them locally. -## Unreleased + -## v0.31.0 - -| Crate | Version | -| :------------------------------------- | :------- | -| `logforth` | `0.31.0` | -| `logforth-core` | `0.5.0` | -| `logforth-logfmt` | `0.1.0` | -| `logforth-syslog` | `0.1.0` | -| `logforth-append-async` | `0.5.0` | -| `logforth-append-fastrace` | `0.5.0` | -| `logforth-append-file` | `0.5.0` | -| `logforth-append-journald` | `0.5.0` | -| `logforth-append-opentelemetry` | `0.5.0` | -| `logforth-append-syslog` | `0.5.0` | -| `logforth-bridge-log` | `0.5.0` | -| `logforth-diagnostic-fastrace` | `0.5.0` | -| `logforth-diagnostic-task-local` | `0.5.0` | -| `logforth-filter-rustlog` | `0.5.0` | -| `logforth-layout-google-cloud-logging` | `0.5.0` | -| `logforth-layout-json` | `0.5.0` | -| `logforth-layout-logfmt` | `0.5.0` | -| `logforth-layout-text` | `0.5.0` | - -### Breaking changes - -* Raise the minimum supported Rust version (MSRV) from `1.89.0` to `1.91.0`. -* Upgrade `jiff` from `0.2` to `1.0` in `logforth-append-file`, `logforth-layout-json`, `logforth-layout-logfmt`, and `logforth-layout-text`. -* Remove `anyhow` from `logforth-core` and redesign `Error`: `Error::new` now accepts `impl Into>`, `Error::with_source` accepts `impl Into>` and replaces any existing source instead of panicking, and `Error::{with_context, sources, from_io_error, from_fmt_error}` are removed; walk `.source()` for causal chains and construct descriptive `Error::new(...).with_source(...)` values at call sites. -* Replace `Trap`, `trap::BestEffortTrap`, `AsyncBuilder::trap`, and `FileBuilder::trap` with `ErrorSink` and `error::{StderrErrorSink, BlackHoleErrorSink}` across `logforth-core`, `logforth`, `logforth-append-async`, and `logforth-append-file`; configure runtime error handling via `LoggerBuilder::error_sink`, `AsyncBuilder::error_sink`, or `starter_log::LogStarter::error_sink`. -* Remove the `const APPEND: bool` generic parameter from `DispatchBuilder` in `logforth-core`; `DispatchBuilder::append` now returns `Self` in any order, and dispatches configured with no appenders are skipped when registered on `LoggerBuilder`. -* Replace `Filter::{enabled, matches}` and `FilterCriteria` in `logforth-core` with `Filter::{filter_level(&self, level: Level) -> FilterResult, filter(&self, record: &Record, diags: &dyn Diagnostic) -> FilterResult}`, precomputing level bitmasks across `Level::ALL` at `Logger` build time and changing `Logger::enabled` to accept `Level` instead of `&FilterCriteria`. -* Mark `record::LevelFilter` as `#[non_exhaustive]` in `logforth-core`; use `LevelFilter::test` or add a wildcard arm when matching. -* Replace `&[Box]` with `&dyn Diagnostic` across `Filter::filter`, `Layout::format`, `Append::append`, and `MakeBody::create` in `logforth-core`, `logforth`, and peripheral crates, and relax the `'static` supertrait bound on `Diagnostic` to the `Box` registration boundary; traverse diagnostics via `diags.visit(&mut visitor)` and pass `&()` for an empty context. -* Change `Layout::format` in `logforth-core` and built-in layouts to append formatted bytes into a caller-supplied `&mut Vec` and return `Result<(), Error>` instead of `Result, Error>`. -* Remove `Record::{target, target_static}` and `RecordBuilder::{target, target_static}` from `logforth-core`, updating `PlainTextLayout`, `TextLayout`, `JsonLayout` (now serializing `"module_path"`), and `LogfmtLayout` to read `Record::module_path`, stopping `OpentelemetryLog` from calling `LogRecord::set_target` (preserving the configured `InstrumentationScope` name), and omitting the non-standard `TARGET` field in `Journald`. -* Change `Record::filename` from `Cow<'a, str>` to `Option<&'a str>`, change `Record::key_values` from `&KeyValues<'a>` to `KeyValues<'a>` by value, and replace `Record::builder` with `RecordBuilder::new` in `logforth-core`; unwrap or match `Record::filename` when a fallback string is needed. -* Require `Sync` on `kv::Value::{debug, display}` in `logforth-core` so `Value<'a>` implements `Send + Sync` (local formatters over non-`Sync` values can construct `kv::DebugValue::new` and `kv::DisplayValue::new` directly), change `ValueOwned::bytes` to accept `impl Into>`, replace `ValueOwned::{from_vec, from_hash_map}` with insertion-ordered `ValueOwned::{list, map}`, and resolve duplicate keys in `KeyValues::get` and `MapValue::get` using last-entry-wins order. -* Change `StaticDiagnostic` and `ThreadLocalDiagnostic` in `logforth-core` to store `(KeyOwned, ValueOwned)` instead of `(String, String)`: `StaticDiagnostic::new` now accepts `IntoIterator`, `StaticDiagnostic::insert` accepts `K: Into` and `V: Into`, and `ThreadLocalDiagnostic::{insert, remove}` are replaced by `ThreadLocalDiagnostic::scope` returning a `!Send` `ThreadLocalDiagnosticGuard`. -* Remove `Copy` from `ThreadLocalDiagnostic` in `logforth-core`, `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`, and `FastraceDiagnostic` in `logforth-diagnostic-fastrace`. -* Reserve the `logforth.` key prefix in key-value pairs for Logforth (`"logforth.log_target"` carries explicit `log` target overrides from `LogBridge` into `RustLogFilter`). -* Promote `Logger`, `LoggerBuilder`, `DispatchBuilder`, and `builder` to the `logforth` crate root (removing `logforth::core`), remove `starter_log::builder` and `LogStarterBuilder`, unify `LogStarterTestingBuilder` and `LogStarterStdStreamBuilder` into `starter_log::LogStarter`, and replace `apply` / `try_apply` with `starter_log::LogStarterExt::{install, try_install}` (implemented for `Logger`, `LoggerBuilder`, `LogStarter`, and `LogBridge`). -* Replace `colored` with `anstyle` in `logforth-layout-text`: `TextLayout::{fatal_color, error_color, warn_color, info_color, debug_color, trace_color}` now accept `impl Into` (re-exported via `logforth_layout_text::anstyle`), and `TextLayout` emits ANSI colors deterministically without per-record heap allocations unless `TextLayout::no_color` is set. -* Remove `{TextLayout, JsonLayout}::timestamp_format` in `logforth-layout-text` and `logforth-layout-json`; configure timestamps declaratively with `.timezone(tz)` (`+HH:MM`), `.utc()` (`Z`), `.precision(u8)` (default `6` for microseconds), or `TextLayout::no_timestamp()`, and implement `Layout` directly for custom timestamp formats. -* Rename `JsonLayout`'s structured record key-value and diagnostic sub-objects in `logforth-layout-json` from `"kvs"` and `"diags"` to `"attributes"` and `"context"`. -* Align `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` with Google Cloud Structured Logging: map all 24 `Level` severities to canonical `LogSeverity` strings (`DEBUG`, `INFO`, `NOTICE`, `WARNING`, `ERROR`, `CRITICAL`, `ALERT`, and `EMERGENCY`), format `logging.googleapis.com/labels` values as JSON strings, omit `logging.googleapis.com/sourceLocation` when `file`, `line`, and `module_path` are all unset, and extract Cloud Trace correlation fields only from `Diagnostic` `("trace_id", "span_id", "sampled")` entries (removing the `"trace_sampled"` diagnostic alias and keeping `Record::key_values()` entries as ordinary payload or label fields). -* Replace `AsyncBuilder::buffered_lines_limit(Option)` with `AsyncBuilder::max_buffered_records(NonZeroUsize)` and change `AsyncBuilder::build` to return `Result` in `logforth-append-async`, returning `Err` instead of panicking when `thread_name` contains NUL bytes or OS thread creation fails; pass a `NonZeroUsize` limit when bounding buffered records (omit `max_buffered_records` for unbounded buffering) and handle the `Result` from `build`. -* `File` in `logforth-append-file` now writes directly to target segment files instead of writing to an unnumbered active file and shifting reverse-numbered archives on rollover: unrotated output remains `[.]`, time-only rotation writes `.[.]`, size rotation numbers segments in ascending order from `1` (oldest) as `[.].[.]`, `max_log_files` counts the active file toward the retention limit, and files from the previous naming scheme are ignored or ordered by ascending sequence number until moved or removed. -* `FileBuilder::rollover_size` in `logforth-append-file` now takes `NonZeroU64` instead of `NonZeroUsize` and rotates before a write would exceed the size limit rather than after, and `FileBuilder::build` now returns `Err` when `filename` is empty or when `filename` or `filename_suffix` is `.` or `..` or contains path separators or NUL bytes; update callers to pass `NonZeroU64` and valid filename components. -* Remove the redundant `"timestamp"` event property (and `jiff` dependency) from `FastraceEvent` in `logforth-append-fastrace` and require an active sampled `SpanContext::current_local_parent()` before recording events (skipping parentless `LocalCollector::start()` scopes); read event timestamps from `fastrace::collector::EventRecord::timestamp_unix_ns` instead. -* Broaden `Journald::with_syslog_identifier` in `logforth-append-journald` from `String` to `impl Into`; pass string literals directly without `.into()` where type inference would otherwise be ambiguous. -* Upgrade `opentelemetry` and `opentelemetry_sdk` from `0.32.0` to `0.33.1` (re-exporting both crates), remove the mandatory `opentelemetry-otlp` dependency, and replace `OpentelemetryLogBuilder` (including `OpentelemetryLogBuilder::{label, labels}`) with `OpentelemetryLog::{new, with_make_body}` over `(InstrumentationScope, SdkLoggerProvider)` in `logforth-append-opentelemetry` so multiple channels can share a provider, custom `Resource` attributes, and custom `LogProcessor` pipelines without premature shutdown on `Drop`. -* `OpentelemetryLog` in `logforth-append-opentelemetry` now emits source location attributes under `code.module.name` (`Record::module_path`), `code.file.path`, `code.line.number`, and `code.column.number` instead of `module_path`, `file`, `line`, and `column`; update queries and processors matching the previous attribute names. -* Replace `fasyslog` with `logforth-syslog` in `logforth-append-syslog` and remove the `rustls` and `native-tls` Cargo features from `logforth-append-syslog` and `logforth`: `Syslog` and `SyslogBuilder` are renamed to `SocketSyslog` and `SocketSyslogBuilder` (re-exported as `logforth::append::SocketSyslog`), and `Facility`, `Severity`, `ParseError`, `SyslogContext`, `Framing`, and `jiff` are exported at the crate root. -* Mark `SyslogFormat` as `#[non_exhaustive]` in `logforth-append-syslog` and rename its variants `{RFC3164, RFC5424}` to `{Rfc3164, Rfc5424}`. -* Replace `{tcp_well_known, udp_well_known, broadcast_well_known, rustls*, native_tls*, new}` on `SocketSyslogBuilder` in `logforth-append-syslog` with fallible constructors returning `Result` (preserving `io::Error` via `.source()`), auto-binding `udp(remote)` (use `udp_bind` or `udp_socket` for explicit sockets), `tcp_tls(addr, handshake)` over caller-supplied TLS closures (defaulting to `Rfc5424` with RFC 5425 `Framing::OctetCounting`), and unbuffered `Framing::LineFeed` (`\n`) with lazy reconnection instead of buffered `\r\n` on stream transports. -* `RustLogFilterBuilder::{from_default_env, from_default_env_or, from_env, from_env_or, from_spec}` in `logforth-filter-rustlog` now return `Result` and fail fast on malformed directives or non-UTF-8 environment variables instead of printing warnings to standard error, `RustLogFilterBuilder::{filter_level, filter_module}` are renamed to `{fallback, prefix}`, `RustLogFilterBuilder::try_from_spec` is removed, and `From<&str>` for `RustLogFilter` is replaced with `TryFrom<&str>`. -* `FutureExt::with_task_local_context` in `logforth-diagnostic-task-local` now accepts `IntoIterator` where `K: Into` and `V: Into` instead of `IntoIterator` and returns the named `TaskLocalFuture` wrapper, preserving typed values instead of converting them to strings and shadowing outer entries for the same key in nested scopes; pass keys and values directly without `.into()` where type inference would otherwise be ambiguous. -* `LogBridge::new` in `logforth-bridge-log` now accepts `Logger` by value instead of `impl Into>` (pass `logger.clone()` when retaining another handle), and `Deref` is replaced with explicit `LogBridge::{logger, into_logger}` accessors so `Log::{enabled, log}` no longer collide with `Logger::{enabled, log}`. - -### New features - -* Add native structured logging macros (`log!`, `trace!`, `debug!`, `info!`, `warn!`, `error!`, and `fatal!`) in `logforth-core` and `logforth` supporting bracketed `"key" = value` fields on explicit `Logger` handles. -* Add `Level::ALL` and `RecordBuilder::time` in `logforth-core` to enumerate all 24 severities and construct records with an explicit observed timestamp. -* Add `ValueOwned::{from_serde, try_from_serde}` and `kv::ValueSerde` (`new`, `Deref`, and `LogValue`, behind the `serde` feature) in `logforth-core` to convert `serde::Serialize` values into `ValueOwned` snapshots without panicking or capture them as lazy structured fields. -* Add `kv::LogValue`, `Value::{owned, lazy_owned, to_owned}`, `Key::{as_str, to_owned}`, `KeyOwned::as_str`, `DebugValue::new`, `DisplayValue::new`, `KeyView::to_static_str`, and `ValueView::{is_none, to_bytes}` in `logforth-core`, and implement `From` on `kv::{KeyOwned, ValueOwned}` across scalars (including `NonZero*` integers), strings, byte slices, `Option`, and borrowed `kv::{Key, KeyView, Value, ValueView}`. -* Add `ThreadLocalDiagnostic::scope` and `ThreadLocalDiagnosticGuard` in `logforth-core` for `!Send` RAII scoped thread-local diagnostics that restore shadowed entries on drop. -* Add `Error::message` and `LoggerBuilder::error_sink` in `logforth-core` (plus `starter_log::LogStarter::error_sink` in `logforth`) to inspect an error's own message and configure runtime error handling. -* Make `Logger` a pointer-sized `Clone` and `Default` handle over a shared pipeline, and add `const fn Logger::noop()`, `LoggerBuilder::new()` and `RecordBuilder::new()` (with `Default`), `const fn new()` on `PlainTextLayout`, `ThreadLocalDiagnostic`, `StderrErrorSink`, and `BlackHoleErrorSink`, and `new()` on `Stdout`, `Stderr`, and `Testing` in `logforth-core`. -* Implement `Append`, `ErrorSink`, `Filter`, and `Layout` in `logforth-core`, and `MakeBody` in `logforth-append-opentelemetry`, for `Arc` and `&'static T` where `T: ?Sized`, and implement `Diagnostic` for `&T`, `Arc`, `()`, `Option`, slices, arrays, and `Vec` (including non-`'static` boxed trait objects). -* Add `starter_log::{LogStarterExt, LogStarter::try_build}` (with `Debug` for `LogStarter`), `layout::{json, logfmt}` module re-exports, and the `serde` feature (`logforth-core/serde`) in `logforth`. -* Add `const fn new()` on `GoogleCloudLoggingLayout`, `new()` on `TextLayout`, `LogfmtLayout`, and `JsonLayout`, `TextLayout::{no_timestamp, no_module_path, no_file}`, and `.utc()` / `.precision(u8)` across `TextLayout`, `LogfmtLayout`, and `JsonLayout` for zero-allocation RFC 3339 timestamp formatting. -* Emit `Record::column` across built-in layouts and omit unset location segments when `filename` or `module_path` is unset instead of formatting empty or `0` placeholders: `PlainTextLayout`, `TextLayout`, and `LogfmtLayout` format locations as `filename:line:column` (defaulting unset line or column numbers to `0` when `filename` is present), and `JsonLayout` emits `"column"` when set. -* Add `FileBuilder::timezone` and re-export `jiff` in `logforth-append-file` to configure the timezone used for rotation boundaries and segment filenames, defaulting to the system timezone. -* Add `Journald::{from_socket_path, socket_path}` in `logforth-append-journald`. -* Extract valid `Diagnostic` `("trace_id", "span_id")` pairs and optional boolean `"sampled"` flags into `LogRecord::set_trace_context` in `logforth-append-opentelemetry`. -* Add `PosixSyslog`, `PosixSyslogBuilder`, `{PosixSyslogOptions, posix_openlog, posix_closelog}` (`cfg(unix)`), and `SocketSyslogBuilder::{udp_socket, framing, timezone}` in `logforth-append-syslog` (re-exporting `PosixSyslog` as `logforth::append::PosixSyslog`). -* Add `const fn new()` on `FastraceEvent` in `logforth-append-fastrace`, `FastraceDiagnostic` in `logforth-diagnostic-fastrace`, and `TaskLocalDiagnostic` in `logforth-diagnostic-task-local`. -* Add `LogBridge::{max_level, logger, into_logger, try_install, install}`, `Clone`, `Default`, `From`, and `pub extern crate log` in `logforth-bridge-log`, updating `log::set_max_level` automatically from enabled logger levels on installation. -* Add the standalone `#![no_std]` (`alloc`) `logforth-logfmt` crate providing a zero-dependency `logfmt` `Encoder` and zero-copy `Decoder`, and back `LogfmtLayout` in `logforth-layout-logfmt` with it. -* Add the standalone `logforth-syslog` crate providing RFC 3164 and RFC 5424 formatters (`SyslogContext`, `SdElement`, `SdParam`, `format_rfc3164`, `format_rfc5424`), datagram and reconnectable stream senders (`UdpSender`, `TcpSender`, `TcpTlsSender`, `UnixDatagramSender`, `UnixStreamSender`, `Sender`, `Framing`), and a Unix POSIX `` backend (`posix::{LogOptions, openlog, syslog, closelog}`). - -### Improvements - -* Make `LevelFilter::test`, `Record` field accessors, and `Record::to_builder` `const fn`, return the closure result from `RecordOwned::with`, and implement `Hash` for `FilterResult` in `logforth-core`. -* Implement `Copy` for `kv::{Key, KeyView, Value, ValueView}`, `AsRef` for `kv::{Key, KeyOwned, KeyView}`, `IntoIterator` for `kv::{KeyValues, ListValue, MapValue}`, `serde::Serialize` for `kv::{KeyValues, DebugValue, DisplayValue}` (behind `serde`), `Clone` and `Debug` for `kv::KeyValuesIter`, and `kv::Visitor` for `FnMut(KeyView, ValueView) -> Result<(), Error>` closures in `logforth-core`. -* Perform lossless checked range conversions across integer variants in `ValueView::{to_i64, to_u64, to_i128, to_u128}` in `logforth-core`. -* Write `kv::ValueView::Bytes` as raw binary field payloads in `logforth-append-journald`. -* Map `kv::ValueView::Bytes` to `AnyValue::Bytes` and omit empty default message bodies (leaving `SdkLogRecord::body` unset) in `logforth-append-opentelemetry`. -* Derive `PartialEq`, `Eq`, `Hash`, and `Default` (`Rfc3164`) for `SyslogFormat` in `logforth-append-syslog`. -* Implement `Clone` for `RustLogFilter` and `Clone` plus `const fn new()` for `RustLogFilterBuilder` in `logforth-filter-rustlog`, and normalize empty prefixes (`""` and `=level`) to the fallback rule. - -### Performance improvements - -* Avoid per-record intermediate value, string, and map allocations when formatting records in `JsonLayout`, `LogfmtLayout`, `GoogleCloudLoggingLayout`, `FastraceDiagnostic`, and `Journald` (preserving `Record::key_values` insertion order in `JsonLayout`). -* Avoid formatting message payloads and event properties in `FastraceEvent` when no sampled local parent span is active. -* Speed up level filtering in `RustLogFilter` by short-circuiting levels that are rejected or unconditionally accepted across all directives before prefix matching. - -### Bug fixes - -* `ValueView`'s `Display` implementation in `logforth-core` now formats list and map entries as values and string keys instead of internal wrapper representations. -* `Logger::log` and `Logger::flush` in `logforth-core` no longer panic when writing internal error reports to standard error fails. -* `PlainTextLayout` and `TextLayout` now omit the message separator space when the formatted payload is empty and return `Err` without modifying the output buffer instead of panicking when formatting fails. -* `TextLayout`, `LogfmtLayout`, `JsonLayout`, and `GoogleCloudLoggingLayout` now return `Err` instead of panicking on out-of-range record timestamps. -* `JsonLayout` and `GoogleCloudLoggingLayout` now serialize 128-bit integers outside 64-bit bounds as JSON numbers instead of degrading values or enclosing containers to strings. -* `LogfmtLayout` in `logforth-layout-logfmt` now escapes quoted strings with standard `\"`/`\\`/`\n`/`\r`/`\t`/`\u00XX` escapes instead of Rust debug escapes, encodes `ValueView::None` as `null` and literal `"null"` as `"\"null\""`, strips invalid characters from keys, and returns `Err` on empty keys. -* `GoogleCloudLoggingLayout` in `logforth-layout-google-cloud-logging` now gives explicit `Record` key-values precedence over colliding `Diagnostic` entries. -* `Async` in `logforth-append-async` now flushes inner appenders on `Drop` after draining queued records, isolates panics in inner appenders and `ErrorSink` during `append`, `flush`, and shutdown instead of terminating the worker thread or panicking in `Drop`, and waits for full bounded queues to drain during `flush` under `overflow_drop_incoming`. -* `File` in `logforth-append-file` now opens segment files in append mode so external truncation does not leave NUL holes, and no longer panics or truncates timestamps and file sizes on matching prefix/suffix edge cases, out-of-range timestamps, or 32-bit targets. -* `OpentelemetryLog` in `logforth-append-opentelemetry` now deduplicates top-level log attribute keys by default (giving explicit `Record` key-values precedence over `Diagnostic` entries and `Diagnostic` entries precedence over `code.*` source location attributes); call `OpentelemetryLog::allow_duplicate_keys` to forward repeated keys unmodified. -* `OpentelemetryLog` in `logforth-append-opentelemetry` now sets `LogRecord::set_timestamp` from `Record::time()` instead of overwriting the event timestamp with `SystemTime::now()`. -* `SocketSyslog` in `logforth-append-syslog` now formats syslog header timestamps from `Record::time()` instead of overwriting them with `SystemTime::now()`, and omits the RFC 3164 `HOSTNAME` token on local Unix socket builders (`SocketSyslogBuilder::{unix, unix_datagram, unix_stream}`) so `systemd-journald` and `rsyslog` parse `TAG[PID]` accurately. -* `ThreadLocalDiagnostic` and `TaskLocalDiagnostic` no longer panic when logging during thread-local teardown, degrading to an empty context instead. +For releases up to `v0.31.0`, see [CHANGELOG-OLD.md](CHANGELOG-OLD.md). diff --git a/Cargo.lock b/Cargo.lock index a74fe868..ae8cb41c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -38,7 +38,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -49,7 +49,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -221,6 +221,12 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "erased-serde" version = "0.4.10" @@ -239,7 +245,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys", ] [[package]] @@ -400,6 +406,12 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "heck" version = "0.5.0" @@ -597,6 +609,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "ipnet" version = "2.12.0" @@ -901,7 +923,7 @@ checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" dependencies = [ "libc", "wasi", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1231,7 +1253,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys", ] [[package]] @@ -1314,6 +1336,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "slab" version = "0.4.12" @@ -1339,7 +1370,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1481,10 +1512,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys", ] [[package]] @@ -1542,7 +1573,7 @@ dependencies = [ "pin-project-lite", "socket2", "tokio-macros", - "windows-sys 0.61.2", + "windows-sys", ] [[package]] @@ -1556,6 +1587,58 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "toml" +version = "1.2.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.21+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.7+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tower" version = "0.5.3" @@ -1812,15 +1895,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -1831,69 +1905,14 @@ dependencies = [ ] [[package]] -name = "windows-targets" -version = "0.52.6" +name = "winnow" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "memchr", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - [[package]] name = "wit-bindgen" version = "0.57.1" @@ -1912,6 +1931,11 @@ version = "0.0.0" dependencies = [ "cargo_metadata", "clap", + "semver", + "serde", + "tempfile", + "toml", + "toml_edit", "which", ] diff --git a/Cargo.toml b/Cargo.toml index bd5c886e..c2c1809c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -68,10 +68,13 @@ log = { version = "0.4.31", default-features = false } opentelemetry = { version = "0.33.1", default-features = false } opentelemetry-otlp = { version = "0.33.1", default-features = false } opentelemetry_sdk = { version = "0.33.1", default-features = false } +semver = { version = "1.0" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } tempfile = { version = "3.16" } tokio = { version = "1.53.1", default-features = false } +toml = { version = "1.0" } +toml_edit = { version = "0.25" } which = { version = "8.0.0" } [workspace.lints.rust] @@ -84,10 +87,3 @@ unused_must_use = "deny" allow_attributes = "deny" dbg_macro = "deny" missing_safety_doc = "deny" - -[workspace.metadata.release] -consolidate-commits = false -pre-release-commit-message = "chore: Release {{crate_name}} version {{version}}" -sign-commit = true -sign-tag = true -tag-message = "chore: Release {{crate_name}} version {{version}}" diff --git a/changes/releases.toml b/changes/releases.toml new file mode 100644 index 00000000..77c325b5 --- /dev/null +++ b/changes/releases.toml @@ -0,0 +1,2 @@ +# Structured release ledger for Logforth (`v0.32.0` and later). +# Updated via `cargo x release prepare --apply`; rendered to `CHANGELOG.md` via `cargo x changelog --write`. diff --git a/changes/unreleased/.gitkeep b/changes/unreleased/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 92555232..0b998676 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -20,9 +20,6 @@ edition.workspace = true license.workspace = true rust-version.workspace = true -[package.metadata.release] -release = false - [dependencies] fastrace = { workspace = true, features = ["enable"] } log = { workspace = true, features = ["kv_serde", "std"] } diff --git a/licenserc.toml b/licenserc.toml index d5f668e0..551d8589 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -16,6 +16,7 @@ builtin = "Apache-2.0" [files] +excludes = ["changes/**"] includes = ["**/*.proto", "**/*.rs", "**/*.toml", "**/*.yaml", "**/*.yml"] [props] diff --git a/tests-integration/Cargo.toml b/tests-integration/Cargo.toml index 217075d6..eabafd4a 100644 --- a/tests-integration/Cargo.toml +++ b/tests-integration/Cargo.toml @@ -20,9 +20,6 @@ edition.workspace = true license.workspace = true rust-version.workspace = true -[package.metadata.release] -release = false - [dependencies] logforth-core = { workspace = true, features = ["serde"] } diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index dc5b1fa0..085dc97c 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -22,13 +22,17 @@ readme.workspace = true repository.workspace = true rust-version.workspace = true -[package.metadata.release] -release = false - [dependencies] cargo_metadata = { workspace = true } clap = { workspace = true } +semver = { workspace = true } +serde = { workspace = true } +toml = { workspace = true } +toml_edit = { workspace = true } which = { workspace = true } +[dev-dependencies] +tempfile = { workspace = true } + [lints] workspace = true diff --git a/xtask/src/changelog.rs b/xtask/src/changelog.rs new file mode 100644 index 00000000..7b674768 --- /dev/null +++ b/xtask/src/changelog.rs @@ -0,0 +1,636 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::fmt::Write as _; +use std::fs; +use std::path::Path; +use std::path::PathBuf; +use std::process; + +use clap::Parser; +use semver::Version; +use serde::Deserialize; +use serde::Serialize; + +use crate::workspace::WorkspaceGraph; +use crate::workspace::crate_sort_key; +use crate::workspace::short_crate_label; + +const LEDGER_HEADER: &str = "# Structured release ledger for Logforth (`v0.32.0` and later).\n# Updated via `cargo x release prepare --apply`; rendered to `CHANGELOG.md` via `cargo x changelog --write`.\n"; +const HEADER: &str = "# Changelog\n\nAll significant changes to this project are documented in this file. Unreleased change fragments live in [`changes/unreleased`](changes/unreleased); run `cargo x changelog` to preview them locally.\n\n\n"; +const FOOTER: &str = "\nFor releases up to `v0.31.0`, see [CHANGELOG-OLD.md](CHANGELOG-OLD.md).\n"; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum Category { + Breaking, + Notable, + Feature, + Improvement, + Performance, + Fix, +} + +impl Category { + fn heading(self) -> &'static str { + match self { + Self::Breaking => "Breaking changes", + Self::Notable => "Notable changes", + Self::Feature => "New features", + Self::Improvement => "Improvements", + Self::Performance => "Performance improvements", + Self::Fix => "Bug fixes", + } + } +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChangeEntry { + pub(crate) category: Category, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) crates: Vec, + pub(crate) text: String, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) workspace: bool, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct FragmentFile { + pub(crate) change: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ReleaseRecord { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) date: Option, + pub(crate) crates: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) change: Vec, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct ReleasesFile { + #[serde(default)] + pub(crate) release: Vec, +} + +pub(crate) struct ChangelogData { + pub(crate) fragments: BTreeMap, + pub(crate) releases: Vec, +} + +fn read_toml(path: &Path) -> Result { + let contents = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + toml::from_str(&contents).map_err(|e| format!("{}: {e}", path.display())) +} + +fn validate_entry(entry: &ChangeEntry, known: &BTreeSet) -> Result<(), String> { + let text = &entry.text; + if text.is_empty() + || text.trim() != text + || text.contains(['\n', '\r']) + || text.starts_with("* ") + || text.starts_with("- ") + { + return Err(format!( + "expected trimmed single-line change text without a bullet: {text:?}" + )); + } + if entry.workspace != entry.crates.is_empty() { + return Err("specify either workspace = true or a nonempty crates list".into()); + } + let mut seen = BTreeSet::new(); + for name in &entry.crates { + if !known.contains(name) { + return Err(format!("unknown crate {name} for this change")); + } + if !seen.insert(name) { + return Err(format!("duplicate crate {name} in change")); + } + } + Ok(()) +} + +fn valid_date(date: &str) -> bool { + let b = date.as_bytes(); + if b.len() != 10 + || b[4] != b'-' + || b[7] != b'-' + || !b + .iter() + .enumerate() + .all(|(i, c)| matches!(i, 4 | 7) || c.is_ascii_digit()) + { + return false; + } + let year: u32 = date[..4].parse().unwrap(); + let days = match &date[5..7] { + "01" | "03" | "05" | "07" | "08" | "10" | "12" => 31, + "04" | "06" | "09" | "11" => 30, + "02" if year.is_multiple_of(400) || year.is_multiple_of(4) && !year.is_multiple_of(100) => { + 29 + } + "02" => 28, + _ => return false, + }; + (1..=days).contains(&date[8..].parse::().unwrap()) +} + +pub(crate) fn load_and_validate( + root: &Path, + publishable_crates: &BTreeSet, +) -> Result { + let dir = root.join("changes/unreleased"); + let mut fragments = BTreeMap::new(); + for item in fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))? { + let item = item.map_err(|e| e.to_string())?; + let path = item.path(); + let name = item.file_name(); + if !item.file_type().map_err(|e| e.to_string())?.is_file() { + return Err(format!("expected a fragment file: {}", path.display())); + } + if name == ".gitkeep" { + continue; + } + let valid = name + .to_str() + .and_then(|s| s.strip_suffix(".toml")) + .is_some_and(|s| { + s.split('-').all(|part| { + !part.is_empty() + && part + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) + }) + }); + if !valid { + return Err(format!("invalid fragment name: {}", path.display())); + } + let fragment: FragmentFile = read_toml(&path)?; + if fragment.change.is_empty() { + return Err(format!("empty fragment: {}", path.display())); + } + for entry in &fragment.change { + validate_entry(entry, publishable_crates) + .map_err(|e| format!("{}: {e}", path.display()))?; + } + fragments.insert(path, fragment); + } + let ledger: ReleasesFile = read_toml(&root.join("changes/releases.toml"))?; + let mut newer = BTreeMap::new(); + for (i, record) in ledger.release.iter().enumerate() { + if let Some(d) = &record.date + && !valid_date(d) + { + return Err(format!("release {i}: invalid calendar date {d}")); + } + if record.crates.is_empty() { + return Err(format!("release {i}: empty crate list")); + } + for (name, version) in &record.crates { + let v = Version::parse(version).map_err(|e| format!("{name} {version}: {e}"))?; + if !v.pre.is_empty() || !v.build.is_empty() || newer.get(name).is_some_and(|n| n <= &v) + { + return Err(format!( + "release {i}: expected strictly descending stable versions for {name}, found {v}" + )); + } + newer.insert(name, v); + } + let names = record.crates.keys().cloned().collect(); + for entry in &record.change { + validate_entry(entry, &names).map_err(|e| format!("release {i}: {e}"))?; + } + } + Ok(ChangelogData { + fragments, + releases: ledger.release, + }) +} + +pub(crate) fn format_releases_toml(releases: &[ReleaseRecord]) -> String { + let mut out = LEDGER_HEADER.to_owned(); + for record in releases { + out.push_str("\n[[release]]\n"); + if let Some(date) = &record.date { + writeln!(out, "date = {}", toml_edit::Value::from(date.as_str())).unwrap(); + } + out.push_str("\n[release.crates]\n"); + for (name, version) in &record.crates { + writeln!( + out, + "{} = {}", + toml_edit::Key::new(name), + toml_edit::Value::from(version.as_str()) + ) + .unwrap(); + } + for entry in &record.change { + out.push_str("\n[[release.change]]\n"); + writeln!( + out, + "category = {}", + toml::Value::try_from(entry.category).unwrap() + ) + .unwrap(); + if !entry.crates.is_empty() { + let names: Vec<_> = entry + .crates + .iter() + .map(|n| toml_edit::Value::from(n.as_str()).to_string()) + .collect(); + let line = format!("crates = [{}]", names.join(", ")); + if line.chars().count() <= 80 { + writeln!(out, "{line}").unwrap(); + } else { + out.push_str("crates = [\n"); + for name in names { + writeln!(out, " {name},").unwrap(); + } + out.push_str("]\n"); + } + } + writeln!( + out, + "text = {}", + toml_edit::Value::from(entry.text.as_str()) + ) + .unwrap(); + if entry.workspace { + out.push_str("workspace = true\n"); + } + } + } + out +} + +fn render_entries(out: &mut String, mut entries: Vec<&ChangeEntry>, crate_name: Option<&str>) { + entries.sort_by_key(|entry| { + ( + entry.category, + entry.crates.iter().map(|n| crate_sort_key(n)).min(), + ) + }); + let mut category = None; + for entry in entries { + if category != Some(entry.category) { + writeln!(out, "\n### {}\n", entry.category.heading()).unwrap(); + category = Some(entry.category); + } + let mut names: Vec<_> = entry.crates.iter().map(String::as_str).collect(); + names.sort_by_key(|n| crate_sort_key(n)); + if entry.workspace || crate_name.is_some_and(|n| n != "logforth" && names == [n]) { + writeln!(out, "* {}", entry.text).unwrap(); + } else { + let labels = names + .into_iter() + .map(short_crate_label) + .collect::>() + .join(", "); + writeln!(out, "* **{labels}**: {}", entry.text).unwrap(); + } + } +} + +fn render_releases(out: &mut String, releases: &[ReleaseRecord]) { + for record in releases { + let mut crates: Vec<_> = record.crates.iter().collect(); + crates.sort_by_key(|(n, _)| crate_sort_key(n)); + let title = match record.crates.get("logforth") { + Some(v) => format!("logforth v{v}"), + None => crates + .iter() + .map(|(n, v)| format!("{n} v{v}")) + .collect::>() + .join(", "), + }; + writeln!(out, "\n## {title}\n").unwrap(); + let summary = crates + .iter() + .map(|(n, v)| format!("`{n} {v}`")) + .collect::>() + .join(", "); + match &record.date { + Some(d) => writeln!(out, "Released on {d}: {summary}.").unwrap(), + None => writeln!(out, "Released crates: {summary}.").unwrap(), + } + render_entries(out, record.change.iter().collect(), None); + } + out.push_str(FOOTER); +} + +pub(crate) fn render_root_changelog(releases: &[ReleaseRecord]) -> String { + let mut out = HEADER.to_owned(); + render_releases(&mut out, releases); + out +} + +fn render_preview(data: &ChangelogData) -> String { + let mut out = format!("{HEADER}\n## Unreleased\n"); + let entries: Vec<_> = data.fragments.values().flat_map(|f| &f.change).collect(); + if entries.is_empty() { + out.push_str("\nNo unreleased changes.\n"); + } else { + render_entries(&mut out, entries, None); + } + render_releases(&mut out, &data.releases); + out +} + +fn entry_applies_to_crate(entry: &ChangeEntry, crate_name: &str) -> bool { + entry.workspace + || entry.crates.iter().any(|n| { + if crate_name == "logforth" { + n != "logforth-logfmt" + } else { + n == crate_name + } + }) +} + +fn render_crate_slice( + data: &ChangelogData, + crate_name: &str, + from: Option<&Version>, + to: Option<&Version>, +) -> String { + let mut out = format!("# Changelog ({crate_name})\n"); + if to.is_none() { + let entries: Vec<_> = data + .fragments + .values() + .flat_map(|f| &f.change) + .filter(|e| entry_applies_to_crate(e, crate_name)) + .collect(); + if !entries.is_empty() { + out.push_str("\n## Unreleased\n"); + render_entries(&mut out, entries, Some(crate_name)); + } + } + for record in &data.releases { + let Some(version) = record.crates.get(crate_name) else { + continue; + }; + let v = Version::parse(version).expect("validated release version"); + if from.is_some_and(|f| &v <= f) || to.is_some_and(|t| &v > t) { + continue; + } + writeln!(out, "\n## {crate_name} v{v}").unwrap(); + if let Some(d) = &record.date { + writeln!(out, "\nReleased on {d}.").unwrap(); + } + let entries: Vec<_> = record + .change + .iter() + .filter(|e| entry_applies_to_crate(e, crate_name)) + .collect(); + if entries.is_empty() { + out.push_str("\n* Update workspace dependencies.\n"); + } else { + render_entries(&mut out, entries, Some(crate_name)); + } + } + out.push_str(FOOTER); + out +} + +#[derive(Parser, Default)] +pub(crate) struct CommandChangelog { + #[arg(long, conflicts_with = "write")] + check: bool, + #[arg(long)] + write: bool, + #[arg(long = "crate", value_name = "CRATE", conflicts_with_all = ["check", "write"])] + crate_name: Option, + #[arg(long, value_name = "VERSION", requires = "crate_name")] + from: Option, + #[arg(long, value_name = "VERSION", requires = "crate_name")] + to: Option, +} + +impl CommandChangelog { + pub(crate) fn run(self) { + if let Err(err) = self.execute(Path::new(env!("CARGO_WORKSPACE_DIR"))) { + eprintln!("error: {err}"); + process::exit(1); + } + } + + fn execute(self, root: &Path) -> Result<(), String> { + let graph = WorkspaceGraph::load(root)?; + let data = load_and_validate(root, &graph.packages.keys().cloned().collect())?; + if self.check || self.write { + let rendered = render_root_changelog(&data.releases); + let path = root.join("CHANGELOG.md"); + match fs::read_to_string(&path) { + Ok(current) if current == rendered => return Ok(()), + Ok(current) if self.check && current.replace("\r\n", "\n") == rendered => { + return Ok(()); + } + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + return Err(format!("{}: {e}", path.display())); + } + _ => (), + } + if self.write { + fs::write(&path, rendered).map_err(|e| format!("{}: {e}", path.display()))?; + } else { + return Err("CHANGELOG.md is stale; run `cargo x changelog --write` or `cargo x lint --fix`".into()); + } + } else if let Some(name) = self.crate_name { + if !graph.packages.contains_key(&name) + && !data.releases.iter().any(|r| r.crates.contains_key(&name)) + { + return Err(format!("unknown publishable crate {name}")); + } + if let (Some(from), Some(to)) = (&self.from, &self.to) + && from >= to + { + return Err(format!( + "expected --from ({from}) to be less than --to ({to})" + )); + } + print!( + "{}", + render_crate_slice(&data, &name, self.from.as_ref(), self.to.as_ref()) + ); + } else { + print!("{}", render_preview(&data)); + } + Ok(()) + } +} + +pub(crate) fn verify_or_fix_workspace(fix: bool) { + CommandChangelog { + check: !fix, + write: fix, + ..Default::default() + } + .run(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ledger_round_trip_preserves_scopes_order_and_version_bounds() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::create_dir_all(root.join("changes/unreleased")).unwrap(); + fs::write( + root.join("changes/unreleased/pending.toml"), + "[[change]]\ncategory = 'feature'\ncrates = ['logforth-core']\ntext = 'Pending.'", + ) + .unwrap(); + let ledger: ReleasesFile = toml::from_str( + r#" +[[release]] +date = "2024-02-29" +[release.crates] +logforth = "0.32.0" +logforth-core = "0.6.0" +logforth-logfmt = "0.2.0" +[[release.change]] +category = "fix" +crates = ["logforth-logfmt"] +text = "Private fix." +[[release.change]] +category = "breaking" +crates = ["logforth", "logforth-core"] +text = 'Remove "old".' +[[release.change]] +category = "breaking" +workspace = true +text = "Raise MSRV." +[[release.change]] +category = "fix" +crates = ["logforth-core"] +text = "Handle missing context." +[[release]] +[release.crates] +logforth-core = "0.5.0" +"#, + ) + .unwrap(); + let formatted = format_releases_toml(&ledger.release); + fs::write(root.join("changes/releases.toml"), &formatted).unwrap(); + let data = load_and_validate(root, &["logforth-core".into()].into()).unwrap(); + assert_eq!(format_releases_toml(&data.releases), formatted); + let changelog = render_root_changelog(&data.releases); + let expected = [ + "## logforth v0.32.0", + "### Breaking changes", + "* Raise MSRV.", + "* **core, logforth**: Remove \"old\".", + "### Bug fixes", + "* **core**: Handle missing context.", + "* **logfmt**: Private fix.", + "## logforth-core v0.5.0", + ]; + let mut rest = changelog.as_str(); + for part in expected { + rest = rest.split_once(part).unwrap().1; + } + let slice = render_crate_slice( + &data, + "logforth-core", + Some(&Version::new(0, 5, 0)), + Some(&Version::new(0, 6, 0)), + ); + assert!( + slice.contains("* Handle missing context.") && slice.contains("* **core, logforth**:") + ); + assert!( + !slice.contains("Private fix.") + && !slice.contains("## Unreleased") + && !slice.contains("v0.5.0") + ); + let facade = render_crate_slice(&data, "logforth", None, None); + assert!(facade.contains("Pending.") && !facade.contains("Private fix.")); + assert!( + render_crate_slice(&data, "logforth-core", None, None) + .contains("## logforth-core v0.5.0\n\n* Update workspace dependencies.") + ); + } + + #[test] + fn command_checks_line_endings_and_validates_crate_ranges() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + fs::write(root.join("Cargo.toml"), "[workspace]\n[package]\nname = 'current'\nversion = '0.1.0'\nedition = '2024'\n[lib]\npath = 'lib.rs'").unwrap(); + fs::write(root.join("lib.rs"), "").unwrap(); + fs::create_dir_all(root.join("changes/unreleased")).unwrap(); + fs::write( + root.join("changes/releases.toml"), + "[[release]]\n[release.crates]\nretired = '0.1.0'", + ) + .unwrap(); + let run = |args: &[&str]| CommandChangelog::parse_from(args).execute(root); + let path = root.join("CHANGELOG.md"); + run(&["changelog", "--write"]).unwrap(); + let rendered = fs::read_to_string(&path).unwrap(); + fs::write(&path, rendered.replace('\n', "\r\n")).unwrap(); + run(&["changelog", "--check"]).unwrap(); + run(&["changelog", "--write"]).unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), rendered); + for name in ["current", "retired"] { + run(&["changelog", "--crate", name]).unwrap(); + } + assert_eq!( + run(&["changelog", "--crate", "missing"]).unwrap_err(), + "unknown publishable crate missing" + ); + for from in ["0.1.0", "0.2.0"] { + assert_eq!( + run(&[ + "changelog", + "--crate", + "retired", + "--from", + from, + "--to", + "0.1.0" + ]) + .unwrap_err(), + format!("expected --from ({from}) to be less than --to (0.1.0)") + ); + } + } + + #[test] + fn rejects_invalid_dates_and_non_descending_versions() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join("changes/unreleased")).unwrap(); + for (date, older) in [ + ("1900-02-29", "0.1.0"), + ("2000-02-29", "0.2.0"), + ("2000-02-29", "0.3.0"), + ("2000-02-29", "0.1.0+build"), + ] { + let ledger = format!( + "[[release]]\ndate = '{date}'\n[release.crates]\nexample = '0.2.0'\n[[release]]\n[release.crates]\nexample = '{older}'\n" + ); + fs::write(dir.path().join("changes/releases.toml"), ledger).unwrap(); + assert!(load_and_validate(dir.path(), &BTreeSet::new()).is_err()); + } + } +} diff --git a/xtask/src/lint.rs b/xtask/src/lint.rs index 33441abf..f40deba6 100644 --- a/xtask/src/lint.rs +++ b/xtask/src/lint.rs @@ -17,6 +17,7 @@ use std::process; use clap::Parser; use crate::cargo; +use crate::changelog::verify_or_fix_workspace; use crate::ensure_installed; use crate::find_command; use crate::run_command; @@ -31,6 +32,7 @@ impl CommandLint { pub fn run(self) { run_command(make_clippy_cmd(self.fix)); run_command(make_format_cmd(self.fix)); + verify_or_fix_workspace(self.fix); run_command(make_taplo_cmd(self.fix)); run_command(make_typos_cmd()); run_command(make_hawkeye_cmd(self.fix)); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 251ea26e..7e9a6c3a 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -19,14 +19,19 @@ use clap::Parser; use clap::Subcommand; use crate::build::CommandBuild; +use crate::changelog::CommandChangelog; use crate::check::CommandCheck; use crate::lint::CommandLint; +use crate::release::CommandRelease; use crate::test::CommandTest; mod build; +mod changelog; mod check; mod lint; +mod release; mod test; +mod workspace; fn main() { Command::parse().run(); @@ -42,8 +47,10 @@ impl Command { fn run(self) { match self.sub { SubCommand::Build(cmd) => cmd.run(), + SubCommand::Changelog(cmd) => cmd.run(), SubCommand::Check(cmd) => cmd.run(), SubCommand::Lint(cmd) => cmd.run(), + SubCommand::Release(cmd) => cmd.run(), SubCommand::Test(cmd) => cmd.run(), } } @@ -53,10 +60,14 @@ impl Command { enum SubCommand { #[command(about = "Compile workspace packages.")] Build(CommandBuild), + #[command(about = "Preview, render, or verify structured changelogs.")] + Changelog(CommandChangelog), #[command(about = "Check workspace packages under the feature matrix.")] Check(CommandCheck), #[command(about = "Run workspace quality checks.")] Lint(CommandLint), + #[command(about = "Prepare workspace crate releases.")] + Release(CommandRelease), #[command(about = "Run workspace tests.")] Test(CommandTest), } diff --git a/xtask/src/release.rs b/xtask/src/release.rs new file mode 100644 index 00000000..6a1c1333 --- /dev/null +++ b/xtask/src/release.rs @@ -0,0 +1,752 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::fs; +use std::path::Path; +use std::path::PathBuf; +use std::process; + +use clap::Parser; +use clap::Subcommand; +use semver::Version; +use toml_edit::DocumentMut; + +use crate::changelog::Category; +use crate::changelog::ReleaseRecord; +use crate::changelog::format_releases_toml; +use crate::changelog::load_and_validate; +use crate::changelog::render_root_changelog; +use crate::workspace::WorkspaceGraph; +use crate::workspace::publish_tier_key; + +#[derive(Parser)] +pub(crate) struct CommandRelease { + #[command(subcommand)] + sub: ReleaseSubcommand, +} + +#[derive(Subcommand)] +enum ReleaseSubcommand { + #[command(about = "Plan a release or apply explicit crate versions.")] + Prepare(CommandReleasePrepare), +} + +impl CommandRelease { + pub(crate) fn run(self) { + let ReleaseSubcommand::Prepare(cmd) = self.sub; + if let Err(err) = cmd.run(Path::new(env!("CARGO_WORKSPACE_DIR"))) { + eprintln!("error: {err}"); + process::exit(1); + } + } +} + +#[derive(Parser)] +struct CommandReleasePrepare { + #[arg(value_name = "CRATE=VERSION")] + specs: Vec, + #[arg(long)] + apply: bool, +} + +impl CommandReleasePrepare { + fn run(self, root: &Path) -> Result<(), String> { + if self.apply && self.specs.is_empty() { + return Err("explicit CRATE=VERSION targets are required with --apply".into()); + } + let graph = WorkspaceGraph::load(root)?; + if self.specs.is_empty() { + return suggest_release(root, &graph); + } + let mut specs = Vec::new(); + for spec in self.specs { + let (name, version) = spec + .split_once('=') + .ok_or_else(|| format!("expected CRATE=VERSION, got {spec}"))?; + specs.push(( + name.to_owned(), + Version::parse(version).map_err(|e| format!("{spec}: {e}"))?, + )); + } + let report = prepare_release(root, &graph, &specs, self.apply)?; + if self.apply { + let status = process::Command::new("cargo") + .args(["update", "--workspace"]) + .current_dir(root) + .status() + .map_err(|e| format!("cargo update --workspace: {e}"))?; + if !status.success() { + return Err(format!( + "release files applied, cargo update --workspace failed: {status}" + )); + } + } + println!( + "{} release with {} consumed and {} retained fragments:", + if self.apply { "Applied" } else { "Planned" }, + report.consumed.len(), + report.retained.len() + ); + for (name, version) in specs { + println!(" {name} {} -> {version}", graph.packages[&name].version); + } + print_order(&report.publish_order); + Ok(()) + } +} + +pub(crate) fn is_breaking_bump(old: &Version, new: &Version) -> bool { + if old.major == 0 { + new.major != 0 || new.minor > old.minor + } else { + new.major > old.major + } +} + +pub(crate) fn suggest_next_version(old: &Version, breaking: bool) -> Version { + if !breaking { + Version::new(old.major, old.minor, old.patch + 1) + } else if old.major == 0 { + Version::new(0, old.minor + 1, 0) + } else { + Version::new(old.major + 1, 0, 0) + } +} + +fn print_order(order: &[String]) { + println!("Publish order:"); + for name in order { + println!(" Tier {}: {name}", publish_tier_key(name).0 + 1); + } +} + +fn suggest_release(root: &Path, graph: &WorkspaceGraph) -> Result<(), String> { + let names = graph.packages.keys().cloned().collect(); + let data = load_and_validate(root, &names)?; + if let Some(record) = data.releases.first() + && record.date.is_none() + { + let order = graph.topological_publish_order(&record.crates.keys().cloned().collect())?; + println!("Pending undated release in changes/releases.toml:"); + for name in &order { + println!(" {name} {}", record.crates[name]); + } + print_order(&order); + return Ok(()); + } + let mut bumps = BTreeMap::::new(); + for entry in data.fragments.values().flat_map(|f| &f.change) { + let affected: Vec<_> = if entry.workspace { + names.iter().collect() + } else { + entry.crates.iter().collect() + }; + for name in affected { + *bumps.entry(name.clone()).or_default() |= entry.category == Category::Breaking; + } + } + let mut counts = BTreeMap::new(); + if root.join(".git").exists() { + for pkg in graph.packages.values() { + let tag = format!("{}-v{}", pkg.name, pkg.version); + let exists = process::Command::new("git") + .current_dir(root) + .args([ + "show-ref", + "--verify", + "--quiet", + &format!("refs/tags/{tag}"), + ]) + .status() + .map_err(|e| e.to_string())?; + if !exists.success() { + if exists.code() == Some(1) { + continue; + } + return Err(format!("git show-ref failed for {tag}: {exists}")); + } + let output = process::Command::new("git") + .current_dir(root) + .args([ + "rev-list", + "--count", + &format!("{tag}..HEAD"), + "--", + pkg.rel_dir.as_str(), + &format!(":(exclude){}/README.md", pkg.rel_dir), + ]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err(String::from_utf8_lossy(&output.stderr).into_owned()); + } + let count: u64 = String::from_utf8_lossy(&output.stdout) + .trim() + .parse() + .map_err(|e| format!("{tag}: {e}"))?; + if count > 0 { + bumps.entry(pkg.name.clone()).or_default(); + } + counts.insert(&pkg.name, count); + } + } + + // Dependencies precede their dependents, so each bump is final when propagated. + for name in graph.topological_publish_order(&names)? { + let pkg = &graph.packages[&name]; + if pkg + .public_deps + .iter() + .any(|dep| bumps.get(dep) == Some(&true)) + { + bumps.insert(name, true); + } else if pkg.private_deps.iter().any(|dep| bumps.contains_key(dep)) { + bumps.entry(name).or_default(); + } + } + if bumps.is_empty() { + println!("No release suggested."); + return Ok(()); + } + println!( + "{:<38} {:<12} {:<12} COMMITS", + "CRATE", "CURRENT", "SUGGESTED" + ); + let mut specs = Vec::new(); + let order = graph.topological_publish_order(&bumps.keys().cloned().collect())?; + for name in &order { + let old = &graph.packages[name].version; + let new = suggest_next_version(old, bumps[name]); + let count = counts + .get(name) + .map_or_else(|| "-".to_owned(), u64::to_string); + println!("{name:<38} {old:<12} {new:<12} {count}"); + specs.push(format!("{name}={new}")); + } + println!("\ncargo x release prepare {}", specs.join(" ")); + print_order(&order); + Ok(()) +} + +pub(crate) struct ReleasePlanReport { + consumed: Vec, + retained: Vec, + publish_order: Vec, +} + +pub(crate) fn prepare_release( + root: &Path, + graph: &WorkspaceGraph, + specs: &[(String, Version)], + apply: bool, +) -> Result { + if specs.is_empty() { + return Err("explicit CRATE=VERSION targets are required".into()); + } + let names = graph.packages.keys().cloned().collect(); + let data = load_and_validate(root, &names)?; + let mut releases = data.releases; + if releases.first().is_some_and(|r| r.date.is_none()) { + return Err("an undated release is already pending in changes/releases.toml; record its release date before preparing another release".into()); + } + let mut versions = BTreeMap::new(); + let mut breaking = BTreeSet::new(); + let mut initial = BTreeSet::new(); + for (name, version) in specs { + let pkg = graph + .packages + .get(name) + .ok_or_else(|| format!("unknown crate {name}"))?; + if version < &pkg.version + || !version.pre.is_empty() + || !version.build.is_empty() + || (version == &pkg.version && has_prior_release(root, name, &releases)?) + { + return Err(format!( + "{name}: expected a stable version greater than {}, got {version}", + pkg.version + )); + } + if versions.insert(name.clone(), version.to_string()).is_some() { + return Err(format!("duplicate target {name}")); + } + if version == &pkg.version { + initial.insert(name.clone()); + } else if is_breaking_bump(&pkg.version, version) { + breaking.insert(name.clone()); + } + } + let selected: BTreeSet<_> = versions.keys().cloned().collect(); + let mut consumed = Vec::new(); + let mut retained = Vec::new(); + let mut change = Vec::new(); + for (path, fragment) in data.fragments { + if fragment.change.iter().any(|e| e.workspace) && selected.len() < graph.packages.len() { + return Err(format!( + "{}: workspace-wide fragments require a full-workspace release or splitting into explicit crates", + path.display() + )); + } + let affected: BTreeSet<_> = fragment + .change + .iter() + .flat_map(|e| e.crates.iter().cloned()) + .collect(); + if affected.is_subset(&selected) { + change.extend(fragment.change); + consumed.push(path); + } else if affected.is_disjoint(&selected) { + retained.push(path); + } else { + let missing: Vec<_> = affected.difference(&selected).cloned().collect(); + return Err(format!( + "{}: fragment also requires {}", + path.display(), + missing.join(", ") + )); + } + } + let needs_breaking_bump = |name: &String| !breaking.contains(name) && !initial.contains(name); + for entry in &change { + if entry.category == Category::Breaking { + let missing = if entry.workspace { + names.iter().find(|n| needs_breaking_bump(n)) + } else { + entry.crates.iter().find(|n| needs_breaking_bump(n)) + }; + if let Some(name) = missing { + return Err(format!( + "breaking change requires a breaking bump for {name}" + )); + } + } + } + for pkg in graph.packages.values() { + if needs_breaking_bump(&pkg.name) + && let Some(dep) = pkg.public_deps.iter().find(|d| breaking.contains(*d)) + { + return Err(format!( + "breaking bump for public dependency {dep} requires a breaking bump for {}", + pkg.name + )); + } + if !selected.contains(&pkg.name) + && let Some(dep) = pkg.private_deps.iter().find(|d| breaking.contains(*d)) + { + return Err(format!( + "breaking bump for private dependency {dep} requires releasing {}", + pkg.name + )); + } + } + for (name, version) in specs { + if let Some(previous) = releases.iter().find_map(|r| r.crates.get(name)) + && &Version::parse(previous).expect("validated release version") >= version + { + return Err(format!( + "{name} {version} must follow ledger version {previous}" + )); + } + } + let publish_order = graph.topological_publish_order(&selected)?; + let mut updates = documentation_updates(root, graph, specs)?; + if apply { + let path = root.join("Cargo.toml"); + let mut workspace = read_manifest(&path)?; + for (name, version) in &versions { + let manifest_path = &graph.packages[name].manifest_path; + let mut manifest = read_manifest(manifest_path)?; + set_version(&mut manifest["package"]["version"], version)?; + set_version( + &mut workspace["workspace"]["dependencies"][name]["version"], + version, + )?; + updates.insert(manifest_path.clone(), manifest.to_string()); + } + updates.insert(path, workspace.to_string()); + releases.insert( + 0, + ReleaseRecord { + date: None, + crates: versions, + change, + }, + ); + updates.insert( + root.join("changes/releases.toml"), + format_releases_toml(&releases), + ); + updates.insert(root.join("CHANGELOG.md"), render_root_changelog(&releases)); + for (path, contents) in updates { + fs::write(&path, contents).map_err(|e| format!("{}: {e}", path.display()))?; + } + for path in &consumed { + fs::remove_file(path).map_err(|e| format!("{}: {e}", path.display()))?; + } + } + Ok(ReleasePlanReport { + consumed, + retained, + publish_order, + }) +} + +fn has_prior_release(root: &Path, name: &str, releases: &[ReleaseRecord]) -> Result { + if releases.iter().any(|r| r.crates.contains_key(name)) { + return Ok(true); + } + if !root.join(".git").exists() { + return Ok(false); + } + let output = process::Command::new("git") + .current_dir(root) + .args(["tag", "--list", &format!("{name}-v*")]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err(String::from_utf8_lossy(&output.stderr).into_owned()); + } + Ok(!output.stdout.trim_ascii().is_empty()) +} + +fn read_manifest(path: &Path) -> Result { + fs::read_to_string(path) + .map_err(|e| format!("{}: {e}", path.display()))? + .parse() + .map_err(|e| format!("{}: {e}", path.display())) +} + +fn set_version(item: &mut toml_edit::Item, version: &str) -> Result<(), String> { + let value = item + .as_value_mut() + .filter(|v| v.is_str()) + .ok_or("expected a manifest version string")?; + let decor = value.decor().clone(); + *value = version.into(); + *value.decor_mut() = decor; + Ok(()) +} + +fn documentation_updates( + root: &Path, + graph: &WorkspaceGraph, + specs: &[(String, Version)], +) -> Result, String> { + let mut paths = Vec::new(); + if root.join(".git").exists() { + let output = process::Command::new("git") + .current_dir(root) + .args(["ls-files", "-z", "--", "*.md", "*.rs"]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err(String::from_utf8_lossy(&output.stderr).into_owned()); + } + let files = std::str::from_utf8(&output.stdout).map_err(|e| e.to_string())?; + paths.extend(files.split_terminator('\0').map(PathBuf::from)); + } else { + let mut dirs = vec![PathBuf::new()]; + while let Some(dir) = dirs.pop() { + for item in fs::read_dir(root.join(&dir)).map_err(|e| e.to_string())? { + let item = item.map_err(|e| e.to_string())?; + let path = dir.join(item.file_name()); + let ty = item.file_type().map_err(|e| e.to_string())?; + if ty.is_dir() && !excluded(&path) { + dirs.push(path); + } else if ty.is_file() { + paths.push(path); + } + } + } + } + let links: Vec<_> = specs + .iter() + .map(|(name, new)| { + let old = &graph.packages[name].version; + ( + format!("https://docs.rs/{name}/{old}/"), + format!("https://docs.rs/{name}/{new}/"), + ) + }) + .collect(); + let mut updates = BTreeMap::new(); + for path in paths { + if excluded(&path) + || !matches!(path.extension().and_then(|s| s.to_str()), Some("md" | "rs")) + { + continue; + } + let full = root.join(&path); + if full.is_symlink() { + continue; + } + let contents = fs::read_to_string(&full).map_err(|e| format!("{}: {e}", full.display()))?; + let mut updated = contents.clone(); + for (old, new) in &links { + updated = updated.replace(old, new); + } + if path == Path::new("README.md") + && let Some(msrv) = &graph.rust_version + { + let short = msrv.split('.').take(2).collect::>().join("."); + for (prefix, suffix, replacement) in [ + ("[![MSRV ", "][msrv-badge]]", short.as_str()), + ( + "https://img.shields.io/badge/MSRV-", + "-green?logo=rust", + short.as_str(), + ), + ("minimum supported rustc version is ", ".", msrv.as_str()), + ] { + let mut offset = 0; + while let Some(i) = updated[offset..].find(prefix) { + let start = offset + i + prefix.len(); + let tail = &updated[start..]; + let len = tail + .bytes() + .take_while(|c| c.is_ascii_digit() || *c == b'.') + .count(); + let old = tail[..len].trim_end_matches('.'); + if !old.is_empty() && tail[old.len()..].starts_with(suffix) { + updated.replace_range(start..start + old.len(), replacement); + offset = start + replacement.len(); + } else { + offset = start; + } + } + } + } + if updated != contents { + updates.insert(full, updated); + } + } + Ok(updates) +} + +fn excluded(path: &Path) -> bool { + ["target", ".git", "changes"] + .iter() + .any(|dir| path.starts_with(dir)) + || path == Path::new("CHANGELOG.md") + || path == Path::new("CHANGELOG-OLD.md") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::workspace::PublishablePackage; + + fn ledger(root: &Path) { + fs::create_dir_all(root.join("changes/unreleased")).unwrap(); + fs::write(root.join("changes/releases.toml"), "").unwrap(); + } + + #[test] + fn partial_release_updates_only_selected_inputs() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + ledger(root); + let mut crates = Vec::new(); + let mut dependencies = String::from("[workspace.dependencies]\n"); + for (name, version) in [("logforth", "0.31.0"), ("logforth-core", "0.5.0")] { + let path = root.join(name); + fs::create_dir(&path).unwrap(); + let manifest_path = path.join("Cargo.toml"); + fs::write( + &manifest_path, + format!("[package]\nversion = \"{version}\" # current\n"), + ) + .unwrap(); + dependencies.push_str(&format!( + "{name} = {{ version = \"{version}\", path = \"{name}\" }}\n" + )); + crates.push(PublishablePackage { + name: name.into(), + version: version.parse().unwrap(), + manifest_path, + rel_dir: name.into(), + public_deps: vec![], + private_deps: vec![], + publish_order_deps: vec![], + }); + } + let graph = WorkspaceGraph::new(crates, Some("1.91.0".into())); + fs::write(root.join("Cargo.toml"), dependencies).unwrap(); + let fragment = |scope| { + format!("[[change]]\ncategory = \"fix\"\ntext = \"Handle missing data.\"\n{scope}\n") + }; + let path = root.join("changes/unreleased/facade.toml"); + let retained = root.join("changes/unreleased/core.toml"); + let keep = root.join("changes/unreleased/.gitkeep"); + fs::write(&keep, "").unwrap(); + let other = fragment("crates = [\"logforth-core\"]"); + fs::write(&retained, &other).unwrap(); + let specs = [("logforth".into(), Version::new(0, 32, 0))]; + for (scope, reason) in [ + ( + "crates = [\"logforth\", \"logforth-core\"]", + "logforth-core", + ), + ("workspace = true", "full-workspace"), + ] { + fs::write(&path, fragment(scope)).unwrap(); + let err = prepare_release(root, &graph, &specs, true).err().unwrap(); + assert!(err.contains("facade.toml") && err.contains(reason), "{err}"); + } + fs::write(&path, fragment("crates = [\"logforth\"]")).unwrap(); + let links = |facade| { + format!( + "https://docs.rs/logforth/{facade}/ https://docs.rs/logforth-core/{}/ https://docs.rs/log/{}/", + "0.5.0", "0.4.31" + ) + }; + let readme = |version, short, msrv| { + format!( + "{}\n[![MSRV {short}][msrv-badge]]\nhttps://img.shields.io/badge/MSRV-{short}-green?logo=rust\nminimum supported rustc version is {msrv}.\n", + links(version) + ) + }; + let before = readme("0.31.0", "1.85", "1.85.0"); + fs::write(root.join("README.md"), &before).unwrap(); + fs::write(root.join("CHANGELOG-OLD.md"), &before).unwrap(); + prepare_release(root, &graph, &specs, false).unwrap(); + assert!(path.exists()); + assert_eq!(fs::read_to_string(root.join("README.md")).unwrap(), before); + prepare_release(root, &graph, &specs, true).unwrap(); + let next = [("logforth-core".into(), Version::new(0, 5, 1))]; + let err = prepare_release(root, &graph, &next, true).err().unwrap(); + assert!( + err.contains("an undated release is already pending"), + "{err}" + ); + assert!(!path.exists() && keep.exists()); + assert_eq!(fs::read_to_string(retained).unwrap(), other); + assert_eq!( + fs::read_to_string(root.join("CHANGELOG-OLD.md")).unwrap(), + before + ); + assert_eq!( + fs::read_to_string(root.join("README.md")).unwrap(), + readme("0.32.0", "1.91", "1.91.0") + ); + assert_eq!(read_manifest(&root.join("Cargo.toml")).unwrap()["workspace"]["dependencies"]["logforth"]["version"].as_str(), Some("0.32.0")); + assert!( + fs::read_to_string(root.join("logforth/Cargo.toml")) + .unwrap() + .contains("\"0.32.0\" # current") + ); + let data = load_and_validate(root, &graph.packages.keys().cloned().collect()).unwrap(); + assert_eq!(data.releases[0].change.len(), 1); + assert_eq!( + data.releases[0].crates.keys().collect::>(), + ["logforth"] + ); + assert_eq!( + fs::read_to_string(root.join("CHANGELOG.md")).unwrap(), + render_root_changelog(&data.releases) + ); + } + + #[test] + fn breaking_changes_follow_runtime_dependencies() { + let graph = WorkspaceGraph::load(Path::new(env!("CARGO_WORKSPACE_DIR"))).unwrap(); + let dir = tempfile::tempdir().unwrap(); + ledger(dir.path()); + let prepare = |targets: &[(&str, bool)]| { + let specs: Vec<_> = targets + .iter() + .map(|&(n, breaking)| { + ( + n.to_owned(), + suggest_next_version(&graph.packages[n].version, breaking), + ) + }) + .collect(); + prepare_release(dir.path(), &graph, &specs, false) + }; + for (name, dependent) in [ + ("logforth-core", "logforth"), + ("logforth-syslog", "logforth-append-syslog"), + ("logforth-logfmt", "logforth-layout-logfmt"), + ] { + let err = prepare(&[(name, true)]).err().unwrap(); + assert!(err.contains(name) && err.contains(dependent), "{err}"); + } + let peripheral = "logforth-append-opentelemetry"; + assert!(prepare(&[(peripheral, true), ("logforth", false)]).is_err()); + prepare(&[(peripheral, true), ("logforth", true)]).unwrap(); + prepare(&[("logforth-logfmt", true), ("logforth-layout-logfmt", false)]).unwrap(); + fs::write(dir.path().join("changes/unreleased/incompatible.toml"), "[[change]]\ncategory = 'breaking'\ncrates = ['logforth']\ntext = 'Remove an obsolete API.'\n").unwrap(); + assert!(prepare(&[("logforth", false)]).is_err()); + } + + #[test] + fn initial_release_can_keep_the_manifest_version() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + ledger(root); + let name = "example"; + let version = Version::new(0, 1, 0); + let graph = WorkspaceGraph::new( + vec![PublishablePackage { + name: name.into(), + version: version.clone(), + manifest_path: root.join("example/Cargo.toml"), + rel_dir: name.into(), + public_deps: vec![], + private_deps: vec![], + publish_order_deps: vec![], + }], + None, + ); + let specs = [(name.into(), version)]; + fs::write(root.join("changes/unreleased/example.toml"), "[[change]]\ncategory = 'breaking'\ncrates = ['example']\ntext = 'Replace the draft API.'").unwrap(); + prepare_release(root, &graph, &specs, false).unwrap(); + fs::write( + root.join("changes/releases.toml"), + "[[release]]\ndate = '2026-01-01'\n[release.crates]\nexample = '0.1.0'", + ) + .unwrap(); + let err = prepare_release(root, &graph, &specs, false).err().unwrap(); + assert!( + err.contains("expected a stable version greater than 0.1.0"), + "{err}" + ); + } + + #[test] + fn publish_order_honors_versioned_dev_dependencies() { + let graph = WorkspaceGraph::load(Path::new(env!("CARGO_WORKSPACE_DIR"))).unwrap(); + let order = graph + .topological_publish_order(&graph.packages.keys().cloned().collect()) + .unwrap(); + let position = |n| order.iter().position(|v| v == n).unwrap(); + for appender in ["logforth-append-file", "logforth-append-opentelemetry"] { + assert!(position("logforth-layout-json") < position(appender)); + } + for name in ["logforth-logfmt", "logforth-syslog"] { + assert!(position(name) < position("logforth-core")); + } + for name in &order { + if publish_tier_key(name).0 == 2 { + assert!( + position("logforth-core") < position(name) + && position(name) < position("logforth") + ); + } + } + } +} diff --git a/xtask/src/test.rs b/xtask/src/test.rs index 6971b2a8..5e5009dc 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -33,7 +33,7 @@ impl CommandTest { fn make_test_cmd(no_capture: bool) -> process::Command { let mut cmd = cargo(); - cmd.args(["test", "--workspace", "--exclude", "x", "--all-features"]); + cmd.args(["test", "--workspace", "--all-features"]); if no_capture { cmd.args(["--", "--nocapture"]); } diff --git a/xtask/src/workspace.rs b/xtask/src/workspace.rs new file mode 100644 index 00000000..bf6a2c20 --- /dev/null +++ b/xtask/src/workspace.rs @@ -0,0 +1,192 @@ +// Copyright 2024 FastLabs Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::collections::BTreeMap; +use std::collections::BTreeSet; +use std::fs; +use std::path::Path; +use std::path::PathBuf; + +use cargo_metadata::DependencyKind; +use cargo_metadata::MetadataCommand; +use semver::Version; +use semver::VersionReq; + +const PRIVATE_WORKSPACE_DEPS: &[(&str, &str)] = &[("logforth-layout-logfmt", "logforth-logfmt")]; + +pub(crate) struct PublishablePackage { + pub(crate) name: String, + pub(crate) version: Version, + pub(crate) manifest_path: PathBuf, + pub(crate) rel_dir: String, + pub(crate) public_deps: Vec, + pub(crate) private_deps: Vec, + pub(crate) publish_order_deps: Vec, +} + +pub(crate) struct WorkspaceGraph { + pub(crate) packages: BTreeMap, + pub(crate) rust_version: Option, +} + +impl WorkspaceGraph { + pub(crate) fn load(root: &Path) -> Result { + let manifest = root.join("Cargo.toml"); + let source = + fs::read_to_string(&manifest).map_err(|e| format!("{}: {e}", manifest.display()))?; + let doc: toml::Table = + toml::from_str(&source).map_err(|e| format!("{}: {e}", manifest.display()))?; + let rust_version = doc + .get("workspace") + .and_then(|v| v.get("package")) + .and_then(|v| v.get("rust-version")) + .and_then(|v| v.as_str()) + .map(str::to_owned); + let metadata = MetadataCommand::new() + .manifest_path(manifest) + .no_deps() + .exec() + .map_err(|e| e.to_string())?; + let packages: Vec<_> = metadata + .workspace_packages() + .into_iter() + .filter(|p| { + p.publish + .as_ref() + .is_none_or(|registries| !registries.is_empty()) + }) + .collect(); + let names: BTreeSet<_> = packages.iter().map(|p| p.name.as_str()).collect(); + let mut result = Vec::new(); + for pkg in packages { + let name = pkg.name.as_str(); + let mut public = BTreeSet::new(); + let mut private = BTreeSet::new(); + let mut order = BTreeSet::new(); + for dep in &pkg.dependencies { + if dep.path.is_none() || !names.contains(dep.name.as_str()) { + continue; + } + if dep.kind != DependencyKind::Development || dep.req != VersionReq::STAR { + order.insert(dep.name.clone()); + } + if dep.kind == DependencyKind::Normal { + if PRIVATE_WORKSPACE_DEPS.contains(&(name, dep.name.as_str())) { + private.insert(dep.name.clone()); + } else { + public.insert(dep.name.clone()); + } + } + } + let dir = pkg + .manifest_path + .parent() + .unwrap() + .strip_prefix(&metadata.workspace_root) + .map_err(|e| e.to_string())?; + result.push(PublishablePackage { + name: name.to_owned(), + version: pkg.version.clone(), + manifest_path: pkg.manifest_path.clone().into_std_path_buf(), + rel_dir: dir + .components() + .map(|c| c.as_str()) + .collect::>() + .join("/"), + public_deps: public.into_iter().collect(), + private_deps: private.into_iter().collect(), + publish_order_deps: order.into_iter().collect(), + }); + } + Ok(Self::new(result, rust_version)) + } + + pub(crate) fn new(packages: Vec, rust_version: Option) -> Self { + Self { + packages: packages.into_iter().map(|p| (p.name.clone(), p)).collect(), + rust_version, + } + } + + pub(crate) fn topological_publish_order( + &self, + selected: &BTreeSet, + ) -> Result, String> { + let mut incoming = BTreeMap::new(); + let mut dependents = BTreeMap::<&str, Vec<&str>>::new(); + let mut ready = BTreeSet::new(); + for name in selected { + let pkg = self + .packages + .get(name) + .ok_or_else(|| format!("unknown crate {name}"))?; + let mut count = 0; + for dep in &pkg.publish_order_deps { + if selected.contains(dep) { + dependents.entry(dep).or_default().push(name); + count += 1; + } + } + incoming.insert(name.as_str(), count); + if count == 0 { + ready.insert(publish_tier_key(name)); + } + } + let mut order = Vec::new(); + while let Some((_, name)) = ready.pop_first() { + order.push(name.to_owned()); + if let Some(children) = dependents.get(name) { + for child in children { + let count = incoming.get_mut(child).unwrap(); + *count -= 1; + if *count == 0 { + ready.insert(publish_tier_key(child)); + } + } + } + } + if order.len() != selected.len() { + return Err("cycle among selected publish dependencies".into()); + } + Ok(order) + } +} + +pub(crate) fn crate_sort_key(name: &str) -> (u8, &str) { + let group = match name { + "logforth-core" => 0, + "logforth" => 1, + n if n.starts_with("logforth-layout-") => 2, + n if n.starts_with("logforth-append-") => 3, + n if n.starts_with("logforth-filter-") => 4, + n if n.starts_with("logforth-diagnostic-") => 5, + n if n.starts_with("logforth-bridge-") => 6, + _ => 7, + }; + (group, name) +} + +pub(crate) fn publish_tier_key(name: &str) -> (u8, &str) { + let tier = match crate_sort_key(name).0 { + 7 => 0, + 0 => 1, + 1 => 3, + _ => 2, + }; + (tier, name) +} + +pub(crate) fn short_crate_label(name: &str) -> &str { + name.strip_prefix("logforth-").unwrap_or(name) +}