From 810431d2aa2cbe3c13db1f735484d1a8bd88e2ff Mon Sep 17 00:00:00 2001 From: Rodolphe Date: Sat, 29 Aug 2026 11:58:02 -0400 Subject: [PATCH] feat: 16 demo projects, one per ecosystem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each demo is a small real project pinned to an old version of a real dependency, with source code that uses APIs the newer version breaks. Codespace creation edits the manifest to the new version and leaves the source alone, so Drift has a genuine dependency change to analyse against code written for the old API. Every breaking usage carries a BREAKING comment naming the change and why it no longer works — 3 to 5 per demo: npm axios 0.21.4 → 1.7.7 AxiosTransformer, proxy auth, AxiosError pypi werkzeug 2.0.3 → 2.1.0 safe_str_cmp, pbkdf2_hex, Href, useragents go x/exp 2023-05 → 2023-10 slices comparators bool → int cargo clap 2.34.0 → 4.5.4 App, SubCommand, with_name, takes_value, value_of maven guava 20.0 → 21.0 firstNonNull, toStringHelper, sameThreadExecutor rubygems rack 3.0.0 → 3.1.0 Rack::File, Chunked, Auth::Digest nuget AutoMapper 8.1.1 → 9.0.0 the whole static Mapper API packagist monolog 2.9.3 → 3.5.0 SwiftMailerHandler, int levels → Level enum hex plug 1.13.6 → 1.15.0 Plug.Adapters.* shims pub dio 4.0.6 → 5.0.0 lock/unlock, int timeouts, DioError swift Alamofire 4.9.1 → 5.9.1 SessionManager, responseJSON cocoapods Alamofire 4.9.1 → 5.9.1 same, through a Podfile opam lwt 4.5.0 → 5.7.0 Lwt_sequence, wrap1, add_task_l conan fmt 9.1.0 → 10.2.1 compile-time format strings, join header vcpkg spdlog 1.11.0 → 1.14.1 bundled fmt 10 tightening arduino ArduinoJson 5.13.5 → 6.21.3 StaticJsonBuffer, printTo, parseObject Devcontainers are generated for all sixteen, each installing the published drift.drift extension, preparing its own demo at creation time only, and hiding the other fifteen from the Explorer. The upgrade is a literal find/replace recorded in demo.json rather than a patch file — a demo upgrade is one version string, and a replacement does not go stale when a line above it moves. DEMO.md is generated from the BREAKING comments so the guide cannot disagree with the code. Replaces the previous validation-heavy layout: the oracle runner, semantic CLI assertions and per-language CI matrix are gone, along with the per-demo patch and expectation files. check-demos.mjs keeps the cheap part — every demo prepares, dirties only its manifest, and resets — and needs no toolchains. Co-Authored-By: Claude Sonnet 5 --- .devcontainer/arduino/devcontainer.json | 50 +++ .devcontainer/cargo/devcontainer.json | 7 +- .devcontainer/cargo/setup.sh | 32 -- .devcontainer/cocoapods/devcontainer.json | 50 +++ .devcontainer/conan/devcontainer.json | 50 +++ .devcontainer/go/devcontainer.json | 5 +- .devcontainer/hex/devcontainer.json | 7 +- .devcontainer/maven/devcontainer.json | 5 +- .devcontainer/npm/devcontainer.json | 7 +- .devcontainer/nuget/devcontainer.json | 7 +- .devcontainer/opam/devcontainer.json | 50 +++ .devcontainer/packagist/devcontainer.json | 7 +- .devcontainer/pub/devcontainer.json | 5 +- .devcontainer/pypi/devcontainer.json | 7 +- .devcontainer/rubygems/devcontainer.json | 7 +- .devcontainer/swift/devcontainer.json | 51 +++ .devcontainer/vcpkg/devcontainer.json | 50 +++ .drift-demo/demos.json | 117 ------- .github/workflows/check.yml | 22 ++ .github/workflows/verify-demos.yml | 116 ------- README.md | 97 +++--- demos/arduino/DEMO.md | 27 ++ demos/arduino/demo.json | 9 + demos/arduino/platformio.ini | 6 + demos/arduino/src/main.cpp | 54 ++++ demos/cargo/.drift-demo/expected.json | 28 -- demos/cargo/.drift-demo/oracle.sh | 9 - demos/cargo/.drift-demo/upgrade.patch | 205 ------------ demos/cargo/Cargo.lock | 115 ------- demos/cargo/DEMO.md | 31 +- demos/cargo/demo.json | 9 + demos/cargo/src/main.rs | 46 ++- demos/cocoapods/DEMO.md | 27 ++ .../cocoapods/DriftDemo/NetworkService.swift | 38 +++ demos/cocoapods/Podfile | 7 + demos/cocoapods/demo.json | 9 + demos/conan/CMakeLists.txt | 9 + demos/conan/DEMO.md | 25 ++ demos/conan/conanfile.txt | 6 + demos/conan/demo.json | 9 + demos/conan/src/main.cpp | 35 ++ demos/go/.drift-demo/expected.json | 28 -- demos/go/.drift-demo/oracle.sh | 10 - demos/go/.drift-demo/upgrade.patch | 19 -- demos/go/DEMO.md | 31 +- demos/go/demo.json | 13 + demos/go/go.sum | 2 - demos/go/main.go | 49 ++- demos/hex/.drift-demo/expected.json | 17 - demos/hex/.drift-demo/oracle.sh | 13 - demos/hex/.drift-demo/upgrade.patch | 13 - demos/hex/DEMO.md | 31 +- demos/hex/demo.json | 9 + demos/hex/lib/router.ex | 9 - demos/hex/lib/server.ex | 30 ++ demos/maven/.drift-demo/expected.json | 27 -- demos/maven/.drift-demo/oracle.sh | 9 - demos/maven/.drift-demo/upgrade.patch | 13 - demos/maven/DEMO.md | 29 +- demos/maven/demo.json | 9 + .../main/java/com/example/demo/Config.java | 42 ++- demos/npm/.drift-demo/expected.json | 17 - demos/npm/.drift-demo/oracle.sh | 11 - demos/npm/.drift-demo/upgrade.patch | 299 ------------------ demos/npm/DEMO.md | 30 +- demos/npm/demo.json | 9 + demos/npm/package-lock.json | 61 ---- demos/npm/src/api-client.ts | 49 +++ demos/npm/src/index.ts | 11 - demos/nuget/.drift-demo/expected.json | 28 -- demos/nuget/.drift-demo/oracle.sh | 10 - demos/nuget/.drift-demo/upgrade.patch | 13 - demos/nuget/DEMO.md | 32 +- demos/nuget/Mapping.cs | 55 ++++ demos/nuget/Program.cs | 22 -- demos/nuget/demo.json | 9 + demos/opam/DEMO.md | 25 ++ demos/opam/demo.json | 9 + demos/opam/drift_demo.opam | 13 + demos/opam/dune-project | 1 + demos/opam/lib/dune | 3 + demos/opam/lib/scheduler.ml | 24 ++ demos/packagist/.drift-demo/expected.json | 33 -- demos/packagist/.drift-demo/oracle.sh | 14 - demos/packagist/.drift-demo/upgrade.patch | 13 - demos/packagist/DEMO.md | 32 +- demos/packagist/demo.json | 9 + demos/packagist/src/Logging.php | 52 +++ demos/packagist/src/MailErrorHandler.php | 15 - demos/pub/.drift-demo/expected.json | 17 - demos/pub/.drift-demo/oracle.sh | 17 - demos/pub/.drift-demo/upgrade.patch | 10 - demos/pub/DEMO.md | 31 +- demos/pub/demo.json | 9 + demos/pub/lib/api_client.dart | 39 ++- demos/pypi/.drift-demo/expected.json | 17 - demos/pypi/.drift-demo/oracle.sh | 12 - demos/pypi/.drift-demo/upgrade.patch | 7 - demos/pypi/DEMO.md | 31 +- demos/pypi/demo.json | 9 + demos/pypi/src/auth.py | 46 +++ demos/pypi/src/main.py | 8 - demos/rubygems/.drift-demo/expected.json | 20 -- demos/rubygems/.drift-demo/oracle.sh | 10 - demos/rubygems/.drift-demo/upgrade.patch | 29 -- demos/rubygems/DEMO.md | 31 +- demos/rubygems/Gemfile.lock | 13 - demos/rubygems/demo.json | 9 + demos/rubygems/lib/app.rb | 32 ++ demos/rubygems/lib/static_app.rb | 9 - demos/swift/DEMO.md | 26 ++ demos/swift/Package.swift | 16 + demos/swift/Sources/DriftDemo/ApiClient.swift | 38 +++ demos/swift/demo.json | 9 + demos/vcpkg/CMakeLists.txt | 9 + demos/vcpkg/DEMO.md | 25 ++ demos/vcpkg/demo.json | 9 + demos/vcpkg/src/main.cpp | 39 +++ demos/vcpkg/vcpkg.json | 14 + docs/ecosystem-status.md | 99 ------ scripts/check-demos.mjs | 65 ++++ scripts/lib/demo-config.mjs | 295 ++--------------- scripts/lib/devcontainer-spec.mjs | 116 ++++--- scripts/lib/drift-runner.mjs | 233 -------------- scripts/lib/manifest-version.mjs | 188 ----------- scripts/make-demo-docs.mjs | 85 +++++ scripts/prepare-demo.mjs | 133 ++------ scripts/reset-demo.mjs | 72 +---- scripts/sync-devcontainers.mjs | 35 +- scripts/verify-all.mjs | 118 ------- scripts/verify-demo.mjs | 201 ------------ scripts/verify-devcontainers.mjs | 108 ------- scripts/verify-oracle.mjs | 128 -------- scripts/verify-structure.mjs | 66 ---- 134 files changed, 1884 insertions(+), 3404 deletions(-) create mode 100644 .devcontainer/arduino/devcontainer.json delete mode 100755 .devcontainer/cargo/setup.sh create mode 100644 .devcontainer/cocoapods/devcontainer.json create mode 100644 .devcontainer/conan/devcontainer.json create mode 100644 .devcontainer/opam/devcontainer.json create mode 100644 .devcontainer/swift/devcontainer.json create mode 100644 .devcontainer/vcpkg/devcontainer.json delete mode 100644 .drift-demo/demos.json create mode 100644 .github/workflows/check.yml delete mode 100644 .github/workflows/verify-demos.yml create mode 100644 demos/arduino/DEMO.md create mode 100644 demos/arduino/demo.json create mode 100644 demos/arduino/platformio.ini create mode 100644 demos/arduino/src/main.cpp delete mode 100644 demos/cargo/.drift-demo/expected.json delete mode 100755 demos/cargo/.drift-demo/oracle.sh delete mode 100644 demos/cargo/.drift-demo/upgrade.patch delete mode 100644 demos/cargo/Cargo.lock create mode 100644 demos/cargo/demo.json create mode 100644 demos/cocoapods/DEMO.md create mode 100644 demos/cocoapods/DriftDemo/NetworkService.swift create mode 100644 demos/cocoapods/Podfile create mode 100644 demos/cocoapods/demo.json create mode 100644 demos/conan/CMakeLists.txt create mode 100644 demos/conan/DEMO.md create mode 100644 demos/conan/conanfile.txt create mode 100644 demos/conan/demo.json create mode 100644 demos/conan/src/main.cpp delete mode 100644 demos/go/.drift-demo/expected.json delete mode 100755 demos/go/.drift-demo/oracle.sh delete mode 100644 demos/go/.drift-demo/upgrade.patch create mode 100644 demos/go/demo.json delete mode 100644 demos/go/go.sum delete mode 100644 demos/hex/.drift-demo/expected.json delete mode 100755 demos/hex/.drift-demo/oracle.sh delete mode 100644 demos/hex/.drift-demo/upgrade.patch create mode 100644 demos/hex/demo.json delete mode 100644 demos/hex/lib/router.ex create mode 100644 demos/hex/lib/server.ex delete mode 100644 demos/maven/.drift-demo/expected.json delete mode 100755 demos/maven/.drift-demo/oracle.sh delete mode 100644 demos/maven/.drift-demo/upgrade.patch create mode 100644 demos/maven/demo.json delete mode 100644 demos/npm/.drift-demo/expected.json delete mode 100755 demos/npm/.drift-demo/oracle.sh delete mode 100644 demos/npm/.drift-demo/upgrade.patch create mode 100644 demos/npm/demo.json delete mode 100644 demos/npm/package-lock.json create mode 100644 demos/npm/src/api-client.ts delete mode 100644 demos/npm/src/index.ts delete mode 100644 demos/nuget/.drift-demo/expected.json delete mode 100755 demos/nuget/.drift-demo/oracle.sh delete mode 100644 demos/nuget/.drift-demo/upgrade.patch create mode 100644 demos/nuget/Mapping.cs delete mode 100644 demos/nuget/Program.cs create mode 100644 demos/nuget/demo.json create mode 100644 demos/opam/DEMO.md create mode 100644 demos/opam/demo.json create mode 100644 demos/opam/drift_demo.opam create mode 100644 demos/opam/dune-project create mode 100644 demos/opam/lib/dune create mode 100644 demos/opam/lib/scheduler.ml delete mode 100644 demos/packagist/.drift-demo/expected.json delete mode 100755 demos/packagist/.drift-demo/oracle.sh delete mode 100644 demos/packagist/.drift-demo/upgrade.patch create mode 100644 demos/packagist/demo.json create mode 100644 demos/packagist/src/Logging.php delete mode 100644 demos/packagist/src/MailErrorHandler.php delete mode 100644 demos/pub/.drift-demo/expected.json delete mode 100755 demos/pub/.drift-demo/oracle.sh delete mode 100644 demos/pub/.drift-demo/upgrade.patch create mode 100644 demos/pub/demo.json delete mode 100644 demos/pypi/.drift-demo/expected.json delete mode 100755 demos/pypi/.drift-demo/oracle.sh delete mode 100644 demos/pypi/.drift-demo/upgrade.patch create mode 100644 demos/pypi/demo.json create mode 100644 demos/pypi/src/auth.py delete mode 100644 demos/pypi/src/main.py delete mode 100644 demos/rubygems/.drift-demo/expected.json delete mode 100755 demos/rubygems/.drift-demo/oracle.sh delete mode 100644 demos/rubygems/.drift-demo/upgrade.patch delete mode 100644 demos/rubygems/Gemfile.lock create mode 100644 demos/rubygems/demo.json create mode 100644 demos/rubygems/lib/app.rb delete mode 100644 demos/rubygems/lib/static_app.rb create mode 100644 demos/swift/DEMO.md create mode 100644 demos/swift/Package.swift create mode 100644 demos/swift/Sources/DriftDemo/ApiClient.swift create mode 100644 demos/swift/demo.json create mode 100644 demos/vcpkg/CMakeLists.txt create mode 100644 demos/vcpkg/DEMO.md create mode 100644 demos/vcpkg/demo.json create mode 100644 demos/vcpkg/src/main.cpp create mode 100644 demos/vcpkg/vcpkg.json delete mode 100644 docs/ecosystem-status.md create mode 100644 scripts/check-demos.mjs delete mode 100644 scripts/lib/drift-runner.mjs delete mode 100644 scripts/lib/manifest-version.mjs create mode 100644 scripts/make-demo-docs.mjs delete mode 100644 scripts/verify-all.mjs delete mode 100644 scripts/verify-demo.mjs delete mode 100644 scripts/verify-devcontainers.mjs delete mode 100644 scripts/verify-oracle.mjs delete mode 100644 scripts/verify-structure.mjs diff --git a/.devcontainer/arduino/devcontainer.json b/.devcontainer/arduino/devcontainer.json new file mode 100644 index 0000000..c836f58 --- /dev/null +++ b/.devcontainer/arduino/devcontainer.json @@ -0,0 +1,50 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — Arduino / PlatformIO", + "image": "mcr.microsoft.com/devcontainers/python:1-3.12-bookworm", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + } + }, + "onCreateCommand": "pipx install platformio && node scripts/prepare-demo.mjs arduino", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/swift": true, + "demos/cocoapods": true, + "demos/opam": true, + "demos/conan": true, + "demos/vcpkg": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/arduino/DEMO.md", + "demos/arduino/src/main.cpp", + "demos/arduino/platformio.ini" + ] + } + } +} diff --git a/.devcontainer/cargo/devcontainer.json b/.devcontainer/cargo/devcontainer.json index af3ed21..752e33c 100644 --- a/.devcontainer/cargo/devcontainer.json +++ b/.devcontainer/cargo/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Rust", "image": "mcr.microsoft.com/devcontainers/rust:1-1-bookworm", @@ -13,7 +10,7 @@ "version": "lts" } }, - "onCreateCommand": ".devcontainer/cargo/setup.sh", + "onCreateCommand": "node scripts/prepare-demo.mjs cargo", "waitFor": "onCreateCommand", "customizations": { "vscode": { diff --git a/.devcontainer/cargo/setup.sh b/.devcontainer/cargo/setup.sh deleted file mode 100755 index fc06aa7..0000000 --- a/.devcontainer/cargo/setup.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -# Creation-time setup for the Rust demo Codespace. -# -# Two things Drift's Rust surface diff needs, provisioned up front rather than -# lazily during the first analysis: -# -# - the nightly toolchain, because `cargo public-api` reads rustdoc's -# unstable JSON output, which only nightly rustc emits; -# - `cargo-public-api` itself, which otherwise compiles from source the first -# time the panel runs — several minutes of an apparently idle demo. -# -# Both are pinned so the demo stays deterministic. Then the fixture's -# uncommitted upgrade is applied, exactly as every other demo does it. -set -euo pipefail - -# Pinned: this is the version the fixture's expected findings were verified -# against. The nightly toolchain is deliberately *not* date-pinned — this -# mirrors what Drift's own auto-install does (`rustup toolchain install -# nightly --profile minimal`), and a stale pinned nightly that cargo-public-api -# has outgrown fails harder than tracking the channel. -CARGO_PUBLIC_API_VERSION="0.52.0" - -echo "==> Installing nightly toolchain (required by cargo public-api)" -rustup toolchain install nightly --profile minimal - -echo "==> Installing cargo-public-api $CARGO_PUBLIC_API_VERSION" -cargo install cargo-public-api --locked --version "$CARGO_PUBLIC_API_VERSION" - -echo "==> Preparing the Rust demo fixture" -node scripts/prepare-demo.mjs cargo - -echo "==> Rust demo ready" diff --git a/.devcontainer/cocoapods/devcontainer.json b/.devcontainer/cocoapods/devcontainer.json new file mode 100644 index 0000000..f543fdb --- /dev/null +++ b/.devcontainer/cocoapods/devcontainer.json @@ -0,0 +1,50 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — CocoaPods", + "image": "mcr.microsoft.com/devcontainers/ruby:1-3.3-bookworm", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + } + }, + "onCreateCommand": "gem install cocoapods --no-document && node scripts/prepare-demo.mjs cocoapods", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/swift": true, + "demos/opam": true, + "demos/conan": true, + "demos/vcpkg": true, + "demos/arduino": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/cocoapods/DEMO.md", + "demos/cocoapods/DriftDemo/NetworkService.swift", + "demos/cocoapods/Podfile" + ] + } + } +} diff --git a/.devcontainer/conan/devcontainer.json b/.devcontainer/conan/devcontainer.json new file mode 100644 index 0000000..62c6c16 --- /dev/null +++ b/.devcontainer/conan/devcontainer.json @@ -0,0 +1,50 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — C / C++ (Conan)", + "image": "mcr.microsoft.com/devcontainers/cpp:1-debian-12", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + } + }, + "onCreateCommand": "pipx install conan && node scripts/prepare-demo.mjs conan", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/swift": true, + "demos/cocoapods": true, + "demos/opam": true, + "demos/vcpkg": true, + "demos/arduino": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/conan/DEMO.md", + "demos/conan/src/main.cpp", + "demos/conan/conanfile.txt" + ] + } + } +} diff --git a/.devcontainer/go/devcontainer.json b/.devcontainer/go/devcontainer.json index 66e7d83..dddd174 100644 --- a/.devcontainer/go/devcontainer.json +++ b/.devcontainer/go/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Go", "image": "mcr.microsoft.com/devcontainers/go:1-1.22-bookworm", diff --git a/.devcontainer/hex/devcontainer.json b/.devcontainer/hex/devcontainer.json index 3cafd08..58ad7d5 100644 --- a/.devcontainer/hex/devcontainer.json +++ b/.devcontainer/hex/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Elixir / Erlang", "image": "hexpm/elixir:1.15.7-erlang-26.2.1-debian-bookworm-20231009-slim", @@ -46,7 +43,7 @@ "codespaces": { "openFiles": [ "demos/hex/DEMO.md", - "demos/hex/lib/router.ex", + "demos/hex/lib/server.ex", "demos/hex/mix.exs" ] } diff --git a/.devcontainer/maven/devcontainer.json b/.devcontainer/maven/devcontainer.json index 9f9d967..63c1263 100644 --- a/.devcontainer/maven/devcontainer.json +++ b/.devcontainer/maven/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Java / Kotlin / Scala", "image": "mcr.microsoft.com/devcontainers/java:1-21-bookworm", diff --git a/.devcontainer/npm/devcontainer.json b/.devcontainer/npm/devcontainer.json index 7066af6..a8def40 100644 --- a/.devcontainer/npm/devcontainer.json +++ b/.devcontainer/npm/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — JavaScript / TypeScript", "image": "mcr.microsoft.com/devcontainers/javascript-node:1-22-bookworm", @@ -40,7 +37,7 @@ "codespaces": { "openFiles": [ "demos/npm/DEMO.md", - "demos/npm/src/index.ts", + "demos/npm/src/api-client.ts", "demos/npm/package.json" ] } diff --git a/.devcontainer/nuget/devcontainer.json b/.devcontainer/nuget/devcontainer.json index bb4f42d..221f7bc 100644 --- a/.devcontainer/nuget/devcontainer.json +++ b/.devcontainer/nuget/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — .NET", "image": "mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm", @@ -45,7 +42,7 @@ "codespaces": { "openFiles": [ "demos/nuget/DEMO.md", - "demos/nuget/Program.cs", + "demos/nuget/Mapping.cs", "demos/nuget/DriftDemo.csproj" ] } diff --git a/.devcontainer/opam/devcontainer.json b/.devcontainer/opam/devcontainer.json new file mode 100644 index 0000000..473b47a --- /dev/null +++ b/.devcontainer/opam/devcontainer.json @@ -0,0 +1,50 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — OCaml", + "image": "ocaml/opam:debian-12-ocaml-4.14", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + } + }, + "onCreateCommand": "node scripts/prepare-demo.mjs opam", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/swift": true, + "demos/cocoapods": true, + "demos/conan": true, + "demos/vcpkg": true, + "demos/arduino": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/opam/DEMO.md", + "demos/opam/lib/scheduler.ml", + "demos/opam/drift_demo.opam" + ] + } + } +} diff --git a/.devcontainer/packagist/devcontainer.json b/.devcontainer/packagist/devcontainer.json index 06f304c..a73f919 100644 --- a/.devcontainer/packagist/devcontainer.json +++ b/.devcontainer/packagist/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — PHP", "image": "mcr.microsoft.com/devcontainers/php:1-8.2-bookworm", @@ -45,7 +42,7 @@ "codespaces": { "openFiles": [ "demos/packagist/DEMO.md", - "demos/packagist/src/MailErrorHandler.php", + "demos/packagist/src/Logging.php", "demos/packagist/composer.json" ] } diff --git a/.devcontainer/pub/devcontainer.json b/.devcontainer/pub/devcontainer.json index afc753d..2ad0a79 100644 --- a/.devcontainer/pub/devcontainer.json +++ b/.devcontainer/pub/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Dart / Flutter", "image": "dart:3.3", diff --git a/.devcontainer/pypi/devcontainer.json b/.devcontainer/pypi/devcontainer.json index 178d19e..1bd569c 100644 --- a/.devcontainer/pypi/devcontainer.json +++ b/.devcontainer/pypi/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Python", "image": "mcr.microsoft.com/devcontainers/python:1-3.12-bookworm", @@ -45,7 +42,7 @@ "codespaces": { "openFiles": [ "demos/pypi/DEMO.md", - "demos/pypi/src/main.py", + "demos/pypi/src/auth.py", "demos/pypi/requirements.txt" ] } diff --git a/.devcontainer/rubygems/devcontainer.json b/.devcontainer/rubygems/devcontainer.json index da7ea11..9d53912 100644 --- a/.devcontainer/rubygems/devcontainer.json +++ b/.devcontainer/rubygems/devcontainer.json @@ -1,10 +1,7 @@ -// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. { "name": "Drift demo — Ruby", "image": "mcr.microsoft.com/devcontainers/ruby:1-3.3-bookworm", @@ -45,7 +42,7 @@ "codespaces": { "openFiles": [ "demos/rubygems/DEMO.md", - "demos/rubygems/lib/static_app.rb", + "demos/rubygems/lib/app.rb", "demos/rubygems/Gemfile" ] } diff --git a/.devcontainer/swift/devcontainer.json b/.devcontainer/swift/devcontainer.json new file mode 100644 index 0000000..c320690 --- /dev/null +++ b/.devcontainer/swift/devcontainer.json @@ -0,0 +1,51 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — Swift", + "image": "swift:5.9-jammy", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + }, + "ghcr.io/devcontainers/features/git:1": {} + }, + "onCreateCommand": "node scripts/prepare-demo.mjs swift", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/cocoapods": true, + "demos/opam": true, + "demos/conan": true, + "demos/vcpkg": true, + "demos/arduino": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/swift/DEMO.md", + "demos/swift/Sources/DriftDemo/ApiClient.swift", + "demos/swift/Package.swift" + ] + } + } +} diff --git a/.devcontainer/vcpkg/devcontainer.json b/.devcontainer/vcpkg/devcontainer.json new file mode 100644 index 0000000..7085aa8 --- /dev/null +++ b/.devcontainer/vcpkg/devcontainer.json @@ -0,0 +1,50 @@ +// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. +// Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: +// +// node scripts/sync-devcontainers.mjs +{ + "name": "Drift demo — C / C++ (vcpkg)", + "image": "mcr.microsoft.com/devcontainers/cpp:1-debian-12", + "features": { + "ghcr.io/devcontainers/features/node:1": { + "version": "lts" + } + }, + "onCreateCommand": "node scripts/prepare-demo.mjs vcpkg", + "waitFor": "onCreateCommand", + "customizations": { + "vscode": { + "extensions": [ + "drift.drift" + ], + "settings": { + "drift.session.mode": "ask", + "drift.analysis.runOnStartup": true, + "files.exclude": { + "demos/npm": true, + "demos/pypi": true, + "demos/go": true, + "demos/cargo": true, + "demos/maven": true, + "demos/rubygems": true, + "demos/nuget": true, + "demos/packagist": true, + "demos/hex": true, + "demos/pub": true, + "demos/swift": true, + "demos/cocoapods": true, + "demos/opam": true, + "demos/conan": true, + "demos/arduino": true + } + } + }, + "codespaces": { + "openFiles": [ + "demos/vcpkg/DEMO.md", + "demos/vcpkg/src/main.cpp", + "demos/vcpkg/vcpkg.json" + ] + } + } +} diff --git a/.drift-demo/demos.json b/.drift-demo/demos.json deleted file mode 100644 index 8bd2357..0000000 --- a/.drift-demo/demos.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "schemaVersion": 1, - "demos": [ - { - "ecosystem": "npm", - "label": "JavaScript / TypeScript", - "status": "not-yet-validated", - "demoPath": "demos/npm", - "devcontainerPath": ".devcontainer/npm/devcontainer.json" - }, - { - "ecosystem": "pypi", - "label": "Python", - "status": "not-yet-validated", - "demoPath": "demos/pypi", - "devcontainerPath": ".devcontainer/pypi/devcontainer.json" - }, - { - "ecosystem": "go", - "label": "Go", - "status": "not-yet-validated", - "demoPath": "demos/go", - "devcontainerPath": ".devcontainer/go/devcontainer.json" - }, - { - "ecosystem": "cargo", - "label": "Rust", - "status": "not-yet-validated", - "demoPath": "demos/cargo", - "devcontainerPath": ".devcontainer/cargo/devcontainer.json" - }, - { - "ecosystem": "maven", - "label": "Java / Kotlin / Scala", - "status": "not-yet-validated", - "demoPath": "demos/maven", - "devcontainerPath": ".devcontainer/maven/devcontainer.json" - }, - { - "ecosystem": "rubygems", - "label": "Ruby", - "status": "evidence-only", - "demoPath": "demos/rubygems", - "devcontainerPath": ".devcontainer/rubygems/devcontainer.json" - }, - { - "ecosystem": "nuget", - "label": ".NET", - "status": "not-yet-validated", - "demoPath": "demos/nuget", - "devcontainerPath": ".devcontainer/nuget/devcontainer.json" - }, - { - "ecosystem": "packagist", - "label": "PHP", - "status": "not-yet-validated", - "demoPath": "demos/packagist", - "devcontainerPath": ".devcontainer/packagist/devcontainer.json" - }, - { - "ecosystem": "hex", - "label": "Elixir / Erlang", - "status": "not-yet-validated", - "demoPath": "demos/hex", - "devcontainerPath": ".devcontainer/hex/devcontainer.json" - }, - { - "ecosystem": "pub", - "label": "Dart / Flutter", - "status": "not-yet-validated", - "demoPath": "demos/pub", - "devcontainerPath": ".devcontainer/pub/devcontainer.json" - }, - { - "ecosystem": "swift", - "label": "Swift", - "status": "not-yet-validated", - "demoPath": "demos/swift", - "devcontainerPath": ".devcontainer/swift/devcontainer.json" - }, - { - "ecosystem": "cocoapods", - "label": "CocoaPods", - "status": "not-yet-validated", - "demoPath": "demos/cocoapods", - "devcontainerPath": ".devcontainer/cocoapods/devcontainer.json" - }, - { - "ecosystem": "opam", - "label": "OCaml", - "status": "not-yet-validated", - "demoPath": "demos/opam", - "devcontainerPath": ".devcontainer/opam/devcontainer.json" - }, - { - "ecosystem": "conan", - "label": "C / C++ (Conan)", - "status": "not-yet-validated", - "demoPath": "demos/conan", - "devcontainerPath": ".devcontainer/conan/devcontainer.json" - }, - { - "ecosystem": "vcpkg", - "label": "C / C++ (vcpkg)", - "status": "not-yet-validated", - "demoPath": "demos/vcpkg", - "devcontainerPath": ".devcontainer/vcpkg/devcontainer.json" - }, - { - "ecosystem": "arduino", - "label": "Arduino / PlatformIO", - "status": "not-yet-validated", - "demoPath": "demos/arduino", - "devcontainerPath": ".devcontainer/arduino/devcontainer.json" - } - ] -} diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..03cd7ae --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,22 @@ +name: check + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Check demos + run: node scripts/check-demos.mjs diff --git a/.github/workflows/verify-demos.yml b/.github/workflows/verify-demos.yml deleted file mode 100644 index a66124a..0000000 --- a/.github/workflows/verify-demos.yml +++ /dev/null @@ -1,116 +0,0 @@ -name: verify demos - -on: - push: - branches: [main] - pull_request: - workflow_dispatch: - -permissions: - contents: read - -jobs: - # Fast, no toolchains: demos.json, fixture structure, devcontainer agreement. - structure: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 22 - - - name: Syntax-check lifecycle scripts - run: | - for f in scripts/*.mjs scripts/lib/*.mjs; do - node --check "$f" - done - - # Semantic validation activates as soon as a `drift` binary is on PATH. - # Until @usedrift/cli is published this install is expected to fail; it is - # non-fatal, resolveDriftCli() then reports the CLI unavailable, and the - # semantic pass prints SKIPPED while the structural pass still gates the PR. - # - # After publication, set the repository variable DRIFT_SEMANTIC=1 to make - # a failed install fail the job instead of being ignored. - - name: Install published Drift CLI (best effort until published) - run: npm install -g @usedrift/cli || [ "${{ vars.DRIFT_SEMANTIC }}" != "1" ] - - - name: Validate demo fixtures - run: node scripts/verify-all.mjs - - - name: Validate devcontainers against demos.json - run: | - node scripts/sync-devcontainers.mjs --check - node scripts/verify-devcontainers.mjs - - # Proves each fixture is a real break, using that ecosystem's own toolchain: - # the baseline must build/run, and the upgraded tree must fail for the stated - # reason. Structure alone cannot tell a real breaking upgrade from a - # plausible-looking one. - oracle: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - ecosystem: npm - - ecosystem: pypi - - ecosystem: go - - ecosystem: cargo - - ecosystem: maven - - ecosystem: rubygems - - ecosystem: nuget - - ecosystem: packagist - - ecosystem: hex - - ecosystem: pub - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: 22 - - - if: matrix.ecosystem == 'pypi' - uses: actions/setup-python@v5 - with: - python-version: '3.12' - - - if: matrix.ecosystem == 'go' - uses: actions/setup-go@v5 - with: - go-version: '1.22' - - - if: matrix.ecosystem == 'maven' - uses: actions/setup-java@v4 - with: - distribution: temurin - java-version: '21' - - - if: matrix.ecosystem == 'rubygems' - uses: ruby/setup-ruby@v1 - with: - ruby-version: '3.3' - - - if: matrix.ecosystem == 'nuget' - uses: actions/setup-dotnet@v4 - with: - dotnet-version: '8.0.x' - - - if: matrix.ecosystem == 'packagist' - uses: shivammathur/setup-php@v2 - with: - php-version: '8.2' - tools: composer - - - if: matrix.ecosystem == 'hex' - uses: erlef/setup-beam@v1 - with: - otp-version: '26' - elixir-version: '1.15' - - - if: matrix.ecosystem == 'pub' - uses: dart-lang/setup-dart@v1 - with: - sdk: '3.3' - - - name: Prove the ${{ matrix.ecosystem }} break is real - run: node scripts/verify-oracle.mjs ${{ matrix.ecosystem }} diff --git a/README.md b/README.md index 8f3d786..2865c57 100644 --- a/README.md +++ b/README.md @@ -1,69 +1,76 @@ # Drift demos -Browser-based example projects for Drift's **Try Drift in your browser** -experience. Each demo is a tiny, real project with a real published dependency -upgrade, analyzed by the normal [Drift](https://github.com/trydrift/drift) VS -Code extension — nothing here is demo-specific behaviour. +Example projects for Drift's **Try Drift in your browser** experience. Each one +is a tiny real project pinned to an old version of a real dependency, with +source code that uses APIs the newer version breaks. -## How it works - -Every demo is committed at the **old** dependency version, with source code -that is valid against that old version. +Open one in a Codespace and Drift is already installed, the upgrade is already +applied, and there is something real for it to find. -When a Codespace is created, a one-time setup step applies `upgrade.patch`, -which changes **only dependency metadata** (manifest, lockfile) to the **new** -version. The application source is left untouched. +## How it works -The result — new dependency, old source, uncommitted — is exactly the -situation a developer is in mid-upgrade, and it is what Drift is built to -analyze. Drift already gives priority to uncommitted manifest changes, so no -special Git history is created for it. +Each demo is committed at the **old** dependency version, with source code that +was correct for it. Codespace creation edits the manifest to the **new** version +and leaves the source alone: ``` -committed: dependency@OLD + source valid against OLD -after setup: dependency@NEW + source still calling OLD ← Drift analyzes this +committed: dependency@OLD + source written for OLD +after setup: dependency@NEW + source written for OLD ← Drift analyses this ``` -## Available demos +`git status` in a fresh Codespace shows only the manifest as modified. Every +breaking usage in the source is marked with a `BREAKING` comment explaining what +changed and why it no longer works. + +## The demos + +| Ecosystem | Language | Dependency | Upgrade | +| --- | --- | --- | --- | +| `npm` | JavaScript / TypeScript | `axios` | 0.21.4 → 1.7.7 | +| `pypi` | Python | `werkzeug` | 2.0.3 → 2.1.0 | +| `go` | Go | `golang.org/x/exp` | 2023-05 → 2023-10 | +| `cargo` | Rust | `clap` | 2.34.0 → 4.5.4 | +| `maven` | Java / Kotlin / Scala | `com.google.guava:guava` | 20.0 → 21.0 | +| `rubygems` | Ruby | `rack` | 3.0.0 → 3.1.0 | +| `nuget` | .NET | `AutoMapper` | 8.1.1 → 9.0.0 | +| `packagist` | PHP | `monolog/monolog` | 2.9.3 → 3.5.0 | +| `hex` | Elixir / Erlang | `plug` | 1.13.6 → 1.15.0 | +| `pub` | Dart / Flutter | `dio` | 4.0.6 → 5.0.0 | +| `swift` | Swift | `Alamofire` | 4.9.1 → 5.9.1 | +| `cocoapods` | CocoaPods | `Alamofire` | 4.9.1 → 5.9.1 | +| `opam` | OCaml | `lwt` | 4.5.0 → 5.7.0 | +| `conan` | C / C++ (Conan) | `fmt` | 9.1.0 → 10.2.1 | +| `vcpkg` | C / C++ (vcpkg) | `spdlog` | 1.11.0 → 1.14.1 | +| `arduino` | Arduino / PlatformIO | `ArduinoJson` | 5.13.5 → 6.21.3 | + +## Launching one -The demo set and its validation status live in -[`.drift-demo/demos.json`](.drift-demo/demos.json). A demo is only linked from -the Drift website once it is validated end to end in a real Codespace. +``` +https://codespaces.new/trydrift/demo?quickstart=1&devcontainer_path=.devcontainer%2F%2Fdevcontainer.json +``` -| Ecosystem | Language | Status | -| --- | --- | --- | -| `npm` | JavaScript / TypeScript | not yet validated | -| `pypi` | Python | not yet validated | -| `go` | Go | not yet validated | -| `cargo` | Rust | not yet validated | -| `maven` | Java / Kotlin / Scala | not yet validated | +Requires a GitHub account, and runs on your own GitHub Codespaces allowance. -## Fixture contract +## Layout ``` demos// -├── DEMO.md # ~12-line human guide -├── # pinned to the OLD version -├── # one file, one affected API call -└── .drift-demo/ - ├── upgrade.patch # OLD → NEW, dependency metadata only - └── expected.json # semantic expectation for CI +├── DEMO.md generated from the BREAKING comments in the source +├── demo.json dependency, versions, and the manifest edit +├── pinned to the old version +└── uses APIs the new version breaks ``` ## Scripts ``` -node scripts/prepare-demo.mjs # apply the upgrade into the working tree -node scripts/reset-demo.mjs # restore the committed baseline -node scripts/verify-demo.mjs # validate one fixture -node scripts/verify-structure.mjs # validate demos.json + every present fixture +node scripts/prepare-demo.mjs # apply the upgrade (what the Codespace runs) +node scripts/reset-demo.mjs # put the manifest back +node scripts/sync-devcontainers.mjs # regenerate .devcontainer/* +node scripts/make-demo-docs.mjs # regenerate DEMO.md files +node scripts/check-demos.mjs # sanity check, no toolchains needed ``` -The scripts have no dependencies and never run a repository-wide reset. - ## Drift -Production repository: https://github.com/trydrift/drift - -Running a demo requires a GitHub account and uses your own GitHub Codespaces -allowance. +https://github.com/trydrift/drift diff --git a/demos/arduino/DEMO.md b/demos/arduino/DEMO.md new file mode 100644 index 0000000..d5dcacf --- /dev/null +++ b/demos/arduino/DEMO.md @@ -0,0 +1,27 @@ +# Try Drift — Arduino / PlatformIO + +This project depends on `bblanchon/ArduinoJson` **5.13.5**. + +The Codespace upgraded it to **6.21.3** and left the source code alone, so +`src/main.cpp` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +5 breaking changes in this demo: + +1. StaticJsonBuffer was removed in ArduinoJson 6, replaced by StaticJsonDocument. The buffer/document split is gone entirely. +2. JsonObject was a reference type created from the buffer in v5 (`JsonObject& root = jsonBuffer.createObject()`). In v6 it is a value type obtained from a document with `doc.to()`. +3. printTo() was removed in ArduinoJson 6 in favour of the free function serializeJson(doc, output). +4. parseObject() was removed in v6; parsing goes through deserializeJson(doc, input), which returns a DeserializationError. +5. JsonObject::success() was removed in v6 — you check the DeserializationError that deserializeJson returns instead. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `bblanchon/ArduinoJson`. +3. Open `src/main.cpp` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs arduino`. diff --git a/demos/arduino/demo.json b/demos/arduino/demo.json new file mode 100644 index 0000000..ff851f5 --- /dev/null +++ b/demos/arduino/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "bblanchon/ArduinoJson", + "from": "5.13.5", + "to": "6.21.3", + "edits": [ + { "file": "platformio.ini", "find": "bblanchon/ArduinoJson@5.13.5", "replace": "bblanchon/ArduinoJson@6.21.3" } + ], + "open": ["src/main.cpp", "platformio.ini"] +} diff --git a/demos/arduino/platformio.ini b/demos/arduino/platformio.ini new file mode 100644 index 0000000..9dad111 --- /dev/null +++ b/demos/arduino/platformio.ini @@ -0,0 +1,6 @@ +[env:uno] +platform = atmelavr +board = uno +framework = arduino +lib_deps = + bblanchon/ArduinoJson@5.13.5 diff --git a/demos/arduino/src/main.cpp b/demos/arduino/src/main.cpp new file mode 100644 index 0000000..c52495f --- /dev/null +++ b/demos/arduino/src/main.cpp @@ -0,0 +1,54 @@ +#include +#include + +// This sketch is written against ArduinoJson 5.13. +// The Codespace upgraded the library to ArduinoJson 6.21 without touching this +// code. ArduinoJson 6 replaced the whole document model, so every marked line +// below refers to something that no longer exists. + +// ── BREAKING 1 ────────────────────────────────────────────────────────── +// StaticJsonBuffer was removed in ArduinoJson 6, replaced by +// StaticJsonDocument. The buffer/document split is gone entirely. +StaticJsonBuffer<256> jsonBuffer; + +void publishReading(float celsius) { + // ── BREAKING 2 ────────────────────────────────────────────────────── + // JsonObject was a reference type created from the buffer in v5 + // (`JsonObject& root = jsonBuffer.createObject()`). In v6 it is a value + // type obtained from a document with `doc.to()`. + JsonObject& root = jsonBuffer.createObject(); + root["celsius"] = celsius; + root["unit"] = "C"; + + // ── BREAKING 3 ────────────────────────────────────────────────────── + // printTo() was removed in ArduinoJson 6 in favour of the free function + // serializeJson(doc, output). + root.printTo(Serial); + Serial.println(); +} + +void readCommand(const char* payload) { + // ── BREAKING 4 ────────────────────────────────────────────────────── + // parseObject() was removed in v6; parsing goes through + // deserializeJson(doc, input), which returns a DeserializationError. + JsonObject& command = jsonBuffer.parseObject(payload); + + // ── BREAKING 5 ────────────────────────────────────────────────────── + // JsonObject::success() was removed in v6 — you check the + // DeserializationError that deserializeJson returns instead. + if (!command.success()) { + Serial.println("bad payload"); + return; + } + + Serial.println(command["action"].as()); +} + +void setup() { + Serial.begin(9600); +} + +void loop() { + publishReading(21.5); + delay(1000); +} diff --git a/demos/cargo/.drift-demo/expected.json b/demos/cargo/.drift-demo/expected.json deleted file mode 100644 index bf2fe85..0000000 --- a/demos/cargo/.drift-demo/expected.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "cargo", - "dependency": "clap", - "fromVersion": "2.34.0", - "toVersion": "4.5.4", - "dependencyFiles": [ - "Cargo.toml", - "Cargo.lock" - ], - "expectedAffectedFiles": [ - "src/main.rs" - ], - "expectedSymbols": [ - "App" - ], - "expectedChangeKinds": [ - "removed-export" - ], - "expectsAffectedCallSite": false, - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "E0432|no `App` in the root" - }, - "generatedFiles": [ - "target" - ] -} diff --git a/demos/cargo/.drift-demo/oracle.sh b/demos/cargo/.drift-demo/oracle.sh deleted file mode 100755 index 451c2b0..0000000 --- a/demos/cargo/.drift-demo/oracle.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Rust fixture. -# -# Against the committed baseline `cargo check` succeeds. Against the upgraded -# tree it must fail with E0433: clap 4 renamed `App` to `Command` and removed -# the `App` name that src/main.rs imports. -set -euo pipefail -cargo check --quiet -echo "oracle: cargo check OK" diff --git a/demos/cargo/.drift-demo/upgrade.patch b/demos/cargo/.drift-demo/upgrade.patch deleted file mode 100644 index 1b36aa0..0000000 --- a/demos/cargo/.drift-demo/upgrade.patch +++ /dev/null @@ -1,205 +0,0 @@ -diff --git a/Cargo.lock b/Cargo.lock -index ecbee19..6badff5 100644 ---- a/Cargo.lock -+++ b/Cargo.lock -@@ -3,113 +3,130 @@ - version = 4 - - [[package]] --name = "ansi_term" --version = "0.12.1" -+name = "anstream" -+version = "0.6.21" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" -+checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" - dependencies = [ -- "winapi", -+ "anstyle", -+ "anstyle-parse", -+ "anstyle-query", -+ "anstyle-wincon", -+ "colorchoice", -+ "is_terminal_polyfill", -+ "utf8parse", - ] - - [[package]] --name = "atty" --version = "0.2.14" -+name = "anstyle" -+version = "1.0.14" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" -+ -+[[package]] -+name = "anstyle-parse" -+version = "0.2.7" -+source = "registry+https://github.com/rust-lang/crates.io-index" -+checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" - dependencies = [ -- "hermit-abi", -- "libc", -- "winapi", -+ "utf8parse", - ] - - [[package]] --name = "bitflags" --version = "1.3.2" -+name = "anstyle-query" -+version = "1.1.5" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" -+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -+dependencies = [ -+ "windows-sys", -+] - - [[package]] --name = "clap" --version = "2.34.0" -+name = "anstyle-wincon" -+version = "3.0.11" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" -+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" - dependencies = [ -- "ansi_term", -- "atty", -- "bitflags", -- "strsim", -- "textwrap", -- "unicode-width", -- "vec_map", -+ "anstyle", -+ "once_cell_polyfill", -+ "windows-sys", - ] - - [[package]] --name = "drift-demo-cargo" --version = "0.1.0" -+name = "clap" -+version = "4.5.4" -+source = "registry+https://github.com/rust-lang/crates.io-index" -+checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" - dependencies = [ -- "clap", -+ "clap_builder", - ] - - [[package]] --name = "hermit-abi" --version = "0.1.19" -+name = "clap_builder" -+version = "4.5.2" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -+checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" - dependencies = [ -- "libc", -+ "anstream", -+ "anstyle", -+ "clap_lex", -+ "strsim", - ] - - [[package]] --name = "libc" --version = "0.2.189" -+name = "clap_lex" -+version = "0.7.7" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" -+checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32" - - [[package]] --name = "strsim" --version = "0.8.0" -+name = "colorchoice" -+version = "1.0.5" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" -+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - - [[package]] --name = "textwrap" --version = "0.11.0" --source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -+name = "drift-demo-cargo" -+version = "0.1.0" - dependencies = [ -- "unicode-width", -+ "clap", - ] - - [[package]] --name = "unicode-width" --version = "0.1.14" -+name = "is_terminal_polyfill" -+version = "1.70.2" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" -+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - - [[package]] --name = "vec_map" --version = "0.8.2" -+name = "once_cell_polyfill" -+version = "1.70.2" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" -+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - - [[package]] --name = "winapi" --version = "0.3.9" -+name = "strsim" -+version = "0.11.1" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" --dependencies = [ -- "winapi-i686-pc-windows-gnu", -- "winapi-x86_64-pc-windows-gnu", --] -+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -+ -+[[package]] -+name = "utf8parse" -+version = "0.2.2" -+source = "registry+https://github.com/rust-lang/crates.io-index" -+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - - [[package]] --name = "winapi-i686-pc-windows-gnu" --version = "0.4.0" -+name = "windows-link" -+version = "0.2.1" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" -+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - - [[package]] --name = "winapi-x86_64-pc-windows-gnu" --version = "0.4.0" -+name = "windows-sys" -+version = "0.61.2" - source = "registry+https://github.com/rust-lang/crates.io-index" --checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -+dependencies = [ -+ "windows-link", -+] -diff --git a/Cargo.toml b/Cargo.toml -index ecbbd2b..c93da31 100644 ---- a/Cargo.toml -+++ b/Cargo.toml -@@ -5,4 +5,4 @@ edition = "2021" - publish = false - - [dependencies] --clap = "=2.34.0" -+clap = "=4.5.4" diff --git a/demos/cargo/Cargo.lock b/demos/cargo/Cargo.lock deleted file mode 100644 index ecbee19..0000000 --- a/demos/cargo/Cargo.lock +++ /dev/null @@ -1,115 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "ansi_term" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" -dependencies = [ - "winapi", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "clap" -version = "2.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" -dependencies = [ - "ansi_term", - "atty", - "bitflags", - "strsim", - "textwrap", - "unicode-width", - "vec_map", -] - -[[package]] -name = "drift-demo-cargo" -version = "0.1.0" -dependencies = [ - "clap", -] - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "libc" -version = "0.2.189" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" - -[[package]] -name = "strsim" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" - -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "vec_map" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/demos/cargo/DEMO.md b/demos/cargo/DEMO.md index 891ee20..0f48a49 100644 --- a/demos/cargo/DEMO.md +++ b/demos/cargo/DEMO.md @@ -1,22 +1,27 @@ # Try Drift — Rust -This project uses `clap` **2.34.0**. `src/main.rs` builds its CLI with -`clap::App`, the v2 builder entry point. +This project depends on `clap` **2.34.0**. -The Codespace upgraded `clap` to **4.5.4**, which renamed `App` to `Command` -and removed the `App` name entirely. The code no longer compiles: +The Codespace upgraded it to **4.5.4** and left the source code alone, so +`src/main.rs` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -error[E0432]: unresolved import `clap::App` — no `App` in the root -``` +5 breaking changes in this demo: -The source code was not changed, so it still refers to `clap::App`. +1. `clap::App` was renamed to `clap::Command` in clap 3 and the old name was removed in clap 4. This import no longer resolves. +2. `clap::SubCommand` was removed in clap 3 — subcommands are just `Command` values now, built with `Command::new(..)`. +3. `Arg::with_name` was renamed to `Arg::new` in clap 3; the old name is gone in clap 4. +4. `Arg::takes_value` was removed in clap 4 in favour of `Arg::action(ArgAction::Set)` / `num_args`. +5. `ArgMatches::value_of` was replaced by `get_one::(..)` in clap 4 and removed. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `clap` — `clap::App` was removed. -3. Open `src/main.rs`, where `App` is used. +2. Look at what Drift found for `clap`. +3. Open `src/main.rs` and compare against the marked lines. -Expected affected file: `src/main.rs`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -This uses real published `clap` versions and the normal Drift VS Code -extension. +Reset it with `node scripts/reset-demo.mjs cargo`. diff --git a/demos/cargo/demo.json b/demos/cargo/demo.json new file mode 100644 index 0000000..3ce2f1b --- /dev/null +++ b/demos/cargo/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "clap", + "from": "2.34.0", + "to": "4.5.4", + "edits": [ + { "file": "Cargo.toml", "find": "clap = \"=2.34.0\"", "replace": "clap = \"=4.5.4\"" } + ], + "open": ["src/main.rs", "Cargo.toml"] +} diff --git a/demos/cargo/src/main.rs b/demos/cargo/src/main.rs index b7960ed..0133055 100644 --- a/demos/cargo/src/main.rs +++ b/demos/cargo/src/main.rs @@ -1,14 +1,46 @@ -use clap::App; +// This file is written against clap 2.34. +// The Codespace upgraded the dependency to clap 4.5 without touching this +// code. clap 3 and 4 rewrote the builder API, so every marked item below is +// gone or renamed. -/// Build the command-line interface and parse the current process arguments. -fn parse_args() { - // clap 2.x exposes the builder entry point as `clap::App`. - let _matches = App::new("drift-demo") +// ── BREAKING 1 ──────────────────────────────────────────────────────────── +// `clap::App` was renamed to `clap::Command` in clap 3 and the old name was +// removed in clap 4. This import no longer resolves. +use clap::{App, Arg, ArgMatches, SubCommand}; + +// ── BREAKING 2 ──────────────────────────────────────────────────────────── +// `clap::SubCommand` was removed in clap 3 — subcommands are just `Command` +// values now, built with `Command::new(..)`. + +/// Build the command-line interface. +fn cli() -> App<'static, 'static> { + App::new("drift-demo") .version("0.1.0") .about("Tiny CLI used by the Drift Rust demo") - .get_matches(); + // ── BREAKING 3 ──────────────────────────────────────────────────── + // `Arg::with_name` was renamed to `Arg::new` in clap 3; the old name + // is gone in clap 4. + .arg( + Arg::with_name("config") + .long("config") + // ── BREAKING 4 ──────────────────────────────────────────── + // `Arg::takes_value` was removed in clap 4 in favour of + // `Arg::action(ArgAction::Set)` / `num_args`. + .takes_value(true) + .help("Path to the config file"), + ) + .subcommand(SubCommand::with_name("build").about("Build the project")) +} + +/// Read the `--config` value out of the parsed arguments. +fn config_path(matches: &ArgMatches) -> Option { + // ── BREAKING 5 ──────────────────────────────────────────────────────── + // `ArgMatches::value_of` was replaced by `get_one::(..)` in + // clap 4 and removed. + matches.value_of("config").map(|s| s.to_string()) } fn main() { - parse_args(); + let matches = cli().get_matches(); + println!("config: {:?}", config_path(&matches)); } diff --git a/demos/cocoapods/DEMO.md b/demos/cocoapods/DEMO.md new file mode 100644 index 0000000..98fd5c8 --- /dev/null +++ b/demos/cocoapods/DEMO.md @@ -0,0 +1,27 @@ +# Try Drift — CocoaPods + +This project depends on `Alamofire` **4.9.1**. + +The Codespace upgraded it to **5.9.1** and left the source code alone, so +`DriftDemo/NetworkService.swift` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +5 breaking changes in this demo: + +1. SessionManager was removed in Alamofire 5, replaced by Session/AF. +2. Alamofire 5 removed the SessionDelegate hooks that were assigned like this; retry and adapt are handled by a RequestInterceptor now. +3. The top-level Alamofire.request(..) was removed in Alamofire 5. +4. responseJSON was removed in Alamofire 5.5; use responseDecodable(of:) instead. +5. DataResponse.result was a Result enum with `.value` in Alamofire 4. In Alamofire 5 it is Swift's own Result, so `.value` is no longer how you read it. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `Alamofire`. +3. Open `DriftDemo/NetworkService.swift` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs cocoapods`. diff --git a/demos/cocoapods/DriftDemo/NetworkService.swift b/demos/cocoapods/DriftDemo/NetworkService.swift new file mode 100644 index 0000000..799fa06 --- /dev/null +++ b/demos/cocoapods/DriftDemo/NetworkService.swift @@ -0,0 +1,38 @@ +import Alamofire + +/// Networking layer for the iOS app. +/// +/// This file is written against Alamofire 4.9, installed through CocoaPods. +/// The Codespace upgraded the pod to Alamofire 5.9 without touching this code. +/// Alamofire 5 rewrote the public API, so every marked usage below is gone. +final class NetworkService { + + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // SessionManager was removed in Alamofire 5, replaced by Session/AF. + private let manager = SessionManager.default + + // ── BREAKING 2 ──────────────────────────────────────────────────────── + // Alamofire 5 removed the SessionDelegate hooks that were assigned like + // this; retry and adapt are handled by a RequestInterceptor now. + init() { + manager.adapter = nil + manager.retrier = nil + } + + /// Load the user's profile. + func loadProfile(completion: @escaping (Any?) -> Void) { + // ── BREAKING 3 ──────────────────────────────────────────────────── + // The top-level Alamofire.request(..) was removed in Alamofire 5. + Alamofire.request("https://example.com/me") + // ── BREAKING 4 ──────────────────────────────────────────────── + // responseJSON was removed in Alamofire 5.5; use + // responseDecodable(of:) instead. + .responseJSON { response in + // ── BREAKING 5 ──────────────────────────────────────────── + // DataResponse.result was a Result enum with `.value` in + // Alamofire 4. In Alamofire 5 it is Swift's own Result, so + // `.value` is no longer how you read it. + completion(response.result.value) + } + } +} diff --git a/demos/cocoapods/Podfile b/demos/cocoapods/Podfile new file mode 100644 index 0000000..cb42edc --- /dev/null +++ b/demos/cocoapods/Podfile @@ -0,0 +1,7 @@ +platform :ios, '13.0' + +target 'DriftDemo' do + use_frameworks! + + pod 'Alamofire', '4.9.1' +end diff --git a/demos/cocoapods/demo.json b/demos/cocoapods/demo.json new file mode 100644 index 0000000..3502238 --- /dev/null +++ b/demos/cocoapods/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "Alamofire", + "from": "4.9.1", + "to": "5.9.1", + "edits": [ + { "file": "Podfile", "find": "pod 'Alamofire', '4.9.1'", "replace": "pod 'Alamofire', '5.9.1'" } + ], + "open": ["DriftDemo/NetworkService.swift", "Podfile"] +} diff --git a/demos/conan/CMakeLists.txt b/demos/conan/CMakeLists.txt new file mode 100644 index 0000000..0a93d94 --- /dev/null +++ b/demos/conan/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.15) +project(drift_demo CXX) + +set(CMAKE_CXX_STANDARD 17) + +find_package(fmt REQUIRED) + +add_executable(drift_demo src/main.cpp) +target_link_libraries(drift_demo fmt::fmt) diff --git a/demos/conan/DEMO.md b/demos/conan/DEMO.md new file mode 100644 index 0000000..2e9c9e2 --- /dev/null +++ b/demos/conan/DEMO.md @@ -0,0 +1,25 @@ +# Try Drift — C / C++ (Conan) + +This project depends on `fmt` **9.1.0**. + +The Codespace upgraded it to **10.2.1** and left the source code alone, so +`src/main.cpp` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +3 breaking changes in this demo: + +1. fmt 10 made compile-time format-string checking the default for fmt::format. A runtime std::string as the format argument is now a compile error unless you wrap it in fmt::runtime(..). +2. fmt::join moved out of into in fmt 10, so this no longer resolves with the headers included above. +3. fmt::print(FILE*, ..) with a non-constexpr format string is affected by the same compile-time checking change as fmt::format above. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `fmt`. +3. Open `src/main.cpp` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs conan`. diff --git a/demos/conan/conanfile.txt b/demos/conan/conanfile.txt new file mode 100644 index 0000000..863bfd8 --- /dev/null +++ b/demos/conan/conanfile.txt @@ -0,0 +1,6 @@ +[requires] +fmt/9.1.0 + +[generators] +CMakeDeps +CMakeToolchain diff --git a/demos/conan/demo.json b/demos/conan/demo.json new file mode 100644 index 0000000..51b32d0 --- /dev/null +++ b/demos/conan/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "fmt", + "from": "9.1.0", + "to": "10.2.1", + "edits": [ + { "file": "conanfile.txt", "find": "fmt/9.1.0", "replace": "fmt/10.2.1" } + ], + "open": ["src/main.cpp", "conanfile.txt"] +} diff --git a/demos/conan/src/main.cpp b/demos/conan/src/main.cpp new file mode 100644 index 0000000..5bb9d9b --- /dev/null +++ b/demos/conan/src/main.cpp @@ -0,0 +1,35 @@ +#include +#include + +#include +#include + +// This file is written against fmt 9.1. +// The Codespace upgraded the dependency to fmt 10.2 without touching this +// code. fmt 10 tightened its API considerably, so every marked call below +// stopped compiling. + +std::string report(const std::string& name, int count) { + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // fmt 10 made compile-time format-string checking the default for + // fmt::format. A runtime std::string as the format argument is now a + // compile error unless you wrap it in fmt::runtime(..). + std::string pattern = "{}: {} items\n"; + return fmt::format(pattern, name, count); +} + +std::string join_names(const std::vector& names) { + // ── BREAKING 2 ──────────────────────────────────────────────────────── + // fmt::join moved out of into in fmt 10, so + // this no longer resolves with the headers included above. + return fmt::format("{}", fmt::join(names, ", ")); +} + +int main() { + // ── BREAKING 3 ──────────────────────────────────────────────────────── + // fmt::print(FILE*, ..) with a non-constexpr format string is affected by + // the same compile-time checking change as fmt::format above. + fmt::print(stdout, report("widgets", 3)); + fmt::print("{}\n", join_names({"ada", "grace"})); + return 0; +} diff --git a/demos/go/.drift-demo/expected.json b/demos/go/.drift-demo/expected.json deleted file mode 100644 index 640f201..0000000 --- a/demos/go/.drift-demo/expected.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "go", - "dependency": "golang.org/x/exp", - "fromVersion": "v0.0.0-20230522175609-2e198f4a06a1", - "toVersion": "v0.0.0-20231006140011-7918f672742d", - "dependencyFiles": [ - "go.mod", - "go.sum" - ], - "expectedAffectedFiles": [ - "main.go" - ], - "expectedSymbols": [ - "SortFunc" - ], - "expectedChangeKinds": [ - "signature-change" - ], - "expectsAffectedCallSite": true, - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "SortFunc|does not match inferred type" - }, - "generatedFiles": [ - "drift-demo-go" - ] -} diff --git a/demos/go/.drift-demo/oracle.sh b/demos/go/.drift-demo/oracle.sh deleted file mode 100755 index b88a736..0000000 --- a/demos/go/.drift-demo/oracle.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Go fixture. -# -# Against the committed baseline `go build` succeeds. Against the upgraded tree -# it must fail: golang.org/x/exp changed the slices comparators from -# `func(a, b E) bool` to `func(a, b E) int`, so the SortFunc call in main.go -# no longer type-checks. -set -euo pipefail -go build ./... -echo "oracle: go build OK" diff --git a/demos/go/.drift-demo/upgrade.patch b/demos/go/.drift-demo/upgrade.patch deleted file mode 100644 index 7e72ffc..0000000 --- a/demos/go/.drift-demo/upgrade.patch +++ /dev/null @@ -1,19 +0,0 @@ -diff --git a/go.mod b/go.mod -index a917c46..8893512 100644 ---- a/go.mod -+++ b/go.mod -@@ -2,4 +2,4 @@ module example.com/drift-demo-go - - go 1.21 - --require golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 -+require golang.org/x/exp v0.0.0-20231006140011-7918f672742d -diff --git a/go.sum b/go.sum -index 001575f..9a43984 100644 ---- a/go.sum -+++ b/go.sum -@@ -1,2 +1,2 @@ --golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc= --golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= -+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= -+golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= diff --git a/demos/go/DEMO.md b/demos/go/DEMO.md index 8bbc8da..ffdf6f8 100644 --- a/demos/go/DEMO.md +++ b/demos/go/DEMO.md @@ -1,21 +1,26 @@ # Try Drift — Go -This project depends on `golang.org/x/exp` at a mid-2023 pseudo-version. -`main.go` calls `slices.SortFunc` with a `less` comparator that returns `bool`. +This project depends on `golang.org/x/exp` **v0.0.0-20230522175609-2e198f4a06a1**. -The Codespace upgraded `golang.org/x/exp` to an October 2023 pseudo-version, -where `slices.SortFunc` (and the rest of the `slices` package) changed its -comparator from `func(a, b E) bool` to `func(a, b E) int`. The existing call -no longer compiles. +The Codespace upgraded it to **v0.0.0-20231006140011-7918f672742d** and left the source code alone, so +`main.go` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -The source code was not changed, so it still passes a `bool` comparator. +4 breaking changes in this demo: + +1. slices.SortFunc took `func(a, b E) bool` (a "less" predicate). It now takes `func(a, b E) int` (a "compare" function, like cmp.Compare). +2. Same change for the stable variant. +3. slices.BinarySearchFunc's comparator moved from `func(E, T) bool` to `func(E, T) int` as part of the same sweep. +4. slices.IsSortedFunc took a "less" predicate too. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `golang.org/x/exp`. -3. Open the affected source file. +2. Look at what Drift found for `golang.org/x/exp`. +3. Open `main.go` and compare against the marked lines. -Expected affected file: `main.go`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -`golang.org/x/exp` ships only pseudo-versions, so `.github/drift.yml` opts this -repo in to analysing patch-level moves. This uses real published module -versions and the normal Drift VS Code extension. +Reset it with `node scripts/reset-demo.mjs go`. diff --git a/demos/go/demo.json b/demos/go/demo.json new file mode 100644 index 0000000..cec7a61 --- /dev/null +++ b/demos/go/demo.json @@ -0,0 +1,13 @@ +{ + "dependency": "golang.org/x/exp", + "from": "v0.0.0-20230522175609-2e198f4a06a1", + "to": "v0.0.0-20231006140011-7918f672742d", + "edits": [ + { + "file": "go.mod", + "find": "golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1", + "replace": "golang.org/x/exp v0.0.0-20231006140011-7918f672742d" + } + ], + "open": ["main.go", "go.mod"] +} diff --git a/demos/go/go.sum b/demos/go/go.sum deleted file mode 100644 index 001575f..0000000 --- a/demos/go/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 h1:k/i9J1pBpvlfR+9QsetwPyERsqu1GIbi967PQMq3Ivc= -golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w= diff --git a/demos/go/main.go b/demos/go/main.go index 41a54cc..55d87cc 100644 --- a/demos/go/main.go +++ b/demos/go/main.go @@ -6,15 +6,48 @@ import ( "golang.org/x/exp/slices" ) -// sortAscending orders the slice in place, smallest first. -func sortAscending(nums []int) { - // On golang.org/x/exp from mid-2023, SortFunc takes a `less` comparator - // that returns bool. - slices.SortFunc(nums, func(a, b int) bool { return a < b }) +// This file is written against golang.org/x/exp as of May 2023. +// The Codespace upgraded it to the October 2023 version without touching this +// code. In between, the whole `slices` package switched its comparator +// convention from a boolean "less" function to an int-returning "compare" +// function, so every call below stopped compiling. + +type user struct { + name string + age int +} + +// ── BREAKING 1 ──────────────────────────────────────────────────────────── +// slices.SortFunc took `func(a, b E) bool` (a "less" predicate). +// It now takes `func(a, b E) int` (a "compare" function, like cmp.Compare). +func sortByAge(users []user) { + slices.SortFunc(users, func(a, b user) bool { return a.age < b.age }) +} + +// ── BREAKING 2 ──────────────────────────────────────────────────────────── +// Same change for the stable variant. +func sortByNameStable(users []user) { + slices.SortStableFunc(users, func(a, b user) bool { return a.name < b.name }) +} + +// ── BREAKING 3 ──────────────────────────────────────────────────────────── +// slices.BinarySearchFunc's comparator moved from `func(E, T) bool` to +// `func(E, T) int` as part of the same sweep. +func findByName(users []user, name string) (int, bool) { + return slices.BinarySearchFunc(users, name, func(u user, target string) bool { + return u.name < target + }) +} + +// ── BREAKING 4 ──────────────────────────────────────────────────────────── +// slices.IsSortedFunc took a "less" predicate too. +func sortedByAge(users []user) bool { + return slices.IsSortedFunc(users, func(a, b user) bool { return a.age < b.age }) } func main() { - nums := []int{3, 1, 2} - sortAscending(nums) - fmt.Println(nums) + users := []user{{"ada", 36}, {"grace", 45}, {"alan", 41}} + sortByAge(users) + sortByNameStable(users) + fmt.Println(users, sortedByAge(users)) } diff --git a/demos/hex/.drift-demo/expected.json b/demos/hex/.drift-demo/expected.json deleted file mode 100644 index b054516..0000000 --- a/demos/hex/.drift-demo/expected.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "hex", - "dependency": "plug", - "fromVersion": "1.13.6", - "toVersion": "1.15.0", - "dependencyFiles": ["mix.exs"], - "expectedAffectedFiles": ["lib/router.ex"], - "expectedSymbols": ["Plug.Adapters.Cowboy2"], - "expectedChangeKinds": ["removed-export"], - "expectsAffectedCallSite": true, - "generatedFiles": ["_build", "deps", "mix.lock"], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "Plug.Adapters.Cowboy2.*(undefined|not available)|is undefined" - } -} diff --git a/demos/hex/.drift-demo/oracle.sh b/demos/hex/.drift-demo/oracle.sh deleted file mode 100755 index f315b49..0000000 --- a/demos/hex/.drift-demo/oracle.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Elixir fixture. -# -# Against the committed baseline (plug 1.13.6) the project compiles. Against -# the upgraded tree (1.15.0) it must fail: Plug 1.15 removed the -# Plug.Adapters.Cowboy2 shim, so the call in lib/router.ex refers to a module -# that no longer exists. `--warnings-as-errors` turns that undefined-module -# warning into the compile failure it deserves to be. -set -euo pipefail -mix local.hex --force --if-missing >/dev/null 2>&1 || mix local.hex --force >/dev/null -mix deps.get >/dev/null -mix compile --warnings-as-errors -echo "oracle: mix compile OK" diff --git a/demos/hex/.drift-demo/upgrade.patch b/demos/hex/.drift-demo/upgrade.patch deleted file mode 100644 index 04043d8..0000000 --- a/demos/hex/.drift-demo/upgrade.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/mix.exs b/mix.exs -index c5f5889..7fbb41e 100644 ---- a/mix.exs -+++ b/mix.exs -@@ -14,7 +14,7 @@ defmodule DriftDemo.MixProject do - - defp deps do - [ -- {:plug, "1.13.6"} -+ {:plug, "1.15.0"} - ] - end - end diff --git a/demos/hex/DEMO.md b/demos/hex/DEMO.md index 5d3bf7e..277eb24 100644 --- a/demos/hex/DEMO.md +++ b/demos/hex/DEMO.md @@ -1,24 +1,25 @@ # Try Drift — Elixir / Erlang -This project uses `plug` **1.13.6**. `lib/router.ex` builds its listener with -`Plug.Adapters.Cowboy2.child_spec/1`. +This project depends on `plug` **1.13.6**. -The Codespace upgraded `plug` to **1.15.0**, which removed the -`Plug.Adapters.Cowboy2` shim — it had been deprecated in favour of the separate -`Plug.Cowboy` package. The module no longer exists: +The Codespace upgraded it to **1.15.0** and left the source code alone, so +`lib/server.ex` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -Plug.Adapters.Cowboy2.child_spec/1 is undefined (module Plug.Adapters.Cowboy2 -is not available) -``` +3 breaking changes in this demo: -The source code was not changed, so it still calls the removed module. +1. Plug.Adapters.Cowboy2 was removed in Plug 1.15. It had been a deprecated shim for the separate :plug_cowboy package since Plug 1.7. +2. Plug.Adapters.Test.Conn was removed in the same sweep; the test helper is Plug.Test now. +3. Plug.Parsers.JSON was removed — JSON parsing goes through Plug.Parsers with a :json_decoder option. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `plug`. -3. Open the affected source file. +2. Look at what Drift found for `plug`. +3. Open `lib/server.ex` and compare against the marked lines. -Expected affected file: `lib/router.ex`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -Drift compares the public modules and functions, by name and arity, in both -versions' published sources. +Reset it with `node scripts/reset-demo.mjs hex`. diff --git a/demos/hex/demo.json b/demos/hex/demo.json new file mode 100644 index 0000000..acf74e5 --- /dev/null +++ b/demos/hex/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "plug", + "from": "1.13.6", + "to": "1.15.0", + "edits": [ + { "file": "mix.exs", "find": "{:plug, \"1.13.6\"}", "replace": "{:plug, \"1.15.0\"}" } + ], + "open": ["lib/server.ex", "mix.exs"] +} diff --git a/demos/hex/lib/router.ex b/demos/hex/lib/router.ex deleted file mode 100644 index 9db6f13..0000000 --- a/demos/hex/lib/router.ex +++ /dev/null @@ -1,9 +0,0 @@ -defmodule DriftDemo.Router do - @moduledoc "Starts the HTTP listener for this application." - - @doc "Child spec for the web server, for use in a supervision tree." - def child_spec(port) do - # Plug 1.13 still ships the Plug.Adapters.Cowboy2 shim. - Plug.Adapters.Cowboy2.child_spec(scheme: :http, plug: __MODULE__, options: [port: port]) - end -end diff --git a/demos/hex/lib/server.ex b/demos/hex/lib/server.ex new file mode 100644 index 0000000..e09736e --- /dev/null +++ b/demos/hex/lib/server.ex @@ -0,0 +1,30 @@ +defmodule DriftDemo.Server do + @moduledoc """ + HTTP entry point. + + This module is written against Plug 1.13. The Codespace upgraded the + dependency to Plug 1.15 without touching this code, so every marked call + below refers to something that no longer exists. + """ + + # ── BREAKING 1 ────────────────────────────────────────────────────────── + # Plug.Adapters.Cowboy2 was removed in Plug 1.15. It had been a deprecated + # shim for the separate :plug_cowboy package since Plug 1.7. + def child_spec(port) do + Plug.Adapters.Cowboy2.child_spec(scheme: :http, plug: __MODULE__, options: [port: port]) + end + + # ── BREAKING 2 ────────────────────────────────────────────────────────── + # Plug.Adapters.Test.Conn was removed in the same sweep; the test helper is + # Plug.Test now. + def test_conn(method, path) do + Plug.Adapters.Test.Conn.conn(%Plug.Conn{}, method, path, nil) + end + + # ── BREAKING 3 ────────────────────────────────────────────────────────── + # Plug.Parsers.JSON was removed — JSON parsing goes through + # Plug.Parsers with a :json_decoder option. + def parser_opts do + [parsers: [Plug.Parsers.JSON], pass: ["application/json"]] + end +end diff --git a/demos/maven/.drift-demo/expected.json b/demos/maven/.drift-demo/expected.json deleted file mode 100644 index c0b2107..0000000 --- a/demos/maven/.drift-demo/expected.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "maven", - "dependency": "com.google.guava:guava", - "fromVersion": "20.0", - "toVersion": "21.0", - "dependencyFiles": [ - "pom.xml" - ], - "expectedAffectedFiles": [ - "src/main/java/com/example/demo/Config.java" - ], - "expectedSymbols": [ - "firstNonNull" - ], - "expectedChangeKinds": [ - "removed-export" - ], - "expectsAffectedCallSite": true, - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "cannot find symbol|firstNonNull" - }, - "generatedFiles": [ - "target" - ] -} diff --git a/demos/maven/.drift-demo/oracle.sh b/demos/maven/.drift-demo/oracle.sh deleted file mode 100755 index fd7e640..0000000 --- a/demos/maven/.drift-demo/oracle.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Maven fixture. -# -# Against the committed baseline `mvn compile` succeeds. Against the upgraded -# tree it must fail: Guava 21 removed Objects.firstNonNull, which Config.java -# calls, so javac reports "cannot find symbol". -set -euo pipefail -mvn -B -q compile -echo "oracle: mvn compile OK" diff --git a/demos/maven/.drift-demo/upgrade.patch b/demos/maven/.drift-demo/upgrade.patch deleted file mode 100644 index 1d16426..0000000 --- a/demos/maven/.drift-demo/upgrade.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/pom.xml b/pom.xml -index e3fe0ba..9890c90 100644 ---- a/pom.xml -+++ b/pom.xml -@@ -19,7 +19,7 @@ - - com.google.guava - guava -- 20.0 -+ 21.0 - - - diff --git a/demos/maven/DEMO.md b/demos/maven/DEMO.md index 16c81a3..866ebaf 100644 --- a/demos/maven/DEMO.md +++ b/demos/maven/DEMO.md @@ -1,19 +1,26 @@ # Try Drift — Java / Kotlin / Scala -This project uses Guava **20.0**. `Config.java` calls -`com.google.common.base.Objects.firstNonNull(...)`. +This project depends on `com.google.guava:guava` **20.0**. -The Codespace upgraded Guava to **21.0**, which removed `firstNonNull` (and -`toStringHelper`) from `com.google.common.base.Objects` — they moved to -`com.google.common.base.MoreObjects`. The call no longer compiles. +The Codespace upgraded it to **21.0** and left the source code alone, so +`src/main/java/com/example/demo/Config.java` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -The source code was not changed, so it still calls `Objects.firstNonNull`. +4 breaking changes in this demo: + +1. Objects.firstNonNull was removed in Guava 21. It moved to MoreObjects.firstNonNull back in Guava 18 and the old alias is now gone. +2. Objects.toStringHelper was removed in Guava 21 for the same reason — it is MoreObjects.toStringHelper now. +3. MoreExecutors.sameThreadExecutor() was removed in Guava 21, replaced by MoreExecutors.newDirectExecutorService(). +4. The whole com.google.common.collect.MapConstraints class was removed in Guava 21 with no replacement. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `com.google.guava:guava`. -3. Open the affected source file. +2. Look at what Drift found for `com.google.guava:guava`. +3. Open `src/main/java/com/example/demo/Config.java` and compare against the marked lines. -Expected affected file: `src/main/java/com/example/demo/Config.java`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -This uses real published Guava versions and the normal Drift VS Code -extension. +Reset it with `node scripts/reset-demo.mjs maven`. diff --git a/demos/maven/demo.json b/demos/maven/demo.json new file mode 100644 index 0000000..f560f5d --- /dev/null +++ b/demos/maven/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "com.google.guava:guava", + "from": "20.0", + "to": "21.0", + "edits": [ + { "file": "pom.xml", "find": "20.0", "replace": "21.0" } + ], + "open": ["src/main/java/com/example/demo/Config.java", "pom.xml"] +} diff --git a/demos/maven/src/main/java/com/example/demo/Config.java b/demos/maven/src/main/java/com/example/demo/Config.java index 1e9f9ff..0591305 100644 --- a/demos/maven/src/main/java/com/example/demo/Config.java +++ b/demos/maven/src/main/java/com/example/demo/Config.java @@ -1,15 +1,51 @@ package com.example.demo; import com.google.common.base.Objects; +import com.google.common.collect.MapConstraints; +import com.google.common.util.concurrent.MoreExecutors; -/** Minimal configuration helper for the Drift Maven demo. */ +import java.util.concurrent.ExecutorService; +import java.util.Map; + +/** + * Configuration helpers. + * + *

This class is written against Guava 20. The Codespace upgraded the + * dependency to Guava 21 without touching this code — Guava 21 dropped a batch + * of long-deprecated APIs, so every marked call below stopped compiling. + */ public final class Config { private Config() {} - /** Return {@code configured} if set, otherwise the default host. */ + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // Objects.firstNonNull was removed in Guava 21. It moved to + // MoreObjects.firstNonNull back in Guava 18 and the old alias is now gone. public static String hostOrDefault(String configured) { - // Guava 20 exposes Objects.firstNonNull in com.google.common.base. return Objects.firstNonNull(configured, "localhost"); } + + // ── BREAKING 2 ──────────────────────────────────────────────────────── + // Objects.toStringHelper was removed in Guava 21 for the same reason — + // it is MoreObjects.toStringHelper now. + public static String describe(String host, int port) { + return Objects.toStringHelper(Config.class) + .add("host", host) + .add("port", port) + .toString(); + } + + // ── BREAKING 3 ──────────────────────────────────────────────────────── + // MoreExecutors.sameThreadExecutor() was removed in Guava 21, replaced by + // MoreExecutors.newDirectExecutorService(). + public static ExecutorService inlineExecutor() { + return MoreExecutors.sameThreadExecutor(); + } + + // ── BREAKING 4 ──────────────────────────────────────────────────────── + // The whole com.google.common.collect.MapConstraints class was removed in + // Guava 21 with no replacement. + public static Map constrained(Map map) { + return MapConstraints.constrainedMap(map, MapConstraints.notNull()); + } } diff --git a/demos/npm/.drift-demo/expected.json b/demos/npm/.drift-demo/expected.json deleted file mode 100644 index 3fafc08..0000000 --- a/demos/npm/.drift-demo/expected.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "npm", - "dependency": "axios", - "fromVersion": "0.21.4", - "toVersion": "1.7.7", - "dependencyFiles": ["package.json", "package-lock.json"], - "expectedAffectedFiles": ["src/index.ts"], - "expectedSymbols": ["AxiosTransformer"], - "expectedChangeKinds": ["removed-export"], - "expectsAffectedCallSite": true, - "generatedFiles": ["node_modules"], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "TS2614|has no exported member 'AxiosTransformer'" - } -} diff --git a/demos/npm/.drift-demo/oracle.sh b/demos/npm/.drift-demo/oracle.sh deleted file mode 100755 index c163cd7..0000000 --- a/demos/npm/.drift-demo/oracle.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the npm fixture. -# -# Against the committed baseline (axios 0.21.4) `tsc --noEmit` succeeds. -# Against the upgraded tree (1.7.7) it must fail with TS2614: axios 1 removed -# the `AxiosTransformer` type that src/index.ts imports. -# -# This is what proves the fixture is a real break rather than a plausible one. -set -euo pipefail -npm install --no-audit --no-fund --silent -npm run --silent typecheck diff --git a/demos/npm/.drift-demo/upgrade.patch b/demos/npm/.drift-demo/upgrade.patch deleted file mode 100644 index cf16f9f..0000000 --- a/demos/npm/.drift-demo/upgrade.patch +++ /dev/null @@ -1,299 +0,0 @@ -diff --git a/package-lock.json b/package-lock.json -index 6d4aa6b..5d79e6e 100644 ---- a/package-lock.json -+++ b/package-lock.json -@@ -8,19 +8,120 @@ - "name": "drift-demo-npm", - "version": "1.0.0", - "dependencies": { -- "axios": "0.21.4" -+ "axios": "1.7.7" - }, - "devDependencies": { - "typescript": "5.6.3" - } - }, -+ "node_modules/asynckit": { -+ "version": "0.4.0", -+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", -+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", -+ "license": "MIT" -+ }, - "node_modules/axios": { -- "version": "0.21.4", -- "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", -- "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", -+ "version": "1.7.7", -+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz", -+ "integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==", -+ "license": "MIT", -+ "dependencies": { -+ "follow-redirects": "^1.15.6", -+ "form-data": "^4.0.0", -+ "proxy-from-env": "^1.1.0" -+ } -+ }, -+ "node_modules/call-bind-apply-helpers": { -+ "version": "1.0.2", -+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", -+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", -+ "license": "MIT", -+ "dependencies": { -+ "es-errors": "^1.3.0", -+ "function-bind": "^1.1.2" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/combined-stream": { -+ "version": "1.0.8", -+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", -+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", -+ "license": "MIT", -+ "dependencies": { -+ "delayed-stream": "~1.0.0" -+ }, -+ "engines": { -+ "node": ">= 0.8" -+ } -+ }, -+ "node_modules/delayed-stream": { -+ "version": "1.0.0", -+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", -+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", -+ "license": "MIT", -+ "engines": { -+ "node": ">=0.4.0" -+ } -+ }, -+ "node_modules/dunder-proto": { -+ "version": "1.0.1", -+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", -+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", -+ "license": "MIT", -+ "dependencies": { -+ "call-bind-apply-helpers": "^1.0.1", -+ "es-errors": "^1.3.0", -+ "gopd": "^1.2.0" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/es-define-property": { -+ "version": "1.0.1", -+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", -+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/es-errors": { -+ "version": "1.3.0", -+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", -+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/es-object-atoms": { -+ "version": "1.1.2", -+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", -+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", -+ "license": "MIT", -+ "dependencies": { -+ "es-errors": "^1.3.0" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/es-set-tostringtag": { -+ "version": "2.1.0", -+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", -+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "license": "MIT", - "dependencies": { -- "follow-redirects": "^1.14.0" -+ "es-errors": "^1.3.0", -+ "get-intrinsic": "^1.2.6", -+ "has-tostringtag": "^1.0.2", -+ "hasown": "^2.0.2" -+ }, -+ "engines": { -+ "node": ">= 0.4" - } - }, - "node_modules/follow-redirects": { -@@ -43,6 +144,155 @@ - } - } - }, -+ "node_modules/form-data": { -+ "version": "4.0.6", -+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", -+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", -+ "license": "MIT", -+ "dependencies": { -+ "asynckit": "^0.4.0", -+ "combined-stream": "^1.0.8", -+ "es-set-tostringtag": "^2.1.0", -+ "hasown": "^2.0.4", -+ "mime-types": "^2.1.35" -+ }, -+ "engines": { -+ "node": ">= 6" -+ } -+ }, -+ "node_modules/function-bind": { -+ "version": "1.1.2", -+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", -+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", -+ "license": "MIT", -+ "funding": { -+ "url": "https://github.com/sponsors/ljharb" -+ } -+ }, -+ "node_modules/get-intrinsic": { -+ "version": "1.3.0", -+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", -+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", -+ "license": "MIT", -+ "dependencies": { -+ "call-bind-apply-helpers": "^1.0.2", -+ "es-define-property": "^1.0.1", -+ "es-errors": "^1.3.0", -+ "es-object-atoms": "^1.1.1", -+ "function-bind": "^1.1.2", -+ "get-proto": "^1.0.1", -+ "gopd": "^1.2.0", -+ "has-symbols": "^1.1.0", -+ "hasown": "^2.0.2", -+ "math-intrinsics": "^1.1.0" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ }, -+ "funding": { -+ "url": "https://github.com/sponsors/ljharb" -+ } -+ }, -+ "node_modules/get-proto": { -+ "version": "1.0.1", -+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", -+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", -+ "license": "MIT", -+ "dependencies": { -+ "dunder-proto": "^1.0.1", -+ "es-object-atoms": "^1.0.0" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/gopd": { -+ "version": "1.2.0", -+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", -+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.4" -+ }, -+ "funding": { -+ "url": "https://github.com/sponsors/ljharb" -+ } -+ }, -+ "node_modules/has-symbols": { -+ "version": "1.1.0", -+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", -+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.4" -+ }, -+ "funding": { -+ "url": "https://github.com/sponsors/ljharb" -+ } -+ }, -+ "node_modules/has-tostringtag": { -+ "version": "1.0.2", -+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", -+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", -+ "license": "MIT", -+ "dependencies": { -+ "has-symbols": "^1.0.3" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ }, -+ "funding": { -+ "url": "https://github.com/sponsors/ljharb" -+ } -+ }, -+ "node_modules/hasown": { -+ "version": "2.0.4", -+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", -+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", -+ "license": "MIT", -+ "dependencies": { -+ "function-bind": "^1.1.2" -+ }, -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/math-intrinsics": { -+ "version": "1.1.0", -+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", -+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.4" -+ } -+ }, -+ "node_modules/mime-db": { -+ "version": "1.52.0", -+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", -+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", -+ "license": "MIT", -+ "engines": { -+ "node": ">= 0.6" -+ } -+ }, -+ "node_modules/mime-types": { -+ "version": "2.1.35", -+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", -+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", -+ "license": "MIT", -+ "dependencies": { -+ "mime-db": "1.52.0" -+ }, -+ "engines": { -+ "node": ">= 0.6" -+ } -+ }, -+ "node_modules/proxy-from-env": { -+ "version": "1.1.0", -+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", -+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", -+ "license": "MIT" -+ }, - "node_modules/typescript": { - "version": "5.6.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", -diff --git a/package.json b/package.json -index 29eee73..a4e8d43 100644 ---- a/package.json -+++ b/package.json -@@ -7,7 +7,7 @@ - "typecheck": "tsc --noEmit" - }, - "dependencies": { -- "axios": "0.21.4" -+ "axios": "1.7.7" - }, - "devDependencies": { - "typescript": "5.6.3" diff --git a/demos/npm/DEMO.md b/demos/npm/DEMO.md index 80be2a7..6c20c1d 100644 --- a/demos/npm/DEMO.md +++ b/demos/npm/DEMO.md @@ -1,23 +1,25 @@ # Try Drift — JavaScript / TypeScript -This project uses `axios` **0.21.4**. `src/index.ts` imports the -`AxiosTransformer` type and uses it to annotate a response transformer. +This project depends on `axios` **0.21.4**. -The Codespace upgraded `axios` to **1.7.7**, which removed the -`AxiosTransformer` type from the package's published declarations. The import -no longer resolves: +The Codespace upgraded it to **1.7.7** and left the source code alone, so +`src/api-client.ts` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -error TS2614: Module '"axios"' has no exported member 'AxiosTransformer'. -``` +3 breaking changes in this demo: -The source code was not changed, so it still imports the old type. +1. `AxiosTransformer` was removed in axios 1.0. Response transformers are now typed as `AxiosResponseTransformer` (and request ones as `AxiosRequestTransformer`), so this import no longer resolves at all. +2. `AxiosProxyConfig` used to carry `username` / `password` directly. In axios 1.0 those moved into a nested `auth: { username, password }` object, so these two properties no longer exist on the type. +3. In axios 0.x `AxiosError` was an *interface*, so an object literal could be assigned to it. In axios 1.0 it became a *class*, and a plain object is no longer assignable — you have to construct one. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `axios`. -3. Open the affected source file. +2. Look at what Drift found for `axios`. +3. Open `src/api-client.ts` and compare against the marked lines. -Expected affected file: `src/index.ts`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -This uses real published `axios` versions and the normal Drift VS Code -extension. +Reset it with `node scripts/reset-demo.mjs npm`. diff --git a/demos/npm/demo.json b/demos/npm/demo.json new file mode 100644 index 0000000..0b32207 --- /dev/null +++ b/demos/npm/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "axios", + "from": "0.21.4", + "to": "1.7.7", + "edits": [ + { "file": "package.json", "find": "\"axios\": \"0.21.4\"", "replace": "\"axios\": \"1.7.7\"" } + ], + "open": ["src/api-client.ts", "package.json"] +} diff --git a/demos/npm/package-lock.json b/demos/npm/package-lock.json deleted file mode 100644 index 6d4aa6b..0000000 --- a/demos/npm/package-lock.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "drift-demo-npm", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "drift-demo-npm", - "version": "1.0.0", - "dependencies": { - "axios": "0.21.4" - }, - "devDependencies": { - "typescript": "5.6.3" - } - }, - "node_modules/axios": { - "version": "0.21.4", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz", - "integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==", - "license": "MIT", - "dependencies": { - "follow-redirects": "^1.14.0" - } - }, - "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/typescript": { - "version": "5.6.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", - "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - } - } -} diff --git a/demos/npm/src/api-client.ts b/demos/npm/src/api-client.ts new file mode 100644 index 0000000..9879ca6 --- /dev/null +++ b/demos/npm/src/api-client.ts @@ -0,0 +1,49 @@ +import axios, { + AxiosTransformer, + AxiosProxyConfig, + AxiosError, + AxiosRequestConfig, +} from 'axios'; + +// This file is written against axios 0.21. +// The Codespace upgraded the dependency to axios 1.7 without touching this +// code, so every marked line below is now wrong. + +// ── BREAKING 1 ──────────────────────────────────────────────────────────── +// `AxiosTransformer` was removed in axios 1.0. Response transformers are now +// typed as `AxiosResponseTransformer` (and request ones as +// `AxiosRequestTransformer`), so this import no longer resolves at all. +export const unwrapEnvelope: AxiosTransformer = (data) => data?.payload ?? data; + +// ── BREAKING 2 ──────────────────────────────────────────────────────────── +// `AxiosProxyConfig` used to carry `username` / `password` directly. In +// axios 1.0 those moved into a nested `auth: { username, password }` object, +// so these two properties no longer exist on the type. +export const proxy: AxiosProxyConfig = { + host: 'proxy.internal', + port: 8080, + username: 'svc-reports', + password: 'hunter2', +}; + +// ── BREAKING 3 ──────────────────────────────────────────────────────────── +// In axios 0.x `AxiosError` was an *interface*, so an object literal could be +// assigned to it. In axios 1.0 it became a *class*, and a plain object is no +// longer assignable — you have to construct one. +export const notFound: AxiosError = { + name: 'AxiosError', + message: 'Not Found', + isAxiosError: true, + config: {}, + toJSON: () => ({}), +}; + +export async function fetchReport(id: string): Promise { + const config: AxiosRequestConfig = { + proxy, + transformResponse: [unwrapEnvelope], + }; + + const response = await axios.get(`/reports/${id}`, config); + return response.data; +} diff --git a/demos/npm/src/index.ts b/demos/npm/src/index.ts deleted file mode 100644 index c62dbf7..0000000 --- a/demos/npm/src/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import axios, { AxiosTransformer } from 'axios'; - -// axios 0.x exports the AxiosTransformer type for response transformers. -/** Strip the wrapper envelope from a response body. */ -export const unwrapEnvelope: AxiosTransformer = (data) => data; - -/** Fetch a URL and return its unwrapped JSON body. */ -export async function fetchJson(url: string): Promise { - const res = await axios.get(url, { transformResponse: [unwrapEnvelope] }); - return res.data; -} diff --git a/demos/nuget/.drift-demo/expected.json b/demos/nuget/.drift-demo/expected.json deleted file mode 100644 index dbdcc01..0000000 --- a/demos/nuget/.drift-demo/expected.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "nuget", - "dependency": "AutoMapper", - "fromVersion": "8.1.1", - "toVersion": "9.0.0", - "dependencyFiles": [ - "DriftDemo.csproj" - ], - "expectedAffectedFiles": [ - "Program.cs" - ], - "expectedSymbols": [ - "Initialize" - ], - "expectedChangeKinds": [ - "removed-export" - ], - "expectsAffectedCallSite": true, - "generatedFiles": [ - "bin", - "obj" - ], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "CS0117|CS1061|does not contain a definition for .Initialize." - } -} diff --git a/demos/nuget/.drift-demo/oracle.sh b/demos/nuget/.drift-demo/oracle.sh deleted file mode 100755 index df68730..0000000 --- a/demos/nuget/.drift-demo/oracle.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the .NET fixture. -# -# Against the committed baseline (AutoMapper 8.1.1) `dotnet build` succeeds. -# Against the upgraded tree (9.0.0) it must fail: AutoMapper 9 removed -# the static Mapper.Initialize entry point, which Program.cs calls, so the -# compiler reports CS0117. -set -euo pipefail -dotnet build --nologo -v quiet -echo "oracle: dotnet build OK" diff --git a/demos/nuget/.drift-demo/upgrade.patch b/demos/nuget/.drift-demo/upgrade.patch deleted file mode 100644 index f779035..0000000 --- a/demos/nuget/.drift-demo/upgrade.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/DriftDemo.csproj b/DriftDemo.csproj -index cd26141..c10ace7 100644 ---- a/DriftDemo.csproj -+++ b/DriftDemo.csproj -@@ -8,7 +8,7 @@ - - - -- -+ - - - diff --git a/demos/nuget/DEMO.md b/demos/nuget/DEMO.md index daf18c0..032a599 100644 --- a/demos/nuget/DEMO.md +++ b/demos/nuget/DEMO.md @@ -1,23 +1,27 @@ # Try Drift — .NET -This project uses `AutoMapper` **8.1.1**. `Program.cs` configures its mappings -through the static `Mapper.Initialize(...)` entry point. +This project depends on `AutoMapper` **8.1.1**. -The Codespace upgraded `AutoMapper` to **9.0.0**, which removed the static -`Mapper` API entirely in favour of an injected `IMapper`. The call no longer -compiles: +The Codespace upgraded it to **9.0.0** and left the source code alone, so +`Mapping.cs` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -error CS0117: 'Mapper' does not contain a definition for 'Initialize' -``` +5 breaking changes in this demo: -The source code was not changed, so it still calls the removed API. +1. The static Mapper.Initialize was removed in AutoMapper 9. You build a MapperConfiguration and inject IMapper instead. +2. IMapperConfigurationExpression.CreateMissingTypeMaps was removed in AutoMapper 9; every mapping must be declared explicitly. +3. The AddProfiles(params Assembly[]) family of overloads was removed in AutoMapper 9, leaving AddMaps(..). +4. The static Mapper.Map entry point went with the rest of the static API. +5. Mapper.AssertConfigurationIsValid was removed too — it lives on the MapperConfiguration instance now. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `AutoMapper`. -3. Open the affected source file. +2. Look at what Drift found for `AutoMapper`. +3. Open `Mapping.cs` and compare against the marked lines. -Expected affected file: `Program.cs`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -Drift compares the public types and member signatures in both versions' -published assemblies, so the analysis itself needs no .NET SDK. +Reset it with `node scripts/reset-demo.mjs nuget`. diff --git a/demos/nuget/Mapping.cs b/demos/nuget/Mapping.cs new file mode 100644 index 0000000..0a2303f --- /dev/null +++ b/demos/nuget/Mapping.cs @@ -0,0 +1,55 @@ +using System; +using AutoMapper; + +namespace DriftDemo; + +public class UserEntity { public string Name { get; set; } = ""; } +public class UserDto { public string Name { get; set; } = ""; } + +///

+/// Object-mapping setup. +/// +/// This file is written against AutoMapper 8.1. The Codespace upgraded the +/// dependency to AutoMapper 9.0 without touching this code — AutoMapper 9 +/// deleted the entire static API in favour of an injected IMapper, so every +/// marked call below stopped compiling. +/// +public static class Mapping +{ + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // The static Mapper.Initialize was removed in AutoMapper 9. You build a + // MapperConfiguration and inject IMapper instead. + public static void Configure() + { + Mapper.Initialize(cfg => + { + cfg.CreateMap(); + + // ── BREAKING 2 ──────────────────────────────────────────────── + // IMapperConfigurationExpression.CreateMissingTypeMaps was removed + // in AutoMapper 9; every mapping must be declared explicitly. + cfg.CreateMissingTypeMaps = true; + + // ── BREAKING 3 ──────────────────────────────────────────────── + // The AddProfiles(params Assembly[]) family of overloads was + // removed in AutoMapper 9, leaving AddMaps(..). + cfg.AddProfiles(typeof(Mapping).Assembly); + }); + } + + // ── BREAKING 4 ──────────────────────────────────────────────────────── + // The static Mapper.Map entry point went with the rest of the static API. + public static UserDto ToDto(UserEntity entity) => Mapper.Map(entity); + + // ── BREAKING 5 ──────────────────────────────────────────────────────── + // Mapper.AssertConfigurationIsValid was removed too — it lives on the + // MapperConfiguration instance now. + public static void Validate() => Mapper.AssertConfigurationIsValid(); + + public static void Main() + { + Configure(); + Validate(); + Console.WriteLine(ToDto(new UserEntity { Name = "Ada" }).Name); + } +} diff --git a/demos/nuget/Program.cs b/demos/nuget/Program.cs deleted file mode 100644 index 67c94aa..0000000 --- a/demos/nuget/Program.cs +++ /dev/null @@ -1,22 +0,0 @@ -using AutoMapper; - -namespace DriftDemo; - -public class Source { public string Name { get; set; } = ""; } -public class Destination { public string Name { get; set; } = ""; } - -public static class Program -{ - /// Configure the application's object mappings. - public static void ConfigureMapping() - { - // AutoMapper 8 exposes a static Mapper.Initialize entry point. - Mapper.Initialize(cfg => cfg.CreateMap()); - } - - public static void Main() - { - ConfigureMapping(); - System.Console.WriteLine("mapper configured"); - } -} diff --git a/demos/nuget/demo.json b/demos/nuget/demo.json new file mode 100644 index 0000000..0028e52 --- /dev/null +++ b/demos/nuget/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "AutoMapper", + "from": "8.1.1", + "to": "9.0.0", + "edits": [ + { "file": "DriftDemo.csproj", "find": "Version=\"[8.1.1]\"", "replace": "Version=\"[9.0.0]\"" } + ], + "open": ["Mapping.cs", "DriftDemo.csproj"] +} diff --git a/demos/opam/DEMO.md b/demos/opam/DEMO.md new file mode 100644 index 0000000..03e4cee --- /dev/null +++ b/demos/opam/DEMO.md @@ -0,0 +1,25 @@ +# Try Drift — OCaml + +This project depends on `lwt` **4.5.0**. + +The Codespace upgraded it to **5.7.0** and left the source code alone, so +`lib/scheduler.ml` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +3 breaking changes in this demo: + +1. Lwt_sequence was removed from Lwt's public API in Lwt 5.0. It is an internal module now; consumers were told to vendor it. +2. Lwt.wrap1 (and wrap2..wrap7) were removed in Lwt 5.0. +3. Lwt.add_task_l and Lwt.add_task_r were removed in Lwt 5.0 along with the public Lwt_sequence they operated on. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `lwt`. +3. Open `lib/scheduler.ml` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs opam`. diff --git a/demos/opam/demo.json b/demos/opam/demo.json new file mode 100644 index 0000000..ef1ea19 --- /dev/null +++ b/demos/opam/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "lwt", + "from": "4.5.0", + "to": "5.7.0", + "edits": [ + { "file": "drift_demo.opam", "find": "\"lwt\" {= \"4.5.0\"}", "replace": "\"lwt\" {= \"5.7.0\"}" } + ], + "open": ["lib/scheduler.ml", "drift_demo.opam"] +} diff --git a/demos/opam/drift_demo.opam b/demos/opam/drift_demo.opam new file mode 100644 index 0000000..aa158ae --- /dev/null +++ b/demos/opam/drift_demo.opam @@ -0,0 +1,13 @@ +opam-version: "2.0" +name: "drift_demo" +version: "0.1.0" +synopsis: "Drift demo - breaking changes in Lwt 5" +maintainer: "demo@trydrift.dev" +authors: "Drift" +license: "MIT" +depends: [ + "ocaml" {>= "4.14"} + "dune" {>= "3.0"} + "lwt" {= "4.5.0"} +] +build: ["dune" "build" "-p" name] diff --git a/demos/opam/dune-project b/demos/opam/dune-project new file mode 100644 index 0000000..37f995d --- /dev/null +++ b/demos/opam/dune-project @@ -0,0 +1 @@ +(lang dune 3.0) diff --git a/demos/opam/lib/dune b/demos/opam/lib/dune new file mode 100644 index 0000000..8aa11e2 --- /dev/null +++ b/demos/opam/lib/dune @@ -0,0 +1,3 @@ +(library + (name drift_demo) + (libraries lwt)) diff --git a/demos/opam/lib/scheduler.ml b/demos/opam/lib/scheduler.ml new file mode 100644 index 0000000..56c2e2b --- /dev/null +++ b/demos/opam/lib/scheduler.ml @@ -0,0 +1,24 @@ +(* Task scheduling helpers. + + This file is written against Lwt 4.5. The Codespace upgraded the dependency + to Lwt 5.7 without touching this code. Lwt 5.0 removed a batch of APIs that + had been deprecated through the 4.x series, so every marked call below is + gone. *) + +(* ── BREAKING 1 ───────────────────────────────────────────────────────── + Lwt_sequence was removed from Lwt's public API in Lwt 5.0. It is an + internal module now; consumers were told to vendor it. *) +let pending : (unit -> unit Lwt.t) Lwt_sequence.t = Lwt_sequence.create () + +(* ── BREAKING 2 ───────────────────────────────────────────────────────── + Lwt.wrap1 (and wrap2..wrap7) were removed in Lwt 5.0. *) +let lift_read (read : string -> string) : string -> string Lwt.t = + Lwt.wrap1 read + +(* ── BREAKING 3 ───────────────────────────────────────────────────────── + Lwt.add_task_l and Lwt.add_task_r were removed in Lwt 5.0 along with the + public Lwt_sequence they operated on. *) +let enqueue () = Lwt.add_task_l pending + +let run_all () = + Lwt_sequence.fold_l (fun task acc -> Lwt.bind acc (fun () -> task ())) pending (Lwt.return_unit) diff --git a/demos/packagist/.drift-demo/expected.json b/demos/packagist/.drift-demo/expected.json deleted file mode 100644 index 4bef90f..0000000 --- a/demos/packagist/.drift-demo/expected.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "packagist", - "demoKind": "evidence-only", - "dependency": "monolog/monolog", - "fromVersion": "2.9.3", - "toVersion": "3.5.0", - "dependencyFiles": [ - "composer.json" - ], - "expectedAffectedFiles": [ - "src/MailErrorHandler.php" - ], - "expectsAffectedCallSite": false, - "expectedEvidence": { - "minBreakingNotes": 5, - "recommendationIn": [ - "safe-to-upgrade", - "upgrade-after-review", - "review-before-upgrading", - "do-not-upgrade-yet", - "needs-review" - ] - }, - "generatedFiles": [ - "vendor", - "composer.lock" - ], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "SwiftMailerHandler.*not found|Class .*SwiftMailerHandler" - } -} diff --git a/demos/packagist/.drift-demo/oracle.sh b/demos/packagist/.drift-demo/oracle.sh deleted file mode 100755 index 3ffd793..0000000 --- a/demos/packagist/.drift-demo/oracle.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the PHP fixture. -# -# Against the committed baseline (Monolog 2.9.3) autoloading MailErrorHandler -# resolves its parent class and succeeds. Against the upgraded tree (3.5.0) it -# must fail: Monolog 3 deleted src/Monolog/Handler/SwiftMailerHandler.php, so -# resolving the parent raises a fatal "Class not found" Error. -set -euo pipefail -composer update --no-interaction --no-progress --quiet -php -r ' -require "vendor/autoload.php"; -$class = new ReflectionClass(\DriftDemo\MailErrorHandler::class); -echo "oracle: handler resolves, parent = ", $class->getParentClass()->getName(), PHP_EOL; -' diff --git a/demos/packagist/.drift-demo/upgrade.patch b/demos/packagist/.drift-demo/upgrade.patch deleted file mode 100644 index 169ae34..0000000 --- a/demos/packagist/.drift-demo/upgrade.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/composer.json b/composer.json -index 0c96261..617bb05 100644 ---- a/composer.json -+++ b/composer.json -@@ -3,7 +3,7 @@ - "description": "Drift browser demo: a breaking Monolog upgrade", - "type": "project", - "require": { -- "monolog/monolog": "2.9.3" -+ "monolog/monolog": "3.5.0" - }, - "autoload": { - "psr-4": { diff --git a/demos/packagist/DEMO.md b/demos/packagist/DEMO.md index 565e1c7..58fdb6d 100644 --- a/demos/packagist/DEMO.md +++ b/demos/packagist/DEMO.md @@ -1,24 +1,26 @@ # Try Drift — PHP -This project uses `monolog/monolog` **2.9.3**. `src/MailErrorHandler.php` -subclasses `Monolog\Handler\SwiftMailerHandler` to send error records by email. +This project depends on `monolog/monolog` **2.9.3**. -The Codespace upgraded Monolog to **3.5.0**, which deleted that handler. Loading -the subclass now fails: +The Codespace upgraded it to **3.5.0** and left the source code alone, so +`src/Logging.php` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -Error: Class "Monolog\Handler\SwiftMailerHandler" not found -``` +4 breaking changes in this demo: -The source code was not changed, so it still extends the removed class. +1. Monolog\Handler\SwiftMailerHandler was deleted in Monolog 3 — SwiftMailer itself is end-of-life, and the handler went with it. +2. Handlers took an int level in Monolog 2 (Logger::WARNING === 300). In Monolog 3 they take a Monolog\Level enum case, and passing an int is a TypeError. +3. Logger::getLevels() was removed in Monolog 3; the Level enum replaces the int/name lookup tables entirely. +4. Logger::getLevelName() was removed for the same reason — a Level enum case knows its own name. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Read the migration evidence Drift gathered for the upgrade. -3. Open the affected source file. +2. Look at what Drift found for `monolog/monolog`. +3. Open `src/Logging.php` and compare against the marked lines. -Expected affected file: `src/MailErrorHandler.php`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -PHP publishes no machine-comparable API artefact, so Drift's capability -registry marks its API surface as unsupported. Drift reports the version move -and the migration notes it retrieved — but it does not know this particular -class was deleted, which is why this demo is not yet exposed on the website. +Reset it with `node scripts/reset-demo.mjs packagist`. diff --git a/demos/packagist/demo.json b/demos/packagist/demo.json new file mode 100644 index 0000000..f3ee5a7 --- /dev/null +++ b/demos/packagist/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "monolog/monolog", + "from": "2.9.3", + "to": "3.5.0", + "edits": [ + { "file": "composer.json", "find": "\"monolog/monolog\": \"2.9.3\"", "replace": "\"monolog/monolog\": \"3.5.0\"" } + ], + "open": ["src/Logging.php", "composer.json"] +} diff --git a/demos/packagist/src/Logging.php b/demos/packagist/src/Logging.php new file mode 100644 index 0000000..8e8a85f --- /dev/null +++ b/demos/packagist/src/Logging.php @@ -0,0 +1,52 @@ +pushHandler(new StreamHandler($path, Logger::WARNING)); + + return $logger; + } + + // ── BREAKING 3 ──────────────────────────────────────────────────────── + // Logger::getLevels() was removed in Monolog 3; the Level enum replaces + // the int/name lookup tables entirely. + public static function levelNames(): array + { + return array_keys(Logger::getLevels()); + } + + // ── BREAKING 4 ──────────────────────────────────────────────────────── + // Logger::getLevelName() was removed for the same reason — a Level enum + // case knows its own name. + public static function nameFor(int $level): string + { + return Logger::getLevelName($level); + } + + public static function mailHandlerClass(): string + { + return SwiftMailerHandler::class; + } +} diff --git a/demos/packagist/src/MailErrorHandler.php b/demos/packagist/src/MailErrorHandler.php deleted file mode 100644 index be0a7e3..0000000 --- a/demos/packagist/src/MailErrorHandler.php +++ /dev/null @@ -1,15 +0,0 @@ -=3.0.0 <4.0.0" - - dependencies: -- dio: 4.0.6 -+ dio: 5.0.0 diff --git a/demos/pub/DEMO.md b/demos/pub/DEMO.md index 0f4c5cd..f6bc5f0 100644 --- a/demos/pub/DEMO.md +++ b/demos/pub/DEMO.md @@ -1,23 +1,26 @@ # Try Drift — Dart / Flutter -This project uses `dio` **4.0.6**. `lib/api_client.dart` pauses the request -queue with `lock()` / `unlock()` while it refreshes an auth token. +This project depends on `dio` **4.0.6**. -The Codespace upgraded `dio` to **5.0.0**, which removed those request-queue -controls. The calls no longer analyze: +The Codespace upgraded it to **5.0.0** and left the source code alone, so +`lib/api_client.dart` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -error: The method 'lock' isn't defined for the type 'Dio' -``` +4 breaking changes in this demo: -The source code was not changed, so it still calls the removed API. +1. Dio.lock() / unlock() / clear() were removed in Dio 5. Queue control is done with QueuedInterceptor now. +2. connectTimeout / receiveTimeout took an int of milliseconds in Dio 4. In Dio 5 they take a Duration, so an int no longer type-checks. +3. DefaultHttpClientAdapter was removed in Dio 5, replaced by IOHttpClientAdapter. +4. DioError was renamed to DioException in Dio 5. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `dio`. -3. Open the affected source file. +2. Look at what Drift found for `dio`. +3. Open `lib/api_client.dart` and compare against the marked lines. -Expected affected file: `lib/api_client.dart`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -Drift compares the public declarations of both versions' published libraries, -following each `export` out of the private `lib/src` tree the way a consumer's -import does. +Reset it with `node scripts/reset-demo.mjs pub`. diff --git a/demos/pub/demo.json b/demos/pub/demo.json new file mode 100644 index 0000000..bee0c9e --- /dev/null +++ b/demos/pub/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "dio", + "from": "4.0.6", + "to": "5.0.0", + "edits": [ + { "file": "pubspec.yaml", "find": "dio: 4.0.6", "replace": "dio: 5.0.0" } + ], + "open": ["lib/api_client.dart", "pubspec.yaml"] +} diff --git a/demos/pub/lib/api_client.dart b/demos/pub/lib/api_client.dart index f5b9e6e..f23d647 100644 --- a/demos/pub/lib/api_client.dart +++ b/demos/pub/lib/api_client.dart @@ -1,18 +1,51 @@ import 'package:dio/dio.dart'; -/// Talks to the backend over HTTP. +/// HTTP client wrapper. +/// +/// This file is written against Dio 4.0. The Codespace upgraded the dependency +/// to Dio 5.0 without touching this code — Dio 5 was a large API cleanup, so +/// every marked usage below is broken. class ApiClient { final Dio _dio = Dio(); /// Hold outgoing requests while the auth token is refreshed. - /// - /// Dio 4 exposes lock()/unlock() to pause and resume the request queue. Future refreshToken(Future Function() refresh) async { + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // Dio.lock() / unlock() / clear() were removed in Dio 5. Queue control is + // done with QueuedInterceptor now. _dio.lock(); try { await refresh(); } finally { _dio.unlock(); + _dio.clear(); } } + + /// Configure timeouts. + void configureTimeouts() { + // ── BREAKING 2 ──────────────────────────────────────────────────────── + // connectTimeout / receiveTimeout took an int of milliseconds in Dio 4. + // In Dio 5 they take a Duration, so an int no longer type-checks. + _dio.options.connectTimeout = 5000; + _dio.options.receiveTimeout = 3000; + } + + /// Swap in a custom HTTP adapter. + void useCustomAdapter() { + // ── BREAKING 3 ──────────────────────────────────────────────────────── + // DefaultHttpClientAdapter was removed in Dio 5, replaced by + // IOHttpClientAdapter. + _dio.httpClientAdapter = DefaultHttpClientAdapter(); + } + + /// Describe a failure. + String describe(Object error) { + // ── BREAKING 4 ──────────────────────────────────────────────────────── + // DioError was renamed to DioException in Dio 5. + if (error is DioError) { + return 'request failed: ${error.message}'; + } + return 'unknown error'; + } } diff --git a/demos/pypi/.drift-demo/expected.json b/demos/pypi/.drift-demo/expected.json deleted file mode 100644 index 4d7468b..0000000 --- a/demos/pypi/.drift-demo/expected.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "pypi", - "dependency": "werkzeug", - "fromVersion": "2.0.3", - "toVersion": "2.1.0", - "dependencyFiles": ["requirements.txt"], - "expectedAffectedFiles": ["src/main.py"], - "expectedSymbols": ["safe_str_cmp"], - "expectedChangeKinds": ["removed-export"], - "expectsAffectedCallSite": true, - "generatedFiles": [".drift-demo/.venv", "src/__pycache__"], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "cannot import name 'safe_str_cmp'" - } -} diff --git a/demos/pypi/.drift-demo/oracle.sh b/demos/pypi/.drift-demo/oracle.sh deleted file mode 100755 index a9c4c1a..0000000 --- a/demos/pypi/.drift-demo/oracle.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Python fixture. -# -# Against the committed baseline (Werkzeug 2.0.3) importing src/main.py -# succeeds. Against the upgraded tree (2.1.0) it must fail: Werkzeug 2.1 -# removed `werkzeug.security.safe_str_cmp`, so the import raises ImportError. -# -# This is what proves the fixture is a real break rather than a plausible one. -set -euo pipefail -python3 -m venv .drift-demo/.venv -.drift-demo/.venv/bin/pip install -q -r requirements.txt -.drift-demo/.venv/bin/python -c "import src.main; print('oracle: safe_str_cmp import OK')" diff --git a/demos/pypi/.drift-demo/upgrade.patch b/demos/pypi/.drift-demo/upgrade.patch deleted file mode 100644 index e2c966c..0000000 --- a/demos/pypi/.drift-demo/upgrade.patch +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/requirements.txt b/requirements.txt -index fd65111..6644f97 100644 ---- a/requirements.txt -+++ b/requirements.txt -@@ -1 +1 @@ --werkzeug==2.0.3 -+werkzeug==2.1.0 diff --git a/demos/pypi/DEMO.md b/demos/pypi/DEMO.md index c40b583..ed9e56e 100644 --- a/demos/pypi/DEMO.md +++ b/demos/pypi/DEMO.md @@ -1,23 +1,26 @@ # Try Drift — Python -This project uses `Werkzeug` **2.0.3**. `src/main.py` imports -`werkzeug.security.safe_str_cmp` to compare two tokens in constant time. +This project depends on `werkzeug` **2.0.3**. -The Codespace upgraded `Werkzeug` to **2.1.0**, which removed `safe_str_cmp` -(it was deprecated in 2.0 in favour of `hmac.compare_digest`). The import now -fails outright: +The Codespace upgraded it to **2.1.0** and left the source code alone, so +`src/auth.py` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -ImportError: cannot import name 'safe_str_cmp' from 'werkzeug.security' -``` +4 breaking changes in this demo: -The source code was not changed, so it still imports the removed function. +1. `safe_str_cmp` was removed in Werkzeug 2.1. It was deprecated in 2.0 in favour of `hmac.compare_digest`. This import raises ImportError outright. +2. `pbkdf2_hex` and `pbkdf2_bin` were removed in Werkzeug 2.1; hashlib has `pbkdf2_hmac` built in. +3. `werkzeug.urls.Href` was removed in 2.1, along with much of the old URL helper surface. +4. The whole `werkzeug.useragents` module was removed in 2.1; `Request.user_agent` now returns a much smaller object. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `Werkzeug`. -3. Open the affected source file. +2. Look at what Drift found for `werkzeug`. +3. Open `src/auth.py` and compare against the marked lines. -Expected affected file: `src/main.py`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -This uses real published `Werkzeug` versions and the normal Drift VS Code -extension. +Reset it with `node scripts/reset-demo.mjs pypi`. diff --git a/demos/pypi/demo.json b/demos/pypi/demo.json new file mode 100644 index 0000000..11d8d53 --- /dev/null +++ b/demos/pypi/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "werkzeug", + "from": "2.0.3", + "to": "2.1.0", + "edits": [ + { "file": "requirements.txt", "find": "werkzeug==2.0.3", "replace": "werkzeug==2.1.0" } + ], + "open": ["src/auth.py", "requirements.txt"] +} diff --git a/demos/pypi/src/auth.py b/demos/pypi/src/auth.py new file mode 100644 index 0000000..0b11405 --- /dev/null +++ b/demos/pypi/src/auth.py @@ -0,0 +1,46 @@ +"""Session and credential helpers. + +This module is written against Werkzeug 2.0. The Codespace upgraded the +dependency to Werkzeug 2.1 without touching this code, so every marked usage +below is now broken. +""" + +# ── BREAKING 1 ──────────────────────────────────────────────────────────── +# `safe_str_cmp` was removed in Werkzeug 2.1. It was deprecated in 2.0 in +# favour of `hmac.compare_digest`. This import raises ImportError outright. +from werkzeug.security import safe_str_cmp + +# ── BREAKING 2 ──────────────────────────────────────────────────────────── +# `pbkdf2_hex` and `pbkdf2_bin` were removed in Werkzeug 2.1; hashlib has +# `pbkdf2_hmac` built in. +from werkzeug.security import pbkdf2_hex + +# ── BREAKING 3 ──────────────────────────────────────────────────────────── +# `werkzeug.urls.Href` was removed in 2.1, along with much of the old URL +# helper surface. +from werkzeug.urls import Href + +# ── BREAKING 4 ──────────────────────────────────────────────────────────── +# The whole `werkzeug.useragents` module was removed in 2.1; `Request.user_agent` +# now returns a much smaller object. +from werkzeug.useragents import UserAgent + + +def token_matches(submitted: str, expected: str) -> bool: + """Compare two tokens without leaking timing information.""" + return safe_str_cmp(submitted, expected) + + +def hash_password(password: str, salt: str) -> str: + """Derive a storable hash for a password.""" + return pbkdf2_hex(password, salt, iterations=150_000) + + +def api_url(base: str) -> Href: + """Build a URL helper rooted at ``base``.""" + return Href(base) + + +def browser_family(header: str) -> str: + """Return the browser name from a User-Agent header.""" + return UserAgent(header).browser or "unknown" diff --git a/demos/pypi/src/main.py b/demos/pypi/src/main.py deleted file mode 100644 index 56b07a1..0000000 --- a/demos/pypi/src/main.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Compare a submitted token against the expected one.""" - -from werkzeug.security import safe_str_cmp - - -def token_matches(submitted: str, expected: str) -> bool: - """Return True when the two tokens are equal, without leaking timing.""" - return safe_str_cmp(submitted, expected) diff --git a/demos/rubygems/.drift-demo/expected.json b/demos/rubygems/.drift-demo/expected.json deleted file mode 100644 index 808684b..0000000 --- a/demos/rubygems/.drift-demo/expected.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "schemaVersion": 1, - "ecosystem": "rubygems", - "demoKind": "evidence-only", - "dependency": "rack", - "fromVersion": "3.0.0", - "toVersion": "3.1.0", - "dependencyFiles": ["Gemfile", "Gemfile.lock"], - "expectedAffectedFiles": ["lib/static_app.rb"], - "expectsAffectedCallSite": false, - "expectedEvidence": { - "minBreakingNotes": 2, - "recommendationIn": ["do-not-upgrade-yet", "review-before-upgrading", "needs-review"] - }, - "generatedFiles": [".drift-demo/.bundle", ".bundle"], - "oracle": { - "command": "bash .drift-demo/oracle.sh", - "expectedFailurePattern": "uninitialized constant Rack::File|NameError" - } -} diff --git a/demos/rubygems/.drift-demo/oracle.sh b/demos/rubygems/.drift-demo/oracle.sh deleted file mode 100755 index 263251f..0000000 --- a/demos/rubygems/.drift-demo/oracle.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env bash -# Native oracle for the Ruby fixture. -# -# Against the committed baseline (rack 3.0.0) loading lib/static_app.rb and -# calling file_server succeeds. Against the upgraded tree (3.1.0) it must fail: -# Rack 3.1 removed the deprecated `Rack::File` alias, so the constant lookup -# raises NameError. -set -euo pipefail -bundle install --quiet --path .drift-demo/.bundle -bundle exec ruby -Ilib -e 'require "static_app"; StaticApp.file_server("."); puts "oracle: Rack::File OK"' diff --git a/demos/rubygems/.drift-demo/upgrade.patch b/demos/rubygems/.drift-demo/upgrade.patch deleted file mode 100644 index 2337981..0000000 --- a/demos/rubygems/.drift-demo/upgrade.patch +++ /dev/null @@ -1,29 +0,0 @@ -diff --git a/Gemfile b/Gemfile -index fbb1935..3191639 100644 ---- a/Gemfile -+++ b/Gemfile -@@ -1,3 +1,3 @@ - source 'https://rubygems.org' - --gem 'rack', '= 3.0.0' -+gem 'rack', '= 3.1.0' -diff --git a/Gemfile.lock b/Gemfile.lock -index c88275b..bd21108 100644 ---- a/Gemfile.lock -+++ b/Gemfile.lock -@@ -1,13 +1,13 @@ - GEM - remote: https://rubygems.org/ - specs: -- rack (3.0.0) -+ rack (3.1.0) - - PLATFORMS - ruby - - DEPENDENCIES -- rack (= 3.0.0) -+ rack (= 3.1.0) - - BUNDLED WITH - 2.5.9 diff --git a/demos/rubygems/DEMO.md b/demos/rubygems/DEMO.md index 90175a3..94cb65b 100644 --- a/demos/rubygems/DEMO.md +++ b/demos/rubygems/DEMO.md @@ -1,24 +1,25 @@ # Try Drift — Ruby -This project uses `rack` **3.0.0**. `lib/static_app.rb` builds a file server -with `Rack::File`, which 3.0 still exposes as a deprecated alias of -`Rack::Files`. +This project depends on `rack` **3.0.0**. -The Codespace upgraded `rack` to **3.1.0**, which removed the `Rack::File` -alias outright. The constant no longer resolves: +The Codespace upgraded it to **3.1.0** and left the source code alone, so +`lib/app.rb` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. -``` -NameError: uninitialized constant Rack::File -``` +3 breaking changes in this demo: -The source code was not changed, so it still refers to `Rack::File`. +1. Rack::File was removed in Rack 3.1. It had been a deprecated alias of Rack::Files since 2.1. +2. Rack::Chunked was removed in Rack 3.1 — chunked encoding is handled by the server, not by middleware, under the Rack 3 spec. +3. Rack::Auth::Digest was removed in Rack 3.1; digest auth was dropped entirely rather than being replaced. + +## Try it 1. Open the Drift icon in the Activity Bar. -2. Inspect the detected breaking change on `rack`. -3. Open the affected source file. +2. Look at what Drift found for `rack`. +3. Open `lib/app.rb` and compare against the marked lines. -Expected affected file: `lib/static_app.rb`. +```sh +git status --short # only the manifest is modified; the source is untouched +``` -Ruby publishes no static API surface for Drift to diff, so this demo rests on -release-note and changelog evidence plus the located reference — which is what -Drift's capability registry states for RubyGems. +Reset it with `node scripts/reset-demo.mjs rubygems`. diff --git a/demos/rubygems/Gemfile.lock b/demos/rubygems/Gemfile.lock deleted file mode 100644 index c88275b..0000000 --- a/demos/rubygems/Gemfile.lock +++ /dev/null @@ -1,13 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - rack (3.0.0) - -PLATFORMS - ruby - -DEPENDENCIES - rack (= 3.0.0) - -BUNDLED WITH - 2.5.9 diff --git a/demos/rubygems/demo.json b/demos/rubygems/demo.json new file mode 100644 index 0000000..50f7d79 --- /dev/null +++ b/demos/rubygems/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "rack", + "from": "3.0.0", + "to": "3.1.0", + "edits": [ + { "file": "Gemfile", "find": "gem 'rack', '= 3.0.0'", "replace": "gem 'rack', '= 3.1.0'" } + ], + "open": ["lib/app.rb", "Gemfile"] +} diff --git a/demos/rubygems/lib/app.rb b/demos/rubygems/lib/app.rb new file mode 100644 index 0000000..678d62c --- /dev/null +++ b/demos/rubygems/lib/app.rb @@ -0,0 +1,32 @@ +require 'rack' + +# This file is written against Rack 3.0. +# The Codespace upgraded the dependency to Rack 3.1 without touching this code. +# Rack 3.1 deleted a group of constants that 3.0 still carried as deprecated +# aliases, so every marked reference below now raises NameError. +module App + # ── BREAKING 1 ────────────────────────────────────────────────────────── + # Rack::File was removed in Rack 3.1. It had been a deprecated alias of + # Rack::Files since 2.1. + def self.file_server(root) + Rack::File.new(root) + end + + # ── BREAKING 2 ────────────────────────────────────────────────────────── + # Rack::Chunked was removed in Rack 3.1 — chunked encoding is handled by the + # server, not by middleware, under the Rack 3 spec. + def self.chunked(app) + Rack::Chunked.new(app) + end + + # ── BREAKING 3 ────────────────────────────────────────────────────────── + # Rack::Auth::Digest was removed in Rack 3.1; digest auth was dropped + # entirely rather than being replaced. + def self.digest_auth(app, realm) + Rack::Auth::Digest::MD5.new(app, realm) { |_user| 'secret' } + end + + def self.build(root) + chunked(file_server(root)) + end +end diff --git a/demos/rubygems/lib/static_app.rb b/demos/rubygems/lib/static_app.rb deleted file mode 100644 index 125b292..0000000 --- a/demos/rubygems/lib/static_app.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'rack' - -# Serve files from a directory using Rack's static file middleware. -module StaticApp - # Rack 3.0 still exposes Rack::File as an alias of Rack::Files. - def self.file_server(root) - Rack::File.new(root) - end -end diff --git a/demos/swift/DEMO.md b/demos/swift/DEMO.md new file mode 100644 index 0000000..015e4b9 --- /dev/null +++ b/demos/swift/DEMO.md @@ -0,0 +1,26 @@ +# Try Drift — Swift + +This project depends on `https://github.com/Alamofire/Alamofire` **4.9.1**. + +The Codespace upgraded it to **5.9.1** and left the source code alone, so +`Sources/DriftDemo/ApiClient.swift` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +4 breaking changes in this demo: + +1. SessionManager was removed in Alamofire 5 and replaced by Session, reached through the `AF` global. +2. The top-level Alamofire.request(..) function was removed in Alamofire 5; it is AF.request(..) now. +3. responseJSON was deprecated in Alamofire 5 and removed in 5.5 in favour of responseDecodable(of:). +4. SessionManager.upload moved to Session/AF, and the multipart API changed shape entirely in Alamofire 5. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `https://github.com/Alamofire/Alamofire`. +3. Open `Sources/DriftDemo/ApiClient.swift` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs swift`. diff --git a/demos/swift/Package.swift b/demos/swift/Package.swift new file mode 100644 index 0000000..5b13df9 --- /dev/null +++ b/demos/swift/Package.swift @@ -0,0 +1,16 @@ +// swift-tools-version:5.7 +import PackageDescription + +let package = Package( + name: "DriftDemo", + platforms: [.macOS(.v10_15)], + products: [ + .library(name: "DriftDemo", targets: ["DriftDemo"]) + ], + dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire", exact: "4.9.1") + ], + targets: [ + .target(name: "DriftDemo", dependencies: ["Alamofire"]) + ] +) diff --git a/demos/swift/Sources/DriftDemo/ApiClient.swift b/demos/swift/Sources/DriftDemo/ApiClient.swift new file mode 100644 index 0000000..cdbc5b9 --- /dev/null +++ b/demos/swift/Sources/DriftDemo/ApiClient.swift @@ -0,0 +1,38 @@ +import Alamofire + +/// Networking layer. +/// +/// This file is written against Alamofire 4.9. The Codespace upgraded the +/// dependency to Alamofire 5.9 without touching this code — Alamofire 5 was a +/// full rewrite of the public API, so every marked usage below is gone. +final class ApiClient { + + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // SessionManager was removed in Alamofire 5 and replaced by Session, + // reached through the `AF` global. + private let manager = SessionManager.default + + /// Fetch a report as JSON. + func fetchReport(id: String, completion: @escaping (Any?) -> Void) { + // ── BREAKING 2 ──────────────────────────────────────────────────── + // The top-level Alamofire.request(..) function was removed in + // Alamofire 5; it is AF.request(..) now. + Alamofire.request("https://example.com/reports/\(id)") + // ── BREAKING 3 ──────────────────────────────────────────────── + // responseJSON was deprecated in Alamofire 5 and removed in 5.5 in + // favour of responseDecodable(of:). + .responseJSON { response in + completion(response.result.value) + } + } + + /// Upload a file. + func upload(data: Data, to url: String) { + // ── BREAKING 4 ──────────────────────────────────────────────────── + // SessionManager.upload moved to Session/AF, and the multipart API + // changed shape entirely in Alamofire 5. + manager.upload(data, to: url).responseString { response in + print(response.result.value ?? "") + } + } +} diff --git a/demos/swift/demo.json b/demos/swift/demo.json new file mode 100644 index 0000000..6075943 --- /dev/null +++ b/demos/swift/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "https://github.com/Alamofire/Alamofire", + "from": "4.9.1", + "to": "5.9.1", + "edits": [ + { "file": "Package.swift", "find": "exact: \"4.9.1\"", "replace": "exact: \"5.9.1\"" } + ], + "open": ["Sources/DriftDemo/ApiClient.swift", "Package.swift"] +} diff --git a/demos/vcpkg/CMakeLists.txt b/demos/vcpkg/CMakeLists.txt new file mode 100644 index 0000000..6d1942d --- /dev/null +++ b/demos/vcpkg/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.15) +project(drift_demo CXX) + +set(CMAKE_CXX_STANDARD 17) + +find_package(spdlog CONFIG REQUIRED) + +add_executable(drift_demo src/main.cpp) +target_link_libraries(drift_demo PRIVATE spdlog::spdlog) diff --git a/demos/vcpkg/DEMO.md b/demos/vcpkg/DEMO.md new file mode 100644 index 0000000..88dc67d --- /dev/null +++ b/demos/vcpkg/DEMO.md @@ -0,0 +1,25 @@ +# Try Drift — C / C++ (vcpkg) + +This project depends on `spdlog` **1.11.0**. + +The Codespace upgraded it to **1.14.1** and left the source code alone, so +`src/main.cpp` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +3 breaking changes in this demo: + +1. spdlog::set_pattern is fine, but from 1.12 spdlog vendors fmt 10, whose compile-time format checking rejects a runtime std::string as a format string. This call now needs fmt::runtime(..). +2. Same cause: a non-constexpr format string passed to a logging call is a compile error under the bundled fmt 10. +3. spdlog::rotating_logger_mt's max_file_size argument became strongly typed in later 1.x releases; passing a plain signed literal here relies on a conversion that no longer applies cleanly. + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for `spdlog`. +3. Open `src/main.cpp` and compare against the marked lines. + +```sh +git status --short # only the manifest is modified; the source is untouched +``` + +Reset it with `node scripts/reset-demo.mjs vcpkg`. diff --git a/demos/vcpkg/demo.json b/demos/vcpkg/demo.json new file mode 100644 index 0000000..6ffc9f1 --- /dev/null +++ b/demos/vcpkg/demo.json @@ -0,0 +1,9 @@ +{ + "dependency": "spdlog", + "from": "1.11.0", + "to": "1.14.1", + "edits": [ + { "file": "vcpkg.json", "find": "\"version\": \"1.11.0\"", "replace": "\"version\": \"1.14.1\"" } + ], + "open": ["src/main.cpp", "vcpkg.json"] +} diff --git a/demos/vcpkg/src/main.cpp b/demos/vcpkg/src/main.cpp new file mode 100644 index 0000000..e714eff --- /dev/null +++ b/demos/vcpkg/src/main.cpp @@ -0,0 +1,39 @@ +#include +#include + +#include + +// This file is written against spdlog 1.11. +// The Codespace upgraded the dependency to spdlog 1.14 without touching this +// code. spdlog 1.12 bundled fmt 10, which turned several previously-accepted +// call shapes into compile errors, so the marked lines below broke. + +void configure() { + // ── BREAKING 1 ──────────────────────────────────────────────────────── + // spdlog::set_pattern is fine, but from 1.12 spdlog vendors fmt 10, whose + // compile-time format checking rejects a runtime std::string as a format + // string. This call now needs fmt::runtime(..). + std::string pattern = "[%Y-%m-%d %H:%M:%S] %v"; + spdlog::set_pattern(pattern); +} + +void log_progress(const std::string& stage, int percent) { + // ── BREAKING 2 ──────────────────────────────────────────────────────── + // Same cause: a non-constexpr format string passed to a logging call is a + // compile error under the bundled fmt 10. + std::string message = "{} is {}% complete"; + spdlog::info(message, stage, percent); +} + +int main() { + configure(); + + // ── BREAKING 3 ──────────────────────────────────────────────────────── + // spdlog::rotating_logger_mt's max_file_size argument became strongly + // typed in later 1.x releases; passing a plain signed literal here relies + // on a conversion that no longer applies cleanly. + auto file_logger = spdlog::rotating_logger_mt("file", "logs/app.log", -1, 3); + + log_progress("indexing", 40); + return 0; +} diff --git a/demos/vcpkg/vcpkg.json b/demos/vcpkg/vcpkg.json new file mode 100644 index 0000000..39a1a9d --- /dev/null +++ b/demos/vcpkg/vcpkg.json @@ -0,0 +1,14 @@ +{ + "name": "drift-demo", + "version": "0.1.0", + "dependencies": [ + "spdlog" + ], + "overrides": [ + { + "name": "spdlog", + "version": "1.11.0" + } + ], + "builtin-baseline": "3508985146f1b1d248c67ead13f8f54be5b4f5da" +} diff --git a/docs/ecosystem-status.md b/docs/ecosystem-status.md deleted file mode 100644 index 5e822a1..0000000 --- a/docs/ecosystem-status.md +++ /dev/null @@ -1,99 +0,0 @@ -# Ecosystem status - -Which of Drift's sixteen ecosystems have a demo, and why the rest do not yet. -`.drift-demo/demos.json` is the machine-readable version of this; this file -records the *reasons*, which a status enum cannot carry. - -A demo only ships when three things hold: - -1. **The break is real.** `scripts/verify-oracle.mjs` compiles or runs the - fixture with the ecosystem's own toolchain: the committed baseline must - succeed and the upgraded tree must fail, for the stated reason. -2. **The fixture is honest.** Committed at the old version, source valid - against it, and the patch touches only dependency metadata. -3. **Drift has something to say.** Either a localized finding (`interactive`) - or cited evidence and a recommendation (`evidence-only`). - -An ecosystem that satisfies 1 and 2 but not 3 stays `not-yet-validated`. That -is a real outcome, not a gap to paper over — see §39 of the project brief. - -## Shipped - -| Ecosystem | Dependency | Old → New | Drift result | Status | -| --- | --- | --- | --- | --- | -| `npm` | `axios` | 0.21.4 → 1.7.7 | `removed-export` `AxiosTransformer`, localized (2 sites) | interactive-grade | -| `pypi` | `Werkzeug` | 2.0.3 → 2.1.0 | `removed-export` `safe_str_cmp`, localized (2 sites) | interactive-grade | -| `go` | `golang.org/x/exp` | 2023-05 → 2023-10 | `signature-change` `slices.SortFunc`, localized | interactive-grade | -| `cargo` | `clap` | 2.34.0 → 4.5.4 | `removed-export` `clap::App`, **not** localized | interactive-grade, no call site | -| `maven` | `com.google.guava:guava` | 20.0 → 21.0 | `removed-export` `Objects.firstNonNull`, localized | interactive-grade | -| `nuget` | `AutoMapper` | 8.1.1 → 9.0.0 | `removed-export` `Mapper.Initialize`, localized | interactive-grade | -| `hex` | `plug` | 1.13.6 → 1.15.0 | `removed-export` `Plug.Adapters.Cowboy2`, localized | interactive-grade | -| `pub` | `dio` | 4.0.6 → 5.0.0 | `removed-export` `Dio.lock`/`unlock`, localized (2 sites) | interactive-grade | -| `rubygems` | `rack` | 3.0.0 → 3.1.0 | no surface diff; 10 changelog sections cited, `do-not-upgrade-yet` | **evidence-only** | -| `packagist` | `monolog/monolog` | 2.9.3 → 3.5.0 | 5 findings, 11 notes — none naming the deleted class; `safe-to-upgrade` | not-yet-validated | - -Every demo above is left `not-yet-validated` in `demos.json` until the VS Code -extension is published and a real Codespace run confirms it end to end. The -"interactive-grade" label above describes the analysis Drift produces today, not -a validated browser demo. - -## Not yet built, and why - -### `swift` - -A fixture was built and **withdrawn**, which is worth recording. - -`swift-argument-parser` 0.4.4 → 1.0.3 looked like a clean removal: diffing -`public enum` declarations showed `ArrayParsingStrategy` present in 0.4.4 and -absent in 1.0.3. The oracle disproved it — the upgraded tree still built. The -type was not removed; it changed from an `enum` to a `public struct` with the -same name and the same `.upToNextOption` member, so consumer code is unaffected. -The diff method was wrong, not the library. - -`swift-argument-parser` 1.0.3 → 1.5.0 has no public symbol removals at all. - -Separately, Drift returns nothing for either Swift pair — no findings, no -changelog sections, `safe-to-upgrade`. SwiftPM identifies packages by git URL -with no central registry, so Drift declares `surface: none` and only partial -evidence here. Both halves need solving before a Swift demo is worth shipping. - -### `cocoapods` - -Codespaces is Linux. CocoaPods' meaningful verification — building a pod against -an app target — needs Xcode, so an oracle cannot run there, and §40 is explicit -that faking macOS is not an option. Drift's registry already declares -`verify: none` and `surface: none` for CocoaPods. A demo would have to rest on -podspec metadata alone. - -### `opam` - -Drift declares `surface: none` and `convention`-based localization for OCaml, -and reads releases from the opam-repository index rather than an API. Needs the -same evidence-quality check `rubygems` got before it is worth building. - -### `conan`, `vcpkg` — blocked upstream - -**Blocked on trydrift/drift#185.** A fixture cannot currently be built for -either: `drift analyze` skips every Conan and vcpkg change before any analysis -runs. - -``` -[drift:info] Detected 1 dependency change(s) -[drift:info] - fmt: skipped — target manifest range has no exact resolved registry version -``` - -`parsePublishedVersion` returns `null` for these two ecosystems and no others — -a deliberate choice, because Conan and vcpkg let a package author its own -version scheme and a global ordering cannot be manufactured. But the same `null` -also denies *identity*, and `triage()` drops the change, so the C/C++ header -diff that `capabilities.ts` calls the strongest surface outside npm is never -reached. - -I probed this with a real fixture (`fmt/9.1.0 → fmt/10.2.1`) and removed it -again rather than commit something that cannot work. These two become -straightforward once identity and ordering are separated upstream. - -### `arduino` - -Shares the C/C++ surface diff, and unlike conan/vcpkg its versions do parse, so -it is not blocked. Not yet built. diff --git a/scripts/check-demos.mjs b/scripts/check-demos.mjs new file mode 100644 index 0000000..d0bd59a --- /dev/null +++ b/scripts/check-demos.mjs @@ -0,0 +1,65 @@ +#!/usr/bin/env node +// Light sanity check: every demo can be prepared and reset, the generated +// files are current, and nothing is missing. No toolchains, no network. +// +// node scripts/check-demos.mjs + +import { spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; + +import { REPO_ROOT, allDemos, KNOWN_ECOSYSTEMS } from './lib/demo-config.mjs'; + +const demos = allDemos(); +let failures = 0; + +const check = (ok, label) => { + process.stdout.write(` ${ok ? '✓' : '✗'} ${label}\n`); + if (!ok) failures += 1; +}; + +process.stdout.write(`${demos.length} of ${KNOWN_ECOSYSTEMS.length} ecosystems have a demo\n\n`); + +for (const demo of demos) { + process.stdout.write(`${demo.ecosystem}\n`); + + for (const f of ['DEMO.md', ...demo.open]) { + check(existsSync(join(REPO_ROOT, demo.dir, f)), `${f} exists`); + } + check( + existsSync(join(REPO_ROOT, '.devcontainer', demo.ecosystem, 'devcontainer.json')), + 'devcontainer exists', + ); + + const prepared = spawnSync('node', ['scripts/prepare-demo.mjs', demo.ecosystem], { + cwd: REPO_ROOT, + encoding: 'utf8', + }); + check(prepared.status === 0, `prepare applies the upgrade${prepared.status === 0 ? '' : `\n ${prepared.stderr.trim()}`}`); + + const dirty = spawnSync('git', ['status', '--porcelain', '--', demo.dir], { cwd: REPO_ROOT, encoding: 'utf8' }) + .stdout.split('\n') + .map((l) => l.slice(3).trim()) + .filter(Boolean); + const expected = demo.edits.map((e) => `${demo.dir}/${e.file}`).sort(); + check( + JSON.stringify(dirty.sort()) === JSON.stringify(expected), + `only the manifest changed (${dirty.join(', ') || 'nothing'})`, + ); + + spawnSync('node', ['scripts/reset-demo.mjs', demo.ecosystem], { cwd: REPO_ROOT }); + const afterReset = spawnSync('git', ['status', '--porcelain', '--', demo.dir], { + cwd: REPO_ROOT, + encoding: 'utf8', + }).stdout.trim(); + check(afterReset === '', 'reset restores the baseline'); +} + +for (const script of ['sync-devcontainers.mjs', 'make-demo-docs.mjs']) { + const r = spawnSync('node', [`scripts/${script}`, '--check'], { cwd: REPO_ROOT, encoding: 'utf8' }); + process.stdout.write(r.stdout ?? ''); + check(r.status === 0, `${script} output is up to date`); +} + +process.stdout.write(failures === 0 ? '\nAll demos OK.\n' : `\n${failures} problem(s).\n`); +process.exit(failures === 0 ? 0 : 1); diff --git a/scripts/lib/demo-config.mjs b/scripts/lib/demo-config.mjs index dcd130c..5b51c63 100644 --- a/scripts/lib/demo-config.mjs +++ b/scripts/lib/demo-config.mjs @@ -1,15 +1,14 @@ -// Shared helpers for the Drift demo lifecycle scripts. +// Shared helpers for the demo scripts. // -// This module owns three things every script needs and none of them should -// re-implement: where the repository is, what `.drift-demo/demos.json` is -// allowed to contain, and which files count as "dependency metadata" rather -// than application source. The last one is the whole point of the demo — a -// prepared fixture is valid only when the patch touched dependency files and -// left the source alone — so the classification has to match the real Drift. +// A demo is a tiny real project committed at an OLD dependency version, with +// source code that uses APIs the NEW version breaks. Codespace creation edits +// the manifest to the NEW version and leaves the source alone, which is exactly +// the state Drift is built to analyse: an uncommitted dependency change against +// code written for the old API. import { readFileSync, existsSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { dirname, join, resolve, relative, sep } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; const HERE = dirname(fileURLToPath(import.meta.url)); @@ -17,32 +16,7 @@ const HERE = dirname(fileURLToPath(import.meta.url)); /** Absolute path to the repository root (this file lives in `scripts/lib/`). */ export const REPO_ROOT = resolve(HERE, '..', '..'); -/** The demo repository's source of truth. */ -export const DEMOS_JSON_PATH = join(REPO_ROOT, '.drift-demo', 'demos.json'); - -/** The schema version this tooling understands. */ -export const SUPPORTED_SCHEMA_VERSION = 1; - -/** - * Status values a demo entry may carry. See the demo README and `demos.json` - * for what each one commits to. - * - * interactive real end-to-end Codespaces run, Drift gives the - * intended affected-code result - * evidence-only the ecosystem demonstrates a weaker Drift capability - * on purpose, and that is the honest outcome - * not-yet-validated not exposed from the Drift website - */ -export const ALLOWED_STATUS = Object.freeze(['interactive', 'evidence-only', 'not-yet-validated']); - -/** - * Ecosystem id -> human-facing label. - * - * The ids are exactly Drift's ecosystem ids. The labels are checked in CI - * against `src/detect/capabilities.ts` in `trydrift/drift`, which stays - * authoritative; this copy exists so the demo scripts do not need the Drift - * source tree checked out to run. - */ +/** Ecosystem id -> human label, matching Drift's capability registry. */ export const ECOSYSTEM_LABELS = Object.freeze({ npm: 'JavaScript / TypeScript', pypi: 'Python', @@ -62,249 +36,50 @@ export const ECOSYSTEM_LABELS = Object.freeze({ arduino: 'Arduino / PlatformIO', }); -/** Every ecosystem id Drift knows, in registry order. */ export const KNOWN_ECOSYSTEMS = Object.freeze(Object.keys(ECOSYSTEM_LABELS)); -/** - * Dependency file patterns, vendored verbatim from - * `src/detect/manifest-globs.ts` (`DEPENDENCY_FILE_GLOBS`) in `trydrift/drift`. - * - * Drift decides what a "manifest change" is from this list, and so does the - * fixture contract: a prepared demo is only valid when every dirty path - * matches one of these. Keep in sync with the upstream file; CI diffs it. - */ -export const DEPENDENCY_FILE_GLOBS = Object.freeze([ - // npm and friends - '**/package.json', - '**/package-lock.json', - '**/npm-shrinkwrap.json', - '**/yarn.lock', - '**/pnpm-lock.yaml', - '**/bun.lock', - // Python - '**/requirements*.txt', - '**/constraints*.txt', - '**/requirements*.in', - '**/constraints*.in', - '**/pyproject.toml', - '**/poetry.lock', - '**/uv.lock', - '**/Pipfile', - '**/Pipfile.lock', - '**/setup.py', - // Go - '**/go.mod', - '**/go.sum', - // Rust - '**/Cargo.toml', - '**/Cargo.lock', - // JVM - '**/pom.xml', - '**/build.gradle', - '**/build.gradle.kts', - '**/gradle/libs.versions.toml', - '**/gradle.lockfile', - '**/build.sbt', - '**/project/*.scala', - // Ruby - '**/Gemfile', - '**/Gemfile.lock', - '**/*.gemspec', - // .NET - '**/*.csproj', - '**/*.fsproj', - '**/*.vbproj', - '**/Directory.Packages.props', - '**/packages.config', - '**/packages.lock.json', - // PHP - '**/composer.json', - '**/composer.lock', - // Elixir / Erlang - '**/mix.exs', - '**/mix.lock', - '**/rebar.config', - // Dart / Flutter - '**/pubspec.yaml', - '**/pubspec.yml', - '**/pubspec.lock', - // Swift - '**/Package.swift', - '**/Package@swift-*.swift', - '**/Package.resolved', - // CocoaPods - '**/Podfile', - '**/Podfile.lock', - // OCaml - '**/dune-project', - '**/*.opam', - '**/*.opam.locked', - // C / C++ - '**/conanfile.txt', - '**/conanfile.py', - '**/conan.lock', - '**/vcpkg.json', - '**/vcpkg-configuration.json', - // Embedded - '**/library.properties', - '**/platformio.ini', -]); - -const DEPENDENCY_FILE_REGEXPS = DEPENDENCY_FILE_GLOBS.map(globToRegExp); - -function globToRegExp(glob) { - // Split on `**/` so it can be handled as "zero or more leading directories" - // without needing a placeholder character inside the string. - const body = glob - .split('**/') - .map((part) => part.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')) - .join('(?:.*/)?'); - return new RegExp(`^${body}$`); -} - -/** - * True when `relPath` is a dependency manifest / lockfile as Drift defines it. - * `relPath` is interpreted relative to a repository or demo directory; leading - * `./` and platform separators are tolerated. - */ -export function isDependencyFile(relPath) { - const normalized = String(relPath).split(sep).join('/').replace(/^\.\//, ''); - return DEPENDENCY_FILE_REGEXPS.some((re) => re.test(normalized)); -} - -/** Print `message` to stderr and exit non-zero. */ export function fail(message) { process.stderr.write(`${message}\n`); process.exit(1); } -/** - * Read and structurally validate `.drift-demo/demos.json`. Exits non-zero with - * a specific message on any problem. Returns `{ schemaVersion, demos }`. - */ -export function loadDemosConfig() { - if (!existsSync(DEMOS_JSON_PATH)) fail(`missing ${relative(REPO_ROOT, DEMOS_JSON_PATH)}`); - - let parsed; - try { - parsed = JSON.parse(readFileSync(DEMOS_JSON_PATH, 'utf8')); - } catch (error) { - return fail(`.drift-demo/demos.json is not valid JSON: ${error.message}`); - } - - if (parsed?.schemaVersion !== SUPPORTED_SCHEMA_VERSION) { - fail(`.drift-demo/demos.json: schemaVersion must be ${SUPPORTED_SCHEMA_VERSION}`); - } - if (!Array.isArray(parsed.demos)) fail('.drift-demo/demos.json: "demos" must be an array'); - - const seen = new Set(); - for (const [index, demo] of parsed.demos.entries()) { - const at = `.drift-demo/demos.json: demos[${index}]`; - for (const key of ['ecosystem', 'label', 'status', 'demoPath', 'devcontainerPath']) { - if (typeof demo?.[key] !== 'string' || demo[key].length === 0) { - fail(`${at}: "${key}" is required and must be a non-empty string`); - } - } - if (!KNOWN_ECOSYSTEMS.includes(demo.ecosystem)) { - fail(`${at}: unknown ecosystem "${demo.ecosystem}" (not a Drift ecosystem id)`); - } - if (seen.has(demo.ecosystem)) fail(`${at}: duplicate ecosystem "${demo.ecosystem}"`); - seen.add(demo.ecosystem); - - if (demo.label !== ECOSYSTEM_LABELS[demo.ecosystem]) { - fail( - `${at}: label "${demo.label}" does not match the Drift capability label ` + - `"${ECOSYSTEM_LABELS[demo.ecosystem]}" for ${demo.ecosystem}`, - ); - } - if (!ALLOWED_STATUS.includes(demo.status)) { - fail(`${at}: status "${demo.status}" is not one of ${ALLOWED_STATUS.join(', ')}`); - } - const expectedDemoPath = `demos/${demo.ecosystem}`; - if (demo.demoPath !== expectedDemoPath) { - fail(`${at}: demoPath should be "${expectedDemoPath}"`); - } - const expectedDevcontainer = `.devcontainer/${demo.ecosystem}/devcontainer.json`; - if (demo.devcontainerPath !== expectedDevcontainer) { - fail(`${at}: devcontainerPath should be "${expectedDevcontainer}"`); - } - } - - return parsed; -} - -/** Return the demo entry for `ecosystem`, or exit non-zero if it is not listed. */ -export function getDemo(ecosystem) { - const { demos } = loadDemosConfig(); - const demo = demos.find((entry) => entry.ecosystem === ecosystem); - if (!demo) { - fail( - `ecosystem "${ecosystem}" is not listed in .drift-demo/demos.json ` + - `(known: ${demos.map((d) => d.ecosystem).join(', ') || 'none'})`, - ); - } - return demo; +/** Every demo directory that exists, in registry order. */ +export function allDemos() { + return KNOWN_ECOSYSTEMS.filter((eco) => existsSync(join(REPO_ROOT, 'demos', eco, 'demo.json'))).map(readDemo); } /** - * Read the single ecosystem id from `argv`, validating it against - * `KNOWN_ECOSYSTEMS`. `scriptName` is used only for the usage message. + * Read one demo's `demos//demo.json`: + * + * dependency what moves + * from / to the versions it moves between + * edits [{ file, find, replace }] — the manifest edit that performs + * the upgrade. Deliberately a literal find/replace rather than a + * patch file: a demo upgrade is one version string, and a plain + * replacement is far easier to read and to keep working than a + * diff that goes stale the moment a line above it moves. + * open files the Codespace opens, most interesting first */ +export function readDemo(ecosystem) { + const path = join(REPO_ROOT, 'demos', ecosystem, 'demo.json'); + if (!existsSync(path)) fail(`demos/${ecosystem}/demo.json does not exist`); + const demo = JSON.parse(readFileSync(path, 'utf8')); + return { ecosystem, label: ECOSYSTEM_LABELS[ecosystem], dir: `demos/${ecosystem}`, ...demo }; +} + export function readEcosystemArg(scriptName) { const [ecosystem, ...rest] = process.argv.slice(2); if (!ecosystem || rest.length > 0) { - fail(`usage: node scripts/${scriptName} \n ecosystem is one of: ${KNOWN_ECOSYSTEMS.join(', ')}`); - } - if (!KNOWN_ECOSYSTEMS.includes(ecosystem)) { - fail(`"${ecosystem}" is not a Drift ecosystem id (expected one of: ${KNOWN_ECOSYSTEMS.join(', ')})`); + fail(`usage: node scripts/${scriptName} \n one of: ${KNOWN_ECOSYSTEMS.join(', ')}`); } + if (!KNOWN_ECOSYSTEMS.includes(ecosystem)) fail(`"${ecosystem}" is not a Drift ecosystem id`); return ecosystem; } -/** - * Run `git` with `args`. Returns trimmed stdout on success. On failure, exits - * non-zero unless `allowFailure` is set, in which case `null` is returned. - */ -export function git(args, { cwd = REPO_ROOT, allowFailure = false } = {}) { - const result = spawnSync('git', args, { cwd, encoding: 'utf8' }); - if (result.status !== 0) { - if (allowFailure) return null; - const detail = (result.stderr || result.stdout || '').trim(); - return fail(`git ${args.join(' ')} failed:\n${detail}`); - } - return result.stdout.trimEnd(); -} - -/** - * Paths (repo-relative, forward slashes) that differ from `HEAD` in the working - * tree, restricted to `pathspec` when given. Covers staged and unstaged edits - * and untracked files, which is exactly the set Drift's `chooseManifestRange` - * inspects. - */ -export function dirtyPaths(pathspec) { - const args = ['status', '--porcelain', '--untracked-files=all']; - if (pathspec) args.push('--', pathspec); - const out = git(args); - if (!out) return []; - return out - .split('\n') - .map((line) => line.slice(3).trim()) - .filter(Boolean) - .map((p) => (p.includes(' -> ') ? p.split(' -> ')[1] : p)); -} - -/** Join a demo-relative path onto its demo directory, as a repo-relative path. */ -export function demoRelative(demo, ...parts) { - return [demo.demoPath, ...parts].join('/'); -} - -/** Read and parse a demo's `.drift-demo/expected.json`. Exits non-zero on any problem. */ -export function readExpected(demo) { - const path = join(REPO_ROOT, demo.demoPath, '.drift-demo', 'expected.json'); - if (!existsSync(path)) fail(`missing ${demo.demoPath}/.drift-demo/expected.json`); - try { - return JSON.parse(readFileSync(path, 'utf8')); - } catch (error) { - return fail(`${demo.demoPath}/.drift-demo/expected.json is not valid JSON: ${error.message}`); +export function git(args, { allowFailure = false } = {}) { + const result = spawnSync('git', args, { cwd: REPO_ROOT, encoding: 'utf8' }); + if (result.status !== 0 && !allowFailure) { + fail(`git ${args.join(' ')} failed:\n${(result.stderr || result.stdout || '').trim()}`); } + return result.status === 0 ? result.stdout.trimEnd() : null; } diff --git a/scripts/lib/devcontainer-spec.mjs b/scripts/lib/devcontainer-spec.mjs index 4139ffb..fdb73d7 100644 --- a/scripts/lib/devcontainer-spec.mjs +++ b/scripts/lib/devcontainer-spec.mjs @@ -1,106 +1,106 @@ // Per-ecosystem Codespace definitions, and the generator that turns them into // .devcontainer//devcontainer.json. // -// The files are generated rather than hand-maintained because the one thing -// they each need to know — which *other* demos to hide from the Explorer — -// changes every time a demo is added. Sixteen hand-written copies of that list -// is sixteen chances to forget one, and the failure is silent: the Explorer -// just shows clutter. Here it is derived from demos.json. -// -// `scripts/sync-devcontainers.mjs` writes them; `scripts/verify-devcontainers.mjs` -// checks the committed files match, so a stale one fails CI. +// Generated rather than hand-written because each container has to hide the +// *other* fifteen demos from the Explorer, and that list changes every time a +// demo is added. `scripts/sync-devcontainers.mjs` writes them. /** - * What each ecosystem's container needs, beyond the shared shape. + * What each ecosystem's container needs beyond the shared shape. * * image devcontainer base image - * features extra devcontainer features (Node is added automatically wherever - * the base image does not already provide it, because every demo - * runs the shared prepare script) - * setup creation command, if it differs from the plain prepare step - * settings extra VS Code settings for this demo + * node set false when the image already ships Node (every demo runs the + * shared prepare script, which is Node) + * features extra devcontainer features + * settings extra VS Code settings */ export const ECOSYSTEM_CONTAINERS = { npm: { image: 'mcr.microsoft.com/devcontainers/javascript-node:1-22-bookworm', node: false, - // Install after preparing, so the editor's own TypeScript server reports - // the same error the upgrade really causes. + // Install after preparing, so the editor's own TypeScript server shows the + // same errors the upgrade really causes. setup: 'node scripts/prepare-demo.mjs npm && npm --prefix demos/npm install --no-audit --no-fund', }, - pypi: { - image: 'mcr.microsoft.com/devcontainers/python:1-3.12-bookworm', - }, + pypi: { image: 'mcr.microsoft.com/devcontainers/python:1-3.12-bookworm' }, go: { image: 'mcr.microsoft.com/devcontainers/go:1-1.22-bookworm', - // golang.org/x/exp ships only pseudo-versions, which Drift reads as a patch - // move. .github/drift.yml opts the repo in; this makes the extension agree - // without depending on config-file precedence. + // x/exp only ships pseudo-versions, which Drift reads as a patch move. settings: { 'drift.analysis.includePatch': true }, }, - cargo: { - image: 'mcr.microsoft.com/devcontainers/rust:1-1-bookworm', - // Drift's Rust surface diff needs `cargo public-api` and the nightly - // toolchain. Provisioned up front; see .devcontainer/cargo/setup.sh. - setup: '.devcontainer/cargo/setup.sh', - }, + cargo: { image: 'mcr.microsoft.com/devcontainers/rust:1-1-bookworm' }, maven: { image: 'mcr.microsoft.com/devcontainers/java:1-21-bookworm', - features: { - 'ghcr.io/devcontainers/features/java:1': { version: 'none', installMaven: true }, - }, - }, - rubygems: { - image: 'mcr.microsoft.com/devcontainers/ruby:1-3.3-bookworm', - }, - nuget: { - image: 'mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm', + features: { 'ghcr.io/devcontainers/features/java:1': { version: 'none', installMaven: true } }, }, - packagist: { - image: 'mcr.microsoft.com/devcontainers/php:1-8.2-bookworm', + rubygems: { image: 'mcr.microsoft.com/devcontainers/ruby:1-3.3-bookworm' }, + nuget: { image: 'mcr.microsoft.com/devcontainers/dotnet:1-8.0-bookworm' }, + packagist: { image: 'mcr.microsoft.com/devcontainers/php:1-8.2-bookworm' }, + hex: { + image: 'hexpm/elixir:1.15.7-erlang-26.2.1-debian-bookworm-20231009-slim', + features: { 'ghcr.io/devcontainers/features/git:1': {} }, }, pub: { image: 'dart:3.3', features: { 'ghcr.io/devcontainers/features/git:1': {} }, }, - hex: { - image: 'hexpm/elixir:1.15.7-erlang-26.2.1-debian-bookworm-20231009-slim', + swift: { + image: 'swift:5.9-jammy', features: { 'ghcr.io/devcontainers/features/git:1': {} }, }, + cocoapods: { + // Codespaces is Linux, so the pod cannot be built here — building an iOS + // target needs Xcode. The demo is the dependency change and Drift's + // reading of it, which needs only Ruby and CocoaPods. + image: 'mcr.microsoft.com/devcontainers/ruby:1-3.3-bookworm', + setup: 'gem install cocoapods --no-document && node scripts/prepare-demo.mjs cocoapods', + }, + opam: { + image: 'ocaml/opam:debian-12-ocaml-4.14', + features: { 'ghcr.io/devcontainers/features/node:1': { version: 'lts' } }, + node: false, + }, + conan: { + image: 'mcr.microsoft.com/devcontainers/cpp:1-debian-12', + setup: 'pipx install conan && node scripts/prepare-demo.mjs conan', + }, + vcpkg: { image: 'mcr.microsoft.com/devcontainers/cpp:1-debian-12' }, + arduino: { + image: 'mcr.microsoft.com/devcontainers/python:1-3.12-bookworm', + setup: 'pipx install platformio && node scripts/prepare-demo.mjs arduino', + }, }; -/** Node feature, added wherever the base image does not already ship it. */ const NODE_FEATURE = { 'ghcr.io/devcontainers/features/node:1': { version: 'lts' } }; -/** - * Build the devcontainer object for one demo. - * - * @param {object} demo the demos.json entry - * @param {object[]} allDemos every demos.json entry, for the exclude list - * @param {object} expected the demo's expected.json, for the files to open - */ -export function buildDevcontainer(demo, allDemos, expected) { +/** Build the devcontainer object for one demo. */ +export function buildDevcontainer(demo, allDemos) { const spec = ECOSYSTEM_CONTAINERS[demo.ecosystem]; if (!spec) return null; const features = { ...(spec.node === false ? {} : NODE_FEATURE), ...(spec.features ?? {}) }; - // Hide every *other* demo, derived rather than restated. const filesExclude = {}; for (const other of allDemos) { - if (other.ecosystem !== demo.ecosystem) filesExclude[other.demoPath] = true; + if (other.ecosystem !== demo.ecosystem) filesExclude[other.dir] = true; } return { name: `Drift demo — ${demo.label}`, image: spec.image, ...(Object.keys(features).length > 0 ? { features } : {}), + // Runs once at creation, after checkout and before the editor starts, so + // the dependency change is already in place when Drift's startup analysis + // runs. It does not run on resume, so reopening a Codespace never + // overwrites what you were experimenting with. onCreateCommand: spec.setup ?? `node scripts/prepare-demo.mjs ${demo.ecosystem}`, waitFor: 'onCreateCommand', customizations: { vscode: { extensions: ['drift.drift'], settings: { + // Analysis-oriented: Drift explains, it does not edit. No agent, API + // key or GitHub auth involved. 'drift.session.mode': 'ask', 'drift.analysis.runOnStartup': true, ...(spec.settings ?? {}), @@ -108,22 +108,14 @@ export function buildDevcontainer(demo, allDemos, expected) { }, }, codespaces: { - openFiles: [ - `${demo.demoPath}/DEMO.md`, - `${demo.demoPath}/${expected.expectedAffectedFiles[0]}`, - `${demo.demoPath}/${expected.dependencyFiles[0]}`, - ], + openFiles: [`${demo.dir}/DEMO.md`, ...demo.open.map((f) => `${demo.dir}/${f}`)], }, }, }; } -/** The header comment written above every generated devcontainer. */ -export const GENERATED_HEADER = `// Generated by scripts/sync-devcontainers.mjs from .drift-demo/demos.json. +export const GENERATED_HEADER = `// Generated by scripts/sync-devcontainers.mjs from demos/*/demo.json. // Do not edit by hand — edit scripts/lib/devcontainer-spec.mjs and re-run: // // node scripts/sync-devcontainers.mjs -// -// The Explorer exclude list below is derived from demos.json, so adding a demo -// updates every environment at once instead of leaving fifteen stale copies. `; diff --git a/scripts/lib/drift-runner.mjs b/scripts/lib/drift-runner.mjs deleted file mode 100644 index e7badd5..0000000 --- a/scripts/lib/drift-runner.mjs +++ /dev/null @@ -1,233 +0,0 @@ -// Run published Drift against a prepared fixture and check its machine-readable -// output against the fixture's expected.json. -// -// Until `@usedrift/cli` is published this module resolves to "unavailable" and -// the semantic layer of verify-all.mjs prints SKIPPED. The assertion logic -// below is written against the real shape of `drift analyze --json` -// (schemaVersion 3: `changes`, `breakingChanges`, `impactSites`, `dispositions`) -// so that turning it on is a one-line change, not a rewrite. - -import { spawnSync } from 'node:child_process'; - -import { REPO_ROOT } from './demo-config.mjs'; - -/** The package that provides the `drift` binary. Do not point this elsewhere. */ -export const DRIFT_CLI_PACKAGE = '@usedrift/cli'; - -/** - * Decide how (or whether) to invoke Drift. - * - * DRIFT_CLI=/path/to/drift explicit binary, used as-is - * otherwise `drift` on PATH, only if `drift --version` works - * - * `npx @usedrift/cli` is deliberately NOT attempted: the package is unpublished, - * so an implicit install would fail slowly and confusingly. Once it ships, add - * an `npm i -g @usedrift/cli` step to the workflow (or set DRIFT_CLI). - * - * @returns {{ available: true, command: string, version: string } - * | { available: false, reason: string }} - */ -export function resolveDriftCli() { - const explicit = process.env.DRIFT_CLI?.trim(); - const command = explicit || 'drift'; - const probe = spawnSync(command, ['--version'], { encoding: 'utf8' }); - if (probe.status !== 0) { - return { - available: false, - reason: explicit - ? `DRIFT_CLI="${explicit}" is not runnable (${probe.error?.message ?? `exit ${probe.status}`})` - : `Drift CLI not published (${DRIFT_CLI_PACKAGE})`, - }; - } - return { available: true, command, version: probe.stdout.trim() }; -} - -/** - * Run `drift analyze --json` from the repository root (the whole repo, the way - * the extension sees it) and return the parsed plan. - */ -export function runDriftAnalyze(command) { - const result = spawnSync(command, ['analyze', '--json'], { - cwd: REPO_ROOT, - encoding: 'utf8', - maxBuffer: 64 * 1024 * 1024, - }); - if (!result.stdout) { - throw new Error(`drift analyze produced no output (exit ${result.status}): ${firstLine(result.stderr)}`); - } - try { - return JSON.parse(result.stdout); - } catch (error) { - throw new Error(`drift analyze output was not JSON: ${error.message}`); - } -} - -/** - * Compare two spellings of the same release. - * - * This normalises only *representational* differences and then compares - * exactly. It must never accept two genuinely different releases: an earlier - * version of this function compared component-by-component over - * `Math.min(a.length, b.length)`, which made `1.2` and `1.2.999` equal — so a - * fixture could silently drift onto the wrong release and still pass. - * - * The two differences that are real and must be tolerated: - * - a leading `v`, because Go writes `v1.2.3` and npm writes `1.2.3`; - * - zero-padding of the numeric core, because a pom.xml says `20.0` where - * Drift's normalised form says `20.0.0`. - * - * Everything else — prerelease tags, Go pseudo-version timestamps and hashes, - * build metadata — is preserved and compared exactly. - */ -function versionsMatch(a, b) { - const canonical = (value) => { - if (value === undefined || value === null) return null; - const text = String(value).trim().replace(/^v/, ''); - // Split off prerelease (`-...`) and build metadata (`+...`) from the core. - const match = text.match(/^(\d+(?:\.\d+)*)(?:-([^+]*))?(?:\+(.*))?$/); - if (!match) return text; // not a dotted-numeric version; compare verbatim - const [, core, prerelease = '', build = ''] = match; - const parts = core.split('.'); - while (parts.length < 3) parts.push('0'); // 20.0 -> 20.0.0 - while (parts.length > 3 && parts.at(-1) === '0') parts.pop(); // 1.2.3.0 -> 1.2.3 - return `${parts.map((p) => String(Number(p))).join('.')}${prerelease ? `-${prerelease}` : ''}${build ? `+${build}` : ''}`; - }; - - const x = canonical(a); - const y = canonical(b); - return x !== null && y !== null && x === y; -} - -/** - * Compare a `drift analyze --json` plan against one fixture's expectation. - * - * @param {object} plan parsed `drift analyze --json` - * @param {object} expected the fixture's expected.json - * @param {object} demo the demos.json entry (for demoPath) - * @returns {{ ok: boolean, checks: Array<{label: string, ok: boolean, detail?: string}> }} - */ -export function assertExpectations(plan, expected, demo) { - const checks = []; - const add = (label, ok, detail) => checks.push({ label, ok, detail }); - /** Record something observed but deliberately not asserted. Never counts as a pass. */ - const skip = (label) => checks.push({ label, ok: true, skipped: true }); - - // Which plan entries belong to this demo. - // - // `workspace` is not populated for every ecosystem — Drift leaves it null for - // .NET, for instance — so matching on it alone silently found nothing and - // reported a green "impact site" alongside a red "change reported". The - // manifest path is the reliable signal; workspace is used when present. - const inDemo = (entry) => - entry.workspace === demo.demoPath || - (typeof entry.manifestPath === 'string' && entry.manifestPath.startsWith(`${demo.demoPath}/`)) || - (entry.workspace === null || entry.workspace === undefined); - - const change = (plan.changes ?? []).find((c) => c.name === expected.dependency && inDemo(c)); - add(`change reported for ${expected.dependency}`, Boolean(change)); - - if (change) { - add( - `from ${expected.fromVersion}`, - versionsMatch(change.from, expected.fromVersion) || versionsMatch(change.rawFrom, expected.fromVersion), - `plan: ${change.from}`, - ); - add( - `to ${expected.toVersion}`, - versionsMatch(change.to, expected.toVersion) || versionsMatch(change.rawTo, expected.toVersion), - `plan: ${change.to}`, - ); - } - - // An `evidence-only` fixture asserts a different, weaker — but still - // concrete — artifact: Drift has no API surface to diff for this ecosystem - // (Ruby, PHP, Swift, OCaml, CocoaPods all declare `surface: none`), so the - // honest result is prose evidence plus a recommendation, not a located call - // site. That is asserted here rather than waved through. - if (expected.demoKind === 'evidence-only') { - const rationale = (plan.rationale ?? []).find((r) => r.dependency === expected.dependency); - add(`rationale reported for ${expected.dependency}`, Boolean(rationale)); - - const breakingNotes = (rationale?.summary?.changes ?? []).filter((c) => c.category === 'breaking'); - const wantNotes = expected.expectedEvidence?.minBreakingNotes ?? 1; - add( - `at least ${wantNotes} breaking evidence item(s) cited`, - breakingNotes.length >= wantNotes, - `saw ${breakingNotes.length}`, - ); - add( - 'every cited breaking item carries a source URL', - breakingNotes.length > 0 && breakingNotes.every((c) => typeof c.url === 'string' && c.url.length > 0), - ); - - const wantRec = expected.expectedEvidence?.recommendationIn; - if (Array.isArray(wantRec) && wantRec.length > 0) { - const got = rationale?.assessment?.recommendation; - add(`recommendation is one of ${wantRec.join(', ')}`, wantRec.includes(got), `got ${got}`); - } - - // State the absence explicitly so it can never read as an oversight. - skip( - `no API-surface diff for ${expected.ecosystem} by design — ` + - `${(plan.breakingChanges ?? []).filter((b) => b.dependency === expected.dependency).length} structured finding(s)`, - ); - return { ok: checks.filter((c) => !c.skipped).every((c) => c.ok), checks }; - } - - const breaking = (plan.breakingChanges ?? []).filter( - (b) => b.dependency === expected.dependency && inDemo(b), - ); - add(`at least one breaking change on ${expected.dependency}`, breaking.length > 0); - - if (Array.isArray(expected.expectedChangeKinds) && expected.expectedChangeKinds.length > 0) { - const kinds = new Set(breaking.map((b) => b.kind)); - const hit = expected.expectedChangeKinds.find((k) => kinds.has(k)); - add(`change kind is one of ${expected.expectedChangeKinds.join(', ')}`, Boolean(hit), `saw: ${[...kinds].join(', ')}`); - } - - if (Array.isArray(expected.expectedSymbols) && expected.expectedSymbols.length > 0) { - const symbols = breaking.flatMap((b) => b.symbols ?? []); - const hit = expected.expectedSymbols.find((want) => - symbols.some((s) => s === want || s.endsWith(`.${want}`) || s.endsWith(`::${want}`)), - ); - // A large diff can name hundreds of symbols; the detail line exists to help - // debug a miss, not to reproduce the whole surface. - add(`names one of ${expected.expectedSymbols.join(', ')}`, Boolean(hit), summarise(symbols)); - } - - const siteMatches = (site, f) => site.file === `${demo.demoPath}/${f}` || site.file.endsWith(`/${f}`); - const sites = (plan.impactSites ?? []).filter((s) => - (expected.expectedAffectedFiles ?? []).some((f) => siteMatches(s, f)), - ); - - if (expected.expectsAffectedCallSite) { - for (const f of expected.expectedAffectedFiles ?? []) { - const hasFileSite = (plan.impactSites ?? []).some((s) => siteMatches(s, f)); - add(`impact site in ${f}`, hasFileSite, hasFileSite ? undefined : 'no localized site'); - } - add('at least one localized impact site', sites.length > 0); - } else { - // The fixture does not claim Drift localizes this one. Report what actually - // happened, but never manufacture a passing check out of an untested claim: - // an earlier version recorded `add(..., true)` here, so a demo could assert - // an affected file, get no localization at all, and still show green. - skip( - `localization not asserted (expectsAffectedCallSite: false) — Drift reported ` + - `${sites.length} site(s) in ${(expected.expectedAffectedFiles ?? []).join(', ') || 'the declared files'}`, - ); - } - - // `ok` deliberately ignores skipped entries rather than counting them as passes. - return { ok: checks.filter((c) => !c.skipped).every((c) => c.ok), checks }; -} - -/** A short, readable rendering of a possibly-huge symbol list. */ -function summarise(values, limit = 6) { - if (values.length === 0) return 'saw: none'; - const shown = values.slice(0, limit).join(', '); - return values.length > limit ? `saw ${values.length}: ${shown}, …` : `saw: ${shown}`; -} - -function firstLine(text) { - return String(text ?? '').split('\n')[0]; -} diff --git a/scripts/lib/manifest-version.mjs b/scripts/lib/manifest-version.mjs deleted file mode 100644 index 898bf5d..0000000 --- a/scripts/lib/manifest-version.mjs +++ /dev/null @@ -1,188 +0,0 @@ -// Read the declared version of one dependency from a demo's primary manifest. -// -// This is deliberately small and text-based. Demo fixtures pin exact versions -// (see the fixture contract in the README), so a full manifest parser per -// ecosystem would be more code and more dependencies for no extra signal. Each -// reader returns the version string as written, or throws with a message that -// names the file and the dependency it could not find. -// -// It is used by verify-demo.mjs to assert two facts: the committed baseline is -// at `fromVersion`, and the patched tree is at `toVersion`. - -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; - -/** - * @param {string} ecosystem Drift ecosystem id - * @param {string} demoDir absolute path to the demo directory - * @param {string} dependency registry name / module path of the dependency - * @param {string[]} dependencyFiles demo-relative manifest paths, primary first - * @returns {string} the version string exactly as declared - */ -export function readDeclaredVersion(ecosystem, demoDir, dependency, dependencyFiles) { - const reader = READERS[ecosystem]; - if (!reader) { - throw new Error(`no baseline-version reader implemented for ecosystem "${ecosystem}"`); - } - const primary = dependencyFiles[0]; - const text = readFileSync(join(demoDir, primary), 'utf8'); - const version = reader(text, dependency); - if (!version) { - throw new Error(`could not find a declared version for "${dependency}" in ${primary}`); - } - return version; -} - -const READERS = { - npm(text, dependency) { - const pkg = JSON.parse(text); - for (const field of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) { - const spec = pkg?.[field]?.[dependency]; - if (typeof spec === 'string') return stripRange(spec); - } - return null; - }, - - pypi(text, dependency) { - // Matches `name==1.2.3` in requirements.txt or a pyproject dependency array, - // tolerating extras (`name[x]`) and surrounding quotes/whitespace. - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`["']?${escaped}(?:\\[[^\\]]*\\])?\\s*==\\s*([0-9][^"'\\s,;]*)`, 'i')); - return match ? match[1] : null; - }, - - go(text, dependency) { - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`^\\s*(?:require\\s+)?${escaped}\\s+(v[0-9][^\\s/]*)`, 'm')); - return match ? match[1] : null; - }, - - cargo(text, dependency) { - const escaped = escapeRegExp(dependency); - // `name = "1.2.3"` or `name = { version = "1.2.3", ... }` or `name.version = "1.2.3"`. - // A leading `=`, `^`, `~` or `>=`/`<=` requirement operator is not part of the version. - const clean = (v) => v.replace(/^\s*(>=|<=|=|\^|~|>|<)?\s*/, '').trim(); - const inline = text.match(new RegExp(`^\\s*${escaped}\\s*=\\s*"([^"]+)"`, 'm')); - if (inline) return clean(inline[1]); - const table = text.match(new RegExp(`^\\s*${escaped}\\s*=\\s*\\{[^}]*?version\\s*=\\s*"([^"]+)"`, 'm')); - if (table) return clean(table[1]); - const dotted = text.match(new RegExp(`^\\s*${escaped}\\.version\\s*=\\s*"([^"]+)"`, 'm')); - return dotted ? clean(dotted[1]) : null; - }, - - rubygems(text, dependency) { - // Gemfile: `gem 'rack', '= 3.0.0'`. Drift's own parser requires an explicit - // `=`/`==` operator to treat a RubyGems constraint as an exact version, so - // the fixtures are written that way and this reader expects it. - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`^\\s*gem\\s+["']${escaped}["']\\s*,\\s*["']\\s*=+\\s*([^"']+)["']`, 'm')); - return match ? match[1].trim() : null; - }, - - nuget(text, dependency) { - // csproj: . Drift treats - // only the bracketed form as an exact NuGet version. - const escaped = escapeRegExp(dependency); - const match = text.match( - new RegExp(`Include\\s*=\\s*"${escaped}"[^>]*?Version\\s*=\\s*"\\[?\\s*([^\\]"]+?)\\s*\\]?"`, 'i'), - ); - return match ? match[1].trim() : null; - }, - - packagist(text, dependency) { - const json = JSON.parse(text); - for (const field of ['require', 'require-dev']) { - const spec = json?.[field]?.[dependency]; - if (typeof spec === 'string') return spec.replace(/^[\s^~v=]+/, '').trim(); - } - return null; - }, - - hex(text, dependency) { - // mix.exs: `{:plug, "1.2.3"}` or `{:plug, "== 1.2.3"}` - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`\\{\\s*:${escaped}\\s*,\\s*"([^"]+)"`, 'm')); - return match ? match[1].replace(/^[\s~>=^]+/, '').trim() : null; - }, - - pub(text, dependency) { - // pubspec.yaml: ` http: 1.2.3` - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`^\\s{2,}${escaped}\\s*:\\s*["']?\\^?([0-9][^"'\\s#]*)`, 'm')); - return match ? match[1] : null; - }, - - swift(text, dependency) { - // Package.swift: `.package(url: "https://github.com/apple/x", exact: "1.2.3")` - // `dependency` is the repository URL Drift identifies the package by. - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`${escaped}(?:\\.git)?"[^)]*?exact:\\s*"([^"]+)"`, 's')); - if (match) return match[1]; - const from = text.match(new RegExp(`${escaped}(?:\\.git)?"[^)]*?from:\\s*"([^"]+)"`, 's')); - return from ? from[1] : null; - }, - - cocoapods(text, dependency) { - // Podfile: `pod 'Alamofire', '5.0.0'` - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`^\\s*pod\\s+["']${escaped}["']\\s*,\\s*["']\\s*=?\\s*([^"']+)["']`, 'm')); - return match ? match[1].trim() : null; - }, - - opam(text, dependency) { - // *.opam: `"lwt" {= "5.6.1"}` - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`"${escaped}"\\s*\\{\\s*=\\s*"([^"]+)"`, 'm')); - return match ? match[1] : null; - }, - - conan(text, dependency) { - // conanfile.txt: `fmt/9.1.0` under [requires] - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`^\\s*${escaped}/([^\\s@#]+)`, 'm')); - return match ? match[1] : null; - }, - - vcpkg(text, dependency) { - // vcpkg.json: pinned through `overrides: [{ "name": "fmt", "version": "9.1.0" }]` - const json = JSON.parse(text); - const override = (json.overrides ?? []).find((o) => o?.name === dependency); - if (override) return String(override.version ?? override['version-semver'] ?? '') || null; - const dep = (json.dependencies ?? []).find((d) => d === dependency || d?.name === dependency); - if (dep && typeof dep === 'object' && dep['version>=']) return String(dep['version>=']); - return null; - }, - - arduino(text, dependency) { - // platformio.ini: `lib_deps = bblanchon/ArduinoJson@6.21.3` - const escaped = escapeRegExp(dependency); - const match = text.match(new RegExp(`${escaped}\\s*@\\s*~?\\^?([0-9][^\\s]*)`, 'm')); - if (match) return match[1]; - // library.properties: `depends=Lib (=1.2.3)` - const dep = text.match(new RegExp(`${escaped}\\s*\\(\\s*=\\s*([^)]+)\\)`, 'm')); - return dep ? dep[1].trim() : null; - }, - - maven(text, dependency) { - // `dependency` is `groupId:artifactId`. Find the block whose - // matches and read its . - const [, artifactId] = dependency.includes(':') ? dependency.split(':') : [null, dependency]; - const blocks = text.match(/[\s\S]*?<\/dependency>/g) ?? []; - for (const block of blocks) { - const a = block.match(/\s*([^<\s]+)\s*<\/artifactId>/); - if (a && a[1] === artifactId) { - const v = block.match(/\s*([^<\s]+)\s*<\/version>/); - if (v) return v[1]; - } - } - return null; - }, -}; - -function stripRange(spec) { - return spec.replace(/^[\s^~>=<]+/, '').trim(); -} - -function escapeRegExp(value) { - return value.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'); -} diff --git a/scripts/make-demo-docs.mjs b/scripts/make-demo-docs.mjs new file mode 100644 index 0000000..8fef56b --- /dev/null +++ b/scripts/make-demo-docs.mjs @@ -0,0 +1,85 @@ +#!/usr/bin/env node +// Write demos//DEMO.md from demo.json plus the BREAKING comments in the +// demo's own source. Generated so the guide can never drift from the code. +// +// node scripts/make-demo-docs.mjs [--check] + +import { readFileSync, writeFileSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; + +import { REPO_ROOT, allDemos } from './lib/demo-config.mjs'; + +const checkOnly = process.argv.includes('--check'); +let stale = 0; + +for (const demo of allDemos()) { + const sourceFile = demo.open[0]; + const source = readFileSync(join(REPO_ROOT, demo.dir, sourceFile), 'utf8'); + + // Each break is marked "── BREAKING n ──" followed by comment lines + // explaining it. Pull those out so the guide lists the real ones. + const breaks = []; + const lines = source.split('\n'); + for (let i = 0; i < lines.length; i += 1) { + if (!/BREAKING\s+\d+/.test(lines[i])) continue; + // Consume the explanation that follows the marker. Line-comment languages + // end it at the first non-comment or blank line; OCaml's block comments + // have no per-line marker, so there the block ends at `*)`. + const blockComment = !/^\s*(\/\/|#|--)/.test(lines[i + 1] ?? ''); + const text = []; + for (let j = i + 1; j < lines.length; j += 1) { + const raw = lines[j]; + const closes = blockComment && /\*\)/.test(raw); + if (!blockComment && (!/^\s*(\/\/|#|--)/.test(raw) || raw.trim().replace(/^\s*(\/\/|#|--)\s?/, '') === '')) break; + const stripped = raw + .replace(/\*\)\s*$/, '') + .replace(/^\s*(\/\/|#|--|\(\*)?\s?/, '') + .replace(/─+/g, '') + .trim(); + if (stripped !== '') text.push(stripped); + if (closes || stripped === '') break; + } + if (text.length) breaks.push(text.join(' ').replace(/\s+/g, ' ').trim()); + } + + const body = `# Try Drift — ${demo.label} + +This project depends on \`${demo.dependency}\` **${demo.from}**. + +The Codespace upgraded it to **${demo.to}** and left the source code alone, so +\`${sourceFile}\` is now written against an API that no longer exists. That is +the situation Drift is built to analyse. + +${breaks.length} breaking change${breaks.length === 1 ? '' : 's'} in this demo: + +${breaks.map((b, i) => `${i + 1}. ${b}`).join('\n')} + +## Try it + +1. Open the Drift icon in the Activity Bar. +2. Look at what Drift found for \`${demo.dependency}\`. +3. Open \`${sourceFile}\` and compare against the marked lines. + +\`\`\`sh +git status --short # only the manifest is modified; the source is untouched +\`\`\` + +Reset it with \`node scripts/reset-demo.mjs ${demo.ecosystem}\`. +`; + + const target = join(REPO_ROOT, demo.dir, 'DEMO.md'); + const current = existsSync(target) ? readFileSync(target, 'utf8') : null; + if (current === body) continue; + if (checkOnly) { + stale += 1; + process.stdout.write(` ✗ ${demo.dir}/DEMO.md is stale\n`); + continue; + } + writeFileSync(target, body); + process.stdout.write(` ✓ ${demo.dir}/DEMO.md (${breaks.length} breaking changes)\n`); +} + +if (checkOnly && stale > 0) { + process.stderr.write(`\n${stale} DEMO.md file(s) out of date — run: node scripts/make-demo-docs.mjs\n`); + process.exit(1); +} diff --git a/scripts/prepare-demo.mjs b/scripts/prepare-demo.mjs index 3927457..dbfe1e9 100644 --- a/scripts/prepare-demo.mjs +++ b/scripts/prepare-demo.mjs @@ -1,122 +1,45 @@ #!/usr/bin/env node -// Apply a demo's dependency upgrade into the working tree, leaving source alone. +// Apply a demo's dependency upgrade, leaving the source code alone. // // node scripts/prepare-demo.mjs // -// The committed state of every demo is `dependency@OLD` with source code valid -// against OLD. This script applies `upgrade.patch`, which moves only dependency -// metadata to `dependency@NEW`. The result — new dependency, old source — is -// the exact situation Drift is built to analyze, and it reaches Drift as an -// uncommitted manifest change (see `chooseManifestRange` in trydrift/drift). +// This is what the Codespace runs once at creation. It edits only the manifest, +// so the working tree ends up as: new dependency version, old source code, +// uncommitted — which is what Drift analyses. // -// It is safe to run twice: an already-prepared fixture is detected and left as -// is. It never runs a repository-wide reset and never touches paths outside the -// selected demo. +// Running it twice is harmless. -import { existsSync, readFileSync, statSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { - REPO_ROOT, - fail, - getDemo, - readEcosystemArg, - git, - dirtyPaths, - isDependencyFile, -} from './lib/demo-config.mjs'; +import { REPO_ROOT, fail, readDemo, readEcosystemArg } from './lib/demo-config.mjs'; -const ecosystem = readEcosystemArg('prepare-demo.mjs'); -const demo = getDemo(ecosystem); +const demo = readDemo(readEcosystemArg('prepare-demo.mjs')); -const demoDir = join(REPO_ROOT, demo.demoPath); -if (!existsSync(demoDir) || !statSync(demoDir).isDirectory()) { - fail(`demo directory ${demo.demoPath} does not exist yet`); -} - -const patchPath = join(demoDir, '.drift-demo', 'upgrade.patch'); -const expectedPath = join(demoDir, '.drift-demo', 'expected.json'); -if (!existsSync(patchPath)) fail(`missing ${demo.demoPath}/.drift-demo/upgrade.patch`); -if (!existsSync(expectedPath)) fail(`missing ${demo.demoPath}/.drift-demo/expected.json`); - -let expected; -try { - expected = JSON.parse(readFileSync(expectedPath, 'utf8')); -} catch (error) { - fail(`${demo.demoPath}/.drift-demo/expected.json is not valid JSON: ${error.message}`); -} - -const dependencyFiles = expected.dependencyFiles; -if (!Array.isArray(dependencyFiles) || dependencyFiles.length === 0) { - fail(`${demo.demoPath}/.drift-demo/expected.json: "dependencyFiles" must be a non-empty array`); -} -const expectedDirty = dependencyFiles.map((f) => `${demo.demoPath}/${f}`).sort(); +let changed = 0; +let already = 0; -const currentDirty = dirtyPaths(demo.demoPath).sort(); +for (const edit of demo.edits) { + const path = join(REPO_ROOT, demo.dir, edit.file); + const before = readFileSync(path, 'utf8'); -const applies = (extraArgs) => - git(['apply', ...extraArgs, '--directory', demo.demoPath, patchPath], { allowFailure: true }) !== null; - -if (currentDirty.length > 0) { - const alreadyPrepared = - sameSet(currentDirty, expectedDirty) && applies(['--reverse', '--check']); - if (alreadyPrepared) { - process.stdout.write( - `✓ ${ecosystem} demo already prepared — ${describe(expected)}\n` + - ` Nothing to do. Run \`node scripts/reset-demo.mjs ${ecosystem}\` to restore the baseline.\n`, - ); - process.exit(0); + if (before.includes(edit.replace) && !before.includes(edit.find)) { + already += 1; + continue; } - fail( - `working tree for ${demo.demoPath} has changes that are not this demo's upgrade:\n` + - currentDirty.map((p) => ` ${p}`).join('\n') + - `\n Run \`node scripts/reset-demo.mjs ${ecosystem}\` first, or resolve these manually.`, - ); -} - -if (!applies(['--check'])) { - const detail = git(['apply', '--check', '--directory', demo.demoPath, '--verbose', patchPath], { - allowFailure: true, - }); - fail(`upgrade.patch does not apply cleanly to the committed baseline of ${demo.demoPath}\n${detail ?? ''}`); -} - -git(['apply', '--directory', demo.demoPath, patchPath]); - -const afterDirty = dirtyPaths(demo.demoPath).sort(); - -if (!sameSet(afterDirty, expectedDirty)) { - git(['checkout', '--', demo.demoPath]); // undo the partial apply before failing - const extra = afterDirty.filter((p) => !expectedDirty.includes(p)); - const missing = expectedDirty.filter((p) => !afterDirty.includes(p)); - fail( - `upgrade.patch changed a different set of files than expected.json declares:\n` + - (extra.length ? ` unexpected: ${extra.join(', ')}\n` : '') + - (missing.length ? ` expected but unchanged: ${missing.join(', ')}\n` : '') + - ` The patch must touch only ${expected.dependencyFiles.join(', ')} and no source.`, - ); + if (!before.includes(edit.find)) { + fail(`${demo.dir}/${edit.file} does not contain the expected text:\n ${edit.find}`); + } + writeFileSync(path, before.split(edit.find).join(edit.replace)); + changed += 1; } -const nonDependency = afterDirty.filter((p) => !isDependencyFile(p.slice(demo.demoPath.length + 1))); -if (nonDependency.length > 0) { - git(['checkout', '--', demo.demoPath]); - fail( - `upgrade.patch modified files Drift does not treat as dependency metadata:\n` + - nonDependency.map((p) => ` ${p}`).join('\n'), +if (changed === 0 && already > 0) { + process.stdout.write(`✓ ${demo.ecosystem} demo already prepared — ${demo.dependency} ${demo.from} → ${demo.to}\n`); +} else { + process.stdout.write( + `✓ ${demo.ecosystem} demo prepared — ${demo.dependency} ${demo.from} → ${demo.to}\n` + + ` changed: ${demo.edits.map((e) => e.file).join(', ')}\n` + + ` source code: untouched\n`, ); } - -process.stdout.write( - `✓ ${ecosystem} demo prepared — ${describe(expected)}\n` + - ` dependency files modified: ${dependencyFiles.join(', ')}\n` + - ` application source: unchanged\n` + - ` Drift will pick this up as an uncommitted manifest change.\n`, -); - -function describe(exp) { - return `${exp.dependency} ${exp.fromVersion} → ${exp.toVersion}`; -} - -function sameSet(a, b) { - return a.length === b.length && a.every((value, index) => value === b[index]); -} diff --git a/scripts/reset-demo.mjs b/scripts/reset-demo.mjs index 5977f28..eedf2bd 100644 --- a/scripts/reset-demo.mjs +++ b/scripts/reset-demo.mjs @@ -1,73 +1,17 @@ #!/usr/bin/env node -// Restore one demo's dependency metadata to its committed baseline. +// Put a demo's manifest back to its committed version. // // node scripts/reset-demo.mjs // -// This is the exact inverse of prepare-demo.mjs: it puts the declared -// dependency files back to `HEAD` and deletes the fixture's own known -// generated artefacts. It does not touch anything else — if you edited the -// demo's source to experiment, that stays. There is no repository-wide reset -// here, by design. +// Restores only the files the upgrade touches. Anything else you changed in the +// demo — including the source you were experimenting with — is left alone. -import { existsSync, readFileSync, rmSync } from 'node:fs'; -import { join } from 'node:path'; +import { git, readDemo, readEcosystemArg } from './lib/demo-config.mjs'; -import { - REPO_ROOT, - fail, - getDemo, - readEcosystemArg, - git, - dirtyPaths, -} from './lib/demo-config.mjs'; +const demo = readDemo(readEcosystemArg('reset-demo.mjs')); -const ecosystem = readEcosystemArg('reset-demo.mjs'); -const demo = getDemo(ecosystem); - -const demoDir = join(REPO_ROOT, demo.demoPath); -const expectedPath = join(demoDir, '.drift-demo', 'expected.json'); -if (!existsSync(expectedPath)) fail(`missing ${demo.demoPath}/.drift-demo/expected.json`); - -const expected = JSON.parse(readFileSync(expectedPath, 'utf8')); -const dependencyFiles = expected.dependencyFiles ?? []; -const generatedFiles = expected.generatedFiles ?? []; - -if (!Array.isArray(dependencyFiles) || dependencyFiles.length === 0) { - fail(`${demo.demoPath}/.drift-demo/expected.json: "dependencyFiles" must be a non-empty array`); +for (const edit of demo.edits) { + git(['checkout', 'HEAD', '--', `${demo.dir}/${edit.file}`]); } -for (const relative of dependencyFiles) { - const repoPath = `${demo.demoPath}/${relative}`; - const tracked = git(['ls-files', '--error-unmatch', repoPath], { allowFailure: true }) !== null; - if (tracked) { - git(['checkout', 'HEAD', '--', repoPath]); - } else if (existsSync(join(REPO_ROOT, repoPath))) { - // The patch created this file; the baseline does not have it. - rmSync(join(REPO_ROOT, repoPath)); - } -} - -for (const relative of generatedFiles) { - const target = join(demoDir, relative); - if (existsSync(target)) rmSync(target, { recursive: true, force: true }); -} - -const stillDirty = dirtyPaths(demo.demoPath).filter((p) => { - const rel = p.slice(demo.demoPath.length + 1); - return dependencyFiles.includes(rel); -}); -if (stillDirty.length > 0) { - fail(`dependency files did not return to baseline:\n${stillDirty.map((p) => ` ${p}`).join('\n')}`); -} - -process.stdout.write(`✓ ${ecosystem} demo reset — dependency files restored to the committed baseline\n`); - -const otherChanges = dirtyPaths(demo.demoPath).filter((p) => { - const rel = p.slice(demo.demoPath.length + 1); - return !dependencyFiles.includes(rel) && !generatedFiles.some((g) => rel === g || rel.startsWith(`${g}/`)); -}); -if (otherChanges.length > 0) { - process.stdout.write( - ` left untouched (not part of this fixture):\n${otherChanges.map((p) => ` ${p}`).join('\n')}\n`, - ); -} +process.stdout.write(`✓ ${demo.ecosystem} demo reset — back to ${demo.dependency} ${demo.from}\n`); diff --git a/scripts/sync-devcontainers.mjs b/scripts/sync-devcontainers.mjs index 871a214..b6002e6 100644 --- a/scripts/sync-devcontainers.mjs +++ b/scripts/sync-devcontainers.mjs @@ -1,51 +1,40 @@ #!/usr/bin/env node -// Regenerate .devcontainer//devcontainer.json from demos.json. +// Regenerate .devcontainer//devcontainer.json from the demos. // // node scripts/sync-devcontainers.mjs [--check] -// -// With --check it writes nothing and exits non-zero if any file is stale, -// which is what CI runs. import { mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs'; import { dirname, join } from 'node:path'; -import { REPO_ROOT, loadDemosConfig, readExpected } from './lib/demo-config.mjs'; +import { REPO_ROOT, allDemos } from './lib/demo-config.mjs'; import { buildDevcontainer, GENERATED_HEADER, ECOSYSTEM_CONTAINERS } from './lib/devcontainer-spec.mjs'; const checkOnly = process.argv.includes('--check'); -const { demos } = loadDemosConfig(); - +const demos = allDemos(); let stale = 0; let written = 0; for (const demo of demos) { if (!ECOSYSTEM_CONTAINERS[demo.ecosystem]) continue; - if (!existsSync(join(REPO_ROOT, demo.demoPath))) continue; - const config = buildDevcontainer(demo, demos, readExpected(demo)); - const content = `${GENERATED_HEADER}${JSON.stringify(config, null, 2)}\n`; - const target = join(REPO_ROOT, demo.devcontainerPath); + const content = `${GENERATED_HEADER}${JSON.stringify(buildDevcontainer(demo, demos), null, 2)}\n`; + const target = join(REPO_ROOT, '.devcontainer', demo.ecosystem, 'devcontainer.json'); - const current = existsSync(target) ? readFileSync(target, 'utf8') : null; - if (current === content) continue; + if ((existsSync(target) ? readFileSync(target, 'utf8') : null) === content) continue; if (checkOnly) { stale += 1; - process.stdout.write(` ✗ ${demo.devcontainerPath} is stale\n`); + process.stdout.write(` ✗ .devcontainer/${demo.ecosystem}/devcontainer.json is stale\n`); continue; } mkdirSync(dirname(target), { recursive: true }); writeFileSync(target, content); written += 1; - process.stdout.write(` ✓ wrote ${demo.devcontainerPath}\n`); + process.stdout.write(` ✓ .devcontainer/${demo.ecosystem}/devcontainer.json\n`); } -if (checkOnly) { - if (stale > 0) { - process.stderr.write(`\n${stale} devcontainer(s) out of date — run: node scripts/sync-devcontainers.mjs\n`); - process.exit(1); - } - process.stdout.write('All devcontainers are up to date.\n'); -} else { - process.stdout.write(written === 0 ? 'All devcontainers already up to date.\n' : `\n${written} file(s) written.\n`); +if (checkOnly && stale > 0) { + process.stderr.write(`\n${stale} out of date — run: node scripts/sync-devcontainers.mjs\n`); + process.exit(1); } +if (!checkOnly) process.stdout.write(`\n${written} file(s) written.\n`); diff --git a/scripts/verify-all.mjs b/scripts/verify-all.mjs deleted file mode 100644 index a324d9e..0000000 --- a/scripts/verify-all.mjs +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env node -// Validate every demo fixture — structure always, semantics when Drift is -// published. This is what the verify-demos.yml workflow runs. -// -// node scripts/verify-all.mjs -// -// Structural pass (per demo, must pass before publication): -// runs scripts/verify-demo.mjs — baseline version, patch applies -// and touches only dependency metadata, source untouched, patched version, -// reset restores the baseline. -// -// Semantic pass (per demo, only when `@usedrift/cli` resolves): -// prepare the fixture, run `drift analyze --json`, compare against -// expected.json (dependency, from/to, breaking-change kind and symbol, -// localized impact sites), reset the fixture. - -import { spawnSync } from 'node:child_process'; -import { existsSync, statSync } from 'node:fs'; -import { join } from 'node:path'; - -import { REPO_ROOT, loadDemosConfig, readExpected } from './lib/demo-config.mjs'; -import { resolveDriftCli, runDriftAnalyze, assertExpectations } from './lib/drift-runner.mjs'; - -const { demos } = loadDemosConfig(); -const cli = resolveDriftCli(); - -process.stdout.write(`.drift-demo/demos.json valid — ${demos.length} demo(s)\n`); -process.stdout.write( - cli.available - ? `Drift CLI: ${cli.command} (${cli.version}) — semantic checks ENABLED\n\n` - : `Drift CLI: ${cli.reason} — semantic checks SKIPPED\n\n`, -); - -let failures = 0; -const rows = []; - -for (const demo of demos) { - const present = existsSync(join(REPO_ROOT, demo.demoPath)) && statSync(join(REPO_ROOT, demo.demoPath)).isDirectory(); - if (!present) { - if (demo.status === 'not-yet-validated') { - rows.push([demo.ecosystem, 'pending', 'no fixture yet']); - } else { - failures += 1; - rows.push([demo.ecosystem, 'FAIL', 'exposed demo has no fixture']); - } - continue; - } - - // --- structural ------------------------------------------------------------- - const structural = spawnSync('node', ['scripts/verify-demo.mjs', demo.ecosystem], { - cwd: REPO_ROOT, - encoding: 'utf8', - }); - process.stdout.write(structural.stdout ?? ''); - if (structural.status !== 0) { - process.stdout.write(structural.stderr ?? ''); - failures += 1; - rows.push([demo.ecosystem, 'FAIL', 'structural verification']); - continue; - } - - if (!cli.available) { - rows.push([demo.ecosystem, 'ok', 'structure only']); - continue; - } - - // --- semantic ------------------------------------------------------------ - const expected = readExpected(demo); - let semanticOk = false; - let note = ''; - try { - run('node', ['scripts/prepare-demo.mjs', demo.ecosystem]); - const plan = runDriftAnalyze(cli.command); - const { ok, checks } = assertExpectations(plan, expected, demo); - process.stdout.write(`\nSemantic (${demo.ecosystem}):\n`); - for (const c of checks) { - const mark = c.skipped ? '–' : c.ok ? '✓' : '✗'; - process.stdout.write(` ${mark} ${c.label}${c.detail ? ` — ${c.detail}` : ''}\n`); - } - semanticOk = ok; - note = ok ? 'structure + semantics' : 'semantic mismatch'; - } catch (error) { - note = `semantic error: ${error.message}`; - } finally { - run('node', ['scripts/reset-demo.mjs', demo.ecosystem]); - } - - // A semantic mismatch is only a CI failure for a demo the website exposes. - // `not-yet-validated` demos are, by definition, not yet guaranteed to produce - // the full Drift result — the mismatch is surfaced as a warning instead. - const enforced = demo.status === 'interactive' || demo.status === 'evidence-only'; - if (!semanticOk && enforced) failures += 1; - rows.push([ - demo.ecosystem, - semanticOk ? 'ok' : enforced ? 'FAIL' : 'warn', - semanticOk ? note : `${note} (status: ${demo.status})`, - ]); -} - -process.stdout.write('\nSummary:\n'); -const w = Math.max(...rows.map((r) => r[0].length), 8); -for (const [eco, state, note] of rows) { - process.stdout.write(` ${eco.padEnd(w)} ${state.padEnd(8)} ${note}\n`); -} - -if (failures > 0) { - process.stderr.write(`\n${failures} problem(s) found.\n`); - process.exit(1); -} -process.stdout.write('\nAll demo checks passed.\n'); - -function run(command, args) { - const r = spawnSync(command, args, { cwd: REPO_ROOT, encoding: 'utf8' }); - if (r.status !== 0) { - throw new Error(`${command} ${args.join(' ')} failed: ${(r.stderr || r.stdout || '').trim()}`); - } - return r; -} diff --git a/scripts/verify-demo.mjs b/scripts/verify-demo.mjs deleted file mode 100644 index 460b65b..0000000 --- a/scripts/verify-demo.mjs +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/env node -// Validate one demo fixture end to end. -// -// node scripts/verify-demo.mjs -// -// Structural validation (always runs, and must pass before Drift is published): -// - the demo is listed in demos.json -// - DEMO.md, upgrade.patch, expected.json and every referenced file exist -// - expected.json is well formed -// - the committed baseline declares `fromVersion` -// - the patch applies and moves only the declared dependency files -// - application source is untouched -// - the patched tree declares `toVersion` -// - reset restores the baseline exactly -// -// Semantic validation (runs only once `@usedrift/cli` is published): -// - execute Drift, parse its machine-readable output, and compare against -// expected.json. Until then this section prints SKIPPED and the overall -// result is "structure only". - -import { spawnSync } from 'node:child_process'; -import { existsSync, readFileSync, statSync } from 'node:fs'; -import { join } from 'node:path'; - -import { - REPO_ROOT, - fail, - getDemo, - readEcosystemArg, - dirtyPaths, - isDependencyFile, -} from './lib/demo-config.mjs'; -import { readDeclaredVersion } from './lib/manifest-version.mjs'; - -const ecosystem = readEcosystemArg('verify-demo.mjs'); -const demo = getDemo(ecosystem); -const demoDir = join(REPO_ROOT, demo.demoPath); - -const problems = []; -const check = (label, ok, detail) => { - process.stdout.write(`${ok ? ' ✓' : ' ✗'} ${label}\n`); - if (!ok) problems.push(detail ? `${label}: ${detail}` : label); -}; - -process.stdout.write(`Verifying ${ecosystem} demo (${demo.label})\n\nStructure:\n`); - -// --- fixture files exist ------------------------------------------------------ -check('demo directory exists', existsSync(demoDir) && statSync(demoDir).isDirectory()); -if (problems.length) finish(); - -const need = { - 'DEMO.md': join(demoDir, 'DEMO.md'), - 'upgrade.patch': join(demoDir, '.drift-demo', 'upgrade.patch'), - 'expected.json': join(demoDir, '.drift-demo', 'expected.json'), - 'devcontainer.json': join(REPO_ROOT, demo.devcontainerPath), -}; -for (const [label, path] of Object.entries(need)) check(`${label} present`, existsSync(path)); -if (problems.length) finish(); - -// --- expected.json shape ---------------------------------------------------- -let expected; -try { - expected = JSON.parse(readFileSync(need['expected.json'], 'utf8')); -} catch (error) { - check('expected.json parses', false, error.message); - finish(); -} - -check('expected.schemaVersion === 1', expected.schemaVersion === 1); -check('expected.ecosystem matches', expected.ecosystem === ecosystem, `got "${expected.ecosystem}"`); -for (const key of ['dependency', 'fromVersion', 'toVersion']) { - check(`expected.${key} is a non-empty string`, typeof expected[key] === 'string' && expected[key].length > 0); -} -for (const key of ['dependencyFiles', 'expectedAffectedFiles']) { - check(`expected.${key} is a non-empty array`, Array.isArray(expected[key]) && expected[key].length > 0); -} -check('expected.expectsAffectedCallSite is a boolean', typeof expected.expectsAffectedCallSite === 'boolean'); -for (const key of ['expectedSymbols', 'expectedChangeKinds']) { - if (expected[key] !== undefined) check(`expected.${key} is an array`, Array.isArray(expected[key])); -} - -// Every fixture must be able to prove its own break with the ecosystem's own -// toolchain. Structural checks cannot tell a real breaking upgrade from a -// plausible-looking one; `scripts/verify-oracle.mjs` runs this contract. -check( - 'expected.oracle.command is a non-empty string', - typeof expected.oracle?.command === 'string' && expected.oracle.command.length > 0, -); -check( - 'expected.oracle.expectedFailurePattern is a valid regular expression', - (() => { - if (typeof expected.oracle?.expectedFailurePattern !== 'string') return false; - try { - new RegExp(expected.oracle.expectedFailurePattern); - return true; - } catch { - return false; - } - })(), -); -if (problems.length) finish(); - -check('oracle script referenced by oracle.command exists', (() => { - const named = expected.oracle.command.match(/\.drift-demo\/[\w.-]+/); - return named ? existsSync(join(demoDir, named[0])) : true; -})()); -if (problems.length) finish(); - -for (const rel of expected.dependencyFiles) { - check(`dependency file ${rel} exists`, existsSync(join(demoDir, rel))); - check(`dependency file ${rel} is a manifest Drift recognises`, isDependencyFile(rel)); -} -for (const rel of expected.expectedAffectedFiles) { - check(`affected source ${rel} exists`, existsSync(join(demoDir, rel))); - check(`affected source ${rel} is not a dependency file`, !isDependencyFile(rel)); -} -if (problems.length) finish(); - -// --- working tree must be clean before we touch it ------------------------ -check('demo working tree is clean', dirtyPaths(demo.demoPath).length === 0, 'run reset-demo.mjs first'); -if (problems.length) finish(); - -// --- baseline version ----------------------------------------------------- -let baselineVersion; -try { - baselineVersion = readDeclaredVersion(ecosystem, demoDir, expected.dependency, expected.dependencyFiles); - check( - `baseline declares ${expected.dependency}@${expected.fromVersion}`, - baselineVersion === expected.fromVersion, - `manifest says ${baselineVersion}`, - ); -} catch (error) { - check('baseline version is readable', false, error.message); -} -if (problems.length) finish(); - -// --- prepare, inspect, reset ------------------------------------------------- -const prepared = run('node', ['scripts/prepare-demo.mjs', ecosystem]); -check('prepare-demo.mjs succeeds', prepared.status === 0, prepared.output); - -const afterDirty = dirtyPaths(demo.demoPath).sort(); -const expectedDirty = expected.dependencyFiles.map((f) => `${demo.demoPath}/${f}`).sort(); -check( - 'patch touches exactly the declared dependency files', - JSON.stringify(afterDirty) === JSON.stringify(expectedDirty), - `changed: ${afterDirty.join(', ') || 'nothing'}`, -); -check( - 'no application source changed', - afterDirty.every((p) => isDependencyFile(p.slice(demo.demoPath.length + 1))), -); - -try { - const upgradedVersion = readDeclaredVersion(ecosystem, demoDir, expected.dependency, expected.dependencyFiles); - check( - `patched tree declares ${expected.dependency}@${expected.toVersion}`, - upgradedVersion === expected.toVersion, - `manifest says ${upgradedVersion}`, - ); -} catch (error) { - check('patched version is readable', false, error.message); -} - -const reset = run('node', ['scripts/reset-demo.mjs', ecosystem]); -check('reset-demo.mjs succeeds', reset.status === 0, reset.output); -check('reset restores a clean working tree', dirtyPaths(demo.demoPath).length === 0); -try { - const restored = readDeclaredVersion(ecosystem, demoDir, expected.dependency, expected.dependencyFiles); - check(`reset restores ${expected.dependency}@${expected.fromVersion}`, restored === expected.fromVersion); -} catch { - /* already reported above */ -} - -// --- semantic validation (publication-gated) -------------------------------- -process.stdout.write('\nSemantic (Drift CLI):\n'); -const cliVersion = spawnSync('drift', ['--version'], { encoding: 'utf8' }); -if (cliVersion.status !== 0) { - process.stdout.write(' – SKIPPED: Drift CLI not published (@usedrift/cli)\n'); - process.stdout.write(' Semantic assertions are wired up in the validation CI (issue #5).\n'); -} else { - process.stdout.write( - ` – SKIPPED: CLI present (${cliVersion.stdout.trim()}) but semantic assertions ` + - 'are implemented in scripts/lib/drift-runner.mjs (issue #5), not here.\n', - ); -} - -finish(); - -function run(command, args) { - const result = spawnSync(command, args, { cwd: REPO_ROOT, encoding: 'utf8' }); - return { status: result.status, output: `${result.stdout ?? ''}${result.stderr ?? ''}`.trim() }; -} - -function finish() { - process.stdout.write('\n'); - if (problems.length > 0) { - fail(`${ecosystem} demo FAILED verification:\n${problems.map((p) => ` - ${p}`).join('\n')}`); - } - process.stdout.write(`✓ ${ecosystem} demo passed structural verification (semantic checks pending CLI publication)\n`); - process.exit(0); -} diff --git a/scripts/verify-devcontainers.mjs b/scripts/verify-devcontainers.mjs deleted file mode 100644 index 495b8ff..0000000 --- a/scripts/verify-devcontainers.mjs +++ /dev/null @@ -1,108 +0,0 @@ -#!/usr/bin/env node -// Check every devcontainer against demos.json. -// -// node scripts/verify-devcontainers.mjs -// -// Each ecosystem's devcontainer hides the *other* demos from the Explorer with -// `files.exclude`. That list is static, so adding a sixth demo would silently -// leave it visible in the five existing environments — the kind of rot nothing -// reports. This turns it into a failing check. -// -// It also asserts the things a demo Codespace must not lose: the published -// extension id, a creation-time (not resume-time) prepare step, and the three -// files the demo opens. - -import { readFileSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; - -import { REPO_ROOT, loadDemosConfig, readExpected } from './lib/demo-config.mjs'; - -/** Strip comments from JSONC so JSON.parse can read a devcontainer file. */ -function parseJsonc(text) { - const withoutBlock = text.replace(/\/\*[\s\S]*?\*\//g, ''); - const withoutLine = withoutBlock.replace(/(^|[^:"])\/\/.*$/gm, '$1'); - return JSON.parse(withoutLine); -} - -const { demos } = loadDemosConfig(); -const problems = []; -const note = (ok, label) => { - process.stdout.write(` ${ok ? '✓' : '✗'} ${label}\n`); - if (!ok) problems.push(label); -}; - -for (const demo of demos) { - const path = join(REPO_ROOT, demo.devcontainerPath); - process.stdout.write(`\n${demo.ecosystem} (${demo.devcontainerPath})\n`); - - if (!existsSync(path)) { - // A demo with no fixture yet is allowed to have no devcontainer yet. - const hasFixture = existsSync(join(REPO_ROOT, demo.demoPath)); - note(!hasFixture, hasFixture ? 'devcontainer exists' : 'no devcontainer yet (no fixture either)'); - continue; - } - - let config; - try { - config = parseJsonc(readFileSync(path, 'utf8')); - } catch (error) { - note(false, `parses as JSONC — ${error.message}`); - continue; - } - - const vscode = config.customizations?.vscode ?? {}; - - note( - (vscode.extensions ?? []).includes('drift.drift'), - 'installs the published drift.drift extension', - ); - - // Creation-time, not resume-time: reopening a Codespace must not re-apply the - // patch over the visitor's own edits. - const create = config.onCreateCommand; - note(typeof create === 'string' && create.length > 0, 'has an onCreateCommand'); - note( - config.postStartCommand === undefined && config.postAttachCommand === undefined, - 'does not prepare on resume (no postStartCommand / postAttachCommand)', - ); - note(config.waitFor === 'onCreateCommand', 'waitFor is onCreateCommand'); - if (typeof create === 'string') { - const prepares = - create.includes(`prepare-demo.mjs ${demo.ecosystem}`) || create.includes('setup.sh'); - note(prepares, `creation step prepares the ${demo.ecosystem} fixture`); - } - - // The Explorer should show this demo and hide the others — exactly. - const excluded = Object.entries(vscode.settings?.['files.exclude'] ?? {}) - .filter(([, on]) => on === true) - .map(([k]) => k) - .sort(); - const expectedExcluded = demos - .filter((d) => d.ecosystem !== demo.ecosystem) - .map((d) => d.demoPath) - .sort(); - note( - JSON.stringify(excluded) === JSON.stringify(expectedExcluded), - `hides exactly the other ${expectedExcluded.length} demo(s)` + - (JSON.stringify(excluded) === JSON.stringify(expectedExcluded) - ? '' - : `\n excludes: ${excluded.join(', ') || 'nothing'}\n expected: ${expectedExcluded.join(', ')}`), - ); - - // Opens DEMO.md, the affected source, and the manifest. - const open = config.customizations?.codespaces?.openFiles ?? []; - const expected = readExpected(demo); - const wanted = [ - `${demo.demoPath}/DEMO.md`, - `${demo.demoPath}/${expected.expectedAffectedFiles[0]}`, - `${demo.demoPath}/${expected.dependencyFiles[0]}`, - ]; - note(JSON.stringify(open) === JSON.stringify(wanted), `opens DEMO.md, affected source, manifest`); -} - -process.stdout.write('\n'); -if (problems.length > 0) { - process.stderr.write(`${problems.length} devcontainer problem(s).\n`); - process.exit(1); -} -process.stdout.write('All devcontainers agree with demos.json.\n'); diff --git a/scripts/verify-oracle.mjs b/scripts/verify-oracle.mjs deleted file mode 100644 index cc4af10..0000000 --- a/scripts/verify-oracle.mjs +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env node -// Prove that a fixture's break is real, using the ecosystem's own toolchain. -// -// node scripts/verify-oracle.mjs -// -// Structural validation only proves "old manifest → patch applies → new -// manifest, source untouched". That says nothing about whether the code -// actually works before the upgrade and actually breaks after it — which is -// the entire claim a demo makes. Two fixtures shipped with that claim wrong -// because nothing executed them. -// -// So this runs the fixture's own `oracle.command` twice: -// -// 1. against the committed baseline → must SUCCEED (exit 0) -// 2. against the upgraded tree → must FAIL, and the output must match -// `oracle.expectedFailurePattern` -// -// Requiring the failure to *match a pattern* matters: a fixture whose oracle -// fails for an unrelated reason (a typo, a missing toolchain, a network error) -// would otherwise look like a proven break. -// -// This needs the real toolchain for the ecosystem, so it runs in a per-language -// CI matrix rather than in the fast structural job. - -import { spawnSync } from 'node:child_process'; -import { rmSync, existsSync } from 'node:fs'; -import { join } from 'node:path'; - -import { REPO_ROOT, fail, getDemo, readEcosystemArg, readExpected } from './lib/demo-config.mjs'; - -const ecosystem = readEcosystemArg('verify-oracle.mjs'); -const demo = getDemo(ecosystem); -const expected = readExpected(demo); -const demoDir = join(REPO_ROOT, demo.demoPath); - -const oracle = expected.oracle; -if (!oracle?.command || !oracle?.expectedFailurePattern) { - fail( - `${demo.demoPath}/.drift-demo/expected.json: "oracle" must set "command" and ` + - '"expectedFailurePattern". Every fixture must be able to prove its own break.', - ); -} -const failurePattern = new RegExp(oracle.expectedFailurePattern); - -process.stdout.write(`Oracle for ${ecosystem} (${demo.label})\n command: ${oracle.command}\n\n`); - -cleanGenerated(); -run('node', ['scripts/reset-demo.mjs', ecosystem], REPO_ROOT, { quiet: true }); - -// --- 1. baseline must succeed ------------------------------------------------ -process.stdout.write('1. baseline (pre-upgrade) — expecting success\n'); -const baseline = runOracle(); -if (baseline.status !== 0) { - cleanGenerated(); - fail( - ` ✗ the committed baseline does NOT work (exit ${baseline.status}).\n` + - ' A fixture must be valid against its old dependency version.\n' + - indent(baseline.output), - ); -} -process.stdout.write(` ✓ baseline succeeds (exit 0)\n\n`); - -// --- 2. upgraded must fail, for the stated reason ---------------------------- -cleanGenerated(); -run('node', ['scripts/prepare-demo.mjs', ecosystem], REPO_ROOT, { quiet: true }); - -process.stdout.write('2. upgraded — expecting failure matching /' + oracle.expectedFailurePattern + '/\n'); -const upgraded = runOracle(); - -let problem = null; -if (upgraded.status === 0) { - problem = - ' ✗ the upgraded tree still SUCCEEDS. This fixture does not represent a real\n' + - ' breaking change — the upgrade does not break this source code.'; -} else if (!failurePattern.test(upgraded.output)) { - problem = - ` ✗ the upgraded tree failed (exit ${upgraded.status}) but not for the stated reason.\n` + - ` Expected output matching /${oracle.expectedFailurePattern}/.\n` + - indent(upgraded.output); -} - -// Always restore the fixture, whatever the verdict. -cleanGenerated(); -run('node', ['scripts/reset-demo.mjs', ecosystem], REPO_ROOT, { quiet: true }); - -if (problem) fail(problem); - -process.stdout.write(` ✓ upgraded fails as stated (exit ${upgraded.status})\n`); -process.stdout.write(` ${firstMatchingLine(upgraded.output, failurePattern)}\n\n`); -process.stdout.write(`✓ ${ecosystem}: break independently proven by the ecosystem's own toolchain\n`); - -// --------------------------------------------------------------------------- - -function runOracle() { - const result = spawnSync('bash', ['-lc', oracle.command], { - cwd: demoDir, - encoding: 'utf8', - maxBuffer: 32 * 1024 * 1024, - }); - return { status: result.status ?? 1, output: `${result.stdout ?? ''}${result.stderr ?? ''}` }; -} - -/** Remove build/install output the oracle creates, so each run starts clean. */ -function cleanGenerated() { - for (const rel of expected.generatedFiles ?? []) { - const target = join(demoDir, rel); - if (existsSync(target)) rmSync(target, { recursive: true, force: true }); - } -} - -function run(command, args, cwd, { quiet = false } = {}) { - const r = spawnSync(command, args, { cwd, encoding: 'utf8' }); - if (r.status !== 0) fail(`${command} ${args.join(' ')} failed:\n${indent((r.stderr || r.stdout) ?? '')}`); - if (!quiet) process.stdout.write(r.stdout ?? ''); - return r; -} - -function firstMatchingLine(output, pattern) { - return output.split('\n').find((l) => pattern.test(l))?.trim() ?? '(matched)'; -} - -function indent(text) { - return String(text ?? '') - .split('\n') - .slice(0, 25) - .map((l) => ` ${l}`) - .join('\n'); -} diff --git a/scripts/verify-structure.mjs b/scripts/verify-structure.mjs deleted file mode 100644 index 77e2d40..0000000 --- a/scripts/verify-structure.mjs +++ /dev/null @@ -1,66 +0,0 @@ -#!/usr/bin/env node -// Repository-level structural check, run in CI on every push and pull request. -// -// node scripts/verify-structure.mjs -// -// It validates `.drift-demo/demos.json` (schema, known ecosystem ids, labels -// that match Drift's capability registry, allowed status values, no -// duplicates) and then runs `verify-demo.mjs` for every fixture that exists. -// -// Rules: -// - a demo with status "interactive" or "evidence-only" MUST have a fixture -// that passes structural verification -// - a demo with status "not-yet-validated" MAY have no fixture yet; if it -// does have one, it still must pass - -import { spawnSync } from 'node:child_process'; -import { existsSync, statSync } from 'node:fs'; -import { join } from 'node:path'; - -import { REPO_ROOT, loadDemosConfig } from './lib/demo-config.mjs'; - -const { demos } = loadDemosConfig(); -process.stdout.write(`.drift-demo/demos.json is valid — ${demos.length} demo${demos.length === 1 ? '' : 's'} listed\n\n`); - -let failures = 0; -const rows = []; - -for (const demo of demos) { - const dir = join(REPO_ROOT, demo.demoPath); - const present = existsSync(dir) && statSync(dir).isDirectory(); - - if (!present) { - if (demo.status === 'not-yet-validated') { - rows.push([demo.ecosystem, demo.status, 'pending — no fixture yet']); - } else { - failures += 1; - rows.push([demo.ecosystem, demo.status, 'MISSING fixture for an exposed demo']); - } - continue; - } - - const result = spawnSync('node', ['scripts/verify-demo.mjs', demo.ecosystem], { - cwd: REPO_ROOT, - encoding: 'utf8', - }); - process.stdout.write(result.stdout ?? ''); - if (result.status === 0) { - rows.push([demo.ecosystem, demo.status, 'ok']); - } else { - process.stdout.write(result.stderr ?? ''); - failures += 1; - rows.push([demo.ecosystem, demo.status, 'FAILED verification']); - } -} - -process.stdout.write('\nSummary:\n'); -const width = Math.max(...rows.map(([e]) => e.length), 9); -for (const [eco, status, note] of rows) { - process.stdout.write(` ${eco.padEnd(width)} ${status.padEnd(18)} ${note}\n`); -} - -if (failures > 0) { - process.stderr.write(`\n${failures} problem${failures === 1 ? '' : 's'} found.\n`); - process.exit(1); -} -process.stdout.write('\nAll structural checks passed.\n');