diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 747007c..117f518 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,28 +6,52 @@ on:
pull_request:
jobs:
- install:
+ test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- - name: Lint
+ - name: Build Burn
run: |
- sh -n install.sh
- shellcheck install.sh
- - name: Install from source
- run: sh install.sh --from-source --no-modify-path --prefix "$RUNNER_TEMP/burn"
- - name: Use the toolchain
+ git clone --depth 1 https://github.com/burnlang/burn "$RUNNER_TEMP/burn"
+ cargo build --release --manifest-path "$RUNNER_TEMP/burn/Cargo.toml"
+ mkdir -p "$RUNNER_TEMP/tools"
+ for tool in burn burni burnc; do ln -sf "$RUNNER_TEMP/burn/target/release/burn" "$RUNNER_TEMP/tools/$tool"; done
+ echo "$RUNNER_TEMP/tools" >> "$GITHUB_PATH"
+ - name: Lint
+ run: shellcheck install.sh tests/e2e.sh
+ - run: burn fmt --check src/*.bn tests/*.bn
+ - run: burn check
+ - run: burn run tests/main.bn
+ - run: burn build
+ - name: End-to-end tests
+ run: BURNUP_BIN="$PWD/build/burnup" sh tests/e2e.sh
+ - name: End-to-end tests on the interpreter
+ run: sh tests/e2e.sh
+
+ bootstrap:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ - name: Install from source with install.sh
+ env:
+ BURNUP_REPO: ${{ github.workspace }}
+ BURNUP_REF: ${{ github.sha }}
+ BURN_HOME: ${{ runner.temp }}/burn-home
+ run: sh install.sh --from-source --no-modify-path
+ - name: Use it
+ env:
+ BURN_HOME: ${{ runner.temp }}/burn-home
run: |
- export PATH="$RUNNER_TEMP/burn/bin:$PATH" BURN_HOME="$RUNNER_TEMP/burn"
+ export PATH="$BURN_HOME/bin:$PATH"
burnup show
+ burnup list
+ burn version
cd "$RUNNER_TEMP"
ash init github.com/ci/hello
cd hello
ash build
./build/hello
- ash install
- - name: Uninstall
- run: |
- "$RUNNER_TEMP/burn/bin/burnup" uninstall --prefix "$RUNNER_TEMP/burn"
- test ! -e "$RUNNER_TEMP/burn"
+ burnup self uninstall
+ test ! -e "$BURN_HOME"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..0e86401
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,33 @@
+name: Release
+
+on:
+ push:
+ tags: ["v*"]
+
+permissions:
+ contents: write
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ include:
+ - os: ubuntu-latest
+ asset: burnup-linux-x86_64
+ - os: macos-15-intel
+ asset: burnup-macos-x86_64
+ runs-on: ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ - name: Build Burn
+ run: |
+ git clone --depth 1 https://github.com/burnlang/burn "$RUNNER_TEMP/burn"
+ cargo build --release --manifest-path "$RUNNER_TEMP/burn/Cargo.toml"
+ - name: Build burnup
+ run: |
+ "$RUNNER_TEMP/burn/target/release/burn" build --target native -o "${{ matrix.asset }}"
+ "./${{ matrix.asset }}" version
+ - uses: softprops/action-gh-release@v2
+ with:
+ files: ${{ matrix.asset }}
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..567609b
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+build/
diff --git a/README.md b/README.md
index a929cdb..5eb5a3d 100644
--- a/README.md
+++ b/README.md
@@ -4,62 +4,102 @@
# burnup
-burnup installs, updates and uninstalls the [Burn](https://github.com/burnlang/burn) toolchain.
+burnup installs [Burn](https://github.com/burnlang/burn), keeps it up to date and switches between versions. It is
+written in Burn.
```sh
curl -fsSL https://raw.githubusercontent.com/burnlang/burnup/master/install.sh | sh
```
-This puts everything into `~/.burn/bin` and adds it to your `PATH`:
+This installs burnup, the newest Burn and [ash](https://github.com/burnlang/ash), the package manager, into
+`~/.burn` and adds `~/.burn/bin` to your `PATH`.
-| Command | What it is |
-| --- | --- |
-| `burn` | the all-in-one driver: run, build, check, fmt, init, repl, lsp |
-| `burni` | the interpreter and REPL |
-| `burnc` | the compiler: native executables, JavaScript and bvm bytecode |
-| `burnfmt` | the code formatter |
-| `burn-lsp` | the language server |
-| `bvm` | the Burn virtual machine |
-| `ash` | the [package manager](https://github.com/burnlang/ash) |
-| `burnup` | this installer |
+## Versions
+
+```sh
+burnup install 26.1 # a release (26.1 means the newest 26.1.x)
+burnup install master # the newest commit, built from source
+burnup default 26.1 # use it everywhere
+burnup list # installed versions
+burnup list --remote # versions that can be installed
+burnup update # rebuild branch versions that moved, and update ash
+burnup uninstall master
+```
+
+A version is a release (`26.1`, `v26.1.0`, `^26.1`), `latest`, a branch such as `master`, or a commit. Releases
+are downloaded prebuilt; branches and commits are built from source, which needs Rust.
+
+## Projects
+
+A project can ask for a Burn version in `burn.toml`:
+
+```toml
+[package]
+name = "github.com/you/app"
+burn = "26.1"
+```
-## Usage
+or with a `.burn-version` file in any folder. `burnup pin 26.1` writes one or the other. Inside that folder,
+`burn`, `burni`, `burnc` and the other tools run that version, and burnup installs it the first time it is needed.
```sh
-burnup update # the newest Burn, ash and burnup
-burnup show # installed versions
-burnup uninstall # remove Burn, downloaded packages and installed commands
-burnup help
+burnup show # which version runs here, and why
+burnup which burnc # the file that runs
+burnup run master burn check # one command with another version
+BURN_TOOLCHAIN=26.1 burn run # or choose with an environment variable
```
-A prebuilt release is used when one exists for your platform; otherwise Burn is built from source, which needs
-`git` and Rust 1.85 or newer (`--install-rust` installs Rust with rustup). ash is built from its Burn source with
-the freshly installed compiler. Native executables need a C toolchain (`cc`).
+The version is chosen in this order: `BURN_TOOLCHAIN`, then the nearest `burn.toml` with a `burn` key or
+`.burn-version`, then the default.
+
+## How it works
+
+```text
+~/.burn/
+├── bin/ burn, burni, burnc, burnfmt, burn-lsp, bvm: small shims that run the active version
+│ ├── ash
+│ └── burnup
+├── toolchains/
+│ ├── v26.1.0/ one folder per version
+│ └── master/
+├── burnup.toml the default version
+├── packages/ packages downloaded by ash
+└── env adds bin/ to PATH
+```
+
+The shims ask burnup which version to use, which adds a few milliseconds to each command. `burnup link dev
+~/burn/dist/burn` adds a local build (for example from `sh scripts/package.sh` in a Burn checkout) as the version
+`dev`.
+
+## Setup
+
+| Command | What it does |
+| --- | --- |
+| `burnup ash` | install or update ash |
+| `burnup self update` | update burnup itself |
+| `burnup self uninstall` | remove Burn, burnup, ash, downloaded packages and the `PATH` lines |
-## Options
+Installer options, passed with `sh -s --`:
| Option | Description |
| --- | --- |
| `--prefix
` | install into `` instead of `~/.burn` |
-| `--ref [` | build a specific branch, tag or commit of Burn |
-| `--ash-ref ][` | build a specific branch, tag or commit of ash |
-| `--from-source` | always build from source |
-| `--install-rust` | install Rust with rustup when `cargo` is missing |
+| `--toolchain ` | the Burn version to install first |
+| `--from-source` | build Burn and burnup from source |
+| `--install-rust` | install Rust with rustup when a source build needs it |
| `--no-ash` | do not install ash |
| `--no-modify-path` | do not touch your shell profile |
-| `-q`, `--quiet` | only print errors |
-Pass options to the piped script with `sh -s --`:
+The installer downloads a prebuilt burnup when there is one for your platform. Otherwise it builds Burn once from
+source and compiles burnup with it.
+
+## Development
```sh
-curl -fsSL https://raw.githubusercontent.com/burnlang/burnup/master/install.sh | sh -s -- --prefix /opt/burn
+burn run tests/main.bn # unit tests
+BURNUP_BIN=build/burnup sh tests/e2e.sh # end-to-end tests with local releases
```
-Environment variables: `BURN_HOME` (the prefix), `BURN_REPO` and `BURN_REF`, `ASH_REPO` and `ASH_REF`.
-
-`burnup uninstall` deletes the whole prefix only when burnup created it; otherwise it removes just the files it
-installed. It also removes the lines it added to your shell profiles.
-
## License
[GNU General Public License v3.0](LICENSE)
diff --git a/burn.toml b/burn.toml
new file mode 100644
index 0000000..f62e458
--- /dev/null
+++ b/burn.toml
@@ -0,0 +1,13 @@
+[package]
+name = "github.com/burnlang/burnup"
+version = "0.2.0"
+kind = "app"
+target = "native"
+main = "src/main.bn"
+description = "Installs and switches Burn versions"
+
+[dependencies]
+
+[scripts]
+dev = "burni src/main.bn"
+test = "burni tests/main.bn && sh tests/e2e.sh"
diff --git a/install.sh b/install.sh
index 4732090..7211678 100644
--- a/install.sh
+++ b/install.sh
@@ -3,43 +3,28 @@ set -eu
BURN_REPO="${BURN_REPO:-https://github.com/burnlang/burn}"
BURN_REF="${BURN_REF:-master}"
-ASH_REPO="${ASH_REPO:-https://github.com/burnlang/ash}"
-ASH_REF="${ASH_REF:-master}"
-BURNUP_URL="${BURNUP_URL:-https://raw.githubusercontent.com/burnlang/burnup/master/install.sh}"
+BURNUP_REPO="${BURNUP_REPO:-https://github.com/burnlang/burnup}"
+BURNUP_REF="${BURNUP_REF:-master}"
+BURNUP_RELEASES="${BURNUP_RELEASES:-https://github.com/burnlang/burnup/releases/latest/download}"
PREFIX="${BURN_HOME:-$HOME/.burn}"
FROM_SOURCE=0
-MODIFY_PATH=1
INSTALL_RUST=0
-WITH_ASH=1
-QUIET=0
-ACTION=install
+TOOLCHAIN=""
+NO_ASH=0
+NO_PATH=0
-if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
+if [ -t 2 ] && [ -z "${NO_COLOR:-}" ]; then
BOLD="$(printf '\033[1m')"
RED="$(printf '\033[31m')"
- GREEN="$(printf '\033[32m')"
- YELLOW="$(printf '\033[33m')"
RESET="$(printf '\033[0m')"
else
BOLD=""
RED=""
- GREEN=""
- YELLOW=""
RESET=""
fi
-say() {
- if [ "$QUIET" -eq 0 ]; then
- printf '%s\n' "$*"
- fi
-}
-
step() {
- say "${BOLD}==>${RESET} $*"
-}
-
-warn() {
- printf '%s\n' "${YELLOW}warning:${RESET} $*" >&2
+ printf '%s\n' "${BOLD}==>${RESET} $*" >&2
}
die() {
@@ -49,52 +34,25 @@ die() {
usage() {
cat < install into instead of ~/.burn
- --ref Burn branch, tag or commit to build (default: master)
- --ash-ref ][ ash branch, tag or commit to build (default: master)
- --from-source build Burn from source instead of downloading a release
- --install-rust install Rust with rustup if cargo is missing
- --no-ash do not install ash
- --no-modify-path do not add the bin directory to your shell profile
- -q, --quiet only print errors
-
-Environment:
- BURN_HOME installation directory (same as --prefix)
- BURN_REPO, BURN_REF where to get Burn from
- ASH_REPO, ASH_REF where to get ash from
-
-Examples:
- curl -fsSL https://raw.githubusercontent.com/burnlang/burnup/master/install.sh | sh
- curl -fsSL https://raw.githubusercontent.com/burnlang/burnup/master/install.sh | sh -s -- --from-source
- burnup update
+ --prefix install into instead of ~/.burn
+ --toolchain the Burn version to install first (default: the latest)
+ --from-source build Burn and burnup from source instead of downloading them
+ --install-rust install Rust with rustup if a source build needs it
+ --no-ash do not install ash, the package manager
+ --no-modify-path do not add ~/.burn/bin to your shell profile
+ -h, --help show this help
+
+Afterwards, burnup manages everything: burnup help
EOF
}
-case "${1:-}" in
- install | update | uninstall | show | help)
- ACTION="$1"
- shift
- ;;
- self-update)
- ACTION=update
- shift
- ;;
-esac
-
while [ $# -gt 0 ]; do
case "$1" in
--prefix)
@@ -106,24 +64,11 @@ while [ $# -gt 0 ]; do
PREFIX="${1#--prefix=}"
shift
;;
- --ref)
- [ $# -ge 2 ] || die "--ref needs a value"
- BURN_REF="$2"
- shift 2
- ;;
- --ref=*)
- BURN_REF="${1#--ref=}"
- shift
- ;;
- --ash-ref)
- [ $# -ge 2 ] || die "--ash-ref needs a value"
- ASH_REF="$2"
+ --toolchain)
+ [ $# -ge 2 ] || die "--toolchain needs a version"
+ TOOLCHAIN="$2"
shift 2
;;
- --ash-ref=*)
- ASH_REF="${1#--ash-ref=}"
- shift
- ;;
--from-source)
FROM_SOURCE=1
shift
@@ -133,117 +78,34 @@ while [ $# -gt 0 ]; do
shift
;;
--no-ash)
- WITH_ASH=0
+ NO_ASH=1
shift
;;
--no-modify-path)
- MODIFY_PATH=0
- shift
- ;;
- --uninstall)
- ACTION=uninstall
- shift
- ;;
- -q | --quiet)
- QUIET=1
+ NO_PATH=1
shift
;;
-h | --help)
- ACTION=help
- shift
+ usage
+ exit 0
;;
*)
- die "unknown option: $1 (see burnup help)"
+ die "unknown option: $1 (see --help)"
;;
esac
done
-if [ "$ACTION" = help ]; then
- usage
- exit 0
-fi
-
case "$PREFIX" in
/*) ;;
*) PREFIX="$(pwd)/$PREFIX" ;;
esac
BIN="$PREFIX/bin"
-SHARE="$PREFIX/share/burn"
-ENV_FILE="$PREFIX/env"
-OWNED="$PREFIX/.burnup"
-MARKER="# added by burnup"
-OLD_MARKER="# added by the Burn installer"
+export BURN_HOME="$PREFIX" BURN_REPO
need() {
command -v "$1" >/dev/null 2>&1
}
-profiles() {
- for f in "$HOME/.profile" "$HOME/.bashrc" "$HOME/.bash_profile" "$HOME/.zshrc" "$HOME/.zprofile"; do
- if [ -f "$f" ]; then
- printf '%s\n' "$f"
- fi
- done
-}
-
-remove_path_lines() {
- for f in $(profiles); do
- if grep -q -e "$MARKER" -e "$OLD_MARKER" "$f" 2>/dev/null; then
- tmp="$f.burnup-tmp"
- grep -v -e "$MARKER" -e "$OLD_MARKER" "$f" >"$tmp" || true
- cat "$tmp" >"$f"
- rm -f "$tmp"
- fi
- done
- rm -f "$HOME/.config/fish/conf.d/burn.fish"
-}
-
-if [ "$ACTION" = show ]; then
- [ -x "$BIN/burn" ] || die "Burn is not installed in $PREFIX"
- "$BIN/burn" version
- if [ -x "$BIN/ash" ]; then
- "$BIN/ash" version
- fi
- say "installed in $PREFIX"
- exit 0
-fi
-
-if [ "$ACTION" = uninstall ]; then
- if [ ! -x "$BIN/burn" ] && [ ! -d "$SHARE" ]; then
- die "no Burn installation found in $PREFIX"
- fi
- step "Removing $PREFIX"
- if [ -f "$OWNED" ]; then
- rm -rf "$PREFIX"
- else
- rm -f "$BIN/burn" "$BIN/burni" "$BIN/burnc" "$BIN/burnfmt" "$BIN/burn-lsp" "$BIN/bvm" "$BIN/ash" "$BIN/burnup"
- rm -rf "$SHARE" "$ENV_FILE" "$PREFIX/packages" "$PREFIX/tools" "$PREFIX/index" "$PREFIX/index.fetched"
- rmdir "$BIN" "$PREFIX/share" "$PREFIX" 2>/dev/null || true
- fi
- remove_path_lines
- say "${GREEN}Burn has been uninstalled.${RESET}"
- exit 0
-fi
-
-OS="$(uname -s)"
-ARCH="$(uname -m)"
-case "$OS" in
- Linux) OS_NAME=linux ;;
- Darwin) OS_NAME=macos ;;
- *) OS_NAME="$(printf '%s' "$OS" | tr '[:upper:]' '[:lower:]')" ;;
-esac
-case "$ARCH" in
- x86_64 | amd64) ARCH_NAME=x86_64 ;;
- arm64 | aarch64) ARCH_NAME=aarch64 ;;
- *) ARCH_NAME="$ARCH" ;;
-esac
-
-WORK="$(mktemp -d 2>/dev/null || mktemp -d -t burnup)"
-cleanup() {
- rm -rf "$WORK"
-}
-trap cleanup EXIT INT TERM
-
download() {
if need curl; then
curl -fsSL "$1" -o "$2"
@@ -254,236 +116,99 @@ download() {
fi
}
-clone() {
- if ! git clone --quiet --depth 1 --branch "$2" "$1" "$3" 2>/dev/null; then
- rm -rf "$3"
- git clone --quiet "$1" "$3" || return 1
- git -C "$3" checkout --quiet "$2" || return 1
- fi
-}
+OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
+ARCH="$(uname -m)"
+case "$OS" in darwin) OS=macos ;; esac
+case "$ARCH" in amd64) ARCH=x86_64 ;; arm64) ARCH=aarch64 ;; esac
-install_release() {
- asset="burn-$OS_NAME-$ARCH_NAME.tar.gz"
- url="$BURN_REPO/releases/latest/download/$asset"
- if [ -n "${BURN_RELEASE_URL:-}" ]; then
- url="$BURN_RELEASE_URL"
- fi
- step "Looking for a prebuilt release ($asset)"
- if ! download "$url" "$WORK/$asset" 2>/dev/null; then
- say " no prebuilt release available, building from source"
- return 1
- fi
- mkdir -p "$WORK/release"
- tar -xzf "$WORK/$asset" -C "$WORK/release" || return 1
- root="$WORK/release"
- if [ -d "$WORK/release/burn" ]; then
- root="$WORK/release/burn"
- fi
- [ -x "$root/bin/burn" ] || return 1
- mkdir -p "$BIN" "$SHARE"
- for exe in burn bvm burnfmt; do
- if [ -f "$root/bin/$exe" ] && [ ! -L "$root/bin/$exe" ]; then
- cp -f "$root/bin/$exe" "$BIN/$exe.new"
- mv -f "$BIN/$exe.new" "$BIN/$exe"
- fi
- done
- for tool in burni burnc burn-lsp; do
- rm -f "$BIN/$tool"
- ln -s burn "$BIN/$tool" 2>/dev/null || cp -f "$BIN/burn" "$BIN/$tool"
- done
- if [ -d "$root/share/burn" ]; then
- cp -R "$root/share/burn/." "$SHARE/"
- fi
- if [ ! -x "$BIN/burnfmt" ] || [ "$(head -c 2 "$BIN/burnfmt")" = "#!" ]; then
- return 1
- fi
- return 0
+WORK="$(mktemp -d 2>/dev/null || mktemp -d -t burnup)"
+trap 'rm -rf "$WORK"' EXIT INT TERM
+mkdir -p "$BIN"
+if [ ! -e "$PREFIX/.burnup" ] && [ -z "$(ls -A "$BIN" 2>/dev/null)" ]; then
+ : >"$PREFIX/.burnup"
+fi
+
+prebuilt() {
+ [ "$FROM_SOURCE" -eq 0 ] || return 1
+ step "Downloading burnup for $OS-$ARCH"
+ download "$BURNUP_RELEASES/burnup-$OS-$ARCH" "$WORK/burnup" 2>/dev/null || return 1
+ chmod +x "$WORK/burnup"
+ "$WORK/burnup" version >/dev/null 2>&1 || return 1
+ mv -f "$WORK/burnup" "$BIN/burnup"
}
ensure_cargo() {
- if need cargo; then
- return 0
- fi
+ need cargo && return 0
if [ -x "$HOME/.cargo/bin/cargo" ]; then
PATH="$HOME/.cargo/bin:$PATH"
export PATH
return 0
fi
- if [ "$INSTALL_RUST" -eq 1 ]; then
- step "Installing Rust with rustup"
- download "https://sh.rustup.rs" "$WORK/rustup.sh" || die "could not download rustup"
- sh "$WORK/rustup.sh" -y --profile minimal >/dev/null || die "rustup failed"
- PATH="$HOME/.cargo/bin:$PATH"
- export PATH
- return 0
- fi
- die "cargo was not found. Install Rust from https://rustup.rs or rerun with --install-rust"
-}
-
-install_source() {
- ensure_cargo
- need git || die "git is required to download the Burn sources"
- step "Downloading Burn ($BURN_REF) from $BURN_REPO"
- clone "$BURN_REPO" "$BURN_REF" "$WORK/burn" || die "could not get $BURN_REF from $BURN_REPO"
- [ -f "$WORK/burn/scripts/package.sh" ] || die "$BURN_REF is too old for burnup (it has no scripts/package.sh)"
- step "Building Burn (this takes a minute the first time)"
- if [ "$QUIET" -eq 1 ]; then
- sh "$WORK/burn/scripts/package.sh" --prefix "$PREFIX" -q || die "the build failed"
- else
- sh "$WORK/burn/scripts/package.sh" --prefix "$PREFIX" || die "the build failed"
- fi
+ [ "$INSTALL_RUST" -eq 1 ] || die "building Burn needs Rust, but cargo was not found. Install it from https://rustup.rs or rerun with --install-rust"
+ step "Installing Rust with rustup"
+ download "https://sh.rustup.rs" "$WORK/rustup.sh" || die "could not download rustup"
+ sh "$WORK/rustup.sh" -y --profile minimal >/dev/null || die "rustup failed"
+ PATH="$HOME/.cargo/bin:$PATH"
+ export PATH
}
-install_ash() {
- if ! need git; then
- warn "git is not installed, so ash was skipped (it needs git to download packages)"
- return 0
- fi
- step "Installing ash, the package manager"
- rm -rf "$WORK/ash"
- if ! clone "$ASH_REPO" "$ASH_REF" "$WORK/ash"; then
- warn "could not download ash from $ASH_REPO; install it later with: burnup update"
- return 0
- fi
- rm -rf "$SHARE/ash"
- mkdir -p "$SHARE"
- cp -R "$WORK/ash" "$SHARE/ash"
- rm -rf "$SHARE/ash/.git"
- if (cd "$SHARE/ash" && "$BIN/burn" build --target native -o "$BIN/ash.new" >/dev/null 2>"$WORK/ash.log"); then
- mv -f "$BIN/ash.new" "$BIN/ash"
- return 0
- fi
- rm -f "$BIN/ash.new"
- if grep -q -e "linker" -e "linking" -e "native" "$WORK/ash.log"; then
- warn "native compilation is not available here; ash will run on the interpreter"
- cat >"$BIN/ash" </dev/null; then
+ rm -rf "$3"
+ git clone --quiet "$1" "$3" || return 1
+ git -C "$3" checkout --quiet "$2" || return 1
fi
- cat "$WORK/ash.log" >&2
- die "ash does not build with this version of Burn"
}
-install_self() {
- target="$BIN/burnup"
- if [ -f "$0" ] && grep -q "burnup - installs and updates the Burn toolchain" "$0" 2>/dev/null; then
- if [ "$0" != "$target" ]; then
- cp -f "$0" "$target.new"
- mv -f "$target.new" "$target"
- fi
- elif download "$BURNUP_URL" "$target.new" 2>/dev/null; then
- mv -f "$target.new" "$target"
+from_source() {
+ need git || die "git is needed to download Burn"
+ ensure_cargo
+ name="$(printf '%s' "$BURN_REF" | tr '/' '-')"
+ toolchain="$PREFIX/toolchains/$name"
+ if [ ! -x "$toolchain/bin/burn" ]; then
+ step "Downloading Burn ($BURN_REF)"
+ clone "$BURN_REPO" "$BURN_REF" "$WORK/burn" || die "could not get $BURN_REF from $BURN_REPO"
+ [ -f "$WORK/burn/scripts/package.sh" ] || die "Burn $BURN_REF is too old for burnup"
+ step "Building Burn (this takes a minute)"
+ rm -rf "$toolchain.partial"
+ sh "$WORK/burn/scripts/package.sh" --prefix "$toolchain.partial" -q || die "the Burn build failed"
+ rm -rf "$toolchain"
+ mv "$toolchain.partial" "$toolchain"
+ version="$("$toolchain/bin/burn" version | sed 's/^Burn //')"
+ rev="$(git -C "$WORK/burn" rev-parse HEAD)"
+ printf 'name = "%s"\nref = "%s"\nrev = "%s"\nsource = "source"\nversion = "%s"\n' "$name" "$BURN_REF" "$rev" "$version" >"$toolchain/burnup.toml"
+ fi
+ step "Building burnup"
+ rm -rf "$WORK/burnup-src"
+ clone "$BURNUP_REPO" "$BURNUP_REF" "$WORK/burnup-src" || die "could not get burnup from $BURNUP_REPO"
+ if (cd "$WORK/burnup-src" && "$toolchain/bin/burn" build --target native -o "$BIN/burnup.new" >/dev/null 2>"$WORK/burnup.log"); then
+ mv -f "$BIN/burnup.new" "$BIN/burnup"
else
- rm -f "$target.new"
- warn "could not save burnup itself; update later by running the install command again"
- return 0
- fi
- chmod +x "$target"
-}
-
-write_env() {
- cat >"$ENV_FILE" <&2; die "burnup does not build"; }
+ rm -rf "$PREFIX/share/burnup"
+ mkdir -p "$PREFIX/share"
+ cp -R "$WORK/burnup-src" "$PREFIX/share/burnup"
+ printf '#!/bin/sh\nexec "%s" "%s" "$@"\n' "$toolchain/bin/burni" "$PREFIX/share/burnup/src/main.bn" >"$BIN/burnup"
+ chmod +x "$BIN/burnup"
fi
- case ":$PATH:" in
- *":$BIN:"*) return ;;
- esac
- line=". \"$ENV_FILE\" $MARKER"
- updated=""
- for f in $(profiles); do
- if ! grep -q -e "$MARKER" -e "$OLD_MARKER" "$f" 2>/dev/null; then
- printf '\n%s\n' "$line" >>"$f"
- fi
- updated="$updated $f"
- done
- if [ -z "$updated" ]; then
- printf '%s\n' "$line" >>"$HOME/.profile"
- updated=" $HOME/.profile"
+ if [ -z "$TOOLCHAIN" ]; then
+ TOOLCHAIN="$name"
fi
- if [ -d "$HOME/.config/fish" ]; then
- mkdir -p "$HOME/.config/fish/conf.d"
- printf 'fish_add_path -g "%s" %s\n' "$BIN" "$MARKER" >"$HOME/.config/fish/conf.d/burn.fish"
- updated="$updated $HOME/.config/fish/conf.d/burn.fish"
- fi
- say " added $BIN to PATH in:$updated"
- PATH_CHANGED=1
}
-fresh=0
-if [ ! -e "$PREFIX" ]; then
- fresh=1
-fi
-if [ "$ACTION" = update ]; then
- say "${BOLD}Updating the Burn toolchain in $PREFIX${RESET}"
-else
- say "${BOLD}Installing the Burn toolchain into $PREFIX${RESET}"
+if ! prebuilt; then
+ from_source
fi
-mkdir -p "$BIN"
-if [ "$fresh" -eq 1 ]; then
- : >"$OWNED"
-fi
-PATH_CHANGED=0
-installed=0
-if [ "$FROM_SOURCE" -eq 0 ] && install_release; then
- if "$BIN/burn" init --help >/dev/null 2>&1; then
- installed=1
- else
- say " the latest release is older than burnup, building from source"
- fi
+set -- setup
+if [ -n "$TOOLCHAIN" ]; then
+ set -- "$@" --toolchain "$TOOLCHAIN"
fi
-if [ "$installed" -eq 0 ]; then
- install_source
+if [ "$NO_ASH" -eq 1 ]; then
+ set -- "$@" --no-ash
fi
-if [ "$WITH_ASH" -eq 1 ]; then
- install_ash
-fi
-install_self
-modify_path
-
-"$BIN/burn" version >/dev/null 2>&1 || die "the installed burn binary does not run"
-check="$WORK/hello.bn"
-printf 'print("ok")\n' >"$check"
-[ "$("$BIN/burni" "$check")" = "ok" ] || die "burni could not run a test program"
-[ "$(printf 'var x=1\n' | "$BIN/burnfmt")" = "var x = 1" ] || die "burnfmt did not format a test program"
-"$BIN/burnc" "$check" --target bvm -o "$WORK/hello.bvmc" >/dev/null || die "burnc could not compile a test program to bvm bytecode"
-[ "$("$BIN/bvm" "$WORK/hello.bvmc")" = "ok" ] || die "bvm could not run a test program"
-if [ -x "$BIN/ash" ]; then
- "$BIN/ash" version >/dev/null || die "the installed ash does not run"
-fi
-
-say ""
-say "${GREEN}Burn $("$BIN/burn" version | sed 's/^Burn //') is installed.${RESET}"
-say ""
-say " burn run, build, check, fmt, init, repl, lsp"
-say " burni interpreter and REPL"
-say " burnc native, JavaScript and bvm bytecode compiler"
-say " burnfmt code formatter"
-say " burn-lsp language server for editors"
-say " bvm the Burn virtual machine"
-if [ -x "$BIN/ash" ]; then
- say " ash package manager: ash init github.com/you/app"
-fi
-say " burnup update or uninstall: burnup update, burnup uninstall"
-say ""
-if [ "$PATH_CHANGED" -eq 1 ]; then
- say "Restart your shell or run: . \"$ENV_FILE\""
-elif [ "$MODIFY_PATH" -eq 0 ]; then
- case ":$PATH:" in
- *":$BIN:"*) ;;
- *) say "Add $BIN to your PATH, for example: . \"$ENV_FILE\"" ;;
- esac
+if [ "$NO_PATH" -eq 1 ]; then
+ set -- "$@" --no-modify-path
fi
+step "Setting up"
+exec "$BIN/burnup" "$@"
diff --git a/src/main.bn b/src/main.bn
new file mode 100644
index 0000000..7cb98a5
--- /dev/null
+++ b/src/main.bn
@@ -0,0 +1,461 @@
+import "fs"
+import "process"
+import "strings"
+import "paths.bn"
+import "semver.bn"
+import "setup.bn"
+import "toolchain.bn"
+import "ui.bn"
+
+const VERSION = "0.2.0"
+
+priv fun help() {
+ print(bold("burnup") + " " + VERSION + " - installs and switches Burn versions")
+ print("")
+ print(bold("Versions"))
+ print(" burnup install [version...] install Burn versions (default: the latest)")
+ print(" burnup uninstall remove a version")
+ print(" burnup default [version] show or set the version used everywhere")
+ print(" burnup list installed versions")
+ print(" burnup list --remote versions that can be installed")
+ print(" burnup update update branch versions like master, and ash")
+ print("")
+ print(bold("Projects"))
+ print(" burnup pin use a version in this project (burn.toml) or folder")
+ print(" burnup show which version runs here, and why")
+ print(" burnup which [tool] the file that runs for burn, burni, burnc, ...")
+ print(" burnup run run one command with a version")
+ print("")
+ print(bold("Setup"))
+ print(" burnup link use a local build (with bin/burn) as a version")
+ print(" burnup ash install or update ash, the package manager")
+ print(" burnup self update update burnup itself")
+ print(" burnup self uninstall remove Burn, burnup and everything they installed")
+ print("")
+ print("A version is a release like 26.1 or v26.1.0, `latest`, a branch like `master`, or a commit.")
+ print("Projects pin one with burn = \"26.1\" in the [package] section of burn.toml.")
+}
+
+priv fun option(args: [string], name: string): string {
+ for i, a in args {
+ if (a == name && i + 1 < len(args)) {
+ return args[i + 1]
+ }
+ if (startsWith(a, name + "=")) {
+ return substring(a, len(name) + 1)
+ }
+ }
+ return ""
+}
+
+priv fun positional(args: [string], valued: [string]): [string] {
+ var out: [string] = []
+ var skip = false
+ for (a in args) {
+ if (skip) {
+ skip = false
+ continue
+ }
+ if (contains(valued, a)) {
+ skip = true
+ continue
+ }
+ if (!startsWith(a, "-")) {
+ out.push(a)
+ }
+ }
+ return out
+}
+
+priv fun proxy(tool: string, rest: [string]) {
+ if (!contains(TOOLS, tool)) {
+ die("burnup cannot run `${tool}`", "")
+ }
+ var t = activeToolchain(true)
+ var exe = t.dir + "/bin/" + tool
+ if (!Files.isFile(exe)) {
+ die("Burn ${t.name} has no ${tool}", "")
+ }
+ var code = Process.run(exe, rest)
+ if (code == -1) {
+ die("cannot start ${exe}", "reinstall it with `burnup install --force ${t.name}`")
+ }
+ exit(code)
+}
+
+priv fun cmdInstall(args: [string]) {
+ var force = contains(args, "--force")
+ var specs = positional(args, [])
+ if (len(specs) == 0) {
+ specs = ["latest"]
+ }
+ for (spec in specs) {
+ var t = install(resolve(spec), force)
+ if (defaultName() == "") {
+ setDefault(t.name)
+ step("Default", "Burn ${t.name}")
+ }
+ }
+}
+
+priv fun cmdDefault(args: [string]) {
+ var specs = positional(args, [])
+ if (len(specs) == 0) {
+ var d = defaultName()
+ if (d == "") {
+ print(dim("no default yet; set one with `burnup default latest`"))
+ } else {
+ print(d)
+ }
+ return
+ }
+ var found = findInstalled(specs[0])
+ var t = found ?? install(resolve(specs[0]), false)
+ setDefault(t.name)
+ step("Default", "Burn ${t.name}")
+}
+
+priv fun cmdList(args: [string]) {
+ if (contains(args, "--remote") || contains(args, "-r")) {
+ var r = remote()
+ if (r.error != "") {
+ die("cannot reach ${burnRepo()}: ${r.error}", "")
+ }
+ var tags = versionTags(r)
+ if (len(tags) == 0) {
+ print(dim("no releases yet"))
+ }
+ for (t in tags) {
+ var mark = ""
+ if (findInstalled(t) != null && findInstalled(t)!!.name == t) {
+ mark = green(" installed")
+ }
+ print(t + mark)
+ }
+ var branches = keys(r.heads)
+ sort(branches)
+ for (b in branches) {
+ if (b == r.headBranch) {
+ print(b + dim(" (newest commit, built from source)"))
+ }
+ }
+ return
+ }
+ var list = installed()
+ if (len(list) == 0) {
+ print(dim("nothing installed; run `burnup install`"))
+ return
+ }
+ var d = defaultName()
+ var width = 0
+ for (t in list) {
+ width = max(width, len(t.name))
+ }
+ for (t in list) {
+ var marks = ""
+ if (t.name == d) {
+ marks = green(" (default)")
+ }
+ var info = t.version
+ if (t.source == "source" && t.rev != "") {
+ info = info + dim(" " + substring(t.rev, 0, 9))
+ }
+ if (t.source == "link") {
+ info = info + dim(" linked to " + t.ref)
+ }
+ print(bold(padRight(t.name, width, " ")) + " " + info + marks)
+ }
+}
+
+priv fun cmdUpdate(args: [string]) {
+ var list = installed()
+ var r = remote()
+ if (r.error != "") {
+ die("cannot reach ${burnRepo()}: ${r.error}", "")
+ }
+ var updated = 0
+ for (t in list) {
+ var head = r.heads[t.name]
+ if (head != null && t.source != "link" && head!! != t.rev) {
+ install(Target { name: t.name, kind: "branch", ref: t.name, rev: head!! }, true)
+ updated += 1
+ }
+ }
+ var tags = versionTags(r)
+ var newest = ""
+ for (t in tags) {
+ if (newest == "" && parseVersion(t).pre == "") {
+ newest = t
+ }
+ }
+ if (newest == "" && len(tags) > 0) {
+ newest = tags[0]
+ }
+ var d = defaultName()
+ var dv = parseVersion(d)
+ if (newest != "" && dv.ok && compareVersions(parseVersion(newest), dv) > 0) {
+ print("")
+ print("Burn ${newest} is out. Switch with: burnup default ${newest}")
+ }
+ if (updated == 0) {
+ step("Finished", "the installed branch versions are up to date")
+ }
+ if (!contains(args, "--no-ash") && Files.isFile(binDir() + "/ash")) {
+ installAsh(activeToolchain(true))
+ }
+}
+
+priv fun cmdPin(args: [string]) {
+ var specs = positional(args, [])
+ if (len(specs) == 0) {
+ die("which version should be pinned?", "for example `burnup pin 26.1`, or `burnup pin master`")
+ }
+ var spec = specs[0]
+ if (findInstalled(spec) == null) {
+ install(resolve(spec), false)
+ }
+ var toml = Process.cwd() + "/burn.toml"
+ if (Files.isFile(toml)) {
+ var lines = split(readFile(toml), "\n")
+ var out: [string] = []
+ var inPackage = false
+ var done = false
+ for (line in lines) {
+ var t = trim(line)
+ if (startsWith(t, "[")) {
+ if (inPackage && !done) {
+ var n = len(out)
+ while (n > 0 && trim(out[n - 1]) == "") {
+ n -= 1
+ }
+ var blanks = slice(out, n)
+ out = slice(out, 0, n)
+ out.push("burn = \"" + spec + "\"")
+ for (b in blanks) {
+ out.push(b)
+ }
+ done = true
+ }
+ inPackage = t == "[package]"
+ } else if (inPackage && (startsWith(t, "burn =") || startsWith(t, "burn="))) {
+ out.push("burn = \"" + spec + "\"")
+ done = true
+ continue
+ }
+ out.push(line)
+ }
+ if (inPackage && !done) {
+ while (len(out) > 0 && trim(out[len(out) - 1]) == "") {
+ out.pop()
+ }
+ out.push("burn = \"" + spec + "\"")
+ out.push("")
+ done = true
+ }
+ if (!done) {
+ die("burn.toml has no [package] section", "")
+ }
+ writeFile(toml, join(out, "\n"))
+ step("Pinned", "Burn ${spec} in burn.toml")
+ return
+ }
+ writeFile(Process.cwd() + "/.burn-version", spec + "\n")
+ step("Pinned", "Burn ${spec} in .burn-version")
+}
+
+priv fun cmdShow() {
+ var a = activeSpec()
+ var t = findInstalled(a.spec)
+ if (t == null) {
+ print("Burn ${a.spec} " + red("(not installed)") + ", from ${a.reason}")
+ return
+ }
+ print(bold(t!!.name) + " " + t!!.version + dim(" from " + a.reason))
+ print(dim(t!!.dir))
+}
+
+priv fun cmdWhich(args: [string]) {
+ var tools = positional(args, [])
+ if (len(tools) == 0) {
+ tools = ["burn"]
+ }
+ var t = activeToolchain(false)
+ for (tool in tools) {
+ if (tool == "ash") {
+ print(binDir() + "/ash")
+ } else if (!contains(TOOLS, tool)) {
+ die("`${tool}` is not part of Burn", "the tools are " + join(TOOLS, ", "))
+ } else {
+ print(t.dir + "/bin/" + tool)
+ }
+ }
+}
+
+priv fun cmdRun(args: [string]) {
+ if (len(args) < 2) {
+ die("usage: burnup run [args...]", "for example `burnup run 26.1 burn build`")
+ }
+ var found = findInstalled(args[0])
+ var t = found ?? install(resolve(args[0]), false)
+ var cmd = args[1]
+ var exe = cmd
+ if (contains(TOOLS, cmd)) {
+ exe = t.dir + "/bin/" + cmd
+ }
+ var code = Process.run("env", ["BURN_TOOLCHAIN=" + t.name, "PATH=" + t.dir + "/bin:" + env("PATH"), exe] + slice(args, 2))
+ exit(code)
+}
+
+priv fun cmdLink(args: [string]) {
+ var p = positional(args, [])
+ if (len(p) != 2) {
+ die("usage: burnup link ", "the directory needs bin/burn, like the output of scripts/package.sh")
+ }
+ var dir = absPath(p[1])
+ if (!Files.isFile(dir + "/bin/burn")) {
+ die("${dir} has no bin/burn", "build one with `sh scripts/package.sh --prefix ` in a Burn checkout")
+ }
+ var target = toolchainDir(p[0])
+ if (Files.isDir(target) || Files.isFile(target)) {
+ die("there is already a version called ${p[0]}", "remove it first with `burnup uninstall ${p[0]}`")
+ }
+ Files.makeDir(toolchainsDir())
+ if (Process.run("ln", ["-s", dir, target]) != 0) {
+ die("cannot link ${dir}", "")
+ }
+ var version = trim(Process.output(dir + "/bin/burn", ["version"]).out)
+ writeKeys(dir + "/burnup.toml", {"name": p[0], "ref": dir, "rev": "", "source": "link", "version": replace(version, "Burn ", "")})
+ step("Linked", "${p[0]} to ${dir}")
+}
+
+priv fun cmdSetup(args: [string]) {
+ Files.makeDir(binDir())
+ Files.makeDir(toolchainsDir())
+ var marker = burnHome() + "/.burnup"
+ if (!Files.isFile(marker)) {
+ writeFile(marker, "")
+ }
+ var wanted = option(args, "--toolchain")
+ var list = installed()
+ var t: Toolchain? = null
+ if (wanted != "") {
+ t = findInstalled(wanted) ?? install(resolve(wanted), false)
+ } else if (defaultName() != "" && findInstalled(defaultName()) != null) {
+ t = findInstalled(defaultName())
+ } else if (len(list) > 0) {
+ t = list[0]
+ } else {
+ t = install(resolve("latest"), false)
+ }
+ setDefault(t!!.name)
+ writeShims()
+ for (old in ["share/burn/tools", "share/burn/examples", "share/burn/install.sh"]) {
+ Files.remove(burnHome() + "/" + old)
+ }
+ if (!contains(args, "--no-ash")) {
+ installAsh(t!!)
+ }
+ var changed: [string] = []
+ if (!contains(args, "--no-modify-path")) {
+ changed = modifyPath()
+ } else {
+ writeEnv()
+ }
+ print("")
+ print(green("Burn ${t!!.version} is installed") + " as the default version (${t!!.name}).")
+ print("")
+ print(" burn, burni, burnc, burnfmt, burn-lsp, bvm the Burn tools, from the active version")
+ if (Files.isFile(binDir() + "/ash")) {
+ print(" ash the package manager")
+ }
+ print(" burnup install and switch versions: burnup help")
+ print("")
+ if (len(changed) > 0) {
+ print("Added ${binDir()} to PATH in " + join(changed, ", ") + ".")
+ print("Restart your shell or run: . \"" + burnHome() + "/env\"")
+ } else if (!onPath()) {
+ print("Add ${binDir()} to your PATH, for example: . \"" + burnHome() + "/env\"")
+ }
+}
+
+priv fun cmdSelf(args: [string]) {
+ var what = ""
+ if (len(args) > 0) {
+ what = args[0]
+ }
+ if (what == "update") {
+ selfUpdate(activeToolchain(true))
+ } else if (what == "uninstall") {
+ var home = burnHome()
+ removePathLines()
+ if (Files.isFile(home + "/.burnup")) {
+ Files.remove(home)
+ } else {
+ for (tool in TOOLS) {
+ Files.remove(binDir() + "/" + tool)
+ }
+ for (x in ["bin/ash", "bin/burnup", "toolchains", "packages", "tools", "index", "index.fetched", "cache", "tmp", "env", "burnup.toml", "share/burn"]) {
+ Files.remove(home + "/" + x)
+ }
+ }
+ eprint(green("Burn has been uninstalled."))
+ } else {
+ die("usage: burnup self update | burnup self uninstall", "")
+ }
+}
+
+fun main() {
+ var argv = args()
+ if (len(argv) == 0) {
+ help()
+ return
+ }
+ var cmd = argv[0]
+ var rest = slice(argv, 1)
+ if (cmd == "proxy") {
+ if (len(rest) == 0) {
+ die("usage: burnup proxy [args...]", "")
+ }
+ proxy(rest[0], slice(rest, 1))
+ } else if (cmd == "-h" || cmd == "--help" || cmd == "help") {
+ help()
+ } else if (cmd == "-v" || cmd == "--version" || cmd == "version") {
+ print("burnup " + VERSION)
+ } else if (cmd == "install" || cmd == "add" || cmd == "i") {
+ cmdInstall(rest)
+ } else if (cmd == "uninstall" || cmd == "remove" || cmd == "rm") {
+ var names = positional(rest, [])
+ if (len(names) == 0) {
+ die("which version should be removed?", "see the installed ones with `burnup list`")
+ }
+ for (n in names) {
+ uninstall(n)
+ }
+ } else if (cmd == "default" || cmd == "use") {
+ cmdDefault(rest)
+ } else if (cmd == "list" || cmd == "ls") {
+ cmdList(rest)
+ } else if (cmd == "update" || cmd == "up") {
+ cmdUpdate(rest)
+ } else if (cmd == "pin") {
+ cmdPin(rest)
+ } else if (cmd == "show" || cmd == "current") {
+ cmdShow()
+ } else if (cmd == "which") {
+ cmdWhich(rest)
+ } else if (cmd == "run") {
+ cmdRun(rest)
+ } else if (cmd == "link") {
+ cmdLink(rest)
+ } else if (cmd == "ash") {
+ installAsh(activeToolchain(true))
+ } else if (cmd == "setup") {
+ cmdSetup(rest)
+ } else if (cmd == "self") {
+ cmdSelf(rest)
+ } else if (cmd == "uninstall-all") {
+ cmdSelf(["uninstall"])
+ } else {
+ die("`${cmd}` is not a burnup command", "see `burnup help`")
+ }
+}
diff --git a/src/paths.bn b/src/paths.bn
new file mode 100644
index 0000000..b0d7c85
--- /dev/null
+++ b/src/paths.bn
@@ -0,0 +1,111 @@
+import "fs"
+import "process"
+
+pub fun parentDir(path: string): string {
+ var p = path
+ while (len(p) > 1 && endsWith(p, "/")) {
+ p = substring(p, 0, len(p) - 1)
+ }
+ var parts = split(p, "/")
+ if (len(parts) <= 1) {
+ return "."
+ }
+ var up = join(slice(parts, 0, len(parts) - 1), "/")
+ if (up == "") {
+ return "/"
+ }
+ return up
+}
+
+pub fun absPath(path: string): string {
+ if (startsWith(path, "/")) {
+ return path
+ }
+ return Process.cwd() + "/" + path
+}
+
+pub fun burnHome(): string {
+ var h = env("BURN_HOME")
+ if (h != "") {
+ return absPath(h)
+ }
+ return env("HOME") + "/.burn"
+}
+
+pub fun binDir(): string {
+ return burnHome() + "/bin"
+}
+
+pub fun toolchainsDir(): string {
+ return burnHome() + "/toolchains"
+}
+
+pub fun shellQuote(text: string): string {
+ return "'" + replace(text, "'", "'\\''") + "'"
+}
+
+pub fun readKeys(path: string): {string: string} {
+ var out: {string: string} = {}
+ if (!Files.isFile(path)) {
+ return out
+ }
+ var section = ""
+ for (raw in split(readFile(path), "\n")) {
+ var line = trim(raw)
+ if (startsWith(line, "[")) {
+ section = trim(replace(replace(line, "[", ""), "]", ""))
+ continue
+ }
+ var eq = indexOf(line, "=")
+ if (eq <= 0 || startsWith(line, "#")) {
+ continue
+ }
+ var key = trim(substring(line, 0, eq))
+ var value = trim(substring(line, eq + 1))
+ var hash = indexOf(value, " #")
+ if (hash >= 0 && !startsWith(value, "\"")) {
+ value = trim(substring(value, 0, hash))
+ }
+ if (startsWith(value, "\"")) {
+ var rest = substring(value, 1)
+ var end = indexOf(rest, "\"")
+ if (end >= 0) {
+ value = substring(rest, 0, end)
+ }
+ }
+ if (section != "") {
+ key = section + "." + key
+ }
+ out[key] = value
+ }
+ return out
+}
+
+pub fun writeKeys(path: string, values: {string: string}) {
+ var names = keys(values)
+ sort(names)
+ var text = ""
+ for (k in names) {
+ text = text + k + " = \"" + replace(values[k]!!, "\"", "") + "\"\n"
+ }
+ Files.makeDir(parentDir(path))
+ if (!writeFile(path, text)) {
+ eprint("error: cannot write " + path)
+ exit(1)
+ }
+}
+
+pub fun findUp(start: string, names: [string]): string {
+ var dir = absPath(start)
+ while (true) {
+ for (n in names) {
+ if (Files.isFile(dir + "/" + n)) {
+ return dir + "/" + n
+ }
+ }
+ if (dir == "/" || dir == "." || dir == "") {
+ return ""
+ }
+ dir = parentDir(dir)
+ }
+}
diff --git a/src/semver.bn b/src/semver.bn
new file mode 100644
index 0000000..04162e2
--- /dev/null
+++ b/src/semver.bn
@@ -0,0 +1,147 @@
+pub def type Version {
+ int major
+ int minor
+ int patch
+ string pre
+ int parts
+ bool ok
+}
+
+pub def type Spec {
+ string kind
+ Version base
+ string text
+}
+
+pub fun parseVersion(text: string): Version {
+ var t = trim(text)
+ if (startsWith(t, "v") || startsWith(t, "V")) {
+ t = substring(t, 1)
+ }
+ var pre = ""
+ var dash = indexOf(t, "-")
+ if (dash >= 0) {
+ pre = substring(t, dash + 1)
+ t = substring(t, 0, dash)
+ }
+ var bad = Version { major: 0, minor: 0, patch: 0, pre: "", parts: 0, ok: false }
+ var nums = split(t, ".")
+ if (t == "" || len(nums) > 3) {
+ return bad
+ }
+ var vals = [0, 0, 0]
+ for i, n in nums {
+ if (n == "" || !isDigit(n)) {
+ return bad
+ }
+ vals[i] = toInt(n)
+ }
+ return Version { major: vals[0], minor: vals[1], patch: vals[2], pre: pre, parts: len(nums), ok: true }
+}
+
+pub fun formatVersion(v: Version): string {
+ var s = "${v.major}.${v.minor}.${v.patch}"
+ if (v.pre != "") {
+ s = s + "-" + v.pre
+ }
+ return s
+}
+
+priv fun order(less: bool): int {
+ if (less) {
+ return -1
+ }
+ return 1
+}
+
+pub fun compareVersions(a: Version, b: Version): int {
+ if (a.major != b.major) {
+ return order(a.major < b.major)
+ }
+ if (a.minor != b.minor) {
+ return order(a.minor < b.minor)
+ }
+ if (a.patch != b.patch) {
+ return order(a.patch < b.patch)
+ }
+ if (a.pre == b.pre) {
+ return 0
+ }
+ if (a.pre == "") {
+ return 1
+ }
+ if (b.pre == "") {
+ return -1
+ }
+ return order(a.pre < b.pre)
+}
+
+pub fun parseSpec(text: string): Spec {
+ var t = trim(text)
+ var none = Version { major: 0, minor: 0, patch: 0, pre: "", parts: 0, ok: false }
+ if (t == "" || t == "*" || t == "latest") {
+ return Spec { kind: "any", base: none, text: "*" }
+ }
+ if (startsWith(t, "#")) {
+ return Spec { kind: "rev", base: none, text: substring(t, 1) }
+ }
+ var kind = "caret"
+ var rest = t
+ if (startsWith(t, ">=")) {
+ kind = "atleast"
+ rest = substring(t, 2)
+ } else if (startsWith(t, "^")) {
+ rest = substring(t, 1)
+ } else if (startsWith(t, "~")) {
+ kind = "tilde"
+ rest = substring(t, 1)
+ } else if (startsWith(t, "=")) {
+ kind = "exact"
+ rest = substring(t, 1)
+ }
+ var v = parseVersion(rest)
+ if (!v.ok) {
+ return Spec { kind: "branch", base: none, text: t }
+ }
+ return Spec { kind: kind, base: v, text: t }
+}
+
+pub fun specAllows(spec: Spec, v: Version): bool {
+ if (spec.kind == "any") {
+ return v.ok && v.pre == ""
+ }
+ if (!v.ok || spec.kind == "branch" || spec.kind == "rev") {
+ return false
+ }
+ var b = spec.base
+ if (v.pre != "" && (b.pre == "" || v.major != b.major || v.minor != b.minor || v.patch != b.patch)) {
+ return false
+ }
+ var cmp = compareVersions(v, b)
+ if (spec.kind == "exact") {
+ return cmp == 0
+ }
+ if (cmp < 0) {
+ return false
+ }
+ if (spec.kind == "atleast") {
+ return true
+ }
+ if (spec.kind == "tilde") {
+ if (b.parts == 1) {
+ return v.major == b.major
+ }
+ return v.major == b.major && v.minor == b.minor
+ }
+ if (b.major > 0 || b.parts == 1) {
+ return v.major == b.major
+ }
+ if (b.minor > 0 || b.parts == 2) {
+ return v.major == 0 && v.minor == b.minor
+ }
+ return v.major == 0 && v.minor == 0 && v.patch == b.patch
+}
+
+pub fun caretFor(v: Version): string {
+ return "^" + formatVersion(v)
+}
diff --git a/src/setup.bn b/src/setup.bn
new file mode 100644
index 0000000..1ce427c
--- /dev/null
+++ b/src/setup.bn
@@ -0,0 +1,179 @@
+import "fs"
+import "process"
+import "paths.bn"
+import "toolchain.bn"
+import "ui.bn"
+
+pub const TOOLS = ["burn", "burni", "burnc", "burnfmt", "burn-lsp", "bvm"]
+
+priv const MARKER = "# added by burnup"
+priv const OLD_MARKER = "# added by the Burn installer"
+
+pub fun selfPath(): string {
+ return binDir() + "/burnup"
+}
+
+pub fun writeShims() {
+ Files.makeDir(binDir())
+ for (tool in TOOLS) {
+ var path = binDir() + "/" + tool
+ var text = "#!/bin/sh\nexec " + shellQuote(selfPath()) + " proxy " + tool + " \"$@\"\n"
+ Files.remove(path)
+ if (!writeFile(path, text)) {
+ die("cannot write ${path}", "")
+ }
+ Process.run("chmod", ["+x", path])
+ }
+}
+
+priv fun profiles(): [string] {
+ var home = env("HOME")
+ var out: [string] = []
+ for (f in [".profile", ".bashrc", ".bash_profile", ".zshrc", ".zprofile"]) {
+ if (Files.isFile(home + "/" + f)) {
+ out.push(home + "/" + f)
+ }
+ }
+ return out
+}
+
+priv fun envFile(): string {
+ return burnHome() + "/env"
+}
+
+pub fun writeEnv() {
+ var bin = binDir()
+ var text = "case \":\${PATH}:\" in\n *:\"" + bin + "\":*) ;;\n *) export PATH=\"" + bin + ":$PATH\" ;;\nesac\n"
+ writeFile(envFile(), text)
+}
+
+pub fun onPath(): bool {
+ return contains(":" + env("PATH") + ":", ":" + binDir() + ":")
+}
+
+pub fun modifyPath(): [string] {
+ writeEnv()
+ var changed: [string] = []
+ if (onPath()) {
+ return changed
+ }
+ var line = ". \"" + envFile() + "\" " + MARKER
+ var files = profiles()
+ if (len(files) == 0) {
+ files = [env("HOME") + "/.profile"]
+ }
+ for (f in files) {
+ var text = ""
+ if (Files.isFile(f)) {
+ text = readFile(f)
+ }
+ if (contains(text, MARKER) || contains(text, OLD_MARKER)) {
+ continue
+ }
+ if (text != "" && !endsWith(text, "\n")) {
+ text = text + "\n"
+ }
+ writeFile(f, text + "\n" + line + "\n")
+ changed.push(f)
+ }
+ var fish = env("HOME") + "/.config/fish"
+ if (Files.isDir(fish)) {
+ Files.makeDir(fish + "/conf.d")
+ writeFile(fish + "/conf.d/burn.fish", "fish_add_path -g \"" + binDir() + "\" " + MARKER + "\n")
+ changed.push(fish + "/conf.d/burn.fish")
+ }
+ return changed
+}
+
+pub fun removePathLines() {
+ for (f in profiles()) {
+ var text = readFile(f)
+ if (!contains(text, MARKER) && !contains(text, OLD_MARKER)) {
+ continue
+ }
+ var kept: [string] = []
+ for (line in split(text, "\n")) {
+ if (!contains(line, MARKER) && !contains(line, OLD_MARKER)) {
+ kept.push(line)
+ }
+ }
+ writeFile(f, join(kept, "\n"))
+ }
+ Files.remove(env("HOME") + "/.config/fish/conf.d/burn.fish")
+}
+
+priv fun ashRepo(): string {
+ var r = env("ASH_REPO")
+ if (r != "") {
+ return r
+ }
+ return "https://github.com/burnlang/ash"
+}
+
+pub fun installAsh(t: Toolchain) {
+ var ref = env("ASH_REF")
+ if (ref == "") {
+ ref = "master"
+ }
+ var dir = burnHome() + "/tools/github.com/burnlang/ash"
+ step("Installing", "ash, the package manager")
+ Files.remove(dir)
+ Files.makeDir(parentDir(dir))
+ var c = Process.output("env", ["GIT_TERMINAL_PROMPT=0", "git", "clone", "-q", "--depth", "1", "--branch", ref, ashRepo(), dir])
+ if (c.code != 0) {
+ warn("could not download ash from ${ashRepo()}; try again later with `burnup ash`")
+ return
+ }
+ Files.remove(dir + "/.git")
+ var out = binDir() + "/ash"
+ Process.setCwd(dir)
+ var built = Process.output(t.dir + "/bin/burn", ["build", "--target", "native", "-o", out + ".new"])
+ if (built.code == 0) {
+ Files.rename(out + ".new", out)
+ } else if (contains(built.err, "native") || contains(built.err, "link")) {
+ warn("native compilation is not available here, so ash runs on the interpreter")
+ writeFile(out, "#!/bin/sh\nexec " + shellQuote(binDir() + "/burni") + " " + shellQuote(dir + "/src/main.bn") + " \"$@\"\n")
+ Process.run("chmod", ["+x", out])
+ } else {
+ eprint(built.out + built.err)
+ warn("ash does not build with Burn ${t.name}; try `burnup ash` after `burnup update`")
+ return
+ }
+ writeFile(burnHome() + "/tools/github.com/burnlang/ash.version", ref)
+ step("Installed", "ash")
+}
+
+pub fun selfUpdate(t: Toolchain) {
+ var base = env("BURNUP_RELEASES")
+ if (base == "") {
+ base = "https://github.com/burnlang/burnup/releases/latest/download"
+ }
+ var target = selfPath()
+ var got = Process.output("curl", ["-fsSL", "-o", target + ".new", base + "/burnup-" + platform()])
+ if (got.code == 0 && Process.run("chmod", ["+x", target + ".new"]) == 0 && Process.output(target + ".new", ["version"]).code == 0) {
+ Files.rename(target + ".new", target)
+ step("Updated", "burnup from the latest release")
+ return
+ }
+ Files.remove(target + ".new")
+ var repo = env("BURNUP_REPO")
+ if (repo == "") {
+ repo = "https://github.com/burnlang/burnup"
+ }
+ var dir = burnHome() + "/tmp/burnup-src"
+ Files.remove(dir)
+ step("Building", "burnup from ${repo}")
+ if (Process.output("env", ["GIT_TERMINAL_PROMPT=0", "git", "clone", "-q", "--depth", "1", repo, dir]).code != 0) {
+ die("cannot download burnup from ${repo}", "")
+ }
+ Process.setCwd(dir)
+ var built = Process.output(t.dir + "/bin/burn", ["build", "--target", "native", "-o", target + ".new"])
+ if (built.code != 0) {
+ eprint(built.out + built.err)
+ Files.remove(dir)
+ die("burnup does not build with Burn ${t.name}", "")
+ }
+ Files.rename(target + ".new", target)
+ Files.remove(dir)
+ step("Updated", "burnup")
+}
diff --git a/src/toolchain.bn b/src/toolchain.bn
new file mode 100644
index 0000000..f18a49d
--- /dev/null
+++ b/src/toolchain.bn
@@ -0,0 +1,480 @@
+import "fs"
+import "process"
+import "paths.bn"
+import "semver.bn"
+import "ui.bn"
+
+pub def type Toolchain {
+ string name
+ string dir
+ string ref
+ string rev
+ string source
+ string version
+}
+
+pub def type Target {
+ string name
+ string kind
+ string ref
+ string rev
+}
+
+pub def type BurnRemote {
+ {string: string} tags
+ {string: string} heads
+ string head
+ string headBranch
+ string error
+ bool loaded
+}
+
+pub def type Active {
+ string spec
+ string reason
+}
+
+priv var remoteCache = BurnRemote { tags: {}, heads: {}, head: "", headBranch: "", error: "", loaded: false }
+
+pub fun burnRepo(): string {
+ var r = env("BURN_REPO")
+ if (r != "") {
+ return r
+ }
+ return "https://github.com/burnlang/burn"
+}
+
+pub fun releasesBase(): string {
+ var r = env("BURN_RELEASES")
+ if (r != "") {
+ return r
+ }
+ return burnRepo() + "/releases/download"
+}
+
+pub fun platform(): string {
+ var os = lower(trim(Process.output("uname", ["-s"]).out))
+ var arch = trim(Process.output("uname", ["-m"]).out)
+ if (os == "darwin") {
+ os = "macos"
+ }
+ if (arch == "amd64") {
+ arch = "x86_64"
+ }
+ if (arch == "arm64") {
+ arch = "aarch64"
+ }
+ return os + "-" + arch
+}
+
+priv fun git(args: [string]): ProcessOutput {
+ var full = ["GIT_TERMINAL_PROMPT=0", "git"]
+ for (a in args) {
+ full.push(a)
+ }
+ return Process.output("env", full)
+}
+
+pub fun remote(): BurnRemote {
+ if (remoteCache.loaded) {
+ return remoteCache
+ }
+ remoteCache.loaded = true
+ var out = git(["ls-remote", "--symref", burnRepo()])
+ if (out.code != 0) {
+ remoteCache.error = trim(out.err)
+ return remoteCache
+ }
+ for (line in split(out.out, "\n")) {
+ var parts = split(line, "\t")
+ if (len(parts) != 2) {
+ continue
+ }
+ var left = parts[0]
+ var ref = trim(parts[1])
+ if (startsWith(left, "ref: ") && ref == "HEAD") {
+ remoteCache.headBranch = replace(substring(left, 5), "refs/heads/", "")
+ } else if (ref == "HEAD") {
+ remoteCache.head = left
+ } else if (startsWith(ref, "refs/heads/")) {
+ remoteCache.heads[substring(ref, 11)] = left
+ } else if (startsWith(ref, "refs/tags/")) {
+ var tag = substring(ref, 10)
+ if (endsWith(tag, "^{}")) {
+ remoteCache.tags[substring(tag, 0, len(tag) - 3)] = left
+ } else if (remoteCache.tags[tag] == null) {
+ remoteCache.tags[tag] = left
+ }
+ }
+ }
+ return remoteCache
+}
+
+pub fun versionTags(r: BurnRemote): [string] {
+ var out: [string] = []
+ for tag, sha in r.tags {
+ if (parseVersion(tag).ok) {
+ out.push(tag)
+ }
+ }
+ var n = len(out)
+ for (i in 0..n) {
+ for (j in i + 1..n) {
+ if (compareVersions(parseVersion(out[j]), parseVersion(out[i])) > 0) {
+ var t = out[i]
+ out[i] = out[j]
+ out[j] = t
+ }
+ }
+ }
+ return out
+}
+
+priv fun isHex(text: string): bool {
+ if (len(text) < 7 || len(text) > 40) {
+ return false
+ }
+ for (c in chars(lower(text))) {
+ if (!isDigit(c) && indexOf("abcdef", c) < 0) {
+ return false
+ }
+ }
+ return true
+}
+
+pub fun versionMatches(spec: string, v: Version): bool {
+ if (!v.ok) {
+ return false
+ }
+ var t = trim(spec)
+ if (startsWith(t, "^") || startsWith(t, "~") || startsWith(t, "=") || startsWith(t, ">")) {
+ return specAllows(parseSpec(t), v)
+ }
+ var b = parseVersion(t)
+ if (!b.ok) {
+ return false
+ }
+ if (v.major != b.major || (b.parts >= 2 && v.minor != b.minor) || (b.parts >= 3 && v.patch != b.patch)) {
+ return false
+ }
+ return b.pre == "" || b.pre == v.pre
+}
+
+pub fun isLatest(spec: string): bool {
+ return spec == "" || spec == "latest" || spec == "stable"
+}
+
+pub fun resolve(spec: string): Target {
+ var r = remote()
+ if (r.error != "") {
+ die("cannot reach the Burn repository ${burnRepo()}: ${r.error}", "check your connection, or set BURN_REPO")
+ }
+ var tags = versionTags(r)
+ if (isLatest(spec)) {
+ for (t in tags) {
+ if (parseVersion(t).pre == "") {
+ return Target { name: t, kind: "tag", ref: t, rev: r.tags[t]!! }
+ }
+ }
+ if (len(tags) > 0) {
+ return Target { name: tags[0], kind: "tag", ref: tags[0], rev: r.tags[tags[0]]!! }
+ }
+ var branch = r.headBranch
+ if (branch == "") {
+ branch = "master"
+ }
+ return Target { name: branch, kind: "branch", ref: branch, rev: r.head }
+ }
+ if (r.heads[spec] != null) {
+ return Target { name: spec, kind: "branch", ref: spec, rev: r.heads[spec]!! }
+ }
+ for (candidate in [spec, "v" + spec]) {
+ if (r.tags[candidate] != null) {
+ return Target { name: candidate, kind: "tag", ref: candidate, rev: r.tags[candidate]!! }
+ }
+ }
+ for (t in tags) {
+ if (versionMatches(spec, parseVersion(t))) {
+ return Target { name: t, kind: "tag", ref: t, rev: r.tags[t]!! }
+ }
+ }
+ var hex = spec
+ if (startsWith(hex, "#")) {
+ hex = substring(hex, 1)
+ }
+ if (isHex(hex)) {
+ return Target { name: substring(lower(hex), 0, min(len(hex), 12)), kind: "commit", ref: lower(hex), rev: lower(hex) }
+ }
+ var known: [string] = []
+ for (t in slice(tags, 0, min(len(tags), 8))) {
+ known.push(t)
+ }
+ for b, sha in r.heads {
+ if (len(known) < 12) {
+ known.push(b)
+ }
+ }
+ var help = "there are no versions yet"
+ if (len(known) > 0) {
+ help = "available: " + join(known, ", ") + "; see all with `burnup list --remote`"
+ }
+ die("there is no Burn version called `${spec}`", help)
+ return Target { name: "", kind: "", ref: "", rev: "" }
+}
+
+pub fun toolchainDir(name: string): string {
+ return toolchainsDir() + "/" + name
+}
+
+pub fun readToolchain(name: string): Toolchain? {
+ var dir = toolchainDir(name)
+ if (!Files.isFile(dir + "/bin/burn")) {
+ return null
+ }
+ var meta = readKeys(dir + "/burnup.toml")
+ return Toolchain {
+ name: name,
+ dir: dir,
+ ref: meta["ref"] ?? name,
+ rev: meta["rev"] ?? "",
+ source: meta["source"] ?? "unknown",
+ version: meta["version"] ?? ""
+ }
+}
+
+pub fun installed(): [Toolchain] {
+ var out: [Toolchain] = []
+ for (n in Files.list(toolchainsDir())) {
+ if (endsWith(n, ".partial") || startsWith(n, ".")) {
+ continue
+ }
+ var t = readToolchain(n)
+ if (t != null) {
+ out.push(t!!)
+ }
+ }
+ return out
+}
+
+pub fun settingsFile(): string {
+ return burnHome() + "/burnup.toml"
+}
+
+pub fun defaultName(): string {
+ return readKeys(settingsFile())["default"] ?? ""
+}
+
+pub fun setDefault(name: string) {
+ var s = readKeys(settingsFile())
+ if (name == "") {
+ s = {}
+ } else {
+ s["default"] = name
+ }
+ writeKeys(settingsFile(), s)
+}
+
+priv fun run(program: string, args: [string]): int {
+ var code = Process.run(program, args)
+ if (code == -1) {
+ die("`${program}` is not installed", "")
+ }
+ return code
+}
+
+priv fun fromRelease(t: Target, partial: string): bool {
+ var archive = "burn-${platform()}.tar.gz"
+ var url = releasesBase() + "/" + t.ref + "/" + archive
+ var tmp = burnHome() + "/tmp/" + t.name
+ Files.remove(tmp)
+ Files.makeDir(tmp + "/x")
+ var got = Process.output("curl", ["-fsSL", "-o", tmp + "/" + archive, url])
+ if (got.code != 0) {
+ Files.remove(tmp)
+ return false
+ }
+ step("Unpacking", archive)
+ if (Process.output("tar", ["-xzf", tmp + "/" + archive, "-C", tmp + "/x"]).code != 0) {
+ Files.remove(tmp)
+ return false
+ }
+ var root = tmp + "/x"
+ if (Files.isDir(root + "/burn")) {
+ root = root + "/burn"
+ }
+ if (!Files.isFile(root + "/bin/burn")) {
+ Files.remove(tmp)
+ return false
+ }
+ var moved = Files.rename(root, partial)
+ Files.remove(tmp)
+ return moved
+}
+
+priv fun fromSource(t: Target, partial: string) {
+ if (Process.output("cargo", ["--version"]).code != 0) {
+ die("building Burn ${t.name} from source needs Rust, but `cargo` was not found", "install Rust from https://rustup.rs, or pick a version with a prebuilt release (`burnup list --remote`)")
+ }
+ var src = burnHome() + "/cache/burn"
+ if (!Files.isDir(src + "/.git")) {
+ step("Cloning", burnRepo())
+ Files.remove(src)
+ Files.makeDir(parentDir(src))
+ if (git(["clone", "-q", "--filter=blob:none", burnRepo(), src]).code != 0) {
+ Files.remove(src)
+ die("cannot clone ${burnRepo()}", "")
+ }
+ }
+ if (git(["-C", src, "fetch", "-q", "origin", t.ref]).code != 0) {
+ die("cannot fetch ${t.ref} from ${burnRepo()}", "")
+ }
+ if (git(["-C", src, "checkout", "-q", "--force", "FETCH_HEAD"]).code != 0) {
+ die("cannot check out ${t.ref}", "")
+ }
+ if (!Files.isFile(src + "/scripts/package.sh")) {
+ die("Burn ${t.name} is too old for burnup (it has no scripts/package.sh)", "install a newer version")
+ }
+ step("Building", "Burn ${t.name} from source (the first build takes a minute)")
+ if (run("sh", [src + "/scripts/package.sh", "--prefix", partial, "-q"]) != 0) {
+ Files.remove(partial)
+ die("building Burn ${t.name} failed", "")
+ }
+}
+
+pub fun install(t: Target, force: bool): Toolchain {
+ var existing = readToolchain(t.name)
+ if (existing != null && !force) {
+ var e = existing!!
+ if (t.kind != "branch" || e.rev == t.rev || t.rev == "") {
+ step("Installed", "Burn ${e.name} is already installed")
+ return e
+ }
+ }
+ var dir = toolchainDir(t.name)
+ var partial = dir + ".partial"
+ Files.remove(partial)
+ Files.makeDir(toolchainsDir())
+ var source = "release"
+ step("Installing", "Burn ${t.name}")
+ if (t.kind != "tag" || !fromRelease(t, partial)) {
+ source = "source"
+ fromSource(t, partial)
+ }
+ var version = trim(Process.output(partial + "/bin/burn", ["version"]).out)
+ if (!startsWith(version, "Burn ")) {
+ Files.remove(partial)
+ die("the installed burn binary of ${t.name} does not run", "")
+ }
+ Files.remove(dir)
+ if (!Files.rename(partial, dir)) {
+ die("cannot move the toolchain into ${dir}", "")
+ }
+ var rev = t.rev
+ if (source == "source") {
+ var head = git(["-C", burnHome() + "/cache/burn", "rev-parse", "HEAD"])
+ if (head.code == 0) {
+ rev = trim(head.out)
+ }
+ }
+ writeKeys(dir + "/burnup.toml", {"name": t.name, "ref": t.ref, "rev": rev, "source": source, "version": substring(version, 5)})
+ step("Installed", "Burn ${t.name} (${substring(version, 5)})")
+ return readToolchain(t.name)!!
+}
+
+pub fun findInstalled(spec: string): Toolchain? {
+ var list = installed()
+ for (t in list) {
+ if (t.name == spec || t.name == "v" + spec) {
+ return t
+ }
+ }
+ if (isLatest(spec)) {
+ var best: Toolchain? = null
+ for (t in list) {
+ var v = parseVersion(t.name)
+ if (v.ok && (best == null || compareVersions(v, parseVersion(best!!.name)) > 0)) {
+ best = t
+ }
+ }
+ return best
+ }
+ var best: Toolchain? = null
+ for (t in list) {
+ var v = parseVersion(t.name)
+ if (versionMatches(spec, v) && (best == null || compareVersions(v, parseVersion(best!!.name)) > 0)) {
+ best = t
+ }
+ }
+ return best
+}
+
+pub fun pinnedIn(dir: string): Active? {
+ if (Files.isFile(dir + "/burn.toml")) {
+ var pin = readKeys(dir + "/burn.toml")["package.burn"]
+ if (pin != null && pin!! != "") {
+ return Active { spec: pin!!, reason: dir + "/burn.toml" }
+ }
+ }
+ if (Files.isFile(dir + "/.burn-version")) {
+ var v = trim(readFile(dir + "/.burn-version"))
+ if (v != "") {
+ return Active { spec: split(v, "\n")[0], reason: dir + "/.burn-version" }
+ }
+ }
+ return null
+}
+
+pub fun activeSpec(): Active {
+ var e = env("BURN_TOOLCHAIN")
+ if (e != "") {
+ return Active { spec: e, reason: "the BURN_TOOLCHAIN environment variable" }
+ }
+ var dir = Process.cwd()
+ while (true) {
+ var p = pinnedIn(dir)
+ if (p != null) {
+ return p!!
+ }
+ if (dir == "/" || dir == "") {
+ break
+ }
+ dir = parentDir(dir)
+ }
+ var d = defaultName()
+ if (d == "") {
+ die("no Burn version is installed", "install one with `burnup install`")
+ }
+ return Active { spec: d, reason: "the default" }
+}
+
+pub fun activeToolchain(autoInstall: bool): Toolchain {
+ var a = activeSpec()
+ var found = findInstalled(a.spec)
+ if (found != null) {
+ return found!!
+ }
+ if (!autoInstall) {
+ die("Burn ${a.spec} (asked for by ${a.reason}) is not installed", "install it with `burnup install ${a.spec}`")
+ }
+ step("Missing", "Burn ${a.spec}, asked for by ${a.reason}")
+ return install(resolve(a.spec), false)
+}
+
+pub fun uninstall(name: string) {
+ var t = findInstalled(name)
+ if (t == null) {
+ die("Burn ${name} is not installed", "see what is installed with `burnup list`")
+ }
+ Files.remove(t!!.dir)
+ step("Removed", "Burn ${t!!.name}")
+ if (defaultName() == t!!.name) {
+ var rest = installed()
+ if (len(rest) > 0) {
+ setDefault(rest[0].name)
+ warn("the default was ${t!!.name}; it is now ${rest[0].name}")
+ } else {
+ setDefault("")
+ warn("no Burn version is installed any more; install one with `burnup install`")
+ }
+ }
+}
diff --git a/src/ui.bn b/src/ui.bn
new file mode 100644
index 0000000..e078810
--- /dev/null
+++ b/src/ui.bn
@@ -0,0 +1,57 @@
+import "process"
+import "strings"
+
+priv var colorState = 0
+
+priv fun paint(code: string, text: string): string {
+ if (colorState == 0) {
+ colorState = 2
+ if (env("NO_COLOR") == "" && env("TERM") != "" && env("TERM") != "dumb" && Process.run("test", ["-t", "2"]) == 0) {
+ colorState = 1
+ }
+ }
+ if (colorState != 1) {
+ return text
+ }
+ return "\u{1b}[" + code + "m" + text + "\u{1b}[0m"
+}
+
+pub fun bold(text: string): string {
+ return paint("1", text)
+}
+
+pub fun dim(text: string): string {
+ return paint("2", text)
+}
+
+pub fun green(text: string): string {
+ return paint("1;32", text)
+}
+
+pub fun cyan(text: string): string {
+ return paint("36", text)
+}
+
+pub fun yellow(text: string): string {
+ return paint("1;33", text)
+}
+
+pub fun red(text: string): string {
+ return paint("1;31", text)
+}
+
+pub fun step(verb: string, text: string) {
+ eprint(green(padLeft(verb, 12, " ")) + " " + text)
+}
+
+pub fun warn(text: string) {
+ eprint(yellow("warning:") + " " + text)
+}
+
+pub fun die(message: string, help: string) {
+ eprint(red("error:") + " " + message)
+ if (help != "") {
+ eprint(" " + cyan("= help:") + " " + help)
+ }
+ exit(1)
+}
diff --git a/tests/e2e.sh b/tests/e2e.sh
new file mode 100644
index 0000000..86a6a92
--- /dev/null
+++ b/tests/e2e.sh
@@ -0,0 +1,120 @@
+#!/bin/sh
+set -eu
+
+here="$(cd "$(dirname "$0")/.." && pwd)"
+work="$(mktemp -d)"
+trap '[ -n "${KEEP:-}" ] || rm -rf "$work"' EXIT
+export HOME="$work/home" BURN_HOME="$work/home/.burn" NO_COLOR=1 ASH_REPO="$work/no-ash"
+export GIT_AUTHOR_NAME=test GIT_AUTHOR_EMAIL=test@example.com GIT_COMMITTER_NAME=test GIT_COMMITTER_EMAIL=test@example.com
+mkdir -p "$HOME"
+touch "$HOME/.profile"
+
+fail() {
+ printf 'FAIL: %s\n' "$*" >&2
+ exit 1
+}
+
+expect() {
+ printf '%s' "$1" | grep -q -- "$2" || fail "expected \"$2\" in: $1"
+}
+
+burn_exe="$(command -v burn)"
+burni_exe="$(command -v burni)"
+burn_root="$(cd "$(dirname "$(readlink -f "$burn_exe")")" && pwd)"
+dist="$work/dist/burn"
+mkdir -p "$dist/bin"
+cp "$burn_root/burn" "$dist/bin/burn"
+for tool in burni burnc burn-lsp; do ln -s burn "$dist/bin/$tool"; done
+cat >"$dist/bin/burnfmt" <<'SH'
+#!/bin/sh
+exec "$(dirname "$0")/burn" fmt "$@"
+SH
+chmod +x "$dist/bin/burnfmt"
+if [ -x "$burn_root/bvm" ]; then cp "$burn_root/bvm" "$dist/bin/bvm"; fi
+
+platform="$(uname -s | tr '[:upper:]' '[:lower:]' | sed 's/darwin/macos/')-$(uname -m | sed 's/amd64/x86_64/; s/arm64/aarch64/')"
+repo="$work/burn-repo"
+git init -q "$repo"
+for tag in v1.0.0 v1.1.0 v2.0.0-beta; do
+ printf '%s\n' "$tag" >"$repo/VERSION"
+ git -C "$repo" add -A
+ git -C "$repo" commit -q -m "$tag"
+ git -C "$repo" tag "$tag"
+ mkdir -p "$work/releases/$tag"
+ tar -czf "$work/releases/$tag/burn-$platform.tar.gz" -C "$work/dist" burn
+done
+export BURN_REPO="$repo" BURN_RELEASES="file://$work/releases"
+
+mkdir -p "$BURN_HOME/bin"
+BURNUP="$BURN_HOME/bin/burnup"
+if [ -n "${BURNUP_BIN:-}" ]; then
+ cp "$BURNUP_BIN" "$BURNUP"
+else
+ printf '#!/bin/sh\nexec %s %s "$@"\n' "$burni_exe" "$here/src/main.bn" >"$BURNUP"
+ chmod +x "$BURNUP"
+fi
+
+out="$($BURNUP setup --no-ash 2>&1)"
+expect "$out" "Installed Burn v1.1.0"
+expect "$out" "is installed"
+grep -q "added by burnup" "$HOME/.profile" || fail "setup did not add burn to PATH"
+export PATH="$BURN_HOME/bin:$PATH"
+
+[ "$(burn eval 'print(6 * 7)')" = "42" ] || fail "the burn shim did not run"
+[ "$(printf 'print("hi")\n' >"$work/hi.bn"; burni "$work/hi.bn")" = "hi" ] || fail "the burni shim did not run"
+[ "$($BURNUP default)" = "v1.1.0" ] || fail "latest should be the newest stable release"
+
+out="$($BURNUP install 1.0 2>&1)"
+expect "$out" "Installed Burn v1.0.0"
+out="$($BURNUP list)"
+expect "$out" "v1.0.0"
+expect "$out" "v1.1.0.*(default)"
+
+$BURNUP default 1.0 >/dev/null 2>&1
+[ "$($BURNUP default)" = "v1.0.0" ] || fail "default did not switch"
+expect "$($BURNUP which burnc)" "toolchains/v1.0.0/bin/burnc"
+
+cd "$work"
+burn init example.com/test/proj --no-git >/dev/null
+cd proj
+$BURNUP pin 1.1 >/dev/null 2>&1
+grep -q '^burn = "1.1"$' burn.toml || fail "pin did not write burn.toml: $(cat burn.toml)"
+expect "$($BURNUP which)" "toolchains/v1.1.0/bin/burn"
+expect "$($BURNUP show)" "from $work/proj/burn.toml"
+[ "$(burn run)" = "Hello from proj!" ] || fail "the project did not run with its pinned version"
+cd src
+expect "$($BURNUP which)" "toolchains/v1.1.0/bin/burn"
+cd "$work"
+expect "$($BURNUP which)" "toolchains/v1.0.0/bin/burn"
+
+mkdir -p "$work/other"
+cd "$work/other"
+$BURNUP pin 1.0.0 >/dev/null 2>&1
+[ "$(cat .burn-version)" = "1.0.0" ] || fail "pin outside a project should write .burn-version"
+cd "$work"
+
+[ "$(BURN_TOOLCHAIN=v1.1.0 $BURNUP which)" = "$BURN_HOME/toolchains/v1.1.0/bin/burn" ] || fail "BURN_TOOLCHAIN was ignored"
+expect "$($BURNUP run v1.1.0 burn version)" "Burn "
+
+$BURNUP uninstall v1.1.0 >/dev/null 2>&1
+[ ! -e "$BURN_HOME/toolchains/v1.1.0" ] || fail "uninstall left the toolchain"
+cd "$work/proj"
+out="$(burn run 2>&1)"
+expect "$out" "Missing Burn 1.1"
+expect "$out" "Hello from proj!"
+cd "$work"
+
+if $BURNUP install 9.9 2>"$work/err"; then fail "a missing version was accepted"; fi
+expect "$(cat "$work/err")" "there is no Burn version called"
+expect "$(cat "$work/err")" "v1.1.0"
+expect "$($BURNUP list --remote)" "v2.0.0-beta"
+
+$BURNUP link dev "$dist" >/dev/null 2>&1
+expect "$($BURNUP list)" "dev"
+[ "$($BURNUP run dev burn eval 'print(1)')" = "1" ] || fail "the linked version did not run"
+
+$BURNUP self uninstall >/dev/null 2>&1
+[ ! -e "$BURN_HOME" ] || fail "self uninstall left $BURN_HOME"
+if grep -q "added by burnup" "$HOME/.profile"; then fail "self uninstall left the PATH line"; fi
+
+printf 'burnup end-to-end tests passed\n'
diff --git a/tests/main.bn b/tests/main.bn
new file mode 100644
index 0000000..9374c8e
--- /dev/null
+++ b/tests/main.bn
@@ -0,0 +1,27 @@
+import "github.com/burnlang/burnup/src/paths"
+import "github.com/burnlang/burnup/src/semver"
+import "github.com/burnlang/burnup/src/toolchain"
+import "process"
+import "fs"
+
+var dir = trim(Process.output("mktemp", ["-d"]).out)
+writeFile(dir + "/burn.toml", "[package]\nname = \"github.com/a/b\" # the name\nburn = \"26.1\"\n\n[scripts]\ndev = \"x = y\"\n")
+var keys = readKeys(dir + "/burn.toml")
+assert(keys["package.name"] == "github.com/a/b")
+assert(keys["package.burn"] == "26.1")
+assert(keys["scripts.dev"] == "x = y")
+assert(pinnedIn(dir)?.spec == "26.1")
+writeKeys(dir + "/meta.toml", {"b": "2", "a": "1"})
+assert(readFile(dir + "/meta.toml") == "a = \"1\"\nb = \"2\"\n")
+Files.remove(dir + "/burn.toml")
+writeFile(dir + "/.burn-version", "master\n")
+assert(pinnedIn(dir)?.spec == "master")
+assert(parentDir("/a/b/c") == "/a/b")
+assert(isLatest("") && isLatest("stable") && !isLatest("master"))
+assert(versionMatches("26.1", parseVersion("v26.1.3")))
+assert(!versionMatches("1.0", parseVersion("v1.1.0")))
+assert(versionMatches("26.1", parseVersion("v26.1.0-experimental-1")))
+assert(versionMatches("^1.0", parseVersion("v1.4.0")))
+assert(!versionMatches("master", parseVersion("v1.0.0")))
+Files.remove(dir)
+print("burnup unit tests passed")
]