diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..7ae57f28 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# shell scripts must keep LF line endings, whatever the checkout: a CRLF install.sh breaks `sh` +*.sh text eol=lf diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml new file mode 100644 index 00000000..9b826cd4 --- /dev/null +++ b/.github/workflows/cli.yml @@ -0,0 +1,157 @@ +# The `bui` command (tools/bui): tested on the three systems for every change to it, and built for +# six targets and attached to the GitHub Release when a release tag is pushed. The installers +# (website/public/install.sh and install.ps1) and `bui update` download these archives. +# +# bui-.tar.gz (Linux, macOS; holds `bui`) +# bui-.zip (Windows; holds `bui.exe`) +# .sha256 +# +# A release is made by tools/release.py (it tags vX.Y.Z); this runs beside release.yml and adds the +# files to the release that one creates (whichever workflow gets there first creates it). + +name: bui command + +on: + push: + tags: ["v*"] + pull_request: + paths: ["tools/bui/**", "website/public/install.*", ".github/workflows/cli.yml"] + workflow_dispatch: + inputs: + tag: + description: "Release tag to attach the archives to (e.g. v0.5.1)" + required: true + publish: + description: "Really upload (otherwise only build)" + type: boolean + default: false + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + test: + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-15] + defaults: + run: + working-directory: tools/bui + steps: + - uses: actions/checkout@v4 + with: + # a manual run builds the tag it was given, not the branch it was started from + ref: ${{ github.event.inputs.tag || github.ref }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: tools/bui + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + + installers: + name: installers (syntax) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: install.sh is POSIX sh and passes shellcheck + run: | + sudo apt-get install -y shellcheck dash + dash -n website/public/install.sh + shellcheck -s sh -S warning website/public/install.sh + - name: install.ps1 is plain ASCII (Windows PowerShell 5.1 decodes a download as it likes) and parses + shell: pwsh + run: | + $bytes = [IO.File]::ReadAllBytes('website/public/install.ps1') + if ($bytes | Where-Object { $_ -gt 127 }) { throw 'install.ps1 has non-ASCII characters' } + $errors = $null + [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'website/public/install.ps1'), [ref]$null, [ref]$errors) + if ($errors) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 } + + build: + name: build (${{ matrix.target }}) + needs: [test, installers] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - { target: x86_64-unknown-linux-gnu, os: ubuntu-22.04 } + - { target: aarch64-unknown-linux-gnu, os: ubuntu-22.04-arm } + - { target: x86_64-apple-darwin, os: macos-15-intel } + - { target: aarch64-apple-darwin, os: macos-15 } + - { target: x86_64-pc-windows-msvc, os: windows-latest } + - { target: aarch64-pc-windows-msvc, os: windows-11-arm } + steps: + - uses: actions/checkout@v4 + with: + # a manual run builds the tag it was given, not the branch it was started from + ref: ${{ github.event.inputs.tag || github.ref }} + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: Swatinem/rust-cache@v2 + with: + workspaces: tools/bui + key: ${{ matrix.target }} + - name: Build + working-directory: tools/bui + run: cargo build --release --locked --target ${{ matrix.target }} + - name: Package (Unix) + if: runner.os != 'Windows' + shell: bash + run: | + set -eu + mkdir -p dist + name="bui-${{ matrix.target }}.tar.gz" + tar -czf "dist/$name" -C "tools/bui/target/${{ matrix.target }}/release" bui + (cd dist && { sha256sum "$name" 2>/dev/null || shasum -a 256 "$name"; } > "$name.sha256") + - name: Package (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + New-Item -ItemType Directory dist | Out-Null + $name = "bui-${{ matrix.target }}.zip" + Compress-Archive -Path "tools/bui/target/${{ matrix.target }}/release/bui.exe" -DestinationPath "dist/$name" + $hash = (Get-FileHash "dist/$name" -Algorithm SHA256).Hash.ToLower() + "$hash $name" | Set-Content "dist/$name.sha256" -NoNewline + - uses: actions/upload-artifact@v4 + with: + name: bui-${{ matrix.target }} + path: dist/* + + upload: + name: attach to the GitHub Release + needs: build + if: github.event_name == 'push' || github.event.inputs.publish == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + env: + TAG: ${{ github.event.inputs.tag || github.ref_name }} + GH_TOKEN: ${{ github.token }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + - name: Create the release if release.yml has not yet, then attach the files + run: | + ls -l dist + gh release view "$TAG" >/dev/null 2>&1 || gh release create "$TAG" --title "BUI ${TAG#v}" --generate-notes --verify-tag || gh release view "$TAG" >/dev/null + gh release upload "$TAG" dist/* --clobber diff --git a/CHANGELOG.md b/CHANGELOG.md index b44d3363..eb325007 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to **blenderui** (BUI). The format follows ## [Unreleased] ### Added +- **The `bui` command** (`tools/bui`, a Rust program): `bui new` / `bui init` ask what to write in (Rust, JavaScript or TypeScript with React, Svelte or plain DOM on Bun, npm or pnpm, Python with Blender components, Qt or tkinter syntax, Lua, C), check that the language's tools are installed and offer the commands that install the newest one, write a project with that language's lints and formatter (Clippy pedantic and rustfmt, Biome and strict TypeScript, Ruff, Luacheck and StyLua, clang-format and clang-tidy) and install the newest BUI with the language's own package manager. `bui dev` and `bui build` run the project; `bui doctor` finds what is wrong with the least work (the project's own checks first, `--all` for every toolchain, `--json`) and offers the fix for each problem before running anything; `bui update` updates `bui` from the release (progress bar, checksum) and the project's packages; `bui docs`, `bui completions`; `bui dev -- ARGS` and `bui build -- ARGS` hand arguments to the tool underneath; `bui` alone lists every command with its options. `bui new` says which packages it will install, with the exact commands, and asks before writing anything. Installed with `curl -LsSf https://bui.preetham.top/install.sh | sh` or `irm https://bui.preetham.top/install.ps1 | iex` (`website/public/install.sh`, `install.ps1`). `.github/workflows/cli.yml` tests it on the three systems and attaches `bui-` archives (six targets, with checksums) to every release; `tools/bump_version.py` and `check_versions.py` move and check its version with the rest. Nothing is installed or changed without a prompt, `--fix` or `--install-tools`. `bui init` in a folder with a `package.json` adds only the missing scripts (and stops on a manifest it cannot read), `bui build` checks for Bun (the bundler of `@blender-ui/native`), `bui update --cli-only` updates only `bui` (what `bui doctor --fix` runs) and a failed required update step is an error; the Unix installer replaces an existing `bui` atomically and the Windows installer by backup and rollback (an installer killed between its two moves leaves `bui.exe.old` to rename back), `bui init` also stops on an unreadable `package.json` or one with `"type": "module"` in a React and TypeScript project (its `tsx` entry cannot import the CommonJS `@blender-ui/react` as an ES module), BUI's `FetchContent_Declare` in a C project is found with spaces before the parenthesis and ignoring comments (a `#` inside a quoted or bracket argument is not one, and a comment between `GIT_TAG` and its value is skipped), `bui update` stages the new binary in a private file beside the old one, and C projects declare C, C++ and Objective-C (macOS). - **Rust: selecting text.** Text in elements is selectable like in a browser: press and drag across words, lines, elements and paragraphs, double-click a word, triple-click a block, `Shift`+click to extend, `Ctrl+A` (Cmd on macOS) for all, `Ctrl+C` to copy, `Esc` or a click elsewhere to clear. The highlight is the theme's `selection` color, drawn behind the text on the CPU and GPU renderers (while something is selected each text line holds one rectangle slot, so a change damages only the lines that changed; with nothing selected there is no extra work), the pointer is the I-beam over selectable text, and a drag that selected text does not click. `user-select` (`none`, `auto`, `text`, `all`, with `-webkit-user-select` / `-moz-user-select` and Tailwind `select-none` / `select-auto` / `select-text` / `select-all`) is implemented and no longer in the accepted-but-ignored list: `auto` follows the parent as in CSS UI 4. Text fields and other widgets keep their own selection; painted lists (`vlist`, `chat_list`) and canvases are not selectable and there is no autoscroll. `Window::selected_text`, `select_all`, `clear_selection`, `on_selection_change` and `read_clipboard` expose it; `examples/selectable.rs` and `tests/selection.rs` show and test it. - **Editor extensions** (`addons/`): `bui-vscode` (a TextMate injection grammar for `rsx!` / `view!` bodies in Rust files, with Tailwind-aware `class` strings, snippets and class completion) and `bui-zed` (a BUI RSX language for `.rsx` files and snippets; Zed cannot extend its built-in Rust macro injections, so `rsx!` inside `.rs` files is not highlighted there). Both GPL-3.0-or-later. - **GPU effects: run your own shader.** A canvas item (`BK_ITEM_EFFECT`, Rust `Painter::effect`) runs a pixel shader of the app's over its box on the GPU renderers, in paint order, clipped and premultiplied like the rest. The source is one portable dialect, GLSL with a small compat set (`vec4 effect(vec2 p)`, `box_size`, `U[i]` floats, `input_color(i, texel)` over up to 8 BUI textures); Direct3D 11 compiles it at run time through `d3dcompiler_47.dll` loaded dynamically (nothing to link, no SDK), OpenGL through the driver, and the compile/link log is returned by `BK_effect_error` / `ShaderEffect::error`. Where the GPU cannot run it (software raster, no compiler, a compile error) the item's image is drawn instead, so an effect has a CPU path too (the distortion wave, `bui-wave`, renders the same frames on the CPU, over every core, and on the GPU through this item; the two agree to within 1/255). `BK_effect_create` / `BK_effect_free` (= `BUI_effect_*`), `BUI_raster_effect`, Rust `ShaderEffect`, `Painter::effect`, `Painter::is_gpu` and `GpuTarget` (off-screen GPU frames). The macOS renderer has no effects yet (it draws the fallback). @@ -92,6 +93,7 @@ All notable changes to **blenderui** (BUI). The format follows audio track plays and each video with sound owns one stream and thread. ### Fixed +- **`bui build` of an npm-installed app.** The JavaScript bundler left `*.node` files out of the bundle but not the platform package `@blender-ui/native-` that holds one, so Bun stopped with "Loading .node files won't work in the browser"; it is left out now. - **Rust: Tailwind `text-sm` / `text-xs` / `text-lg` line heights.** A unitless `calc()` line height (`calc(1.25 / 0.875)`, what the Tailwind theme sets) was read as pixels (1.4 px), so the text sat about 9 px above its box and a parent with `overflow: hidden` (`truncate`) cut it. It is now a factor of the font size, like a number. - **Rust: `text-overflow: ellipsis` on a clipping block.** A `nowrap` text in a block with `overflow: hidden` (`truncate`) was laid out as line-box words, so it was clipped without the `…`. A block holding only text now lays it out as one measured run whatever its `overflow` (except scrolling ones), clips it to the content box and ends it with `…`; `text-overflow` takes effect only when `overflow-x` is not `visible`, as in CSS. - **Windows window exposure and resizing:** a window dragged back from outside the screen, restored from minimize or uncovered diff --git a/README.md b/README.md index 41f0fb7b..8e77da24 100644 --- a/README.md +++ b/README.md @@ -377,6 +377,23 @@ theme. ## 7. Install +**The `bui` command (any language).** One line installs it, and `bui new` makes a project in +Rust, JavaScript or TypeScript (React, Svelte or plain DOM), Python, Lua or C, with that +language's lints, checking its tools first and installing the newest BUI with its own package +manager: + +```sh +curl -LsSf https://bui.preetham.top/install.sh | sh # Linux and macOS +irm https://bui.preetham.top/install.ps1 | iex # Windows (PowerShell) + +bui new my-app # asks what to write it in, then makes it +bui dev # run it +bui doctor # find what is wrong with the setup, and fix it +bui update # update bui and the project's BUI packages +``` + +Or install by hand, per language: + **Python.** You need CPython 3.11 or newer. Wheels are published for Windows, Linux and macOS, so there's nothing to compile. One package gives you all four Python APIs (tkinter syntax, Qt syntax, the Blender components and Dear ImGui): diff --git a/bindings/node/bundle.js b/bindings/node/bundle.js index 7f5261d9..15167443 100644 --- a/bindings/node/bundle.js +++ b/bindings/node/bundle.js @@ -40,7 +40,7 @@ async function main ({ entry, out, bun, dev, console: keepConsole }) { // an ES module importing the entry: Bun's IIFE output runs a CommonJS // entry only when something imports it entrypoints: [writeWrapper(entry, out)], target: 'browser', format: 'iife', minify: true, define, plugins, - external: ['node:*', '*.node'], + external: ['node:*', '*.node', '@blender-ui/native-*'], }) if (!r.success) { for (const log of r.logs) console.error(log) diff --git a/docs/getting-started.md b/docs/getting-started.md index af5112c9..8993e83d 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,5 +1,7 @@ # Getting started +**Fastest start: the `bui` command.** `curl -LsSf https://bui.preetham.top/install.sh | sh` (Windows: `irm https://bui.preetham.top/install.ps1 | iex`), then `bui new my-app`. It asks for a language (Rust, JavaScript or TypeScript, Python, Lua, C), makes a project with that language's lints and installs the newest BUI. `bui doctor` checks and fixes the setup, `bui update` updates. See [tools/bui](../tools/bui/README.md). The rest of this page builds BUI from source. + ## 1. Build Requirements: diff --git a/tools/bui/Cargo.lock b/tools/bui/Cargo.lock new file mode 100644 index 00000000..9918def8 --- /dev/null +++ b/tools/bui/Cargo.lock @@ -0,0 +1,1611 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bui-cli" +version = "0.5.1" +dependencies = [ + "anyhow", + "clap", + "clap_complete", + "cliclack", + "console", + "flate2", + "include_dir", + "self-replace", + "serde", + "serde_json", + "sha2", + "tar", + "tempfile", + "toml", + "ureq", + "zip", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_complete" +version = "4.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037e2a1a92236d0aff7e845093f64661d6df4c02c9fcc61a60e9e1d736fa392f" +dependencies = [ + "clap", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cliclack" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a017eb2baf257bfbdfa7966bd390eacb44f379bfe7131bb0478c64f8f2f390" +dependencies = [ + "console", + "indicatif", + "once_cell", + "strsim", + "textwrap", + "zeroize", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode", + "libc", + "unicode-width", + "windows-sys 0.61.2", +] + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + +[[package]] +name = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "wasm-bindgen", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "include_dir" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "923d117408f1e49d914f1a379a309cffe4f18c05cf4e3d12e613a15fc81bd0dd" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cab85a7ed0bd5f0e76d93846e0147172bed2e2d3f859bcc33a8d9699cad1a75" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "indicatif" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c" +dependencies = [ + "console", + "portable-atomic", + "unicode-width", + "unit-prefix", + "web-time", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "self-replace" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "609c5606d9d357b26e4ee1a7a01beac396628d0fa01ebbade2a09cefb88e65af" +dependencies = [ + "fastrand", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "foldhash", + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "icu_segmenter", + "smawk", + "unicode-width", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unit-prefix" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64", + "cookie_store", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zip" +version = "9.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80cc68510ea7553c30a69c732de5278e94183f68765af6c642dbccefd6ec777e" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/tools/bui/Cargo.toml b/tools/bui/Cargo.toml new file mode 100644 index 00000000..3bab1d5a --- /dev/null +++ b/tools/bui/Cargo.toml @@ -0,0 +1,73 @@ +[package] +name = "bui-cli" +description = "bui: create, run, check and update BUI apps (Rust, JavaScript, Python, Lua, C)" +version = "0.5.1" +edition = "2024" +rust-version = "1.88" +license = "GPL-3.0-or-later" +repository = "https://github.com/ppmpreetham/BUI" +homepage = "https://bui.preetham.top" +publish = false + +[[bin]] +name = "bui" +path = "src/main.rs" + +[dependencies] +anyhow = "1.0.104" +clap = { version = "4.6.7", features = ["derive", "env"] } +clap_complete = "4.6.11" +cliclack = "0.5.7" +console = "0.16.6" +flate2 = "1.1.11" +include_dir = "0.7.4" +self-replace = "1.5.1" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = { version = "1.0.154", features = ["preserve_order"] } +sha2 = "0.11.1" +tar = "0.4.46" +tempfile = "3.27.0" +toml = "1.2.1" +ureq = { version = "3.5.2", features = ["json"] } +zip = { version = "9.6.0", default-features = false, features = ["deflate"] } + +# Its own workspace: nothing else in the repo builds it (it needs no BUI code, so it builds in seconds). +[workspace] + +[profile.release] +opt-level = "z" +lto = "fat" +codegen-units = 1 +panic = "abort" +strip = "symbols" + +[lints.rust] +unsafe_code = "forbid" + +[lints.clippy] +all = { level = "warn", priority = -2 } +pedantic = { level = "warn", priority = -2 } +perf = { level = "warn", priority = -1 } +complexity = { level = "warn", priority = -1 } +inline_always = "allow" +unseparated_literal_suffix = "allow" +similar_names = "allow" +missing_panics_doc = "allow" +missing_errors_doc = "allow" +absolute_paths = "allow" +module_name_repetitions = "allow" +doc_markdown = "allow" +too_many_lines = "allow" +unused_self = "allow" +cast_possible_truncation = "allow" +cast_sign_loss = "allow" +cast_precision_loss = "allow" +unreadable_literal = "allow" +implicit_hasher = "allow" +significant_drop_tightening = "warn" +redundant_clone = "warn" +use_self = "warn" +redundant_else = "warn" +or_fun_call = "warn" +missing_const_for_fn = "warn" +derive_partial_eq_without_eq = "warn" diff --git a/tools/bui/README.md b/tools/bui/README.md new file mode 100644 index 00000000..6d86d26a --- /dev/null +++ b/tools/bui/README.md @@ -0,0 +1,50 @@ +# bui + +The `bui` command: makes, runs, checks and updates BUI apps in Rust, JavaScript, TypeScript, Python, +Lua and C. Docs: [the bui command](https://bui.preetham.top/start/bui-command/). + +```sh +curl -LsSf https://bui.preetham.top/install.sh | sh # Linux and macOS +irm https://bui.preetham.top/install.ps1 | iex # Windows (PowerShell) +bui new my-app +``` + +## Build and test + +It is its own Cargo workspace and needs no BUI code, so it builds in seconds: + +```sh +cd tools/bui +cargo build +cargo clippy --all-targets -- -D warnings +cargo test +``` + +## How it is organised + +- `src/flavours/`: one module per language (`rust`, `js`, `python`, `lua`, `c`). Each implements the + `Flavour` trait: the tools it needs, the files of a new project, the install steps (always the newest + versions), how it runs and builds, and its `doctor` checks. A language is a module there and a variant + of `project::Stack`. +- `templates/`: the files of new projects, laid over each other (`js/common` then `js/react-ts`). + `{{name}}`, `{{ident}}`, `{{title}}` and `{{tag}}` are filled in; a file named `_gitignore` is written as + `.gitignore` (a real one here would ignore the templates). +- `src/ui.rs`: everything the user sees (banner, prompts, spinners). Nothing else prints, so a terminal + without colors or a TTY falls back to plain lines in one place. +- `src/tools.rs`: toolchain detection and the commands that install each tool on each system. +- `src/doctor.rs`, `src/update.rs`, `src/create.rs`, `src/run.rs`: the commands. +- `src/registry.rs`: the newest versions (crates.io, npm, PyPI, and GitHub's release redirect, not its + rate-limited API). + +## Rules it follows + +- Nothing is installed or changed without an answer: a prompt, `--fix`, or `--install-tools`. Without a + terminal and without `--yes` a question stops the program instead of guessing. +- `BUI_RELEASE_TAG` and `BUI_DOWNLOAD_BASE` point `bui update` at another release or a mirror (used by the tests of + the update path); `BUI_INSTALLER_BASE_URL` does the same for the installers (and `BUI_LATEST_URL`, in `install.ps1`, replaces the page whose + redirect names the newest release). + +## Release + +`bui-.tar.gz` / `.zip` (with `.sha256`) are built for six targets by `.github/workflows/cli.yml` when a +release tag is pushed (`tools/release.py`), and the installers and `bui update` read them. diff --git a/tools/bui/src/check.rs b/tools/bui/src/check.rs new file mode 100644 index 00000000..36d2b82a --- /dev/null +++ b/tools/bui/src/check.rs @@ -0,0 +1,122 @@ +//! What `bui doctor` is made of: a check says how something is and, when it is not right, the work +//! that makes it right. + +use std::fs; +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +use crate::sys::{Cmd, semver}; +use crate::tools::Tool; +use crate::ui; + +/// One piece of work: a command, or a change to a file that no command can make portably. +pub enum Work { + Run(Cmd), + Rewrite { path: PathBuf, from: String, to: String }, +} + +impl Work { + /// What the user would type, or what changes. + pub fn display(&self) -> String { + match self { + Self::Run(c) => c.display(), + Self::Rewrite { path, from, to } => format!("edit {}: {from} -> {to}", path.display()), + } + } + + /// Does it under a spinner titled `title`; false when it failed (the reason was shown). + pub fn perform(&self, title: &str) -> Result { + match self { + Self::Run(cmd) => ui::run(title, cmd), + Self::Rewrite { path, from, to } => { + let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + fs::write(path, text.replacen(from.as_str(), to, 1)).with_context(|| format!("writing {}", path.display()))?; + ui::success(title); + Ok(true) + } + } + } +} + +/// Work that fixes a problem, and why it does. +pub struct Fix { + pub why: String, + pub work: Vec, + /// An installer: it gets the terminal (it may ask for a password) instead of a spinner. + pub interactive: bool, +} + +impl Fix { + pub fn run(why: &str, cmds: Vec) -> Self { + Self { why: why.to_owned(), work: cmds.into_iter().map(Work::Run).collect(), interactive: false } + } + + pub fn install(why: &str, cmds: Vec) -> Self { + Self { interactive: true, ..Self::run(why, cmds) } + } + + pub const fn edit(why: String, work: Vec) -> Self { + Self { why, work, interactive: false } + } +} + +pub enum Health { + Ok(String), + /// Works, but should be better (an old version). + Warn(String, Option), + /// Does not work. + Fail(String, Option), +} + +pub struct Check { + pub name: String, + pub health: Health, +} + +impl Check { + pub fn ok(name: &str, detail: impl Into) -> Self { + Self { name: name.to_owned(), health: Health::Ok(detail.into()) } + } + + pub fn warn(name: &str, detail: impl Into, fix: Option) -> Self { + Self { name: name.to_owned(), health: Health::Warn(detail.into(), fix) } + } + + pub fn fail(name: &str, detail: impl Into, fix: Option) -> Self { + Self { name: name.to_owned(), health: Health::Fail(detail.into(), fix) } + } + + pub const fn is_ok(&self) -> bool { + matches!(self.health, Health::Ok(_)) + } + + pub const fn fix(&self) -> Option<&Fix> { + match &self.health { + Health::Warn(_, f) | Health::Fail(_, f) => f.as_ref(), + Health::Ok(_) => None, + } + } +} + +/// A tool is installed, or here is how to install the newest. +pub fn tool(t: Tool) -> Check { + match t.probe() { + Some(v) => Check::ok(t.label(), v), + None => Check::fail( + t.label(), + "not installed", + Some(Fix::install(&format!("installs the newest {}", t.label()), t.install().cmds)), + ), + } +} + +/// `have` is the newest version, or here is how to get it. A registry that could not be reached is not +/// a problem. +pub fn newest(name: &str, have: &str, latest: Option<&str>, fix: Fix) -> Check { + match latest { + Some(l) if semver(l) > semver(have) => Check::warn(name, format!("{have}, newest is {l}"), Some(fix)), + Some(_) => Check::ok(name, format!("{have} (newest)")), + None => Check::ok(name, format!("{have} (could not look up the newest)")), + } +} diff --git a/tools/bui/src/cli.rs b/tools/bui/src/cli.rs new file mode 100644 index 00000000..afa1bb7d --- /dev/null +++ b/tools/bui/src/cli.rs @@ -0,0 +1,161 @@ +//! The command line: what `bui --help` shows. + +use clap::{Args, Parser, Subcommand, ValueEnum}; +use clap_complete::Shell; + +use crate::project::{Framework, Language, PackageManager, PyApi}; + +const EXAMPLES: &str = "\ +Examples: + bui new my-app make an app, asking what to use + bui new my-app -l js --framework react --typescript --pm bun -y + make a React app without any question + bui dev run it (reloads when you save) + bui dev -- --release anything after -- goes to the tool underneath + bui build make a release build + bui doctor --fix find what is wrong and fix it + bui update --check see what is out of date + bui update --cli-only update bui itself, leave the app's packages + +Docs: https://bui.preetham.top (or run: bui docs)"; + +#[derive(Parser)] +#[command( + name = "bui", + bin_name = "bui", + version, + about = "Create, run, check and update BUI apps", + propagate_version = true, + after_help = EXAMPLES, + arg_required_else_help = false +)] +pub struct Cli { + #[command(subcommand)] + pub command: Option, + + /// No animation and no colors (this is automatic without a terminal, in CI, or with NO_COLOR) + #[arg(long, global = true)] + pub plain: bool, + + /// Answer every question with its default, and ask nothing + #[arg(short, long, global = true)] + pub yes: bool, + + /// Install missing tools (Rust, Bun, uv, ...) without asking + #[arg(long, global = true)] + pub install_tools: bool, +} + +#[derive(Subcommand)] +pub enum Command { + /// Make an app in a new folder + New(NewArgs), + /// Make an app in this folder + Init(Choices), + /// Run the app (reloads when you save, where the language can) + Dev(RunArgs), + /// Make a release build + Build(RunArgs), + /// Check your setup and the app, and fix what is wrong + Doctor(DoctorArgs), + /// Update bui, then the app's BUI packages + Update(UpdateArgs), + /// Open the documentation in your browser + Docs, + /// Print shell completions (`bui completions bash > ~/.bui-completions.bash`) + Completions { + /// bash, zsh, fish, powershell or elvish + shell: Shell, + }, +} + +#[derive(Args)] +pub struct RunArgs { + /// Arguments for the tool underneath (cargo, your package manager, uv, cmake), after `--` + #[arg(last = true)] + pub args: Vec, +} + +#[derive(Args)] +pub struct NewArgs { + /// What to call the app (also its folder) + pub name: Option, + #[command(flatten)] + pub choices: Choices, +} + +/// What to make; anything you leave out is asked. +#[derive(Args, Default)] +#[allow(clippy::struct_excessive_bools)] // command-line switches +pub struct Choices { + /// The language to write it in + #[arg(short, long, value_enum)] + pub language: Option, + /// JavaScript: the framework + #[arg(long, value_enum)] + pub framework: Option, + /// JavaScript: use TypeScript + #[arg(long, conflicts_with = "javascript")] + pub typescript: bool, + /// JavaScript: use plain JavaScript + #[arg(long)] + pub javascript: bool, + /// JavaScript: the runtime and package manager + #[arg(long, value_enum)] + pub pm: Option, + /// Python: the style of UI code to write + #[arg(long, value_enum)] + pub api: Option, + /// Do not install dependencies + #[arg(long)] + pub no_install: bool, + /// Do not start a git repository + #[arg(long)] + pub no_git: bool, +} + +impl Choices { + /// `--typescript` or `--javascript`, when one was given. + pub const fn language_choice(&self) -> Option { + if self.typescript { + Some(Language::TypeScript) + } else if self.javascript { + Some(Language::JavaScript) + } else { + None + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum Lang { + Rust, + #[value(alias = "javascript", alias = "typescript", alias = "ts")] + Js, + Python, + Lua, + C, +} + +#[derive(Args)] +pub struct DoctorArgs { + /// Check every language's tools, not only this app's + #[arg(long)] + pub all: bool, + /// Run the fixes without asking + #[arg(long)] + pub fix: bool, + /// Print the results as JSON and change nothing + #[arg(long)] + pub json: bool, +} + +#[derive(Args)] +pub struct UpdateArgs { + /// Only say what is out of date + #[arg(long)] + pub check: bool, + /// Update bui itself only, not the packages of the app you are in + #[arg(long, conflicts_with = "check")] + pub cli_only: bool, +} diff --git a/tools/bui/src/create.rs b/tools/bui/src/create.rs new file mode 100644 index 00000000..c9375dcf --- /dev/null +++ b/tools/bui/src/create.rs @@ -0,0 +1,290 @@ +//! `bui new` and `bui init`: ask what to make, make sure its tools are there, say what will be installed +//! and ask, write the project, and install the newest BUI and tooling with the language's own +//! package manager. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use anyhow::{Result, bail}; + +use crate::cli::{Choices, Lang, NewArgs}; +use crate::flavours::{File, Step, Vars}; +use crate::flavours::{c::CApp, js::JsApp, lua::LuaApp, python::PythonApp, rust::RustApp}; +use crate::project::{FILE, Framework, Language, Meta, PackageManager, PyApi, Stack}; +use crate::sys::{Cmd, which}; +use crate::ui::{self, choice}; +use crate::{registry, tools}; + +pub fn new(args: NewArgs) -> Result<()> { + ui::banner(true); + ui::intro("Let's make an app"); + let name = match args.name { + Some(n) => n, + None => ui::input("What do you want to call it?", "my-app", |s| bad_name(s.as_str()))?, + }; + if let Some(problem) = bad_name(&name) { + bail!("{problem}"); + } + let dir = std::env::current_dir()?.join(&name); + if dir.exists() && fs::read_dir(&dir)?.next().is_some() { + bail!( + "{} already exists and has files in it. Pick another name, or go into that folder and run `bui init`.", + dir.display() + ); + } + make(&name, &dir, &args.choices, true) +} + +pub fn init(choices: &Choices) -> Result<()> { + ui::banner(true); + ui::intro("Add a BUI app to this folder"); + let dir = std::env::current_dir()?; + if dir.join(FILE).exists() { + bail!("this folder is already a BUI app ({FILE} is here). Run `bui doctor` to check it."); + } + let raw = dir.file_name().map_or_else(|| "app".into(), |n| n.to_string_lossy().into_owned()); + make(&sanitize(&raw), &dir, choices, false) +} + +/// A folder name as an app name: lowercase letters, digits, `-` and `_`. +fn sanitize(raw: &str) -> String { + let s: String = raw.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c.to_ascii_lowercase() } else { '-' }).collect(); + let s = s.trim_matches('-').to_owned(); + if s.is_empty() || s.starts_with(|c: char| c.is_ascii_digit()) { format!("app-{s}") } else { s } +} + +fn bad_name(name: &str) -> Option { + let ok = !name.is_empty() + && name.starts_with(|c: char| c.is_ascii_lowercase()) + && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_'); + (!ok).then(|| "Use lowercase letters, digits, - and _, starting with a letter (for example my-app).".to_owned()) +} + +fn make(name: &str, dir: &Path, choices: &Choices, new_folder: bool) -> Result<()> { + let started = Instant::now(); + let stack = ask(choices)?; + let app = stack.app(); + ui::info(format!("Setting up {}", ui::accent(&app.label()))); + + // the tools the language needs, offered for install when missing + let missing = tools::ensure(&app.tools())?; + + // what will be installed, said and asked before anything is written + let steps = app.deps(dir); + let install_now = if choices.no_install { + false + } else if !missing.is_empty() { + ui::warn("I can't install the packages until those tools are there. `bui doctor` will do it once they are."); + false + } else { + ui::note("I'll install the newest versions of", &step_list(&steps)); + ui::confirm("Install them now?", true)? + }; + + // the files that are there already, made to fit (a manifest that cannot be read stops here, with nothing written) + let adopted = app.adopt(dir)?; + let writing = ui::task("Writing your app"); + fs::create_dir_all(dir)?; + let mut files = app.files(&Vars::new(name, &release_tag())); + files.push(File { path: FILE.into(), body: Meta { name: name.to_owned(), stack: stack.clone() }.to_toml()? }); + let (wrote, mut skipped) = write_files(dir, files)?; + skipped.retain(|f| !adopted.iter().any(|a| a.path == f)); + writing.done(&format!("Wrote {wrote} files")); + for a in &adopted { + ui::success(format!("{}: {}", a.path, a.note)); + } + if !skipped.is_empty() { + ui::warn(format!("Left your existing {} as it was", skipped.join(", "))); + } + + git_init(dir, choices.no_git)?; + + if !(install_now && install(&steps)?) { + ui::info(format!("Install the packages later with {}", ui::code("bui doctor"))); + } + + ui::note("What's next", &next_steps(name, new_folder)); + ui::outro(&format!("{} {name} is ready {}", ui::accent("✦"), ui::dim(&format!("({})", took(started))))); + Ok(()) +} + +/// The newest BUI release, as a git tag (for the C template; the others install through their package manager). +fn release_tag() -> String { + registry::bui_version().map_or_else(|| format!("v{}", env!("CARGO_PKG_VERSION")), |v| format!("v{v}")) +} + +/// The install steps with the command each runs. +fn step_list(steps: &[Step]) -> String { + steps.iter().map(|s| format!("{}\n $ {}", s.title, ui::code(&s.work.display()))).collect::>().join("\n") +} + +/// Every command, so there is nothing to look up afterwards. +fn next_steps(name: &str, new_folder: bool) -> String { + let mut lines = Vec::new(); + if new_folder { + lines.push(format!("$ {}", ui::code(&format!("cd {name}")))); + } + for (cmd, what) in [ + ("bui dev", "run it (reloads when you save)"), + ("bui build", "make a release build"), + ("bui doctor", "check your setup and fix what is wrong"), + ("bui update", "get newer versions"), + ("bui docs", "open the documentation"), + ] { + lines.push(format!("$ {} {}", ui::code(&format!("{cmd:<11}")), ui::dim(what))); + } + lines.push(String::new()); + lines.push(ui::dim("Every command takes --help for its options.")); + lines.join("\n") +} + +fn took(started: Instant) -> String { + let s = started.elapsed().as_secs(); + if s < 60 { format!("took {s}s") } else { format!("took {}m {}s", s / 60, s % 60) } +} + +/// Writes the files that are not there yet; returns how many it wrote and which it left alone. +fn write_files(dir: &Path, files: Vec) -> Result<(usize, Vec)> { + let mut wrote = 0; + let mut skipped = Vec::new(); + for f in files { + let path: PathBuf = dir.join(&f.path); + if path.exists() { + skipped.push(f.path); + continue; + } + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&path, f.body)?; + wrote += 1; + } + Ok((wrote, skipped)) +} + +/// The language, and that language's choices: each question can be answered by a flag. +fn ask(c: &Choices) -> Result { + let lang = ui::select( + "Which language do you want to use?", + &[ + choice(Lang::Rust, "Rust".into(), "Builders like GPUI, or HTML and Tailwind"), + choice(Lang::Js, "JavaScript or TypeScript".into(), "React, Svelte or plain DOM"), + choice(Lang::Python, "Python".into(), "Blender's components, or Qt or tkinter style"), + choice(Lang::Lua, "Lua".into(), "Small, quick to start"), + choice(Lang::C, "C".into(), "BUI's own API, built with CMake"), + ], + c.language.as_ref(), + )?; + Ok(match lang { + Lang::Rust => Stack::Rust(RustApp {}), + Lang::Lua => Stack::Lua(LuaApp {}), + Lang::C => Stack::C(CApp {}), + Lang::Python => Stack::Python(PythonApp { + api: ui::select( + "How do you want to write the UI?", + &[ + choice(PyApi::Components, "Blender's components".into(), "Panels, sliders, color swatches: Blender's own look"), + choice(PyApi::Qt, "Qt style".into(), "Qt code where only the import changes (no PySide needed)"), + choice(PyApi::Tk, "tkinter style".into(), "tkinter code where only the import changes"), + ], + c.api.as_ref(), + )?, + }), + Lang::Js => ask_js(c)?, + }) +} + +fn ask_js(c: &Choices) -> Result { + let framework = ui::select( + "Which framework?", + &[ + choice(Framework::React, "React".into(), "React 19: components and hooks"), + choice(Framework::Svelte, "Svelte".into(), "Svelte 5: runes (runs on Node.js)"), + choice(Framework::Vanilla, "None".into(), "BUI's own DOM-like API"), + ], + c.framework.as_ref(), + )?; + // Svelte files are compiled by BUI's loader and written in plain JavaScript + let language = if framework == Framework::Svelte { + Language::JavaScript + } else { + ui::select( + "Do you want TypeScript?", + &[ + choice(Language::TypeScript, "Yes, TypeScript".into(), "recommended: catches mistakes while you type"), + choice(Language::JavaScript, "No, plain JavaScript".into(), ""), + ], + c.language_choice().as_ref(), + )? + }; + if framework == Framework::Svelte && c.pm == Some(PackageManager::Bun) { + bail!("Svelte runs on Node.js (its loader does not work under Bun yet): use --pm npm or --pm pnpm"); + } + let have = |bin: &str| if which(bin).is_some() { "installed" } else { "not installed yet: I can install it" }; + let mut runtimes = vec![ + choice(PackageManager::Npm, "Node.js with npm".into(), have("node")), + choice(PackageManager::Pnpm, "Node.js with pnpm".into(), have("pnpm")), + ]; + // Svelte's loader runs on Node only (it fails under Bun) + if framework != Framework::Svelte { + runtimes.insert(0, choice(PackageManager::Bun, "Bun".into(), format!("fastest, runs TypeScript directly; {}", have("bun")))); + } + let pm = ui::select("Which runtime and package manager?", &runtimes, c.pm.as_ref())?; + Ok(Stack::Js(JsApp { framework, language, pm })) +} + +fn git_init(dir: &Path, skip: bool) -> Result<()> { + if skip || which("git").is_none() || Cmd::new("git", ["rev-parse", "--git-dir"]).in_dir(dir).capture().is_some() { + return Ok(()); + } + if ui::confirm("Start a git repository?", true)? { + ui::run("Starting a git repository", &Cmd::new("git", ["init", "--quiet"]).in_dir(dir))?; + } + Ok(()) +} + +/// Runs the install steps; stops at the first that fails and says how to finish by hand. +fn install(steps: &[Step]) -> Result { + for (i, s) in steps.iter().enumerate() { + if !s.work.perform(&s.title)? { + if s.optional { + ui::info("That one is optional: your app works without it."); + continue; + } + let rest: Vec = steps[i..].iter().map(|s| ui::code(&s.work.display())).collect(); + ui::warn(format!("Finish the install later with:\n {}", rest.join("\n "))); + return Ok(false); + } + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_are_checked() { + assert!(bad_name("my-app").is_none()); + assert!(bad_name("app_2").is_none()); + for bad in ["", "My-App", "2fast", "-x", "a b", "a/b"] { + assert!(bad_name(bad).is_some(), "{bad}"); + } + } + + #[test] + fn a_folder_name_becomes_an_app_name() { + assert_eq!(sanitize("My App"), "my-app"); + assert_eq!(sanitize("2048"), "app-2048"); + assert_eq!(sanitize("__x__"), "__x__"); + } + + #[test] + fn the_next_steps_name_every_command() { + let text = console::strip_ansi_codes(&next_steps("demo", true)).into_owned(); + for cmd in ["cd demo", "bui dev", "bui build", "bui doctor", "bui update", "bui docs"] { + assert!(text.contains(cmd), "{cmd} missing from {text}"); + } + } +} diff --git a/tools/bui/src/doctor.rs b/tools/bui/src/doctor.rs new file mode 100644 index 00000000..9b9880a7 --- /dev/null +++ b/tools/bui/src/doctor.rs @@ -0,0 +1,184 @@ +//! `bui doctor`: look at what the current project needs (and only that, unless asked for all), say what +//! is wrong in a line each, and offer to run the fixes. + +use std::path::Path; +use std::process::ExitCode; + +use anyhow::Result; +use serde_json::json; + +use crate::check::{self, Check, Fix, Health, Work}; +use crate::cli::DoctorArgs; +use crate::project; +use crate::registry; +use crate::sys::{Cmd, OS, Os, semver}; +use crate::tools::Tool; +use crate::ui; + +/// Every toolchain bui knows, for `--all` and for a folder that is not a project. +const ALL: [Tool; 9] = + [Tool::Rust, Tool::Cc, Tool::Cmake, Tool::Bun, Tool::Node, Tool::Uv, Tool::Lua, Tool::Luarocks, Tool::Git]; + +struct Section { + title: String, + checks: Vec, +} + +pub fn run(args: &DoctorArgs) -> Result { + if !args.json { + ui::banner(false); + ui::intro("bui doctor"); + } + let project = project::find(Path::new(".")); + let mut sections = gather(project.as_ref(), args.all); + if args.json { + print_json(§ions); + return Ok(exit_code(§ions)); + } + show(§ions); + let fixable: Vec<&Fix> = sections.iter().flat_map(|s| &s.checks).filter_map(Check::fix).collect(); + if fixable.is_empty() { + return Ok(finish(§ions)); + } + let list: Vec = fixable + .iter() + .enumerate() + .map(|(i, f)| { + let cmds: Vec = f.work.iter().map(|w| format!(" $ {}", ui::code(&w.display()))).collect(); + format!("{}. {}\n{}", i + 1, f.why, cmds.join("\n")) + }) + .collect(); + ui::note("What would fix it", &list.join("\n")); + if args.fix || (ui::asking() && ui::confirm(&format!("Run {} fix{} now?", fixable.len(), if fixable.len() == 1 { "" } else { "es" }), true)?) { + for fix in &fixable { + for w in &fix.work { + if !perform(fix, w)? { + break; + } + } + } + // look again: a fix may have fixed more than it said, or not worked + ui::info("Checking again"); + sections = gather(project.as_ref(), args.all); + show(§ions); + } + Ok(finish(§ions)) +} + +fn perform(fix: &Fix, work: &Work) -> Result { + match work { + // an installer may ask for a password or show its own progress: give it the terminal + Work::Run(cmd) if fix.interactive => { + ui::flush(); + let ok = cmd.run_inherit()?.success(); + if !ok { + ui::error(format!("`{}` failed", cmd.display())); + } + Ok(ok) + } + w => w.perform(&fix.why), + } +} + +fn gather(project: Option<&project::Project>, all: bool) -> Vec
{ + let task = ui::task("Looking around"); + let mut sections = vec![Section { title: "bui".into(), checks: bui_checks() }]; + if let Some(p) = project { + let app = p.meta.stack.app(); + task.set("Checking the toolchain"); + sections.push(Section { title: format!("{} ({})", p.meta.name, app.label()), checks: Vec::new() }); + let toolchain: Vec = app.build_tools().into_iter().map(check::tool).collect(); + let toolchain_ok = toolchain.iter().all(Check::is_ok); + let mut checks = toolchain; + // a project's own checks need its tools (they run them) + if toolchain_ok { + task.set("Checking the project"); + checks.extend(app.checks(&p.dir)); + } + if let Some(s) = sections.last_mut() { + s.checks = checks; + } + if !p.declared { + ui::flush(); + } + } + if all || project.is_none() { + task.set("Checking every toolchain"); + sections.push(Section { title: "Toolchains".into(), checks: ALL.into_iter().map(check::tool).collect() }); + } + if OS == Os::Linux && std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() { + sections.push(Section { + title: "Display".into(), + checks: vec![Check::warn("window system", "no DISPLAY or WAYLAND_DISPLAY: windows cannot open here (SSH? WSL without WSLg?). Headless rendering still works.", None)], + }); + } + let bad = sections.iter().flat_map(|s| &s.checks).filter(|c| !c.is_ok()).count(); + task.done(&if bad == 0 { "Checked".to_owned() } else { format!("Checked: {bad} to look at") }); + sections +} + +/// This `bui` against the newest release. +fn bui_checks() -> Vec { + let have = env!("CARGO_PKG_VERSION"); + let exe = std::env::current_exe().map_or_else(|_| "bui".into(), |p| p.to_string_lossy().into_owned()); + let fix = Fix::run("updates bui", vec![Cmd::new(&exe, ["update", "--yes", "--cli-only"])]); + match registry::release_tag() { + Some(tag) if semver(&tag) > semver(have) => vec![Check::warn("bui", format!("{have}, newest is {}", tag.trim_start_matches('v')), Some(fix))], + Some(_) => vec![Check::ok("bui", format!("{have} (newest)"))], + None => vec![Check::ok("bui", format!("{have} (no newer release found, or offline)"))], + } +} + +/// One check as a line. +pub fn line(c: &Check) -> String { + match &c.health { + Health::Ok(d) => format!("{} {} {}", console::style("✔").green(), c.name, ui::dim(d)), + Health::Warn(d, _) => format!("{} {} {}", console::style("▲").yellow(), c.name, d), + Health::Fail(d, _) => format!("{} {} {}", console::style("✘").red(), c.name, d), + } +} + +fn show(sections: &[Section]) { + for s in sections { + let lines: Vec = s.checks.iter().map(line).collect(); + ui::note(&s.title, &lines.join("\n")); + } +} + +fn finish(sections: &[Section]) -> ExitCode { + let bad = sections.iter().flat_map(|s| &s.checks).filter(|c| matches!(c.health, Health::Fail(..))).count(); + let warn = sections.iter().flat_map(|s| &s.checks).filter(|c| matches!(c.health, Health::Warn(..))).count(); + match (bad, warn) { + (0, 0) => ui::outro(&format!("{} All good", ui::accent("✦"))), + (0, w) => ui::outro(&format!("Works, with {w} thing{} to look at", if w == 1 { "" } else { "s" })), + (b, _) => ui::outro(&format!("{b} problem{} left", if b == 1 { "" } else { "s" })), + } + exit_code(sections) +} + +fn exit_code(sections: &[Section]) -> ExitCode { + if sections.iter().flat_map(|s| &s.checks).any(|c| matches!(c.health, Health::Fail(..))) { ExitCode::FAILURE } else { ExitCode::SUCCESS } +} + +fn print_json(sections: &[Section]) { + let out: Vec<_> = sections + .iter() + .map(|s| { + let checks: Vec<_> = s + .checks + .iter() + .map(|c| { + let (status, detail) = match &c.health { + Health::Ok(d) => ("ok", d), + Health::Warn(d, _) => ("warn", d), + Health::Fail(d, _) => ("fail", d), + }; + let fix: Vec = c.fix().map(|f| f.work.iter().map(Work::display).collect()).unwrap_or_default(); + json!({ "name": c.name, "status": status, "detail": detail, "fix": fix }) + }) + .collect(); + json!({ "section": s.title, "checks": checks }) + }) + .collect(); + println!("{}", serde_json::to_string_pretty(&out).unwrap_or_default()); +} diff --git a/tools/bui/src/flavours/c.rs b/tools/bui/src/flavours/c.rs new file mode 100644 index 00000000..83c55d7f --- /dev/null +++ b/tools/bui/src/flavours/c.rs @@ -0,0 +1,234 @@ +//! C: CMake fetching BUI at a release tag, clang-format and clang-tidy configured. + +use std::path::Path; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use super::{File, Flavour, Step, Vars, read, render, step, work_step}; +use crate::check::{Check, Fix, Work}; +use crate::registry; +use crate::sys::{Cmd, semver}; +use crate::tools::Tool; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CApp {} + +fn cmake(dir: &Path, args: &[&str]) -> Cmd { + Cmd::new("cmake", args.iter().copied()).in_dir(dir) +} + +/// `text` lower-cased, with the comments (`# ...` and `#[[ ... ]]`) blanked to spaces. Every byte offset stays the +/// same, so a position found here slices `text`. A `#` inside a quoted or bracket argument is not a comment. +fn mask(text: &str) -> String { + let src = text.as_bytes(); + let mut out = src.to_ascii_lowercase(); + // the length of a bracket opener `[==[` at `i` (its `=` count + 2), if there is one + let bracket = |i: usize| -> Option { + let eq = src[i + 1..].iter().take_while(|&&b| b == b'=').count(); + (src.get(i) == Some(&b'[') && src.get(i + 1 + eq) == Some(&b'[')).then_some(eq + 2) + }; + // the end of a bracket body that opened with `eq` signs, from `i` + let close = |i: usize, eq: usize| -> usize { + let mut shut = vec![b']']; + shut.extend(std::iter::repeat_n(b'=', eq)); + shut.push(b']'); + src[i..].windows(shut.len()).position(|w| w == shut.as_slice()).map_or(src.len(), |at| i + at + shut.len()) + }; + let mut i = 0; + while i < src.len() { + match src[i] { + b'"' => { + i += 1; + while i < src.len() && src[i] != b'"' { + i += if src[i] == b'\\' { 2 } else { 1 }; + } + i += 1; + } + b'[' if bracket(i).is_some() => i = close(i + bracket(i).unwrap_or(2), bracket(i).unwrap_or(2) - 2), + b'#' => { + let end = match bracket(i + 1) { + Some(n) => close(i + 1 + n, n - 2), + None => src[i..].iter().position(|&b| b == b'\n').map_or(src.len(), |at| i + at), + }; + for b in &mut out[i..end.min(src.len())] { + if *b != b'\n' && *b != b'\r' { + *b = b' '; + } + } + i = end; + } + _ => i += 1, + } + } + String::from_utf8(out).unwrap_or_else(|_| text.to_ascii_lowercase()) +} + +/// BUI's own `FetchContent_Declare(...)` in a CMakeLists: the text up to where its tag begins, and the +/// tag (`v0.5.1`). Other dependencies' blocks have tags of their own, which are not ours to read or move. +fn bui_pin(text: &str) -> Option<(&str, &str)> { + const DECLARE: &str = "fetchcontent_declare"; + let lower = mask(text); // a commented-out tag is not the tag + let mut from = 0; + while let Some(i) = lower[from..].find(DECLARE) { + let start = from + i; + let after = start + DECLARE.len(); + let open = lower[after..].trim_start_matches([' ', '\t']); + if !open.starts_with('(') { + from = after; + continue; + } + let body = lower.len() - open.len() + 1; + let end = lower[body..].find(')').map_or(text.len(), |j| body + j); + from = end; + let block = &lower[body..end]; + let name = block.split_whitespace().next().unwrap_or_default(); + if !(matches!(name, "bui" | "blender-ui" | "blenderui") || block.contains("ppmpreetham/bui")) { + continue; + } + let key = lower[start..end].find("git_tag")? + "git_tag".len(); + let rest = &lower[start + key..end]; // found in the masked text, a comment between key and value is blank + let tag_at = start + key + (rest.len() - rest.trim_start().len()); + let tag_len = lower[tag_at..end].split_whitespace().next()?.len(); + let tag = &text[tag_at..tag_at + tag_len]; + return Some((&text[start..tag_at], tag)); + } + None +} + +/// The release tag `CMakeLists.txt` fetches BUI at. +fn pinned_tag(dir: &Path) -> Option { + bui_pin(&read(dir, "CMakeLists.txt")?).map(|(_, tag)| tag.to_owned()) +} + +/// The edit that moves BUI's tag to `to`: it spans from BUI's declaration, so it cannot land on another dependency's tag. +fn move_tag(dir: &Path, to: &str) -> Option { + let text = read(dir, "CMakeLists.txt")?; + let (head, tag) = bui_pin(&text)?; + Some(Work::Rewrite { path: dir.join("CMakeLists.txt"), from: format!("{head}{tag}"), to: format!("{head}{to}") }) +} + +impl Flavour for CApp { + fn label(&self) -> String { + "C".into() + } + + fn tools(&self) -> Vec { + vec![Tool::Cc, Tool::Cmake, Tool::Git] + } + + fn files(&self, vars: &Vars) -> Vec { + render(&["c"], vars) + } + + fn deps(&self, dir: &Path) -> Vec { + vec![step( + "Fetching and building BUI once (a few minutes now, seconds after)", + cmake(dir, &["--workflow", "--preset", "default"]), + )] + } + + fn dev(&self, dir: &Path, args: &[String]) -> Result> { + let exe = dir.join("build/bin").join(if cfg!(windows) { "app.exe" } else { "app" }); + Ok(vec![ + cmake(dir, &["--preset", "default"]), + cmake(dir, &["--build", "--preset", "default"]), + Cmd::new(&exe.to_string_lossy(), Vec::::new()).in_dir(dir).with_args(args), + ]) + } + + fn build(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![cmake(dir, &["--preset", "default"]), cmake(dir, &["--build", "--preset", "release"]).with_args(args)]) + } + + fn checks(&self, dir: &Path) -> Vec { + let Some(have) = pinned_tag(dir) else { + return vec![Check::fail("BUI version", "CMakeLists.txt has no BUI FetchContent_Declare with a GIT_TAG", None)]; + }; + let latest = registry::bui_version().map(|v| format!("v{v}")); + match latest { + Some(l) if semver(&l) > semver(&have) => { + let fix = move_tag(dir, &l).map(|w| Fix::edit(format!("moves BUI's GIT_TAG to {l}"), vec![w])); + vec![Check::warn("BUI release", format!("{have}, newest is {l}"), fix)] + } + Some(_) => vec![Check::ok("BUI release", format!("{have} (newest)"))], + None => vec![Check::ok("BUI release", format!("{have} (could not look up the newest)"))], + } + } + + fn update(&self, dir: &Path) -> Vec { + let Some(latest) = registry::bui_version().map(|v| format!("v{v}")) else { + return Vec::new(); + }; + move_tag(dir, &latest).map(|work| work_step("Moving BUI to the newest release", work)).into_iter().collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const TWO: &str = "include(FetchContent) +FetchContent_Declare( + fmt + GIT_REPOSITORY https://github.com/fmtlib/fmt.git + GIT_TAG v0.5.1) +fetchcontent_declare( + bui + GIT_REPOSITORY https://github.com/ppmpreetham/BUI.git + GIT_TAG v0.5.1 + GIT_SHALLOW TRUE) +"; + + #[test] + fn the_tag_is_read_from_buis_own_declaration() { + let (_, tag) = bui_pin(TWO).unwrap(); + assert_eq!(tag, "v0.5.1"); + let other = TWO.replace("GIT_TAG v0.5.1 + GIT_SHALLOW", "GIT_TAG v0.6.0 + GIT_SHALLOW"); + assert_eq!(bui_pin(&other).unwrap().1, "v0.6.0", "not the first dependency's"); + assert!(bui_pin("FetchContent_Declare(fmt GIT_TAG 1)").is_none()); + } + + #[test] + fn moving_the_tag_leaves_other_dependencies_alone() { + let dir = std::env::temp_dir().join(format!("bui-c-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("CMakeLists.txt"), TWO).unwrap(); + let work = move_tag(&dir, "v0.9.0").unwrap(); + assert!(work.perform("test").unwrap()); + let text = std::fs::read_to_string(dir.join("CMakeLists.txt")).unwrap(); + assert_eq!(text, TWO.replacen("GIT_TAG v0.5.1 + GIT_SHALLOW", "GIT_TAG v0.9.0 + GIT_SHALLOW", 1)); + assert_eq!(pinned_tag(&dir).as_deref(), Some("v0.9.0")); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn spaces_before_the_parenthesis_and_comments_are_cmake_syntax() { + let text = "FetchContent_Declare (bui # the \u{e9}tag below\n GIT_REPOSITORY https://github.com/ppmpreetham/BUI.git\n # GIT_TAG v0.4.0\n GIT_TAG v0.5.1)\n"; + let (head, tag) = bui_pin(text).unwrap(); + assert_eq!(tag, "v0.5.1"); + assert!(head.ends_with("# GIT_TAG v0.4.0\n GIT_TAG ")); + } + + #[test] + fn a_hash_in_a_quoted_or_bracket_argument_is_not_a_comment() { + let text = "FetchContent_Declare(bui SOURCE_DIR \"bui#src \\\" #x\" GIT_TAG v0.5.1)\n"; + assert_eq!(bui_pin(text).unwrap().1, "v0.5.1"); + let text = "FetchContent_Declare(bui #[==[ GIT_TAG v0.1 ]] ]==] GIT_TAG v0.5.1 #[[ x\n GIT_TAG v0.2 ]])\n"; + assert_eq!(bui_pin(text).unwrap().1, "v0.5.1"); + let text = "FetchContent_Declare(bui SOURCE_DIR [[a#b]] GIT_TAG v0.5.1)\n"; + assert_eq!(bui_pin(text).unwrap().1, "v0.5.1"); + } + + #[test] + fn a_comment_between_the_key_and_the_value_is_skipped() { + let text = "FetchContent_Declare (bui\n GIT_TAG # pinned \u{e9}\n v0.5.1)\n"; + let (head, tag) = bui_pin(text).unwrap(); + assert_eq!(tag, "v0.5.1"); + assert!(head.ends_with("pinned \u{e9}\n ")); + } +} diff --git a/tools/bui/src/flavours/js.rs b/tools/bui/src/flavours/js.rs new file mode 100644 index 00000000..3f62e2e5 --- /dev/null +++ b/tools/bui/src/flavours/js.rs @@ -0,0 +1,358 @@ +//! JavaScript and TypeScript: React, Svelte or BUI's own DOM-like API, on Bun, npm or pnpm, with +//! Biome for lint and format and TypeScript's strict mode. + +use std::path::Path; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +use super::{Adopted, File, Flavour, Step, Vars, read, render, step}; +use crate::check::{self, Check, Fix}; +use crate::project::{Framework, Language, PackageManager}; +use crate::registry; +use crate::sys::Cmd; +use crate::tools::Tool; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct JsApp { + pub framework: Framework, + pub language: Language, + pub pm: PackageManager, +} + +impl PackageManager { + const fn bin(self) -> &'static str { + match self { + Self::Bun => "bun", + Self::Npm => "npm", + Self::Pnpm => "pnpm", + } + } + + /// `bun add` / `npm install` / `pnpm add`, with the packages at their newest versions. + fn add(self, dir: &Path, dev: bool, packages: &[&str]) -> Cmd { + let mut args: Vec<&str> = vec![match self { + Self::Npm => "install", + Self::Bun | Self::Pnpm => "add", + }]; + if dev { + args.push(if self == Self::Npm { "--save-dev" } else { "--dev" }); + } + args.extend_from_slice(packages); + Cmd::new(self.bin(), args).in_dir(dir) + } + + /// Runs a `package.json` script; npm and pnpm need `--` before the user's arguments. + fn run(self, dir: &Path, script: &str, args: &[String]) -> Cmd { + let mut cmd = Cmd::new(self.bin(), ["run", script]).in_dir(dir); + if !args.is_empty() && self != Self::Bun { + cmd = cmd.with_args(&["--".to_owned()]); + } + cmd.with_args(args) + } + + /// Everything the lock file names, at the newest version the ranges allow. + fn update(self, dir: &Path) -> Cmd { + Cmd::new(self.bin(), ["update"]).in_dir(dir) + } +} + +impl JsApp { + const fn typed(&self) -> bool { + matches!(self.language, Language::TypeScript) + } + + /// The script the app starts from. + const fn entry(&self) -> &'static str { + match (self.framework, self.language) { + (Framework::React, Language::TypeScript) => "src/main.tsx", + (Framework::React, Language::JavaScript) => "src/main.jsx", + (Framework::Svelte, _) | (Framework::Vanilla, Language::JavaScript) => "src/main.js", + (Framework::Vanilla, Language::TypeScript) => "src/main.ts", + } + } + + /// Run by `tsx` (TypeScript and JSX on Node): in CommonJS mode, as Node cannot import the named + /// exports of BUI's CommonJS packages from an ES module. + fn uses_tsx(&self) -> bool { + self.pm != PackageManager::Bun && self.framework != Framework::Svelte && (self.typed() || self.framework == Framework::React) + } + + /// The command that runs the entry, as `bun`, `tsx` or `node` do, with the Svelte loader where needed. + fn runner(&self, watch: bool) -> String { + let entry = self.entry(); + let flag = |on: &'static str| if watch { on } else { "" }; + match self.framework { + // @blender-ui/svelte's loader does not work under Bun (its compiler call fails there): Node runs it + Framework::Svelte => format!("node --import @blender-ui/svelte/register {}{entry}", flag("--watch ")), + _ if self.pm == PackageManager::Bun => format!("bun {}{entry}", flag("--watch ")), + _ if self.uses_tsx() => format!("tsx {}{entry}", flag("watch ")), + _ => format!("node {}{entry}", flag("--watch ")), + } + } + + /// The scripts `bui dev`, `bui build` and the formatting step run through the package manager. + fn scripts(&self) -> serde_json::Map { + let mut scripts = serde_json::Map::new(); + let mut put = |k: &str, v: String| { + scripts.insert(k.into(), json!(v)); + }; + put("dev", self.runner(true)); + put("start", self.runner(false)); + put("build", format!("bui build {}", self.entry())); + if self.typed() { + put("typecheck", "tsc --noEmit".into()); + } + put("lint", "biome check .".into()); + put("format", "biome format --write .".into()); + put("fix", "biome check --write .".into()); + scripts + } + + fn package_json(&self, name: &str) -> String { + let mut doc = json!({ + "name": name, + "version": "0.1.0", + "private": true, + "scripts": self.scripts(), + }); + if !self.uses_tsx() { + doc["type"] = json!("module"); + } + format!("{}\n", serde_json::to_string_pretty(&doc).unwrap_or_default()) + } + + fn tsconfig(&self) -> String { + let types = if self.pm == PackageManager::Bun { "bun" } else { "node" }; + let mut options = json!({ + "target": "ES2023", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noUncheckedIndexedAccess": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "skipLibCheck": true, + "noEmit": true, + "types": [types], + }); + if self.framework == Framework::React { + options["jsx"] = json!("react-jsx"); + options["jsxImportSource"] = json!("@blender-ui/react"); + } + format!("{}\n", serde_json::to_string_pretty(&json!({ "compilerOptions": options, "include": ["src"] })).unwrap_or_default()) + } + + fn packages(&self) -> (Vec<&'static str>, Vec<&'static str>) { + let mut prod = vec!["@blender-ui/native"]; + match self.framework { + Framework::React => prod.extend(["@blender-ui/react", "react"]), + Framework::Svelte => prod.extend(["@blender-ui/svelte", "svelte"]), + Framework::Vanilla => {} + } + let mut dev = vec!["@biomejs/biome"]; + if self.typed() { + dev.extend(["typescript", if self.pm == PackageManager::Bun { "@types/bun" } else { "@types/node" }]); + if self.framework == Framework::React { + dev.push("@types/react"); + } + } + if self.uses_tsx() { + dev.push("tsx"); + } + (prod, dev) + } +} + +impl Flavour for JsApp { + fn label(&self) -> String { + let fw = match self.framework { + Framework::React => "React", + Framework::Svelte => "Svelte", + Framework::Vanilla => "plain DOM", + }; + let lang = if self.typed() { "TypeScript" } else { "JavaScript" }; + format!("{fw} + {lang} on {}", self.pm.bin()) + } + + fn tools(&self) -> Vec { + let mut tools = match self.pm { + PackageManager::Bun => vec![Tool::Bun], + PackageManager::Npm => vec![Tool::Node], + PackageManager::Pnpm => vec![Tool::Node, Tool::Pnpm], + }; + if self.framework == Framework::Svelte && !tools.contains(&Tool::Node) { + tools.push(Tool::Node); + } + tools + } + + /// `@blender-ui/native`'s `bui` bundles with Bun (bindings/node/bundle.js has no other path), whatever runs the app. + fn build_tools(&self) -> Vec { + let mut tools = self.tools(); + if !tools.contains(&Tool::Bun) { + tools.push(Tool::Bun); + } + tools + } + + /// An existing `package.json` keeps everything it has; the scripts the commands run are added when absent. + fn adopt(&self, dir: &Path) -> Result> { + let path = dir.join("package.json"); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e).with_context(|| format!("reading {}: fix it first, then run `bui init` again", path.display())), + }; + let mut doc: serde_json::Value = serde_json::from_str(&text).with_context(|| format!("{} is not valid JSON: fix it first, then run `bui init` again", path.display()))?; + let Some(root) = doc.as_object_mut() else { + bail!("{} is not a JSON object: fix it first, then run `bui init` again", path.display()); + }; + if self.uses_tsx() && root.get("type").and_then(serde_json::Value::as_str) == Some("module") { + bail!( + "{} has \"type\": \"module\", and `tsx` would then load the entry as an ES module, where Node cannot import the named exports of the CommonJS @blender-ui/react that way: remove \"type\" (or pick JavaScript, or another framework), then run `bui init` again", + path.display() + ); + } + let scripts = root.entry("scripts").or_insert_with(|| json!({})); + let Some(scripts) = scripts.as_object_mut() else { + bail!("\"scripts\" in {} is not an object: fix it first, then run `bui init` again", path.display()); + }; + let mut added = Vec::new(); + for (name, command) in self.scripts() { + if !scripts.contains_key(&name) { + scripts.insert(name.clone(), command); + added.push(name); + } + } + let note = if added.is_empty() { + "has every script bui runs; left as it was".to_owned() + } else { + std::fs::write(&path, format!("{} +", serde_json::to_string_pretty(&doc)?)).with_context(|| format!("writing {}", path.display()))?; + format!("kept as it was, and added the scripts {}", added.join(", ")) + }; + Ok(vec![Adopted { path: "package.json", note }]) + } + + fn files(&self, vars: &Vars) -> Vec { + let flavour = match (self.framework, self.language) { + (Framework::React, Language::TypeScript) => "js/react-ts", + (Framework::React, Language::JavaScript) => "js/react-js", + (Framework::Svelte, _) => "js/svelte", + (Framework::Vanilla, Language::TypeScript) => "js/vanilla-ts", + (Framework::Vanilla, Language::JavaScript) => "js/vanilla-js", + }; + let mut files = render(&["js/common", flavour], vars); + files.push(File { path: "package.json".into(), body: self.package_json(&vars.name) }); + if self.typed() { + files.push(File { path: "tsconfig.json".into(), body: self.tsconfig() }); + } + files + } + + fn deps(&self, dir: &Path) -> Vec { + let (prod, dev) = self.packages(); + vec![ + step("Adding BUI (newest)", self.pm.add(dir, false, &prod)), + step("Adding TypeScript, Biome and the rest (newest)", self.pm.add(dir, true, &dev)), + // the generated files in Biome's own style, so `lint` starts clean + step("Formatting the new files", self.pm.run(dir, "fix", &[])), + ] + } + + fn dev(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![self.pm.run(dir, "dev", args)]) + } + + fn build(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![self.pm.run(dir, "build", args)]) + } + + fn checks(&self, dir: &Path) -> Vec { + let install = Fix::run("installs the packages", vec![Cmd::new(self.pm.bin(), ["install"]).in_dir(dir)]); + if !dir.join("node_modules").is_dir() { + return vec![Check::fail("node_modules", "packages are not installed", Some(install))]; + } + let manifest = read(dir, "node_modules/@blender-ui/native/package.json"); + let have = manifest.and_then(|m| serde_json::from_str::(&m).ok()).and_then(|v| v["version"].as_str().map(str::to_owned)); + let Some(have) = have else { + return vec![Check::fail("@blender-ui/native", "not installed", Some(install))]; + }; + let fix = Fix::run("updates the packages to the newest", vec![self.pm.update(dir)]); + vec![check::newest("@blender-ui/native", &have, registry::npm_version("@blender-ui/native").as_deref(), fix)] + } + + fn update(&self, dir: &Path) -> Vec { + vec![step("Updating packages", self.pm.update(dir))] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> JsApp { + JsApp { framework: Framework::Vanilla, language: Language::JavaScript, pm: PackageManager::Npm } + } + + fn scratch(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("bui-js-{tag}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn an_existing_manifest_gets_only_the_missing_scripts() { + let dir = scratch("adopt"); + let manifest = r#"{"name":"mine","zeta":1,"scripts":{"dev":"vite","test":"vitest"},"alpha":2}"#; + std::fs::write(dir.join("package.json"), manifest).unwrap(); + let adopted = app().adopt(&dir).unwrap(); + assert_eq!(adopted.len(), 1); + let doc: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).unwrap()).unwrap(); + assert_eq!(doc["scripts"]["dev"], "vite", "their script is kept"); + assert_eq!(doc["scripts"]["test"], "vitest"); + assert_eq!(doc["scripts"]["build"], "bui build src/main.js"); + assert_eq!(doc["scripts"]["fix"], "biome check --write ."); + let keys: Vec<&String> = doc.as_object().unwrap().keys().collect(); + assert_eq!(keys, ["name", "zeta", "scripts", "alpha"], "their order is kept"); + let again = std::fs::read_to_string(dir.join("package.json")).unwrap(); + assert!(app().adopt(&dir).unwrap()[0].note.contains("left as it was")); + assert_eq!(again, std::fs::read_to_string(dir.join("package.json")).unwrap(), "a second pass changes nothing"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn a_manifest_that_cannot_be_read_stops_init() { + let dir = scratch("broken"); + std::fs::write(dir.join("package.json"), "{ not json").unwrap(); + assert!(app().adopt(&dir).is_err()); + assert_eq!(std::fs::read_to_string(dir.join("package.json")).unwrap(), "{ not json", "it is not touched"); + std::fs::write(dir.join("package.json"), r#"{"scripts": []}"#).unwrap(); + assert!(app().adopt(&dir).is_err()); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn unreadable_manifests_and_module_type_with_tsx_stop_init() { + let dir = scratch("stop"); + std::fs::write(dir.join("package.json"), [0xff, 0xfe, 0x7b]).unwrap(); + assert!(app().adopt(&dir).is_err(), "invalid UTF-8 is an error, not an absent file"); + let tsx = JsApp { framework: Framework::React, language: Language::TypeScript, pm: PackageManager::Npm }; + std::fs::write(dir.join("package.json"), r#"{"type":"module"}"#).unwrap(); + assert!(tsx.adopt(&dir).is_err(), "tsx cannot import the CommonJS react package as ESM"); + assert!(app().adopt(&dir).is_ok(), "plain JavaScript can"); + assert_eq!(app().adopt(&scratch("none")).unwrap().len(), 0, "no manifest, nothing adopted"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn building_needs_bun_whatever_runs_the_app() { + for pm in [PackageManager::Npm, PackageManager::Pnpm, PackageManager::Bun] { + let tools = JsApp { pm, ..app() }.build_tools(); + assert_eq!(tools.iter().filter(|t| **t == Tool::Bun).count(), 1); + } + assert!(!app().tools().contains(&Tool::Bun), "running does not"); + } +} diff --git a/tools/bui/src/flavours/lua.rs b/tools/bui/src/flavours/lua.rs new file mode 100644 index 00000000..0db19a10 --- /dev/null +++ b/tools/bui/src/flavours/lua.rs @@ -0,0 +1,106 @@ +//! Lua: LuaRocks into a `lua_modules` folder of the project (nothing global), Luacheck for lint. + +use std::path::Path; + +use anyhow::{Result, bail}; +use serde::{Deserialize, Serialize}; + +use super::{File, Flavour, Step, Vars, optional, render, step}; +use crate::check::{Check, Fix}; +use crate::registry; +use crate::sys::{Cmd, semver}; +use crate::tools::Tool; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct LuaApp {} + +const TREE: &str = "lua_modules"; + +fn rocks(dir: &Path, args: &[&str]) -> Cmd { + let mut all = vec!["--tree", TREE]; + all.extend_from_slice(args); + Cmd::new("luarocks", all).in_dir(dir) +} + +/// `LUA_PATH` and `LUA_CPATH` for the project's rocks, as `luarocks path` prints them. +fn rock_env(dir: &Path) -> Vec<(String, String)> { + let Some(out) = rocks(dir, &["path"]).capture() else { + return Vec::new(); + }; + out.lines() + .filter_map(|l| { + let l = l.trim(); + // `export LUA_PATH='...'` (Unix) or `SET "LUA_PATH=..."` (Windows) + let (k, v) = if let Some(rest) = l.strip_prefix("export ") { + rest.split_once('=')? + } else { + l.strip_prefix("SET \"")?.strip_suffix('"')?.split_once('=')? + }; + let v = v.trim_matches('\''); + matches!(k, "LUA_PATH" | "LUA_CPATH" | "PATH").then(|| (k.to_owned(), v.replace("$PATH", &std::env::var("PATH").unwrap_or_default()))) + }) + .collect() +} + +/// The version of a rock installed in the project's tree. +fn installed(dir: &Path, rock: &str) -> Option { + let out = rocks(dir, &["list", "--porcelain", rock]).capture()?; + out.lines().find_map(|l| { + let mut f = l.split_whitespace(); + (f.next()? == rock).then(|| f.next().map(|v| v.split('-').next().unwrap_or(v).to_owned()))? + }) +} + +fn lua_program() -> &'static str { + ["lua5.4", "lua54", "lua"].into_iter().find(|p| crate::sys::which(p).is_some()).unwrap_or("lua") +} + +impl Flavour for LuaApp { + fn label(&self) -> String { + "Lua".into() + } + + fn tools(&self) -> Vec { + // the rock builds BUI's native module (a C compiler) + vec![Tool::Lua, Tool::Luarocks, Tool::Cc] + } + + fn files(&self, vars: &Vars) -> Vec { + render(&["lua"], vars) + } + + fn deps(&self, dir: &Path) -> Vec { + vec![ + step("Adding blenderui (newest)", rocks(dir, &["install", "blenderui"])), + optional("Adding Luacheck (newest)", rocks(dir, &["install", "luacheck"])), + ] + } + + fn dev(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![Cmd::new(lua_program(), ["main.lua"]).in_dir(dir).with_args(args).with_env(rock_env(dir))]) + } + + fn build(&self, _dir: &Path, _args: &[String]) -> Result> { + bail!("a Lua app is not built: run it with `bui dev`.") + } + + fn checks(&self, dir: &Path) -> Vec { + let install = Fix::run("installs blenderui into lua_modules", vec![rocks(dir, &["install", "blenderui"])]); + let Some(have) = installed(dir, "blenderui") else { + return vec![Check::fail("blenderui rock", "not installed in lua_modules", Some(install))]; + }; + let fix = Fix::run("installs the newest blenderui", vec![rocks(dir, &["install", "blenderui"])]); + // LuaRocks has no cheap "newest" lookup: every package is released with the same version + match registry::bui_version() { + Some(newest) if semver(&newest) > semver(&have) => { + vec![Check::warn("blenderui rock", format!("{have}, newest is {newest}"), Some(fix))] + } + _ => vec![Check::ok("blenderui rock", have)], + } + } + + fn update(&self, dir: &Path) -> Vec { + vec![step("Updating blenderui", rocks(dir, &["install", "blenderui"]))] + } + +} diff --git a/tools/bui/src/flavours/mod.rs b/tools/bui/src/flavours/mod.rs new file mode 100644 index 00000000..7eaa657a --- /dev/null +++ b/tools/bui/src/flavours/mod.rs @@ -0,0 +1,152 @@ +//! The languages a BUI project can be in. Each one is a module that says what it needs, what files a new +//! project has, how its dependencies are installed (always the newest), how it runs and builds, and how +//! `bui doctor` checks it. Adding a language is a module here and a variant in `project::Stack`. + +pub mod c; +pub mod js; +pub mod lua; +pub mod python; +pub mod rust; + +use std::collections::BTreeMap; +use std::path::Path; + +use anyhow::Result; +use include_dir::{Dir, include_dir}; + +use crate::check::{Check, Work}; +use crate::sys::Cmd; +use crate::tools::Tool; + +static TEMPLATES: Dir<'static> = include_dir!("$CARGO_MANIFEST_DIR/templates"); + +/// A piece of work with the words to show while it runs. +pub struct Step { + pub title: String, + pub work: Work, + /// A step that may fail without the project being unfinished (a linter that needs a C compiler). + pub optional: bool, +} + +pub fn step(title: &str, cmd: Cmd) -> Step { + Step { title: title.to_owned(), work: Work::Run(cmd), optional: false } +} + +/// A step that is allowed to fail. +pub fn optional(title: &str, cmd: Cmd) -> Step { + Step { optional: true, ..step(title, cmd) } +} + +/// A step that does `work`, such as a change to a file's text. +pub fn work_step(title: &str, work: Work) -> Step { + Step { title: title.to_owned(), work, optional: false } +} + +/// A file the project already had that `adopt` changed: which, and what was done. +pub struct Adopted { + pub path: &'static str, + pub note: String, +} + +pub struct File { + pub path: String, + pub body: String, +} + +/// What templates fill in. +pub struct Vars { + pub name: String, + /// The name as an identifier (`my_app`). + pub ident: String, + /// The name as words (`My App`). + pub title: String, + /// The newest BUI release tag (`v0.5.1`), for projects that fetch the sources. + pub tag: String, +} + +impl Vars { + pub fn new(name: &str, tag: &str) -> Self { + let ident: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect(); + let ident = if ident.starts_with(|c: char| c.is_ascii_digit()) { format!("app_{ident}") } else { ident }; + let title = name + .split(['-', '_', ' ']) + .filter(|w| !w.is_empty()) + .map(|w| { + let mut cs = w.chars(); + cs.next().map(|f| f.to_uppercase().chain(cs).collect::()).unwrap_or_default() + }) + .collect::>() + .join(" "); + Self { name: name.to_owned(), ident, title, tag: tag.to_owned() } + } + + fn fill(&self, text: &str) -> String { + text.replace("{{name}}", &self.name) + .replace("{{ident}}", &self.ident) + .replace("{{title}}", &self.title) + .replace("{{tag}}", &self.tag) + } +} + +fn collect(dir: &Dir<'_>, layer: &str, vars: &Vars, out: &mut BTreeMap) { + for file in dir.files() { + let rel = file.path().strip_prefix(layer).unwrap_or_else(|_| file.path()); + let mut path = rel.to_string_lossy().replace('\\', "/"); + // dotfiles are stored without the dot: a `.gitignore` in the templates would ignore them + if let Some(rest) = path.strip_prefix("_") { + path = format!(".{rest}"); + } else if let Some(i) = path.rfind("/_") { + path = format!("{}/.{}", &path[..i], &path[i + 2..]); + } + if let Some(text) = file.contents_utf8() { + out.insert(path, vars.fill(text)); + } + } + for sub in dir.dirs() { + collect(sub, layer, vars, out); + } +} + +/// The files of template folders laid over each other (a later folder replaces a file of the same name). +pub fn render(layers: &[&str], vars: &Vars) -> Vec { + let mut files = BTreeMap::new(); + for layer in layers { + if let Some(dir) = TEMPLATES.get_dir(layer) { + collect(dir, layer, vars, &mut files); + } + } + files.into_iter().map(|(path, body)| File { path, body }).collect() +} + +pub trait Flavour { + /// What the user chose, in words ("React + TypeScript on Bun"). + fn label(&self) -> String; + /// The programs needed to make, run and build the project. + fn tools(&self) -> Vec; + /// The programs `bui build` needs: those of `tools` unless the build needs more (JavaScript bundles with Bun). + fn build_tools(&self) -> Vec { + self.tools() + } + fn files(&self, vars: &Vars) -> Vec; + /// Makes the project's existing files fit (`bui init` in a folder that has them), before anything is + /// written: an error stops `init` with nothing changed. Everything else of theirs is left as it is. + fn adopt(&self, _dir: &Path) -> Result> { + Ok(Vec::new()) + } + /// Installs BUI and the language's tooling at their newest versions, in the new project. + fn deps(&self, dir: &Path) -> Vec; + /// Runs the app (a dev server where the language has one), as a list of commands. `args` are the + /// user's own, for the last of them. + fn dev(&self, dir: &Path, args: &[String]) -> Result>; + /// Makes a release build; an error says what to do instead where there is no build step. + fn build(&self, dir: &Path, args: &[String]) -> Result>; + /// The problems of the project itself (`bui doctor` adds the toolchain's). + fn checks(&self, dir: &Path) -> Vec; + /// Brings BUI and the tooling to their newest versions. + fn update(&self, dir: &Path) -> Vec; +} + +/// A file's text, if it can be read. +pub fn read(dir: &Path, file: &str) -> Option { + std::fs::read_to_string(dir.join(file)).ok() +} diff --git a/tools/bui/src/flavours/python.rs b/tools/bui/src/flavours/python.rs new file mode 100644 index 00000000..c9ec9c03 --- /dev/null +++ b/tools/bui/src/flavours/python.rs @@ -0,0 +1,94 @@ +//! Python: uv (the Python, the virtual environment and the lock file), Ruff for lint and format. + +use std::path::Path; + +use anyhow::{Result, bail}; +use serde::{Deserialize, Serialize}; + +use super::{File, Flavour, Step, Vars, read, render, step}; +use crate::check::{self, Check, Fix}; +use crate::project::PyApi; +use crate::registry; +use crate::sys::Cmd; +use crate::tools::Tool; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PythonApp { + pub api: PyApi, +} + +fn uv(dir: &Path, args: &[&str]) -> Cmd { + Cmd::new("uv", args.iter().copied()).in_dir(dir) +} + +impl Flavour for PythonApp { + fn label(&self) -> String { + let api = match self.api { + PyApi::Components => "Blender components", + PyApi::Qt => "Qt syntax", + PyApi::Tk => "tkinter syntax", + }; + format!("Python ({api})") + } + + fn tools(&self) -> Vec { + vec![Tool::Uv] + } + + fn files(&self, vars: &Vars) -> Vec { + let api = match self.api { + PyApi::Components => "python/components", + PyApi::Qt => "python/qt", + PyApi::Tk => "python/tk", + }; + render(&["python/common", api], vars) + } + + fn deps(&self, dir: &Path) -> Vec { + vec![ + step("Adding blenderui (newest)", uv(dir, &["add", "blenderui"])), + step("Adding Ruff (newest)", uv(dir, &["add", "--dev", "ruff"])), + ] + } + + fn dev(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![uv(dir, &["run", "main.py"]).with_args(args)]) + } + + fn build(&self, _dir: &Path, _args: &[String]) -> Result> { + bail!("a Python app is not built: run it with `bui dev`. To hand it out as one file, use PyInstaller (`uv run --with pyinstaller pyinstaller --onefile main.py`).") + } + + fn checks(&self, dir: &Path) -> Vec { + let sync = Fix::run("creates the environment and installs the packages", vec![uv(dir, &["sync"])]); + let Some(lock) = read(dir, "uv.lock") else { + return vec![Check::fail("environment", "no uv.lock: nothing installed yet", Some(sync))]; + }; + let mut lines = lock.lines(); + let mut have = None; + while let Some(l) = lines.next() { + if l == "name = \"blenderui\"" { + have = lines.next().and_then(|v| v.strip_prefix("version = \"")).and_then(|v| v.strip_suffix('"')).map(str::to_owned); + break; + } + } + let Some(have) = have else { + let add = Fix::run("adds blenderui", vec![uv(dir, &["add", "blenderui"])]); + return vec![Check::fail("blenderui", "not a dependency", Some(add))]; + }; + let mut checks = Vec::new(); + if !dir.join(".venv").is_dir() { + checks.push(Check::warn("environment", ".venv is missing", Some(sync))); + } + let fix = Fix::run("updates blenderui to the newest", vec![uv(dir, &["lock", "--upgrade-package", "blenderui"]), uv(dir, &["sync"])]); + checks.push(check::newest("blenderui (PyPI)", &have, registry::pypi_version("blenderui").as_deref(), fix)); + checks + } + + fn update(&self, dir: &Path) -> Vec { + vec![ + step("Updating blenderui", uv(dir, &["lock", "--upgrade-package", "blenderui"])), + step("Installing", uv(dir, &["sync"])), + ] + } +} diff --git a/tools/bui/src/flavours/rust.rs b/tools/bui/src/flavours/rust.rs new file mode 100644 index 00000000..c8edc0bd --- /dev/null +++ b/tools/bui/src/flavours/rust.rs @@ -0,0 +1,78 @@ +//! Rust: `cargo add blenderui`, clippy's pedantic lints on, rustfmt. + +use std::path::Path; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use super::{File, Flavour, Step, Vars, read, render, step}; +use crate::check::{self, Check, Fix}; +use crate::registry; +use crate::sys::Cmd; +use crate::tools::Tool; + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct RustApp {} + +impl Flavour for RustApp { + fn label(&self) -> String { + "Rust".into() + } + + fn tools(&self) -> Vec { + // blenderui-sys builds BUI's C kit with CMake while it compiles + vec![Tool::Rust, Tool::Cc, Tool::Cmake] + } + + fn files(&self, vars: &Vars) -> Vec { + render(&["rust"], vars) + } + + fn deps(&self, dir: &Path) -> Vec { + vec![ + step("Adding blenderui (newest)", Cmd::new("cargo", ["add", "blenderui"]).in_dir(dir)), + step( + "Compiling BUI once (a few minutes now, seconds after)", + Cmd::new("cargo", ["build"]).in_dir(dir), + ), + ] + } + + fn dev(&self, dir: &Path, args: &[String]) -> Result> { + // `bui dev -- --release` is `cargo run --release`; the app's own arguments need a second `--` + Ok(vec![Cmd::new("cargo", ["run"]).in_dir(dir).with_args(args)]) + } + + fn build(&self, dir: &Path, args: &[String]) -> Result> { + Ok(vec![Cmd::new("cargo", ["build", "--release"]).in_dir(dir).with_args(args)]) + } + + fn checks(&self, dir: &Path) -> Vec { + let Some(manifest) = read(dir, "Cargo.toml") else { + return vec![Check::fail("Cargo.toml", "missing", None)]; + }; + let Some(have) = locked_version(dir, "blenderui") else { + let fix = Fix::run("adds blenderui", vec![Cmd::new("cargo", ["add", "blenderui"]).in_dir(dir)]); + let detail = if manifest.contains("blenderui") { "not fetched yet" } else { "not a dependency" }; + return vec![Check::fail("blenderui crate", detail, Some(fix))]; + }; + let fix = Fix::run("updates blenderui to the newest", vec![Cmd::new("cargo", ["update", "--package", "blenderui"]).in_dir(dir)]); + vec![check::newest("blenderui crate", &have, registry::crate_version("blenderui").as_deref(), fix)] + } + + fn update(&self, dir: &Path) -> Vec { + vec![step("Updating blenderui", Cmd::new("cargo", ["update", "--package", "blenderui"]).in_dir(dir))] + } +} + +/// The version of `package` in `Cargo.lock`. +fn locked_version(dir: &Path, package: &str) -> Option { + let lock = read(dir, "Cargo.lock")?; + let mut lines = lock.lines(); + while let Some(l) = lines.next() { + if l == format!("name = \"{package}\"") { + return lines.next()?.strip_prefix("version = \"")?.strip_suffix('"').map(str::to_owned); + } + } + None +} diff --git a/tools/bui/src/home.rs b/tools/bui/src/home.rs new file mode 100644 index 00000000..028d81a3 --- /dev/null +++ b/tools/bui/src/home.rs @@ -0,0 +1,79 @@ +//! What `bui` prints with no command: the app you are in, and every command with its options. + +use std::path::Path; + +use crate::{project, ui}; + +/// (what to type, what it does, its options as `(flag, meaning)`) +type Entry = (&'static str, &'static str, &'static [(&'static str, &'static str)]); + +const COMMANDS: &[Entry] = &[ + ( + "bui new [NAME]", + "Make an app in a new folder", + &[ + ("-l, --language ", "the language"), + ("--framework ", "JavaScript"), + ("--typescript | --javascript", "JavaScript"), + ("--pm ", "JavaScript: runtime and package manager"), + ("--api ", "Python: the style of UI code"), + ("--no-install", "do not install packages"), + ("--no-git", "do not start a git repository"), + ], + ), + ("bui init", "Make an app in this folder (same options as new)", &[]), + ("bui dev [-- ARGS]", "Run the app (reloads when you save)", &[("-- ARGS", "given to the tool underneath")]), + ("bui build [-- ARGS]", "Make a release build", &[("-- ARGS", "given to the tool underneath")]), + ( + "bui doctor", + "Check your setup and fix what is wrong", + &[("--fix", "run the fixes without asking"), ("--all", "check every language's tools"), ("--json", "print the results, change nothing")], + ), + ("bui update", "Update bui, then this app's BUI packages", &[("--check", "only say what is out of date")]), + ("bui docs", "Open the documentation", &[]), + ("bui completions ", "Shell completions", &[("", "bash, zsh, fish, powershell or elvish")]), +]; + +const EVERYWHERE: &[(&str, &str)] = &[ + ("--plain", "no animation or color (automatic in CI and pipes)"), + ("-y, --yes", "answer every question with its default"), + ("--install-tools", "install missing tools without asking"), + ("-h, --help", "help for any command"), + ("-V, --version", "the version"), +]; + +fn render(entries: &[Entry]) -> String { + let mut lines = Vec::new(); + for (usage, what, options) in entries { + lines.push(format!("{} {}", ui::code(&format!("{usage:<25}")), what)); + for (flag, meaning) in *options { + let text = if meaning.is_empty() { (*flag).to_owned() } else { format!("{flag:<40}{meaning}") }; + lines.push(format!(" {}", ui::dim(&text))); + } + } + lines.join("\n") +} + +pub fn show() { + ui::banner(true); + if let Some(p) = project::find(Path::new(".")) { + ui::note("This app", &format!("{} {}", p.meta.name, ui::dim(&p.meta.stack.app().label()))); + } + ui::note("Commands", &render(COMMANDS)); + let everywhere: Vec = EVERYWHERE.iter().map(|(f, m)| format!("{} {}", ui::code(&format!("{f:<16}")), m)).collect(); + ui::note("Options for every command", &everywhere.join("\n")); + ui::outro(&format!("New here? Run {}. Docs: {}", ui::code("bui new"), ui::code("https://bui.preetham.top"))); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_command_is_listed() { + let text = console::strip_ansi_codes(&render(COMMANDS)).into_owned(); + for word in ["bui new", "bui init", "bui dev", "bui build", "bui doctor", "bui update", "bui docs", "bui completions", "--fix", "--language"] { + assert!(text.contains(word), "{word} missing"); + } + } +} diff --git a/tools/bui/src/main.rs b/tools/bui/src/main.rs new file mode 100644 index 00000000..eebb0b03 --- /dev/null +++ b/tools/bui/src/main.rs @@ -0,0 +1,61 @@ +//! `bui`: create, run, check and update BUI apps. + +mod check; +mod cli; +mod create; +mod doctor; +mod flavours; +mod home; +mod project; +mod registry; +mod run; +mod sys; +mod tools; +mod ui; +mod update; + +use std::process::ExitCode; + +use anyhow::Result; +use clap::{CommandFactory, Parser}; + +use cli::{Cli, Command}; + +fn main() -> ExitCode { + let cli = Cli::parse(); + ui::init(cli.plain, cli.yes); + if cli.install_tools { + tools::install_without_asking(); + } + match dispatch(cli) { + Ok(code) => code, + Err(e) => { + ui::error(format!("{e:#}")); + if project::find(std::path::Path::new(".")).is_some() { + ui::info(format!("Run {} to check your setup.", ui::code("bui doctor"))); + } + ExitCode::FAILURE + } + } +} + +fn dispatch(cli: Cli) -> Result { + let ok = |r: Result<()>| r.map(|()| ExitCode::SUCCESS); + match cli.command { + Some(Command::New(args)) => ok(create::new(args)), + Some(Command::Init(choices)) => ok(create::init(&choices)), + Some(Command::Dev(a)) => run::dev(&a.args), + Some(Command::Build(a)) => run::build(&a.args), + Some(Command::Docs) => Ok(run::docs()), + Some(Command::Doctor(args)) => doctor::run(&args), + Some(Command::Update(args)) => ok(update::run(&args)), + Some(Command::Completions { shell }) => { + clap_complete::generate(shell, &mut Cli::command(), "bui", &mut std::io::stdout()); + Ok(ExitCode::SUCCESS) + } + None => { + home::show(); + Ok(ExitCode::SUCCESS) + } + } +} diff --git a/tools/bui/src/project.rs b/tools/bui/src/project.rs new file mode 100644 index 00000000..0bbab895 --- /dev/null +++ b/tools/bui/src/project.rs @@ -0,0 +1,231 @@ +//! A BUI project: what `bui.toml` says about it (which language and options it was made with), found +//! from any folder inside it, or guessed from its files when it has none. + +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use clap::ValueEnum; +use serde::{Deserialize, Serialize}; + +use crate::flavours::{Flavour, c::CApp, js::JsApp, lua::LuaApp, python::PythonApp, rust::RustApp}; + +pub const FILE: &str = "bui.toml"; + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum Framework { + React, + Svelte, + /// BUI's DOM-like API with no framework. + Vanilla, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum Language { + #[value(name = "ts")] + TypeScript, + #[value(name = "js")] + JavaScript, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum PackageManager { + Bun, + Npm, + Pnpm, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, ValueEnum)] +#[serde(rename_all = "lowercase")] +pub enum PyApi { + /// Blender's own components. + Components, + Qt, + Tk, +} + +/// The language a project is in, with that language's options. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "flavour", rename_all = "lowercase")] +pub enum Stack { + Rust(RustApp), + Js(JsApp), + Python(PythonApp), + Lua(LuaApp), + C(CApp), +} + +impl Stack { + pub fn app(&self) -> &dyn Flavour { + match self { + Self::Rust(a) => a, + Self::Js(a) => a, + Self::Python(a) => a, + Self::Lua(a) => a, + Self::C(a) => a, + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Meta { + pub name: String, + #[serde(flatten)] + pub stack: Stack, +} + +#[derive(Serialize, Deserialize)] +struct Doc { + project: Meta, +} + +pub struct Project { + pub dir: PathBuf, + pub meta: Meta, + /// Read from `bui.toml` (not guessed). + pub declared: bool, +} + +impl Meta { + pub fn to_toml(&self) -> Result { + let body = toml::to_string_pretty(&Doc { project: self.clone() })?; + Ok(format!("# Made by `bui new`: bui reads this to know how to run, build and check the project.\n{body}")) + } +} + +/// The project that contains `from`: the nearest folder up with a `bui.toml`, else the folder itself +/// when its files say what it is. +pub fn find(from: &Path) -> Option { + let start = from.canonicalize().unwrap_or_else(|_| from.to_owned()); + // Windows' canonical paths start with `\\?\`, which many tools cannot read + let start = start.to_string_lossy().strip_prefix(r"\\?\").map_or_else(|| start.clone(), PathBuf::from); + for dir in start.ancestors() { + if let Some(doc) = fs::read_to_string(dir.join(FILE)).ok().and_then(|t| toml::from_str::(&t).ok()) { + return Some(Project { dir: dir.to_owned(), meta: doc.project, declared: true }); + } + } + guess(&start).map(|meta| Project { dir: start, meta, declared: false }) +} + +fn read(dir: &Path, file: &str) -> String { + fs::read_to_string(dir.join(file)).unwrap_or_default() +} + +fn guess(dir: &Path) -> Option { + let name = dir.file_name()?.to_string_lossy().into_owned(); + let stack = if read(dir, "Cargo.toml").contains("blenderui") { + Stack::Rust(RustApp {}) + } else if read(dir, "package.json").contains("@blender-ui/") { + let pkg = read(dir, "package.json"); + let framework = if pkg.contains("@blender-ui/react") { + Framework::React + } else if pkg.contains("@blender-ui/svelte") { + Framework::Svelte + } else { + Framework::Vanilla + }; + let pm = if dir.join("bun.lock").exists() || dir.join("bun.lockb").exists() { + PackageManager::Bun + } else if dir.join("pnpm-lock.yaml").exists() { + PackageManager::Pnpm + } else { + PackageManager::Npm + }; + let language = if dir.join("tsconfig.json").exists() { Language::TypeScript } else { Language::JavaScript }; + Stack::Js(JsApp { framework, language, pm }) + } else if depends_on_blenderui(&read(dir, "pyproject.toml")) { + Stack::Python(PythonApp { api: PyApi::Components }) + } else if read(dir, "main.lua").contains("require(\"bui\")") || read(dir, "main.lua").contains("require('bui')") { + Stack::Lua(LuaApp {}) + } else if read(dir, "CMakeLists.txt").contains("BUI") && dir.join("src").is_dir() { + Stack::C(CApp {}) + } else { + return None; + }; + Some(Meta { name, stack }) +} + +/// A `pyproject.toml` that uses blenderui (not the one of blenderui itself, which is named that). +fn depends_on_blenderui(pyproject: &str) -> bool { + pyproject.contains("blenderui") && !pyproject.contains("name = \"blenderui\"") +} + +pub fn require(from: &Path) -> Result { + find(from).with_context(|| "this folder is not a BUI project (no bui.toml). Make one with `bui new` or `bui init`.") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::flavours::{Vars, c::CApp}; + + pub fn every_stack() -> Vec { + let mut stacks = vec![Stack::Rust(RustApp {}), Stack::Lua(LuaApp {}), Stack::C(CApp {})]; + for api in [PyApi::Components, PyApi::Qt, PyApi::Tk] { + stacks.push(Stack::Python(PythonApp { api })); + } + for pm in [PackageManager::Bun, PackageManager::Npm, PackageManager::Pnpm] { + for (framework, language) in [ + (Framework::React, Language::TypeScript), + (Framework::React, Language::JavaScript), + (Framework::Svelte, Language::JavaScript), + (Framework::Vanilla, Language::TypeScript), + (Framework::Vanilla, Language::JavaScript), + ] { + stacks.push(Stack::Js(JsApp { framework, language, pm })); + } + } + stacks + } + + #[test] + fn bui_toml_round_trips_for_every_stack() { + for stack in every_stack() { + let meta = Meta { name: "demo".into(), stack }; + let text = meta.to_toml().unwrap(); + let back: Doc = toml::from_str(&text).unwrap(); + assert_eq!(back.project.stack.app().label(), meta.stack.app().label(), "{text}"); + } + } + + #[test] + fn every_stack_renders_files_with_no_placeholder_left() { + let vars = Vars::new("my-app", "v1.2.3"); + for stack in every_stack() { + let files = stack.app().files(&vars); + assert!(!files.is_empty(), "{}", stack.app().label()); + assert!(files.iter().any(|f| f.path == ".gitignore"), "{} has no .gitignore", stack.app().label()); + for f in &files { + assert!(!f.body.contains("{{"), "{}: {} has a placeholder left", stack.app().label(), f.path); + assert!(!f.path.contains("/_") && !f.path.starts_with('_'), "{}: {} keeps its underscore", stack.app().label(), f.path); + } + } + } + + #[test] + fn blenderuis_own_pyproject_is_not_an_app() { + assert!(!depends_on_blenderui("[project] +name = \"blenderui\" +")); + assert!(depends_on_blenderui("[project] +name = \"x\" +dependencies = [\"blenderui>=0.5\"] +")); + } + + #[test] + fn a_project_is_found_from_a_folder_inside_it() { + let dir = std::env::temp_dir().join(format!("bui-test-{}", std::process::id())); + let inner = dir.join("src/deep"); + fs::create_dir_all(&inner).unwrap(); + let meta = Meta { name: "demo".into(), stack: Stack::Lua(LuaApp {}) }; + fs::write(dir.join(FILE), meta.to_toml().unwrap()).unwrap(); + let found = find(&inner).expect("found"); + assert!(found.declared); + assert_eq!(found.meta.name, "demo"); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/tools/bui/src/registry.rs b/tools/bui/src/registry.rs new file mode 100644 index 00000000..799229d9 --- /dev/null +++ b/tools/bui/src/registry.rs @@ -0,0 +1,88 @@ +//! The newest versions of things, from the registries. Every lookup can fail (offline): the answer is +//! `None` and the caller carries on. + +use std::time::Duration; + +use serde_json::Value; + +const REPO: &str = "ppmpreetham/BUI"; + +fn get(url: &str) -> Option { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(6))) + .user_agent(concat!("bui-cli/", env!("CARGO_PKG_VERSION"))) + .build() + .into(); + agent.get(url).call().ok()?.body_mut().read_json().ok() +} + +fn text(v: &Value, path: &[&str]) -> Option { + path.iter().try_fold(v, |v, k| v.get(k))?.as_str().map(str::to_owned) +} + +pub fn crate_version(name: &str) -> Option { + text(&get(&format!("https://crates.io/api/v1/crates/{name}"))?, &["crate", "max_version"]) +} + +pub fn npm_version(package: &str) -> Option { + text(&get(&format!("https://registry.npmjs.org/{package}/latest"))?, &["version"]) +} + +pub fn pypi_version(package: &str) -> Option { + text(&get(&format!("https://pypi.org/pypi/{package}/json"))?, &["info", "version"]) +} + +/// The tag of the newest GitHub release of the `bui` program (`v0.5.1`). It follows the page's redirect +/// (`/releases/latest` -> `/releases/tag/v0.5.1`): the API would rate-limit a tool that runs on every machine. +pub fn release_tag() -> Option { + // for tests and mirrors + if let Ok(tag) = std::env::var("BUI_RELEASE_TAG") { + return Some(tag); + } + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(6))) + .max_redirects(0) + .max_redirects_will_error(false) + .user_agent(concat!("bui-cli/", env!("CARGO_PKG_VERSION"))) + .build() + .into(); + let response = agent.get(&format!("https://github.com/{REPO}/releases/latest")).call().ok()?; + let location = response.headers().get("location")?.to_str().ok()?; + location.rsplit_once("/tag/").map(|(_, tag)| tag.to_owned()) +} + +/// The newest BUI the language packages carry (the crate is published with every release). +pub fn bui_version() -> Option { + crate_version("blenderui") +} + +/// Where a release's file is. +pub fn download_url(tag: &str, asset: &str) -> String { + if let Ok(base) = std::env::var("BUI_DOWNLOAD_BASE") { + return format!("{}/{asset}", base.trim_end_matches('/')); + } + format!("https://github.com/{REPO}/releases/download/{tag}/{asset}") +} + +/// A file from the release as bytes (the archive of a new `bui`), with progress reported to `on_chunk`. +pub fn download(url: &str, mut on_chunk: impl FnMut(u64, Option)) -> Option> { + use std::io::Read; + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(120))) + .user_agent(concat!("bui-cli/", env!("CARGO_PKG_VERSION"))) + .build() + .into(); + let mut response = agent.get(url).call().ok()?; + let total = response.headers().get("content-length").and_then(|v| v.to_str().ok()?.parse().ok()); + let mut reader = response.body_mut().as_reader(); + let mut bytes = Vec::with_capacity(total.map_or(1 << 20, |t: u64| t as usize)); + let mut buf = vec![0u8; 32 * 1024].into_boxed_slice(); + loop { + let n = reader.read(&mut buf).ok()?; + if n == 0 { + return Some(bytes); + } + bytes.extend_from_slice(&buf[..n]); + on_chunk(bytes.len() as u64, total); + } +} diff --git a/tools/bui/src/run.rs b/tools/bui/src/run.rs new file mode 100644 index 00000000..5498d30a --- /dev/null +++ b/tools/bui/src/run.rs @@ -0,0 +1,59 @@ +//! `bui dev` and `bui build`: the project's own commands, with the toolchain checked first. + +use std::path::Path; +use std::process::ExitCode; + +use anyhow::Result; + +use crate::flavours::Flavour; +use crate::project::{self, Project}; +use crate::sys::{Cmd, OS, Os}; +use crate::tools::{self, Tool}; +use crate::ui; + +pub fn dev(args: &[String]) -> Result { + go("Running", |a| a.tools(), |p| p.meta.stack.app().dev(&p.dir, args)) +} + +pub fn build(args: &[String]) -> Result { + go("Building", |a| a.build_tools(), |p| p.meta.stack.app().build(&p.dir, args)) +} + +const DOCS: &str = "https://bui.preetham.top"; + +/// `bui docs`: the documentation in the browser (or just its address, where there is no browser to open). +pub fn docs() -> ExitCode { + ui::info(format!("Documentation: {}", ui::code(DOCS))); + if ui::interactive() { + let open = match OS { + Os::Windows => Cmd::script(&format!("Start-Process '{DOCS}'")), + Os::Mac => Cmd::new("open", [DOCS]), + Os::Linux => Cmd::new("xdg-open", [DOCS]), + }; + if !open.run_inherit().is_ok_and(|s| s.success()) { + ui::info("Could not open a browser: visit the address above."); + } + } + ExitCode::SUCCESS +} + +fn go(verb: &str, needs: impl Fn(&dyn Flavour) -> Vec, commands: impl Fn(&Project) -> Result>) -> Result { + let project = project::require(Path::new("."))?; + let app = project.meta.stack.app(); + let missing = tools::ensure(&needs(app))?; + if !missing.is_empty() { + ui::error("Cannot continue without those. `bui doctor` shows what to do."); + return Ok(ExitCode::FAILURE); + } + let cmds = commands(&project)?; + ui::info(format!("{verb} {} ({})", project.meta.name, app.label())); + for cmd in &cmds { + ui::flush(); + let status = cmd.run_inherit()?; + if !status.success() { + ui::error(format!("`{}` failed", cmd.display())); + return Ok(ExitCode::from(u8::try_from(status.code().unwrap_or(1)).unwrap_or(1))); + } + } + Ok(ExitCode::SUCCESS) +} diff --git a/tools/bui/src/sys.rs b/tools/bui/src/sys.rs new file mode 100644 index 00000000..561167d9 --- /dev/null +++ b/tools/bui/src/sys.rs @@ -0,0 +1,257 @@ +//! The machine: the operating system, finding programs and running commands. + +use std::collections::VecDeque; +use std::io::{BufRead, BufReader, Read}; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitStatus, Stdio}; +use std::sync::mpsc; +use std::thread; + +use anyhow::{Context, Result}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Os { + Windows, + Mac, + Linux, +} + +pub const OS: Os = if cfg!(windows) { + Os::Windows +} else if cfg!(target_os = "macos") { + Os::Mac +} else { + Os::Linux +}; + +pub fn home() -> Option { + std::env::home_dir() +} + +/// Where tools put themselves that a terminal started before the install does not search yet. +fn extra_dirs() -> Vec { + let mut dirs = Vec::new(); + if let Some(h) = home() { + for d in [".cargo/bin", ".bun/bin", ".local/bin", ".bui/bin", "scoop/shims", ".deno/bin", ".local/share/fnm/aliases/default/bin"] { + dirs.push(h.join(d)); + } + } + if OS == Os::Windows { + for var in ["ProgramFiles", "ProgramFiles(x86)"] { + if let Some(p) = std::env::var_os(var).map(PathBuf::from) { + for d in ["nodejs", "Git/cmd", "CMake/bin", "LuaRocks"] { + dirs.push(p.join(d)); + } + } + } + } + if OS == Os::Mac { + dirs.push(PathBuf::from("/opt/homebrew/bin")); + dirs.push(PathBuf::from("/usr/local/bin")); + } + dirs +} + +fn candidates(dir: &Path, name: &str) -> Vec { + if OS == Os::Windows { + ["exe", "cmd", "bat", "com"].iter().map(|e| dir.join(format!("{name}.{e}"))).collect() + } else { + vec![dir.join(name)] + } +} + +/// The program `name` on `PATH` (or where installers put it), as the shell would find it. +pub fn which(name: &str) -> Option { + let path = std::env::var_os("PATH").unwrap_or_default(); + std::env::split_paths(&path) + .chain(extra_dirs()) + .flat_map(|d| candidates(&d, name)) + .find(|p| p.is_file()) +} + +/// A command to run: a program and its arguments, or a line for the shell (installers pipe). +#[derive(Clone, Debug)] +pub struct Cmd { + program: String, + args: Vec, + script: bool, + pub cwd: Option, + pub env: Vec<(String, String)>, +} + +impl Cmd { + pub fn new(program: &str, args: I) -> Self + where + I: IntoIterator, + S: Into, + { + Self { + program: program.to_owned(), + args: args.into_iter().map(Into::into).collect(), + script: false, + cwd: None, + env: Vec::new(), + } + } + + /// A line for `sh -c` (Windows: PowerShell). + pub fn script(line: &str) -> Self { + Self { program: line.to_owned(), args: Vec::new(), script: true, cwd: None, env: Vec::new() } + } + + #[must_use] + pub fn in_dir(mut self, dir: &Path) -> Self { + self.cwd = Some(dir.to_owned()); + self + } + + /// More arguments after the ones it has. + #[must_use] + pub fn with_args(mut self, more: &[String]) -> Self { + self.args.extend(more.iter().cloned()); + self + } + + #[must_use] + pub fn with_env(mut self, vars: Vec<(String, String)>) -> Self { + self.env = vars; + self + } + + /// What the user would type. + pub fn display(&self) -> String { + if self.script { + return self.program.clone(); + } + std::iter::once(self.program.as_str()) + .chain(self.args.iter().map(String::as_str)) + .map(|a| if a.contains(' ') { format!("\"{a}\"") } else { a.to_owned() }) + .collect::>() + .join(" ") + } + + fn command(&self) -> Result { + let mut c = if self.script { + if OS == Os::Windows { + let mut c = Command::new("powershell"); + c.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &self.program]); + c + } else { + let mut c = Command::new("sh"); + c.args(["-c", &self.program]); + c + } + } else { + let given = Path::new(&self.program); + let exe = if given.is_absolute() { given.to_owned() } else { which(&self.program).with_context(|| format!("`{}` is not installed", self.program))? }; + let mut c = Command::new(exe); + c.args(&self.args); + c + }; + if let Some(d) = &self.cwd { + c.current_dir(d); + } + c.envs(self.env.iter().map(|(k, v)| (k, v))); + Ok(c) + } + + /// Runs with the terminal's own input and output (a dev server, an installer asking for sudo). + pub fn run_inherit(&self) -> Result { + self.command()?.status().with_context(|| format!("running {}", self.display())) + } + + /// Runs quietly and returns the output when it succeeds. + pub fn capture(&self) -> Option { + let out = self.command().ok()?.stdin(Stdio::null()).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned()) + } + + /// Runs with each line it prints handed to `on_line`, and the last lines kept for an error. + pub fn run_live(&self, mut on_line: impl FnMut(&str)) -> Result { + let mut child = self + .command()? + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .with_context(|| format!("starting {}", self.display()))?; + let (tx, rx) = mpsc::channel::(); + let streams: [Option>; 2] = [ + child.stdout.take().map(|s| Box::new(s) as Box), + child.stderr.take().map(|s| Box::new(s) as Box), + ]; + let readers: Vec<_> = streams + .into_iter() + .flatten() + .map(|stream| { + let tx = tx.clone(); + thread::spawn(move || { + for line in BufReader::new(stream).split(b'\n').map_while(Result::ok) { + let text = String::from_utf8_lossy(&line).into_owned(); + // progress bars redraw with \r: the last redraw is the line + let last = text.rsplit('\r').find(|s| !s.trim().is_empty()).unwrap_or(""); + let _ = tx.send(console::strip_ansi_codes(last).trim_end().to_owned()); + } + }) + }) + .collect(); + drop(tx); + let mut tail = VecDeque::with_capacity(TAIL); + for line in rx { + if line.is_empty() { + continue; + } + on_line(&line); + if tail.len() == TAIL { + tail.pop_front(); + } + tail.push_back(line); + } + for r in readers { + let _ = r.join(); + } + let status = child.wait()?; + Ok(Outcome { ok: status.success(), tail: tail.into() }) + } +} + +const TAIL: usize = 24; + +pub struct Outcome { + pub ok: bool, + /// The last lines it printed. + pub tail: Vec, +} + +/// The first `1.2.3`-looking token of a program's `--version`. +pub fn version_of(program: &str, args: &[&str]) -> Option { + let out = Cmd::new(program, args.iter().copied()).capture()?; + out.split(|c: char| !(c.is_ascii_digit() || c == '.')) + .find(|t| t.contains('.') && t.chars().next().is_some_and(|c| c.is_ascii_digit())) + .map(|t| t.trim_end_matches('.').to_owned()) +} + +/// `a.b.c` as numbers, to compare versions. +pub fn semver(v: &str) -> [u64; 3] { + let mut parts = v.trim_start_matches('v').split(['.', '-', '+']).map(|p| p.parse().unwrap_or(0)); + [parts.next().unwrap_or(0), parts.next().unwrap_or(0), parts.next().unwrap_or(0)] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions_compare_as_numbers() { + assert!(semver("0.10.0") > semver("0.9.9")); + assert!(semver("v1.0.0") > semver("0.99.99")); + assert_eq!(semver("1.2"), [1, 2, 0]); + assert_eq!(semver("0.5.1-beta"), [0, 5, 1]); + } + + #[test] + fn a_command_shows_as_typed() { + assert_eq!(Cmd::new("cargo", ["add", "blenderui"]).display(), "cargo add blenderui"); + assert_eq!(Cmd::new("x", ["a b"]).display(), "x \"a b\""); + } +} diff --git a/tools/bui/src/tools.rs b/tools/bui/src/tools.rs new file mode 100644 index 00000000..aac4cbb4 --- /dev/null +++ b/tools/bui/src/tools.rs @@ -0,0 +1,211 @@ +//! The programs a language needs (Rust's cargo, Bun, uv, ...): whether they are there, the commands +//! that install the newest one on this machine, and the question that offers to run them. + +use std::sync::atomic::{AtomicBool, Ordering}; + +use anyhow::Result; + +use crate::sys::{Cmd, OS, Os, version_of, which}; +use crate::ui; + +static INSTALL_WITHOUT_ASKING: AtomicBool = AtomicBool::new(false); + +/// `--install-tools`: install what is missing without the question (scripts, CI). +pub fn install_without_asking() { + INSTALL_WITHOUT_ASKING.store(true, Ordering::Relaxed); +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Tool { + Rust, + Bun, + Node, + Pnpm, + Uv, + Lua, + Luarocks, + Cmake, + /// A C compiler (on Windows, Visual Studio's C++ tools). + Cc, + Git, +} + +/// How to install a tool: commands, in order. +pub struct Install { + pub cmds: Vec, + pub note: Option<&'static str>, +} + +fn pkg(apt: &str, dnf: &str, pacman: &str) -> Cmd { + let line = if which("apt-get").is_some() { + format!("sudo apt-get install -y {apt}") + } else if which("dnf").is_some() { + format!("sudo dnf install -y {dnf}") + } else if which("pacman").is_some() { + format!("sudo pacman -S --needed --noconfirm {pacman}") + } else { + format!("sudo apt-get install -y {apt}") + }; + Cmd::script(&line) +} + +fn winget(id: &str) -> Cmd { + Cmd::new("winget", ["install", "-e", "--id", id, "--accept-source-agreements", "--accept-package-agreements"]) +} + +fn brew(formulae: &str) -> Cmd { + Cmd::script(&format!("brew install {formulae}")) +} + +impl Tool { + pub const fn label(self) -> &'static str { + match self { + Self::Rust => "Rust (cargo)", + Self::Bun => "Bun", + Self::Node => "Node.js", + Self::Pnpm => "pnpm", + Self::Uv => "uv", + Self::Lua => "Lua 5.4", + Self::Luarocks => "LuaRocks", + Self::Cmake => "CMake", + Self::Cc => "a C compiler", + Self::Git => "Git", + } + } + + /// The version when it is installed (`"found"` when it has none to print). + pub fn probe(self) -> Option { + let v = |program: &str, arg: &str| which(program).map(|_| version_of(program, &[arg]).unwrap_or_else(|| "found".into())); + match self { + Self::Rust => v("cargo", "--version"), + Self::Bun => v("bun", "--version"), + Self::Node => v("node", "--version"), + Self::Pnpm => v("pnpm", "--version"), + Self::Uv => v("uv", "--version"), + Self::Lua => ["lua5.4", "lua54", "lua"] + .into_iter() + .find_map(|p| which(p).and_then(|_| version_of(p, &["-v"]).filter(|ver| ver.starts_with("5.4")))), + Self::Luarocks => v("luarocks", "--version"), + Self::Cmake => v("cmake", "--version"), + Self::Git => v("git", "--version"), + Self::Cc => cc_probe(), + } + } + + pub fn install(self) -> Install { + let none = |cmds: Vec| Install { cmds, note: None }; + match (self, OS) { + (Self::Rust, Os::Windows) => Install { + cmds: vec![winget("Rustlang.Rustup")], + note: Some("Rust on Windows also needs Visual Studio's C++ build tools (bui offers them next)."), + }, + (Self::Rust, _) => none(vec![Cmd::script("curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y")]), + (Self::Bun, Os::Windows) => none(vec![Cmd::script("irm bun.sh/install.ps1 | iex")]), + (Self::Bun, _) => none(vec![Cmd::script("curl -fsSL https://bun.sh/install | bash")]), + (Self::Node, Os::Windows) => none(vec![winget("OpenJS.NodeJS.LTS")]), + (Self::Node, Os::Mac) if which("brew").is_some() => none(vec![brew("node")]), + (Self::Node, _) => none(vec![Cmd::script( + "curl -fsSL https://fnm.vercel.app/install | bash && export PATH=\"$HOME/.local/share/fnm:$PATH\" && eval \"$(fnm env)\" && fnm install --lts && fnm default lts-latest", + )]), + (Self::Pnpm, _) => none(vec![Cmd::new("npm", ["install", "--global", "pnpm"])]), + (Self::Uv, Os::Windows) => none(vec![Cmd::script("irm https://astral.sh/uv/install.ps1 | iex")]), + (Self::Uv, _) => none(vec![Cmd::script("curl -LsSf https://astral.sh/uv/install.sh | sh")]), + (Self::Lua | Self::Luarocks, Os::Windows) => Install { + cmds: vec![Cmd::script("scoop install lua luarocks")], + note: Some("Needs Scoop (https://scoop.sh): `irm get.scoop.sh | iex`."), + }, + (Self::Lua | Self::Luarocks, Os::Mac) => none(vec![brew("lua luarocks")]), + (Self::Lua | Self::Luarocks, Os::Linux) => none(vec![pkg( + "lua5.4 liblua5.4-dev luarocks build-essential", + "lua lua-devel luarocks gcc make", + "lua luarocks base-devel", + )]), + (Self::Cmake, Os::Windows) => none(vec![winget("Kitware.CMake")]), + (Self::Cmake, Os::Mac) => none(vec![brew("cmake")]), + (Self::Cmake, Os::Linux) => none(vec![pkg("cmake", "cmake", "cmake")]), + (Self::Cc, Os::Windows) => Install { + cmds: vec![Cmd::new( + "winget", + [ + "install", "-e", "--id", "Microsoft.VisualStudio.2022.BuildTools", "--override", + "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended", + ], + )], + note: Some("A large download (a few GB); it only has to happen once."), + }, + (Self::Cc | Self::Git, Os::Mac) => none(vec![Cmd::script("xcode-select --install")]), + (Self::Cc, Os::Linux) => none(vec![pkg("build-essential", "gcc gcc-c++ make", "base-devel")]), + (Self::Git, Os::Windows) => none(vec![winget("Git.Git")]), + (Self::Git, Os::Linux) => none(vec![pkg("git", "git", "git")]), + } + } +} + +fn cc_probe() -> Option { + if OS == Os::Windows { + let root = std::env::var_os("ProgramFiles(x86)")?; + let vswhere = std::path::Path::new(&root).join("Microsoft Visual Studio/Installer/vswhere.exe"); + let out = Cmd::new( + vswhere.to_str()?, + [ + "-latest", "-products", "*", "-requires", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", + "-property", "installationPath", + ], + ) + .capture()?; + let path = out.trim(); + return (!path.is_empty()).then(|| "Visual Studio C++ tools".to_owned()); + } + ["cc", "gcc", "clang"].into_iter().find_map(|c| which(c).map(|_| c.to_owned())) +} + +/// Looks for each tool; for the missing ones shows how to install the newest, offers to run it and +/// looks again. Returns the tools that are still missing. +pub fn ensure(tools: &[Tool]) -> Result> { + let mut wanted: Vec = Vec::new(); + for t in tools { + if !wanted.contains(t) { + wanted.push(*t); + } + } + let missing: Vec = wanted.into_iter().filter(|t| t.probe().is_none()).collect(); + if missing.is_empty() { + return Ok(missing); + } + let names: Vec<&str> = missing.iter().map(|t| t.label()).collect(); + ui::warn(format!("Not installed: {}", names.join(", "))); + let mut done: Vec = Vec::new(); + for tool in &missing { + let install = tool.install(); + let shown: Vec = install.cmds.iter().map(Cmd::display).collect(); + if shown.iter().all(|s| done.contains(s)) { + continue; // the same command already installed this one (Lua and LuaRocks) + } + let mut body = shown.iter().map(|s| format!("$ {}", ui::code(s))).collect::>().join("\n"); + if let Some(n) = install.note { + body = format!("{body}\n{}", ui::dim(n)); + } + ui::note(&format!("Install the newest {}", tool.label()), &body); + let go = INSTALL_WITHOUT_ASKING.load(Ordering::Relaxed) + || (ui::asking() && ui::confirm(&format!("Run it now to install {}?", tool.label()), true)?); + if !go { + continue; + } + for cmd in &install.cmds { + ui::flush(); + if !cmd.run_inherit().is_ok_and(|s| s.success()) { + ui::error(format!("Could not install {}. Run the command above yourself, then `bui doctor`.", tool.label())); + break; + } + } + done.extend(shown); + } + let still: Vec = missing.into_iter().filter(|t| t.probe().is_none()).collect(); + if !still.is_empty() && !done.is_empty() { + ui::info(format!( + "Installed, but not visible to this terminal yet: open a new terminal and run {}.", + ui::code("bui doctor") + )); + } + Ok(still) +} diff --git a/tools/bui/src/ui.rs b/tools/bui/src/ui.rs new file mode 100644 index 00000000..65596689 --- /dev/null +++ b/tools/bui/src/ui.rs @@ -0,0 +1,364 @@ +//! Everything the user sees: the banner, prompts, spinners and progress bars, in one look. Nothing +//! else in `bui` prints directly, so a terminal that cannot draw (a pipe, CI) falls back to plain +//! lines here and only here. + +use std::fmt::Display; +use std::io::{self, IsTerminal, Write}; +use std::process::exit; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::thread; +use std::time::Duration; + +use anyhow::Result; +use cliclack::{ProgressBar, Theme, ThemeState}; +use console::{Style, Term, style, truncate_str}; + +/// Blender's orange to its blue: the logo's gradient and the accent color of the prompts. +const ORANGE: (u8, u8, u8) = (232, 125, 13); +const BLUE: (u8, u8, u8) = (71, 133, 214); + +const LOGO: [&str; 6] = [ + "██████╗ ██╗ ██╗██╗", + "██╔══██╗██║ ██║██║", + "██████╔╝██║ ██║██║", + "██╔══██╗██║ ██║██║", + "██████╔╝╚██████╔╝██║", + "╚═════╝ ╚═════╝ ╚═╝", +]; + +static PLAIN: AtomicBool = AtomicBool::new(false); +static AUTO: AtomicBool = AtomicBool::new(false); +static YES: AtomicBool = AtomicBool::new(false); + +/// Can this terminal take prompts and animation: a terminal on both ends, and not CI. +pub fn interactive() -> bool { + io::stdin().is_terminal() && io::stderr().is_terminal() && std::env::var_os("CI").is_none() +} + +/// Sets how to talk: `plain` (no animation), `auto` (answer every question with its default). +pub fn init(plain: bool, auto: bool) { + let plain = plain || !interactive() || std::env::var_os("NO_COLOR").is_some(); + PLAIN.store(plain, Ordering::Relaxed); + AUTO.store(auto || !interactive(), Ordering::Relaxed); + YES.store(auto, Ordering::Relaxed); + if !plain { + cliclack::set_theme(BuiTheme); + } +} + +fn plain() -> bool { + PLAIN.load(Ordering::Relaxed) +} + +fn auto() -> bool { + AUTO.load(Ordering::Relaxed) +} + +/// Can the user be asked (a terminal, and no `--yes`)? Anything that changes the machine needs this, +/// or a flag that names it. +pub fn asking() -> bool { + !auto() +} + +/// Without a terminal and without `--yes` nothing can be answered: say so instead of guessing. +fn unanswerable(prompt: &str) -> anyhow::Error { + anyhow::anyhow!("cannot ask \"{prompt}\" without a terminal: pass the option as a flag, or --yes for the defaults") +} + +// --------------------------------------------------------------------------------------------- +// Color + +fn lerp(a: (u8, u8, u8), b: (u8, u8, u8), t: f32) -> (u8, u8, u8) { + let mix = |x: u8, y: u8| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8; + (mix(a.0, b.0), mix(a.1, b.1), mix(a.2, b.2)) +} + +fn truecolor() -> bool { + std::env::var("COLORTERM").is_ok_and(|v| v.contains("truecolor") || v.contains("24bit")) + || std::env::var_os("WT_SESSION").is_some() + || std::env::var_os("TERM_PROGRAM").is_some() +} + +/// `text` in an RGB color (the nearest of 256 where the terminal has no true color). +pub fn paint(text: &str, (r, g, b): (u8, u8, u8)) -> String { + if !console::colors_enabled_stderr() { + return text.to_owned(); + } + if truecolor() { + return format!("\x1b[38;2;{r};{g};{b}m{text}\x1b[0m"); + } + let q = |c: u8| (u16::from(c) * 5 / 255) as u8; + format!("\x1b[38;5;{}m{text}\x1b[0m", 16 + 36 * q(r) + 6 * q(g) + q(b)) +} + +pub fn accent(text: &str) -> String { + paint(text, ORANGE) +} + +/// A command or a path, as the user would type it. +pub fn code(text: &str) -> String { + style(text).cyan().to_string() +} + +pub fn dim(text: &str) -> String { + style(text).dim().to_string() +} + +struct BuiTheme; + +impl Theme for BuiTheme { + fn bar_color(&self, state: &ThemeState) -> Style { + match state { + ThemeState::Active => Style::new().color256(208), + ThemeState::Cancel => Style::new().red(), + ThemeState::Submit => Style::new().bright().black(), + ThemeState::Error(_) => Style::new().yellow(), + } + } +} + +// --------------------------------------------------------------------------------------------- +// Banner + +/// The logo, wiped in left to right with a glint on the edge, then the tagline. +pub fn banner(animate: bool) { + let version = env!("CARGO_PKG_VERSION"); + if plain() { + eprintln!("bui {version}"); + return; + } + let width = LOGO[0].chars().count(); + let term = Term::stderr(); + let frame = |reveal: usize| { + let mut out = String::new(); + for line in LOGO { + for (x, ch) in line.chars().enumerate() { + if x >= reveal || ch == ' ' { + out.push(' '); + } else if x + 3 >= reveal && reveal < width { + out.push_str(&paint(&ch.to_string(), (255, 245, 230))); + } else { + out.push_str(&paint(&ch.to_string(), lerp(ORANGE, BLUE, x as f32 / width as f32))); + } + } + out.push('\n'); + } + out + }; + let _ = term.hide_cursor(); + eprintln!(); + if animate { + for reveal in (0..width).step_by(2) { + eprint!("{}", frame(reveal)); + thread::sleep(Duration::from_millis(14)); + let _ = term.move_cursor_up(LOGO.len()); + } + } + eprint!("{}", frame(width)); + eprintln!(" {}", style(format!("v{version}")).dim()); + eprintln!(); + let _ = term.show_cursor(); +} + +// --------------------------------------------------------------------------------------------- +// Words + +pub fn intro(title: &str) { + if plain() { + eprintln!("{title}"); + } else { + let _ = cliclack::intro(style(format!(" {title} ")).black().on_color256(208)); + } +} + +pub fn outro(message: &str) { + if plain() { + eprintln!("{message}"); + } else { + let _ = cliclack::outro(message); + } +} + +pub fn info(message: impl Display) { + if plain() { eprintln!(" {message}") } else { let _ = cliclack::log::info(message); } +} + +pub fn success(message: impl Display) { + if plain() { eprintln!("✔ {message}") } else { let _ = cliclack::log::success(message); } +} + +pub fn warn(message: impl Display) { + if plain() { eprintln!("! {message}") } else { let _ = cliclack::log::warning(message); } +} + +pub fn error(message: impl Display) { + if plain() { eprintln!("✘ {message}") } else { let _ = cliclack::log::error(message); } +} + +/// A titled box. +pub fn note(title: &str, body: &str) { + if plain() { + eprintln!("{title}\n{body}"); + } else { + let _ = cliclack::note(title, body); + } +} + +/// Ends the program as the user cancelled (Esc, Ctrl-C). +pub fn cancelled() -> ! { + if plain() { + eprintln!("cancelled"); + } else { + let _ = cliclack::outro_cancel("Cancelled"); + } + exit(130) +} + +fn answer(r: io::Result) -> Result { + match r { + Ok(v) => Ok(v), + Err(e) if e.kind() == io::ErrorKind::Interrupted => cancelled(), + Err(e) => Err(e.into()), + } +} + +// --------------------------------------------------------------------------------------------- +// Questions: each has a default for `--yes` and for a terminal that cannot ask, and a `preset` +// (a command-line flag) that skips asking. + +pub struct Choice { + pub value: T, + pub label: String, + pub hint: String, +} + +pub fn choice(value: T, label: String, hint: impl Into) -> Choice { + Choice { value, label, hint: hint.into() } +} + +pub fn select(prompt: &str, choices: &[Choice], preset: Option<&T>) -> Result { + let pick = preset.and_then(|p| choices.iter().find(|c| &c.value == p)); + if preset.is_none() && auto() && !YES.load(Ordering::Relaxed) { + return Err(unanswerable(prompt)); + } + if let Some(c) = pick.or_else(|| auto().then(|| &choices[0])) { + info(format!("{prompt} {}", style(&c.label).bold())); + return Ok(c.value.clone()); + } + let mut q = cliclack::select(prompt); + for c in choices { + q = q.item(c.value.clone(), &c.label, &c.hint); + } + answer(q.interact()) +} + +/// Yes or no. With `--yes` the default; without a terminal, no: nothing happens that was not asked for. +pub fn confirm(prompt: &str, default: bool) -> Result { + if auto() { + let answer = default && YES.load(Ordering::Relaxed); + info(format!("{prompt} {}", style(if answer { "yes" } else { "no" }).bold())); + return Ok(answer); + } + answer(cliclack::confirm(prompt).initial_value(default).interact()) +} + +/// Text with a default; `valid` returns a message for a bad answer. +pub fn input(prompt: &str, default: &str, valid: impl Fn(&String) -> Option + 'static) -> Result { + if auto() { + if !YES.load(Ordering::Relaxed) { + return Err(unanswerable(prompt)); + } + info(format!("{prompt} {}", style(default).bold())); + return Ok(default.to_owned()); + } + answer( + cliclack::input(prompt) + .default_input(default) + .placeholder(default) + .validate(move |s: &String| valid(s).map_or(Ok(()), Err)) + .interact(), + ) +} + +// --------------------------------------------------------------------------------------------- +// Work that takes a while + +/// A spinner with a message that follows what is happening. +pub struct Task { + bar: Option, +} + +pub fn task(message: &str) -> Task { + if plain() { + eprintln!("… {message}"); + return Task { bar: None }; + } + let bar = cliclack::spinner(); + bar.start(message); + Task { bar: Some(bar) } +} + +/// A bar for `len` units (a download). +pub fn progress(message: &str, len: u64) -> Task { + if plain() { + eprintln!("… {message}"); + return Task { bar: None }; + } + let bar = cliclack::progress_bar(len).with_download_template(); + bar.start(message); + Task { bar: Some(bar) } +} + +impl Task { + /// The one-line status next to the spinner (truncated to the terminal). + pub fn set(&self, message: &str) { + if let Some(b) = &self.bar { + let width = Term::stderr().size().1 as usize; + b.set_message(truncate_str(message, width.saturating_sub(12), "…")); + } + } + + pub fn position(&self, done: u64, total: Option) { + if let Some(b) = &self.bar { + if let Some(t) = total { + b.set_length(t); + } + b.set_position(done); + } + } + + pub fn done(self, message: &str) { + match self.bar { + Some(b) => b.stop(message), + None => eprintln!("✔ {message}"), + } + } + + pub fn fail(self, message: &str) { + match self.bar { + Some(b) => b.error(message), + None => eprintln!("✘ {message}"), + } + } +} + +/// Runs a command under a spinner that shows what it prints; on failure shows what it said last. +pub fn run(title: &str, cmd: &crate::sys::Cmd) -> Result { + let t = task(title); + let out = cmd.run_live(|line| t.set(&format!("{title} {}", dim(line))))?; + if out.ok { + t.done(title); + } else { + t.fail(&format!("{title} failed")); + for line in &out.tail { + eprintln!(" {}", dim(line)); + } + info(format!("Run it yourself to see everything: {}", code(&cmd.display()))); + } + Ok(out.ok) +} + +/// Flushes what was printed (before handing the terminal to another program). +pub fn flush() { + let _ = io::stderr().flush(); +} diff --git a/tools/bui/src/update.rs b/tools/bui/src/update.rs new file mode 100644 index 00000000..7d33f192 --- /dev/null +++ b/tools/bui/src/update.rs @@ -0,0 +1,183 @@ +//! `bui update`: this program from the newest release (checked, with a progress bar), then the BUI +//! packages of the project you are in. + +use std::fmt::Write as _; +use std::fs; +use std::io::{Cursor, Read, Write}; +use std::path::Path; + +use anyhow::{Context, Result, bail}; +use sha2::{Digest, Sha256}; + +use crate::check::Check; +use crate::cli::UpdateArgs; +use crate::sys::{OS, Os, semver}; +use crate::{doctor, project, registry, ui}; + +pub fn run(args: &UpdateArgs) -> Result<()> { + ui::banner(false); + ui::intro("bui update"); + let have = env!("CARGO_PKG_VERSION"); + match registry::release_tag() { + None => ui::warn("Could not reach GitHub to look for a newer bui."), + Some(tag) if semver(&tag) > semver(have) => { + ui::info(format!("A newer bui: {have} → {}", ui::accent(tag.trim_start_matches('v')))); + if args.check { + ui::info(format!("Update with {}", ui::code("bui update"))); + } else if ui::confirm("Update bui now?", true)? { + replace_self(&tag)?; + ui::success(format!("bui is now {}", tag.trim_start_matches('v'))); + } + } + Some(_) => ui::success(format!("bui {have} is the newest")), + } + + if args.cli_only { + ui::outro("Done"); + return Ok(()); + } + let Some(p) = project::find(Path::new(".")) else { + ui::outro("Done (run it inside a project to update its packages too)"); + return Ok(()); + }; + let app = p.meta.stack.app(); + ui::info(format!("Project {} ({})", p.meta.name, app.label())); + if args.check { + for c in app.checks(&p.dir) { + ui::info(doctor::line(&c)); + } + } else { + let steps = app.update(&p.dir); + if steps.is_empty() { + ui::success("Nothing to update in the project"); + } else if ui::confirm("Update the project's BUI packages to the newest?", true)? { + for s in &steps { + if s.work.perform(&s.title)? { + continue; + } + // the reason was shown; an optional step may fail, a required one leaves the project half updated + if !s.optional { + bail!("{} failed: the project's packages are not fully updated (`bui doctor` shows what is left)", s.title); + } + ui::warn(format!("{} did not work; carrying on", s.title)); + } + let outdated: Vec = app.checks(&p.dir).into_iter().filter(|c| !c.is_ok()).collect(); + for c in &outdated { + ui::warn(doctor::line(c)); + } + } + } + ui::outro(&format!("{} Done", ui::accent("✦"))); + Ok(()) +} + +/// What the release's archive for this machine is called. +fn asset() -> Result<(String, bool)> { + let triple = match (std::env::consts::OS, std::env::consts::ARCH) { + ("windows", "x86_64") => "x86_64-pc-windows-msvc", + ("windows", "aarch64") => "aarch64-pc-windows-msvc", + ("linux", "x86_64") => "x86_64-unknown-linux-gnu", + ("linux", "aarch64") => "aarch64-unknown-linux-gnu", + ("macos", "x86_64") => "x86_64-apple-darwin", + ("macos", "aarch64") => "aarch64-apple-darwin", + (os, arch) => bail!("there is no bui build for {os} on {arch}"), + }; + let zip = OS == Os::Windows; + Ok((format!("bui-{triple}.{}", if zip { "zip" } else { "tar.gz" }), zip)) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().fold(String::new(), |mut s, b| { + let _ = write!(s, "{b:02x}"); + s + }) +} + +fn replace_self(tag: &str) -> Result<()> { + let (asset, zip) = asset()?; + let bar = ui::progress(&format!("Downloading {asset}"), 1); + let archive = registry::download(®istry::download_url(tag, &asset), |done, total| bar.position(done, total)); + let Some(archive) = archive else { + bar.fail("Download failed"); + bail!("could not download {asset} for {tag}"); + }; + bar.done(&format!("Downloaded {:.1} MB", archive.len() as f64 / 1_048_576.0)); + + // the checksum the release publishes next to it + let sums = registry::download(®istry::download_url(tag, &format!("{asset}.sha256")), |_, _| {}) + .and_then(|b| String::from_utf8(b).ok()) + .context("the release has no checksum for this download")?; + let want = sums.split_whitespace().next().unwrap_or_default().to_ascii_lowercase(); + if hex(&Sha256::digest(&archive)) != want { + bail!("the download does not match its checksum: not installing it"); + } + ui::success("Checksum matches"); + + let exe_name = if zip { "bui.exe" } else { "bui" }; + let binary = if zip { + let mut z = zip::ZipArchive::new(Cursor::new(archive))?; + let mut file = z.by_name(exe_name).with_context(|| format!("{exe_name} is not in the archive"))?; + let mut out = Vec::new(); + file.read_to_end(&mut out)?; + out + } else { + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(Cursor::new(archive))); + let mut out = Vec::new(); + for entry in tar.entries()? { + let mut entry = entry?; + if entry.path()?.file_name().is_some_and(|n| n == exe_name) { + entry.read_to_end(&mut out)?; + break; + } + } + if out.is_empty() { + bail!("{exe_name} is not in the archive"); + } + out + }; + let staged = stage(&binary, zip)?; + // the file that goes in is the one that was verified: read back, it is the same bytes + if fs::read(&staged).ok().is_none_or(|b| Sha256::digest(&b) != Sha256::digest(&binary)) { + bail!("the staged copy of the new bui changed before it could be installed: not installing it"); + } + // `staged` deletes itself when it goes out of scope, installed or not + self_replace::self_replace(&staged).context("replacing the running bui") +} + +/// Writes `binary` to a new file with a random name that nothing else can have made (it must not exist) and +/// only this user can read or change, beside the running bui (the same disk, in a folder that is already +/// the user's) or else in the temp folder. The file is deleted when the returned path is dropped. +fn stage(binary: &[u8], zip: bool) -> Result { + let mut builder = tempfile::Builder::new(); + builder.prefix(".bui-update-").suffix(if zip { ".exe" } else { "" }); + let beside = std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf)); + let mut file = match beside.map(|dir| builder.tempfile_in(dir)) { + Some(Ok(file)) => file, + _ => builder.tempfile().context("making a private file for the new bui")?, // 0600 on Unix, exclusive + }; + file.write_all(binary)?; + file.flush()?; + let path = file.into_temp_path(); // closes the file; the path still deletes it + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&path, fs::Permissions::from_mode(0o700))?; + } + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_staged_binary_is_a_new_file_that_goes_away() { + let one = stage(b"one", false).unwrap(); + let two = stage(b"two", false).unwrap(); + assert_ne!(one.to_path_buf(), two.to_path_buf(), "names are random, never reused"); + assert_eq!(fs::read(&one).unwrap(), b"one"); + let path = one.to_path_buf(); + drop(one); + assert!(!path.exists()); + } +} diff --git a/tools/bui/templates/c/CMakeLists.txt b/tools/bui/templates/c/CMakeLists.txt new file mode 100644 index 00000000..7e62050d --- /dev/null +++ b/tools/bui/templates/c/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.25) +project({{ident}} LANGUAGES C CXX) +if(APPLE) + enable_language(OBJC) # bui::kit has Objective-C on macOS +endif() + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # for clangd and clang-tidy + +# the app ends up in build/bin, whatever the generator +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +foreach(config DEBUG RELEASE RELWITHDEBINFO MINSIZEREL) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${config} ${CMAKE_BINARY_DIR}/bin) +endforeach() + +# BUI, fetched at a release (`bui update` moves the tag to the newest release) +include(FetchContent) +FetchContent_Declare( + bui + GIT_REPOSITORY https://github.com/ppmpreetham/BUI.git + GIT_TAG {{tag}} + GIT_SHALLOW TRUE) +set(BUI_BUILD_TESTS OFF CACHE BOOL "" FORCE) +set(BUI_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) +set(BUI_BUILD_PYTHON_BINDINGS OFF CACHE BOOL "" FORCE) +set(BUI_BUILD_IMGUI OFF CACHE BOOL "" FORCE) +FetchContent_MakeAvailable(bui) + +add_executable(app src/main.c) +target_link_libraries(app PRIVATE bui::kit) +target_compile_options(app PRIVATE + $<$:/W4> + $<$>:-Wall -Wextra -Wpedantic>) diff --git a/tools/bui/templates/c/CMakePresets.json b/tools/bui/templates/c/CMakePresets.json new file mode 100644 index 00000000..0f80f5e0 --- /dev/null +++ b/tools/bui/templates/c/CMakePresets.json @@ -0,0 +1,19 @@ +{ + "version": 6, + "configurePresets": [ + { "name": "default", "binaryDir": "${sourceDir}/build" } + ], + "buildPresets": [ + { "name": "default", "configurePreset": "default", "configuration": "Debug", "targets": ["app"] }, + { "name": "release", "configurePreset": "default", "configuration": "Release", "targets": ["app"] } + ], + "workflowPresets": [ + { + "name": "default", + "steps": [ + { "type": "configure", "name": "default" }, + { "type": "build", "name": "default" } + ] + } + ] +} diff --git a/tools/bui/templates/c/README.md b/tools/bui/templates/c/README.md new file mode 100644 index 00000000..32ee92a6 --- /dev/null +++ b/tools/bui/templates/c/README.md @@ -0,0 +1,12 @@ +# {{title}} + +A [BUI](https://bui.preetham.top) app in C, built with CMake (BUI is fetched at release `{{tag}}`). + +```sh +bui dev # configure, build and run it +bui build # a release build +bui doctor # check the toolchain, and fix what is wrong +bui update # move BUI to the newest release +``` + +`clang-format -i src/*.c` formats (see `.clang-format`); `clang-tidy src/main.c -p build` lints (see `.clang-tidy`). diff --git a/tools/bui/templates/c/_clang-format b/tools/bui/templates/c/_clang-format new file mode 100644 index 00000000..012fe253 --- /dev/null +++ b/tools/bui/templates/c/_clang-format @@ -0,0 +1,6 @@ +BasedOnStyle: LLVM +IndentWidth: 2 +ColumnLimit: 100 +BreakBeforeBraces: Linux +AllowShortFunctionsOnASingleLine: None +SortIncludes: CaseSensitive diff --git a/tools/bui/templates/c/_clang-tidy b/tools/bui/templates/c/_clang-tidy new file mode 100644 index 00000000..467ccf76 --- /dev/null +++ b/tools/bui/templates/c/_clang-tidy @@ -0,0 +1,11 @@ +Checks: > + bugprone-*, + clang-analyzer-*, + misc-*, + performance-*, + portability-*, + readability-*, + -readability-magic-numbers, + -readability-identifier-length +WarningsAsErrors: '' +HeaderFilterRegex: 'src/.*' diff --git a/tools/bui/templates/c/_gitignore b/tools/bui/templates/c/_gitignore new file mode 100644 index 00000000..902f3c72 --- /dev/null +++ b/tools/bui/templates/c/_gitignore @@ -0,0 +1,3 @@ +build/ +.cache/ +compile_commands.json diff --git a/tools/bui/templates/c/src/main.c b/tools/bui/templates/c/src/main.c new file mode 100644 index 00000000..0a50d2fb --- /dev/null +++ b/tools/bui/templates/c/src/main.c @@ -0,0 +1,54 @@ +#include + +#include "BUI_kit.h" + +static void on_event(void *data, BKNode *node, int kind, void *ref, double a, double b) +{ + (void)data; + (void)ref; + (void)a; + (void)b; + if (kind == BK_EV_CLICK) { + printf("clicked %s\n", BK_get_str(node, "text")); + } + else if (kind == BK_EV_CHANGE) { + printf("%s = %g\n", BK_get_str(node, "label"), BK_get_num(node, "value")); + } +} + +int main(void) +{ + BKNode *root = BK_node_new("frame"); + BK_set_num(root, "padding", 8); + + BKNode *size = BK_node_new("slider"); + BK_set_str(size, "label", "Size"); + BK_set_num(size, "min", 0); + BK_set_num(size, "max", 10); + BK_set_num(size, "value", 2.5); + BK_node_add(root, size, -1); + BK_geom_set_manager(size, BK_GEOM_PACK); + BK_geom_set(size, "fill", 1); + + BKNode *apply = BK_node_new("button"); + BK_set_str(apply, "text", "Apply"); + BK_node_add(root, apply, -1); + BK_geom_set_manager(apply, BK_GEOM_PACK); + BK_geom_set(apply, "fill", 1); + BK_geom_set(apply, "pady0", 6); + + BKContext *ctx = BK_context_new(root); + BKHost host = {0}; + host.emit = on_event; + BK_context_set_host(ctx, &host); + + if (!BK_window_supported()) { + fprintf(stderr, "No window system here.\n"); + return 1; + } + BKWindow *win = BK_window_new(ctx, "{{title}}", 320, 120); + BK_window_show(win); + BK_window_run(); + BK_window_free(win); + return 0; +} diff --git a/tools/bui/templates/js/common/README.md b/tools/bui/templates/js/common/README.md new file mode 100644 index 00000000..b05893e9 --- /dev/null +++ b/tools/bui/templates/js/common/README.md @@ -0,0 +1,12 @@ +# {{title}} + +A [BUI](https://bui.preetham.top) app: native windows from JavaScript, with no browser or Electron. + +```sh +bui dev # run it and restart on every save +bui build # one small executable (about 5 MB) +bui doctor # check the setup, and fix what is wrong +bui update # update bui and this project's packages +``` + +The scripts in `package.json` are what those run (`dev`, `build`, `lint`, `format`, `fix`). diff --git a/tools/bui/templates/js/common/_gitignore b/tools/bui/templates/js/common/_gitignore new file mode 100644 index 00000000..6d3b97ea --- /dev/null +++ b/tools/bui/templates/js/common/_gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist/ +# `bui build` writes the app next to the project +main +main.exe +*.log diff --git a/tools/bui/templates/js/common/biome.json b/tools/bui/templates/js/common/biome.json new file mode 100644 index 00000000..29610f12 --- /dev/null +++ b/tools/bui/templates/js/common/biome.json @@ -0,0 +1,6 @@ +{ + "formatter": { "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 }, + "javascript": { "formatter": { "quoteStyle": "single", "semicolons": "asNeeded" } }, + "files": { "includes": ["**", "!**/*.svelte"] }, + "linter": { "enabled": true } +} diff --git a/tools/bui/templates/js/react-js/src/main.jsx b/tools/bui/templates/js/react-js/src/main.jsx new file mode 100644 index 00000000..3d1167bd --- /dev/null +++ b/tools/bui/templates/js/react-js/src/main.jsx @@ -0,0 +1,22 @@ +/** @jsxImportSource @blender-ui/react */ +import { render, useState } from '@blender-ui/react' + +function Counter() { + const [count, setCount] = useState(0) + const [name, setName] = useState('') + return ( +
+

{{title}}

+
+ Clicks: {count} + +
+ setName(e.target.value)} /> + {name.value &&

Hello, {name}!

} +
+ ) +} + +const { window } = render(, { title: '{{title}}', width: 420, height: 260 }) +window.body.setAttribute('styled', '') +window.body.className = 'm-0 min-h-screen bg-[#2b2b2b] text-[#e6e6e6]' diff --git a/tools/bui/templates/js/react-ts/src/main.tsx b/tools/bui/templates/js/react-ts/src/main.tsx new file mode 100644 index 00000000..18b1534c --- /dev/null +++ b/tools/bui/templates/js/react-ts/src/main.tsx @@ -0,0 +1,21 @@ +import { render, useState } from '@blender-ui/react' + +function Counter() { + const [count, setCount] = useState(0) + const [name, setName] = useState('') + return ( +
+

{{title}}

+
+ Clicks: {count} + +
+ setName(e.target.value)} /> + {name.value &&

Hello, {name}!

} +
+ ) +} + +const { window } = render(, { title: '{{title}}', width: 420, height: 260 }) +window.body.setAttribute('styled', '') +window.body.className = 'm-0 min-h-screen bg-[#2b2b2b] text-[#e6e6e6]' diff --git a/tools/bui/templates/js/svelte/src/Counter.svelte b/tools/bui/templates/js/svelte/src/Counter.svelte new file mode 100644 index 00000000..f7952dcf --- /dev/null +++ b/tools/bui/templates/js/svelte/src/Counter.svelte @@ -0,0 +1,16 @@ + + +
+

{{title}}

+
+ Clicks: {count} + +
+ + {#if name}

Hello, {name}!

{/if} +
diff --git a/tools/bui/templates/js/svelte/src/main.js b/tools/bui/templates/js/svelte/src/main.js new file mode 100644 index 00000000..e52c9d07 --- /dev/null +++ b/tools/bui/templates/js/svelte/src/main.js @@ -0,0 +1,6 @@ +import { render } from '@blender-ui/svelte' +import Counter from './Counter.svelte' + +const { window } = render(Counter, { title: '{{title}}', width: 420, height: 260 }) +window.body.setAttribute('styled', '') +window.body.className = 'm-0 min-h-screen bg-[#2b2b2b] text-[#e6e6e6]' diff --git a/tools/bui/templates/js/vanilla-js/src/main.js b/tools/bui/templates/js/vanilla-js/src/main.js new file mode 100644 index 00000000..d50f2b9e --- /dev/null +++ b/tools/bui/templates/js/vanilla-js/src/main.js @@ -0,0 +1,28 @@ +import { App } from '@blender-ui/native' + +const app = new App() +const win = app.window({ title: '{{title}}', width: 360, height: 220 }) +win.body.setAttribute('styled', '') +win.body.className = 'm-0 flex flex-col gap-3 bg-[#2b2b2b] p-6 text-[#e6e6e6]' + +const title = win.createElement('h1') +title.className = 'text-xl font-bold' +title.textContent = '{{title}}' + +const row = win.createElement('div') +row.className = 'flex items-center gap-3' +const label = win.createElement('span') +label.textContent = 'Clicks: 0' +const button = win.createElement('button') +button.textContent = 'Add one' + +let clicks = 0 +button.addEventListener('click', () => { + clicks += 1 + label.textContent = `Clicks: ${clicks}` +}) + +row.appendChild(label) +row.appendChild(button) +win.body.appendChild(title) +win.body.appendChild(row) diff --git a/tools/bui/templates/js/vanilla-ts/src/main.ts b/tools/bui/templates/js/vanilla-ts/src/main.ts new file mode 100644 index 00000000..d50f2b9e --- /dev/null +++ b/tools/bui/templates/js/vanilla-ts/src/main.ts @@ -0,0 +1,28 @@ +import { App } from '@blender-ui/native' + +const app = new App() +const win = app.window({ title: '{{title}}', width: 360, height: 220 }) +win.body.setAttribute('styled', '') +win.body.className = 'm-0 flex flex-col gap-3 bg-[#2b2b2b] p-6 text-[#e6e6e6]' + +const title = win.createElement('h1') +title.className = 'text-xl font-bold' +title.textContent = '{{title}}' + +const row = win.createElement('div') +row.className = 'flex items-center gap-3' +const label = win.createElement('span') +label.textContent = 'Clicks: 0' +const button = win.createElement('button') +button.textContent = 'Add one' + +let clicks = 0 +button.addEventListener('click', () => { + clicks += 1 + label.textContent = `Clicks: ${clicks}` +}) + +row.appendChild(label) +row.appendChild(button) +win.body.appendChild(title) +win.body.appendChild(row) diff --git a/tools/bui/templates/lua/README.md b/tools/bui/templates/lua/README.md new file mode 100644 index 00000000..7140adcc --- /dev/null +++ b/tools/bui/templates/lua/README.md @@ -0,0 +1,12 @@ +# {{title}} + +A [BUI](https://bui.preetham.top) app in Lua 5.4. + +```sh +bui dev # run it (lua main.lua, with this project's rocks) +bui doctor # check the setup, and fix what is wrong +bui update # update bui and this project's blenderui +``` + +Rocks are installed into `lua_modules/` (nothing global): `luarocks --tree lua_modules install `. +Lint with `luarocks --tree lua_modules path` set and `luacheck .`; format with [StyLua](https://github.com/JohnnyMorganz/StyLua). diff --git a/tools/bui/templates/lua/_gitignore b/tools/bui/templates/lua/_gitignore new file mode 100644 index 00000000..82b96120 --- /dev/null +++ b/tools/bui/templates/lua/_gitignore @@ -0,0 +1,2 @@ +lua_modules/ +.luarocks/ diff --git a/tools/bui/templates/lua/_luacheckrc b/tools/bui/templates/lua/_luacheckrc new file mode 100644 index 00000000..c8a8c8f4 --- /dev/null +++ b/tools/bui/templates/lua/_luacheckrc @@ -0,0 +1,3 @@ +std = "lua54" +max_line_length = 100 +exclude_files = { "lua_modules" } diff --git a/tools/bui/templates/lua/_luarc.json b/tools/bui/templates/lua/_luarc.json new file mode 100644 index 00000000..abf78cf1 --- /dev/null +++ b/tools/bui/templates/lua/_luarc.json @@ -0,0 +1,6 @@ +{ + "runtime.version": "Lua 5.4", + "workspace.library": ["lua_modules/share/lua/5.4"], + "workspace.ignoreDir": ["lua_modules"], + "diagnostics.globals": [] +} diff --git a/tools/bui/templates/lua/main.lua b/tools/bui/templates/lua/main.lua new file mode 100644 index 00000000..a118958f --- /dev/null +++ b/tools/bui/templates/lua/main.lua @@ -0,0 +1,27 @@ +local bui = require("bui") + +local root = bui.Node("column") +root:set("padding", 12) +root:set("spacing", 6) + +local title = bui.Node("label") +title:set("text", "{{title}}") +root:add(title) + +local count = 0 +local label = bui.Node("label") +label:set("text", "Clicks: 0") +root:add(label) + +local button = bui.Node("button") +button:set("text", "Add one") +button:on(bui.EV_CLICK, function() + count = count + 1 + label:set("text", "Clicks: " .. count) +end) +root:add(button) + +local win, err = bui.open({ root = root, title = "{{title}}", width = 320, height = 200 }) +if not win then + print("No window: " .. tostring(err)) +end diff --git a/tools/bui/templates/lua/stylua.toml b/tools/bui/templates/lua/stylua.toml new file mode 100644 index 00000000..9218af58 --- /dev/null +++ b/tools/bui/templates/lua/stylua.toml @@ -0,0 +1,4 @@ +column_width = 100 +indent_type = "Spaces" +indent_width = 2 +quote_style = "AutoPreferDouble" diff --git a/tools/bui/templates/python/common/README.md b/tools/bui/templates/python/common/README.md new file mode 100644 index 00000000..d84081a2 --- /dev/null +++ b/tools/bui/templates/python/common/README.md @@ -0,0 +1,13 @@ +# {{title}} + +A [BUI](https://bui.preetham.top) app in Python. + +```sh +bui dev # run it (uv run main.py) +bui doctor # check the setup, and fix what is wrong +bui update # update bui and this project's blenderui +uv run ruff check . # lint +uv run ruff format . # format +``` + +`uv` keeps the Python version, the virtual environment (`.venv`) and the lock file (`uv.lock`). diff --git a/tools/bui/templates/python/common/_gitignore b/tools/bui/templates/python/common/_gitignore new file mode 100644 index 00000000..96a4e967 --- /dev/null +++ b/tools/bui/templates/python/common/_gitignore @@ -0,0 +1,6 @@ +.venv/ +__pycache__/ +*.pyc +.ruff_cache/ +dist/ +build/ diff --git a/tools/bui/templates/python/common/pyproject.toml b/tools/bui/templates/python/common/pyproject.toml new file mode 100644 index 00000000..52a717b1 --- /dev/null +++ b/tools/bui/templates/python/common/pyproject.toml @@ -0,0 +1,17 @@ +[project] +name = "{{name}}" +version = "0.1.0" +description = "A BUI app" +readme = "README.md" +requires-python = ">=3.11" +dependencies = [] + +[tool.uv] +package = false + +[tool.ruff] +line-length = 100 +target-version = "py311" + +[tool.ruff.lint] +select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "RUF", "PIE", "PT"] diff --git a/tools/bui/templates/python/components/main.py b/tools/bui/templates/python/components/main.py new file mode 100644 index 00000000..5a5491d1 --- /dev/null +++ b/tools/bui/templates/python/components/main.py @@ -0,0 +1,24 @@ +"""{{title}}: a window of Blender's own components.""" + +from blenderui.components import App, Button, Checkbox, ColorSwatch, NumberSlider, Panel + + +def main() -> None: + App( + "{{title}}", + (420, 420), + Panel( + "Transform", + NumberSlider("Scale", 1.0, min=0, max=10, on_change=print), + ), + Panel( + "Shading", + Checkbox("Shadows", True), + ColorSwatch("Color", (0.8, 0.3, 0.1, 1.0)), + ), + Button("Apply", on_click=lambda: print("applied")), + ).run() + + +if __name__ == "__main__": + main() diff --git a/tools/bui/templates/python/qt/main.py b/tools/bui/templates/python/qt/main.py new file mode 100644 index 00000000..1cbe92f3 --- /dev/null +++ b/tools/bui/templates/python/qt/main.py @@ -0,0 +1,49 @@ +"""{{title}}: Qt-style code. Only the import differs from PySide or PyQt; neither is installed.""" + +import sys + +from blenderui.qtsyntax import ( + QApplication, + QComboBox, + QFormLayout, + QLabel, + QProgressBar, + QPushButton, + QSlider, + Qt, + QVBoxLayout, + QWidget, +) + + +def main() -> int: + app = QApplication(sys.argv) + window = QWidget() + window.setWindowTitle("{{title}}") + layout = QVBoxLayout(window) + + form = QFormLayout() + kind = QComboBox() + kind.addItems(["glTF", "FBX", "OBJ"]) + quality = QSlider(Qt.Horizontal) + quality.setRange(0, 100) + form.addRow("Format:", kind) + form.addRow("Quality:", quality) + layout.addLayout(form) + + bar = QProgressBar() + quality.valueChanged.connect(bar.setValue) + layout.addWidget(bar) + + status = QLabel("Ready.") + go = QPushButton("Export") + go.clicked.connect(lambda: status.setText("Exporting as " + kind.currentText())) + layout.addWidget(status) + layout.addWidget(go) + + window.show() + return app.exec() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/bui/templates/python/tk/main.py b/tools/bui/templates/python/tk/main.py new file mode 100644 index 00000000..39be2366 --- /dev/null +++ b/tools/bui/templates/python/tk/main.py @@ -0,0 +1,21 @@ +"""{{title}}: tkinter-style code. Only the import differs from the standard library.""" + +import blenderui.tksyntax as tk +from blenderui.tksyntax import messagebox, ttk + + +def main() -> None: + root = tk.Tk() + root.title("{{title}}") + name = tk.StringVar(value="Cube") + ttk.Entry(root, textvariable=name).pack(fill="x", padx=8, pady=8) + ttk.Button( + root, + text="Greet", + command=lambda: messagebox.showinfo("Hi", "Hello " + name.get()), + ).pack() + root.mainloop() + + +if __name__ == "__main__": + main() diff --git a/tools/bui/templates/rust/Cargo.toml b/tools/bui/templates/rust/Cargo.toml new file mode 100644 index 00000000..f94b0633 --- /dev/null +++ b/tools/bui/templates/rust/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "{{name}}" +version = "0.1.0" +edition = "2024" +rust-version = "1.88" +publish = false + +[dependencies] + +[profile.release] +lto = "thin" +strip = true + +[lints.rust] +unsafe_code = "forbid" + +[lints.clippy] +all = { level = "warn", priority = -2 } +pedantic = { level = "warn", priority = -2 } +perf = { level = "warn", priority = -1 } +complexity = { level = "warn", priority = -1 } +module_name_repetitions = "allow" +missing_errors_doc = "allow" +missing_panics_doc = "allow" +redundant_clone = "warn" +use_self = "warn" +missing_const_for_fn = "warn" diff --git a/tools/bui/templates/rust/README.md b/tools/bui/templates/rust/README.md new file mode 100644 index 00000000..62063910 --- /dev/null +++ b/tools/bui/templates/rust/README.md @@ -0,0 +1,12 @@ +# {{title}} + +A [BUI](https://bui.preetham.top) app in Rust. + +```sh +bui dev # run it (cargo run) +bui build # a release build (cargo build --release) +bui doctor # check the toolchain and the project, and fix what is wrong +bui update # update bui and this project's blenderui +cargo clippy # lints (pedantic is on, see Cargo.toml) +cargo fmt # format +``` diff --git a/tools/bui/templates/rust/_gitignore b/tools/bui/templates/rust/_gitignore new file mode 100644 index 00000000..ea8c4bf7 --- /dev/null +++ b/tools/bui/templates/rust/_gitignore @@ -0,0 +1 @@ +/target diff --git a/tools/bui/templates/rust/rustfmt.toml b/tools/bui/templates/rust/rustfmt.toml new file mode 100644 index 00000000..38cba21d --- /dev/null +++ b/tools/bui/templates/rust/rustfmt.toml @@ -0,0 +1,3 @@ +edition = "2024" +max_width = 100 +use_small_heuristics = "Max" diff --git a/tools/bui/templates/rust/src/main.rs b/tools/bui/templates/rust/src/main.rs new file mode 100644 index 00000000..41e65af9 --- /dev/null +++ b/tools/bui/templates/rust/src/main.rs @@ -0,0 +1,35 @@ +use blenderui::prelude::*; + +struct Counter { + count: i32, +} + +impl Render for Counter { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + div() + .styled() + .flex() + .flex_col() + .gap_2() + .p_4() + .child(h1().child(format!("Count: {}", self.count))) + .child( + p().child("Any ") + .child(b().child("HTML element")) + .child(", styled with Tailwind-style methods or CSS."), + ) + .child(button().child("Add one").on_click(cx.listener(|this, _, _, cx| { + this.count += 1; + cx.notify(); + }))) + // a Blender slider + .child(input().input_type("range").min(0.0).max(10.0)) + } +} + +fn main() { + Application::new().run(|cx: &mut App| { + cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Counter { count: 0 })) + .expect("opening the window"); + }); +} diff --git a/tools/bump_version.py b/tools/bump_version.py index 85c4c6f4..92f91ed4 100644 --- a/tools/bump_version.py +++ b/tools/bump_version.py @@ -26,7 +26,9 @@ * LuaRocks: `bindings/lua/blenderui--1.rockspec` (its version, its source tag and its file name move; the old file is removed, as a rename). * `CHANGELOG.md`: `[Unreleased]` becomes a dated section and a fresh `[Unreleased]` opens. -* The lock files (`Cargo.lock`, `bindings/package-lock.json`) are refreshed (best effort). +* The `bui` command: `tools/bui/Cargo.toml` (it is released with every BUI release, as `bui-` + archives on the GitHub Release; `bui update` compares its own version with the release's). +* The lock files (`Cargo.lock`, `tools/bui/Cargo.lock`, `bindings/package-lock.json`) are refreshed (best effort). `--dry-run` shows what would change and touches nothing. """ @@ -146,6 +148,10 @@ def put(path: Path, text: str) -> None: out.append(line) put(toml, "".join(out)) + # the `bui` command is released with BUI: one version, so `bui update` has one to compare + cli = ROOT / "tools" / "bui" / "Cargo.toml" + put(cli, re.sub(r'(^version\s*=\s*")[^"]+(")', rf"\g<1>{new}\g<2>", read(cli), count=1, flags=re.M)) + # LuaRocks: the version is in the file name too, so the rockspec is renamed (rock,) = rockspecs() text = re.sub(r'(^version\s*=\s*")[^"]+(")', rf"\g<1>{new}-1\g<2>", read(rock), count=1, flags=re.M) @@ -180,16 +186,19 @@ def put(path: Path, text: str) -> None: return edits, gone +def cargo_lock(cwd: Path) -> bool: + """Refresh a workspace's Cargo.lock: offline first (the common case, nothing to download), then online.""" + return any(run(["cargo", "update", "--workspace", *flags], cwd=cwd, check=False).returncode == 0 for flags in (["--offline"], [])) + + def refresh_locks(npm: bool) -> list[Path]: """Best effort: a lock file that can't be refreshed is reported, not fatal.""" touched = [] - r = run(["cargo", "update", "--workspace", "--offline"], cwd=RUST, check=False) - if r.returncode != 0: - r = run(["cargo", "update", "--workspace"], cwd=RUST, check=False) - if r.returncode == 0: - touched.append(RUST / "Cargo.lock") - else: - print("warning: Cargo.lock was not refreshed (run `cargo update --workspace` in bindings/rust)") + for cwd, label in ((RUST, "bindings/rust"), (ROOT / "tools" / "bui", "tools/bui")): + if cargo_lock(cwd): + touched.append(cwd / "Cargo.lock") + else: + print(f"warning: {label}/Cargo.lock was not refreshed (run `cargo update --workspace` in {label}): CI builds with --locked and would reject it") if npm: r = run(["npm", "install", "--package-lock-only", "--ignore-scripts"], cwd=ROOT / "bindings", check=False) if r.returncode == 0: diff --git a/tools/check_versions.py b/tools/check_versions.py index 00a0fe3d..2d5433ca 100644 --- a/tools/check_versions.py +++ b/tools/check_versions.py @@ -45,6 +45,9 @@ def main() -> int: found["bindings/rust/Cargo.toml [workspace.package]"] = re.search( r'^version\s*=\s*"([^"]+)"', read(RUST / "Cargo.toml"), re.M).group(1) + found["tools/bui/Cargo.toml (the bui command)"] = re.search( + r'^version\s*=\s*"([^"]+)"', read(ROOT / "tools" / "bui" / "Cargo.toml"), re.M).group(1) + header = read(ROOT / "kit" / "include" / "BUI_kit.h") parts = [re.search(rf"#define BUI_KIT_VERSION_{p}\s+(\d+)", header) for p in ("MAJOR", "MINOR", "PATCH")] string = re.search(r'#define BUI_KIT_VERSION_STRING\s+"([^"]+)"', header) diff --git a/website/public/install.ps1 b/website/public/install.ps1 new file mode 100644 index 00000000..2bc4ed83 --- /dev/null +++ b/website/public/install.ps1 @@ -0,0 +1,136 @@ +# Installs `bui`, the command that makes, runs, checks and updates BUI apps. +# +# irm https://bui.preetham.top/install.ps1 | iex +# +# Windows (x86_64 and arm64), Windows PowerShell 5.1 and PowerShell 7. It downloads the newest release +# from GitHub, checks its checksum, puts bui.exe in %USERPROFILE%\.bui\bin and adds that folder to your +# user PATH. +# +# $env:BUI_VERSION = 'v0.5.1' install that release instead of the newest +# $env:BUI_INSTALL_DIR = 'DIR' install into DIR +# $env:BUI_NO_MODIFY_PATH = '1' do not change PATH +# +# For testing: BUI_LATEST_URL replaces the page whose redirect names the newest release, and +# BUI_INSTALLER_BASE_URL a folder that holds the archive and its .sha256. +# +# SPDX-License-Identifier: GPL-2.0-or-later + +& { + $ErrorActionPreference = 'Stop' + [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + $ProgressPreference = 'SilentlyContinue' # Windows PowerShell 5.1 crawls with its own progress bar + + $repo = 'ppmpreetham/BUI' + $installDir = if ($env:BUI_INSTALL_DIR) { $env:BUI_INSTALL_DIR } else { Join-Path $env:USERPROFILE '.bui\bin' } + $baseUrl = $env:BUI_INSTALLER_BASE_URL # for testing: a folder that holds the archive and its .sha256 + $latestUrl = if ($env:BUI_LATEST_URL) { $env:BUI_LATEST_URL } else { "https://github.com/$repo/releases/latest" } + + $esc = [char]27 + $color = [Environment]::UserInteractive -and -not $env:NO_COLOR -and ($Host.UI.SupportsVirtualTerminal -or $env:WT_SESSION) + function C($code, $text) { if ($color) { "$esc[${code}m$text$esc[0m" } else { $text } } + # the glyphs are made from character codes: this file stays plain ASCII, which any PowerShell + # reads the same whatever encoding it downloads it with + $dot = [char]0x25CF; $tick = [char]0x2714; $cross = [char]0x2718 + function Glyphs($art) { # @ = full block, 1 2 3 4 5 6 = the box corners and lines of the logo + $art.Replace('@', [string][char]0x2588).Replace('1', [string][char]0x2557).Replace('2', [string][char]0x2554).Replace('3', [string][char]0x255D).Replace('4', [string][char]0x255A).Replace('5', [string][char]0x2551).Replace('6', [string][char]0x2550) + } + # the Location of the page's redirect. Invoke-WebRequest cannot be asked for it the same way on both + # PowerShells (5.1 fails without a response, 7 hands over HttpResponseHeaders, which has no string + # indexer), so this asks HttpWebRequest, whose headers are a WebHeaderCollection on both. + function LocationOf($url) { + $request = [Net.HttpWebRequest]::Create($url) + $request.AllowAutoRedirect = $false + $request.UserAgent = 'bui-installer' + $request.Timeout = 15000 + try { + $response = $request.GetResponse() + } catch [Net.WebException] { + $response = $_.Exception.Response # a redirect is not an error everywhere + if (-not $response) { return '' } + } + try { return [string]$response.Headers['Location'] } finally { $response.Close() } + } + function Step($text) { Write-Host "$(C '38;5;208' $dot) $text" } + function Ok($text) { Write-Host "$(C '32' $tick) $text" } + function Fail($text) { Write-Host "$(C '31' "$cross $text")"; throw $text } + + Write-Host '' + Write-Host (C '38;5;208' (Glyphs '@@@@@@1 @@1 @@1@@1')) + Write-Host (C '38;5;208' (Glyphs '@@266@@1@@5 @@5@@5')) + Write-Host (C '38;5;208' (Glyphs '@@@@@@23@@5 @@5@@5')) + Write-Host (C '38;5;208' (Glyphs '@@266@@1@@5 @@5@@5')) + Write-Host "$(C '38;5;208' (Glyphs '@@@@@@234@@@@@@23@@5')) $(C '1' 'installing bui')" + Write-Host (C '38;5;208' (Glyphs '4666663 4666663 463')) + Write-Host '' + + $arch = [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() + $triple = switch ($arch) { + 'X64' { 'x86_64-pc-windows-msvc' } + 'Arm64' { 'aarch64-pc-windows-msvc' } + default { Fail "there is no bui build for the $arch processor" } + } + + $tag = $env:BUI_VERSION + if (-not $tag) { + Step 'Looking for the newest release' + # the tag comes from the page's redirect (the API would rate-limit) + $location = LocationOf $latestUrl + if ($location -notmatch '/tag/(v\d[^/]*)$') { Fail "could not find the newest release of $repo (offline, or no release yet)" } + $tag = $Matches[1] + } + if ($tag -notlike 'v*') { $tag = "v$tag" } + + $asset = "bui-$triple.zip" + $url = if ($baseUrl) { "$baseUrl/$asset" } else { "https://github.com/$repo/releases/download/$tag/$asset" } + $tmp = Join-Path ([IO.Path]::GetTempPath()) ("bui-install-" + [guid]::NewGuid().ToString('N')) + New-Item -ItemType Directory -Path $tmp | Out-Null + try { + Step "Downloading bui $($tag.TrimStart('v')) for $triple" + Invoke-WebRequest -Uri $url -OutFile (Join-Path $tmp $asset) -UseBasicParsing + Invoke-WebRequest -Uri "$url.sha256" -OutFile (Join-Path $tmp "$asset.sha256") -UseBasicParsing + $want = ((Get-Content (Join-Path $tmp "$asset.sha256") -Raw).Trim() -split '\s+')[0].ToLower() + $got = (Get-FileHash (Join-Path $tmp $asset) -Algorithm SHA256).Hash.ToLower() + if ($want -ne $got) { Fail 'the download does not match its checksum: not installing it' } + Ok 'Checksum matches' + + Expand-Archive -Path (Join-Path $tmp $asset) -DestinationPath $tmp -Force + if (-not (Test-Path (Join-Path $tmp 'bui.exe'))) { Fail 'the download has no bui.exe in it' } + New-Item -ItemType Directory -Path $installDir -Force | Out-Null + # the new file goes in beside the old one first; a running bui cannot be overwritten, but it can be + # renamed, and the old one comes back if anything fails before the new one is in place + $target = Join-Path $installDir 'bui.exe' + $staged = "$target.new" + $backup = "$target.old" + Copy-Item (Join-Path $tmp 'bui.exe') $staged -Force + $hadOld = Test-Path $target + try { + if ($hadOld) { Move-Item $target $backup -Force } + Move-Item $staged $target -Force + } catch { + $reason = $_.Exception.Message + if ($hadOld -and -not (Test-Path $target) -and (Test-Path $backup)) { Move-Item $backup $target -Force } + Remove-Item $staged -Force -ErrorAction SilentlyContinue + Fail "could not replace $target ($reason): the old bui is as it was" + } + Remove-Item $backup -Force -ErrorAction SilentlyContinue + Ok "Installed $target" + } finally { + Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue + } + + $userPath = [Environment]::GetEnvironmentVariable('Path', 'User') + $onPath = ($userPath -split ';') -contains $installDir + if (-not $onPath -and -not $env:BUI_NO_MODIFY_PATH) { + [Environment]::SetEnvironmentVariable('Path', "$installDir;$userPath", 'User') + $env:Path = "$installDir;$env:Path" + Ok "Added $installDir to your PATH" + } + + Write-Host '' + Write-Host "$(C '1;32' 'bui is ready.') Open a new terminal, then:" + Write-Host '' + Write-Host " $(C '38;5;208' 'bui new my-app') $(C '2' 'make an app')" + Write-Host " $(C '38;5;208' 'bui doctor') $(C '2' 'check your setup')" + Write-Host " $(C '38;5;208' 'bui update') $(C '2' 'get newer versions later')" + Write-Host '' +} diff --git a/website/public/install.sh b/website/public/install.sh new file mode 100644 index 00000000..2333c4b5 --- /dev/null +++ b/website/public/install.sh @@ -0,0 +1,151 @@ +#!/bin/sh +# Installs `bui`, the command that makes, runs, checks and updates BUI apps. +# +# curl -LsSf https://bui.preetham.top/install.sh | sh +# +# Linux and macOS (x86_64 and arm64). It downloads the newest release from GitHub, checks its +# checksum, puts `bui` in ~/.bui/bin and adds that folder to your shell's PATH. +# +# BUI_VERSION=v0.5.1 install that release instead of the newest +# BUI_INSTALL_DIR=DIR install into DIR (default: ~/.bui/bin) +# BUI_NO_MODIFY_PATH=1 do not touch any shell profile +# +# SPDX-License-Identifier: GPL-2.0-or-later + +set -eu + +REPO="ppmpreetham/BUI" +INSTALL_DIR="${BUI_INSTALL_DIR:-$HOME/.bui/bin}" +BASE_URL="${BUI_INSTALLER_BASE_URL:-}" # for testing: a folder that holds the archive and its .sha256 + +if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then + ORANGE="$(printf '\033[38;5;208m')"; DIM="$(printf '\033[2m')"; RED="$(printf '\033[31m')" + GREEN="$(printf '\033[32m')"; BOLD="$(printf '\033[1m')"; RESET="$(printf '\033[0m')" +else + ORANGE=""; DIM=""; RED=""; GREEN=""; BOLD=""; RESET="" +fi + +say() { printf '%s\n' "$*"; } +step() { printf '%s●%s %s\n' "$ORANGE" "$RESET" "$*"; } +ok() { printf '%s✔%s %s\n' "$GREEN" "$RESET" "$*"; } +die() { printf '%s✘ %s%s\n' "$RED" "$*" "$RESET" >&2; exit 1; } + +have() { command -v "$1" >/dev/null 2>&1; } + +# download URL FILE (a progress bar on a terminal) +download() { + if have curl; then + if [ -t 2 ]; then curl -fL --progress-bar -o "$2" "$1"; else curl -fsSL -o "$2" "$1"; fi + elif have wget; then + wget -q ${BUI_WGET_PROGRESS:+--show-progress} -O "$2" "$1" + else + die "need curl or wget to download bui" + fi +} + +banner() { + say "" + say "${ORANGE}██████╗ ██╗ ██╗██╗${RESET}" + say "${ORANGE}██╔══██╗██║ ██║██║${RESET}" + say "${ORANGE}██████╔╝██║ ██║██║${RESET}" + say "${ORANGE}██╔══██╗██║ ██║██║${RESET}" + say "${ORANGE}██████╔╝╚██████╔╝██║${RESET} ${BOLD}installing bui${RESET}" + say "${ORANGE}╚═════╝ ╚═════╝ ╚═╝${RESET}" + say "" +} + +target() { + os="$(uname -s)"; arch="$(uname -m)" + case "$arch" in + x86_64 | amd64) arch="x86_64" ;; + aarch64 | arm64) arch="aarch64" ;; + *) die "there is no bui build for the $arch processor" ;; + esac + case "$os" in + Linux) echo "$arch-unknown-linux-gnu" ;; + Darwin) echo "$arch-apple-darwin" ;; + *) die "this installer is for Linux and macOS: on Windows use irm https://bui.preetham.top/install.ps1 | iex" ;; + esac +} + +# the tag of the newest release, from the page's redirect (the API would rate-limit) +latest_tag() { + if have curl; then + url="$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest")" + else + url="$(wget -q --max-redirect=0 --server-response -O /dev/null "https://github.com/$REPO/releases/latest" 2>&1 | sed -n 's/^ *Location: //p' | tail -n 1)" + fi + tag="${url##*/tag/}" + case "$tag" in v[0-9]*) echo "$tag" ;; *) die "could not find the newest release of $REPO (offline, or no release yet)" ;; esac +} + +sha256_of() { + if have sha256sum; then sha256sum "$1" | cut -d ' ' -f 1 + elif have shasum; then shasum -a 256 "$1" | cut -d ' ' -f 1 + else die "need sha256sum or shasum to check the download"; fi +} + +add_to_path() { + case ":$PATH:" in *":$INSTALL_DIR:"*) return 0 ;; esac + [ -n "${BUI_NO_MODIFY_PATH:-}" ] && { say "${DIM}Add $INSTALL_DIR to your PATH to use it.${RESET}"; return 0; } + line="export PATH=\"$INSTALL_DIR:\$PATH\" # added by the bui installer" + changed="" + for rc in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.zshrc"; do + # profiles that exist (and .profile always, as login shells read it) + if [ -f "$rc" ] || [ "$rc" = "$HOME/.profile" ]; then + if ! grep -qs "added by the bui installer" "$rc" 2>/dev/null; then + printf '\n%s\n' "$line" >> "$rc" + changed="$changed $rc" + fi + fi + done + if have fish && [ -d "$HOME/.config/fish" ]; then + mkdir -p "$HOME/.config/fish/conf.d" + printf 'fish_add_path "%s"\n' "$INSTALL_DIR" > "$HOME/.config/fish/conf.d/bui.fish" + changed="$changed fish" + fi + [ -n "$changed" ] && ok "Added $INSTALL_DIR to your PATH (${changed# })" + return 0 +} + +main() { + banner + triple="$(target)" + tag="${BUI_VERSION:-}" + if [ -z "$tag" ]; then step "Looking for the newest release"; tag="$(latest_tag)"; fi + case "$tag" in v*) ;; *) tag="v$tag" ;; esac + asset="bui-$triple.tar.gz" + if [ -n "$BASE_URL" ]; then url="$BASE_URL/$asset"; else url="https://github.com/$REPO/releases/download/$tag/$asset"; fi + + tmp="$(mktemp -d)" + trap 'rm -rf "$tmp"' EXIT INT TERM + + step "Downloading bui ${tag#v} for $triple" + download "$url" "$tmp/$asset" || die "could not download $url" + download "$url.sha256" "$tmp/$asset.sha256" || die "could not download the checksum" + want="$(cut -d ' ' -f 1 < "$tmp/$asset.sha256" | tr 'A-F' 'a-f')" + got="$(sha256_of "$tmp/$asset")" + [ "$want" = "$got" ] || die "the download does not match its checksum: not installing it" + ok "Checksum matches" + + tar -xzf "$tmp/$asset" -C "$tmp" || die "could not unpack the download" + [ -f "$tmp/bui" ] || die "the download has no bui in it" + mkdir -p "$INSTALL_DIR" + # the new file is written beside the old one (the same disk), then renamed over it in one step: the old + # bui stays whole until the new one is complete, and a running one is replaced, not overwritten + staged="$(mktemp "$INSTALL_DIR/.bui-install.XXXXXX")" || die "could not write in $INSTALL_DIR" + trap 'rm -rf "$tmp" "$staged"' EXIT INT TERM + cp "$tmp/bui" "$staged" && chmod 755 "$staged" && mv -f "$staged" "$INSTALL_DIR/bui" || die "could not install into $INSTALL_DIR: the old bui (if any) is as it was" + ok "Installed $INSTALL_DIR/bui" + + add_to_path + say "" + say "${BOLD}${GREEN}bui is ready.${RESET} Open a new terminal (or run ${BOLD}export PATH=\"$INSTALL_DIR:\$PATH\"${RESET}), then:" + say "" + say " ${ORANGE}bui new my-app${RESET} ${DIM}make an app${RESET}" + say " ${ORANGE}bui doctor${RESET} ${DIM}check your setup${RESET}" + say " ${ORANGE}bui update${RESET} ${DIM}get newer versions later${RESET}" + say "" +} + +main "$@" diff --git a/website/src/content/docs/start/bui-command.mdx b/website/src/content/docs/start/bui-command.mdx new file mode 100644 index 00000000..29a67990 --- /dev/null +++ b/website/src/content/docs/start/bui-command.mdx @@ -0,0 +1,139 @@ +--- +title: The bui command +sidebarLabel: The bui command +description: One command that makes a BUI app in Rust, JavaScript, TypeScript, Python, Lua or C, checks your setup, fixes what is wrong and keeps everything up to date. Installs with one line on Windows, Linux and macOS. +section: Start here +order: 15 +sources: ["tools/bui/src/main.rs", "tools/bui/src/cli.rs", "tools/bui/src/create.rs", "tools/bui/src/doctor.rs", "tools/bui/src/update.rs", "tools/bui/src/tools.rs", "tools/bui/src/flavours/mod.rs", "tools/bui/src/project.rs", "website/public/install.sh", "website/public/install.ps1", ".github/workflows/cli.yml"] +--- + +`bui` is a small program that gets you from nothing to a running BUI window. It asks what you want to write, checks that the tools for it are installed (and offers to install them), makes the project with the language's own modern setup and lints, installs the newest BUI with the language's own package manager, and later tells you what is out of date and how to fix it. + +## Install it + + + + +```sh +curl -LsSf https://bui.preetham.top/install.sh | sh +``` + +It downloads the newest release for your processor (x86_64 or arm64), checks its checksum, puts `bui` in `~/.bui/bin` and adds that folder to your shell's `PATH`. Open a new terminal afterwards. + + + + +```powershell +irm https://bui.preetham.top/install.ps1 | iex +``` + +Works in Windows PowerShell and PowerShell 7. It puts `bui.exe` in `%USERPROFILE%\.bui\bin` and adds that folder to your user `PATH`. + + + + +```sh +cargo install --path tools/bui --locked +``` + +This builds `tools/bui` from a clone of the repository in a minute or two. It needs a Rust toolchain. + + + + +Both installers take `BUI_VERSION` (install that release instead of the newest) and `BUI_INSTALL_DIR`; `BUI_NO_MODIFY_PATH=1` leaves your shell profile alone. On Linux and macOS a new `bui` is written beside the old one and renamed over it in one step. On Windows the old `bui.exe` is moved to `bui.exe.old`, the new one moved in, and the old one put back if that fails; if the installer is killed between those two moves, rename `bui.exe.old` back to `bui.exe`. + +## Make an app + +```sh +bui new my-app # in a new folder +bui init # in the folder you are in +``` + +`bui` asks, one question at a time (every question is also a flag, see below): + +1. **The language.** Rust, JavaScript or TypeScript, Python, Lua or C. +2. **That language's choices.** JavaScript asks for the framework (React, Svelte or plain DOM), TypeScript or JavaScript, and the runtime and package manager (Bun, or Node.js with npm or pnpm). Python asks for the API: Blender's components, Qt syntax or tkinter syntax. +3. **The tools.** If something the language needs is missing (Rust, Bun, uv, a C compiler, CMake, LuaRocks...), `bui` shows the command that installs the newest one on your system and asks before it runs it. +4. **The packages.** Before it writes anything, `bui` lists the exact commands that install BUI and the tooling at their newest versions (`bun add ...`, `cargo add blenderui`, ...) and asks whether to run them now. Say no and `bui doctor` does it later. +5. **The project.** It writes the files (files you already have are kept: in a folder with a `package.json`, `bui init` adds only the scripts `bui` runs that are missing, says which, and stops, leaving your project files unchanged, if the file cannot be read, is not valid JSON, or is a React and TypeScript project whose `package.json` has `"type": "module"`; tools offered for install are checked before the file is read), offers to start a git repository, runs the install, and ends with every command you will need. + +What you get, by language: + +| Language | Dependencies | Lints and format | +| --- | --- | --- | +| Rust | `cargo add blenderui` | Clippy with the pedantic lints on, rustfmt | +| JavaScript / TypeScript | `bun add`, `npm install` or `pnpm add` | Biome; TypeScript in strict mode | +| Python | `uv add blenderui` (uv keeps Python, the environment and the lock file) | Ruff | +| Lua | `luarocks install blenderui` into `lua_modules/` (nothing global) | Luacheck, StyLua and LuaLS settings | +| C | CMake `FetchContent` at the newest release | `.clang-format`, `.clang-tidy` | + +Each project also gets a `bui.toml` that records what you chose, so `bui` knows how to run, build and check it from any folder inside it. + +## Run, build, check, update + +| Command | What it does | +| --- | --- | +| `bui dev [-- ARGS]` | Runs the app, restarting on every save where the language can (`cargo run`, `bun --watch`, `uv run`, ...) | +| `bui build [-- ARGS]` | A release build (`cargo build --release`; a JavaScript app becomes one small executable) | +| `bui doctor` | Looks at what this project needs, says what is wrong in one line each and offers the fixes | +| `bui update` | Updates `bui` itself, then the BUI packages of the project you are in | +| `bui docs` | Opens the documentation in your browser | +| `bui completions ` | Shell completions for bash, zsh, fish, PowerShell and elvish | + +Everything after `--` in `bui dev` and `bui build` is given to the tool underneath: `bui dev -- --release` runs `cargo run --release`, and `bui build -- --features foo` runs `cargo build --release --features foo`. Run `bui` with no command to see every command and option, and `--help` on any command for its own. + +### bui doctor + +`bui doctor` checks the project you are in and only what it needs: its toolchain, whether the packages are installed, whether BUI is the newest version. Outside a project it checks every toolchain. Each problem comes with the commands that fix it, shown before anything runs: + +```text +✔ bui 0.5.1 (newest) +my-app (React + TypeScript on bun) +✔ Bun 1.4.4 +✘ node_modules packages are not installed +What would fix it + 1. installs the packages + $ bun install +Run 1 fix now? › yes +``` + +Nothing is installed or changed without your answer: `--fix` says yes for you, and without a terminal `bui doctor` only reports. `--all` checks every toolchain, and `--json` prints the results for editors and CI. + +### bui update + +`bui update` looks for a newer `bui` (a download with a progress bar, checked against its published checksum), then offers to bring the project's `blenderui` packages to the newest version. `bui update --check` only reports, and `bui update --cli-only` updates `bui` itself and leaves the project alone (what `bui doctor --fix` runs for an old `bui`). If a step that has to work fails, the command exits with an error instead of saying it is done. + +## Scripts, CI and flags + +Every question has a flag, so a script never has to answer one: + +```sh +bui new my-app --language js --framework react --typescript --pm bun --yes +``` + +| Flag | Meaning | +| --- | --- | +| `-l, --language rust\|js\|python\|lua\|c` | The language | +| `--framework react\|svelte\|vanilla`, `--typescript` or `--javascript`, `--pm bun\|npm\|pnpm` | JavaScript | +| `--api components\|qt\|tk` | Python | +| `--yes`, `-y` | Answer every question with its default, and ask nothing | +| `--no-install`, `--no-git` | Skip installing dependencies, or `git init` | +| `--install-tools` | Install missing tools (Rust, Bun, uv...) without asking | +| `--plain` | No animation or color. This is automatic without a terminal, in CI, or with `NO_COLOR` | + +Without a terminal and without `--yes`, a question that cannot be answered stops with a message instead of guessing. + +## Good to know + + +`@blender-ui/svelte`'s loader fails under Bun today, so a Svelte project runs on Node.js (with npm or pnpm). React and plain DOM projects run on Bun or Node.js. + + + +For JavaScript and TypeScript projects, `bui build` runs `@blender-ui/native`'s `bui`, which bundles your app with Bun, so Bun is checked (and offered for install) before a build even in an npm or pnpm project. + + +- **Python needs 3.11 or newer.** BUI's wheels cover CPython 3.11 to 3.14 on Windows, Linux x86_64 and macOS. +- **Lua and Rust compile BUI's C kit** while they install, so they need a C compiler and CMake. `bui doctor` checks both. On Windows, LuaRocks needs a compiler that matches your Lua build. +- **macOS** builds of `bui` come from the release workflow and have not been tried by hand yet. **iOS** is not supported. diff --git a/website/src/content/docs/start/installation.mdx b/website/src/content/docs/start/installation.mdx index 3c6348ab..08d48d13 100644 --- a/website/src/content/docs/start/installation.mdx +++ b/website/src/content/docs/start/installation.mdx @@ -8,7 +8,9 @@ languages: ["python", "rust", "javascript", "c", "imgui"] sources: ["README.md", "docs/getting-started.md", "docs/rust.md", "docs/javascript.md", "docs/imgui.md", "docs/c-api.md", "pyproject.toml"] --- -Good news first: for Python and JavaScript, installing BUI is one command. Rust is one line in `Cargo.toml`, and C is a normal CMake build. +The quickest way in is [the `bui` command](/docs/start/bui-command): one line installs it, and `bui new my-app` makes a project in any of the languages below, with the tools checked and the newest BUI installed. + +Or install by hand: for Python and JavaScript, installing BUI is one command. Rust is one line in `Cargo.toml`, and C is a normal CMake build. Pick your language below. The page remembers your choice, so every other page shows the same tab.