Repository: Schniz/fnm Branch: master Commit: bfb186034978 Files: 152 Total size: 391.3 KB Directory structure: gitextract_q8q0nzc1/ ├── .changeset/ │ ├── README.md │ ├── brave-timers-move.md │ ├── config.json │ ├── cuddly-cars-ring.md │ └── fair-carrots-greet.md ├── .ci/ │ ├── get_shell_profile.sh │ ├── install.sh │ ├── prepare-static-build.sh │ ├── prepare-version.js │ ├── print-command-docs.js │ ├── record_screen.sh │ ├── recorded_screen_script.sh │ ├── test_installation_script.sh │ └── type-letters.js ├── .gitattributes ├── .github/ │ └── workflows/ │ ├── debug.yml │ ├── installation_script.yml │ ├── release-to-cargo.yml │ ├── release.yml │ └── rust.yml ├── .gitignore ├── .kodiak.toml ├── .node-version ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── benchmarks/ │ ├── basic/ │ │ ├── fnm │ │ └── nvm │ ├── run │ └── run.mjs ├── build.rs ├── docs/ │ ├── commands.md │ ├── configuration.md │ └── nightly.md ├── e2e/ │ ├── __snapshots__/ │ │ ├── aliases.test.ts.snap │ │ ├── basic.test.ts.snap │ │ ├── corepack.test.ts.snap │ │ ├── current.test.ts.snap │ │ ├── env.test.ts.snap │ │ ├── exec.test.ts.snap │ │ ├── existing-installation.test.ts.snap │ │ ├── latest-lts.test.ts.snap │ │ ├── latest.test.ts.snap │ │ ├── log-level.test.ts.snap │ │ ├── multishell.test.ts.snap │ │ ├── nvmrc-lts.test.ts.snap │ │ ├── old-versions.test.ts.snap │ │ ├── uninstall.test.ts.snap │ │ └── use-on-cd.test.ts.snap │ ├── aliases.test.ts │ ├── basic.test.ts │ ├── corepack.test.ts │ ├── current.test.ts │ ├── describe.ts │ ├── env.test.ts │ ├── exec.test.ts │ ├── existing-installation.test.ts │ ├── latest-lts.test.ts │ ├── latest.test.ts │ ├── log-level.test.ts │ ├── multishell.test.ts │ ├── nvmrc-lts.test.ts │ ├── old-versions.test.ts │ ├── shellcode/ │ │ ├── get-stderr.ts │ │ ├── script.ts │ │ ├── shells/ │ │ │ ├── cmdCall.ts │ │ │ ├── cmdEnv.ts │ │ │ ├── expect-command-output.ts │ │ │ ├── output-contains.ts │ │ │ ├── redirect-output.ts │ │ │ ├── sub-shell.ts │ │ │ └── types.ts │ │ ├── shells.ts │ │ ├── test-bin-dir.ts │ │ ├── test-cwd.ts │ │ ├── test-node-version.ts │ │ └── test-tmp-dir.ts │ ├── system-node.test.ts │ ├── uninstall.test.ts │ ├── use-on-cd.test.ts │ └── windows-scoop.test.ts ├── fnm-manifest.rc ├── fnm.manifest ├── jest.config.cjs ├── jest.global-setup.js ├── jest.global-teardown.js ├── package.json ├── renovate.json ├── rust-toolchain.toml ├── site/ │ ├── package.json │ └── vercel.json ├── src/ │ ├── alias.rs │ ├── arch.rs │ ├── archive/ │ │ ├── extract.rs │ │ ├── mod.rs │ │ ├── tar.rs │ │ └── zip.rs │ ├── choose_version_for_user_input.rs │ ├── cli.rs │ ├── commands/ │ │ ├── alias.rs │ │ ├── command.rs │ │ ├── completions.rs │ │ ├── current.rs │ │ ├── default.rs │ │ ├── env.rs │ │ ├── exec.rs │ │ ├── install.rs │ │ ├── ls_local.rs │ │ ├── ls_remote.rs │ │ ├── mod.rs │ │ ├── unalias.rs │ │ ├── uninstall.rs │ │ └── use.rs │ ├── config.rs │ ├── current_version.rs │ ├── default_version.rs │ ├── directories.rs │ ├── directory_portal.rs │ ├── downloader.rs │ ├── fs.rs │ ├── http.rs │ ├── installed_versions.rs │ ├── log_level.rs │ ├── lts.rs │ ├── main.rs │ ├── package_json.rs │ ├── path_ext.rs │ ├── pretty_serde.rs │ ├── progress.rs │ ├── remote_node_index.rs │ ├── shell/ │ │ ├── bash.rs │ │ ├── fish.rs │ │ ├── infer/ │ │ │ ├── mod.rs │ │ │ ├── unix.rs │ │ │ └── windows.rs │ │ ├── mod.rs │ │ ├── powershell.rs │ │ ├── shell.rs │ │ ├── windows_cmd/ │ │ │ ├── cd.cmd │ │ │ └── mod.rs │ │ ├── windows_compat.rs │ │ └── zsh.rs │ ├── system_info.rs │ ├── system_version.rs │ ├── user_version.rs │ ├── user_version_reader.rs │ ├── version.rs │ ├── version_file_strategy.rs │ └── version_files.rs ├── tests/ │ └── proxy-server/ │ └── index.mjs └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .changeset/README.md ================================================ # Changesets Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) ================================================ FILE: .changeset/brave-timers-move.md ================================================ --- "fnm": patch --- support `x64-glibc-217` arch by adding a `--arch x64-glibc-217` to fnm env ================================================ FILE: .changeset/config.json ================================================ { "$schema": "https://unpkg.com/@changesets/config@2.0.0/schema.json", "changelog": ["@changesets/changelog-github", { "repo": "Schniz/fnm" }], "commit": false, "fixed": [], "linked": [], "access": "restricted", "baseBranch": "master", "updateInternalDependencies": "patch", "ignore": [] } ================================================ FILE: .changeset/cuddly-cars-ring.md ================================================ --- "fnm": patch --- prefer explicit shell flags in installer-generated shell setup and fix ARM installer CI platform selection ================================================ FILE: .changeset/fair-carrots-greet.md ================================================ --- "fnm": patch --- Clarify the interactive `fnm use` missing-version prompt by prefixing the message with `fnm` so it is obvious which tool is asking to install Node. ================================================ FILE: .ci/get_shell_profile.sh ================================================ #!/bin/bash case $1 in "fish") echo "$HOME/.config/fish/conf.d/fnm.fish" ;; "zsh") echo "$HOME/.zshrc" ;; "bash") OS="$(uname -s)" if [ "$OS" = "Darwin" ]; then echo "$HOME/.profile" else echo "$HOME/.bashrc" fi ;; *) exit 1 ;; esac ================================================ FILE: .ci/install.sh ================================================ #!/bin/bash set -e RELEASE="latest" OS="$(uname -s)" case "${OS}" in MINGW* | Win*) OS="Windows" ;; esac if [ -d "$HOME/.fnm" ]; then INSTALL_DIR="$HOME/.fnm" elif [ -n "$XDG_DATA_HOME" ]; then INSTALL_DIR="$XDG_DATA_HOME/fnm" elif [ "$OS" = "Darwin" ]; then INSTALL_DIR="$HOME/Library/Application Support/fnm" else INSTALL_DIR="$HOME/.local/share/fnm" fi # Parse Flags parse_args() { while [[ $# -gt 0 ]]; do key="$1" case $key in -d | --install-dir) INSTALL_DIR="$2" shift # past argument shift # past value ;; -s | --skip-shell) SKIP_SHELL="true" shift # past argument ;; --force-install | --force-no-brew) echo "\`--force-install\`: I hope you know what you're doing." >&2 FORCE_INSTALL="true" shift ;; -r | --release) RELEASE="$2" shift # past release argument shift # past release value ;; *) echo "Unrecognized argument $key" exit 1 ;; esac done } set_filename() { if [ "$OS" = "Linux" ]; then # Based on https://stackoverflow.com/a/45125525 case "$(uname -m)" in arm | armv7*) FILENAME="fnm-arm32" ;; aarch* | armv8*) FILENAME="fnm-arm64" ;; *) FILENAME="fnm-linux" esac elif [ "$OS" = "Darwin" ] && [ "$FORCE_INSTALL" = "true" ]; then FILENAME="fnm-macos" USE_HOMEBREW="false" echo "Downloading the latest fnm binary from GitHub..." echo " Pro tip: it's easier to use Homebrew for managing fnm in macOS." echo " Remove the \`--force-no-brew\` so it will be easy to upgrade." elif [ "$OS" = "Darwin" ]; then USE_HOMEBREW="true" echo "Downloading fnm using Homebrew..." elif [ "$OS" = "Windows" ] ; then FILENAME="fnm-windows" echo "Downloading the latest fnm binary from GitHub..." else echo "OS $OS is not supported." echo "If you think that's a bug - please file an issue to https://github.com/Schniz/fnm/issues" exit 1 fi } download_fnm() { if [ "$USE_HOMEBREW" = "true" ]; then brew install fnm INSTALL_DIR="$(brew --prefix fnm)/bin" else if [ "$RELEASE" = "latest" ]; then URL="https://github.com/Schniz/fnm/releases/latest/download/$FILENAME.zip" else URL="https://github.com/Schniz/fnm/releases/download/$RELEASE/$FILENAME.zip" fi DOWNLOAD_DIR=$(mktemp -d) echo "Downloading $URL..." mkdir -p "$INSTALL_DIR" &>/dev/null if ! curl --progress-bar --fail -L "$URL" -o "$DOWNLOAD_DIR/$FILENAME.zip"; then echo "Download failed. Check that the release/filename are correct." exit 1 fi unzip -q "$DOWNLOAD_DIR/$FILENAME.zip" -d "$DOWNLOAD_DIR" if [ -f "$DOWNLOAD_DIR/fnm" ]; then mv "$DOWNLOAD_DIR/fnm" "$INSTALL_DIR/fnm" else mv "$DOWNLOAD_DIR/$FILENAME/fnm" "$INSTALL_DIR/fnm" fi chmod u+x "$INSTALL_DIR/fnm" fi } check_dependencies() { echo "Checking dependencies for the installation script..." echo -n "Checking availability of curl... " if hash curl 2>/dev/null; then echo "OK!" else echo "Missing!" SHOULD_EXIT="true" fi echo -n "Checking availability of unzip... " if hash unzip 2>/dev/null; then echo "OK!" else echo "Missing!" SHOULD_EXIT="true" fi if [ "$USE_HOMEBREW" = "true" ]; then echo -n "Checking availability of Homebrew (brew)... " if hash brew 2>/dev/null; then echo "OK!" else echo "Missing!" SHOULD_EXIT="true" fi fi if [ "$SHOULD_EXIT" = "true" ]; then echo "Not installing fnm due to missing dependencies." exit 1 fi } ensure_containing_dir_exists() { local CONTAINING_DIR CONTAINING_DIR="$(dirname "$1")" if [ ! -d "$CONTAINING_DIR" ]; then echo " >> Creating directory $CONTAINING_DIR" mkdir -p "$CONTAINING_DIR" fi } setup_shell() { CURRENT_SHELL="$(basename "$SHELL")" if [ "$CURRENT_SHELL" = "zsh" ]; then CONF_FILE=${ZDOTDIR:-$HOME}/.zshrc ensure_containing_dir_exists "$CONF_FILE" echo "Installing for Zsh. Appending the following to $CONF_FILE:" { echo '' echo '# fnm' echo 'FNM_PATH="'"$INSTALL_DIR"'"' echo 'if [ -d "$FNM_PATH" ]; then' if [ "$USE_HOMEBREW" != "true" ]; then echo ' export PATH="$FNM_PATH:$PATH"' fi echo ' eval "$(fnm env --shell zsh)"' echo 'fi' } | tee -a "$CONF_FILE" elif [ "$CURRENT_SHELL" = "fish" ]; then CONF_FILE=$HOME/.config/fish/conf.d/fnm.fish ensure_containing_dir_exists "$CONF_FILE" echo "Installing for Fish. Appending the following to $CONF_FILE:" { echo '' echo '# fnm' echo 'set FNM_PATH "'"$INSTALL_DIR"'"' echo 'if [ -d "$FNM_PATH" ]' if [ "$USE_HOMEBREW" != "true" ]; then echo ' set PATH "$FNM_PATH" $PATH' fi echo ' fnm env --shell fish | source' echo 'end' } | tee -a "$CONF_FILE" elif [ "$CURRENT_SHELL" = "bash" ]; then if [ "$OS" = "Darwin" ]; then CONF_FILE=$HOME/.profile else CONF_FILE=$HOME/.bashrc fi ensure_containing_dir_exists "$CONF_FILE" echo "Installing for Bash. Appending the following to $CONF_FILE:" { echo '' echo '# fnm' echo 'FNM_PATH="'"$INSTALL_DIR"'"' echo 'if [ -d "$FNM_PATH" ]; then' if [ "$USE_HOMEBREW" != "true" ]; then echo ' export PATH="$FNM_PATH:$PATH"' fi echo ' eval "$(fnm env --shell bash)"' echo 'fi' } | tee -a "$CONF_FILE" else echo "Could not infer shell type. Please set up manually." exit 1 fi echo "" echo "In order to apply the changes, open a new terminal or run the following command:" echo "" echo " source $CONF_FILE" } parse_args "$@" set_filename check_dependencies download_fnm if [ "$SKIP_SHELL" != "true" ]; then setup_shell fi ================================================ FILE: .ci/prepare-static-build.sh ================================================ sed -i 's@"flags": \[\]@"flags": ["-ccopt", "-static"]@' package.json ================================================ FILE: .ci/prepare-version.js ================================================ #!/usr/bin/env node /// @ts-check import fs from "fs" import cp from "child_process" import cmd from "cmd-ts" import toml from "toml" import assert from "assert" const CARGO_TOML_PATH = new URL("../Cargo.toml", import.meta.url).pathname const command = cmd.command({ name: "prepare-version", description: "Prepare a new fnm version", args: {}, async handler({}) { updateCargoToml(await getPackageVersion()) exec("cargo build --release") exec("pnpm generate-command-docs --binary-path=./target/release/fnm") exec("./.ci/record_screen.sh") }, }) cmd.run(cmd.binary(command), process.argv) ////////////////////// // Helper functions // ////////////////////// /** * @returns {Promise} */ async function getPackageVersion() { const pkgJson = await fs.promises.readFile( new URL("../package.json", import.meta.url), "utf8" ) const version = JSON.parse(pkgJson).version assert(version, "package.json version is not set") return version } function updateCargoToml(nextVersion) { const cargoToml = fs.readFileSync(CARGO_TOML_PATH, "utf8") const cargoTomlContents = toml.parse(cargoToml) const currentVersion = cargoTomlContents.package.version const newToml = cargoToml.replace( `version = "${currentVersion}"`, `version = "${nextVersion}"` ) if (newToml === cargoToml) { console.error("Cargo.toml didn't change, error!") process.exitCode = 1 return } fs.writeFileSync(CARGO_TOML_PATH, newToml, "utf8") return nextVersion } function exec(command, env) { console.log(`$ ${command}`) return cp.execSync(command, { cwd: new URL("..", import.meta.url), stdio: "inherit", env: { ...process.env, ...env }, }) } ================================================ FILE: .ci/print-command-docs.js ================================================ #!/usr/bin/env node /// @ts-check import { execa } from "execa" import fs from "node:fs" import cmd from "cmd-ts" import cmdFs from "cmd-ts/dist/cjs/batteries/fs.js" const FnmBinaryPath = { ...cmdFs.ExistingPath, defaultValue() { const target = new URL("../target/debug/fnm", import.meta.url) if (!fs.existsSync(target)) { throw new Error( "Can't find debug target, please run `cargo build` or provide a specific binary path" ) } return target.pathname }, } const command = cmd.command({ name: "print-command-docs", description: "prints the docs/command.md file with updated contents", args: { checkForDirty: cmd.flag({ long: "check", description: `Check that file was not changed`, }), fnmPath: cmd.option({ long: "binary-path", description: "the fnm binary path", type: FnmBinaryPath, }), }, async handler({ checkForDirty, fnmPath }) { const targetFile = new URL("../docs/commands.md", import.meta.url).pathname await main(targetFile, fnmPath) if (checkForDirty) { const gitStatus = await checkGitStatus(targetFile) if (gitStatus.state === "dirty") { process.exitCode = 1 console.error( "The file has changed. Please re-run `pnpm generate-command-docs`." ) console.error(`hint: The following diff was found:`) console.error() console.error(gitStatus.diff) } } }, }) cmd.run(cmd.binary(command), process.argv).catch((err) => { console.error(err) process.exitCode = process.exitCode || 1 }) /** * @param {string} targetFile * @param {string} fnmPath * @returns {Promise} */ async function main(targetFile, fnmPath) { const stream = fs.createWriteStream(targetFile) const { subcommands, text: mainText } = await getCommandHelp(fnmPath) await write(stream, line(`fnm`, mainText)) for (const subcommand of subcommands) { const { text: subcommandText } = await getCommandHelp(fnmPath, subcommand) await write(stream, "\n" + line(`fnm ${subcommand}`, subcommandText)) } stream.close() await execa(`pnpm`, ["prettier", "--write", targetFile]) } /** * @param {import('stream').Writable} stream * @param {string} content * @returns {Promise} */ function write(stream, content) { return new Promise((resolve, reject) => { stream.write(content, (err) => (err ? reject(err) : resolve())) }) } function line(cmd, text) { const cmdCode = "`" + cmd + "`" const textCode = "```\n" + text + "\n```" return `# ${cmdCode}\n${textCode}` } /** * @param {string} fnmPath * @param {string} [command] * @returns {Promise<{ subcommands: string[], text: string }>} */ async function getCommandHelp(fnmPath, command) { const cmdArg = command ? [command] : [] const result = await run(fnmPath, [...cmdArg, "--help"]) const text = result.stdout const rows = text.split("\n") const headerIndex = rows.findIndex((x) => x.includes("Commands:")) /** @type {string[]} */ const subcommands = [] if (!command) { for (const row of rows.slice( headerIndex + 1, rows.indexOf("", headerIndex + 1) )) { const [, word] = row.split(/\s+/) if (word && word[0].toLowerCase() === word[0]) { subcommands.push(word) } } } return { subcommands, text, } } /** * @param {string[]} args * @returns {import('execa').ExecaChildProcess} */ function run(fnmPath, args) { return execa(fnmPath, args, { reject: false, stdout: "pipe", stderr: "pipe", }) } /** * @param {string} targetFile * @returns {Promise<{ state: "dirty", diff: string } | { state: "clean" }>} */ async function checkGitStatus(targetFile) { const { stdout, exitCode } = await execa( `git`, ["diff", "--color", "--exit-code", targetFile], { reject: false, } ) if (exitCode === 0) { return { state: "clean" } } return { state: "dirty", diff: stdout } } ================================================ FILE: .ci/record_screen.sh ================================================ #!/bin/bash DIRECTORY="$(dirname "$0")" function setup_binary() { TEMP_DIR="/tmp/fnm-$(date '+%s')" mkdir "$TEMP_DIR" cp ./target/release/fnm "$TEMP_DIR/fnm" export PATH=$TEMP_DIR:$PATH export FNM_DIR=$TEMP_DIR/.fnm # First run of the binary might be slower due to anti-virus software echo "Using $(which fnm)" echo " with version $(fnm --version)" } setup_binary RECORDING_PATH=$DIRECTORY/screen_recording (rm -rf "$RECORDING_PATH" &> /dev/null || true) asciinema rec \ --command "$DIRECTORY/recorded_screen_script.sh" \ --cols 70 \ --rows 17 \ "$RECORDING_PATH" sed "s@$TEMP_DIR@~@g" "$RECORDING_PATH" | \ svg-term \ --window \ --out "docs/fnm.svg" \ --height=17 \ --width=70 ================================================ FILE: .ci/recorded_screen_script.sh ================================================ #!/bin/bash set -e export PATH=$PATH_ADDITION:$PATH GAL_PROMPT_PREFIX="\e[34m✡\e[m " function type() { printf $GAL_PROMPT_PREFIX echo -n " " echo $* | node .ci/type-letters.js } type 'eval "$(fnm env)"' eval "$(fnm env)" type 'fnm --version' fnm --version type 'cat .node-version' cat .node-version type 'fnm install' fnm install type 'fnm use' fnm use type 'node -v' node -v sleep 2 echo "" ================================================ FILE: .ci/test_installation_script.sh ================================================ #!/bin/bash set -e DIRECTORY="$(dirname "$0")" SHELL_TO_RUN="$1" PROFILE_FILE="$("$DIRECTORY/get_shell_profile.sh" "$SHELL_TO_RUN")" ls -lah ~ echo "---" echo "Profile is $PROFILE_FILE" echo "---" cat "$PROFILE_FILE" echo "---" echo "PATH=$PATH" echo "---" $SHELL_TO_RUN -c " . $PROFILE_FILE fnm --version " $SHELL_TO_RUN -c " . $PROFILE_FILE fnm install 12.5.0 fnm ls | grep 12.5.0 echo 'fnm ls worked.' " $SHELL_TO_RUN -c " . $PROFILE_FILE fnm use 12.5.0 node --version | grep 12.5.0 echo 'node --version worked.' " ================================================ FILE: .ci/type-letters.js ================================================ (async () => { for await (const chunk of process.stdin) { const letters = chunk.toString("utf8").split(""); for (const letter of letters) { process.stdout.write(letter); await sleep(Math.random() * 100 + 20); } } })(); function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } ================================================ FILE: .gitattributes ================================================ *__Fish.snap linguist-language=fish *__Zsh.snap linguist-language=Shell *__Bash.snap linguist-language=Shell *__PowerShell.snap linguist-language=PowerShell *__WinCmd.snap linguist-language=Batchfile ================================================ FILE: .github/workflows/debug.yml ================================================ name: "debug" on: workflow_dispatch: concurrency: group: debug cancel-in-progress: true jobs: e2e_windows_debug: runs-on: windows-latest name: "e2e/windows/debug" steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.inputs.commit_hash }} - name: Download artifact id: download-artifact uses: dawidd6/action-download-artifact@v6 with: workflow: rust.yml workflow_conclusion: "" branch: ${{ env.GITHUB_REF }} name: "fnm-windows" path: "target/release" if_no_artifact_found: ignore - uses: hecrj/setup-rust-action@v1 if: steps.download-artifact.outputs.artifact-found == false with: rust-version: stable - uses: Swatinem/rust-cache@v2 if: steps.download-artifact.outputs.artifact-found == false - name: Build release binary if: steps.download-artifact.outputs.artifact-found == false run: cargo build --release env: RUSTFLAGS: "-C target-feature=+crt-static" - uses: pnpm/action-setup@v4.0.0 with: run_install: false - uses: actions/setup-node@v4 with: node-version: 16.x cache: 'pnpm' - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - run: pnpm install - name: 🐛 Debug Build if: always() uses: mxschmitt/action-tmate@v3 with: limit-access-to-actor: true ================================================ FILE: .github/workflows/installation_script.yml ================================================ name: Installation script on: pull_request: paths: - .ci/install.sh push: branches: - master paths: - .ci/install.sh jobs: test_against_latest_release_arm: strategy: matrix: include: - docker_image: arm64v8/ubuntu docker_platform: linux/arm64/v8 - docker_image: arm32v7/ubuntu docker_platform: linux/arm/v7 name: Test against latest release (ARM) runs-on: ubuntu-latest steps: - name: Set up QEMU id: qemu uses: docker/setup-qemu-action@v3 - uses: actions/checkout@v4 - name: Run installation script in Docker run: | docker run --rm --platform ${{ matrix.docker_platform }} -v $(pwd):$(pwd) -e "RUST_LOG=fnm=debug" --workdir $(pwd) ${{matrix.docker_image}} bash -c ' set -e apt update && apt install -y unzip curl libatomic1 echo "-------------------------------------" echo "Installing for CPU arch: $(uname -m)" bash ./.ci/install.sh echo "fnm --version" ~/.local/share/fnm/fnm --version echo "eval fnm env" eval "$(~/.local/share/fnm/fnm env)" echo "fnm install" ~/.local/share/fnm/fnm install 12 echo "node -v" ~/.local/share/fnm/fnm exec --using=12 -- node -v ' test_against_latest_release: name: Test against latest release strategy: matrix: shell: [fish, zsh, bash] setup: - os: ubuntu script_arguments: "" - os: macos script_arguments: "" - os: macos script_arguments: "--force-no-brew" runs-on: ${{ matrix.setup.os }}-latest steps: - uses: actions/checkout@v4 - run: "sudo apt-get install -y ${{ matrix.shell }}" name: Install ${{matrix.shell}} using apt-get if: matrix.setup.os == 'ubuntu' - run: "brew update && brew install ${{ matrix.shell }}" name: Update formulae and install ${{matrix.shell}} using Homebrew if: matrix.setup.os == 'macos' - run: | if [ -f ~/.bashrc ]; then cp ~/.bashrc ~/.bashrc.bak echo 'echo hello world' > ~/.bashrc echo '. ~/.bashrc.bak' >> ~/.bashrc fi if [ -f ~/.zshrc ]; then echo 'echo hello world' > ~/.zshrc echo '. ~/.zshrc.bak' >> ~/.zshrc fi name: reset shell profiles - run: "env SHELL=$(which ${{ matrix.shell }}) bash ./.ci/install.sh ${{ matrix.setup.script_arguments }}" name: Run the installation script - run: ./.ci/test_installation_script.sh ${{ matrix.shell }} name: "Test installation script" ================================================ FILE: .github/workflows/release-to-cargo.yml ================================================ name: release to cargo on: workflow_dispatch: push: tags: ['*'] jobs: publish_to_crates_io: runs-on: ubuntu-latest name: Publish to crates.io steps: # set up - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v1 with: rust-version: stable - uses: Swatinem/rust-cache@v2 - uses: pnpm/action-setup@v4.0.0 with: run_install: false - name: Publish to crates.io run: cargo publish env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} TERM: xterm ================================================ FILE: .github/workflows/release.yml ================================================ name: release on: push: branches: - master - main concurrency: ${{ github.workflow }}-${{ github.ref }} jobs: create_pull_request: runs-on: ubuntu-latest steps: # set up - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v1 with: rust-version: stable - uses: Swatinem/rust-cache@v2 - uses: pnpm/action-setup@v4.0.0 with: run_install: false # pnpm - uses: actions/setup-node@v4 with: node-version: 20.x cache: "pnpm" - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - name: Install Asciinema run: | pipx install asciinema - name: Install Node.js project dependencies run: pnpm install - name: Create Release Pull Request uses: changesets/action@v1 with: version: "pnpm version:prepare" env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} TERM: xterm ================================================ FILE: .github/workflows/rust.yml ================================================ name: Rust on: pull_request: push: branches: - master concurrency: group: ci-${{ github.head_ref }} cancel-in-progress: true env: RUST_VERSION: "1.88" jobs: fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} - uses: Swatinem/rust-cache@v2 - name: cargo fmt run: cargo fmt -- --check clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} - uses: Swatinem/rust-cache@v2 - name: cargo clippy run: cargo clippy -- -D warnings unit_tests: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macOS-latest, windows-latest] steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} - uses: Swatinem/rust-cache@v2 - name: Run tests run: cargo test build_release: runs-on: windows-latest name: "Release build for Windows" steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} - uses: Swatinem/rust-cache@v2 - name: Build release binary run: cargo build --release env: RUSTFLAGS: "-C target-feature=+crt-static" - uses: actions/upload-artifact@v4 with: name: fnm-windows path: target/release/fnm.exe build_macos_release: runs-on: macos-latest name: "Release build for macOS" steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} targets: x86_64-apple-darwin,aarch64-apple-darwin - uses: Swatinem/rust-cache@v2 - name: Build release binary run: | cargo build --release --target x86_64-apple-darwin strip target/x86_64-apple-darwin/release/fnm cargo build --release --target aarch64-apple-darwin strip target/aarch64-apple-darwin/release/fnm mkdir -p target/release # create a universal binary lipo -create \ target/x86_64-apple-darwin/release/fnm \ target/aarch64-apple-darwin/release/fnm \ -output target/release/fnm env: LZMA_API_STATIC: "true" - name: Strip binary from debug symbols run: strip target/release/fnm - name: List dynamically linked libraries run: otool -L target/release/fnm - uses: actions/upload-artifact@v4 with: name: fnm-macos path: target/release/fnm e2e_macos: runs-on: macos-latest needs: [build_macos_release] name: "e2e/macos" steps: - uses: actions/checkout@v4 - name: install necessary shells run: brew install fish zsh bash - uses: actions/download-artifact@v4 with: name: fnm-macos path: target/release - name: mark binary as executable run: chmod +x target/release/fnm - uses: pnpm/action-setup@v4.0.0 with: run_install: false - uses: actions/setup-node@v4 with: node-version: 18.x cache: "pnpm" - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - run: pnpm install - run: pnpm test env: FNM_TARGET_NAME: "release" FORCE_COLOR: "1" e2e_windows: runs-on: windows-latest needs: [build_release] name: "e2e/windows" steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 with: name: fnm-windows path: target/release - uses: MinoruSekine/setup-scoop@v4 - uses: pnpm/action-setup@v4.0.0 with: run_install: false - uses: actions/setup-node@v4 with: node-version: 18.x cache: "pnpm" - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - run: pnpm install - run: pnpm test env: FNM_TARGET_NAME: "release" FORCE_COLOR: "1" # e2e_windows_debug: # runs-on: windows-latest # name: "e2e/windows/debug" # environment: Debug # needs: [e2e_windows] # if: contains(join(needs.*.result, ','), 'failure') # steps: # - uses: actions/checkout@v3 # - uses: actions/download-artifact@v3 # with: # name: fnm-windows # path: target/release # - uses: pnpm/action-setup@v2.2.2 # with: # run_install: false # - uses: actions/setup-node@v3 # with: # node-version: 18.x # cache: 'pnpm' # - name: Get pnpm store directory # id: pnpm-cache # run: | # echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" # - uses: actions/cache@v3 # name: Setup pnpm cache # with: # path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} # key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} # restore-keys: | # ${{ runner.os }}-pnpm-store- # - run: pnpm install # - name: 🐛 Debug Build # uses: mxschmitt/action-tmate@v3 e2e_linux: runs-on: ubuntu-latest needs: [build_static_linux_binary] name: "e2e/linux" steps: - uses: actions/checkout@v4 - name: install necessary shells run: sudo apt-get update && sudo apt-get install -y fish zsh bash - uses: actions/download-artifact@v4 with: name: fnm-linux path: target/release - name: mark binary as executable run: chmod +x target/release/fnm - uses: pnpm/action-setup@v4.0.0 with: run_install: false - uses: actions/setup-node@v4 with: node-version: 18.x cache: "pnpm" - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - run: pnpm install - run: pnpm test env: FNM_TARGET_NAME: "release" FORCE_COLOR: "1" build_static_linux_binary: name: "Build static Linux binary" runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} targets: x86_64-unknown-linux-musl - uses: Swatinem/rust-cache@v2 with: key: static-linux-binary - name: Install musl tools run: | sudo apt-get update sudo apt-get install -y --no-install-recommends musl-tools - name: Build release binary run: cargo build --release --target x86_64-unknown-linux-musl - name: Strip binary from debug symbols run: strip target/x86_64-unknown-linux-musl/release/fnm - uses: actions/upload-artifact@v4 with: name: fnm-linux path: target/x86_64-unknown-linux-musl/release/fnm build_static_arm_binary: name: "Build ARM binary" strategy: matrix: include: - arch: arm64 rust_target: aarch64-unknown-linux-musl docker_image: arm64v8/ubuntu docker_platform: aarch64 - arch: arm32 rust_target: armv7-unknown-linux-gnueabihf docker_image: arm32v7/ubuntu docker_platform: armv7 runs-on: ubuntu-latest env: RUST_TARGET: ${{ matrix.rust_target }} steps: - uses: actions/checkout@v4 - name: Set up QEMU id: qemu uses: docker/setup-qemu-action@v3 - uses: hecrj/setup-rust-action@v2 with: rust-version: ${{env.RUST_VERSION}} - uses: Swatinem/rust-cache@v2 with: key: arm-binary-${{ matrix.arch }} - name: "Download `cross` crate" run: cargo install cross - name: "Build release" run: cross build --target $RUST_TARGET --release - uses: uraimo/run-on-arch-action@v2.1.2 name: Sanity test with: arch: ${{matrix.docker_platform}} distro: ubuntu18.04 # Not required, but speeds up builds by storing container images in # a GitHub package registry. githubToken: ${{ github.token }} env: | RUST_LOG: fnm=debug dockerRunArgs: | --volume "${PWD}/target/${{matrix.rust_target}}/release:/artifacts" # Set an output parameter `uname` for use in subsequent steps run: | echo "Hello from $(uname -a)" /artifacts/fnm --version echo "fnm install 12.0.0" /artifacts/fnm install 12.0.0 echo "fnm exec --using=12 -- node --version" /artifacts/fnm exec --using=12 -- node --version - uses: actions/upload-artifact@v4 with: name: fnm-${{ matrix.arch }} path: target/${{ env.RUST_TARGET }}/release/fnm ensure_commands_markdown_is_up_to_date: runs-on: ubuntu-latest name: Ensure command docs are up-to-date needs: [build_static_linux_binary] steps: - uses: actions/checkout@v4 - name: install necessary shells run: sudo apt-get update && sudo apt-get install -y fish zsh bash - uses: actions/download-artifact@v4 with: name: fnm-linux path: target/release - name: mark binary as executable run: chmod +x target/release/fnm - name: install fnm as binary run: | sudo install target/release/fnm /bin fnm --version - uses: pnpm/action-setup@v4.0.0 with: run_install: false - uses: actions/setup-node@v4 with: node-version: 18.x cache: "pnpm" - name: Get pnpm store directory id: pnpm-cache run: | echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" - uses: actions/cache@v4 name: Setup pnpm cache with: path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} restore-keys: | ${{ runner.os }}-pnpm-store- - run: pnpm install - name: Generate command markdown run: | pnpm run generate-command-docs --check --binary-path=$(which fnm) # TODO: use bnz # run_e2e_benchmarks: # runs-on: ubuntu-latest # name: bench/linux # needs: [build_static_linux_binary] # permissions: # contents: write # pull-requests: write # steps: # - name: install necessary shells # run: sudo apt-get update && sudo apt-get install -y fish zsh bash hyperfine # - uses: actions/checkout@v3 # - uses: actions/download-artifact@v3 # with: # name: fnm-linux # path: target/release # - name: mark binary as executable # run: chmod +x target/release/fnm # - name: install fnm as binary # run: | # sudo install target/release/fnm /bin # fnm --version # - uses: pnpm/action-setup@v2.2.4 # with: # run_install: false # - uses: actions/setup-node@v3 # with: # node-version: 18.x # cache: "pnpm" # - name: Get pnpm store directory # id: pnpm-cache # run: | # echo "::set-output name=pnpm_cache_dir::$(pnpm store path)" # - uses: actions/cache@v3 # name: Setup pnpm cache # with: # path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }} # key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} # restore-keys: | # ${{ runner.os }}-pnpm-store- # - run: pnpm install # - name: Run benchmarks # env: # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # SHOULD_STORE: ${{ toJson(!github.event.pull_request) }} # id: benchmark # run: | # delimiter="$(openssl rand -hex 8)" # echo "markdown<<${delimiter}" >> "${GITHUB_OUTPUT}" # node benchmarks/run.mjs --store=$SHOULD_STORE >> "${GITHUB_OUTPUT}" # echo "${delimiter}" >> "${GITHUB_OUTPUT}" # - name: Create a PR comment # if: ${{ github.event.pull_request }} # uses: thollander/actions-comment-pull-request@v2 # with: # message: | # ## Linux Benchmarks for ${{ github.event.pull_request.head.sha }} # ${{ steps.benchmark.outputs.markdown }} # comment_tag: "benchy comment" # # - name: Create a commit comment # if: ${{ !github.event.pull_request }} # uses: peter-evans/commit-comment@v2 # with: # body: | # ## Linux Benchmarks # ${{ steps.benchmark.outputs.markdown }} ================================================ FILE: .gitignore ================================================ node_modules/ .ci/screen_recording /benchmarks/results /target **/*.rs.bk feature_tests/.tmp *.log /site/public .vercel .proxy ================================================ FILE: .kodiak.toml ================================================ version = 1 ================================================ FILE: .node-version ================================================ 20.14.0 ================================================ FILE: CHANGELOG.md ================================================ ## 1.31.0 (2022-02-16) ## 1.39.0 ### Minor Changes - [#1516](https://github.com/Schniz/fnm/pull/1516) [`10c68cb`](https://github.com/Schniz/fnm/commit/10c68cb6630be811799afdccf212a399e08bef99) Thanks [@Schniz](https://github.com/Schniz)! - Reduce shell startup overhead for `env --use-on-cd` by applying the initial version during `fnm env`, instead of requiring an immediate extra `fnm use` subprocess from shell hook output. - [#1435](https://github.com/Schniz/fnm/pull/1435) [`1ebc90d`](https://github.com/Schniz/fnm/commit/1ebc90decf58c2176dcbd4f8ac00ecb3adb1de12) Thanks [@SunsetTechuila](https://github.com/SunsetTechuila)! - add `use` flag to the `install` command ### Patch Changes - [#1268](https://github.com/Schniz/fnm/pull/1268) [`ddab191`](https://github.com/Schniz/fnm/commit/ddab1911dc33a24aeec9d2b8139df1916c518d64) Thanks [@isaacl](https://github.com/isaacl)! - Make `fnm default` with no trailing positional argument to return the default version - [#1517](https://github.com/Schniz/fnm/pull/1517) [`d3747af`](https://github.com/Schniz/fnm/commit/d3747affd604223c752171c14944bd5773096b09) Thanks [@Schniz](https://github.com/Schniz)! - Improve `--use-on-cd` shell hook robustness by de-duplicating the zsh hook on re-source and fixing Windows CMD hook behavior for paths with spaces and drive changes. - [#1441](https://github.com/Schniz/fnm/pull/1441) [`bc4d19a`](https://github.com/Schniz/fnm/commit/bc4d19a481c11b4182f51683f03a8d366f1208d2) Thanks [@Schniz](https://github.com/Schniz)! - bump Rust toolchain to 1.88 ## 1.38.1 ### Patch Changes - [#1326](https://github.com/Schniz/fnm/pull/1326) [`172fb0a`](https://github.com/Schniz/fnm/commit/172fb0adc9d9d78b4763be087769388802c5345d) Thanks [@Schniz](https://github.com/Schniz)! - fix --use-on-cd failing with newly released default of --resolve-engines when `engines` key didn't exist ## 1.38.0 ### Minor Changes - [#1265](https://github.com/Schniz/fnm/pull/1265) [`186e4bb`](https://github.com/Schniz/fnm/commit/186e4bbd9204d7658a4f9923955281687a01e8c3) Thanks [@Schniz](https://github.com/Schniz)! - enable `--resolve-engines` by default. out of experimental phase. to disable it, add a `--resolve-engines=false` flag, and make sure to open an issue describing _why_. It might feel like a breaking change but .nvmrc and .node-version have precedence so it should not. I am all in favor of better experience and I believe supporting engines.node is a good direction. ### Patch Changes - [#1310](https://github.com/Schniz/fnm/pull/1310) [`9273981`](https://github.com/Schniz/fnm/commit/9273981dc0d78124181927fae8746b5a61901c45) Thanks [@Schniz](https://github.com/Schniz)! - make github releases of macos to be a universal macos executable (both m1 and x64) as github changed the workers to be m1 - [#1277](https://github.com/Schniz/fnm/pull/1277) [`12cf977`](https://github.com/Schniz/fnm/commit/12cf977beb8581000ea84d7b8d1636dc3ae25db3) Thanks [@deanshub](https://github.com/deanshub)! - Having install and uninstall aliases - [#1318](https://github.com/Schniz/fnm/pull/1318) [`65f7a22`](https://github.com/Schniz/fnm/commit/65f7a22822ce03f07972fe175d08cc60112856f8) Thanks [@Schniz](https://github.com/Schniz)! - better error handling for malformed json ## 1.37.2 ### Patch Changes - [#1264](https://github.com/Schniz/fnm/pull/1264) [`364d2a9`](https://github.com/Schniz/fnm/commit/364d2a939c684fede25c43c6a9c14b7c4c6e3fc5) Thanks [@Schniz](https://github.com/Schniz)! - fix: allow to type powershell and power-shell as shell type inputs - [#1195](https://github.com/Schniz/fnm/pull/1195) [`74d7c33`](https://github.com/Schniz/fnm/commit/74d7c33da9f5ac53a42633012d775015eb774bcb) Thanks [@mattmess1221](https://github.com/mattmess1221)! - When downloading from node-dist, Fallback to .tar.gz download when the .tar.xz download fails - [#1259](https://github.com/Schniz/fnm/pull/1259) [`1000914`](https://github.com/Schniz/fnm/commit/10009143460e161b76350eb738652f332e8a893c) Thanks [@skirsten](https://github.com/skirsten)! - Fix `--resolve-engines` in combination with `--use-on-cd` - [#1248](https://github.com/Schniz/fnm/pull/1248) [`e03d345`](https://github.com/Schniz/fnm/commit/e03d345e9f485c4ab0183a3a542bcba20525fff4) Thanks [@bburns](https://github.com/bburns)! - docs: add link for windows terminal startup script configuration - [#1184](https://github.com/Schniz/fnm/pull/1184) [`fefdf69`](https://github.com/Schniz/fnm/commit/fefdf69870ddaec0ba59b103aef730dd03e56e4a) Thanks [@julescubtree](https://github.com/julescubtree)! - fix panic when list-remote --filter --latest has no results - [#1255](https://github.com/Schniz/fnm/pull/1255) [`71c1c9a`](https://github.com/Schniz/fnm/commit/71c1c9a9998f7fd0dc512de6ead9244f03fa532d) Thanks [@stefanboca](https://github.com/stefanboca)! - set aliases during install, even if corepack is enabled - [#1204](https://github.com/Schniz/fnm/pull/1204) [`19bffe5`](https://github.com/Schniz/fnm/commit/19bffe5af6ee1d624095c94f5ec55660fe69ac3b) Thanks [@JLarky](https://github.com/JLarky)! - Document how to use nightly builds - [#1218](https://github.com/Schniz/fnm/pull/1218) [`345adaf`](https://github.com/Schniz/fnm/commit/345adafb856e2e0ba8feb8acf487a4669cea4055) Thanks [@Schniz](https://github.com/Schniz)! - internal: retry download in case of error in test proxy - [#1226](https://github.com/Schniz/fnm/pull/1226) [`8e2d37d`](https://github.com/Schniz/fnm/commit/8e2d37d858b15d965d9644b27f5c111478cc59f2) Thanks [@mo8it](https://github.com/mo8it)! - performance optimizations, especially for `fnm env` - [#1223](https://github.com/Schniz/fnm/pull/1223) [`2b211ef`](https://github.com/Schniz/fnm/commit/2b211ef64a7eb2ff5fe7ac017d1f963db522b6cf) Thanks [@mo8it](https://github.com/mo8it)! - Allow reading non-unicode paths from environment variables ## 1.37.1 ### Patch Changes - [#1164](https://github.com/Schniz/fnm/pull/1164) [`318f86d`](https://github.com/Schniz/fnm/commit/318f86d72938166cb2b3195cae37826f827b6c08) Thanks [@Schniz](https://github.com/Schniz)! - windows: fix shell inference in powershell when using scoop's shims ## 1.37.0 ### Minor Changes - [#1143](https://github.com/Schniz/fnm/pull/1143) [`f76a001`](https://github.com/Schniz/fnm/commit/f76a0011f7a613bb818e47acd224b7de48c5a81f) Thanks [@Schniz](https://github.com/Schniz)! - use XDG conventions in MacOS directories by default ### Patch Changes - [#1148](https://github.com/Schniz/fnm/pull/1148) [`0b530cc`](https://github.com/Schniz/fnm/commit/0b530cc257e33e9801804b73ed831a1f28489b57) Thanks [@Schniz](https://github.com/Schniz)! - fix ordering in ls-remote - [#1133](https://github.com/Schniz/fnm/pull/1133) [`a1afe84`](https://github.com/Schniz/fnm/commit/a1afe8436afb29960b71e14e221441398f6a48ca) Thanks [@Schniz](https://github.com/Schniz)! - upgrade all dependencies & maintain lockfile ## 1.36.0 ### Minor Changes - [#1063](https://github.com/Schniz/fnm/pull/1063) [`121128f`](https://github.com/Schniz/fnm/commit/121128f42bc27583c2cf9a77b14f60f456af4a82) Thanks [@ryanccn](https://github.com/ryanccn)! - feat: add remote version sorting and filtering - [#896](https://github.com/Schniz/fnm/pull/896) [`7b47b3e`](https://github.com/Schniz/fnm/commit/7b47b3ef0a741fe40a39efaa5eca6945b2e11c59) Thanks [@pedrofialho](https://github.com/pedrofialho)! - `fnm install latest` will now tag the `latest` alias - [#1028](https://github.com/Schniz/fnm/pull/1028) [`66efc5b`](https://github.com/Schniz/fnm/commit/66efc5b90c71f2f24592dbf8d7e28c9f53bcf5f9) Thanks [@eblocha](https://github.com/eblocha)! - Show a progress bar when downloading and extracting node ### Patch Changes - [#1014](https://github.com/Schniz/fnm/pull/1014) [`6be23c8`](https://github.com/Schniz/fnm/commit/6be23c868f5ddb2a4508a1f302c345298401d674) Thanks [@tottoto](https://github.com/tottoto)! - Disable unused chrono features (#1014) - [#1050](https://github.com/Schniz/fnm/pull/1050) [`d6c132a`](https://github.com/Schniz/fnm/commit/d6c132adfd1c29c48acb0b9de42538146e23cf18) Thanks [@JakeHandsome](https://github.com/JakeHandsome)! - Fix `cd /D` on windows with `--use-on-cd` - [#1109](https://github.com/Schniz/fnm/pull/1109) [`8f3acbb`](https://github.com/Schniz/fnm/commit/8f3acbb8ee4991b838ce3fe146d62864aaa290b9) Thanks [@Vinfall](https://github.com/Vinfall)! - support `x64-musl` arch by adding a `--arch x64-musl` to fnm env - [#1125](https://github.com/Schniz/fnm/pull/1125) [`d9af62f`](https://github.com/Schniz/fnm/commit/d9af62ff432e57398efdd812e218f3fb390c5243) Thanks [@Schniz](https://github.com/Schniz)! - make nicer styling in progress bar (add newline, make it unicode) - [#1058](https://github.com/Schniz/fnm/pull/1058) [`734df47`](https://github.com/Schniz/fnm/commit/734df47795c3b71d104ec9638034447cc4ef47cc) Thanks [@aquacash5](https://github.com/aquacash5)! - fix: return default version if canonicalize fails - [#1066](https://github.com/Schniz/fnm/pull/1066) [`9ff98da`](https://github.com/Schniz/fnm/commit/9ff98da93c69013274322c3a63dfdb1beaf73875) Thanks [@floh1695](https://github.com/floh1695)! - Fixes a bug when running `eval $(fnm env)` in sh when there a spaces in the $PATH ## 1.35.1 ### Patch Changes - [#1010](https://github.com/Schniz/fnm/pull/1010) [`b185446`](https://github.com/Schniz/fnm/commit/b185446cfa08d4d6e2552db53937762a3c38d4db) Thanks [@quixoten](https://github.com/quixoten)! - fix: panic on `fnm completions` ## 1.35.0 ### Minor Changes - [#839](https://github.com/Schniz/fnm/pull/839) [`97be792`](https://github.com/Schniz/fnm/commit/97be792a4410d8f121e03a1f81f60c48cbfdee2c) Thanks [@amitdahan](https://github.com/amitdahan)! - Support resolving `engines.node` field via experimental `--resolve-engines` flag ### Patch Changes - [#991](https://github.com/Schniz/fnm/pull/991) [`b19eb29`](https://github.com/Schniz/fnm/commit/b19eb29b26323f0b9fb427d3d9271c9cc13a58f8) Thanks [@amitdahan](https://github.com/amitdahan)! - Bump Clap 3 -> 4 ## 1.34.0 ### Minor Changes - Add --corepack-enabled flag for automatically enabling corepack on fnm install ([#960](https://github.com/Schniz/fnm/pull/960)) ### Patch Changes - modernize tty check (#973 by @tottoto) ([`48b2611`](https://github.com/Schniz/fnm/commit/48b2611e4b1c205f07dcbd50f2fff436becb77c1)) - use cygwinpath to make the path posix-like on Windows Bash usage ([#960](https://github.com/Schniz/fnm/pull/960)) - capitalize "n" to show default (#963 by @Joshuahuahua) ([`48b2611`](https://github.com/Schniz/fnm/commit/48b2611e4b1c205f07dcbd50f2fff436becb77c1)) ## 1.33.1 ### Patch Changes - remove upx compression from arm binaries because it fails to build on latest rust ([#875](https://github.com/Schniz/fnm/pull/875)) ## 1.33.0 ### Minor Changes - Replace `semver` with `node_semver` ([#816](https://github.com/Schniz/fnm/pull/816)) - support `fnm install --latest` to install the latest Node.js version ([#859](https://github.com/Schniz/fnm/pull/859)) ## 1.32.0 ### Minor Changes - Add `--json` to `fnm env` to output the env vars as JSON ([#800](https://github.com/Schniz/fnm/pull/800)) ### Patch Changes - This updates the Changesets configurations. ([#783](https://github.com/Schniz/fnm/pull/783)) - fix test: Use correct PATH for npm install test ([#768](https://github.com/Schniz/fnm/pull/768)) - Make installation script respect `$XDG_DATA_HOME` ([#614](https://github.com/Schniz/fnm/pull/614)) ## 1.31.1 ### Patch Changes - 6e6bdd8: Add changesets #### Bugfix 🐛 - [#671](https://github.com/Schniz/fnm/pull/671) fix native-creds errors (using the unpublished version of reqwest) ([@Schniz](https://github.com/Schniz)) - [#663](https://github.com/Schniz/fnm/pull/663) remove .unwrap() and .expect() in shell code ([@Schniz](https://github.com/Schniz)) - [#656](https://github.com/Schniz/fnm/pull/656) Remove unwrap in fnm env, make error more readable ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.30.1 (2022-01-30) #### Bugfix 🐛 - [#652](https://github.com/Schniz/fnm/pull/652) Fix `fnm completions` ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.30.0 (2022-01-30) #### Bugfix 🐛 - [#625](https://github.com/Schniz/fnm/pull/625) Revert from using sysinfo, but only on Unix machines ([@Schniz](https://github.com/Schniz)) - [#638](https://github.com/Schniz/fnm/pull/638) Use local cache directory instead of temp directory for symlinks ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#617](https://github.com/Schniz/fnm/pull/617) fix(deps): update rust crate clap to v3 ([@renovate[bot]](https://github.com/apps/renovate)) - [#630](https://github.com/Schniz/fnm/pull/630) Replace `snafu` with `thiserror` ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#637](https://github.com/Schniz/fnm/pull/637) [Documentation] Adds Additional info regarding .node-version ([@uchihamalolan](https://github.com/uchihamalolan)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Malolan B ([@uchihamalolan](https://github.com/uchihamalolan)) ## v1.29.2 (2022-01-06) #### Bugfix 🐛 - [#626](https://github.com/Schniz/fnm/pull/626) Create the multishells directory if it is missing ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#598](https://github.com/Schniz/fnm/pull/598) Update README.md file emoji ([@lorensr](https://github.com/lorensr)) - [#616](https://github.com/Schniz/fnm/pull/616) Use on cd by default ([@matthieubosquet](https://github.com/matthieubosquet)) #### Committers: 3 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Loren ☺️ ([@lorensr](https://github.com/lorensr)) - Matthieu Bosquet ([@matthieubosquet](https://github.com/matthieubosquet)) ## v1.29.1 (2021-12-28) #### Bugfix 🐛 - [#613](https://github.com/Schniz/fnm/pull/613) Don't warn on `~/.fnm` yet ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.29.0 (2021-12-28) #### New Feature 🎉 - [#607](https://github.com/Schniz/fnm/pull/607) Allow recursive version lookups ([@Schniz](https://github.com/Schniz)) - [#416](https://github.com/Schniz/fnm/pull/416) Respect \$XDG_DATA_HOME ([@samhh](https://github.com/samhh)) #### Bugfix 🐛 - [#603](https://github.com/Schniz/fnm/pull/603) (re)Include feature for (native) certificates ([@pfiaux](https://github.com/pfiaux)) - [#605](https://github.com/Schniz/fnm/pull/605) Add a user-agent header ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#606](https://github.com/Schniz/fnm/pull/606) Migrate to Rust 2021 edition ([@Schniz](https://github.com/Schniz)) #### Committers: 3 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Patrick Fiaux ([@pfiaux](https://github.com/pfiaux)) - Sam A. Horvath-Hunt ([@samhh](https://github.com/samhh)) ## v1.28.2 (2021-12-05) #### Bugfix 🐛 - [#586](https://github.com/Schniz/fnm/pull/586) Revert the change to ureq ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#584](https://github.com/Schniz/fnm/pull/584) Add warning to symlink creation ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.28.1 (2021-11-17) #### Bugfix 🐛 - [#576](https://github.com/Schniz/fnm/pull/576) First fix for slowess in fnm env ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.28.0 (2021-11-16) #### New Feature 🎉 - [#556](https://github.com/Schniz/fnm/pull/556) Allow aliasing to the system version ([@Schniz](https://github.com/Schniz)) - [#547](https://github.com/Schniz/fnm/pull/547) Replace reqwest with ureq for less dependencies and smaller file size ([@dnaka91](https://github.com/dnaka91)) #### Bugfix 🐛 - [#573](https://github.com/Schniz/fnm/pull/573) Infer shell with `sysinfo` crate ([@Schniz](https://github.com/Schniz)) - [#553](https://github.com/Schniz/fnm/pull/553) Fix Windows CMD `cd` failure on paths with spaces (`use-on-cd`) ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#554](https://github.com/Schniz/fnm/pull/554) Fix clippy & use musl target on Rust compiler for static compilation ([@dnaka91](https://github.com/dnaka91)) #### Documentation 📝 - [#545](https://github.com/Schniz/fnm/pull/545) docs(cli): Fix typo ([@SanchithHegde](https://github.com/SanchithHegde)) - [#544](https://github.com/Schniz/fnm/pull/544) Replace error message with a more useful one ([@yonifra](https://github.com/yonifra)) - [#537](https://github.com/Schniz/fnm/pull/537) Show log level options in help and error message ([@lucasweng](https://github.com/lucasweng)) #### Committers: 5 - Dominik Nakamura ([@dnaka91](https://github.com/dnaka91)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Jonathan Fraimorice ([@yonifra](https://github.com/yonifra)) - Lucas Weng ([@lucasweng](https://github.com/lucasweng)) - Sanchith Hegde ([@SanchithHegde](https://github.com/SanchithHegde)) ## v1.27.0 (2021-09-17) #### New Feature 🎉 - [#519](https://github.com/Schniz/fnm/pull/519) Windows: Use junctions rather than symlinks ([@davidaurelio](https://github.com/davidaurelio)) - [#489](https://github.com/Schniz/fnm/pull/489) Add unalias command ([@AlexMunoz](https://github.com/AlexMunoz)) #### Bugfix 🐛 - [#528](https://github.com/Schniz/fnm/pull/528) installation script: Use `=` instead of `==` ([@develoot](https://github.com/develoot)) - [#512](https://github.com/Schniz/fnm/pull/512) fix(dep): Revert "Include feature for (native) certificates #468" ([@itotallyrock](https://github.com/itotallyrock)) - [#514](https://github.com/Schniz/fnm/pull/514) Invoke fnm use on startup for PowerShell ([@naoey](https://github.com/naoey)) #### Documentation 📝 - [#529](https://github.com/Schniz/fnm/pull/529) Add Chocolatey installation instructions ([@CMeeg](https://github.com/CMeeg)) - [#496](https://github.com/Schniz/fnm/pull/496) install.sh: print an exit message for missing deps ([@waldyrious](https://github.com/waldyrious)) - [#516](https://github.com/Schniz/fnm/pull/516) More informative log level error message ([@waldyrious](https://github.com/waldyrious)) - [#493](https://github.com/Schniz/fnm/pull/493) Add instructions to setup the file for Cmder ([@Lunchb0ne](https://github.com/Lunchb0ne)) #### Committers: 8 - Abhishek Aryan ([@Lunchb0ne](https://github.com/Lunchb0ne)) - Alex Munoz ([@AlexMunoz](https://github.com/AlexMunoz)) - Chris Meagher ([@CMeeg](https://github.com/CMeeg)) - David Aurelio ([@davidaurelio](https://github.com/davidaurelio)) - Jeffrey Meyer ([@itotallyrock](https://github.com/itotallyrock)) - Kitae Kim ([@develoot](https://github.com/develoot)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) - [@naoey](https://github.com/naoey) ## v1.26.0 (2021-07-15) #### Bugfix 🐛 - [#484](https://github.com/Schniz/fnm/pull/484) fix: --install-if-missing when using version alias ([@AlexMunoz](https://github.com/AlexMunoz)) - [#468](https://github.com/Schniz/fnm/pull/468) Include feature for (native) certificates ([@pfiaux](https://github.com/pfiaux)) #### Documentation 📝 - [#467](https://github.com/Schniz/fnm/pull/467) Add instructions for removing fnm ([@binyamin](https://github.com/binyamin)) - [#461](https://github.com/Schniz/fnm/pull/461) Fix missing list-remote in command doc ([@binhonglee](https://github.com/binhonglee)) #### Committers: 4 - Alex Munoz ([@AlexMunoz](https://github.com/AlexMunoz)) - BinHong Lee ([@binhonglee](https://github.com/binhonglee)) - Binyamin Aron Green ([@binyamin](https://github.com/binyamin)) - Patrick Fiaux ([@pfiaux](https://github.com/pfiaux)) ## v1.25.0 (2021-05-17) #### New Feature 🎉 - [#436](https://github.com/Schniz/fnm/pull/436) feat: use arm for aarch64-darwin-node@16 platforms ([@pckilgore](https://github.com/pckilgore)) #### Documentation 📝 - [#432](https://github.com/Schniz/fnm/pull/432) Auto-generate command documentation markdown ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Patrick Kilgore ([@pckilgore](https://github.com/pckilgore)) ## v1.24.0 (2021-04-02) #### New Feature 🎉 - [#421](https://github.com/Schniz/fnm/pull/421) Adding FNM_ARCH as an exported env var from `fnm env` ([@Schniz](https://github.com/Schniz)) - [#417](https://github.com/Schniz/fnm/pull/417) Support Apple M1 by installing Rosetta Node builds ([@pckilgore](https://github.com/pckilgore)) #### Bugfix 🐛 - [#422](https://github.com/Schniz/fnm/pull/422) Create version symlinks in a nested directory ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Patrick Kilgore ([@pckilgore](https://github.com/pckilgore)) ## v1.23.2 (2021-03-24) #### Bugfix 🐛 - [#413](https://github.com/Schniz/fnm/pull/413) Improve "version not found" error message ([@waldyrious](https://github.com/waldyrious)) - [#414](https://github.com/Schniz/fnm/pull/414) More meaningful error message when a subprocess is killed ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) ## v1.23.1 (2021-03-21) #### Bugfix 🐛 - [#411](https://github.com/Schniz/fnm/pull/411) Call the fnm use-on-cd hook on fish initialization ([@Schniz](https://github.com/Schniz)) - [#404](https://github.com/Schniz/fnm/pull/404) Ignore LogLevel on `fnm ls` ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#408](https://github.com/Schniz/fnm/pull/408) Fix ARM builds CI ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#405](https://github.com/Schniz/fnm/pull/405) Fix a couple typos ([@waldyrious](https://github.com/waldyrious)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) ## v1.23.0 (2021-03-02) #### New Feature 🎉 - [#403](https://github.com/Schniz/fnm/pull/403) Allow `fnm use` to use a file path ([@Schniz](https://github.com/Schniz)) - [#401](https://github.com/Schniz/fnm/pull/401) Allow using filenames in --using= ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#398](https://github.com/Schniz/fnm/pull/398) `fnm exec`: Don't require double-dash ([@Schniz](https://github.com/Schniz)) - [#389](https://github.com/Schniz/fnm/pull/389) Chore - Use a tier 1 target for Linux binary ([@kaioduarte](https://github.com/kaioduarte)) - [#384](https://github.com/Schniz/fnm/pull/384) Do not list hidden directories as installed versions ([@scadu](https://github.com/scadu)) #### Documentation 📝 - [#397](https://github.com/Schniz/fnm/pull/397) Fix minor typos ([@leafrogers](https://github.com/leafrogers)) - [#385](https://github.com/Schniz/fnm/pull/385) README: add symlink support on Windows ([@scadu](https://github.com/scadu)) - [#377](https://github.com/Schniz/fnm/pull/377) Improvements to the README ([@waldyrious](https://github.com/waldyrious)) #### Committers: 5 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Kaio Duarte ([@kaioduarte](https://github.com/kaioduarte)) - Leaf Rogers ([@leafrogers](https://github.com/leafrogers)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) - Łukasz Jendrysik ([@scadu](https://github.com/scadu)) ## v1.22.9 (2021-01-22) #### Bugfix 🐛 - [#368](https://github.com/Schniz/fnm/pull/368) Update 'ring' to '0.16.17' ([@gucheen](https://github.com/gucheen)) - [#347](https://github.com/Schniz/fnm/pull/347) Check if \$ZDOTDIR exists to find correct path to .zshrc ([@thales-maciel](https://github.com/thales-maciel)) #### Documentation 📝 - [#341](https://github.com/Schniz/fnm/pull/341) Update installation instructions ([@Schniz](https://github.com/Schniz)) - [#329](https://github.com/Schniz/fnm/pull/329) Add scoop support ([@Armaldio](https://github.com/Armaldio)) - [#334](https://github.com/Schniz/fnm/pull/334) Add installation instructions from cargo ([@zhmushan](https://github.com/zhmushan)) #### Committers: 5 - Cheng Gu ([@gucheen](https://github.com/gucheen)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Quentin Goinaud ([@Armaldio](https://github.com/Armaldio)) - Thales Maciel ([@thales-maciel](https://github.com/thales-maciel)) - 木杉 ([@zhmushan](https://github.com/zhmushan)) ## v1.22.8 (2020-11-10) #### Documentation 📝 - [#327](https://github.com/Schniz/fnm/pull/327) Make ls and ls-remote aliases visible ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.22.7 (2020-11-09) #### New Feature 🎉 - [#315](https://github.com/Schniz/fnm/pull/315) Add `list` alias for `ls` ([@probablykasper](https://github.com/probablykasper)) #### Bugfix 🐛 - [#326](https://github.com/Schniz/fnm/pull/326) Make config arguments globally available on all commands ([@Schniz](https://github.com/Schniz)) - [#323](https://github.com/Schniz/fnm/pull/323) Escape `cd` calls in Bash's use-on-cd ([@Schniz](https://github.com/Schniz)) - [#322](https://github.com/Schniz/fnm/pull/322) Run `fnm use` on shell initialization in Bash ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Kasper ([@probablykasper](https://github.com/probablykasper)) ## v1.22.6 (2020-11-04) #### Bugfix 🐛 - [#317](https://github.com/Schniz/fnm/pull/317) Bring back --using-file flag with a deprecation warning. ([@bjornua](https://github.com/bjornua)) #### Committers: 1 - Bjørn Arnholtz ([@bjornua](https://github.com/bjornua)) ## v1.22.5 (2020-10-29) #### Bugfix 🐛 - [#310](https://github.com/Schniz/fnm/pull/310) Better error handling in symlink replacement ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#307](https://github.com/Schniz/fnm/pull/307) Refer to homebrew/core formula instead of custom tap ([@jameschensmith](https://github.com/jameschensmith)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith)) ## v1.22.4 (2020-10-28) #### New Feature 🎉 - [#304](https://github.com/Schniz/fnm/pull/304) Make the first installed version the default one ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#308](https://github.com/Schniz/fnm/pull/308) Allow unsuccessful symlink deletion in `fnm use` ([@Schniz](https://github.com/Schniz)) - [#303](https://github.com/Schniz/fnm/pull/303) Add ARM handling to installation script ([@Schniz](https://github.com/Schniz)) - [#289](https://github.com/Schniz/fnm/pull/289) Remove logs from automatic version switching in `--use-on-cd` ([@maxjacobson](https://github.com/maxjacobson)) - [#301](https://github.com/Schniz/fnm/pull/301) UserVersion: Fix different parsing for leading `v` ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#306](https://github.com/Schniz/fnm/pull/306) Throw an error instead of panicking when can't infer shell ([@Schniz](https://github.com/Schniz)) - [#297](https://github.com/Schniz/fnm/pull/297) Update CI badge ([@jameschensmith](https://github.com/jameschensmith)) #### Committers: 3 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith)) - Max Jacobson ([@maxjacobson](https://github.com/maxjacobson)) ## v1.22.3 (2020-10-26) #### New Feature 🎉 - [#292](https://github.com/Schniz/fnm/pull/292) Add uninstall command ([@Schniz](https://github.com/Schniz)) - [#276](https://github.com/Schniz/fnm/pull/276) Add pre-built binaries for ARM32 and ARM64 ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#290](https://github.com/Schniz/fnm/pull/290) Fix shell inference in VSCode ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#287](https://github.com/Schniz/fnm/pull/287) Remove `--multi` from install script ([@jameschensmith](https://github.com/jameschensmith)) #### Documentation 📝 - [#295](https://github.com/Schniz/fnm/pull/295) Add a warning if MULTISHELL env var is not in PATH ([@Schniz](https://github.com/Schniz)) - [#293](https://github.com/Schniz/fnm/pull/293) Add detailed error instead of panic regarding `fnm env` ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith)) ## v1.22.2 (2020-10-25) #### Bugfix 🐛 - [#284](https://github.com/Schniz/fnm/pull/284) Fix npm not working because of wrong file copying ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#282](https://github.com/Schniz/fnm/pull/282) site: proxy the installation script ([@Schniz](https://github.com/Schniz)) - [#271](https://github.com/Schniz/fnm/pull/271) Update README for Windows instructions ([@Schniz](https://github.com/Schniz)) - [#281](https://github.com/Schniz/fnm/pull/281) docs: removed mentions of --multi from README ([@folke](https://github.com/folke)) #### Committers: 2 - Folke Lemaitre ([@folke](https://github.com/folke)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.22.1 (2020-10-25) #### Internal 🛠 - [#279](https://github.com/Schniz/fnm/pull/279) Remove UPX binary compression for now ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.22.0 (2020-10-25) #### Bugfix 🐛 - [#275](https://github.com/Schniz/fnm/pull/275) Fix moving a node installation across mounting points ([@jaythomas](https://github.com/jaythomas)) #### Internal 🛠 - [#274](https://github.com/Schniz/fnm/pull/274) Add ARM arch support in downloads ([@jaythomas](https://github.com/jaythomas)) - [#266](https://github.com/Schniz/fnm/pull/266) Use separate config file for fish config ([@wesbaker](https://github.com/wesbaker)) #### Committers: 3 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Jay Thomas ([@jaythomas](https://github.com/jaythomas)) - Wes Baker ([@wesbaker](https://github.com/wesbaker)) ## v1.22.0-beta-1 (2020-10-07) #### New Feature 🎉 - [#244](https://github.com/Schniz/fnm/pull/244) Allow using homebrew to install with the installation script ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#225](https://github.com/Schniz/fnm/pull/225) Remove unused condition ([@joliss](https://github.com/joliss)) #### Internal 🛠 - [#246](https://github.com/Schniz/fnm/pull/246) Rewrite fnm in Rust (merge fnm.rs into fnm) — adding Windows support! ([@Schniz](https://github.com/Schniz)) - [#243](https://github.com/Schniz/fnm/pull/243) Add installation script testing ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#247](https://github.com/Schniz/fnm/pull/247) fixed a typo ([@0xflotus](https://github.com/0xflotus)) - [#245](https://github.com/Schniz/fnm/pull/245) Shorten the installation script ([@Schniz](https://github.com/Schniz)) - [#237](https://github.com/Schniz/fnm/pull/237) docs: add explanation of uninstall command to README ([@kazushisan](https://github.com/kazushisan)) - [#235](https://github.com/Schniz/fnm/pull/235) Mention fnm omf plugin for Fish users ([@idkjs](https://github.com/idkjs)) #### Committers: 5 - 0xflotus ([@0xflotus](https://github.com/0xflotus)) - Alain Armand ([@idkjs](https://github.com/idkjs)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Jo Liss ([@joliss](https://github.com/joliss)) - Kazushi Konosu ([@kazushisan](https://github.com/kazushisan)) ## v1.21.0 (2020-06-07) #### New Feature 🎉 - [#220](https://github.com/Schniz/fnm/pull/220) Add `current` command to retrieve the current Node version ([@vladimyr](https://github.com/vladimyr)) - [#210](https://github.com/Schniz/fnm/pull/210) Allow aliasing and removing an alias ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#217](https://github.com/Schniz/fnm/pull/217) Set version on new shell initialization in fish ([@jaredramirez](https://github.com/jaredramirez)) - [#207](https://github.com/Schniz/fnm/pull/207) Format dotfiles versions before comparison ([@amitdahan](https://github.com/amitdahan)) #### Committers: 4 - Amit Dahan ([@amitdahan](https://github.com/amitdahan)) - Dario Vladović ([@vladimyr](https://github.com/vladimyr)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Jared Ramirez ([@jaredramirez](https://github.com/jaredramirez)) ## v1.20.0 (2020-03-22) #### New Feature 🎉 - [#201](https://github.com/Schniz/fnm/pull/201) Create alias from version range (Closes [#185](https://github.com/Schniz/fnm/issues/185)) ([@tatchi](https://github.com/tatchi)) #### Bugfix 🐛 - [#199](https://github.com/Schniz/fnm/pull/199) Fix typo criterias -> criteria ([@waldyrious](https://github.com/waldyrious)) #### Documentation 📝 - [#204](https://github.com/Schniz/fnm/pull/204) Improve eval expression in `README.md` ([@loliee](https://github.com/loliee)) #### Committers: 3 - Corentin Leruth ([@tatchi](https://github.com/tatchi)) - Maxime Loliée ([@loliee](https://github.com/loliee)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) ## v1.19.0 (2020-03-09) #### New Feature 🎉 - [#194](https://github.com/Schniz/fnm/pull/194) Add `fnm exec` to run commands with the fnm environment ([@Schniz](https://github.com/Schniz)) - [#191](https://github.com/Schniz/fnm/pull/191) uninstall allow prefix (Closes [#121](https://github.com/Schniz/fnm/issues/121)) ([@tatchi](https://github.com/tatchi)) - [#190](https://github.com/Schniz/fnm/pull/190) Add majorVersion option to ls-remote ([@tatchi](https://github.com/tatchi)) #### Bugfix 🐛 - [#200](https://github.com/Schniz/fnm/pull/200) Do not repeat installation prompt for unrecognized versions ([@tatchi](https://github.com/tatchi)) - [#197](https://github.com/Schniz/fnm/pull/197) Fix capitalization of message in Use.re ([@waldyrious](https://github.com/waldyrious)) #### Internal 🛠 - [#202](https://github.com/Schniz/fnm/pull/202) Update rely ([@tatchi](https://github.com/tatchi)) - [#192](https://github.com/Schniz/fnm/pull/192) Bump ocaml to 4.08 ([@tatchi](https://github.com/tatchi)) #### Committers: 3 - Corentin Leruth ([@tatchi](https://github.com/tatchi)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Waldir Pimenta ([@waldyrious](https://github.com/waldyrious)) ## v1.18.1 (2019-12-30) #### Bugfix 🐛 - [#182](https://github.com/Schniz/fnm/pull/182) Closes [#181](https://github.com/Schniz/fnm/issues/181) by dropping `exit(1)` ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.18.0 (2019-12-23) #### New Feature 🎉 - [#176](https://github.com/Schniz/fnm/pull/176) Specify the release to the install script ([@chrisdaley](https://github.com/chrisdaley)) #### Bugfix 🐛 - [#177](https://github.com/Schniz/fnm/pull/177) Fix "illegal instruction" errors on some CPUs ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#179](https://github.com/Schniz/fnm/pull/179) Bump lwt version ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Chris Daley ([@chrisdaley](https://github.com/chrisdaley)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.17.0 (2019-11-26) #### Bugfix 🐛 - [#169](https://github.com/Schniz/fnm/pull/169) Support spaces in directory name in Bash ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#172](https://github.com/Schniz/fnm/pull/172) Revert into using `ocaml-tls` instead of `ocaml-ssl` ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.16.0 (2019-10-27) #### New Feature 🎉 - [#146](https://github.com/Schniz/fnm/pull/146) Add support for `lts/*` ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#150](https://github.com/Schniz/fnm/pull/150) Add missing log level to `env` output for Fish shell ([@thomsj](https://github.com/thomsj)) #### Internal 🛠 - [#154](https://github.com/Schniz/fnm/pull/154) Run all feature tests ([@Schniz](https://github.com/Schniz)) - [#148](https://github.com/Schniz/fnm/pull/148) Make `env` smoke test pass when run with fish ([@thomsj](https://github.com/thomsj)) - [#153](https://github.com/Schniz/fnm/pull/153) Add missing `exit 1`s to `partial_semver` tests ([@thomsj](https://github.com/thomsj)) - [#151](https://github.com/Schniz/fnm/pull/151) Add a CI check for code formatting ([@Schniz](https://github.com/Schniz)) - [#149](https://github.com/Schniz/fnm/pull/149) Update to v6.17.1 in `partial_semver` feature test ([@thomsj](https://github.com/thomsj)) - [#143](https://github.com/Schniz/fnm/pull/143) Try to install new deps ([@Schniz](https://github.com/Schniz)) - [#142](https://github.com/Schniz/fnm/pull/142) Drop buildsInSource ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#157](https://github.com/Schniz/fnm/pull/157) Rename `--base-dir` to `--fnm-dir` in README ([@thomsj](https://github.com/thomsj)) - [#158](https://github.com/Schniz/fnm/pull/158) Uncapitalise "Node" in `--multi` description ([@thomsj](https://github.com/thomsj)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - James Thomson ([@thomsj](https://github.com/thomsj)) ## v1.15.0 (2019-09-23) #### Bugfix 🐛 - [#138](https://github.com/Schniz/fnm/pull/138) Do uninstallation in steps ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#132](https://github.com/Schniz/fnm/pull/132) Fix spelling of availability in install.sh ([@trevershick](https://github.com/trevershick)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Trever Shick ([@trevershick](https://github.com/trevershick)) ## v1.14.0 (2019-08-20) #### New Feature 🎉 - [#134](https://github.com/Schniz/fnm/pull/134) Alias -v to --version ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#131](https://github.com/Schniz/fnm/pull/131) Deprecates MacOS installation using the script in favor of Homebrew ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#133](https://github.com/Schniz/fnm/pull/133) Fix Windows build once again! ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.13.0 (2019-07-15) #### New Feature 🎉 - [#129](https://github.com/Schniz/fnm/pull/129) Alias latest versions on installation ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#125](https://github.com/Schniz/fnm/pull/125) format versions in `uninstall` ([@Schniz](https://github.com/Schniz)) - [#114](https://github.com/Schniz/fnm/pull/114) installation script: use $INSTALL_DIR instead of hard-coded $HOME/.fnm ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#130](https://github.com/Schniz/fnm/pull/130) Fix issues related to help pages ([@Schniz](https://github.com/Schniz)) - [#123](https://github.com/Schniz/fnm/pull/123) Fix typo in successfully ([@pavelloz](https://github.com/pavelloz)) - [#118](https://github.com/Schniz/fnm/pull/118) Add note about upgrading ([@pavelloz](https://github.com/pavelloz)) - [#119](https://github.com/Schniz/fnm/pull/119) Remove "Homebrew" from future plans as it is done ([@pavelloz](https://github.com/pavelloz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Paweł Kowalski ([@pavelloz](https://github.com/pavelloz)) ## v1.12.0 (2019-06-06) #### New Feature 🎉 - [#106](https://github.com/Schniz/fnm/pull/106) Add `default`, as a shortcut for `alias default` ([@dangdennis](https://github.com/dangdennis)) - [#104](https://github.com/Schniz/fnm/pull/104) Add a 'debug' log level ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#88](https://github.com/Schniz/fnm/pull/88) Successfully build on Windows ([@ulrikstrid](https://github.com/ulrikstrid)) #### Committers: 3 - Dennis Dang ([@dangdennis](https://github.com/dangdennis)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Ulrik Strid ([@ulrikstrid](https://github.com/ulrikstrid)) ## v1.11.0 (2019-05-27) #### New Feature 🎉 - [#98](https://github.com/Schniz/fnm/pull/98) Add `uninstall` command ([@tatchi](https://github.com/tatchi)) - [#97](https://github.com/Schniz/fnm/pull/97) Add the ability to use system version of Node ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#103](https://github.com/Schniz/fnm/pull/103) Fix missing aliases due to newer `realpath` ([@Schniz](https://github.com/Schniz)) - [#99](https://github.com/Schniz/fnm/pull/99) fix EACCES error when installing an already downloaded version ([@tatchi](https://github.com/tatchi)) #### Internal 🛠 - [#101](https://github.com/Schniz/fnm/pull/101) Move from base to core ([@ulrikstrid](https://github.com/ulrikstrid)) - [#102](https://github.com/Schniz/fnm/pull/102) Implement `realpath` instead of binding to C library ([@Schniz](https://github.com/Schniz)) - [#100](https://github.com/Schniz/fnm/pull/100) Add Semver to library, an simple non-spec implementation of semver ([@Schniz](https://github.com/Schniz)) #### Committers: 3 - Corentin Leruth ([@tatchi](https://github.com/tatchi)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Ulrik Strid ([@ulrikstrid](https://github.com/ulrikstrid)) ## v1.10.0 (2019-05-01) #### New Feature 🎉 - [#93](https://github.com/Schniz/fnm/pull/93) Add support for log level (Closes [#33](https://github.com/Schniz/fnm/issues/33)) ([@ohana54](https://github.com/ohana54)) #### Documentation 📝 - [#95](https://github.com/Schniz/fnm/pull/95) Shorten installation script url ([@vladimyr](https://github.com/vladimyr)) #### Committers: 2 - Dario Vladović ([@vladimyr](https://github.com/vladimyr)) - Tomer Ohana ([@ohana54](https://github.com/ohana54)) ## v1.9.1 (2019-04-14) #### Bugfix 🐛 - [#91](https://github.com/Schniz/fnm/pull/91) Fix `fnm env` for fish shell. ([@hwartig](https://github.com/hwartig)) - [#90](https://github.com/Schniz/fnm/pull/90) Installation script doesn't use GitHub API, but a link to the latest directly ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Harald Wartig ([@hwartig](https://github.com/hwartig)) ## v1.9.0 (2019-03-18) #### New Feature 🎉 - [#86](https://github.com/Schniz/fnm/pull/86) Add support for interactive installation for use ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#85](https://github.com/Schniz/fnm/pull/85) Update README.md ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.8.0 (2019-03-13) #### Bugfix 🐛 - [#83](https://github.com/Schniz/fnm/pull/83) fix: remove unmatched quote written in the fish config file ([@thomasmarcel](https://github.com/thomasmarcel)) #### Internal 🛠 - [#84](https://github.com/Schniz/fnm/pull/84) Strip binaries to make them smaller ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Thomas Alcala Schneider ([@thomasmarcel](https://github.com/thomasmarcel)) ## v1.7.2 (2019-03-07) #### Bugfix 🐛 - [#79](https://github.com/Schniz/fnm/pull/79) Guard from more non-existent directories errors ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.7.1 (2019-03-05) #### Bugfix 🐛 - [#77](https://github.com/Schniz/fnm/pull/77) Fix "command not found: elsif" error ([@jletey](https://github.com/jletey)) #### Internal 🛠 - [#78](https://github.com/Schniz/fnm/pull/78) Add a test to `use-on-cd` when `.node-version` is found ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - John Letey ([@jletey](https://github.com/jletey)) ## v1.7.0 (2019-03-04) #### New Feature 🎉 - [#68](https://github.com/Schniz/fnm/pull/68) Infer shells automatically, and `use` versions based on the current working directory (optional) ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.6.2 (2019-03-04) #### Bugfix 🐛 - [#72](https://github.com/Schniz/fnm/pull/72) Fix alias paths ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#70](https://github.com/Schniz/fnm/pull/70) Fix installation script parameters docs ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.6.1 (2019-02-26) #### Bugfix 🐛 - [#69](https://github.com/Schniz/fnm/pull/69) Fix version inference by throwing on http 404 again ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.6.0 (2019-02-25) #### New Feature 🎉 - [#57](https://github.com/Schniz/fnm/pull/57) Switch to cohttp(lwt) instead of curl ([@tatchi](https://github.com/tatchi)) #### Bugfix 🐛 - [#64](https://github.com/Schniz/fnm/pull/64) Throw on errors in installation script ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#67](https://github.com/Schniz/fnm/pull/67) Use `perl-utils` instead of custom written `shasum` ([@Schniz](https://github.com/Schniz)) - [#66](https://github.com/Schniz/fnm/pull/66) Use newer esy ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Corentin Leruth ([@tatchi](https://github.com/tatchi)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.5.1 (2019-02-22) #### Bugfix 🐛 - [#61](https://github.com/Schniz/fnm/pull/61) Fix a bug where `fnm env --multi` didn't used the default alias ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.5.0 (2019-02-21) #### New Feature 🎉 - [#60](https://github.com/Schniz/fnm/pull/60) Disable colors for non-tty devices ([@Schniz](https://github.com/Schniz)) - [#48](https://github.com/Schniz/fnm/pull/48) Add parameters to the install script, enabling custom installs (`--install-dir` and `--skip-shell`) ([@from-nibly](https://github.com/from-nibly)) - [#54](https://github.com/Schniz/fnm/pull/54) Infer complete semver (`vX.X.X`) out of partial input (`vX`/`vX.X`). ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#58](https://github.com/Schniz/fnm/pull/58) Adding check for OSX during writing for bash shell ([@maxknee](https://github.com/maxknee)) - [#56](https://github.com/Schniz/fnm/pull/56) Correct status code on `install` failures ([@ranyitz](https://github.com/ranyitz)) #### Internal 🛠 - [#55](https://github.com/Schniz/fnm/pull/55) Make tests faster by using cnpmjs as Node.js mirror in tests ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#49](https://github.com/Schniz/fnm/pull/49) Add a `--fnm-dir` option to `fnm env` ([@Schniz](https://github.com/Schniz)) - [#50](https://github.com/Schniz/fnm/pull/50) Added CHANGELOG ([@Schniz](https://github.com/Schniz)) #### Committers: 4 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - Jordan Davidson ([@from-nibly](https://github.com/from-nibly)) - Max Knee ([@maxknee](https://github.com/maxknee)) - Ran Yitzhaki ([@ranyitz](https://github.com/ranyitz)) ## v1.4.0 (2019-02-18) #### New Feature 🎉 - [#45](https://github.com/Schniz/fnm/pull/45) Use exit code 1 on errors on `fnm use` ([@Schniz](https://github.com/Schniz)) - [#42](https://github.com/Schniz/fnm/pull/42) Add support for .node-version files ([@Dean177](https://github.com/Dean177)) #### Documentation 📝 - [#44](https://github.com/Schniz/fnm/pull/44) Quick fix for the dev environment setup ([@AdamGS](https://github.com/AdamGS)) #### Committers: 3 - Adam Gutglick ([@AdamGS](https://github.com/AdamGS)) - Dean Merchant ([@Dean177](https://github.com/Dean177)) - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.3.0 (2019-02-14) #### New Feature 🎉 - [#36](https://github.com/Schniz/fnm/pull/36) Support Node.js mirrors ([@Schniz](https://github.com/Schniz)) - [#30](https://github.com/Schniz/fnm/pull/30) Aliases and multishell support ([@Schniz](https://github.com/Schniz)) - [#37](https://github.com/Schniz/fnm/pull/37) Don't throw on existing installation ([@Schniz](https://github.com/Schniz)) - [#27](https://github.com/Schniz/fnm/pull/27) skip installation if the version is already installed ([@kentac55](https://github.com/kentac55)) #### Documentation 📝 - [#22](https://github.com/Schniz/fnm/pull/22) Add a LICENSE file ([@Schniz](https://github.com/Schniz)) #### Committers: 2 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) - [@kentac55](https://github.com/kentac55) ## v1.2.1 (2019-02-11) #### Bugfix 🐛 - [#25](https://github.com/Schniz/fnm/pull/25) CI (fnm-linux => fnm) ([@Schniz](https://github.com/Schniz)) #### Internal 🛠 - [#21](https://github.com/Schniz/fnm/pull/21) Add feature test for Fish shell ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#23](https://github.com/Schniz/fnm/pull/23) Add installation script ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.2.0 (2019-01-30) #### New Feature 🎉 - [#17](https://github.com/Schniz/fnm/pull/17) Use xz files instead of gz ([@Schniz](https://github.com/Schniz)) #### Bugfix 🐛 - [#16](https://github.com/Schniz/fnm/pull/16) Make `fnm --version` show the correct version ([@Schniz](https://github.com/Schniz)) - [#15](https://github.com/Schniz/fnm/pull/15) Don't throw in nonexistent directory on `fnm ls` ([@Schniz](https://github.com/Schniz)) #### Documentation 📝 - [#13](https://github.com/Schniz/fnm/pull/13) Added short docs to the README ([@Schniz](https://github.com/Schniz)) #### Committers: 1 - Gal Schlezinger ([@Schniz](https://github.com/Schniz)) ## v1.1.0 (2019-01-27) #### New Feature 🎉 - [#10](https://github.com/Schniz/fnm/pull/10) Add fish shell setup to `env` command and README ([@elliottsj](https://github.com/elliottsj)) #### Committers: 1 - Spencer Elliott ([@elliottsj](https://github.com/elliottsj)) ================================================ FILE: Cargo.toml ================================================ [package] name = "fnm" version = "1.39.0" authors = ["Gal Schlezinger "] edition = "2021" build = "build.rs" license = "GPL-3.0" repository = "https://github.com/Schniz/fnm" description = "Fast and simple Node.js version manager" [dependencies] serde = { version = "1.0.203", features = ["derive"] } clap = { version = "4.5.4", features = ["derive", "env"] } serde_json = "1.0.117" chrono = { version = "0.4.38", features = ["serde", "now"], default-features = false } tar = "0.4.40" xz2 = "0.1.7" node-semver = "2.1.0" etcetera = "0.8.0" colored = "2.1.0" zip = "2.1.0" tempfile = "3.10.1" indoc = "2.0.5" log = "0.4.21" env_logger = "0.11.3" encoding_rs_io = "0.1.7" reqwest = { version = "0.12.4", features = ["blocking", "json", "rustls-tls", "rustls-tls-native-roots", "brotli"], default-features = false } url = "2.5.0" sysinfo = "0.30.12" thiserror = "1.0.61" clap_complete = "4.5.2" anyhow = "1.0.86" indicatif = { version = "0.17.8", features = ["improved_unicode"] } flate2 = "1.0.30" miette = { version = "7.2.0", features = ["fancy"] } [dev-dependencies] pretty_assertions = "1.4.0" duct = "0.13.7" test-log = "0.2.16" http = "1.1.0" [build-dependencies] embed-resource = "2.4.2" [target.'cfg(windows)'.dependencies] csv = "1.3.0" junction = "1.1.0" [features] ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Fast Node Manager (fnm) Amount of downloads GitHub Actions workflow status

> 🚀 Fast and simple Node.js version manager, built in Rust
Blazing fast!
## Features 🌎 Cross-platform support (macOS, Windows, Linux) ✨ Single file, easy installation, instant startup 🚀 Built with speed in mind 📂 Works with `.node-version` and `.nvmrc` files ## Installation ### Using a script (macOS/Linux) For `bash`, `zsh` and `fish` shells, there's an [automatic installation script](./.ci/install.sh). First ensure that `curl` and `unzip` are already installed on your operating system. Then execute: ```sh curl -fsSL https://fnm.vercel.app/install | bash ``` #### Upgrade On macOS, it is as simple as `brew upgrade fnm`. On other operating systems, upgrading `fnm` is almost the same as installing it. To prevent duplication in your shell config file, pass `--skip-shell` to the install command: ```sh curl -fsSL https://fnm.vercel.app/install | bash -s -- --skip-shell ``` #### Parameters `--install-dir` Set a custom directory for fnm to be installed. The default is `$XDG_DATA_HOME/fnm` (if `$XDG_DATA_HOME` is not defined it falls back to `$HOME/.local/share/fnm` on linux and `$HOME/Library/Application Support/fnm` on MacOS). > **Note:** On macOS, this option is only meaningful when using `--force-install` since Homebrew is the default installation method. `--skip-shell` Skip appending shell specific loader to shell config file, based on the current user shell, defined in `$SHELL`. e.g. for Bash, `$HOME/.bashrc`. `$HOME/.zshrc` for Zsh. For Fish - `$HOME/.config/fish/conf.d/fnm.fish` `--force-install` macOS installations using the installation script are deprecated in favor of the Homebrew formula, but this forces the script to install using it anyway. Example: ```sh curl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir "./.fnm" --skip-shell ``` ### Manually #### Using Homebrew (macOS/Linux) ```sh brew install fnm ``` Then, [set up your shell for fnm](#shell-setup) #### Using Winget (Windows) ```sh winget install Schniz.fnm ``` #### Using Scoop (Windows) ```sh scoop install fnm ``` Then, [set up your shell for fnm](#shell-setup) #### Using Chocolatey (Windows) ```sh choco install fnm ``` Then, [set up your shell for fnm](#shell-setup) #### Using Cargo (Linux/macOS/Windows) ```sh cargo install fnm ``` Then, [set up your shell for fnm](#shell-setup) #### Using a release binary (Linux/macOS/Windows) - Download the [latest release binary](https://github.com/Schniz/fnm/releases) for your system - Make it available globally on `PATH` environment variable - [Set up your shell for fnm](#shell-setup) ### Removing To remove fnm (😢), just delete the `.fnm` folder in your home directory. You should also edit your shell configuration to remove any references to fnm (ie. read [Shell Setup](#shell-setup), and do the opposite). ## Completions fnm ships its completions with the binary: ```sh fnm completions --shell ``` Where `` can be one of the supported shells: - `bash` - `zsh` - `fish` - `powershell` Please follow your shell instructions to install them. ### Shell Setup Environment variables need to be setup before you can start using fnm. This is done by evaluating the output of `fnm env`. > [!TIP] > Prefer passing an explicit shell (for example `fnm env --shell bash`) instead of relying on shell inference at runtime. It is a bit faster and avoids process tree detection. > [!NOTE] > Check out the [Configuration](./docs/configuration.md) section to enable highly > recommended features, like automatic version switching. Adding a `.node-version` to your project is as simple as: ```bash $ node --version v14.18.3 $ node --version > .node-version ``` Check out the following guides for the shell you use: #### Bash Add the following to your `.bashrc` profile: ```bash eval "$(fnm env --use-on-cd --shell bash)" ``` #### Zsh Add the following to your `.zshrc` profile: ```zsh eval "$(fnm env --use-on-cd --shell zsh)" ``` #### Fish shell Create `~/.config/fish/conf.d/fnm.fish` and add this line to it: ```fish fnm env --use-on-cd --shell fish | source ``` #### PowerShell Add the following to the end of your profile file: ```powershell fnm env --use-on-cd --shell powershell | Out-String | Invoke-Expression ``` - For macOS/Linux, the profile is located at `~/.config/powershell/Microsoft.PowerShell_profile.ps1` - For Windows location is either: - `%userprofile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1` Powershell 5 - `%userprofile%\Documents\PowerShell\Microsoft.PowerShell_profile.ps1` Powershell 6+ - To create the profile file you can run this in PowerShell: ```powershell if (-not (Test-Path $profile)) { New-Item $profile -Force } ``` - To edit your profile run this in PowerShell: ```powershell Invoke-Item $profile ``` #### Windows Command Prompt aka Batch aka WinCMD fnm is also supported but is not entirely covered. You can set up a startup script for [cmd.exe](https://superuser.com/a/144348) or [Windows Terminal](https://superuser.com/a/1855283) and append the following lines: ```batch @echo off :: for /F will launch a new instance of cmd so we create a guard to prevent an infnite loop if not defined FNM_AUTORUN_GUARD ( set "FNM_AUTORUN_GUARD=AutorunGuard" FOR /f "tokens=*" %%z IN ('fnm env --use-on-cd') DO CALL %%z ) ``` #### Usage with Cmder Usage is very similar to the normal WinCMD install, apart for a few tweaks to allow being called from the cmder startup script. The example **assumes** that the `CMDER_ROOT` environment variable is **set** to the **root directory** of your Cmder installation. Then you can do something like this: - Make a .cmd file to invoke it ```batch :: %CMDER_ROOT%\bin\fnm_init.cmd @echo off FOR /f "tokens=*" %%z IN ('fnm env --use-on-cd') DO CALL %%z ``` - Add it to the startup script ```batch :: %CMDER_ROOT%\config\user_profile.cmd call "%CMDER_ROOT%\bin\fnm_init.cmd" ``` You can replace `%CMDER_ROOT%` with any other convenient path too. ## [Configuration](./docs/configuration.md) [See the available configuration options for an extended configuration documentation](./docs/configuration.md) ## [Usage](./docs/commands.md) [See the available commands for an extended usage documentation](./docs/commands.md) ## Contributing PRs welcome :tada: ### Developing: ```sh # Install Rust git clone https://github.com/Schniz/fnm.git cd fnm/ cargo build ``` ### Running Binary: ```sh cargo run -- --help # Will behave like `fnm --help` ``` ### Running Tests: ```sh cargo test ``` ================================================ FILE: benchmarks/basic/fnm ================================================ #!/bin/bash eval "$(fnm env --shell=bash)" fnm install v10.11.0 fnm use v10.11.0 node -v ================================================ FILE: benchmarks/basic/nvm ================================================ #!/bin/bash export NVM_DIR="$HOME/.nvm" \. "$NVM_DIR/nvm.sh" # This loads nvm nvm install v10.11.0 nvm use v10.11.0 node -v ================================================ FILE: benchmarks/run ================================================ #!/bin/bash set -e export FNM_DIR BASE_DIR="$(dirname "$(realpath "$0")")" cd "$BASE_DIR" || exit 1 FNM_DIR="$(mktemp -d)" export PATH="$BASE_DIR/../target/release:$PATH" mkdir results 2>/dev/null || : if [ ! -f "$BASE_DIR/../target/release/fnm" ]; then echo "Can't access the release version of fnm.rs" exit 1 fi if ! command -v hyperfine >/dev/null 2>&1; then echo "Can't access Hyperfine. Are you sure it is installed?" echo " if not, visit https://github.com/sharkdp/hyperfine" exit 1 fi # Running it with warmup means we're going to have the versions # pre-installed. I think it is good because you open your shell more times # than you install Node versions. hyperfine \ --warmup=2 \ --min-runs=40 \ --time-unit=millisecond \ --export-json="./results/basic.json" \ --export-markdown="./results/basic.md" \ "basic/nvm" \ "basic/fnm" ================================================ FILE: benchmarks/run.mjs ================================================ // @ts-check import z from "zod" import os from "node:os" import path from "node:path" import fetch from "node-fetch" import { execa } from "execa" import { binary, command, flag, option } from "cmd-ts" import Url from "cmd-ts/dist/cjs/batteries/url.js" import { run } from "cmd-ts" import fs from "node:fs/promises" import { dedent } from "ts-dedent" const HyperfineResult = z.object({ results: z.array( z.object({ command: z.string(), mean: z.number(), stddev: z.number(), median: z.number(), user: z.number(), system: z.number(), min: z.number(), max: z.number(), times: z.array(z.number()), exit_codes: z.array(z.literal(0)), }) ), }) const BenchyResult = z.object({ data: z.object({ embed: z.object({ small: z.string(), big: z.string(), currentValue: z.number(), lastValue: z.number().optional(), diff: z .object({ value: z.number(), arrowImage: z.string(), }) .optional(), }), }), }) const { HttpUrl } = Url const cmd = command({ name: "run-benchmarks", args: { serverUrl: option({ long: "server-url", type: HttpUrl, defaultValue: () => new URL("https://benchy.hagever.com"), defaultValueIsSerializable: true, }), githubToken: option({ long: "github-token", env: "GITHUB_TOKEN", }), shouldStore: flag({ long: "store", }), }, async handler({ serverUrl, githubToken, shouldStore }) { const repoName = "fnm" const repoOwner = "schniz" const hyperfineResult = await runHyperfine() if (!hyperfineResult.success) { console.error( `Can't run benchmarks: wrong data:`, hyperfineResult.error.issues ) process.exitCode = 1 return } const { results } = hyperfineResult.data const url = new URL("/api/metrics", serverUrl) const trackedKeys = ["median", "max", "mean", "min", "stddev"] const metrics = results .flatMap((result) => { return trackedKeys.map((key) => { return { displayName: `${result.command}/${key}`, value: result[key] * 1000, // everything is in seconds units: "ms", } }) }) .concat([ { displayName: `binary size`, value: await getFilesize(), units: "kb", }, ]) .map((metric) => { return { ...metric, key: `${os.platform()}/${os.arch()}/${metric.displayName}`, } }) const embeds$ = metrics.map(async ({ key, value, displayName, units }) => { const response = await fetch(String(url), { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ coloring: "lower-is-better", repoOwner, repoName, githubToken, key, value, }), }) if (!response.ok) { throw new Error(`Response is not okay: ${response.status}`) } const { data } = BenchyResult.parse(await response.json()) return { displayName, units, ...data.embed, } }) const embeds = await Promise.all(embeds$) const table = (() => { const rows = embeds .map((data) => { return dedent` ${data.displayName} ${round(data.currentValue, 2)}${data.units} ${ typeof data.lastValue === "undefined" ? "" : `${round(data.lastValue, 2)}${data.units}` } ${ !data.diff ? "0" : dedent` 0 ? "increase" : "decrease" )}> ${data.diff.value > 0 ? "+" : ""}${round( data.diff.value, 2 )}${data.units} ` }

` }) .join("\n") return dedent` ${rows}
benchmark current value last value diff trend
` })() console.log(table) if (shouldStore) { const response = await fetch(String(url), { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ repoOwner, repoName, githubToken, metrics, }), }) if (!response.ok) { throw new Error(`Response is not okay: ${response.status}`) } console.error(await response.json()) } }, }) /** * @param {number} number * @param {number} digits */ function round(number, digits) { const pow = Math.pow(10, digits) return Math.round(number * pow) / pow } /** * Returns the size of the `fnm` binary in kilobytes * * @returns number */ async function getFilesize() { const fnmBinary = await execa("which", ["fnm"]) const stat = await fs.stat(fnmBinary.stdout.trim()) return Math.round(stat.size / 1024) } async function runHyperfine() { const file = path.join(os.tmpdir(), `bench-${Date.now()}.json`) await execa( `hyperfine`, [ "--min-runs=20", `--export-json=${file}`, "--warmup=2", ...[ "--command-name=fnm_basic", new URL("./basic/fnm", import.meta.url).pathname, ], // ...[ // "--command-name=nvm_basic", // new URL("./basic/nvm", import.meta.url).pathname, // ], ], { stdout: process.stderr, stderr: process.stderr, stdin: "ignore", } ) const json = JSON.parse(await fs.readFile(file, "utf8")) const parsed = HyperfineResult.safeParse(json) return parsed } run(binary(cmd), process.argv) ================================================ FILE: build.rs ================================================ fn main() { embed_resource::compile("fnm-manifest.rc", embed_resource::NONE); } ================================================ FILE: docs/commands.md ================================================ # `fnm` ``` A fast and simple Node.js manager Usage: fnm [OPTIONS] Commands: list-remote List all remote Node.js versions [aliases: ls-remote] list List all locally installed Node.js versions [aliases: ls] install Install a new Node.js version [aliases: i] use Change Node.js version env Print and set up required environment variables for fnm completions Print shell completions to stdout alias Alias a version to a common name unalias Remove an alias definition default Set a version as the default version or get the current default version current Print the current Node.js version exec Run a command within fnm context uninstall Uninstall a Node.js version [aliases: uni] help Print this message or the help of the given subcommand(s) Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') -V, --version Print version ``` # `fnm list-remote` ``` List all remote Node.js versions Usage: fnm list-remote [OPTIONS] Options: --filter Filter versions by a user-defined version or a semver range --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --lts [] Show only LTS versions (optionally filter by LTS codename) --sort Version sorting order [default: asc] Possible values: - desc: Sort versions in descending order (latest to earliest) - asc: Sort versions in ascending order (earliest to latest) --latest Only show the latest matching version --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm list` ``` List all locally installed Node.js versions Usage: fnm list [OPTIONS] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm install` ``` Install a new Node.js version Usage: fnm install [OPTIONS] [VERSION] Arguments: [VERSION] A version string. Can be a partial semver or a LTS version name by the format lts/NAME Options: --lts Install latest LTS --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --latest Install latest version --progress Show an interactive progress bar for the download status [default: auto] [possible values: auto, never, always] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --use Use the installed version immediately after installation --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm use` ``` Change Node.js version Usage: fnm use [OPTIONS] [VERSION] Arguments: [VERSION] Options: --install-if-missing Install the version if it isn't installed yet --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --silent-if-unchanged Don't output a message identifying the version being used if it will not change due to execution of this command --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm env` ``` Print and set up required environment variables for fnm This command generates a series of shell commands that should be evaluated by your shell to create a fnm-ready environment. Each shell has its own syntax of evaluating a dynamic expression. For example, evaluating fnm on Bash and Zsh would look like `eval "$(fnm env --shell bash)"`. In Fish, evaluating would look like `fnm env --shell fish | source` Usage: fnm env [OPTIONS] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --shell The shell syntax to use. Infers when missing [possible values: bash, zsh, fish, powershell] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --json Print JSON instead of shell commands --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --use-on-cd Print the script to change Node versions every directory change --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm completions` ``` Print shell completions to stdout Usage: fnm completions [OPTIONS] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --shell The shell syntax to use. Infers when missing [possible values: bash, zsh, fish, powershell] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm alias` ``` Alias a version to a common name Usage: fnm alias [OPTIONS] Arguments: Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm unalias` ``` Remove an alias definition Usage: fnm unalias [OPTIONS] Arguments: Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm default` ``` Set a version as the default version or get the current default version. This is a shorthand for `fnm alias VERSION default` Usage: fnm default [OPTIONS] [VERSION] Arguments: [VERSION] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm current` ``` Print the current Node.js version Usage: fnm current [OPTIONS] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm exec` ``` Run a command within fnm context Example: -------- fnm exec --using=v12.0.0 node --version => v12.0.0 Usage: fnm exec [OPTIONS] [ARGUMENTS]... Arguments: [ARGUMENTS]... The command to run Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --using Either an explicit version, or a filename with the version written in it --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm uninstall` ``` Uninstall a Node.js version > Warning: when providing an alias, it will remove the Node version the alias > is pointing to, along with the other aliases that point to the same version. Usage: fnm uninstall [OPTIONS] [VERSION] Arguments: [VERSION] Options: --node-dist-mirror mirror [env: FNM_NODE_DIST_MIRROR] [default: https://nodejs.org/dist] --fnm-dir The root directory of fnm installations [env: FNM_DIR] --log-level The log level of fnm commands [env: FNM_LOGLEVEL] [default: info] [possible values: quiet, error, info] --arch Override the architecture of the installed Node binary. Defaults to arch of fnm binary [env: FNM_ARCH] --version-file-strategy A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is called without a version, or when `--use-on-cd` is configured on evaluation [env: FNM_VERSION_FILE_STRATEGY] [default: local] Possible values: - local: Use the local version of Node defined within the current directory - recursive: Use the version of Node defined within the current directory and all parent directories --corepack-enabled Enable corepack support for each new installation. This will make fnm call `corepack enable` on every Node.js installation. For more information about corepack see [env: FNM_COREPACK_ENABLED] --resolve-engines [] Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. This feature is enabled by default. To disable it, provide `--resolve-engines=false`. Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. In the future, disabling it might be a no-op, so it's worth knowing any reason to do that. [env: FNM_RESOLVE_ENGINES] [possible values: true, false] -h, --help Print help (see a summary with '-h') ``` # `fnm help` ``` ``` ================================================ FILE: docs/configuration.md ================================================ # Configuration fnm comes with many features out of the box. Some of them are not activated by default as they’re changing your shell default behavior, and some are just a feature flag to avoid breaking changes or just experimental until we decide it is worthwhile to introduce them. All these features can be configured by adding flags to the `fnm env` call when initializing the shell. For instance, if your shell set up looks like `eval "$(fnm env)"` then you can add a flag to it by changing it to `eval "$(fnm env --my-flag=value)"` Here’s a list of these features and capabilities: ### `--use-on-cd` **✅ Highly recommended** `--use-on-cd` appends output to `fnm env`'s output that will hook into your shell upon changing directories, and will switch the Node.js version based on the requirements of the current directory, based on `.node-version` or `.nvmrc` (or `packages.json#engines#node` if `--resolve-engines` was enabled). This allows you do avoid thinking about `fnm use`, and only `cd ` to make it work. ### `--version-file-strategy=recursive` **✅ Highly recommended** Makes `fnm use` and `fnm install` take parent directories into account when looking for a version file ("dotfile")--when no argument was given. So, let's say we have the following directory structure: ``` repo/ ├── package.json ├── .node-version <- with content: `20.0.0` └── packages/ └── my-package/ <- I am here └── package.json ``` And I'm running the following command: ```sh-session repo/packages/my-package$ fnm use ``` Then fnm will switch to Node.js v20.0.0. Without the explicit flag, the value is set to `local`, which will not traverse the directory tree and therefore will print: ```sh-session repo/packages/my-package$ fnm use error: Can't find version in dotfiles. Please provide a version manually to the command. ``` ### `--corepack-enabled` **🧪 Experimental** Runs [`corepack enable`](https://nodejs.org/api/corepack.html#enabling-the-feature) when a new version of Node.js is installed. Experimental due to the fact Corepack itself is experimental. ### `--resolve-engines` **🧪 Experimental** Treats `package.json#engines#node` as a valid Node.js version file ("dotfile"). So, if you have a package.json with the following content: ```json { "engines": { "node": ">=20 <21" } } ``` Then: - `fnm install` will install the latest satisfying Node.js 20.x version available in the Node.js dist server - `fnm use` will use the latest satisfying Node.js 20.x version available on your system, or prompt to install if no version matched. ================================================ FILE: docs/nightly.md ================================================ # Working with Node nightly builds fnm doesn't give you any shorthands to install nightly builds, but you can do that by manually passing a "dist mirror" with the `--node-dist-mirror` flag. ## Example usage Here's an example of installing Node 23. To get a list of available versions run this: fnm --node-dist-mirror https://nodejs.org/download/nightly/ ls-remote To use and install nightly version run this: fnm --node-dist-mirror https://nodejs.org/download/nightly/ use 23 # or fnm --node-dist-mirror https://nodejs.org/download/nightly/ use v23.0.0-nightly202407253de7a4c374 Once you installed it you would be able to see that version in you list: fnm ls And use it without providing `--node-dist-mirror` flag: fnm use 23 ================================================ FILE: e2e/__snapshots__/aliases.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash aliasing versions: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install 6.11.3 fnm install 8.11.3 fnm alias 8.11 oldie fnm alias 6 older fnm default older ((fnm ls) | grep 8.11.3 || (echo "Expected output to contain 8.11.3" && exit 1)) | grep oldie || (echo "Expected output to contain oldie" && exit 1) ((fnm ls) | grep 6.11.3 || (echo "Expected output to contain 6.11.3" && exit 1)) | grep older || (echo "Expected output to contain older" && exit 1) fnm use older if [ "$(node --version)" != "v6.11.3" ]; then echo "Expected node version to be v6.11.3. Got $(node --version)" exit 1 fi fnm use oldie if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi fnm use default if [ "$(node --version)" != "v6.11.3" ]; then echo "Expected node version to be v6.11.3. Got $(node --version)" exit 1 fi" `; exports[`Bash allows to install an lts if version missing: Bash 1`] = ` "set -e eval "$(fnm env)" fnm use --install-if-missing (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1)" `; exports[`Bash can alias the system node: Bash 1`] = ` "set -e eval "$(fnm env)" fnm alias system my_system (fnm ls) | grep my_system || (echo "Expected output to contain my_system" && exit 1) fnm alias system default fnm alias my_system my_system2 (fnm ls) | grep my_system2 || (echo "Expected output to contain my_system2" && exit 1) (fnm use my_system) | grep 'Bypassing fnm' || (echo "Expected output to contain 'Bypassing fnm'" && exit 1) fnm unalias my_system (fnm use my_system 2>&1) | grep 'Requested version my_system is not currently installed' || (echo "Expected output to contain 'Requested version my_system is not currently installed'" && exit 1)" `; exports[`Bash errors when alias is not found: Bash 1`] = ` "set -e eval "$(fnm env --log-level=error)" (fnm use 2>&1) | grep 'Requested version lts-latest is not' || (echo "Expected output to contain 'Requested version lts-latest is not'" && exit 1)" `; exports[`Bash installs aliases when corepack is enabled: Bash 1`] = ` "set -e eval "$(fnm env --corepack-enabled)" fnm use --install-if-missing (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1)" `; exports[`Bash unalias a version: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install 11.10.0 fnm install 8.11.3 fnm alias 8.11.3 version8 (fnm ls) | grep version8 || (echo "Expected output to contain version8" && exit 1) fnm unalias version8 (fnm use version8 2>&1) | grep 'Requested version version8 is not currently installed' || (echo "Expected output to contain 'Requested version version8 is not currently installed'" && exit 1)" `; exports[`Bash unalias errors if alias not found: Bash 1`] = ` "set -e eval "$(fnm env --log-level=error)" (fnm unalias lts 2>&1) | grep 'Requested alias lts not found' || (echo "Expected output to contain 'Requested alias lts not found'" && exit 1)" `; exports[`Fish aliasing versions: Fish 1`] = ` "fnm env | source fnm install 6.11.3 fnm install 8.11.3 fnm alias 8.11 oldie fnm alias 6 older fnm default older begin; begin; fnm ls; end | grep 8.11.3; or echo "Expected output to contain 8.11.3" && exit 1; end | grep oldie; or echo "Expected output to contain oldie" && exit 1 begin; begin; fnm ls; end | grep 6.11.3; or echo "Expected output to contain 6.11.3" && exit 1; end | grep older; or echo "Expected output to contain older" && exit 1 fnm use older set ____test____ (node --version) if test "$____test____" != "v6.11.3" echo "Expected node version to be v6.11.3. Got $____test____" exit 1 end fnm use oldie set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end fnm use default set ____test____ (node --version) if test "$____test____" != "v6.11.3" echo "Expected node version to be v6.11.3. Got $____test____" exit 1 end" `; exports[`Fish allows to install an lts if version missing: Fish 1`] = ` "fnm env | source fnm use --install-if-missing begin; fnm ls; end | grep lts-latest; or echo "Expected output to contain lts-latest" && exit 1" `; exports[`Fish can alias the system node: Fish 1`] = ` "fnm env | source fnm alias system my_system begin; fnm ls; end | grep my_system; or echo "Expected output to contain my_system" && exit 1 fnm alias system default fnm alias my_system my_system2 begin; fnm ls; end | grep my_system2; or echo "Expected output to contain my_system2" && exit 1 begin; fnm use my_system; end | grep 'Bypassing fnm'; or echo "Expected output to contain 'Bypassing fnm'" && exit 1 fnm unalias my_system begin; fnm use my_system 2>&1; end | grep 'Requested version my_system is not currently installed'; or echo "Expected output to contain 'Requested version my_system is not currently installed'" && exit 1" `; exports[`Fish errors when alias is not found: Fish 1`] = ` "fnm env --log-level=error | source begin; fnm use 2>&1; end | grep 'Requested version lts-latest is not'; or echo "Expected output to contain 'Requested version lts-latest is not'" && exit 1" `; exports[`Fish installs aliases when corepack is enabled: Fish 1`] = ` "fnm env --corepack-enabled | source fnm use --install-if-missing begin; fnm ls; end | grep lts-latest; or echo "Expected output to contain lts-latest" && exit 1" `; exports[`Fish unalias a version: Fish 1`] = ` "fnm env | source fnm install 11.10.0 fnm install 8.11.3 fnm alias 8.11.3 version8 begin; fnm ls; end | grep version8; or echo "Expected output to contain version8" && exit 1 fnm unalias version8 begin; fnm use version8 2>&1; end | grep 'Requested version version8 is not currently installed'; or echo "Expected output to contain 'Requested version version8 is not currently installed'" && exit 1" `; exports[`Fish unalias errors if alias not found: Fish 1`] = ` "fnm env --log-level=error | source begin; fnm unalias lts 2>&1; end | grep 'Requested alias lts not found'; or echo "Expected output to contain 'Requested alias lts not found'" && exit 1" `; exports[`PowerShell aliasing versions: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install 6.11.3 fnm install 8.11.3 fnm alias 8.11 oldie fnm alias 6 older fnm default older $($__out__ = $($($__out__ = $(fnm ls | Select-String 8.11.3); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) | Select-String oldie); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) $($__out__ = $($($__out__ = $(fnm ls | Select-String 6.11.3); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) | Select-String older); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm use older if ( "$(node --version)" -ne "v6.11.3" ) { echo "Expected node version to be v6.11.3. Got $(node --version)"; exit 1 } fnm use oldie if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 } fnm use default if ( "$(node --version)" -ne "v6.11.3" ) { echo "Expected node version to be v6.11.3. Got $(node --version)"; exit 1 }" `; exports[`PowerShell allows to install an lts if version missing: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm use --install-if-missing $($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`PowerShell can alias the system node: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm alias system my_system $($__out__ = $(fnm ls | Select-String my_system); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm alias system default fnm alias my_system my_system2 $($__out__ = $(fnm ls | Select-String my_system2); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) $($__out__ = $(fnm use my_system | Select-String 'Bypassing fnm'); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm unalias my_system $($__out__ = $(fnm use my_system 2>&1 | Select-String 'Requested version my_system is not currently installed'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`PowerShell errors when alias is not found: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --log-level=error | Out-String | Invoke-Expression $($__out__ = $(fnm use 2>&1 | Select-String 'Requested version lts-latest is not'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`PowerShell installs aliases when corepack is enabled: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --corepack-enabled | Out-String | Invoke-Expression fnm use --install-if-missing $($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`PowerShell unalias a version: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install 11.10.0 fnm install 8.11.3 fnm alias 8.11.3 version8 $($__out__ = $(fnm ls | Select-String version8); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm unalias version8 $($__out__ = $(fnm use version8 2>&1 | Select-String 'Requested version version8 is not currently installed'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`PowerShell unalias errors if alias not found: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --log-level=error | Out-String | Invoke-Expression $($__out__ = $(fnm unalias lts 2>&1 | Select-String 'Requested alias lts not found'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`Zsh aliasing versions: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install 6.11.3 fnm install 8.11.3 fnm alias 8.11 oldie fnm alias 6 older fnm default older ((fnm ls) | grep 8.11.3 || (echo "Expected output to contain 8.11.3" && exit 1)) | grep oldie || (echo "Expected output to contain oldie" && exit 1) ((fnm ls) | grep 6.11.3 || (echo "Expected output to contain 6.11.3" && exit 1)) | grep older || (echo "Expected output to contain older" && exit 1) fnm use older if [ "$(node --version)" != "v6.11.3" ]; then echo "Expected node version to be v6.11.3. Got $(node --version)" exit 1 fi fnm use oldie if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi fnm use default if [ "$(node --version)" != "v6.11.3" ]; then echo "Expected node version to be v6.11.3. Got $(node --version)" exit 1 fi" `; exports[`Zsh allows to install an lts if version missing: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm use --install-if-missing (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1)" `; exports[`Zsh can alias the system node: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm alias system my_system (fnm ls) | grep my_system || (echo "Expected output to contain my_system" && exit 1) fnm alias system default fnm alias my_system my_system2 (fnm ls) | grep my_system2 || (echo "Expected output to contain my_system2" && exit 1) (fnm use my_system) | grep 'Bypassing fnm' || (echo "Expected output to contain 'Bypassing fnm'" && exit 1) fnm unalias my_system (fnm use my_system 2>&1) | grep 'Requested version my_system is not currently installed' || (echo "Expected output to contain 'Requested version my_system is not currently installed'" && exit 1)" `; exports[`Zsh errors when alias is not found: Zsh 1`] = ` "set -e eval "$(fnm env --log-level=error)" (fnm use 2>&1) | grep 'Requested version lts-latest is not' || (echo "Expected output to contain 'Requested version lts-latest is not'" && exit 1)" `; exports[`Zsh installs aliases when corepack is enabled: Zsh 1`] = ` "set -e eval "$(fnm env --corepack-enabled)" fnm use --install-if-missing (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1)" `; exports[`Zsh unalias a version: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install 11.10.0 fnm install 8.11.3 fnm alias 8.11.3 version8 (fnm ls) | grep version8 || (echo "Expected output to contain version8" && exit 1) fnm unalias version8 (fnm use version8 2>&1) | grep 'Requested version version8 is not currently installed' || (echo "Expected output to contain 'Requested version version8 is not currently installed'" && exit 1)" `; exports[`Zsh unalias errors if alias not found: Zsh 1`] = ` "set -e eval "$(fnm env --log-level=error)" (fnm unalias lts 2>&1) | grep 'Requested alias lts not found' || (echo "Expected output to contain 'Requested alias lts not found'" && exit 1)" `; ================================================ FILE: e2e/__snapshots__/basic.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash .node-version: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Bash .nvmrc: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Bash \`fnm ls\` with nothing installed: Bash 1`] = ` "set -e eval "$(fnm env)" if [ "$(fnm ls)" != "* system" ]; then echo "Expected fnm ls to be * system. Got $(fnm ls)" exit 1 fi" `; exports[`Bash basic usage: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 fnm use v8.11.3 if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Bash package.json engines.node with semver range: Bash 1`] = ` "set -e eval "$(fnm env --resolve-engines)" fnm install fnm use if [ "$(node --version)" != "v6.17.0" ]; then echo "Expected node version to be v6.17.0. Got $(node --version)" exit 1 fi" `; exports[`Bash package.json engines.node: Bash 1`] = ` "set -e eval "$(fnm env --resolve-engines)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Bash resolves partial semver: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install 6 fnm use 6 if [ "$(node --version)" != "v6.17.1" ]; then echo "Expected node version to be v6.17.1. Got $(node --version)" exit 1 fi" `; exports[`Bash when .node-version and .nvmrc are in sync, it throws no error: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v11.10.0" ]; then echo "Expected node version to be v11.10.0. Got $(node --version)" exit 1 fi" `; exports[`Fish .node-version: Fish 1`] = ` "fnm env | source fnm install fnm use set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end" `; exports[`Fish .nvmrc: Fish 1`] = ` "fnm env | source fnm install fnm use set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end" `; exports[`Fish \`fnm ls\` with nothing installed: Fish 1`] = ` "fnm env | source set ____test____ (fnm ls) if test "$____test____" != "* system" echo "Expected fnm ls to be * system. Got $____test____" exit 1 end" `; exports[`Fish basic usage: Fish 1`] = ` "fnm env | source fnm install v8.11.3 fnm use v8.11.3 set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end" `; exports[`Fish package.json engines.node with semver range: Fish 1`] = ` "fnm env --resolve-engines | source fnm install fnm use set ____test____ (node --version) if test "$____test____" != "v6.17.0" echo "Expected node version to be v6.17.0. Got $____test____" exit 1 end" `; exports[`Fish package.json engines.node: Fish 1`] = ` "fnm env --resolve-engines | source fnm install fnm use set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end" `; exports[`Fish resolves partial semver: Fish 1`] = ` "fnm env | source fnm install 6 fnm use 6 set ____test____ (node --version) if test "$____test____" != "v6.17.1" echo "Expected node version to be v6.17.1. Got $____test____" exit 1 end" `; exports[`Fish when .node-version and .nvmrc are in sync, it throws no error: Fish 1`] = ` "fnm env | source fnm install fnm use set ____test____ (node --version) if test "$____test____" != "v11.10.0" echo "Expected node version to be v11.10.0. Got $____test____" exit 1 end" `; exports[`PowerShell .node-version: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install fnm use if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 }" `; exports[`PowerShell .nvmrc: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install fnm use if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 }" `; exports[`PowerShell \`fnm ls\` with nothing installed: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression if ( "$(fnm ls)" -ne "* system" ) { echo "Expected fnm ls to be * system. Got $(fnm ls)"; exit 1 }" `; exports[`PowerShell basic usage: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install v8.11.3 fnm use v8.11.3 if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 }" `; exports[`PowerShell package.json engines.node with semver range: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --resolve-engines | Out-String | Invoke-Expression fnm install fnm use if ( "$(node --version)" -ne "v6.17.0" ) { echo "Expected node version to be v6.17.0. Got $(node --version)"; exit 1 }" `; exports[`PowerShell package.json engines.node: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --resolve-engines | Out-String | Invoke-Expression fnm install fnm use if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 }" `; exports[`PowerShell resolves partial semver: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install 6 fnm use 6 if ( "$(node --version)" -ne "v6.17.1" ) { echo "Expected node version to be v6.17.1. Got $(node --version)"; exit 1 }" `; exports[`PowerShell when .node-version and .nvmrc are in sync, it throws no error: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install fnm use if ( "$(node --version)" -ne "v11.10.0" ) { echo "Expected node version to be v11.10.0. Got $(node --version)"; exit 1 }" `; exports[`Zsh .node-version: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Zsh .nvmrc: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Zsh \`fnm ls\` with nothing installed: Zsh 1`] = ` "set -e eval "$(fnm env)" if [ "$(fnm ls)" != "* system" ]; then echo "Expected fnm ls to be * system. Got $(fnm ls)" exit 1 fi" `; exports[`Zsh basic usage: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 fnm use v8.11.3 if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Zsh package.json engines.node with semver range: Zsh 1`] = ` "set -e eval "$(fnm env --resolve-engines)" fnm install fnm use if [ "$(node --version)" != "v6.17.0" ]; then echo "Expected node version to be v6.17.0. Got $(node --version)" exit 1 fi" `; exports[`Zsh package.json engines.node: Zsh 1`] = ` "set -e eval "$(fnm env --resolve-engines)" fnm install fnm use if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Zsh resolves partial semver: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install 6 fnm use 6 if [ "$(node --version)" != "v6.17.1" ]; then echo "Expected node version to be v6.17.1. Got $(node --version)" exit 1 fi" `; exports[`Zsh when .node-version and .nvmrc are in sync, it throws no error: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use if [ "$(node --version)" != "v11.10.0" ]; then echo "Expected node version to be v11.10.0. Got $(node --version)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/corepack.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash installs corepack: Bash 1`] = ` "set -e eval "$(fnm env --corepack-enabled)" fnm install 18 fnm exec --using=18 node test-pnpm-corepack.js" `; exports[`Fish installs corepack: Fish 1`] = ` "fnm env --corepack-enabled | source fnm install 18 fnm exec --using=18 node test-pnpm-corepack.js" `; exports[`PowerShell installs corepack: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --corepack-enabled | Out-String | Invoke-Expression fnm install 18 fnm exec --using=18 node test-pnpm-corepack.js" `; exports[`Zsh installs corepack: Zsh 1`] = ` "set -e eval "$(fnm env --corepack-enabled)" fnm install 18 fnm exec --using=18 node test-pnpm-corepack.js" `; ================================================ FILE: e2e/__snapshots__/current.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash current returns the current Node.js version set in fnm: Bash 1`] = ` "set -e eval "$(fnm env)" if [ "$(fnm current)" != "none" ]; then echo "Expected currently activated version to be none. Got $(fnm current)" exit 1 fi fnm install v8.11.3 fnm install v10.10.0 fnm use v8.11.3 if [ "$(fnm current)" != "v8.11.3" ]; then echo "Expected currently activated version to be v8.11.3. Got $(fnm current)" exit 1 fi fnm use v10.10.0 if [ "$(fnm current)" != "v10.10.0" ]; then echo "Expected currently activated version to be v10.10.0. Got $(fnm current)" exit 1 fi fnm use system if [ "$(fnm current)" != "system" ]; then echo "Expected currently activated version to be system. Got $(fnm current)" exit 1 fi" `; exports[`Fish current returns the current Node.js version set in fnm: Fish 1`] = ` "fnm env | source set ____test____ (fnm current) if test "$____test____" != "none" echo "Expected currently activated version to be none. Got $____test____" exit 1 end fnm install v8.11.3 fnm install v10.10.0 fnm use v8.11.3 set ____test____ (fnm current) if test "$____test____" != "v8.11.3" echo "Expected currently activated version to be v8.11.3. Got $____test____" exit 1 end fnm use v10.10.0 set ____test____ (fnm current) if test "$____test____" != "v10.10.0" echo "Expected currently activated version to be v10.10.0. Got $____test____" exit 1 end fnm use system set ____test____ (fnm current) if test "$____test____" != "system" echo "Expected currently activated version to be system. Got $____test____" exit 1 end" `; exports[`PowerShell current returns the current Node.js version set in fnm: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression if ( "$(fnm current)" -ne "none" ) { echo "Expected currently activated version to be none. Got $(fnm current)"; exit 1 } fnm install v8.11.3 fnm install v10.10.0 fnm use v8.11.3 if ( "$(fnm current)" -ne "v8.11.3" ) { echo "Expected currently activated version to be v8.11.3. Got $(fnm current)"; exit 1 } fnm use v10.10.0 if ( "$(fnm current)" -ne "v10.10.0" ) { echo "Expected currently activated version to be v10.10.0. Got $(fnm current)"; exit 1 } fnm use system if ( "$(fnm current)" -ne "system" ) { echo "Expected currently activated version to be system. Got $(fnm current)"; exit 1 }" `; exports[`Zsh current returns the current Node.js version set in fnm: Zsh 1`] = ` "set -e eval "$(fnm env)" if [ "$(fnm current)" != "none" ]; then echo "Expected currently activated version to be none. Got $(fnm current)" exit 1 fi fnm install v8.11.3 fnm install v10.10.0 fnm use v8.11.3 if [ "$(fnm current)" != "v8.11.3" ]; then echo "Expected currently activated version to be v8.11.3. Got $(fnm current)" exit 1 fi fnm use v10.10.0 if [ "$(fnm current)" != "v10.10.0" ]; then echo "Expected currently activated version to be v10.10.0. Got $(fnm current)" exit 1 fi fnm use system if [ "$(fnm current)" != "system" ]; then echo "Expected currently activated version to be system. Got $(fnm current)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/env.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash outputs json: Bash 1`] = ` "set -e fnm env --json > file.json" `; exports[`Fish outputs json: Fish 1`] = `"fnm env --json > file.json"`; exports[`PowerShell outputs json: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --json | Out-File file.json -Encoding UTF8" `; exports[`Zsh outputs json: Zsh 1`] = ` "set -e fnm env --json > file.json" `; ================================================ FILE: e2e/__snapshots__/exec.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash \`exec\` usage: Bash 1`] = ` "set -e fnm install fnm install v6.10.0 fnm install v10.10.0 if [ "$(fnm exec -- node -v)" != "v8.10.0" ]; then echo "Expected version file exec to be v8.10.0. Got $(fnm exec -- node -v)" exit 1 fi if [ "$(fnm exec --using=6 -- node -v)" != "v6.10.0" ]; then echo "Expected exec:6 node -v to be v6.10.0. Got $(fnm exec --using=6 -- node -v)" exit 1 fi if [ "$(fnm exec --using=10 -- node -v)" != "v10.10.0" ]; then echo "Expected exec:6 node -v to be v10.10.0. Got $(fnm exec --using=10 -- node -v)" exit 1 fi" `; exports[`Fish \`exec\` usage: Fish 1`] = ` "fnm install fnm install v6.10.0 fnm install v10.10.0 set ____test____ (fnm exec -- node -v) if test "$____test____" != "v8.10.0" echo "Expected version file exec to be v8.10.0. Got $____test____" exit 1 end set ____test____ (fnm exec --using=6 -- node -v) if test "$____test____" != "v6.10.0" echo "Expected exec:6 node -v to be v6.10.0. Got $____test____" exit 1 end set ____test____ (fnm exec --using=10 -- node -v) if test "$____test____" != "v10.10.0" echo "Expected exec:6 node -v to be v10.10.0. Got $____test____" exit 1 end" `; exports[`PowerShell \`exec\` usage: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm install fnm install v6.10.0 fnm install v10.10.0 if ( "$(fnm exec -- node -v)" -ne "v8.10.0" ) { echo "Expected version file exec to be v8.10.0. Got $(fnm exec -- node -v)"; exit 1 } if ( "$(fnm exec --using=6 -- node -v)" -ne "v6.10.0" ) { echo "Expected exec:6 node -v to be v6.10.0. Got $(fnm exec --using=6 -- node -v)"; exit 1 } if ( "$(fnm exec --using=10 -- node -v)" -ne "v10.10.0" ) { echo "Expected exec:6 node -v to be v10.10.0. Got $(fnm exec --using=10 -- node -v)"; exit 1 }" `; exports[`Zsh \`exec\` usage: Zsh 1`] = ` "set -e fnm install fnm install v6.10.0 fnm install v10.10.0 if [ "$(fnm exec -- node -v)" != "v8.10.0" ]; then echo "Expected version file exec to be v8.10.0. Got $(fnm exec -- node -v)" exit 1 fi if [ "$(fnm exec --using=6 -- node -v)" != "v6.10.0" ]; then echo "Expected exec:6 node -v to be v6.10.0. Got $(fnm exec --using=6 -- node -v)" exit 1 fi if [ "$(fnm exec --using=10 -- node -v)" != "v10.10.0" ]; then echo "Expected exec:6 node -v to be v10.10.0. Got $(fnm exec --using=10 -- node -v)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/existing-installation.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash warns about an existing installation: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 (fnm install v8.11.3 2>&1) | grep 'already installed' || (echo "Expected output to contain 'already installed'" && exit 1)" `; exports[`Fish warns about an existing installation: Fish 1`] = ` "fnm env | source fnm install v8.11.3 begin; fnm install v8.11.3 2>&1; end | grep 'already installed'; or echo "Expected output to contain 'already installed'" && exit 1" `; exports[`PowerShell warns about an existing installation: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install v8.11.3 $($__out__ = $(fnm install v8.11.3 2>&1 | Select-String 'already installed'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`Zsh warns about an existing installation: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 (fnm install v8.11.3 2>&1) | grep 'already installed' || (echo "Expected output to contain 'already installed'" && exit 1)" `; ================================================ FILE: e2e/__snapshots__/latest-lts.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash installs latest lts: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install --lts (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1) fnm use 'lts/*'" `; exports[`Fish installs latest lts: Fish 1`] = ` "fnm env | source fnm install --lts begin; fnm ls; end | grep lts-latest; or echo "Expected output to contain lts-latest" && exit 1 fnm use 'lts/*'" `; exports[`PowerShell installs latest lts: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install --lts $($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm use 'lts/*'" `; exports[`Zsh installs latest lts: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install --lts (fnm ls) | grep lts-latest || (echo "Expected output to contain lts-latest" && exit 1) fnm use 'lts/*'" `; ================================================ FILE: e2e/__snapshots__/latest.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash installs latest: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install --latest (fnm ls) | grep latest || (echo "Expected output to contain latest" && exit 1) fnm use 'latest'" `; exports[`Fish installs latest: Fish 1`] = ` "fnm env | source fnm install --latest begin; fnm ls; end | grep latest; or echo "Expected output to contain latest" && exit 1 fnm use 'latest'" `; exports[`PowerShell installs latest: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install --latest $($__out__ = $(fnm ls | Select-String latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm use 'latest'" `; exports[`Zsh installs latest: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install --latest (fnm ls) | grep latest || (echo "Expected output to contain latest" && exit 1) fnm use 'latest'" `; ================================================ FILE: e2e/__snapshots__/log-level.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash "quiet" log level: Bash 1`] = ` "set -e eval "$(fnm env --log-level=quiet)" if [ "$(fnm install v8.11.3)" != "" ]; then echo "Expected fnm install to be . Got $(fnm install v8.11.3)" exit 1 fi if [ "$(fnm use v8.11.3)" != "" ]; then echo "Expected fnm use to be . Got $(fnm use v8.11.3)" exit 1 fi if [ "$(fnm alias v8.11.3 something)" != "" ]; then echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)" exit 1 fi" `; exports[`Bash error log level: Bash 1`] = ` "set -e eval "$(fnm env --log-level=error)" if [ "$(fnm install v8.11.3)" != "" ]; then echo "Expected fnm install to be . Got $(fnm install v8.11.3)" exit 1 fi if [ "$(fnm use v8.11.3)" != "" ]; then echo "Expected fnm use to be . Got $(fnm use v8.11.3)" exit 1 fi if [ "$(fnm alias v8.11.3 something)" != "" ]; then echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)" exit 1 fi (fnm alias abcd efg 2>&1) | grep "find requested version" || (echo "Expected output to contain "find requested version"" && exit 1)" `; exports[`Fish "quiet" log level: Fish 1`] = ` "fnm env --log-level=quiet | source set ____test____ (fnm install v8.11.3) if test "$____test____" != "" echo "Expected fnm install to be . Got $____test____" exit 1 end set ____test____ (fnm use v8.11.3) if test "$____test____" != "" echo "Expected fnm use to be . Got $____test____" exit 1 end set ____test____ (fnm alias v8.11.3 something) if test "$____test____" != "" echo "Expected fnm alias to be . Got $____test____" exit 1 end" `; exports[`Fish error log level: Fish 1`] = ` "fnm env --log-level=error | source set ____test____ (fnm install v8.11.3) if test "$____test____" != "" echo "Expected fnm install to be . Got $____test____" exit 1 end set ____test____ (fnm use v8.11.3) if test "$____test____" != "" echo "Expected fnm use to be . Got $____test____" exit 1 end set ____test____ (fnm alias v8.11.3 something) if test "$____test____" != "" echo "Expected fnm alias to be . Got $____test____" exit 1 end begin; fnm alias abcd efg 2>&1; end | grep "find requested version"; or echo "Expected output to contain "find requested version"" && exit 1" `; exports[`PowerShell "quiet" log level: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --log-level=quiet | Out-String | Invoke-Expression if ( "$(fnm install v8.11.3)" -ne "" ) { echo "Expected fnm install to be . Got $(fnm install v8.11.3)"; exit 1 } if ( "$(fnm use v8.11.3)" -ne "" ) { echo "Expected fnm use to be . Got $(fnm use v8.11.3)"; exit 1 } if ( "$(fnm alias v8.11.3 something)" -ne "" ) { echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)"; exit 1 }" `; exports[`PowerShell error log level: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --log-level=error | Out-String | Invoke-Expression if ( "$(fnm install v8.11.3)" -ne "" ) { echo "Expected fnm install to be . Got $(fnm install v8.11.3)"; exit 1 } if ( "$(fnm use v8.11.3)" -ne "" ) { echo "Expected fnm use to be . Got $(fnm use v8.11.3)"; exit 1 } if ( "$(fnm alias v8.11.3 something)" -ne "" ) { echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)"; exit 1 } $($__out__ = $(fnm alias abcd efg 2>&1 | Select-String "find requested version"); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`Zsh "quiet" log level: Zsh 1`] = ` "set -e eval "$(fnm env --log-level=quiet)" if [ "$(fnm install v8.11.3)" != "" ]; then echo "Expected fnm install to be . Got $(fnm install v8.11.3)" exit 1 fi if [ "$(fnm use v8.11.3)" != "" ]; then echo "Expected fnm use to be . Got $(fnm use v8.11.3)" exit 1 fi if [ "$(fnm alias v8.11.3 something)" != "" ]; then echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)" exit 1 fi" `; exports[`Zsh error log level: Zsh 1`] = ` "set -e eval "$(fnm env --log-level=error)" if [ "$(fnm install v8.11.3)" != "" ]; then echo "Expected fnm install to be . Got $(fnm install v8.11.3)" exit 1 fi if [ "$(fnm use v8.11.3)" != "" ]; then echo "Expected fnm use to be . Got $(fnm use v8.11.3)" exit 1 fi if [ "$(fnm alias v8.11.3 something)" != "" ]; then echo "Expected fnm alias to be . Got $(fnm alias v8.11.3 something)" exit 1 fi (fnm alias abcd efg 2>&1) | grep "find requested version" || (echo "Expected output to contain "find requested version"" && exit 1)" `; ================================================ FILE: e2e/__snapshots__/multishell.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash multishell changes don't affect parent: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 fnm install v11.9.0 echo 'set -e eval "$(fnm env)" fnm use v11 if [ "$(node --version)" != "v11.9.0" ]; then echo "Expected node version to be v11.9.0. Got $(node --version)" exit 1 fi' | bash if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; exports[`Fish multishell changes don't affect parent: Fish 1`] = ` "fnm env | source fnm install v8.11.3 fnm install v11.9.0 fish -c 'fnm env | source fnm use v11 set ____test____ (node --version) if test "$____test____" != "v11.9.0" echo "Expected node version to be v11.9.0. Got $____test____" exit 1 end' set ____test____ (node --version) if test "$____test____" != "v8.11.3" echo "Expected node version to be v8.11.3. Got $____test____" exit 1 end" `; exports[`PowerShell multishell changes don't affect parent: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install v8.11.3 fnm install v11.9.0 echo '$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm use v11 if ( "$(node --version)" -ne "v11.9.0" ) { echo "Expected node version to be v11.9.0. Got $(node --version)"; exit 1 }' | pwsh -NoProfile if ( "$(node --version)" -ne "v8.11.3" ) { echo "Expected node version to be v8.11.3. Got $(node --version)"; exit 1 }" `; exports[`Zsh multishell changes don't affect parent: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install v8.11.3 fnm install v11.9.0 echo 'set -e eval "$(fnm env)" fnm use v11 if [ "$(node --version)" != "v11.9.0" ]; then echo "Expected node version to be v11.9.0. Got $(node --version)" exit 1 fi' | zsh if [ "$(node --version)" != "v8.11.3" ]; then echo "Expected node version to be v8.11.3. Got $(node --version)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/nvmrc-lts.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash uses .nvmrc with lts definition: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use (fnm ls) | grep lts-dubnium || (echo "Expected output to contain lts-dubnium" && exit 1)" `; exports[`Fish uses .nvmrc with lts definition: Fish 1`] = ` "fnm env | source fnm install fnm use begin; fnm ls; end | grep lts-dubnium; or echo "Expected output to contain lts-dubnium" && exit 1" `; exports[`PowerShell uses .nvmrc with lts definition: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install fnm use $($__out__ = $(fnm ls | Select-String lts-dubnium); if ($__out__ -eq $null) { exit 1 } else { $__out__ })" `; exports[`Zsh uses .nvmrc with lts definition: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install fnm use (fnm ls) | grep lts-dubnium || (echo "Expected output to contain lts-dubnium" && exit 1)" `; ================================================ FILE: e2e/__snapshots__/old-versions.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash download old Node.js 0.10.x: Bash 1`] = ` "set -e eval "$(fnm env)" fnm install v0.10.36 fnm use v0.10.36 if [ "$(node --version)" != "v0.10.36" ]; then echo "Expected node version to be v0.10.36. Got $(node --version)" exit 1 fi" `; exports[`Fish download old Node.js 0.10.x: Fish 1`] = ` "fnm env | source fnm install v0.10.36 fnm use v0.10.36 set ____test____ (node --version) if test "$____test____" != "v0.10.36" echo "Expected node version to be v0.10.36. Got $____test____" exit 1 end" `; exports[`PowerShell download old Node.js 0.10.x: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env | Out-String | Invoke-Expression fnm install v0.10.36 fnm use v0.10.36 if ( "$(node --version)" -ne "v0.10.36" ) { echo "Expected node version to be v0.10.36. Got $(node --version)"; exit 1 }" `; exports[`Zsh download old Node.js 0.10.x: Zsh 1`] = ` "set -e eval "$(fnm env)" fnm install v0.10.36 fnm use v0.10.36 if [ "$(node --version)" != "v0.10.36" ]; then echo "Expected node version to be v0.10.36. Got $(node --version)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/uninstall.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash uninstalls a version: Bash 1`] = ` "set -e fnm i 12.0.0 fnm alias 12.0.0 hello ((fnm ls) | grep v12.0.0 || (echo "Expected output to contain v12.0.0" && exit 1)) | grep hello || (echo "Expected output to contain hello" && exit 1) fnm uni hello if [ "$(fnm ls)" != "* system" ]; then echo "Expected fnm ls to be * system. Got $(fnm ls)" exit 1 fi" `; exports[`Fish uninstalls a version: Fish 1`] = ` "fnm i 12.0.0 fnm alias 12.0.0 hello begin; begin; fnm ls; end | grep v12.0.0; or echo "Expected output to contain v12.0.0" && exit 1; end | grep hello; or echo "Expected output to contain hello" && exit 1 fnm uni hello set ____test____ (fnm ls) if test "$____test____" != "* system" echo "Expected fnm ls to be * system. Got $____test____" exit 1 end" `; exports[`PowerShell uninstalls a version: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm i 12.0.0 fnm alias 12.0.0 hello $($__out__ = $($($__out__ = $(fnm ls | Select-String v12.0.0); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) | Select-String hello); if ($__out__ -eq $null) { exit 1 } else { $__out__ }) fnm uni hello if ( "$(fnm ls)" -ne "* system" ) { echo "Expected fnm ls to be * system. Got $(fnm ls)"; exit 1 }" `; exports[`Zsh uninstalls a version: Zsh 1`] = ` "set -e fnm i 12.0.0 fnm alias 12.0.0 hello ((fnm ls) | grep v12.0.0 || (echo "Expected output to contain v12.0.0" && exit 1)) | grep hello || (echo "Expected output to contain hello" && exit 1) fnm uni hello if [ "$(fnm ls)" != "* system" ]; then echo "Expected fnm ls to be * system. Got $(fnm ls)" exit 1 fi" `; ================================================ FILE: e2e/__snapshots__/use-on-cd.test.ts.snap ================================================ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Bash use on cd: Bash 1`] = ` "set -e eval "$(fnm env --use-on-cd)" fnm install v8.11.3 fnm install v12.22.12 cd subdir if [ "$(node --version)" != "v12.22.12" ]; then echo "Expected node version to be v12.22.12. Got $(node --version)" exit 1 fi" `; exports[`Fish use on cd: Fish 1`] = ` "fnm env --use-on-cd | source fnm install v8.11.3 fnm install v12.22.12 cd subdir set ____test____ (node --version) if test "$____test____" != "v12.22.12" echo "Expected node version to be v12.22.12. Got $____test____" exit 1 end" `; exports[`PowerShell use on cd: PowerShell 1`] = ` "$ErrorActionPreference = "Stop" fnm env --use-on-cd | Out-String | Invoke-Expression fnm install v8.11.3 fnm install v12.22.12 cd subdir if ( "$(node --version)" -ne "v12.22.12" ) { echo "Expected node version to be v12.22.12. Got $(node --version)"; exit 1 }" `; exports[`Zsh use on cd: Zsh 1`] = ` "set -e eval "$(fnm env --use-on-cd)" fnm install v8.11.3 fnm install v12.22.12 cd subdir if [ "$(node --version)" != "v12.22.12" ]; then echo "Expected node version to be v12.22.12. Got $(node --version)" exit 1 fi" `; ================================================ FILE: e2e/aliases.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" import { writeFile } from "node:fs/promises" import path from "node:path" import testCwd from "./shellcode/test-cwd.js" import getStderr from "./shellcode/get-stderr.js" import testNodeVersion from "./shellcode/test-node-version.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`installs aliases when corepack is enabled`, async () => { await writeFile(path.join(testCwd(), ".node-version"), "lts/*") await script(shell) .then(shell.env({ corepackEnabled: true })) .then(shell.call("fnm", ["use", "--install-if-missing"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "lts-latest"), ) .takeSnapshot(shell) .execute(shell) }) test(`allows to install an lts if version missing`, async () => { await writeFile(path.join(testCwd(), ".node-version"), "lts/*") await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["use", "--install-if-missing"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "lts-latest"), ) .takeSnapshot(shell) .execute(shell) }) test(`errors when alias is not found`, async () => { await writeFile(path.join(testCwd(), ".node-version"), "lts/*") await script(shell) .then(shell.env({ logLevel: "error" })) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["use"])), "'Requested version lts-latest is not'", ), ) .takeSnapshot(shell) .execute(shell) }) test(`unalias a version`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "11.10.0"])) .then(shell.call("fnm", ["install", "8.11.3"])) .then(shell.call("fnm", ["alias", "8.11.3", "version8"])) .then(shell.scriptOutputContains(shell.call("fnm", ["ls"]), "version8")) .then(shell.call("fnm", ["unalias", "version8"])) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["use", "version8"])), "'Requested version version8 is not currently installed'", ), ) .takeSnapshot(shell) .execute(shell) }) test(`unalias errors if alias not found`, async () => { await script(shell) .then(shell.env({ logLevel: "error" })) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["unalias", "lts"])), "'Requested alias lts not found'", ), ) .takeSnapshot(shell) .execute(shell) }) test(`can alias the system node`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["alias", "system", "my_system"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "my_system"), ) .then(shell.call("fnm", ["alias", "system", "default"])) .then(shell.call("fnm", ["alias", "my_system", "my_system2"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "my_system2"), ) .then( shell.scriptOutputContains( shell.call("fnm", ["use", "my_system"]), "'Bypassing fnm'", ), ) .then(shell.call("fnm", ["unalias", "my_system"])) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["use", "my_system"])), "'Requested version my_system is not currently installed'", ), ) .takeSnapshot(shell) .execute(shell) }) test(`aliasing versions`, async () => { const installedVersions = shell.call("fnm", ["ls"]) await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "6.11.3"])) .then(shell.call("fnm", ["install", "8.11.3"])) .then(shell.call("fnm", ["alias", "8.11", "oldie"])) .then(shell.call("fnm", ["alias", "6", "older"])) .then(shell.call("fnm", ["default", "older"])) .then( shell.scriptOutputContains( shell.scriptOutputContains(installedVersions, "8.11.3"), "oldie", ), ) .then( shell.scriptOutputContains( shell.scriptOutputContains(installedVersions, "6.11.3"), "older", ), ) .then(shell.call("fnm", ["use", "older"])) .then(testNodeVersion(shell, "v6.11.3")) .then(shell.call("fnm", ["use", "oldie"])) .then(testNodeVersion(shell, "v8.11.3")) .then(shell.call("fnm", ["use", "default"])) .then(testNodeVersion(shell, "v6.11.3")) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/basic.test.ts ================================================ import { writeFile } from "node:fs/promises" import { join } from "node:path" import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testCwd from "./shellcode/test-cwd.js" import testNodeVersion from "./shellcode/test-node-version.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`basic usage`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["use", "v8.11.3"])) .then(testNodeVersion(shell, "v8.11.3")) .takeSnapshot(shell) .execute(shell) }) test(`.nvmrc`, async () => { await writeFile(join(testCwd(), ".nvmrc"), "v8.11.3") await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then(testNodeVersion(shell, "v8.11.3")) .takeSnapshot(shell) .execute(shell) }) test(`.node-version`, async () => { await writeFile(join(testCwd(), ".node-version"), "v8.11.3") await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then(testNodeVersion(shell, "v8.11.3")) .takeSnapshot(shell) .execute(shell) }) test(`package.json engines.node`, async () => { await writeFile( join(testCwd(), "package.json"), JSON.stringify({ engines: { node: "8.11.3" } }), ) await script(shell) .then(shell.env({ resolveEngines: true })) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then(testNodeVersion(shell, "v8.11.3")) .takeSnapshot(shell) .execute(shell) }) test(`package.json engines.node with semver range`, async () => { await writeFile( join(testCwd(), "package.json"), JSON.stringify({ engines: { node: "^6 < 6.17.1" } }), ) await script(shell) .then(shell.env({ resolveEngines: true })) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then(testNodeVersion(shell, "v6.17.0")) .takeSnapshot(shell) .execute(shell) }) test(`resolves partial semver`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "6"])) .then(shell.call("fnm", ["use", "6"])) .then(testNodeVersion(shell, "v6.17.1")) .takeSnapshot(shell) .execute(shell) }) test("`fnm ls` with nothing installed", async () => { await script(shell) .then(shell.env({})) .then( shell.hasCommandOutput( shell.call("fnm", ["ls"]), "* system", "fnm ls", ), ) .takeSnapshot(shell) .execute(shell) }) test(`when .node-version and .nvmrc are in sync, it throws no error`, async () => { await writeFile(join(testCwd(), ".nvmrc"), "v11.10.0") await writeFile(join(testCwd(), ".node-version"), "v11.10.0") await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then(testNodeVersion(shell, "v11.10.0")) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/corepack.test.ts ================================================ import fs from "fs" import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" import path from "path" import testCwd from "./shellcode/test-cwd.js" import { createRequire } from "module" const require = createRequire(import.meta.url) const whichPath = require.resolve("which") const nodescript = ` const which = require(${JSON.stringify(whichPath)}); const pnpmBinary = which.sync('pnpm') const nodeBinary = which.sync('node') const binPath = require('path').dirname(nodeBinary); if (!pnpmBinary.includes(binPath)) { console.log('pnpm not found in current Node.js bin', { binPath, pnpmBinary }); process.exit(1); } const scriptContents = require('fs').readFileSync(pnpmBinary, 'utf8'); console.log('scriptContents', scriptContents) if (!scriptContents.includes('corepack')) { console.log('corepack not found in pnpm script'); process.exit(1); } ` for (const shell of [Bash, Fish, PowerShell, Zsh]) { describe(shell, () => { test(`installs corepack`, async () => { const cwd = testCwd() const filepath = path.join(cwd, "test-pnpm-corepack.js") fs.writeFileSync(filepath, nodescript) await script(shell) .then(shell.env({ corepackEnabled: true })) .then(shell.call("fnm", ["install", "18"])) .then( shell.call("fnm", [ "exec", "--using=18", "node", "test-pnpm-corepack.js", ]) ) .takeSnapshot(shell) // .addExtraEnvVar("RUST_LOG", "fnm=debug") .execute(shell) }) }) } ================================================ FILE: e2e/current.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`current returns the current Node.js version set in fnm`, async () => { await script(shell) .then(shell.env({})) .then( shell.hasCommandOutput( shell.call("fnm", ["current"]), "none", "currently activated version" ) ) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v10.10.0"])) .then(shell.call("fnm", ["use", "v8.11.3"])) .then( shell.hasCommandOutput( shell.call("fnm", ["current"]), "v8.11.3", "currently activated version" ) ) .then(shell.call("fnm", ["use", "v10.10.0"])) .then( shell.hasCommandOutput( shell.call("fnm", ["current"]), "v10.10.0", "currently activated version" ) ) .then(shell.call("fnm", ["use", "system"])) .then( shell.hasCommandOutput( shell.call("fnm", ["current"]), "system", "currently activated version" ) ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/describe.ts ================================================ import { WinCmd } from "./shellcode/shells.js" import { Shell } from "./shellcode/shells/types.js" export default function describe( shell: Pick, fn: () => void ): void { if (shell === WinCmd) { // wincmd tests do not work right now and I don't have a Windows machine to fix it // maybe in the future when I have some time to spin a VM to check what's happening. return globalThis.describe.skip("WinCmd", fn) } globalThis.describe(shell.name(), fn) } ================================================ FILE: e2e/env.test.ts ================================================ import { readFile } from "node:fs/promises" import { join } from "node:path" import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testCwd from "./shellcode/test-cwd.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`outputs json`, async () => { const filename = `file.json` await script(shell) .then( shell.redirectOutput(shell.call("fnm", ["env", "--json"]), { output: filename, }), ) .takeSnapshot(shell) .execute(shell) if (shell.currentlySupported()) { const file = await readFile(join(testCwd(), filename), "utf8") expect(JSON.parse(file)).toEqual({ FNM_ARCH: expect.any(String), FNM_DIR: expect.any(String), FNM_LOGLEVEL: "info", FNM_MULTISHELL_PATH: expect.any(String), FNM_NODE_DIST_MIRROR: expect.any(String), FNM_RESOLVE_ENGINES: "true", FNM_COREPACK_ENABLED: "false", FNM_VERSION_FILE_STRATEGY: "local", }) } }) }) } ================================================ FILE: e2e/exec.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testCwd from "./shellcode/test-cwd.js" import fs from "node:fs/promises" import path from "node:path" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test("`exec` usage", async () => { await fs.writeFile(path.join(testCwd(), ".nvmrc"), "v8.10.0") await script(shell) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["install", "v6.10.0"])) .then(shell.call("fnm", ["install", "v10.10.0"])) .then( shell.hasCommandOutput( shell.call("fnm", ["exec", "--", "node", "-v"]), "v8.10.0", "version file exec" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["exec", "--using=6", "--", "node", "-v"]), "v6.10.0", "exec:6 node -v" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["exec", "--using=10", "--", "node", "-v"]), "v10.10.0", "exec:6 node -v" ) ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/existing-installation.test.ts ================================================ import getStderr from "./shellcode/get-stderr.js" import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`warns about an existing installation`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v8.11.3"])) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["install", "v8.11.3"])), "'already installed'" ) ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/latest-lts.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`installs latest lts`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "--lts"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "lts-latest") ) .then(shell.call("fnm", ["use", "'lts/*'"])) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/latest.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`installs latest`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "--latest"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "latest") ) .then(shell.call("fnm", ["use", "'latest'"])) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/log-level.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" import getStderr from "./shellcode/get-stderr.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`"quiet" log level`, async () => { await script(shell) .then(shell.env({ logLevel: "quiet" })) .then( shell.hasCommandOutput( shell.call("fnm", ["install", "v8.11.3"]), "", "fnm install" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["use", "v8.11.3"]), "", "fnm use" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["alias", "v8.11.3", "something"]), "", "fnm alias" ) ) .takeSnapshot(shell) .execute(shell) }) test("error log level", async () => { await script(shell) .then(shell.env({ logLevel: "error" })) .then( shell.hasCommandOutput( shell.call("fnm", ["install", "v8.11.3"]), "", "fnm install" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["use", "v8.11.3"]), "", "fnm use" ) ) .then( shell.hasCommandOutput( shell.call("fnm", ["alias", "v8.11.3", "something"]), "", "fnm alias" ) ) .then( shell.scriptOutputContains( getStderr(shell.call("fnm", ["alias", "abcd", "efg"])), `"find requested version"` ) ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/multishell.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import testNodeVersion from "./shellcode/test-node-version.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`multishell changes don't affect parent`, async () => { await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v11.9.0"])) .then( shell.inSubShell( script(shell) .then(shell.env({})) .then(shell.call("fnm", ["use", "v11"])) .then(testNodeVersion(shell, "v11.9.0")) .asLine() ) ) .then(testNodeVersion(shell, "v8.11.3")) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/nvmrc-lts.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import fs from "node:fs/promises" import path from "node:path" import describe from "./describe.js" import testCwd from "./shellcode/test-cwd.js" for (const shell of [Bash, Fish, PowerShell, Zsh]) { describe(shell, () => { test(`uses .nvmrc with lts definition`, async () => { await fs.writeFile(path.join(testCwd(), ".nvmrc"), `lts/dubnium`) await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install"])) .then(shell.call("fnm", ["use"])) .then( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "lts-dubnium") ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/old-versions.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testNodeVersion from "./shellcode/test-node-version.js" import describe from "./describe.js" import os from "node:os" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`download old Node.js 0.10.x`, async () => { const testCase = script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v0.10.36"])) .then(shell.call("fnm", ["use", "v0.10.36"])) .then(testNodeVersion(shell, "v0.10.36")) .takeSnapshot(shell) if (os.platform() === "win32") { console.warn(`test skipped as 0.10.x isn't prebuilt for windows`) } else { await testCase.execute(shell) } }) }) } ================================================ FILE: e2e/shellcode/get-stderr.ts ================================================ export default function getStderr(script: string): string { return `${script} 2>&1` } ================================================ FILE: e2e/shellcode/script.ts ================================================ import { ScriptLine, Shell } from "./shells/types.js" import { execa, type ExecaChildProcess } from "execa" import testTmpDir from "./test-tmp-dir.js" import { Writable } from "node:stream" import { dedent } from "ts-dedent" import testCwd from "./test-cwd.js" import path, { join } from "node:path" import { writeFile } from "node:fs/promises" import chalk from "chalk" import testBinDir from "./test-bin-dir.js" import { rmSync } from "node:fs" class Script { constructor( private readonly config: { fnmDir: string }, private readonly lines: ScriptLine[], private readonly extraEnvVars: Record = {} ) {} then(line: ScriptLine): Script { return new Script(this.config, [...this.lines, line]) } takeSnapshot(shell: Pick): this { const script = this.lines.join("\n") expect(script).toMatchSnapshot(shell.name()) return this } addExtraEnvVar(name: string, value: string): this { return new Script( this.config, this.lines, Object.assign({}, this.extraEnvVars, { [name]: value }) ) as this } async execute( shell: Pick< Shell, "binaryName" | "launchArgs" | "currentlySupported" | "forceFile" > ): Promise { if (!shell.currentlySupported()) { return } const args = [...shell.launchArgs()] if (shell.forceFile) { let filename = join(testTmpDir(), "script") if (typeof shell.forceFile === "string") { filename = filename + shell.forceFile } await writeFile(filename, [...this.lines, "exit 0"].join("\n")) args.push(filename) } const child = execa(shell.binaryName(), args, { stdio: [shell.forceFile ? "ignore" : "pipe", "pipe", "pipe"], cwd: testCwd(), env: (() => { const newProcessEnv: Record = { ...this.extraEnvVars, ...removeAllFnmEnvVars(process.env), PATH: [testBinDir(), fnmTargetDir(), process.env.PATH] .filter(Boolean) .join(path.delimiter), FNM_DIR: this.config.fnmDir, FNM_NODE_DIST_MIRROR: "http://localhost:8080", } delete newProcessEnv.NODE_OPTIONS return newProcessEnv })(), extendEnv: false, reject: false, }) if (child.stdin) { const childStdin = child.stdin for (const line of this.lines) { await write(childStdin, `${line}\n`) } await write(childStdin, "exit 0\n") } const { stdout, stderr } = streamOutputsAndBuffer(child) const finished = await child if (finished.failed) { console.error( dedent` Script failed. code ${finished.exitCode} signal ${finished.signal} stdout: ${padAllLines(stdout.join(""), 2)} stderr: ${padAllLines(stderr.join(""), 2)} ` ) throw new Error( `Script failed on ${testCwd()} with code ${finished.exitCode}` ) } } asLine(): ScriptLine { return this.lines.join("\n") } } function streamOutputsAndBuffer(child: ExecaChildProcess) { const stdout: string[] = [] const stderr: string[] = [] const testName = expect.getState().currentTestName ?? "unknown" const testPath = expect.getState().testPath ?? "unknown" const stdoutPrefix = chalk.cyan.dim(`[stdout] ${testPath}/${testName}: `) const stderrPrefix = chalk.magenta.dim(`[stderr] ${testPath}/${testName}: `) if (child.stdout) { child.stdout.on("data", (data) => { const lines = data.toString().trim().split(/\r?\n/) for (const line of lines) { process.stdout.write(`${stdoutPrefix}${line}\n`) } stdout.push(data.toString()) }) } if (child.stderr) { child.stderr.on("data", (data) => { const lines = data.toString().trim().split(/\r?\n/) for (const line of lines) { process.stdout.write(`${stderrPrefix}${line}\n`) } stderr.push(data.toString()) }) } return { stdout, stderr } } function padAllLines(text: string, padding: number): string { return text .split("\n") .map((line) => " ".repeat(padding) + line) .join("\n") } function write(writable: Writable, text: string): Promise { return new Promise((resolve, reject) => { writable.write(text, (err) => { if (err) return reject(err) return resolve() }) }) } export function script(shell: Pick): Script { const fnmDir = path.join(testTmpDir(), "fnm") rmSync(join(fnmDir, "aliases"), { recursive: true, force: true }) return new Script({ fnmDir }, shell.dieOnErrors ? [shell.dieOnErrors()] : []) } function removeAllFnmEnvVars(obj: NodeJS.ProcessEnv): NodeJS.ProcessEnv { const result: NodeJS.ProcessEnv = {} for (const [key, value] of Object.entries(obj)) { if (!key.startsWith("FNM_")) { result[key] = value } } return result } function fnmTargetDir(): string { return path.join( process.cwd(), "target", process.env.FNM_TARGET_NAME ?? "debug" ) } ================================================ FILE: e2e/shellcode/shells/cmdCall.ts ================================================ import { define, ScriptLine } from "./types.js" export type HasCall = { call: (binary: string, args: string[]) => ScriptLine } export const cmdCall = { all: define({ call: (binary: string, args: string[]) => `${binary} ${args.join(" ")}` as ScriptLine, }), } ================================================ FILE: e2e/shellcode/shells/cmdEnv.ts ================================================ import { ScriptLine, define } from "./types.js" type EnvConfig = { executableName: string useOnCd: boolean logLevel: string corepackEnabled: boolean resolveEngines: boolean nodeDistMirror: string } export type HasEnv = { env(cfg: Partial): ScriptLine } function stringify(envConfig: Partial = {}) { const { useOnCd, logLevel, corepackEnabled, resolveEngines, executableName = "fnm", nodeDistMirror, } = envConfig return [ `${executableName} env`, useOnCd && "--use-on-cd", logLevel && `--log-level=${logLevel}`, corepackEnabled && "--corepack-enabled", resolveEngines && `--resolve-engines`, nodeDistMirror && `--node-dist-mirror=${JSON.stringify(nodeDistMirror)}`, ] .filter(Boolean) .join(" ") } export const cmdEnv = { bash: define({ env: (envConfig) => `eval "$(${stringify(envConfig)})"`, }), fish: define({ env: (envConfig) => `${stringify(envConfig)} | source`, }), powershell: define({ env: (envConfig) => `${stringify(envConfig)} | Out-String | Invoke-Expression`, }), wincmd: define({ env: (envConfig) => `FOR /f "tokens=*" %i IN ('${stringify(envConfig)}') DO CALL %i`, }), } ================================================ FILE: e2e/shellcode/shells/expect-command-output.ts ================================================ import { dedent } from "ts-dedent" import { define, ScriptLine } from "./types.js" export type HasExpectCommandOutput = { hasCommandOutput( script: ScriptLine, output: string, message: string ): ScriptLine } export const cmdExpectCommandOutput = { bash: define({ hasCommandOutput(script, output, message) { return dedent` if [ "$(${script})" != "${output}" ]; then echo "Expected ${message} to be ${output}. Got $(${script})" exit 1 fi ` }, }), fish: define({ hasCommandOutput(script, output, message) { return dedent` set ____test____ (${script}) if test "$____test____" != "${output}" echo "Expected ${message} to be ${output}. Got $____test____" exit 1 end ` }, }), powershell: define({ hasCommandOutput(script, output, message) { return dedent` if ( "$(${script})" -ne "${output}" ) { echo "Expected ${message} to be ${output}. Got $(${script})"; exit 1 } ` }, }), wincmd: define({ hasCommandOutput(script, output, message) { return dedent` ${script} | findstr ${output} if %errorlevel% neq 0 ( echo Expected ${message} to be ${output} exit 1 ) ` }, }), } ================================================ FILE: e2e/shellcode/shells/output-contains.ts ================================================ import { define, ScriptLine } from "./types.js" export type HasOutputContains = { scriptOutputContains(script: ScriptLine, substring: string): ScriptLine } export const cmdHasOutputContains = { bash: define({ scriptOutputContains: (script, substring) => { return `(${script}) | grep ${substring} || (echo "Expected output to contain ${substring}" && exit 1)` }, }), fish: define({ scriptOutputContains: (script, substring) => { return `begin; ${script}; end | grep ${substring}; or echo "Expected output to contain ${substring}" && exit 1` }, }), powershell: define({ scriptOutputContains: (script, substring) => { const inner: string = `${script} | Select-String ${substring}` return `$($__out__ = $(${inner}); if ($__out__ -eq $null) { exit 1 } else { $__out__ })` }, }), } ================================================ FILE: e2e/shellcode/shells/redirect-output.ts ================================================ import { ScriptLine, define } from "./types.js" type RedirectOutputOpts = { output: string } export type HasRedirectOutput = { redirectOutput(childCommand: ScriptLine, opts: RedirectOutputOpts): string } export const redirectOutput = { bash: define({ redirectOutput: (childCommand, opts) => `${childCommand} > ${opts.output}`, }), powershell: define({ redirectOutput: (childCommand, opts) => `${childCommand} | Out-File ${opts.output} -Encoding UTF8`, }), } ================================================ FILE: e2e/shellcode/shells/sub-shell.ts ================================================ import { ScriptLine, define } from "./types.js" import quote from "shell-escape" type HasInSubShell = { inSubShell: (script: ScriptLine) => ScriptLine } export const cmdInSubShell = { bash: define({ inSubShell: (script) => `echo ${quote([script])} | bash`, }), zsh: define({ inSubShell: (script) => `echo ${quote([script])} | zsh`, }), fish: define({ inSubShell: (script) => `fish -c ${quote([script])}`, }), powershell: define({ inSubShell: (script) => `echo '${script.replace(/'/g, "\\'")}' | pwsh -NoProfile`, }), } ================================================ FILE: e2e/shellcode/shells/types.ts ================================================ export type Shell = { escapeText(str: string): string binaryName(): string currentlySupported(): boolean name(): string launchArgs(): string[] dieOnErrors?(): string forceFile?: true | string } export type ScriptLine = string export function define(s: S): S { return s } ================================================ FILE: e2e/shellcode/shells.ts ================================================ import { cmdCall } from "./shells/cmdCall.js" import { cmdEnv } from "./shells/cmdEnv.js" import { cmdExpectCommandOutput } from "./shells/expect-command-output.js" import { cmdHasOutputContains } from "./shells/output-contains.js" import { redirectOutput } from "./shells/redirect-output.js" import { cmdInSubShell } from "./shells/sub-shell.js" import { define, Shell } from "./shells/types.js" export const Bash = { ...define({ binaryName: () => "bash", currentlySupported: () => true, name: () => "Bash", launchArgs: () => ["-i"], escapeText: (x) => x, dieOnErrors: () => `set -e`, }), ...cmdEnv.bash, ...cmdCall.all, ...redirectOutput.bash, ...cmdExpectCommandOutput.bash, ...cmdHasOutputContains.bash, ...cmdInSubShell.bash, } export const Zsh = { ...define({ binaryName: () => "zsh", currentlySupported: () => process.platform !== "win32", name: () => "Zsh", launchArgs: () => [], escapeText: (x) => x, dieOnErrors: () => `set -e`, }), ...cmdEnv.bash, ...cmdCall.all, ...redirectOutput.bash, ...cmdExpectCommandOutput.bash, ...cmdHasOutputContains.bash, ...cmdInSubShell.zsh, } export const Fish = { ...define({ binaryName: () => "fish", currentlySupported: () => process.platform !== "win32", name: () => "Fish", launchArgs: () => [], escapeText: (x) => x, forceFile: true, }), ...cmdEnv.fish, ...cmdCall.all, ...redirectOutput.bash, ...cmdExpectCommandOutput.fish, ...cmdHasOutputContains.fish, ...cmdInSubShell.fish, } export const PowerShell = { ...define({ binaryName: () => "pwsh", forceFile: ".ps1", currentlySupported: () => process.platform === "win32", name: () => "PowerShell", launchArgs: () => ["-NoProfile"], escapeText: (x) => x, dieOnErrors: () => `$ErrorActionPreference = "Stop"`, }), ...cmdEnv.powershell, ...cmdCall.all, ...redirectOutput.powershell, ...cmdExpectCommandOutput.powershell, ...cmdHasOutputContains.powershell, ...cmdInSubShell.powershell, } export const WinCmd = { ...define({ binaryName: () => "cmd.exe", currentlySupported: () => process.platform === "win32", name: () => "Windows Command Prompt", launchArgs: () => [], escapeText: (str) => str .replace(/\r/g, "") .replace(/\n/g, "^\n\n") .replace(/\%/g, "%%") .replace(/\|/g, "^|") .replace(/\(/g, "^(") .replace(/\)/g, "^)"), }), ...cmdEnv.wincmd, ...cmdCall.all, ...cmdExpectCommandOutput.wincmd, ...redirectOutput.bash, } ================================================ FILE: e2e/shellcode/test-bin-dir.ts ================================================ import { mkdirSync } from "node:fs" import path from "node:path" import testTmpDir from "./test-tmp-dir.js" export default function testBinDir() { const dir = path.join(testTmpDir(), "bin") mkdirSync(dir, { recursive: true }) return dir } ================================================ FILE: e2e/shellcode/test-cwd.ts ================================================ import { mkdirSync } from "node:fs" import path from "node:path" import testTmpDir from "./test-tmp-dir.js" export default function testCwd() { const dir = path.join(testTmpDir(), "cwd") mkdirSync(dir, { recursive: true }) return dir } ================================================ FILE: e2e/shellcode/test-node-version.ts ================================================ import { HasCall } from "./shells/cmdCall.js" import { ScriptLine } from "./shells/types.js" import { HasExpectCommandOutput } from "./shells/expect-command-output.js" export default function testNodeVersion< S extends HasCall & HasExpectCommandOutput >(shell: S, version: string): ScriptLine { const nodeVersion = shell.call("node", ["--version"]) return shell.hasCommandOutput(nodeVersion, version, "node version") } ================================================ FILE: e2e/shellcode/test-tmp-dir.ts ================================================ import { mkdirSync } from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" export default function testTmpDir(): string { const testName = (expect.getState().currentTestName ?? "unknown") .toLowerCase() .replace(/[^a-z0-9]/gi, "_") .replace(/_+/g, "_") const tmpDir = join(tmpdir(), `shellcode/${testName}`) mkdirSync(tmpDir, { recursive: true }) return tmpDir } ================================================ FILE: e2e/system-node.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import fs from "node:fs/promises" import path from "node:path" import describe from "./describe.js" import testNodeVersion from "./shellcode/test-node-version.js" import testBinDir from "./shellcode/test-bin-dir.js" for (const shell of [Bash, Fish, PowerShell, WinCmd, Zsh]) { describe(shell, () => { // latest bash breaks this as it seems. gotta find a solution. const t = process.platform === "darwin" && shell === Bash ? test.skip : test t(`switches to system node`, async () => { await writeCustomNode() await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v10.10.0"])) .then(shell.call("fnm", ["use", "v10"])) .then(testNodeVersion(shell, "v10.10.0")) .then(shell.call("fnm", ["use", "system"])) .then(testNodeVersion(shell, "custom")) .execute(shell) }) t(`aliasing a system node`, async () => { writeCustomNode() const init = script(shell).then(shell.env({})) await init .then(shell.call("fnm", ["install", "v10.10.0"])) .then(shell.call("fnm", ["use", "v10"])) .then(shell.call("fnm", ["default", "10"])) .execute(shell) await init .then(testNodeVersion(shell, "v10.10.0")) .then(shell.call("fnm", ["default", "system"])) .execute(shell) await init.then(testNodeVersion(shell, "custom")).execute(shell) }) }) async function writeCustomNode() { const customNode = path.join(testBinDir(), "node") if (process.platform === "win32" && [WinCmd, PowerShell].includes(shell)) { await fs.writeFile(customNode + ".cmd", "@echo custom") } else { await fs.writeFile(customNode, `#!/bin/bash\n\necho "custom"\n`) // set executable await fs.chmod(customNode, 0o766) } } } ================================================ FILE: e2e/uninstall.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell]) { describe(shell, () => { test(`uninstalls a version`, async () => { await script(shell) .then(shell.call("fnm", ["i", "12.0.0"])) .then(shell.call("fnm", ["alias", "12.0.0", "hello"])) .then( shell.scriptOutputContains( shell.scriptOutputContains(shell.call("fnm", ["ls"]), "v12.0.0"), "hello" ) ) .then(shell.call("fnm", ["uni", "hello"])) .then( shell.hasCommandOutput( shell.call("fnm", ["ls"]), "* system", "fnm ls" ) ) .takeSnapshot(shell) .execute(shell) }) }) } ================================================ FILE: e2e/use-on-cd.test.ts ================================================ import { writeFile, mkdir } from "node:fs/promises" import { join } from "node:path" import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testCwd from "./shellcode/test-cwd.js" import testNodeVersion from "./shellcode/test-node-version.js" import describe from "./describe.js" for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`use on cd`, async () => { await mkdir(join(testCwd(), "subdir"), { recursive: true }) await writeFile(join(testCwd(), "subdir", ".node-version"), "v12.22.12") await script(shell) .then(shell.env({ useOnCd: true })) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v12.22.12"])) .then(shell.call("cd", ["subdir"])) .then(testNodeVersion(shell, "v12.22.12")) .takeSnapshot(shell) .execute(shell) }) test(`uses current directory version immediately on env setup`, async () => { await writeFile(join(testCwd(), ".node-version"), "v12.22.12") await script(shell) .then(shell.env({})) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v12.22.12"])) .then(shell.call("fnm", ["use", "v8.11.3"])) .then(shell.env({ useOnCd: true })) .then(testNodeVersion(shell, "v12.22.12")) .execute(shell) }) test(`with resolve-engines`, async () => { await mkdir(join(testCwd(), "subdir"), { recursive: true }) await writeFile( join(testCwd(), "subdir", "package.json"), JSON.stringify({ name: "hello", engines: { node: "v12.22.12", }, }), ) await script(shell) .then(shell.env({ useOnCd: true, resolveEngines: true })) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v12.22.12"])) .then(shell.call("cd", ["subdir"])) .then(testNodeVersion(shell, "v12.22.12")) .execute(shell) }) test(`works after sourcing env twice`, async () => { await mkdir(join(testCwd(), "subdir"), { recursive: true }) await writeFile(join(testCwd(), "subdir", ".node-version"), "v12.22.12") await script(shell) .then(shell.env({ useOnCd: true })) .then(shell.env({ useOnCd: true })) .then(shell.call("fnm", ["install", "v8.11.3"])) .then(shell.call("fnm", ["install", "v12.22.12"])) .then(shell.call("cd", ["subdir"])) .then(testNodeVersion(shell, "v12.22.12")) .execute(shell) }) test(`doesn't throw on missing env data`, async () => { await mkdir(join(testCwd(), "subdir"), { recursive: true }) await writeFile( join(testCwd(), "subdir", "package.json"), JSON.stringify({ name: "hello", }), ) await script(shell) .then(shell.env({ useOnCd: true, resolveEngines: true })) .then(shell.call("cd", ["subdir"])) .execute(shell) }) }) } ================================================ FILE: e2e/windows-scoop.test.ts ================================================ import { script } from "./shellcode/script.js" import { Bash, Fish, PowerShell, WinCmd, Zsh } from "./shellcode/shells.js" import testNodeVersion from "./shellcode/test-node-version.js" import describe from "./describe.js" import os from "node:os" import { execa } from "execa" if (os.platform() !== "win32") { test.skip("scoop shims only work on Windows", () => {}) } else { beforeAll(async () => { // Create a scoop shim for tests await execa(`scoop`, [ "shim", "add", "fnm_release", "target/release/fnm.exe", ]) }) for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) { describe(shell, () => { test(`scoop shims infer the shell`, async () => { await script(shell) .then(shell.env({ executableName: "fnm_release" })) .then(shell.call("fnm_release", ["install", "v20.14.0"])) .then(shell.call("fnm_release", ["use", "v20.14.0"])) .then(testNodeVersion(shell, "v20.14.0")) .execute(shell) }) }) } } ================================================ FILE: fnm-manifest.rc ================================================ #define RT_MANIFEST 24 1 RT_MANIFEST "fnm.manifest" ================================================ FILE: fnm.manifest ================================================ true ================================================ FILE: jest.config.cjs ================================================ /** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: "ts-jest/presets/default-esm", globalSetup: "./jest.global-setup.js", globalTeardown: "./jest.global-teardown.js", testEnvironment: "node", testTimeout: 120000, extensionsToTreatAsEsm: [".ts"], testPathIgnorePatterns: ["/node_modules/", "/dist/", "/target/"], moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", "#ansi-styles": "ansi-styles/index.js", "#supports-color": "supports-color/index.js", }, transform: { // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest` // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest` "^.+\\.tsx?$": [ "ts-jest", { useESM: true, }, ], }, } ================================================ FILE: jest.global-setup.js ================================================ import { server } from "./tests/proxy-server/index.mjs" export default function () { server.listen(8080) } ================================================ FILE: jest.global-teardown.js ================================================ import { server } from "./tests/proxy-server/index.mjs" export default () => { server.close() } ================================================ FILE: package.json ================================================ { "name": "fnm", "version": "1.39.0", "private": true, "repository": "git@github.com:Schniz/fnm.git", "author": "Gal Schlezinger ", "type": "module", "packageManager": "pnpm@9.1.4", "license": "GPLv3", "scripts": { "test": "cross-env NODE_OPTIONS='--experimental-vm-modules' jest", "version:prepare": "changeset version && ./.ci/prepare-version.js", "generate-command-docs": "./.ci/print-command-docs.js" }, "changelog": { "repo": "Schniz/fnm", "labels": { "PR: New Feature": "New Feature 🎉", "PR: Bugfix": "Bugfix 🐛", "PR: Internal": "Internal 🛠", "PR: Documentation": "Documentation 📝" } }, "devDependencies": { "@changesets/changelog-github": "0.5.1", "@changesets/cli": "2.28.0", "@types/jest": "^29.2.3", "@types/node": "^18.11.9", "@types/shell-escape": "^0.2.1", "chalk": "^5.1.2", "cmd-ts": "0.13.0", "cross-env": "^7.0.3", "execa": "7.2.0", "jest": "^29.3.1", "lerna-changelog": "2.2.0", "node-fetch": "^3.3.0", "p-retry": "^6.2.0", "prettier": "3.5.1", "pv": "1.0.1", "shell-escape": "^0.2.0", "svg-term-cli": "2.1.1", "toml": "3.0.0", "ts-dedent": "^2.2.0", "ts-jest": "^29.0.3", "typescript": "^5.0.0", "which": "^3.0.1", "zod": "^3.19.1" }, "prettier": { "semi": false } } ================================================ FILE: renovate.json ================================================ { "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": ["config:base"], "labels": ["PR: Dependency Update"], "packageRules": [ { "packagePatterns": ["*"], "minor": { "groupName": "all non-major dependencies", "groupSlug": "all-minor-patch" } }, { "matchPackagePatterns": ["serde", "serde_json"], "groupName": "serde", "groupSlug": "serde" }, { "matchPackagePatterns": ["clap", "clap_*"], "groupName": "clap-rs", "groupSlug": "clap-rs" }, { "matchDepTypes": ["devDependencies", "dev-dependencies"], "matchPackagePatterns": ["*"], "automerge": true, "groupName": "all dev dependencies", "groupSlug": "all-dev-dependencies" }, { "matchPackagePatterns": ["uraimo/run-on-arch-action"], "matchManagers": ["github-actions"], "allowedVersions": "2.1.2" } ], "lockFileMaintenance": { "enabled": true } } ================================================ FILE: rust-toolchain.toml ================================================ [toolchain] channel = "1.88" components = ["rustfmt", "clippy"] ================================================ FILE: site/package.json ================================================ { "name": "fnm", "version": "1.0.0", "main": "index.js", "author": "Gal Schlezinger", "license": "MIT", "scripts": { "build": "rm -rf public; mkdir public; cp ../.ci/install.sh ./public/install.txt" } } ================================================ FILE: site/vercel.json ================================================ { "$schema": "https://openapi.vercel.sh/vercel.json", "github": { "silent": true }, "redirects": [ { "source": "/", "destination": "https://github.com/Schniz/fnm" } ], "rewrites": [{ "source": "/install", "destination": "/install.txt" }], "headers": [ { "source": "/install", "headers": [ { "key": "Cache-Control", "value": "public, max-age=3600" } ] } ] } ================================================ FILE: src/alias.rs ================================================ use crate::config::FnmConfig; use crate::fs::{remove_symlink_dir, shallow_read_symlink, symlink_dir}; use crate::system_version; use crate::version::Version; use std::convert::TryInto; use std::path::PathBuf; pub fn create_alias( config: &FnmConfig, common_name: &str, version: &Version, ) -> std::io::Result<()> { let aliases_dir = config.aliases_dir(); std::fs::create_dir_all(&aliases_dir)?; let version_dir = version.installation_path(config); let alias_dir = aliases_dir.join(common_name); remove_symlink_dir(&alias_dir).ok(); symlink_dir(version_dir, &alias_dir)?; Ok(()) } pub fn list_aliases(config: &FnmConfig) -> std::io::Result> { let vec: Vec<_> = std::fs::read_dir(config.aliases_dir())? .filter_map(Result::ok) .filter_map(|x| TryInto::::try_into(x.path().as_path()).ok()) .collect(); Ok(vec) } pub fn get_alias_by_name(config: &FnmConfig, alias_name: &str) -> Option { let alias_path = config.aliases_dir().join(alias_name); TryInto::::try_into(alias_path.as_path()).ok() } #[derive(Debug)] pub struct StoredAlias { alias_path: PathBuf, destination_path: PathBuf, } impl std::convert::TryInto for &std::path::Path { type Error = std::io::Error; fn try_into(self) -> Result { let shallow_self = shallow_read_symlink(self)?; let destination_path = if shallow_self == system_version::path() { shallow_self } else { std::fs::canonicalize(&shallow_self)? }; Ok(StoredAlias { alias_path: PathBuf::from(self), destination_path, }) } } impl StoredAlias { pub fn s_ver(&self) -> &str { if self.destination_path == system_version::path() { system_version::display_name() } else { self.destination_path .parent() .unwrap() .file_name() .expect("must have basename") .to_str() .unwrap() } } pub fn name(&self) -> &str { self.alias_path .file_name() .expect("must have basename") .to_str() .unwrap() } pub fn path(&self) -> &std::path::Path { &self.alias_path } } ================================================ FILE: src/arch.rs ================================================ use crate::version::Version; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Arch { X86, X64, X64Musl, X64Glibc217, Arm64, Armv7l, Ppc64le, Ppc64, S390x, } impl Arch { pub fn as_str(self) -> &'static str { match self { Arch::X86 => "x86", Arch::X64 => "x64", Arch::X64Musl => "x64-musl", Arch::X64Glibc217 => "x64-glibc-217", Arch::Arm64 => "arm64", Arch::Armv7l => "armv7l", Arch::Ppc64le => "ppc64le", Arch::Ppc64 => "ppc64", Arch::S390x => "s390x", } } } #[cfg(unix)] /// handle common case: Apple Silicon / Node < 16 pub fn get_safe_arch(arch: Arch, version: &Version) -> Arch { use crate::system_info::{platform_arch, platform_name}; match (platform_name(), platform_arch(), version) { ("darwin", "arm64", Version::Semver(v)) if v.major < 16 => Arch::X64, _ => arch, } } #[cfg(windows)] /// handle common case: Apple Silicon / Node < 16 pub fn get_safe_arch(arch: Arch, _version: &Version) -> Arch { arch } impl Default for Arch { fn default() -> Arch { match crate::system_info::platform_arch().parse() { Ok(arch) => arch, Err(e) => panic!("{}", e.details), } } } impl std::str::FromStr for Arch { type Err = ArchError; fn from_str(s: &str) -> Result { match s { "x86" => Ok(Arch::X86), "x64" => Ok(Arch::X64), "x64-musl" => Ok(Arch::X64Musl), "x64-glibc-217" => Ok(Arch::X64Glibc217), "arm64" => Ok(Arch::Arm64), "armv7l" => Ok(Arch::Armv7l), "ppc64le" => Ok(Arch::Ppc64le), "ppc64" => Ok(Arch::Ppc64), "s390x" => Ok(Arch::S390x), unknown => Err(ArchError::new(format!("Unknown Arch: {unknown}"))), } } } impl std::fmt::Display for Arch { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } #[derive(Debug)] pub struct ArchError { details: String, } impl ArchError { fn new(msg: String) -> ArchError { ArchError { details: msg } } } impl std::fmt::Display for ArchError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.details) } } impl std::error::Error for ArchError { fn description(&self) -> &str { &self.details } } ================================================ FILE: src/archive/extract.rs ================================================ use std::error::Error as StdError; use std::path::Path; #[derive(Debug)] pub enum Error { IoError(std::io::Error), ZipError(zip::result::ZipError), HttpError(crate::http::Error), } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::IoError(x) => x.fmt(f), Self::ZipError(x) => x.fmt(f), Self::HttpError(x) => x.fmt(f), } } } impl StdError for Error {} impl From for Error { fn from(err: std::io::Error) -> Self { Self::IoError(err) } } impl From for Error { fn from(err: zip::result::ZipError) -> Self { Self::ZipError(err) } } impl From for Error { fn from(err: crate::http::Error) -> Self { Self::HttpError(err) } } pub trait Extract { fn extract_into(self: Box, path: &Path) -> Result<(), Error>; } ================================================ FILE: src/archive/mod.rs ================================================ pub mod extract; pub mod tar; pub mod zip; use std::io::Read; use std::path::Path; pub use self::extract::{Error, Extract}; #[cfg(unix)] use self::tar::Tar; #[cfg(windows)] use self::zip::Zip; pub enum Archive { #[cfg(windows)] Zip, #[cfg(unix)] TarXz, #[cfg(unix)] TarGz, } impl Archive { pub fn extract_archive_into(&self, path: &Path, response: impl Read) -> Result<(), Error> { let extractor: Box = match self { #[cfg(windows)] Self::Zip => Box::new(Zip::new(response)), #[cfg(unix)] Self::TarXz => Box::new(Tar::Xz(response)), #[cfg(unix)] Self::TarGz => Box::new(Tar::Gz(response)), }; extractor.extract_into(path)?; Ok(()) } pub fn file_extension(&self) -> &'static str { match self { #[cfg(windows)] Self::Zip => "zip", #[cfg(unix)] Self::TarXz => "tar.xz", #[cfg(unix)] Self::TarGz => "tar.gz", } } #[cfg(windows)] pub fn supported() -> &'static [Self] { &[Self::Zip] } #[cfg(unix)] pub fn supported() -> &'static [Self] { &[Self::TarXz, Self::TarGz] } } ================================================ FILE: src/archive/tar.rs ================================================ use super::{extract::Error, Extract}; use std::{io::Read, path::Path}; pub enum Tar { /// Tar archive with XZ compression Xz(R), /// Tar archive with Gzip compression Gz(R), } impl Tar { fn extract_into_impl>(self, path: P) -> Result<(), Error> { let stream: Box = match self { Self::Xz(response) => Box::new(xz2::read::XzDecoder::new(response)), Self::Gz(response) => Box::new(flate2::read::GzDecoder::new(response)), }; let mut tar_archive = tar::Archive::new(stream); tar_archive.unpack(&path)?; Ok(()) } } impl Extract for Tar { fn extract_into(self: Box, path: &Path) -> Result<(), Error> { self.extract_into_impl(path) } } ================================================ FILE: src/archive/zip.rs ================================================ use super::extract::{Error, Extract}; use log::debug; use std::fs; use std::io::{self, Read}; use std::path::Path; use tempfile::tempfile; use zip::read::ZipArchive; pub struct Zip { response: R, } impl Zip { #[allow(dead_code)] pub fn new(response: R) -> Self { Self { response } } } impl Extract for Zip { fn extract_into(mut self: Box, path: &Path) -> Result<(), Error> { let mut tmp_zip_file = tempfile().expect("Can't get a temporary file"); debug!("Created a temporary zip file"); io::copy(&mut self.response, &mut tmp_zip_file)?; debug!( "Wrote zipfile successfully. Now extracting into {}.", path.display() ); let mut archive = ZipArchive::new(&mut tmp_zip_file)?; for i in 0..archive.len() { let mut file = archive.by_index(i)?; let outpath = path.join(file.mangled_name()); { let comment = file.comment(); if !comment.is_empty() { debug!("File {} comment: {}", i, comment); } } if file.name().ends_with('/') { debug!( "File {} extracted to \"{}\"", i, outpath.as_path().display() ); fs::create_dir_all(&outpath)?; } else { debug!( "Extracting file {} to \"{}\" ({} bytes)", i, outpath.as_path().display(), file.size() ); if let Some(p) = outpath.parent() { if !p.exists() { fs::create_dir_all(p)?; } } let mut outfile = fs::File::create(&outpath)?; io::copy(&mut file, &mut outfile)?; } // Get and Set permissions #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; if let Some(mode) = file.unix_mode() { fs::set_permissions(&outpath, fs::Permissions::from_mode(mode))?; } } } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test_log::test] fn test_zip_extraction() { let temp_dir = &tempfile::tempdir().expect("Can't create a temp directory"); let response = crate::http::get("https://nodejs.org/dist/v12.0.0/node-v12.0.0-win-x64.zip") .expect("Can't make request to Node v12.0.0 zip file"); Box::new(Zip::new(response)) .extract_into(temp_dir.as_ref()) .expect("Can't unzip files"); let node_file = temp_dir .as_ref() .join("node-v12.0.0-win-x64") .join("node.exe"); assert!(node_file.exists()); } } ================================================ FILE: src/choose_version_for_user_input.rs ================================================ use crate::config::FnmConfig; use crate::fs; use crate::installed_versions; use crate::system_version; use crate::user_version::UserVersion; use crate::version::Version; use colored::Colorize; use log::info; use std::path::{Path, PathBuf}; use thiserror::Error; #[derive(Debug)] pub struct ApplicableVersion { path: PathBuf, version: Version, } impl ApplicableVersion { pub fn path(&self) -> &Path { &self.path } pub fn version(&self) -> &Version { &self.version } } pub fn choose_version_for_user_input<'a>( requested_version: &'a UserVersion, config: &'a FnmConfig, ) -> Result, Error> { let all_versions = installed_versions::list(config.installations_dir()) .map_err(|source| Error::VersionListing { source })?; let result = if let UserVersion::Full(Version::Bypassed) = requested_version { info!( "Bypassing fnm: using {} node", system_version::display_name().cyan() ); Some(ApplicableVersion { path: system_version::path(), version: Version::Bypassed, }) } else if let Some(alias_name) = requested_version.alias_name() { let alias_path = config.aliases_dir().join(&alias_name); let system_path = system_version::path(); if matches!(fs::shallow_read_symlink(&alias_path), Ok(shallow_path) if shallow_path == system_path) { info!( "Bypassing fnm: using {} node", system_version::display_name().cyan() ); Some(ApplicableVersion { path: alias_path, version: Version::Bypassed, }) } else if alias_path.exists() { info!("Using Node for alias {}", alias_name.cyan()); Some(ApplicableVersion { path: alias_path, version: Version::Alias(alias_name), }) } else { return Err(Error::CantFindVersion { requested_version: requested_version.clone(), }); } } else { let current_version = requested_version.to_version(&all_versions, config); current_version.map(|version| { info!("Using Node {}", version.to_string().cyan()); let path = config .installations_dir() .join(version.to_string()) .join("installation"); ApplicableVersion { path, version: version.clone(), } }) }; Ok(result) } #[derive(Debug, Error)] pub enum Error { #[error("Can't find requested version: {}", requested_version)] CantFindVersion { requested_version: UserVersion }, #[error("Can't list local installed versions: {}", source)] VersionListing { source: installed_versions::Error }, } ================================================ FILE: src/cli.rs ================================================ use crate::commands; use crate::commands::command::Command; use crate::config::FnmConfig; use clap::Parser; #[derive(clap::Parser, Debug)] pub enum SubCommand { /// List all remote Node.js versions #[clap(name = "list-remote", bin_name = "list-remote", visible_aliases = &["ls-remote"])] LsRemote(commands::ls_remote::LsRemote), /// List all locally installed Node.js versions #[clap(name = "list", bin_name = "list", visible_aliases = &["ls"])] LsLocal(commands::ls_local::LsLocal), /// Install a new Node.js version #[clap(name = "install", bin_name = "install", visible_aliases = &["i"])] Install(commands::install::Install), /// Change Node.js version #[clap(name = "use", bin_name = "use")] Use(commands::r#use::Use), /// Print and set up required environment variables for fnm /// /// This command generates a series of shell commands that /// should be evaluated by your shell to create a fnm-ready environment. /// /// Each shell has its own syntax of evaluating a dynamic expression. /// For example, evaluating fnm on Bash and Zsh would look like `eval "$(fnm env --shell bash)"`. /// In Fish, evaluating would look like `fnm env --shell fish | source` #[clap(name = "env", bin_name = "env")] Env(commands::env::Env), /// Print shell completions to stdout #[clap(name = "completions", bin_name = "completions")] Completions(commands::completions::Completions), /// Alias a version to a common name #[clap(name = "alias", bin_name = "alias")] Alias(commands::alias::Alias), /// Remove an alias definition #[clap(name = "unalias", bin_name = "unalias")] Unalias(commands::unalias::Unalias), /// Set a version as the default version or get the current default version. /// /// This is a shorthand for `fnm alias VERSION default` #[clap(name = "default", bin_name = "default")] Default(commands::default::Default), /// Print the current Node.js version #[clap(name = "current", bin_name = "current")] Current(commands::current::Current), /// Run a command within fnm context /// /// Example: /// -------- /// fnm exec --using=v12.0.0 node --version /// => v12.0.0 #[clap(name = "exec", bin_name = "exec", verbatim_doc_comment)] Exec(commands::exec::Exec), /// Uninstall a Node.js version /// /// > Warning: when providing an alias, it will remove the Node version the alias /// > is pointing to, along with the other aliases that point to the same version. #[clap(name = "uninstall", bin_name = "uninstall", visible_aliases = &["uni"])] Uninstall(commands::uninstall::Uninstall), } impl SubCommand { pub fn call(self, config: FnmConfig) { match self { Self::LsLocal(cmd) => cmd.call(config), Self::LsRemote(cmd) => cmd.call(config), Self::Install(cmd) => cmd.call(config), Self::Env(cmd) => cmd.call(config), Self::Use(cmd) => cmd.call(config), Self::Completions(cmd) => cmd.call(config), Self::Alias(cmd) => cmd.call(config), Self::Default(cmd) => cmd.call(config), Self::Current(cmd) => cmd.call(config), Self::Exec(cmd) => cmd.call(config), Self::Uninstall(cmd) => cmd.call(config), Self::Unalias(cmd) => cmd.call(config), } } } /// A fast and simple Node.js manager. #[derive(clap::Parser, Debug)] #[clap(name = "fnm", version = env!("CARGO_PKG_VERSION"), bin_name = "fnm")] pub struct Cli { #[clap(flatten)] pub config: FnmConfig, #[clap(subcommand)] pub subcmd: SubCommand, } pub fn parse() -> Cli { Cli::parse() } ================================================ FILE: src/commands/alias.rs ================================================ use super::command::Command; use crate::alias::create_alias; use crate::choose_version_for_user_input::{ choose_version_for_user_input, Error as ApplicableVersionError, }; use crate::config::FnmConfig; use crate::user_version::UserVersion; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct Alias { pub(crate) to_version: UserVersion, pub(crate) name: String, } impl Command for Alias { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let applicable_version = choose_version_for_user_input(&self.to_version, config) .map_err(|source| Error::CantUnderstandVersion { source })? .ok_or(Error::VersionNotFound { version: self.to_version, })?; create_alias(config, &self.name, applicable_version.version()) .map_err(|source| Error::CantCreateSymlink { source })?; Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error("Can't create symlink for alias: {}", source)] CantCreateSymlink { source: std::io::Error }, #[error("Version {} not found locally", version)] VersionNotFound { version: UserVersion }, #[error(transparent)] CantUnderstandVersion { source: ApplicableVersionError }, #[error("A default version has not been set.")] DefaultAliasDoesNotExist, } ================================================ FILE: src/commands/command.rs ================================================ use crate::config::FnmConfig; use crate::outln; use colored::Colorize; pub trait Command: Sized { type Error: std::error::Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error>; fn handle_error(err: Self::Error, config: &FnmConfig) { let err_s = format!("{err}"); outln!(config, Error, "{} {}", "error:".red().bold(), err_s.red()); std::process::exit(1); } fn call(self, config: FnmConfig) { match self.apply(&config) { Ok(()) => (), Err(err) => Self::handle_error(err, &config), } } } ================================================ FILE: src/commands/completions.rs ================================================ use super::command::Command; use crate::config::FnmConfig; use crate::shell::{infer_shell, Shell}; use crate::{cli::Cli, shell::Shells}; use clap::{CommandFactory, Parser, ValueEnum}; use clap_complete::{Generator, Shell as ClapShell}; use thiserror::Error; #[derive(Parser, Debug)] pub struct Completions { /// The shell syntax to use. Infers when missing. #[clap(long)] shell: Option, } impl Command for Completions { type Error = Error; fn apply(self, _config: &FnmConfig) -> Result<(), Self::Error> { let mut stdio = std::io::stdout(); let shell: Box = self .shell .map(Into::into) .or_else(|| infer_shell()) .ok_or(Error::CantInferShell)?; let shell: ClapShell = shell.into(); let mut app = Cli::command(); app.build(); shell.generate(&app, &mut stdio); Ok(()) } } #[derive(Error, Debug)] pub enum Error { #[error( "{}\n{}\n{}\n{}", "Can't infer shell!", "fnm can't infer your shell based on the process tree.", "Maybe it is unsupported? we support the following shells:", shells_as_string() )] CantInferShell, } fn shells_as_string() -> String { Shells::value_variants() .iter() .map(|x| format!("* {x}")) .collect::>() .join("\n") } #[cfg(test)] mod tests { use super::*; #[test] #[cfg(not(windows))] fn test_smoke() { let config = FnmConfig::default(); Completions { shell: Some(Shells::Bash), } .call(config); } } ================================================ FILE: src/commands/current.rs ================================================ use super::command::Command; use crate::config::FnmConfig; use crate::current_version::{current_version, Error}; #[derive(clap::Parser, Debug)] pub struct Current {} impl Command for Current { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let version_string = match current_version(config)? { Some(ver) => ver.v_str(), None => "none".into(), }; println!("{version_string}"); Ok(()) } } ================================================ FILE: src/commands/default.rs ================================================ use super::alias::Alias; use super::command::Command; use crate::alias::get_alias_by_name; use crate::config::FnmConfig; use crate::user_version::UserVersion; #[derive(clap::Parser, Debug)] pub struct Default { version: Option, } impl Command for Default { type Error = super::alias::Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { match self.version { Some(version) => Alias { name: "default".into(), to_version: version, } .apply(config), None => match get_alias_by_name(config, "default") { Some(alias) => { println!("{}", alias.s_ver()); Ok(()) } None => Err(Self::Error::DefaultAliasDoesNotExist), }, } } fn handle_error(err: Self::Error, config: &FnmConfig) { Alias::handle_error(err, config); } } ================================================ FILE: src/commands/env.rs ================================================ use super::command::Command; use super::r#use::Use; use crate::config::FnmConfig; use crate::fs::symlink_dir; use crate::outln; use crate::path_ext::PathExt; use crate::shell::{infer_shell, Shell, Shells}; use clap::ValueEnum; use colored::Colorize; use std::collections::HashMap; use std::fmt::Debug; use std::io::IsTerminal; use thiserror::Error; #[derive(clap::Parser, Debug, Default)] pub struct Env { /// The shell syntax to use. Infers when missing. #[clap(long)] shell: Option, /// Print JSON instead of shell commands. #[clap(long, conflicts_with = "shell")] json: bool, /// Deprecated. This is the default now. #[clap(long, hide = true)] multi: bool, /// Print the script to change Node versions every directory change #[clap(long)] use_on_cd: bool, } fn generate_symlink_path() -> String { format!( "{}_{}", std::process::id(), chrono::Utc::now().timestamp_millis(), ) } fn make_symlink(config: &FnmConfig) -> Result { let base_dir = config.multishell_storage().ensure_exists_silently(); let mut temp_dir = base_dir.join(generate_symlink_path()); while temp_dir.exists() { temp_dir = base_dir.join(generate_symlink_path()); } match symlink_dir(config.default_version_dir(), &temp_dir) { Ok(()) => Ok(temp_dir), Err(source) => Err(Error::CantCreateSymlink { source, temp_dir }), } } #[inline] fn bool_as_str(value: bool) -> &'static str { if value { "true" } else { "false" } } fn set_path_for_multishell(multishell_path: &std::path::Path) { let path_for_node = if cfg!(windows) { multishell_path.to_path_buf() } else { multishell_path.join("bin") }; let current_path = std::env::var_os("PATH").unwrap_or_default(); let mut split_paths: Vec<_> = std::env::split_paths(¤t_path).collect(); split_paths.insert(0, path_for_node); if let Ok(new_path) = std::env::join_paths(split_paths) { unsafe { std::env::set_var("PATH", new_path); } } } impl Command for Env { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { if self.multi { outln!( config, Error, "{} {} is deprecated. This is now the default.", "warning:".yellow().bold(), "--multi".italic() ); } let multishell_path = make_symlink(config)?; let base_dir = config.base_dir_with_default(); let env_vars = [ ("FNM_MULTISHELL_PATH", multishell_path.to_str().unwrap()), ( "FNM_VERSION_FILE_STRATEGY", config.version_file_strategy().as_str(), ), ("FNM_DIR", base_dir.to_str().unwrap()), ("FNM_LOGLEVEL", config.log_level().as_str()), ("FNM_NODE_DIST_MIRROR", config.node_dist_mirror.as_str()), ( "FNM_COREPACK_ENABLED", bool_as_str(config.corepack_enabled()), ), ("FNM_RESOLVE_ENGINES", bool_as_str(config.resolve_engines())), ("FNM_ARCH", config.arch.as_str()), ]; if self.json { println!( "{}", serde_json::to_string(&HashMap::from(env_vars)).unwrap() ); return Ok(()); } let shell: Box = self .shell .map(Into::into) .or_else(infer_shell) .ok_or(Error::CantInferShell)?; let binary_path = if cfg!(windows) { shell.path(&multishell_path) } else { shell.path(&multishell_path.join("bin")) }; println!("{}", binary_path?); for (name, value) in &env_vars { println!("{}", shell.set_env_var(name, value)); } if self.use_on_cd { // Call `use` internally for the initial directory, so the shell doesn't // need to spawn a subprocess after evaluating the env output. set_path_for_multishell(&multishell_path); let config_with_multishell = config.clone().with_multishell_path(multishell_path.clone()); let use_cmd = Use { version: None, install_if_missing: false, silent_if_unchanged: true, info_to_stderr: true, }; let should_force_stderr_color = !std::io::stdout().is_terminal() && std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none(); if should_force_stderr_color { colored::control::set_override(true); } // Ignore errors - if there's no version file, that's fine let _ = use_cmd.apply(&config_with_multishell); if should_force_stderr_color { colored::control::unset_override(); } println!("{}", shell.use_on_cd(config)?); } if let Some(v) = shell.rehash() { println!("{v}"); } Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error( "{}\n{}\n{}\n{}", "Can't infer shell!", "fnm can't infer your shell based on the process tree.", "Maybe it is unsupported? we support the following shells:", shells_as_string() )] CantInferShell, #[error("Can't create the symlink for multishells at {temp_dir:?}. Maybe there are some issues with permissions for the directory? {source}")] CantCreateSymlink { #[source] source: std::io::Error, temp_dir: std::path::PathBuf, }, #[error(transparent)] ShellError { #[from] source: anyhow::Error, }, } fn shells_as_string() -> String { Shells::value_variants() .iter() .map(|x| format!("* {x}")) .collect::>() .join("\n") } #[cfg(test)] mod tests { use super::*; #[test] fn test_smoke() { let config = FnmConfig::default(); Env { #[cfg(windows)] shell: Some(Shells::Cmd), #[cfg(not(windows))] shell: Some(Shells::Bash), ..Default::default() } .call(config); } } ================================================ FILE: src/commands/exec.rs ================================================ use super::command::Command as Cmd; use crate::choose_version_for_user_input::{ choose_version_for_user_input, Error as UserInputError, }; use crate::config::FnmConfig; use crate::outln; use crate::user_version::UserVersion; use crate::user_version_reader::UserVersionReader; use colored::Colorize; use std::process::{Command, Stdio}; use thiserror::Error; #[derive(Debug, clap::Parser)] #[clap(trailing_var_arg = true)] pub struct Exec { /// Either an explicit version, or a filename with the version written in it #[clap(long = "using")] version: Option, /// Deprecated. This is the default now. #[clap(long = "using-file", hide = true)] using_file: bool, /// The command to run arguments: Vec, } impl Exec { pub(crate) fn new_for_version( version: &crate::version::Version, cmd: &str, arguments: &[&str], ) -> Self { let reader = UserVersionReader::Direct(UserVersion::Full(version.clone())); let args: Vec<_> = std::iter::once(cmd) .chain(arguments.iter().copied()) .map(String::from) .collect(); Self { version: Some(reader), using_file: false, arguments: args, } } } impl Cmd for Exec { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { if self.using_file { outln!( config, Error, "{} {} is deprecated. This is now the default.", "warning:".yellow().bold(), "--using-file".italic() ); } let (binary, arguments) = self .arguments .split_first() .ok_or(Error::NoBinaryProvided)?; let version = self .version .unwrap_or_else(|| { let current_dir = std::env::current_dir().unwrap(); UserVersionReader::Path(current_dir) }) .into_user_version(config) .ok_or(Error::CantInferVersion)?; let applicable_version = choose_version_for_user_input(&version, config) .map_err(|source| Error::ApplicableVersionError { source })? .ok_or(Error::VersionNotFound { version })?; #[cfg(windows)] let bin_path = applicable_version.path().to_path_buf(); #[cfg(unix)] let bin_path = applicable_version.path().join("bin"); let path_env = { let paths_env = std::env::var_os("PATH").ok_or(Error::CantReadPathVariable)?; let mut paths: Vec<_> = std::env::split_paths(&paths_env).collect(); paths.insert(0, bin_path); std::env::join_paths(paths) .map_err(|source| Error::CantAddPathToEnvironment { source })? }; log::debug!("Running {} with PATH={:?}", binary, path_env); let exit_status = Command::new(binary) .args(arguments) .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .env("PATH", path_env) .spawn() .map_err(|source| Error::CantSpawnProgram { source, binary: binary.to_string(), })? .wait() .expect("Failed to grab exit code"); let code = exit_status.code().ok_or(Error::CantReadProcessExitCode)?; std::process::exit(code); } } #[derive(Debug, Error)] pub enum Error { #[error("Can't spawn program: {source}\nMaybe the program {} does not exist on not available in PATH?", binary.bold())] CantSpawnProgram { source: std::io::Error, binary: String, }, #[error("Can't read path environment variable")] CantReadPathVariable, #[error("Can't add path to environment variable: {}", source)] CantAddPathToEnvironment { source: std::env::JoinPathsError }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("Requested version {} is not currently installed", version)] VersionNotFound { version: UserVersion }, #[error(transparent)] ApplicableVersionError { #[from] source: UserInputError, }, #[error("Can't read exit code from process.\nMaybe the process was killed using a signal?")] CantReadProcessExitCode, #[error("command not provided. Please provide a command to run as an argument, like {} or {}.\n{} {}", "node".italic(), "bash".italic(), "example:".yellow().bold(), "fnm exec --using=12 node --version".italic().yellow())] NoBinaryProvided, } ================================================ FILE: src/commands/install.rs ================================================ use super::command::Command; use super::r#use::Use; use crate::alias::create_alias; use crate::arch::get_safe_arch; use crate::config::FnmConfig; use crate::downloader::{install_node_dist, Error as DownloaderError}; use crate::lts::LtsType; use crate::outln; use crate::progress::ProgressConfig; use crate::remote_node_index; use crate::user_version::UserVersion; use crate::user_version_reader::UserVersionReader; use crate::version::Version; use crate::version_files::get_user_version_for_directory; use colored::Colorize; use log::debug; use thiserror::Error; #[derive(clap::Parser, Debug, Default)] pub struct Install { /// A version string. Can be a partial semver or a LTS version name by the format lts/NAME pub version: Option, /// Install latest LTS #[clap(long, conflicts_with_all = &["version", "latest"])] pub lts: bool, /// Install latest version #[clap(long, conflicts_with_all = &["version", "lts"])] pub latest: bool, /// Show an interactive progress bar for the download /// status. #[clap(long, default_value_t)] #[arg(value_enum)] pub progress: ProgressConfig, /// Use the installed version immediately after installation #[clap(long)] pub r#use: bool, } impl Install { fn version(self) -> Result, Error> { match self { Self { version: v, lts: false, latest: false, .. } => Ok(v), Self { version: None, lts: true, latest: false, .. } => Ok(Some(UserVersion::Full(Version::Lts(LtsType::Latest)))), Self { version: None, lts: false, latest: true, .. } => Ok(Some(UserVersion::Full(Version::Latest))), _ => Err(Error::TooManyVersionsProvided), } } } impl Command for Install { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let current_dir = std::env::current_dir().unwrap(); let show_progress = self.progress.enabled(config); let use_installed = self.r#use; let current_version = self .version()? .or_else(|| get_user_version_for_directory(current_dir, config)) .ok_or(Error::CantInferVersion)?; let version = match current_version.clone() { UserVersion::Full(Version::Semver(actual_version)) => Version::Semver(actual_version), UserVersion::Full(v @ (Version::Bypassed | Version::Alias(_))) => { return Err(Error::UninstallableVersion { version: v }); } UserVersion::Full(Version::Lts(lts_type)) => { let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror) .map_err(|source| Error::CantListRemoteVersions { source })?; let picked_version = lts_type .pick_latest(&available_versions) .ok_or_else(|| Error::CantFindRelevantLts { lts_type: lts_type.clone(), })? .version .clone(); debug!( "Resolved {} into Node version {}", Version::Lts(lts_type).v_str().cyan(), picked_version.v_str().cyan() ); picked_version } UserVersion::Full(Version::Latest) => { let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror) .map_err(|source| Error::CantListRemoteVersions { source })?; let picked_version = available_versions .last() .ok_or(Error::CantFindLatest)? .version .clone(); debug!( "Resolved {} into Node version {}", Version::Latest.v_str().cyan(), picked_version.v_str().cyan() ); picked_version } current_version => { let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror) .map_err(|source| Error::CantListRemoteVersions { source })? .drain(..) .map(|x| x.version) .collect(); current_version .to_version(&available_versions, config) .ok_or(Error::CantFindNodeVersion { requested_version: current_version, })? .clone() } }; // Automatically swap Apple Silicon to x64 arch for appropriate versions. let safe_arch = get_safe_arch(config.arch, &version); let version_str = format!("Node {}", &version); outln!( config, Info, "Installing {} ({})", version_str.cyan(), safe_arch.as_str() ); match install_node_dist( &version, &config.node_dist_mirror, config.installations_dir(), safe_arch, show_progress, ) { Err(err @ DownloaderError::VersionAlreadyInstalled { .. }) => { outln!(config, Error, "{} {}", "warning:".bold().yellow(), err); } Err(source) => Err(Error::DownloadError { source })?, Ok(()) => {} } if !config.default_version_dir().exists() { debug!("Tagging {} as the default version", version.v_str().cyan()); create_alias(config, "default", &version)?; } if let Some(tagged_alias) = current_version.inferred_alias() { tag_alias(config, &version, &tagged_alias)?; } if config.corepack_enabled() { outln!(config, Info, "Enabling corepack for {}", version_str.cyan()); enable_corepack(&version, config)?; } if use_installed { use_installed_version(&version, config)?; } Ok(()) } } fn tag_alias(config: &FnmConfig, matched_version: &Version, alias: &Version) -> Result<(), Error> { let alias_name = alias.v_str(); debug!( "Tagging {} as alias for {}", alias_name.cyan(), matched_version.v_str().cyan() ); create_alias(config, &alias_name, matched_version)?; Ok(()) } fn enable_corepack(version: &Version, config: &FnmConfig) -> Result<(), Error> { let corepack_path = version.installation_path(config); let corepack_path = if cfg!(windows) { corepack_path.join("corepack.cmd") } else { corepack_path.join("bin").join("corepack") }; super::exec::Exec::new_for_version(version, corepack_path.to_str().unwrap(), &["enable"]) .apply(config) .map_err(|source| Error::CorepackError { source })?; Ok(()) } fn use_installed_version(version: &Version, config: &FnmConfig) -> Result<(), Error> { Use { version: Some(UserVersionReader::Direct(UserVersion::Full( version.clone(), ))), install_if_missing: false, silent_if_unchanged: false, info_to_stderr: false, } .apply(config) .map_err(|source| Error::UseError { source: Box::new(source), })?; Ok(()) } #[derive(Debug, Error)] pub enum Error { #[error("Can't download the requested binary: {}", source)] DownloadError { source: DownloaderError }, #[error(transparent)] IoError { #[from] source: std::io::Error, }, #[error("Can't enable corepack: {source}")] CorepackError { #[from] source: super::exec::Error, }, #[error(transparent)] UseError { source: Box<::Error>, }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error(transparent)] CantListRemoteVersions { source: remote_node_index::Error }, #[error( "Can't find a Node version that matches {} in remote", requested_version )] CantFindNodeVersion { requested_version: UserVersion }, #[error("Can't find relevant LTS named {}", lts_type)] CantFindRelevantLts { lts_type: crate::lts::LtsType }, #[error("Can't find any versions in the upstream version index.")] CantFindLatest, #[error("The requested version is not installable: {}", version.v_str())] UninstallableVersion { version: Version }, #[error("Too many versions provided. Please don't use --lts with a version string.")] TooManyVersionsProvided, } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use std::str::FromStr; #[test] fn test_set_default_on_new_installation() { let base_dir = tempfile::tempdir().unwrap(); let config = FnmConfig::default().with_base_dir(Some(base_dir.path().to_path_buf())); assert!(!config.default_version_dir().exists()); Install { version: UserVersion::from_str("12.0.0").ok(), lts: false, latest: false, progress: ProgressConfig::Never, r#use: false, } .apply(&config) .expect("Can't install"); assert!(config.default_version_dir().exists()); assert_eq!( config.default_version_dir().canonicalize().ok(), config .installations_dir() .join("v12.0.0") .join("installation") .canonicalize() .ok() ); } #[test] fn test_install_latest() { let base_dir = tempfile::tempdir().unwrap(); let config = FnmConfig::default().with_base_dir(Some(base_dir.path().to_path_buf())); Install { version: None, lts: false, latest: true, progress: ProgressConfig::Never, r#use: false, } .apply(&config) .expect("Can't install"); let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror).expect("Can't get node version list"); let latest_version = available_versions.last().unwrap().version.clone(); assert!(config.installations_dir().exists()); assert!(config .installations_dir() .join(latest_version.to_string()) .join("installation") .canonicalize() .unwrap() .exists()); } } ================================================ FILE: src/commands/ls_local.rs ================================================ use crate::alias::{list_aliases, StoredAlias}; use crate::config::FnmConfig; use crate::current_version::current_version; use crate::version::Version; use colored::Colorize; use std::collections::HashMap; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct LsLocal {} impl super::command::Command for LsLocal { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let base_dir = config.installations_dir(); let mut versions = crate::installed_versions::list(base_dir) .map_err(|source| Error::CantListLocallyInstalledVersion { source })?; versions.insert(0, Version::Bypassed); versions.sort(); let aliases_hash = generate_aliases_hash(config).map_err(|source| Error::CantReadAliases { source })?; let curr_version = current_version(config).ok().flatten(); for version in versions { let version_aliases = match aliases_hash.get(&version.v_str()) { None => String::new(), Some(versions) => { let version_string = versions .iter() .map(StoredAlias::name) .collect::>() .join(", "); format!(" {}", version_string.dimmed()) } }; let version_str = format!("* {version}{version_aliases}"); if curr_version == Some(version) { println!("{}", version_str.cyan()); } else { println!("{version_str}"); } } Ok(()) } } fn generate_aliases_hash(config: &FnmConfig) -> std::io::Result>> { let mut aliases = list_aliases(config)?; let mut hashmap: HashMap> = HashMap::with_capacity(aliases.len()); for alias in aliases.drain(..) { if let Some(value) = hashmap.get_mut(alias.s_ver()) { value.push(alias); } else { hashmap.insert(alias.s_ver().into(), vec![alias]); } } Ok(hashmap) } #[derive(Debug, Error)] pub enum Error { #[error("Can't list locally installed versions: {}", source)] CantListLocallyInstalledVersion { source: crate::installed_versions::Error, }, #[error("Can't read aliases: {}", source)] CantReadAliases { source: std::io::Error }, } ================================================ FILE: src/commands/ls_remote.rs ================================================ use crate::config::FnmConfig; use crate::remote_node_index; use crate::user_version::UserVersion; use colored::Colorize; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct LsRemote { /// Filter versions by a user-defined version or a semver range #[arg(long)] filter: Option, /// Show only LTS versions (optionally filter by LTS codename) #[arg(long)] #[expect( clippy::option_option, reason = "clap Option> supports --x and --x=value syntaxes" )] lts: Option>, /// Version sorting order #[arg(long, default_value = "asc")] sort: SortingMethod, /// Only show the latest matching version #[arg(long)] latest: bool, } #[derive(clap::ValueEnum, Clone, Debug, PartialEq)] pub enum SortingMethod { #[clap(name = "desc")] /// Sort versions in descending order (latest to earliest) Descending, #[clap(name = "asc")] /// Sort versions in ascending order (earliest to latest) Ascending, } /// Drain all elements but the last one fn truncate_except_latest(list: &mut Vec) { let len = list.len(); if len > 1 { list.swap(0, len - 1); list.truncate(1); } } impl super::command::Command for LsRemote { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let mut all_versions = remote_node_index::list(&config.node_dist_mirror)?; if let Some(lts) = &self.lts { match lts { Some(codename) => all_versions.retain(|v| { v.lts .as_ref() .is_some_and(|v_lts| v_lts.eq_ignore_ascii_case(codename)) }), None => all_versions.retain(|v| v.lts.is_some()), } } if let Some(filter) = &self.filter { all_versions.retain(|v| filter.matches(&v.version, config)); } if self.latest { truncate_except_latest(&mut all_versions); } if let SortingMethod::Descending = self.sort { all_versions.reverse(); } if all_versions.is_empty() { eprintln!("{}", "No versions were found!".red()); return Ok(()); } for version in &all_versions { print!("{}", version.version); if let Some(lts) = &version.lts { print!("{}", format!(" ({lts})").cyan()); } println!(); } Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error(transparent)] RemoteListing { #[from] source: remote_node_index::Error, }, } #[cfg(test)] mod test { use super::*; #[test] fn test_truncate_except_latest() { let mut list = vec![1, 2, 3, 4, 5]; truncate_except_latest(&mut list); assert_eq!(list, vec![5]); let mut list: Vec<()> = vec![]; truncate_except_latest(&mut list); assert_eq!(list, vec![]); let mut list = vec![1]; truncate_except_latest(&mut list); assert_eq!(list, vec![1]); } } ================================================ FILE: src/commands/mod.rs ================================================ pub mod alias; pub mod command; pub mod completions; pub mod current; pub mod default; pub mod env; pub mod exec; pub mod install; pub mod ls_local; pub mod ls_remote; pub mod unalias; pub mod uninstall; pub mod r#use; ================================================ FILE: src/commands/unalias.rs ================================================ use super::command::Command; use crate::fs::remove_symlink_dir; use crate::user_version::UserVersion; use crate::version::Version; use crate::{choose_version_for_user_input, config::FnmConfig}; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct Unalias { pub(crate) requested_alias: String, } impl Command for Unalias { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let requested_version = choose_version_for_user_input::choose_version_for_user_input( &UserVersion::Full(Version::Alias(self.requested_alias.clone())), config, ) .ok() .flatten() .ok_or(Error::AliasNotFound { requested_alias: self.requested_alias, })?; remove_symlink_dir(requested_version.path()) .map_err(|source| Error::CantDeleteSymlink { source })?; Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error("Can't delete symlink: {}", source)] CantDeleteSymlink { source: std::io::Error }, #[error("Requested alias {} not found", requested_alias)] AliasNotFound { requested_alias: String }, } ================================================ FILE: src/commands/uninstall.rs ================================================ use super::command::Command; use crate::config::FnmConfig; use crate::fs::remove_symlink_dir; use crate::installed_versions; use crate::outln; use crate::user_version::UserVersion; use crate::version::Version; use crate::version_files::get_user_version_for_directory; use colored::Colorize; use log::debug; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct Uninstall { version: Option, } impl Command for Uninstall { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let all_versions = installed_versions::list(config.installations_dir()) .map_err(|source| Error::VersionListingError { source })?; let requested_version = self .version .or_else(|| { let current_dir = std::env::current_dir().unwrap(); get_user_version_for_directory(current_dir, config) }) .ok_or(Error::CantInferVersion)?; if matches!(requested_version, UserVersion::Full(Version::Bypassed)) { return Err(Error::CantUninstallSystemVersion); } let available_versions: Vec<&Version> = all_versions .iter() .filter(|v| requested_version.matches(v, config)) .collect(); if available_versions.len() >= 2 { return Err(Error::PleaseBeMoreSpecificToDelete { matched_versions: available_versions .iter() .map(std::string::ToString::to_string) .collect(), }); } let version = requested_version .to_version(&all_versions, config) .ok_or(Error::CantFindVersion)?; let matching_aliases = version.find_aliases(config)?; let root_path = version .root_path(config) .ok_or_else(|| Error::RootPathNotFound { version: version.clone(), })?; debug!("Removing Node version from {:?}", root_path); std::fs::remove_dir_all(root_path) .map_err(|source| Error::CantDeleteNodeVersion { source })?; outln!( config, Info, "Node version {} was removed successfully", version.v_str().cyan() ); for alias in matching_aliases { debug!("Removing alias from {:?}", alias.path()); remove_symlink_dir(alias.path()) .map_err(|source| Error::CantDeleteSymlink { source })?; outln!( config, Info, "Alias {} was removed successfully", alias.name().cyan() ); } Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error("Can't get locally installed versions: {}", source)] VersionListingError { source: installed_versions::Error }, #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] CantInferVersion, #[error("Can't uninstall system version")] CantUninstallSystemVersion, #[error("Too many versions had matched, please be more specific.\nFound {} matching versions, expected 1:\n{}", matched_versions.len(), matched_versions.iter().map(|v| format!("* {v}")).collect::>().join("\n"))] PleaseBeMoreSpecificToDelete { matched_versions: Vec }, #[error("Can't find a matching version")] CantFindVersion, #[error("Root path not found for version {}", version)] RootPathNotFound { version: Version }, #[error("io error: {}", source)] IoError { #[from] source: std::io::Error, }, #[error("Can't delete Node.js version: {}", source)] CantDeleteNodeVersion { source: std::io::Error }, #[error("Can't delete symlink: {}", source)] CantDeleteSymlink { source: std::io::Error }, } ================================================ FILE: src/commands/use.rs ================================================ use super::command::Command; use super::install::Install; use crate::current_version::current_version; use crate::fs; use crate::installed_versions; use crate::outln; use crate::shell; use crate::system_version; use crate::user_version::UserVersion; use crate::version::Version; use crate::version_file_strategy::VersionFileStrategy; use crate::{config::FnmConfig, user_version_reader::UserVersionReader}; use colored::Colorize; use std::path::Path; use thiserror::Error; #[derive(clap::Parser, Debug)] pub struct Use { pub version: Option, /// Install the version if it isn't installed yet #[clap(long)] pub install_if_missing: bool, /// Don't output a message identifying the version being used /// if it will not change due to execution of this command #[clap(long)] pub silent_if_unchanged: bool, /// Print informational output to stderr (used internally by `fnm env`) #[clap(skip)] pub info_to_stderr: bool, } impl Command for Use { type Error = Error; fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> { let multishell_path = config.multishell_path().ok_or(Error::FnmEnvWasNotSourced)?; warn_if_multishell_path_not_in_path_env_var(multishell_path, config); let all_versions = installed_versions::list(config.installations_dir()) .map_err(|source| Error::VersionListingError { source })?; let requested_version = self .version .unwrap_or_else(|| { let current_dir = std::env::current_dir().unwrap(); UserVersionReader::Path(current_dir) }) .into_user_version(config) .ok_or_else(|| match config.version_file_strategy() { VersionFileStrategy::Local => InferVersionError::Local, VersionFileStrategy::Recursive => InferVersionError::Recursive, }) .map_err(|source| Error::CantInferVersion { source }); // Swallow the missing version error if `silent_if_unchanged` was provided let requested_version = match (self.silent_if_unchanged, requested_version) { (true, Err(_)) => return Ok(()), (_, v) => v?, }; let (message, version_path) = if let UserVersion::Full(Version::Bypassed) = requested_version { let message = format!( "Bypassing fnm: using {} node", system_version::display_name().cyan() ); (message, system_version::path()) } else if let Some(alias_name) = requested_version.alias_name() { let alias_path = config.aliases_dir().join(&alias_name); let system_path = system_version::path(); if matches!(fs::shallow_read_symlink(&alias_path), Ok(shallow_path) if shallow_path == system_path) { let message = format!( "Bypassing fnm: using {} node", system_version::display_name().cyan() ); (message, system_path) } else if alias_path.exists() { let message = format!("Using Node for alias {}", alias_name.cyan()); (message, alias_path) } else { install_new_version(requested_version, config, self.install_if_missing)?; return Ok(()); } } else { let current_version = requested_version.to_version(&all_versions, config); if let Some(version) = current_version { let version_path = config .installations_dir() .join(version.to_string()) .join("installation"); let message = format!("Using Node {}", version.to_string().cyan()); (message, version_path) } else { install_new_version(requested_version, config, self.install_if_missing)?; return Ok(()); } }; if !self.silent_if_unchanged || will_version_change(&version_path, config) { if self.info_to_stderr { outln!(config, Error, "{}", message); } else { outln!(config, Info, "{}", message); } } if let Some(multishells_path) = multishell_path.parent() { std::fs::create_dir_all(multishells_path).map_err(|_err| { Error::MultishellDirectoryCreationIssue { path: multishells_path.to_path_buf(), } })?; } replace_symlink(&version_path, multishell_path) .map_err(|source| Error::SymlinkingCreationIssue { source })?; Ok(()) } } fn will_version_change(resolved_path: &Path, config: &FnmConfig) -> bool { let current_version_path = current_version(config) .unwrap_or(None) .map(|v| v.installation_path(config)); current_version_path.as_deref() != Some(resolved_path) } fn install_new_version( requested_version: UserVersion, config: &FnmConfig, install_if_missing: bool, ) -> Result<(), Error> { if !install_if_missing && !should_install_interactively(&requested_version) { return Err(Error::CantFindVersion { version: requested_version, }); } Install { version: Some(requested_version.clone()), ..Install::default() } .apply(config) .map_err(|source| Error::InstallError { source })?; Use { version: Some(UserVersionReader::Direct(requested_version)), install_if_missing: true, silent_if_unchanged: false, info_to_stderr: false, } .apply(config)?; Ok(()) } /// Tries to delete `from`, and then tries to symlink `from` to `to` anyway. /// If the symlinking fails, it will return the errors in the following order: /// * The deletion error (if exists) /// * The creation error /// /// This way, we can create a symlink if it is missing. fn replace_symlink(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> { let symlink_deletion_result = fs::remove_symlink_dir(to); match fs::symlink_dir(from, to) { ok @ Ok(()) => ok, err @ Err(_) => symlink_deletion_result.and(err), } } fn should_install_interactively(requested_version: &UserVersion) -> bool { use std::io::{IsTerminal, Write}; if !(std::io::stdout().is_terminal() && std::io::stdin().is_terminal()) { return false; } let error_message = format!( "fnm can't find an installed Node version matching {}.", requested_version.to_string().italic() ); eprintln!("{}", error_message.red()); let do_you_want = format!("Do you want to install it? {} [y/N]:", "answer".bold()); eprint!("{} ", do_you_want.yellow()); std::io::stdout().flush().unwrap(); let mut s = String::new(); std::io::stdin() .read_line(&mut s) .expect("Can't read user input"); s.trim().to_lowercase() == "y" } fn warn_if_multishell_path_not_in_path_env_var( multishell_path: &std::path::Path, config: &FnmConfig, ) { if let Some(path_var) = std::env::var_os("PATH") { let bin_path = if cfg!(unix) { multishell_path.join("bin") } else { multishell_path.to_path_buf() }; let fixed_path = bin_path.to_str().and_then(shell::maybe_fix_windows_path); let fixed_path = fixed_path.as_deref(); for path in std::env::split_paths(&path_var) { if bin_path == path || fixed_path == path.to_str() { return; } } } outln!( config, Error, "{} {}\n{}\n{}", "warning:".yellow().bold(), "The current Node.js path is not on your PATH environment variable.".yellow(), "You should setup your shell profile to evaluate `fnm env`, see https://github.com/Schniz/fnm#shell-setup on how to do this".yellow(), "Check out our documentation for more information: https://fnm.vercel.app".yellow() ); } #[derive(Debug, Error)] pub enum Error { #[error("Can't create the symlink: {}", source)] SymlinkingCreationIssue { source: std::io::Error }, #[error(transparent)] InstallError { source: ::Error }, #[error("Can't get locally installed versions: {}", source)] VersionListingError { source: installed_versions::Error }, #[error("Requested version {} is not currently installed", version)] CantFindVersion { version: UserVersion }, #[error(transparent)] CantInferVersion { #[from] source: InferVersionError, }, #[error( "{}\n{}\n{}", "We can't find the necessary environment variables to replace the Node version.", "You should setup your shell profile to evaluate `fnm env`, see https://github.com/Schniz/fnm#shell-setup on how to do this", "Check out our documentation for more information: https://fnm.vercel.app" )] FnmEnvWasNotSourced, #[error("Can't create the multishell directory: {}", path.display())] MultishellDirectoryCreationIssue { path: std::path::PathBuf }, } #[derive(Debug, Error)] pub enum InferVersionError { #[error("Can't find version in dotfiles. Please provide a version manually to the command.")] Local, #[error("Could not find any version to use. Maybe you don't have a default version set?\nTry running `fnm default ` to set one,\nor create a .node-version file inside your project to declare a Node.js version.")] Recursive, } ================================================ FILE: src/config.rs ================================================ use crate::arch::Arch; use crate::directories::Directories; use crate::log_level::LogLevel; use crate::path_ext::PathExt; use crate::version_file_strategy::VersionFileStrategy; use url::Url; #[derive(clap::Parser, Debug, Clone)] pub struct FnmConfig { /// mirror #[clap( long, env = "FNM_NODE_DIST_MIRROR", default_value = "https://nodejs.org/dist", global = true, hide_env_values = true )] pub node_dist_mirror: Url, /// The root directory of fnm installations. #[clap( long = "fnm-dir", env = "FNM_DIR", global = true, hide_env_values = true )] pub base_dir: Option, /// Where the current node version link is stored. /// This value will be populated automatically by evaluating /// `fnm env` in your shell profile. Read more about it using `fnm help env` #[clap(long, env = "FNM_MULTISHELL_PATH", hide_env_values = true, hide = true)] multishell_path: Option, /// The log level of fnm commands #[clap( long, env = "FNM_LOGLEVEL", default_value_t, global = true, hide_env_values = true )] log_level: LogLevel, /// Override the architecture of the installed Node binary. /// Defaults to arch of fnm binary. #[clap( long, env = "FNM_ARCH", default_value_t, global = true, hide_env_values = true, hide_default_value = true )] pub arch: Arch, /// A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is /// called without a version, or when `--use-on-cd` is configured on evaluation. #[clap( long, env = "FNM_VERSION_FILE_STRATEGY", default_value_t, global = true, hide_env_values = true )] version_file_strategy: VersionFileStrategy, /// Enable corepack support for each new installation. /// This will make fnm call `corepack enable` on every Node.js installation. /// For more information about corepack see #[clap( long, env = "FNM_COREPACK_ENABLED", global = true, hide_env_values = true )] corepack_enabled: bool, /// Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present. /// This feature is enabled by default. To disable it, provide `--resolve-engines=false`. /// /// Note: `engines.node` can be any semver range, with the latest satisfying version being resolved. /// Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it. /// In the future, disabling it might be a no-op, so it's worth knowing any reason to /// do that. #[clap( long, env = "FNM_RESOLVE_ENGINES", global = true, hide_env_values = true, verbatim_doc_comment )] #[expect( clippy::option_option, reason = "clap Option> supports --x and --x=value syntaxes" )] resolve_engines: Option>, #[clap(skip)] directories: Directories, } impl Default for FnmConfig { fn default() -> Self { Self { node_dist_mirror: Url::parse("https://nodejs.org/dist/").unwrap(), base_dir: None, multishell_path: None, log_level: LogLevel::Info, arch: Arch::default(), version_file_strategy: VersionFileStrategy::default(), corepack_enabled: false, resolve_engines: None, directories: Directories::default(), } } } impl FnmConfig { pub fn version_file_strategy(&self) -> VersionFileStrategy { self.version_file_strategy } pub fn corepack_enabled(&self) -> bool { self.corepack_enabled } pub fn resolve_engines(&self) -> bool { self.resolve_engines.flatten().unwrap_or(true) } pub fn multishell_path(&self) -> Option<&std::path::Path> { match &self.multishell_path { None => None, Some(v) => Some(v.as_path()), } } pub fn log_level(&self) -> LogLevel { self.log_level } pub fn base_dir_with_default(&self) -> std::path::PathBuf { if let Some(dir) = &self.base_dir { return dir.clone(); } self.directories.default_base_dir() } pub fn installations_dir(&self) -> std::path::PathBuf { self.base_dir_with_default() .join("node-versions") .ensure_exists_silently() } pub fn default_version_dir(&self) -> std::path::PathBuf { self.aliases_dir().join("default") } pub fn aliases_dir(&self) -> std::path::PathBuf { self.base_dir_with_default() .join("aliases") .ensure_exists_silently() } pub fn multishell_storage(&self) -> std::path::PathBuf { self.directories.multishell_storage() } #[cfg(test)] pub fn with_base_dir(mut self, base_dir: Option) -> Self { self.base_dir = base_dir; self } pub fn with_multishell_path(mut self, multishell_path: std::path::PathBuf) -> Self { self.multishell_path = Some(multishell_path); self } } ================================================ FILE: src/current_version.rs ================================================ use thiserror::Error; use crate::config::FnmConfig; use crate::system_version; use crate::version::Version; pub fn current_version(config: &FnmConfig) -> Result, Error> { let multishell_path = config.multishell_path().ok_or(Error::EnvNotApplied)?; if multishell_path.read_link().ok() == Some(system_version::path()) { return Ok(Some(Version::Bypassed)); } if let Ok(resolved_path) = std::fs::canonicalize(multishell_path) { let installation_path = resolved_path .parent() .expect("multishell path can't be in the root"); let file_name = installation_path .file_name() .expect("Can't get filename") .to_str() .expect("Invalid OS string"); let version = Version::parse(file_name).map_err(|source| Error::VersionError { source, version: file_name.to_string(), })?; Ok(Some(version)) } else { Ok(None) } } #[derive(Debug, Error)] pub enum Error { #[error("`fnm env` was not applied in this context.\nCan't find fnm's environment variables")] EnvNotApplied, #[error("Can't read the version as a valid semver")] VersionError { source: node_semver::SemverError, version: String, }, } ================================================ FILE: src/default_version.rs ================================================ use crate::config::FnmConfig; use crate::version::Version; use std::str::FromStr; pub fn find_default_version(config: &FnmConfig) -> Option { if let Ok(version_path) = config.default_version_dir().canonicalize() { let file_name = version_path.parent()?.file_name()?; Version::from_str(file_name.to_str()?).ok()?.into() } else { Some(Version::Alias("default".into())) } } ================================================ FILE: src/directories.rs ================================================ use etcetera::BaseStrategy; use std::path::PathBuf; use crate::path_ext::PathExt; fn xdg_dir(env: &str) -> Option { if cfg!(windows) { let env_var = std::env::var_os(env)?; Some(PathBuf::from(env_var)) } else { // On non-Windows platforms, `etcetera` already handles XDG variables None } } fn runtime_dir(basedirs: &impl BaseStrategy) -> Option { xdg_dir("XDG_RUNTIME_DIR").or_else(|| basedirs.runtime_dir()) } fn state_dir(basedirs: &impl BaseStrategy) -> Option { xdg_dir("XDG_STATE_HOME").or_else(|| basedirs.state_dir()) } fn cache_dir(basedirs: &impl BaseStrategy) -> PathBuf { xdg_dir("XDG_CACHE_HOME").unwrap_or_else(|| basedirs.cache_dir()) } /// A helper struct for directories in fnm that uses XDG Base Directory Specification /// if applicable for the platform. #[derive(Debug, Clone)] pub struct Directories( #[cfg(windows)] etcetera::base_strategy::Windows, #[cfg(not(windows))] etcetera::base_strategy::Xdg, ); impl Default for Directories { fn default() -> Self { Self(etcetera::choose_base_strategy().expect("choosing base strategy")) } } impl Directories { pub fn strategy(&self) -> &impl BaseStrategy { &self.0 } pub fn default_base_dir(&self) -> PathBuf { let strategy = self.strategy(); let modern = strategy.data_dir().join("fnm"); if modern.exists() { return modern; } let legacy = strategy.home_dir().join(".fnm"); if legacy.exists() { return legacy; } #[cfg(target_os = "macos")] { let basedirs = etcetera::base_strategy::Apple::new().expect("Can't get home directory"); let legacy = basedirs.data_dir().join("fnm"); if legacy.exists() { return legacy; } } modern.ensure_exists_silently() } pub fn multishell_storage(&self) -> PathBuf { let basedirs = self.strategy(); let dir = runtime_dir(basedirs) .or_else(|| state_dir(basedirs)) .unwrap_or_else(|| cache_dir(basedirs)); dir.join("fnm_multishells") } } ================================================ FILE: src/directory_portal.rs ================================================ use log::debug; use std::path::Path; use tempfile::TempDir; /// A "work-in-progress" directory, which will "teleport" into the path /// given in `target` only on successful, guarding from invalid state in the file system. /// /// Underneath, it uses `fs::rename`, so make sure to make the `temp_dir` inside the same /// mount as `target`. This is why we have the `new_in` constructor. pub struct DirectoryPortal> { temp_dir: TempDir, target: P, } impl> DirectoryPortal

{ /// Create a new portal which will keep the temp files in /// a subdirectory of `parent_dir` until teleporting to `target`. #[must_use] pub fn new_in(parent_dir: impl AsRef, target: P) -> Self { let temp_dir = TempDir::new_in(parent_dir).expect("Can't generate a temp directory"); debug!("Created a temp directory in {:?}", temp_dir.path()); Self { temp_dir, target } } pub fn teleport(self) -> std::io::Result

{ debug!( "Moving directory {:?} into {:?}", self.temp_dir.path(), self.target.as_ref() ); std::fs::rename(&self.temp_dir, &self.target)?; Ok(self.target) } } impl> std::ops::Deref for DirectoryPortal

{ type Target = Path; fn deref(&self) -> &Self::Target { self.as_ref() } } impl> AsRef for DirectoryPortal

{ fn as_ref(&self) -> &Path { self.temp_dir.as_ref() } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use tempfile::tempdir; #[test_log::test] fn test_portal() { let tempdir = tempdir().expect("Can't generate a temp directory"); let portal = DirectoryPortal::new_in(std::env::temp_dir(), tempdir.path().join("subdir")); let new_file_path = portal.to_path_buf().join("README.md"); std::fs::write(new_file_path, "Hello world!").expect("Can't write file"); let target = portal.teleport().expect("Can't close directory portal"); let file_exists: Vec<_> = target .read_dir() .expect("Can't read dir") .map(|x| x.unwrap().file_name().into_string().unwrap()) .collect(); assert_eq!(file_exists, vec!["README.md"]); } } ================================================ FILE: src/downloader.rs ================================================ use crate::arch::Arch; use crate::archive::{Archive, Error as ExtractError}; use crate::directory_portal::DirectoryPortal; use crate::progress::ResponseProgress; use crate::version::Version; use indicatif::ProgressDrawTarget; use log::debug; use std::path::Path; use std::path::PathBuf; use thiserror::Error; use url::Url; #[derive(Debug, Error)] pub enum Error { #[error(transparent)] HttpError { #[from] source: crate::http::Error, }, #[error(transparent)] IoError { #[from] source: std::io::Error, }, #[error("Can't extract the file: {}", source)] CantExtractFile { #[from] source: ExtractError, }, #[error("The downloaded archive is empty")] TarIsEmpty, #[error("{} for {} not found upstream.\nYou can `fnm ls-remote` to see available versions or try a different `--arch`.", version, arch)] VersionNotFound { version: Version, arch: Arch }, #[error("Version already installed at {:?}", path)] VersionAlreadyInstalled { path: PathBuf }, } #[cfg(unix)] fn filename_for_version(version: &Version, arch: Arch, ext: &str) -> String { format!( "node-{node_ver}-{platform}-{arch}.{ext}", node_ver = &version, platform = crate::system_info::platform_name(), arch = arch, ext = ext ) } #[cfg(windows)] fn filename_for_version(version: &Version, arch: Arch, ext: &str) -> String { format!( "node-{node_ver}-win-{arch}.{ext}", node_ver = &version, arch = arch, ext = ext, ) } fn download_url(base_url: &Url, version: &Version, arch: Arch, ext: &str) -> Url { Url::parse(&format!( "{}/{}/{}", base_url.as_str().trim_end_matches('/'), version, filename_for_version(version, arch, ext) )) .unwrap() } /// Install a Node package pub fn install_node_dist>( version: &Version, node_dist_mirror: &Url, installations_dir: P, arch: Arch, show_progress: bool, ) -> Result<(), Error> { let installation_dir = PathBuf::from(installations_dir.as_ref()).join(version.v_str()); if installation_dir.exists() { return Err(Error::VersionAlreadyInstalled { path: installation_dir, }); } std::fs::create_dir_all(installations_dir.as_ref())?; let temp_installations_dir = installations_dir.as_ref().join(".downloads"); std::fs::create_dir_all(&temp_installations_dir)?; let portal = DirectoryPortal::new_in(&temp_installations_dir, installation_dir); for extract in Archive::supported() { let ext = extract.file_extension(); let url = download_url(node_dist_mirror, version, arch, ext); debug!("Going to call for {}", &url); let response = crate::http::get(url.as_str())?; if !response.status().is_success() { continue; } debug!("Extracting response..."); if show_progress { extract.extract_archive_into( portal.as_ref(), ResponseProgress::new(response, ProgressDrawTarget::stderr()), )?; } else { extract.extract_archive_into(portal.as_ref(), response)?; } debug!("Extraction completed"); let installed_directory = std::fs::read_dir(&portal)? .next() .ok_or(Error::TarIsEmpty)??; let installed_directory = installed_directory.path(); let renamed_installation_dir = portal.join("installation"); std::fs::rename(installed_directory, renamed_installation_dir)?; portal.teleport()?; return Ok(()); } Err(Error::VersionNotFound { version: version.clone(), arch, }) } #[cfg(test)] mod tests { use super::*; use crate::downloader::install_node_dist; use crate::version::Version; use pretty_assertions::assert_eq; use tempfile::tempdir; #[test_log::test] fn test_installing_node_12() { let installations_dir = tempdir().unwrap(); let node_path = install_in(installations_dir.path()).join("node"); let stdout = duct::cmd(node_path.to_str().unwrap(), vec!["--version"]) .stdout_capture() .run() .expect("Can't run Node binary") .stdout; let result = String::from_utf8(stdout).expect("Can't read `node --version` output"); assert_eq!(result.trim(), "v12.0.0"); } #[test_log::test] fn test_installing_npm() { let installations_dir = tempdir().unwrap(); let bin_dir = install_in(installations_dir.path()); let npm_path = bin_dir.join(if cfg!(windows) { "npm.cmd" } else { "npm" }); let stdout = duct::cmd(npm_path.to_str().unwrap(), vec!["--version"]) .env("PATH", bin_dir) .stdout_capture() .run() .expect("Can't run npm") .stdout; let result = String::from_utf8(stdout).expect("Can't read npm output"); assert_eq!(result.trim(), "6.9.0"); } fn install_in(path: &Path) -> PathBuf { let version = Version::parse("12.0.0").unwrap(); let arch = Arch::X64; let node_dist_mirror = Url::parse("https://nodejs.org/dist/").unwrap(); install_node_dist(&version, &node_dist_mirror, path, arch, false) .expect("Can't install Node 12"); let mut location_path = path.join(version.v_str()).join("installation"); if cfg!(unix) { location_path.push("bin"); } location_path } } ================================================ FILE: src/fs.rs ================================================ use std::path::Path; #[cfg(unix)] pub fn symlink_dir, U: AsRef>(from: P, to: U) -> std::io::Result<()> { std::os::unix::fs::symlink(from, to)?; Ok(()) } #[cfg(windows)] pub fn symlink_dir, U: AsRef>(from: P, to: U) -> std::io::Result<()> { junction::create(from, to)?; Ok(()) } #[cfg(windows)] pub fn remove_symlink_dir>(path: P) -> std::io::Result<()> { std::fs::remove_dir(path)?; Ok(()) } #[cfg(unix)] pub fn remove_symlink_dir>(path: P) -> std::io::Result<()> { std::fs::remove_file(path)?; Ok(()) } pub fn shallow_read_symlink>(path: P) -> std::io::Result { std::fs::read_link(path) } ================================================ FILE: src/http.rs ================================================ //! This module is an adapter for HTTP related operations. //! In the future, if we want to migrate to a different HTTP library, //! we can easily change this facade instead of multiple places in the crate. use reqwest::{blocking::Client, IntoUrl}; #[derive(Debug, thiserror::Error, miette::Diagnostic)] #[error(transparent)] #[diagnostic(code("fnm::http::error"))] pub struct Error(#[from] reqwest::Error); pub type Response = reqwest::blocking::Response; pub fn get(url: impl IntoUrl) -> Result { Ok(Client::new() .get(url) // Some sites require a user agent. .header("User-Agent", concat!("fnm ", env!("CARGO_PKG_VERSION"))) .send()?) } ================================================ FILE: src/installed_versions.rs ================================================ use crate::version::Version; use std::path::Path; use thiserror::Error; pub fn list>(installations_dir: P) -> Result, Error> { let mut vec = vec![]; for result_entry in installations_dir.as_ref().read_dir()? { let entry = result_entry?; if entry .file_name() .to_str() .is_some_and(|s| s.starts_with('.')) { continue; } let path = entry.path(); let filename = path .file_name() .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))? .to_str() .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?; let version = Version::parse(filename)?; vec.push(version); } Ok(vec) } #[derive(Debug, Error)] pub enum Error { #[error(transparent)] IoError { #[from] source: std::io::Error, }, #[error(transparent)] SemverError { #[from] source: node_semver::SemverError, }, } ================================================ FILE: src/log_level.rs ================================================ use std::fmt::Display; use clap::ValueEnum; #[derive(Debug, Default, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, ValueEnum)] pub enum LogLevel { Quiet, Error, #[default] #[value(alias("all"))] Info, } impl LogLevel { pub fn as_str(self) -> &'static str { match self { Self::Quiet => "quiet", Self::Info => "info", Self::Error => "error", } } pub fn is_writable(self, logging: Self) -> bool { use std::cmp::Ordering; matches!(self.cmp(&logging), Ordering::Greater | Ordering::Equal) } pub fn writer_for(self, logging: Self) -> Box { if self.is_writable(logging) { match logging { Self::Error => Box::from(std::io::stderr()), _ => Box::from(std::io::stdout()), } } else { Box::from(std::io::sink()) } } pub fn possible_values() -> &'static [&'static str; 4] { &["quiet", "info", "all", "error"] } } impl Display for LogLevel { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } #[macro_export] macro_rules! outln { ($config:ident, $level:path, $($expr:expr),+) => {{ use $crate::log_level::LogLevel::*; writeln!($config.log_level().writer_for($level), $($expr),+).expect("Can't write output"); }} } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_writable() { assert!(!LogLevel::Quiet.is_writable(LogLevel::Info)); assert!(!LogLevel::Error.is_writable(LogLevel::Info)); assert!(LogLevel::Info.is_writable(LogLevel::Info)); assert!(LogLevel::Info.is_writable(LogLevel::Error)); } } ================================================ FILE: src/lts.rs ================================================ use crate::remote_node_index::IndexedNodeVersion; use std::fmt::Display; #[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)] pub enum LtsType { /// lts-*, lts/* Latest, /// lts-erbium, lts/erbium CodeName(String), } impl From<&str> for LtsType { fn from(s: &str) -> Self { if s == "*" || s == "latest" { Self::Latest } else { Self::CodeName(s.to_string()) } } } impl Display for LtsType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Latest => f.write_str("latest"), Self::CodeName(s) => f.write_str(s), } } } impl LtsType { pub fn pick_latest<'vec>( &self, versions: &'vec [IndexedNodeVersion], ) -> Option<&'vec IndexedNodeVersion> { match self { Self::Latest => versions.iter().filter(|x| x.lts.is_some()).next_back(), Self::CodeName(s) => versions .iter() .filter(|x| match &x.lts { None => false, Some(x) => s.to_lowercase() == x.to_lowercase(), }) .next_back(), } } } ================================================ FILE: src/main.rs ================================================ #![warn(rust_2018_idioms, clippy::all, clippy::pedantic)] #![allow( clippy::enum_variant_names, clippy::large_enum_variant, clippy::module_name_repetitions, clippy::similar_names )] mod alias; mod arch; mod archive; mod choose_version_for_user_input; mod cli; mod commands; mod config; mod current_version; mod directory_portal; mod downloader; mod fs; mod http; mod installed_versions; mod lts; mod package_json; mod path_ext; mod progress; mod remote_node_index; mod shell; mod system_info; mod system_version; mod user_version; mod user_version_reader; mod version; mod version_file_strategy; mod version_files; #[macro_use] mod log_level; mod default_version; mod directories; mod pretty_serde; fn main() { env_logger::init(); let value = crate::cli::parse(); value.subcmd.call(value.config); } ================================================ FILE: src/package_json.rs ================================================ use serde::Deserialize; #[derive(Debug, Deserialize, Default)] struct EnginesField { node: Option, } #[derive(Debug, Deserialize, Default)] pub struct PackageJson { engines: Option, } impl PackageJson { pub fn node_range(&self) -> Option<&node_semver::Range> { self.engines .as_ref() .and_then(|engines| engines.node.as_ref()) } } ================================================ FILE: src/path_ext.rs ================================================ use log::warn; pub trait PathExt { fn ensure_exists_silently(self) -> Self; } impl> PathExt for T { /// Ensures a path is existing by creating it recursively /// if it is missing. No error is emitted if the creation has failed. fn ensure_exists_silently(self) -> Self { if let Err(err) = std::fs::create_dir_all(self.as_ref()) { warn!("Failed to create directory {:?}: {}", self.as_ref(), err); } self } } ================================================ FILE: src/pretty_serde.rs ================================================ use miette::SourceOffset; #[derive(Debug, thiserror::Error, miette::Diagnostic)] #[error("malformed json\n{}", self.report())] pub struct DecodeError { cause: serde_json::Error, #[source_code] input: String, #[label("at this position")] location: SourceOffset, } #[derive(Debug, thiserror::Error, miette::Diagnostic)] #[error("")] pub struct ClonedError { message: String, #[source_code] input: String, #[label("{message}")] location: SourceOffset, } impl DecodeError { pub fn from_serde(input: impl Into, cause: serde_json::Error) -> Self { let input = input.into(); let location = SourceOffset::from_location(&input, cause.line(), cause.column()); DecodeError { cause, input, location, } } pub fn report(&self) -> String { use colored::Colorize; let report = miette::Report::from(ClonedError { message: self.cause.to_string().italic().to_string(), input: self.input.clone(), location: self.location, }); let mut output = String::new(); for line in format!("{report:?}").lines().skip(1) { use std::fmt::Write; writeln!(&mut output, "{line}").unwrap(); } output.white().to_string() } } ================================================ FILE: src/progress.rs ================================================ use std::io::Read; use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}; use reqwest::blocking::Response; pub struct ResponseProgress { progress: Option, response: Response, } #[derive(Default, Clone, Debug, clap::ValueEnum)] pub enum ProgressConfig { #[default] Auto, Never, Always, } impl ProgressConfig { pub fn enabled(&self, config: &crate::config::FnmConfig) -> bool { match self { Self::Never => false, Self::Always => true, Self::Auto => config .log_level() .is_writable(crate::log_level::LogLevel::Info), } } } fn make_progress_bar(size: u64, target: ProgressDrawTarget) -> ProgressBar { let bar = ProgressBar::with_draw_target(Some(size), target); bar.set_style( ProgressStyle::with_template( "{elapsed_precise:.white.dim} {wide_bar:.cyan} {bytes}/{total_bytes} ({bytes_per_sec}, {eta})", ) .unwrap() .progress_chars("█▉▊▋▌▍▎▏ "), ); bar } impl ResponseProgress { pub fn new(response: Response, target: ProgressDrawTarget) -> Self { Self { progress: response .content_length() .map(|len| make_progress_bar(len, target)), response, } } pub fn finish(&self) { if let Some(ref bar) = self.progress { bar.finish(); } } } impl Read for ResponseProgress { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let size = self.response.read(buf)?; if let Some(ref bar) = self.progress { bar.inc(size as u64); } Ok(size) } } impl Drop for ResponseProgress { fn drop(&mut self) { self.finish(); eprintln!(); } } #[cfg(test)] mod tests { use indicatif::{ProgressDrawTarget, TermLike}; use reqwest::blocking::Response; use std::{ io::Read, sync::{Arc, Mutex}, }; use super::ResponseProgress; const CONTENT_LENGTH: usize = 100; #[derive(Debug)] struct MockedTerm { pub buf: Arc>, } impl TermLike for MockedTerm { fn width(&self) -> u16 { 80 } fn move_cursor_up(&self, _n: usize) -> std::io::Result<()> { Ok(()) } fn move_cursor_down(&self, _n: usize) -> std::io::Result<()> { Ok(()) } fn move_cursor_right(&self, _n: usize) -> std::io::Result<()> { Ok(()) } fn move_cursor_left(&self, _n: usize) -> std::io::Result<()> { Ok(()) } fn write_line(&self, s: &str) -> std::io::Result<()> { self.buf.lock().unwrap().push_str(s); Ok(()) } fn write_str(&self, s: &str) -> std::io::Result<()> { self.buf.lock().unwrap().push_str(s); Ok(()) } fn clear_line(&self) -> std::io::Result<()> { Ok(()) } fn flush(&self) -> std::io::Result<()> { Ok(()) } } #[test] fn test_reads_data_and_shows_progress() { let response: Response = http::Response::builder() .header("Content-Length", CONTENT_LENGTH) .body("a".repeat(CONTENT_LENGTH)) .unwrap() .into(); let mut buf = [0; CONTENT_LENGTH]; let out_buf = Arc::new(Mutex::new(String::new())); let mut progress = ResponseProgress::new( response, ProgressDrawTarget::term_like(Box::new(MockedTerm { buf: out_buf.clone(), })), ); let size = progress.read(&mut buf[..]).unwrap(); drop(progress); assert_eq!(size, CONTENT_LENGTH); assert_eq!(buf, "a".repeat(CONTENT_LENGTH).as_bytes()); assert!(out_buf.lock().unwrap().contains(&"█".repeat(40))); } } ================================================ FILE: src/remote_node_index.rs ================================================ use crate::{pretty_serde::DecodeError, version::Version}; use serde::Deserialize; use url::Url; mod lts_status { use serde::{Deserialize, Deserializer}; #[derive(Deserialize, Debug, PartialEq, Eq)] #[serde(untagged)] enum LtsStatus { Nope(bool), Yes(String), } impl From for Option { fn from(status: LtsStatus) -> Self { match status { LtsStatus::Nope(_) => None, LtsStatus::Yes(x) => Some(x), } } } pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { Ok(LtsStatus::deserialize(deserializer)?.into()) } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; #[derive(Deserialize)] struct TestSubject { #[serde(deserialize_with = "deserialize")] lts: Option, } #[test] fn test_false_deserialization() { let json = serde_json::json!({ "lts": false }); let subject: TestSubject = serde_json::from_value(json).expect("Can't deserialize json"); assert_eq!(subject.lts, None); } #[test] fn test_value_deserialization() { let json = serde_json::json!({ "lts": "dubnium" }); let subject: TestSubject = serde_json::from_value(json).expect("Can't deserialize json"); assert_eq!(subject.lts, Some("dubnium".into())); } } } #[derive(Deserialize, Debug)] pub struct IndexedNodeVersion { pub version: Version, #[serde(with = "lts_status")] pub lts: Option, // pub date: chrono::NaiveDate, // pub files: Vec, } #[derive(Debug, thiserror::Error, miette::Diagnostic)] pub enum Error { #[error("can't get remote versions file: {0}")] #[diagnostic(transparent)] Http(#[from] crate::http::Error), #[error("can't decode remote versions file: {0}")] #[diagnostic(transparent)] Decode(#[from] DecodeError), } /// Prints /// /// ```rust /// use crate::remote_node_index::list; /// ``` pub fn list(base_url: &Url) -> Result, Error> { let base_url = base_url.as_str().trim_end_matches('/'); let index_json_url = format!("{base_url}/index.json"); let resp = crate::http::get(&index_json_url)? .error_for_status() .map_err(crate::http::Error::from)?; let text = resp.text().map_err(crate::http::Error::from)?; let mut value: Vec = serde_json::from_str(&text[..]).map_err(|cause| DecodeError::from_serde(text, cause))?; value.sort_by(|a, b| a.version.cmp(&b.version)); Ok(value) } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; #[test] fn test_list() { let base_url = Url::parse("https://nodejs.org/dist").unwrap(); let expected_version = Version::parse("12.0.0").unwrap(); let mut versions = list(&base_url).expect("Can't get HTTP data"); assert_eq!( versions .drain(..) .find(|x| x.version == expected_version) .map(|x| x.version), Some(expected_version) ); } } ================================================ FILE: src/shell/bash.rs ================================================ use crate::version_file_strategy::VersionFileStrategy; use super::shell::Shell; use indoc::formatdoc; use std::path::Path; #[derive(Debug)] pub struct Bash; impl Shell for Bash { fn to_clap_shell(&self) -> clap_complete::Shell { clap_complete::Shell::Bash } fn path(&self, path: &Path) -> anyhow::Result { let path = path .to_str() .ok_or_else(|| anyhow::anyhow!("Can't convert path to string"))?; let path = super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); Ok(format!("export PATH={path:?}:\"$PATH\"")) } fn set_env_var(&self, name: &str, value: &str) -> String { format!("export {name}={value:?}") } fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result { let version_file_exists_condition = if config.resolve_engines() { "-f .node-version || -f .nvmrc || -f package.json" } else { "-f .node-version || -f .nvmrc" }; let autoload_hook = match config.version_file_strategy() { VersionFileStrategy::Local => formatdoc!( r" if [[ {version_file_exists_condition} ]]; then fnm use --silent-if-unchanged fi ", version_file_exists_condition = version_file_exists_condition, ), VersionFileStrategy::Recursive => String::from(r"fnm use --silent-if-unchanged"), }; Ok(formatdoc!( r#" __fnm_use_if_file_found() {{ {autoload_hook} }} __fnmcd() {{ \cd "$@" || return $? __fnm_use_if_file_found }} alias cd=__fnmcd "#, autoload_hook = autoload_hook )) } } ================================================ FILE: src/shell/fish.rs ================================================ use crate::version_file_strategy::VersionFileStrategy; use super::shell::Shell; use indoc::formatdoc; use std::path::Path; #[derive(Debug)] pub struct Fish; impl Shell for Fish { fn to_clap_shell(&self) -> clap_complete::Shell { clap_complete::Shell::Fish } fn path(&self, path: &Path) -> anyhow::Result { let path = path .to_str() .ok_or_else(|| anyhow::anyhow!("Can't convert path to string"))?; let path = super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); Ok(format!("set -gx PATH {path:?} $PATH;")) } fn set_env_var(&self, name: &str, value: &str) -> String { format!("set -gx {name} {value:?};") } fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result { let version_file_exists_condition = if config.resolve_engines() { "test -f .node-version -o -f .nvmrc -o -f package.json" } else { "test -f .node-version -o -f .nvmrc" }; let autoload_hook = match config.version_file_strategy() { VersionFileStrategy::Local => formatdoc!( r" if {version_file_exists_condition} fnm use --silent-if-unchanged end ", version_file_exists_condition = version_file_exists_condition, ), VersionFileStrategy::Recursive => String::from(r"fnm use --silent-if-unchanged"), }; Ok(formatdoc!( r" function _fnm_autoload_hook --on-variable PWD --description 'Change Node version on directory change' status --is-command-substitution; and return {autoload_hook} end ", autoload_hook = autoload_hook )) } } ================================================ FILE: src/shell/infer/mod.rs ================================================ mod unix; mod windows; #[cfg(unix)] pub use self::unix::infer_shell; #[cfg(not(unix))] pub use self::windows::infer_shell; fn shell_from_string(shell: &str) -> Option> { use super::{Bash, Fish, PowerShell, WindowsCmd, Zsh}; match shell { "sh" | "bash" => return Some(Box::from(Bash)), "zsh" => return Some(Box::from(Zsh)), "fish" => return Some(Box::from(Fish)), "pwsh" | "powershell" => return Some(Box::from(PowerShell)), "cmd" => return Some(Box::from(WindowsCmd)), cmd_name => log::debug!("binary is not a supported shell: {:?}", cmd_name), } None } ================================================ FILE: src/shell/infer/unix.rs ================================================ #![cfg(unix)] use crate::shell::Shell; use log::debug; use std::io::{Error, ErrorKind}; use thiserror::Error; #[derive(Debug)] struct ProcessInfo { parent_pid: Option, command: String, } const MAX_ITERATIONS: u8 = 10; pub fn infer_shell() -> Option> { let mut pid = Some(std::process::id()); let mut visited = 0; while let Some(current_pid) = pid { if visited > MAX_ITERATIONS { return None; } let process_info = get_process_info(current_pid) .map_err(|err| { debug!("{}", err); err }) .ok()?; let binary = process_info .command .trim_start_matches('-') .split('/') .next_back()?; if let Some(shell) = super::shell_from_string(binary) { return Some(shell); } pid = process_info.parent_pid; visited += 1; } None } fn get_process_info(pid: u32) -> Result { use std::io::{BufRead, BufReader}; use std::process::Command; let buffer = Command::new("ps") .arg("-o") .arg("ppid,comm") .arg(pid.to_string()) .stdout(std::process::Stdio::piped()) .spawn()? .stdout .ok_or_else(|| Error::from(ErrorKind::UnexpectedEof))?; let mut lines = BufReader::new(buffer).lines(); // skip header line lines .next() .ok_or_else(|| Error::from(ErrorKind::UnexpectedEof))??; let line = lines .next() .ok_or_else(|| Error::from(ErrorKind::NotFound))??; let mut parts = line.split_whitespace(); let ppid = parts.next().ok_or_else(|| ProcessInfoError::Parse { expectation: "Can't read the ppid from ps, should be the first item in the table", got: line.to_string(), })?; let command = parts.next().ok_or_else(|| ProcessInfoError::Parse { expectation: "Can't read the command from ps, should be the second item in the table", got: line.to_string(), })?; Ok(ProcessInfo { parent_pid: ppid.parse().ok(), command: command.into(), }) } #[derive(Debug, Error)] enum ProcessInfoError { #[error("Can't read process info: {source}")] Io { #[source] #[from] source: std::io::Error, }, #[error("Can't parse process info output. {expectation}. Got: {got}")] Parse { got: String, expectation: &'static str, }, } #[cfg(all(test, unix))] mod tests { use super::*; use pretty_assertions::assert_eq; use std::process::{Command, Stdio}; #[test] fn test_get_process_info() -> anyhow::Result<()> { let subprocess = Command::new("bash") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; let process_info = get_process_info(subprocess.id()); let parent_pid = process_info.ok().and_then(|x| x.parent_pid); assert_eq!(parent_pid, Some(std::process::id())); Ok(()) } } ================================================ FILE: src/shell/infer/windows.rs ================================================ #![cfg(not(unix))] use crate::shell::Shell; use log::{debug, warn}; use sysinfo::{ProcessRefreshKind, System, UpdateKind}; pub fn infer_shell() -> Option> { let mut system = System::new(); let mut current_pid = sysinfo::get_current_pid().ok(); system .refresh_processes_specifics(ProcessRefreshKind::new().with_exe(UpdateKind::OnlyIfNotSet)); while let Some(pid) = current_pid { if let Some(process) = system.process(pid) { current_pid = process.parent(); debug!("pid {pid} parent process is {current_pid:?}"); let process_name = process .exe() .and_then(|x| { tap_none(x.file_stem(), || { warn!("failed to get file stem from {:?}", x); }) }) .and_then(|x| { tap_none(x.to_str(), || { warn!("failed to convert file stem to string: {:?}", x); }) }) .map(str::to_lowercase); if let Some(shell) = process_name .as_ref() .map(|x| &x[..]) .and_then(super::shell_from_string) { return Some(shell); } } else { warn!("process not found for {pid}"); current_pid = None; } } None } fn tap_none(opt: Option, f: F) -> Option where F: FnOnce(), { match &opt { Some(_) => (), None => f(), }; opt } ================================================ FILE: src/shell/mod.rs ================================================ mod bash; mod fish; mod infer; mod powershell; mod windows_cmd; mod zsh; #[allow(clippy::module_inception)] mod shell; mod windows_compat; pub use bash::Bash; pub use fish::Fish; pub use infer::infer_shell; pub use powershell::PowerShell; pub use shell::{Shell, Shells}; pub use windows_cmd::WindowsCmd; pub use windows_compat::maybe_fix_windows_path; pub use zsh::Zsh; ================================================ FILE: src/shell/powershell.rs ================================================ use crate::version_file_strategy::VersionFileStrategy; use super::Shell; use indoc::formatdoc; use std::path::Path; #[derive(Debug)] pub struct PowerShell; impl Shell for PowerShell { fn path(&self, path: &Path) -> anyhow::Result { let current_path = std::env::var_os("PATH").ok_or_else(|| anyhow::anyhow!("Can't read PATH env var"))?; let mut split_paths: Vec<_> = std::env::split_paths(¤t_path).collect(); split_paths.insert(0, path.to_path_buf()); let new_path = std::env::join_paths(split_paths) .map_err(|source| anyhow::anyhow!("Can't join paths: {}", source))?; let new_path = new_path .to_str() .ok_or_else(|| anyhow::anyhow!("Can't read PATH"))?; Ok(self.set_env_var("PATH", new_path)) } fn set_env_var(&self, name: &str, value: &str) -> String { format!(r#"$env:{name} = "{value}""#) } fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result { let version_file_exists_condition = if config.resolve_engines() { "(Test-Path .nvmrc) -Or (Test-Path .node-version) -Or (Test-Path package.json)" } else { "(Test-Path .nvmrc) -Or (Test-Path .node-version)" }; let autoload_hook = match config.version_file_strategy() { VersionFileStrategy::Local => formatdoc!( r" If ({version_file_exists_condition}) {{ & fnm use --silent-if-unchanged }} ", version_file_exists_condition = version_file_exists_condition, ), VersionFileStrategy::Recursive => String::from(r"fnm use --silent-if-unchanged"), }; Ok(formatdoc!( r" function global:Set-FnmOnLoad {{ {autoload_hook} }} function global:Set-LocationWithFnm {{ param($path); if ($path -eq $null) {{Set-Location}} else {{Set-Location $path}}; Set-FnmOnLoad }} Set-Alias -Scope global cd_with_fnm Set-LocationWithFnm Set-Alias -Option AllScope -Scope global cd Set-LocationWithFnm ", autoload_hook = autoload_hook )) } fn to_clap_shell(&self) -> clap_complete::Shell { clap_complete::Shell::PowerShell } } ================================================ FILE: src/shell/shell.rs ================================================ use std::fmt::{Debug, Display}; use std::path::Path; use clap::ValueEnum; pub trait Shell: Debug { fn path(&self, path: &Path) -> anyhow::Result; fn set_env_var(&self, name: &str, value: &str) -> String; fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result; fn rehash(&self) -> Option<&'static str> { None } fn to_clap_shell(&self) -> clap_complete::Shell; } #[derive(Debug, Clone, ValueEnum)] pub enum Shells { Bash, Zsh, Fish, #[clap(name = "powershell", alias = "power-shell")] PowerShell, #[cfg(windows)] Cmd, } impl Display for Shells { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Shells::Bash => f.write_str("bash"), Shells::Zsh => f.write_str("zsh"), Shells::Fish => f.write_str("fish"), Shells::PowerShell => f.write_str("powershell"), #[cfg(windows)] Shells::Cmd => f.write_str("cmd"), } } } impl From for Box { fn from(shell: Shells) -> Box { match shell { Shells::Zsh => Box::from(super::zsh::Zsh), Shells::Bash => Box::from(super::bash::Bash), Shells::Fish => Box::from(super::fish::Fish), Shells::PowerShell => Box::from(super::powershell::PowerShell), #[cfg(windows)] Shells::Cmd => Box::from(super::windows_cmd::WindowsCmd), } } } impl From> for clap_complete::Shell { fn from(shell: Box) -> Self { shell.to_clap_shell() } } ================================================ FILE: src/shell/windows_cmd/cd.cmd ================================================ @echo off cd /d %* if "%FNM_VERSION_FILE_STRATEGY%" == "recursive" ( fnm use --silent-if-unchanged ) else ( if exist .nvmrc ( fnm use --silent-if-unchanged ) else ( if exist .node-version ( fnm use --silent-if-unchanged ) ) ) @echo on ================================================ FILE: src/shell/windows_cmd/mod.rs ================================================ use super::shell::Shell; use std::path::Path; #[derive(Debug)] pub struct WindowsCmd; impl Shell for WindowsCmd { fn to_clap_shell(&self) -> clap_complete::Shell { // TODO: move to Option panic!("Shell completion is not supported for Windows Command Prompt. Maybe try using PowerShell for a better experience?"); } fn path(&self, path: &Path) -> anyhow::Result { let current_path = std::env::var_os("path").ok_or_else(|| anyhow::anyhow!("Can't read PATH env var"))?; let mut split_paths: Vec<_> = std::env::split_paths(¤t_path).collect(); split_paths.insert(0, path.to_path_buf()); let new_path = std::env::join_paths(split_paths) .map_err(|err| anyhow::anyhow!("Can't join paths: {}", err))?; let new_path = new_path .to_str() .ok_or_else(|| anyhow::anyhow!("Can't convert path to string"))?; Ok(format!("SET PATH={new_path}")) } fn set_env_var(&self, name: &str, value: &str) -> String { format!("SET {name}={value}") } fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result { let path = config.base_dir_with_default().join("cd.cmd"); create_cd_file_at(&path).map_err(|source| { anyhow::anyhow!( "Can't create cd.cmd file for use-on-cd at {}: {}", path.display(), source ) })?; let path = path .to_str() .ok_or_else(|| anyhow::anyhow!("Can't read path to cd.cmd"))?; Ok(format!("doskey cd=\"{path}\" $*",)) } } fn create_cd_file_at(path: &std::path::Path) -> std::io::Result<()> { use std::io::Write; let cmd_contents = include_bytes!("./cd.cmd"); let mut file = std::fs::File::create(path)?; file.write_all(cmd_contents)?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn use_on_cd_quotes_macro_path() { let base_dir = std::env::temp_dir().join("fnm cmd test with spaces"); std::fs::create_dir_all(&base_dir).unwrap(); let config = crate::config::FnmConfig::default().with_base_dir(Some(base_dir.clone())); let output = WindowsCmd.use_on_cd(&config).unwrap(); assert!(output.starts_with("doskey cd=\"")); assert!(output.ends_with("\" $*")); assert!(output.contains("with spaces")); assert!(output.contains("cd.cmd")); std::fs::remove_file(base_dir.join("cd.cmd")).unwrap(); std::fs::remove_dir_all(base_dir).unwrap(); } } ================================================ FILE: src/shell/windows_compat.rs ================================================ /// On Bash for Windows, we need to convert the path from a Windows-style /// path to a Unix-style path. This is because Bash for Windows doesn't /// understand Windows-style paths. We use `cygpath` to do this conversion. /// If `cygpath` fails, we assume we're not on Bash for Windows and just /// return the original path. pub fn maybe_fix_windows_path(path: &str) -> Option { if !cfg!(windows) { return None; } let output = std::process::Command::new("cygpath") .arg(path) .output() .ok()?; if output.status.success() { let output = String::from_utf8(output.stdout).ok()?; Some(output.trim().to_string()) } else { None } } ================================================ FILE: src/shell/zsh.rs ================================================ use crate::version_file_strategy::VersionFileStrategy; use super::shell::Shell; use indoc::formatdoc; use std::path::Path; #[derive(Debug)] pub struct Zsh; impl Shell for Zsh { fn to_clap_shell(&self) -> clap_complete::Shell { clap_complete::Shell::Zsh } fn path(&self, path: &Path) -> anyhow::Result { let path = path .to_str() .ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))?; let path = super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); Ok(format!("export PATH={path:?}:$PATH")) } fn set_env_var(&self, name: &str, value: &str) -> String { format!("export {name}={value:?}") } fn rehash(&self) -> Option<&'static str> { Some("rehash") } fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result { let version_file_exists_condition = if config.resolve_engines() { "-f .node-version || -f .nvmrc || -f package.json" } else { "-f .node-version || -f .nvmrc" }; let autoload_hook = match config.version_file_strategy() { VersionFileStrategy::Local => formatdoc!( r" if [[ {version_file_exists_condition} ]]; then fnm use --silent-if-unchanged fi ", version_file_exists_condition = version_file_exists_condition, ), VersionFileStrategy::Recursive => String::from(r"fnm use --silent-if-unchanged"), }; Ok(formatdoc!( r" autoload -U add-zsh-hook _fnm_autoload_hook () {{ {autoload_hook} }} add-zsh-hook -D chpwd _fnm_autoload_hook add-zsh-hook chpwd _fnm_autoload_hook ", autoload_hook = autoload_hook )) } } #[cfg(test)] mod tests { use super::*; #[test] fn use_on_cd_removes_existing_hook_before_adding() { let output = Zsh.use_on_cd(&crate::config::FnmConfig::default()).unwrap(); assert!(output.contains("add-zsh-hook -D chpwd _fnm_autoload_hook")); } } ================================================ FILE: src/system_info.rs ================================================ #[cfg(target_os = "macos")] pub fn platform_name() -> &'static str { "darwin" } #[cfg(target_os = "linux")] pub fn platform_name() -> &'static str { "linux" } #[cfg(all( target_pointer_width = "32", any(target_arch = "arm", target_arch = "aarch64") ))] pub fn platform_arch() -> &'static str { "armv7l" } #[cfg(all( target_pointer_width = "32", not(any(target_arch = "arm", target_arch = "aarch64")) ))] pub fn platform_arch() -> &'static str { "x86" } #[cfg(all( target_pointer_width = "64", any(target_arch = "arm", target_arch = "aarch64") ))] pub fn platform_arch() -> &'static str { "arm64" } #[cfg(all( target_pointer_width = "64", not(any(target_arch = "arm", target_arch = "aarch64")) ))] pub fn platform_arch() -> &'static str { "x64" } ================================================ FILE: src/system_version.rs ================================================ use std::path::PathBuf; pub fn path() -> PathBuf { let path_as_string = if cfg!(windows) { "Z:/_fnm_/Nothing/Should/Be/Here/installation" } else { "/dev/null/installation" }; PathBuf::from(path_as_string) } pub fn display_name() -> &'static str { "system" } ================================================ FILE: src/user_version.rs ================================================ use crate::version::Version; use std::str::FromStr; #[derive(Clone, Debug)] pub enum UserVersion { OnlyMajor(u64), MajorMinor(u64, u64), SemverRange(node_semver::Range), Full(Version), } impl UserVersion { pub fn to_version<'a, T>( &self, available_versions: T, config: &crate::config::FnmConfig, ) -> Option<&'a Version> where T: IntoIterator, { available_versions .into_iter() .filter(|x| self.matches(x, config)) .max() } pub fn alias_name(&self) -> Option { match self { Self::Full(version) => version.alias_name(), _ => None, } } pub fn matches(&self, version: &Version, config: &crate::config::FnmConfig) -> bool { match (self, version) { (Self::Full(a), b) if a == b => true, (Self::Full(user_version), maybe_alias) => { match (user_version.alias_name(), maybe_alias.find_aliases(config)) { (None, _) | (_, Err(_)) => false, (Some(user_alias), Ok(aliases)) => { aliases.iter().any(|alias| alias.name() == user_alias) } } } (Self::SemverRange(range), Version::Semver(semver)) => semver.satisfies(range), (_, Version::Bypassed | Version::Lts(_) | Version::Alias(_) | Version::Latest) => false, (Self::OnlyMajor(major), Version::Semver(other)) => *major == other.major, (Self::MajorMinor(major, minor), Version::Semver(other)) => { *major == other.major && *minor == other.minor } } } /// The inferred alias for the user version, if it exists. pub fn inferred_alias(&self) -> Option { match self { UserVersion::Full(Version::Latest) => Some(Version::Latest), UserVersion::Full(Version::Lts(lts_type)) => Some(Version::Lts(lts_type.clone())), _ => None, } } } fn next_of<'a, T: FromStr, It: Iterator>(i: &mut It) -> Option { let x = i.next()?; T::from_str(x).ok() } impl std::fmt::Display for UserVersion { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Full(x) => x.fmt(f), Self::SemverRange(x) => x.fmt(f), Self::OnlyMajor(major) => write!(f, "v{major}.x.x"), Self::MajorMinor(major, minor) => write!(f, "v{major}.{minor}.x"), } } } fn skip_first_v(str: &str) -> &str { str.strip_prefix('v').unwrap_or(str) } impl FromStr for UserVersion { type Err = node_semver::SemverError; fn from_str(s: &str) -> Result { match Version::parse(s) { Ok(v) => Ok(Self::Full(v)), Err(e) => { let mut parts = skip_first_v(s.trim()).split('.'); match (next_of::(&mut parts), next_of::(&mut parts)) { (Some(major), None) => Ok(Self::OnlyMajor(major)), (Some(major), Some(minor)) => Ok(Self::MajorMinor(major, minor)), _ => Err(e), } } } } } #[cfg(test)] impl PartialEq for UserVersion { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::OnlyMajor(a), Self::OnlyMajor(b)) if a == b => true, (Self::MajorMinor(a1, a2), Self::MajorMinor(b1, b2)) if (a1, a2) == (b1, b2) => true, (Self::Full(v1), Self::Full(v2)) if v1 == v2 => true, (_, _) => false, } } } #[cfg(test)] mod tests { use crate::config::FnmConfig; use super::*; #[test] fn test_parsing_only_major() { let version = UserVersion::from_str("10").ok(); assert_eq!(version, Some(UserVersion::OnlyMajor(10))); } #[test] fn test_parsing_major_minor() { let version = UserVersion::from_str("10.20").ok(); assert_eq!(version, Some(UserVersion::MajorMinor(10, 20))); } #[test] fn test_parsing_only_major_with_v() { let version = UserVersion::from_str("v10").ok(); assert_eq!(version, Some(UserVersion::OnlyMajor(10))); } #[test] fn test_major_to_version() { let expected = Version::parse("6.1.0").unwrap(); let versions = vec![ Version::parse("6.0.0").unwrap(), Version::parse("6.0.1").unwrap(), expected.clone(), Version::parse("7.0.1").unwrap(), ]; let result = UserVersion::OnlyMajor(6).to_version(&versions, &FnmConfig::default()); assert_eq!(result, Some(&expected)); } #[test] fn test_major_minor_to_version() { let expected = Version::parse("6.0.1").unwrap(); let versions = vec![ Version::parse("6.0.0").unwrap(), Version::parse("6.1.0").unwrap(), expected.clone(), Version::parse("7.0.1").unwrap(), ]; let result = UserVersion::MajorMinor(6, 0).to_version(&versions, &FnmConfig::default()); assert_eq!(result, Some(&expected)); } #[test] fn test_semver_to_version() { let expected = Version::parse("6.0.0").unwrap(); let versions = vec![ expected.clone(), Version::parse("6.1.0").unwrap(), Version::parse("6.0.1").unwrap(), Version::parse("7.0.1").unwrap(), ]; let result = UserVersion::Full(expected.clone()).to_version(&versions, &FnmConfig::default()); assert_eq!(result, Some(&expected)); } } ================================================ FILE: src/user_version_reader.rs ================================================ use crate::config::FnmConfig; use crate::user_version::UserVersion; use crate::version_files::{get_user_version_for_directory, get_user_version_for_file}; use std::path::PathBuf; use std::str::FromStr; #[derive(Debug, Clone)] pub enum UserVersionReader { Direct(UserVersion), Path(PathBuf), } impl UserVersionReader { pub fn into_user_version(self, config: &FnmConfig) -> Option { match self { Self::Direct(uv) => Some(uv), Self::Path(pathbuf) if pathbuf.is_file() => get_user_version_for_file(pathbuf, config), Self::Path(pathbuf) => get_user_version_for_directory(pathbuf, config), } } } impl FromStr for UserVersionReader { type Err = node_semver::SemverError; fn from_str(s: &str) -> Result { let pathbuf = PathBuf::from_str(s); let user_version = UserVersion::from_str(s); match (user_version, pathbuf) { (_, Ok(pathbuf)) if pathbuf.exists() => Ok(Self::Path(pathbuf)), (Ok(user_version), _) => Ok(Self::Direct(user_version)), (Err(user_version_err), _) => Err(user_version_err), } } } #[cfg(test)] mod tests { use super::*; use crate::version::Version; use pretty_assertions::assert_eq; use std::io::Write; use tempfile::{NamedTempFile, TempDir}; #[test] fn test_file_pathbuf_to_version() { let mut file = NamedTempFile::new().unwrap(); file.write_all(b"14").unwrap(); let pathbuf = file.path().to_path_buf(); let user_version = UserVersionReader::Path(pathbuf).into_user_version(&FnmConfig::default()); assert_eq!(user_version, Some(UserVersion::OnlyMajor(14))); } #[test] fn test_directory_pathbuf_to_version() { let directory = TempDir::new().unwrap(); let node_version_path = directory.path().join(".node-version"); std::fs::write(node_version_path, "14").unwrap(); let pathbuf = directory.path().to_path_buf(); let user_version = UserVersionReader::Path(pathbuf).into_user_version(&FnmConfig::default()); assert_eq!(user_version, Some(UserVersion::OnlyMajor(14))); } #[test] fn test_direct_to_version() { let user_version = UserVersionReader::Direct(UserVersion::OnlyMajor(14)) .into_user_version(&FnmConfig::default()); assert_eq!(user_version, Some(UserVersion::OnlyMajor(14))); } #[test] fn test_from_str_directory() { let directory = TempDir::new().unwrap(); let node_version_path = directory.path().join(".node-version"); std::fs::write(node_version_path, "14").unwrap(); let pathbuf = directory.path().to_path_buf(); let user_version = UserVersionReader::from_str(pathbuf.to_str().unwrap()); assert!(matches!(user_version, Ok(UserVersionReader::Path(_)))); } #[test] fn test_from_str_file() { let mut file = NamedTempFile::new().unwrap(); write!(file, "14").unwrap(); let pathbuf = file.path().to_path_buf(); let user_version = UserVersionReader::from_str(pathbuf.to_str().unwrap()); assert!(matches!(user_version, Ok(UserVersionReader::Path(_)))); } #[test] fn test_non_existing_path() { let user_version = UserVersionReader::from_str("/tmp/some_random_text_that_probably_does_not_exist"); assert!(matches!( user_version, Ok(UserVersionReader::Direct(UserVersion::Full( Version::Alias(_) ))) )); } #[test] fn test_a_version_number() { let user_version = UserVersionReader::from_str("12.0"); assert!(matches!( user_version, Ok(UserVersionReader::Direct(UserVersion::MajorMinor(12, 0))) )); } } ================================================ FILE: src/version.rs ================================================ use crate::alias; use crate::config; use crate::lts::LtsType; use crate::system_version; use std::str::FromStr; #[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)] pub enum Version { Semver(node_semver::Version), Lts(LtsType), Alias(String), Latest, Bypassed, } fn first_letter_is_number(s: &str) -> bool { s.chars().next().is_some_and(|x| x.is_ascii_digit()) } impl Version { pub fn parse>(version_str: S) -> Result { let lowercased = version_str.as_ref().to_lowercase(); if lowercased == system_version::display_name() { Ok(Self::Bypassed) } else if lowercased.starts_with("lts-") || lowercased.starts_with("lts/") { let lts_type = LtsType::from(&lowercased[4..]); Ok(Self::Lts(lts_type)) } else if first_letter_is_number(lowercased.trim_start_matches('v')) { let version_plain = lowercased.trim_start_matches('v'); let sver = node_semver::Version::parse(version_plain)?; Ok(Self::Semver(sver)) } else { Ok(Self::Alias(lowercased)) } } pub fn alias_name(&self) -> Option { match self { l @ (Self::Lts(_) | Self::Alias(_)) => Some(l.v_str()), _ => None, } } pub fn find_aliases( &self, config: &config::FnmConfig, ) -> std::io::Result> { let aliases = alias::list_aliases(config)? .drain(..) .filter(|alias| alias.s_ver() == self.v_str()) .collect(); Ok(aliases) } pub fn v_str(&self) -> String { format!("{self}") } pub fn installation_path(&self, config: &config::FnmConfig) -> std::path::PathBuf { match self { Self::Bypassed => system_version::path(), v @ (Self::Lts(_) | Self::Alias(_) | Self::Latest) => { config.aliases_dir().join(v.alias_name().unwrap()) } v @ Self::Semver(_) => config .installations_dir() .join(v.v_str()) .join("installation"), } } pub fn root_path(&self, config: &config::FnmConfig) -> Option { let path = self.installation_path(config); let mut canon_path = path.canonicalize().ok()?; canon_path.pop(); Some(canon_path) } } // TODO: add a trait called BinPath that &Path and PathBuf implements // which adds the `.bin_path()` which works both on windows and unix :) impl<'de> serde::Deserialize<'de> for Version { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { let version_str = String::deserialize(deserializer)?; Version::parse(version_str).map_err(serde::de::Error::custom) } } impl std::fmt::Display for Version { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Bypassed => write!(f, "{}", system_version::display_name()), Self::Lts(lts) => write!(f, "lts-{lts}"), Self::Semver(semver) => write!(f, "v{semver}"), Self::Alias(alias) => write!(f, "{alias}"), Self::Latest => write!(f, "latest"), } } } impl FromStr for Version { type Err = node_semver::SemverError; fn from_str(s: &str) -> Result { Self::parse(s) } } impl PartialEq for Version { fn eq(&self, other: &node_semver::Version) -> bool { match self { Self::Bypassed | Self::Lts(_) | Self::Alias(_) | Self::Latest => false, Self::Semver(v) => v == other, } } } ================================================ FILE: src/version_file_strategy.rs ================================================ use clap::ValueEnum; use std::fmt::Display; #[derive(Debug, Clone, Copy, Default, ValueEnum)] pub enum VersionFileStrategy { /// Use the local version of Node defined within the current directory #[default] Local, /// Use the version of Node defined within the current directory and all parent directories Recursive, } impl VersionFileStrategy { pub fn as_str(self) -> &'static str { match self { VersionFileStrategy::Local => "local", VersionFileStrategy::Recursive => "recursive", } } } impl Display for VersionFileStrategy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } ================================================ FILE: src/version_files.rs ================================================ use crate::config::FnmConfig; use crate::default_version; use crate::package_json::PackageJson; use crate::user_version::UserVersion; use crate::version_file_strategy::VersionFileStrategy; use encoding_rs_io::DecodeReaderBytes; use log::info; use std::io::Read; use std::path::Path; use std::str::FromStr; const PATH_PARTS: [&str; 3] = [".nvmrc", ".node-version", "package.json"]; pub fn get_user_version_for_directory( path: impl AsRef, config: &FnmConfig, ) -> Option { match config.version_file_strategy() { VersionFileStrategy::Local => get_user_version_for_single_directory(path, config), VersionFileStrategy::Recursive => get_user_version_for_directory_recursive(path, config) .or_else(|| { info!("Did not find anything recursively. Falling back to default alias."); default_version::find_default_version(config).map(UserVersion::Full) }), } } fn get_user_version_for_directory_recursive( path: impl AsRef, config: &FnmConfig, ) -> Option { let mut current_path = Some(path.as_ref()); while let Some(child_path) = current_path { if let Some(version) = get_user_version_for_single_directory(child_path, config) { return Some(version); } current_path = child_path.parent(); } None } fn get_user_version_for_single_directory( path: impl AsRef, config: &FnmConfig, ) -> Option { let path = path.as_ref(); for path_part in &PATH_PARTS { let new_path = path.join(path_part); info!( "Looking for version file in {}. exists? {}", new_path.display(), new_path.exists() ); if let Some(version) = get_user_version_for_file(&new_path, config) { return Some(version); } } None } pub fn get_user_version_for_file( path: impl AsRef, config: &FnmConfig, ) -> Option { let is_pkg_json = match path.as_ref().file_name() { Some(name) => name == "package.json", None => false, }; let file = std::fs::File::open(path).ok()?; let file = { let mut reader = DecodeReaderBytes::new(file); let mut version = String::new(); reader.read_to_string(&mut version).map(|_| version) }; match (file, is_pkg_json, config.resolve_engines()) { (_, true, false) => None, (Err(err), _, _) => { info!("Can't read file: {}", err); None } (Ok(version), false, _) => { info!("Found string {:?} in version file", version); UserVersion::from_str(version.trim()).ok() } (Ok(pkg_json), true, true) => { let pkg_json = serde_json::from_str::(&pkg_json).ok(); let range: Option = pkg_json.as_ref().and_then(PackageJson::node_range).cloned(); if let Some(range) = range { info!("Found package.json with {:?} in engines.node field", range); Some(UserVersion::SemverRange(range)) } else { info!("No engines.node range found in package.json"); None } } } } ================================================ FILE: tests/proxy-server/index.mjs ================================================ // @ts-check import { createServer } from "node:http" import path from "node:path" import fs from "node:fs" import crypto from "node:crypto" import fetch from "node-fetch" import chalk from "chalk" import pRetry from "p-retry" const baseDir = path.join(process.cwd(), ".proxy") try { fs.mkdirSync(baseDir, { recursive: true }) } catch (e) {} /** @type {Map, body: ArrayBuffer }>>} */ const cache = new Map() /** * @param {object} opts * @param {string} opts.pathname * @param {string} opts.headersFilename * @param {string} opts.filename */ const download = async ({ pathname, filename, headersFilename }) => { const response = await fetch( "https://nodejs.org/dist/" + pathname.replace(/^\/+/, ""), { compress: false, }, ) const headers = Object.fromEntries(response.headers.entries()) headers.__status__ = String(response.status) const body = await response.arrayBuffer() fs.writeFileSync(headersFilename, JSON.stringify(headers)) fs.writeFileSync(filename, Buffer.from(body)) return { headers, body } } export const server = createServer((req, res) => { const pathname = req.url ?? "/" const hash = crypto .createHash("sha1") .update(pathname ?? "/") .digest("hex") const extension = path.extname(pathname) const filename = path.join(baseDir, hash) + extension const headersFilename = path.join(baseDir, hash) + ".headers.json" try { const { __status__ = "200", ...headers } = JSON.parse( fs.readFileSync(headersFilename, "utf-8"), ) const status = parseInt(__status__, 10) const body = fs.createReadStream(filename) console.log(chalk.green.dim(`[proxy] hit: ${pathname} -> ${filename}`)) res.writeHead(status, headers) body.pipe(res) } catch { let promise = cache.get(filename) if (!promise) { console.log(chalk.red.dim(`[proxy] miss: ${pathname} -> ${filename}`)) promise = pRetry( () => download({ pathname, headersFilename, filename }), { retries: 5, maxTimeout: 5000, onFailedAttempt: (error) => { console.error( chalk.red( `[proxy] ${chalk.bold("error")}: ${error.message}, retries left: ${error.retriesLeft}`, ), ) }, }, ) cache.set(filename, promise) promise.finally(() => cache.delete(filename)) } promise.then( ({ headers: { __status__ = "200", ...headers }, body }) => { res.writeHead(parseInt(__status__, 10), headers) res.end(Buffer.from(body)) }, (err) => { console.error(err) res.writeHead(500) res.end() }, ) } }) ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "target": "esnext", "moduleResolution": "NodeNext", "moduleDetection": "force", "module": "esnext", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true } }