[
  {
    "path": ".changeset/README.md",
    "content": "# Changesets\n\nHello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works\nwith multi-package repos, or single-package repos to help you version and publish your code. You can\nfind the full documentation for it [in our repository](https://github.com/changesets/changesets)\n\nWe have a quick list of common questions to get you started engaging with this project in\n[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)\n"
  },
  {
    "path": ".changeset/brave-timers-move.md",
    "content": "---\n\"fnm\": patch\n---\n\nsupport `x64-glibc-217` arch by adding a `--arch x64-glibc-217` to fnm env\n"
  },
  {
    "path": ".changeset/config.json",
    "content": "{\n  \"$schema\": \"https://unpkg.com/@changesets/config@2.0.0/schema.json\",\n  \"changelog\": [\"@changesets/changelog-github\", { \"repo\": \"Schniz/fnm\" }],\n  \"commit\": false,\n  \"fixed\": [],\n  \"linked\": [],\n  \"access\": \"restricted\",\n  \"baseBranch\": \"master\",\n  \"updateInternalDependencies\": \"patch\",\n  \"ignore\": []\n}\n"
  },
  {
    "path": ".changeset/cuddly-cars-ring.md",
    "content": "---\n\"fnm\": patch\n---\n\nprefer explicit shell flags in installer-generated shell setup and fix ARM installer CI platform selection\n"
  },
  {
    "path": ".changeset/fair-carrots-greet.md",
    "content": "---\n\"fnm\": patch\n---\n\nClarify the interactive `fnm use` missing-version prompt by prefixing the message with `fnm` so it is obvious which tool is asking to install Node.\n"
  },
  {
    "path": ".ci/get_shell_profile.sh",
    "content": "#!/bin/bash\n\ncase $1 in\n  \"fish\")\n    echo \"$HOME/.config/fish/conf.d/fnm.fish\"\n    ;;\n  \"zsh\")\n    echo \"$HOME/.zshrc\"\n    ;;\n  \"bash\")\n    OS=\"$(uname -s)\"\n    if [ \"$OS\" = \"Darwin\" ]; then\n      echo \"$HOME/.profile\"\n    else\n      echo \"$HOME/.bashrc\"\n    fi\n    ;;\n  *)\n    exit 1\n    ;;\nesac\n"
  },
  {
    "path": ".ci/install.sh",
    "content": "#!/bin/bash\n\nset -e\n\nRELEASE=\"latest\"\nOS=\"$(uname -s)\"\n\ncase \"${OS}\" in\n   MINGW* | Win*) OS=\"Windows\" ;;\nesac\n\nif [ -d \"$HOME/.fnm\" ]; then\n  INSTALL_DIR=\"$HOME/.fnm\"\nelif [ -n \"$XDG_DATA_HOME\" ]; then\n  INSTALL_DIR=\"$XDG_DATA_HOME/fnm\"\nelif [ \"$OS\" = \"Darwin\" ]; then\n  INSTALL_DIR=\"$HOME/Library/Application Support/fnm\"\nelse\n  INSTALL_DIR=\"$HOME/.local/share/fnm\"\nfi\n\n# Parse Flags\nparse_args() {\n  while [[ $# -gt 0 ]]; do\n    key=\"$1\"\n\n    case $key in\n    -d | --install-dir)\n      INSTALL_DIR=\"$2\"\n      shift # past argument\n      shift # past value\n      ;;\n    -s | --skip-shell)\n      SKIP_SHELL=\"true\"\n      shift # past argument\n      ;;\n    --force-install | --force-no-brew)\n      echo \"\\`--force-install\\`: I hope you know what you're doing.\" >&2\n      FORCE_INSTALL=\"true\"\n      shift\n      ;;\n    -r | --release)\n      RELEASE=\"$2\"\n      shift # past release argument\n      shift # past release value\n      ;;\n    *)\n      echo \"Unrecognized argument $key\"\n      exit 1\n      ;;\n    esac\n  done\n}\n\nset_filename() {\n  if [ \"$OS\" = \"Linux\" ]; then\n    # Based on https://stackoverflow.com/a/45125525\n    case \"$(uname -m)\" in\n      arm | armv7*)\n        FILENAME=\"fnm-arm32\"\n        ;;\n      aarch* | armv8*)\n        FILENAME=\"fnm-arm64\"\n        ;;\n      *)\n        FILENAME=\"fnm-linux\"\n    esac\n  elif [ \"$OS\" = \"Darwin\" ] && [ \"$FORCE_INSTALL\" = \"true\" ]; then\n    FILENAME=\"fnm-macos\"\n    USE_HOMEBREW=\"false\"\n    echo \"Downloading the latest fnm binary from GitHub...\"\n    echo \"  Pro tip: it's easier to use Homebrew for managing fnm in macOS.\"\n    echo \"           Remove the \\`--force-no-brew\\` so it will be easy to upgrade.\"\n  elif [ \"$OS\" = \"Darwin\" ]; then\n    USE_HOMEBREW=\"true\"\n    echo \"Downloading fnm using Homebrew...\"\n  elif [ \"$OS\" = \"Windows\" ] ; then\n    FILENAME=\"fnm-windows\"\n    echo \"Downloading the latest fnm binary from GitHub...\"\n  else\n    echo \"OS $OS is not supported.\"\n    echo \"If you think that's a bug - please file an issue to https://github.com/Schniz/fnm/issues\"\n    exit 1\n  fi\n}\n\ndownload_fnm() {\n  if [ \"$USE_HOMEBREW\" = \"true\" ]; then\n    brew install fnm\n    INSTALL_DIR=\"$(brew --prefix fnm)/bin\"\n  else\n    if [ \"$RELEASE\" = \"latest\" ]; then\n      URL=\"https://github.com/Schniz/fnm/releases/latest/download/$FILENAME.zip\"\n    else\n      URL=\"https://github.com/Schniz/fnm/releases/download/$RELEASE/$FILENAME.zip\"\n    fi\n\n    DOWNLOAD_DIR=$(mktemp -d)\n\n    echo \"Downloading $URL...\"\n\n    mkdir -p \"$INSTALL_DIR\" &>/dev/null\n\n    if ! curl --progress-bar --fail -L \"$URL\" -o \"$DOWNLOAD_DIR/$FILENAME.zip\"; then\n      echo \"Download failed.  Check that the release/filename are correct.\"\n      exit 1\n    fi\n\n    unzip -q \"$DOWNLOAD_DIR/$FILENAME.zip\" -d \"$DOWNLOAD_DIR\"\n\n    if [ -f \"$DOWNLOAD_DIR/fnm\" ]; then\n      mv \"$DOWNLOAD_DIR/fnm\" \"$INSTALL_DIR/fnm\"\n    else\n      mv \"$DOWNLOAD_DIR/$FILENAME/fnm\" \"$INSTALL_DIR/fnm\"\n    fi\n\n    chmod u+x \"$INSTALL_DIR/fnm\"\n  fi\n}\n\ncheck_dependencies() {\n  echo \"Checking dependencies for the installation script...\"\n\n  echo -n \"Checking availability of curl... \"\n  if hash curl 2>/dev/null; then\n    echo \"OK!\"\n  else\n    echo \"Missing!\"\n    SHOULD_EXIT=\"true\"\n  fi\n\n  echo -n \"Checking availability of unzip... \"\n  if hash unzip 2>/dev/null; then\n    echo \"OK!\"\n  else\n    echo \"Missing!\"\n    SHOULD_EXIT=\"true\"\n  fi\n\n  if [ \"$USE_HOMEBREW\" = \"true\" ]; then\n    echo -n \"Checking availability of Homebrew (brew)... \"\n    if hash brew 2>/dev/null; then\n      echo \"OK!\"\n    else\n      echo \"Missing!\"\n      SHOULD_EXIT=\"true\"\n    fi\n  fi\n\n  if [ \"$SHOULD_EXIT\" = \"true\" ]; then\n    echo \"Not installing fnm due to missing dependencies.\"\n    exit 1\n  fi\n}\n\nensure_containing_dir_exists() {\n  local CONTAINING_DIR\n  CONTAINING_DIR=\"$(dirname \"$1\")\"\n  if [ ! -d \"$CONTAINING_DIR\" ]; then\n    echo \" >> Creating directory $CONTAINING_DIR\"\n    mkdir -p \"$CONTAINING_DIR\"\n  fi\n}\n\nsetup_shell() {\n  CURRENT_SHELL=\"$(basename \"$SHELL\")\"\n\n  if [ \"$CURRENT_SHELL\" = \"zsh\" ]; then\n    CONF_FILE=${ZDOTDIR:-$HOME}/.zshrc\n    ensure_containing_dir_exists \"$CONF_FILE\"\n    echo \"Installing for Zsh. Appending the following to $CONF_FILE:\"\n    {\n      echo ''\n      echo '# fnm'\n      echo 'FNM_PATH=\"'\"$INSTALL_DIR\"'\"'\n      echo 'if [ -d \"$FNM_PATH\" ]; then'\n      if [ \"$USE_HOMEBREW\" != \"true\" ]; then\n        echo '  export PATH=\"$FNM_PATH:$PATH\"'\n      fi\n      echo '  eval \"$(fnm env --shell zsh)\"'\n      echo 'fi'\n    } | tee -a \"$CONF_FILE\"\n\n  elif [ \"$CURRENT_SHELL\" = \"fish\" ]; then\n    CONF_FILE=$HOME/.config/fish/conf.d/fnm.fish\n    ensure_containing_dir_exists \"$CONF_FILE\"\n    echo \"Installing for Fish. Appending the following to $CONF_FILE:\"\n    {\n      echo ''\n      echo '# fnm'\n      echo 'set FNM_PATH \"'\"$INSTALL_DIR\"'\"'\n      echo 'if [ -d \"$FNM_PATH\" ]'\n      if [ \"$USE_HOMEBREW\" != \"true\" ]; then\n        echo '  set PATH \"$FNM_PATH\" $PATH'\n      fi\n      echo '  fnm env --shell fish | source'\n      echo 'end'\n    } | tee -a \"$CONF_FILE\"\n\n  elif [ \"$CURRENT_SHELL\" = \"bash\" ]; then\n    if [ \"$OS\" = \"Darwin\" ]; then\n      CONF_FILE=$HOME/.profile\n    else\n      CONF_FILE=$HOME/.bashrc\n    fi\n    ensure_containing_dir_exists \"$CONF_FILE\"\n    echo \"Installing for Bash. Appending the following to $CONF_FILE:\"\n    {\n      echo ''\n      echo '# fnm'\n      echo 'FNM_PATH=\"'\"$INSTALL_DIR\"'\"'\n      echo 'if [ -d \"$FNM_PATH\" ]; then'\n      if [ \"$USE_HOMEBREW\" != \"true\" ]; then\n        echo '  export PATH=\"$FNM_PATH:$PATH\"'\n      fi\n      echo '  eval \"$(fnm env --shell bash)\"'\n      echo 'fi'\n    } | tee -a \"$CONF_FILE\"\n\n  else\n    echo \"Could not infer shell type. Please set up manually.\"\n    exit 1\n  fi\n\n  echo \"\"\n  echo \"In order to apply the changes, open a new terminal or run the following command:\"\n  echo \"\"\n  echo \"  source $CONF_FILE\"\n}\n\nparse_args \"$@\"\nset_filename\ncheck_dependencies\ndownload_fnm\nif [ \"$SKIP_SHELL\" != \"true\" ]; then\n  setup_shell\nfi\n"
  },
  {
    "path": ".ci/prepare-static-build.sh",
    "content": "sed -i 's@\"flags\": \\[\\]@\"flags\": [\"-ccopt\", \"-static\"]@' package.json\n"
  },
  {
    "path": ".ci/prepare-version.js",
    "content": "#!/usr/bin/env node\n\n/// @ts-check\n\nimport fs from \"fs\"\nimport cp from \"child_process\"\nimport cmd from \"cmd-ts\"\nimport toml from \"toml\"\nimport assert from \"assert\"\n\nconst CARGO_TOML_PATH = new URL(\"../Cargo.toml\", import.meta.url).pathname\n\nconst command = cmd.command({\n  name: \"prepare-version\",\n  description: \"Prepare a new fnm version\",\n  args: {},\n  async handler({}) {\n    updateCargoToml(await getPackageVersion())\n    exec(\"cargo build --release\")\n    exec(\"pnpm generate-command-docs --binary-path=./target/release/fnm\")\n    exec(\"./.ci/record_screen.sh\")\n  },\n})\n\ncmd.run(cmd.binary(command), process.argv)\n\n//////////////////////\n// Helper functions //\n//////////////////////\n\n/**\n * @returns {Promise<string>}\n */\nasync function getPackageVersion() {\n  const pkgJson = await fs.promises.readFile(\n    new URL(\"../package.json\", import.meta.url),\n    \"utf8\"\n  )\n  const version = JSON.parse(pkgJson).version\n  assert(version, \"package.json version is not set\")\n  return version\n}\n\nfunction updateCargoToml(nextVersion) {\n  const cargoToml = fs.readFileSync(CARGO_TOML_PATH, \"utf8\")\n  const cargoTomlContents = toml.parse(cargoToml)\n  const currentVersion = cargoTomlContents.package.version\n\n  const newToml = cargoToml.replace(\n    `version = \"${currentVersion}\"`,\n    `version = \"${nextVersion}\"`\n  )\n\n  if (newToml === cargoToml) {\n    console.error(\"Cargo.toml didn't change, error!\")\n    process.exitCode = 1\n    return\n  }\n\n  fs.writeFileSync(CARGO_TOML_PATH, newToml, \"utf8\")\n\n  return nextVersion\n}\n\nfunction exec(command, env) {\n  console.log(`$ ${command}`)\n  return cp.execSync(command, {\n    cwd: new URL(\"..\", import.meta.url),\n    stdio: \"inherit\",\n    env: { ...process.env, ...env },\n  })\n}\n"
  },
  {
    "path": ".ci/print-command-docs.js",
    "content": "#!/usr/bin/env node\n\n/// @ts-check\n\nimport { execa } from \"execa\"\nimport fs from \"node:fs\"\nimport cmd from \"cmd-ts\"\nimport cmdFs from \"cmd-ts/dist/cjs/batteries/fs.js\"\n\nconst FnmBinaryPath = {\n  ...cmdFs.ExistingPath,\n  defaultValue() {\n    const target = new URL(\"../target/debug/fnm\", import.meta.url)\n    if (!fs.existsSync(target)) {\n      throw new Error(\n        \"Can't find debug target, please run `cargo build` or provide a specific binary path\"\n      )\n    }\n    return target.pathname\n  },\n}\n\nconst command = cmd.command({\n  name: \"print-command-docs\",\n  description: \"prints the docs/command.md file with updated contents\",\n  args: {\n    checkForDirty: cmd.flag({\n      long: \"check\",\n      description: `Check that file was not changed`,\n    }),\n    fnmPath: cmd.option({\n      long: \"binary-path\",\n      description: \"the fnm binary path\",\n      type: FnmBinaryPath,\n    }),\n  },\n  async handler({ checkForDirty, fnmPath }) {\n    const targetFile = new URL(\"../docs/commands.md\", import.meta.url).pathname\n    await main(targetFile, fnmPath)\n    if (checkForDirty) {\n      const gitStatus = await checkGitStatus(targetFile)\n      if (gitStatus.state === \"dirty\") {\n        process.exitCode = 1\n        console.error(\n          \"The file has changed. Please re-run `pnpm generate-command-docs`.\"\n        )\n        console.error(`hint: The following diff was found:`)\n        console.error()\n        console.error(gitStatus.diff)\n      }\n    }\n  },\n})\n\ncmd.run(cmd.binary(command), process.argv).catch((err) => {\n  console.error(err)\n  process.exitCode = process.exitCode || 1\n})\n\n/**\n * @param {string} targetFile\n * @param {string} fnmPath\n * @returns {Promise<void>}\n */\nasync function main(targetFile, fnmPath) {\n  const stream = fs.createWriteStream(targetFile)\n\n  const { subcommands, text: mainText } = await getCommandHelp(fnmPath)\n\n  await write(stream, line(`fnm`, mainText))\n\n  for (const subcommand of subcommands) {\n    const { text: subcommandText } = await getCommandHelp(fnmPath, subcommand)\n    await write(stream, \"\\n\" + line(`fnm ${subcommand}`, subcommandText))\n  }\n\n  stream.close()\n\n  await execa(`pnpm`, [\"prettier\", \"--write\", targetFile])\n}\n\n/**\n * @param {import('stream').Writable} stream\n * @param {string} content\n * @returns {Promise<void>}\n */\nfunction write(stream, content) {\n  return new Promise((resolve, reject) => {\n    stream.write(content, (err) => (err ? reject(err) : resolve()))\n  })\n}\n\nfunction line(cmd, text) {\n  const cmdCode = \"`\" + cmd + \"`\"\n  const textCode = \"```\\n\" + text + \"\\n```\"\n  return `# ${cmdCode}\\n${textCode}`\n}\n\n/**\n * @param {string} fnmPath\n * @param {string} [command]\n * @returns {Promise<{ subcommands: string[], text: string }>}\n */\nasync function getCommandHelp(fnmPath, command) {\n  const cmdArg = command ? [command] : []\n  const result = await run(fnmPath, [...cmdArg, \"--help\"])\n  const text = result.stdout\n  const rows = text.split(\"\\n\")\n  const headerIndex = rows.findIndex((x) => x.includes(\"Commands:\"))\n  /** @type {string[]} */\n  const subcommands = []\n  if (!command) {\n    for (const row of rows.slice(\n      headerIndex + 1,\n      rows.indexOf(\"\", headerIndex + 1)\n    )) {\n      const [, word] = row.split(/\\s+/)\n      if (word && word[0].toLowerCase() === word[0]) {\n        subcommands.push(word)\n      }\n    }\n  }\n  return {\n    subcommands,\n    text,\n  }\n}\n\n/**\n * @param {string[]} args\n * @returns {import('execa').ExecaChildProcess<string>}\n */\nfunction run(fnmPath, args) {\n  return execa(fnmPath, args, {\n    reject: false,\n    stdout: \"pipe\",\n    stderr: \"pipe\",\n  })\n}\n\n/**\n * @param {string} targetFile\n * @returns {Promise<{ state: \"dirty\", diff: string } | { state: \"clean\" }>}\n */\nasync function checkGitStatus(targetFile) {\n  const { stdout, exitCode } = await execa(\n    `git`,\n    [\"diff\", \"--color\", \"--exit-code\", targetFile],\n    {\n      reject: false,\n    }\n  )\n  if (exitCode === 0) {\n    return { state: \"clean\" }\n  }\n  return { state: \"dirty\", diff: stdout }\n}\n"
  },
  {
    "path": ".ci/record_screen.sh",
    "content": "#!/bin/bash\n\nDIRECTORY=\"$(dirname \"$0\")\"\n\nfunction setup_binary() {\n  TEMP_DIR=\"/tmp/fnm-$(date '+%s')\"\n  mkdir \"$TEMP_DIR\"\n  cp ./target/release/fnm \"$TEMP_DIR/fnm\"\n  export PATH=$TEMP_DIR:$PATH\n  export FNM_DIR=$TEMP_DIR/.fnm\n\n  # First run of the binary might be slower due to anti-virus software\n  echo \"Using $(which fnm)\"\n  echo \"  with version $(fnm --version)\"\n}\n\nsetup_binary\n\nRECORDING_PATH=$DIRECTORY/screen_recording\n\n(rm -rf \"$RECORDING_PATH\" &> /dev/null || true)\n\nasciinema rec \\\n  --command \"$DIRECTORY/recorded_screen_script.sh\" \\\n  --cols 70 \\\n  --rows 17 \\\n  \"$RECORDING_PATH\"\nsed \"s@$TEMP_DIR@~@g\" \"$RECORDING_PATH\" | \\\n  svg-term \\\n    --window \\\n    --out \"docs/fnm.svg\" \\\n    --height=17 \\\n    --width=70\n"
  },
  {
    "path": ".ci/recorded_screen_script.sh",
    "content": "#!/bin/bash\n\nset -e\n\nexport PATH=$PATH_ADDITION:$PATH\n\nGAL_PROMPT_PREFIX=\"\\e[34m✡\\e[m  \"\n\nfunction type() {\n  printf $GAL_PROMPT_PREFIX\n  echo -n \" \"\n  echo $* | node .ci/type-letters.js\n}\n\ntype 'eval \"$(fnm env)\"'\neval \"$(fnm env)\"\n\ntype 'fnm --version'\nfnm --version\n\ntype 'cat .node-version'\ncat .node-version\n\ntype 'fnm install'\nfnm install\n\ntype 'fnm use'\nfnm use\n\ntype 'node -v'\nnode -v\n\nsleep 2\necho \"\"\n"
  },
  {
    "path": ".ci/test_installation_script.sh",
    "content": "#!/bin/bash\n\nset -e\n\nDIRECTORY=\"$(dirname \"$0\")\"\nSHELL_TO_RUN=\"$1\"\nPROFILE_FILE=\"$(\"$DIRECTORY/get_shell_profile.sh\" \"$SHELL_TO_RUN\")\"\n\nls -lah ~\necho \"---\"\necho \"Profile is $PROFILE_FILE\"\necho \"---\"\ncat \"$PROFILE_FILE\"\necho \"---\"\necho \"PATH=$PATH\"\necho \"---\"\n\n$SHELL_TO_RUN -c \"\n  . $PROFILE_FILE\n  fnm --version\n\"\n\n$SHELL_TO_RUN -c \"\n  . $PROFILE_FILE\n  fnm install 12.5.0\n  fnm ls | grep 12.5.0\n\n  echo 'fnm ls worked.'\n\"\n\n$SHELL_TO_RUN -c \"\n  . $PROFILE_FILE\n  fnm use 12.5.0\n  node --version | grep 12.5.0\n\n  echo 'node --version worked.'\n\"\n"
  },
  {
    "path": ".ci/type-letters.js",
    "content": "(async () => {\n  for await (const chunk of process.stdin) {\n    const letters = chunk.toString(\"utf8\").split(\"\");\n    for (const letter of letters) {\n      process.stdout.write(letter);\n      await sleep(Math.random() * 100 + 20);\n    }\n  }\n})();\n\nfunction sleep(ms) {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "*__Fish.snap linguist-language=fish\n*__Zsh.snap linguist-language=Shell\n*__Bash.snap linguist-language=Shell\n*__PowerShell.snap linguist-language=PowerShell\n*__WinCmd.snap linguist-language=Batchfile\n"
  },
  {
    "path": ".github/workflows/debug.yml",
    "content": "name: \"debug\"\n\non:\n  workflow_dispatch:\n\nconcurrency:\n  group: debug\n  cancel-in-progress: true\n\njobs:\n  e2e_windows_debug:\n    runs-on: windows-latest\n    name: \"e2e/windows/debug\"\n    steps:\n    - uses: actions/checkout@v4\n      with:\n        ref: ${{ github.event.inputs.commit_hash }}\n    - name: Download artifact\n      id: download-artifact\n      uses: dawidd6/action-download-artifact@v6\n      with:\n        workflow: rust.yml\n        workflow_conclusion: \"\"\n        branch: ${{ env.GITHUB_REF }}\n        name: \"fnm-windows\"\n        path: \"target/release\"\n        if_no_artifact_found: ignore\n    - uses: hecrj/setup-rust-action@v1\n      if: steps.download-artifact.outputs.artifact-found == false\n      with:\n        rust-version: stable\n    - uses: Swatinem/rust-cache@v2\n      if: steps.download-artifact.outputs.artifact-found == false\n    - name: Build release binary\n      if: steps.download-artifact.outputs.artifact-found == false\n      run: cargo build --release\n      env:\n        RUSTFLAGS: \"-C target-feature=+crt-static\"\n    - uses: pnpm/action-setup@v4.0.0\n      with:\n        run_install: false\n    - uses: actions/setup-node@v4\n      with:\n        node-version: 16.x\n        cache: 'pnpm'\n    - name: Get pnpm store directory\n      id: pnpm-cache\n      run: |\n        echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n    - uses: actions/cache@v4\n      name: Setup pnpm cache\n      with:\n        path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n        key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n        restore-keys: |\n          ${{ runner.os }}-pnpm-store-\n    - run: pnpm install\n    - name: 🐛 Debug Build\n      if: always()\n      uses: mxschmitt/action-tmate@v3\n      with:\n        limit-access-to-actor: true\n"
  },
  {
    "path": ".github/workflows/installation_script.yml",
    "content": "name: Installation script\non:\n  pull_request:\n    paths:\n      - .ci/install.sh\n  push:\n    branches:\n      - master\n    paths:\n      - .ci/install.sh\n\njobs:\n  test_against_latest_release_arm:\n    strategy:\n      matrix:\n        include:\n          - docker_image: arm64v8/ubuntu\n            docker_platform: linux/arm64/v8\n          - docker_image: arm32v7/ubuntu\n            docker_platform: linux/arm/v7\n    name: Test against latest release (ARM)\n    runs-on: ubuntu-latest\n    steps:\n      - name: Set up QEMU\n        id: qemu\n        uses: docker/setup-qemu-action@v3\n      - uses: actions/checkout@v4\n      - name: Run installation script in Docker\n        run: |\n          docker run --rm --platform ${{ matrix.docker_platform }} -v $(pwd):$(pwd) -e \"RUST_LOG=fnm=debug\" --workdir $(pwd) ${{matrix.docker_image}} bash -c '\n            set -e\n\n            apt update && apt install -y unzip curl libatomic1\n\n            echo \"-------------------------------------\"\n            echo \"Installing for CPU arch: $(uname -m)\"\n\n            bash ./.ci/install.sh\n\n            echo \"fnm --version\"\n            ~/.local/share/fnm/fnm --version\n\n            echo \"eval fnm env\"\n            eval \"$(~/.local/share/fnm/fnm env)\"\n\n            echo \"fnm install\"\n            ~/.local/share/fnm/fnm install 12\n\n            echo \"node -v\"\n            ~/.local/share/fnm/fnm exec --using=12 -- node -v\n          '\n\n  test_against_latest_release:\n    name: Test against latest release\n    strategy:\n      matrix:\n        shell: [fish, zsh, bash]\n        setup:\n          - os: ubuntu\n            script_arguments: \"\"\n          - os: macos\n            script_arguments: \"\"\n          - os: macos\n            script_arguments: \"--force-no-brew\"\n    runs-on: ${{ matrix.setup.os }}-latest\n    steps:\n      - uses: actions/checkout@v4\n      - run: \"sudo apt-get install -y ${{ matrix.shell }}\"\n        name: Install ${{matrix.shell}} using apt-get\n        if: matrix.setup.os == 'ubuntu'\n      - run: \"brew update && brew install ${{ matrix.shell }}\"\n        name: Update formulae and install ${{matrix.shell}} using Homebrew\n        if: matrix.setup.os == 'macos'\n      - run: |\n          if [ -f ~/.bashrc ]; then\n            cp ~/.bashrc ~/.bashrc.bak\n            echo 'echo hello world' > ~/.bashrc\n            echo '. ~/.bashrc.bak' >> ~/.bashrc\n          fi\n\n          if [ -f ~/.zshrc ]; then\n            echo 'echo hello world' > ~/.zshrc\n            echo '. ~/.zshrc.bak' >> ~/.zshrc\n          fi\n        name: reset shell profiles\n      - run: \"env SHELL=$(which ${{ matrix.shell }}) bash ./.ci/install.sh ${{ matrix.setup.script_arguments }}\"\n        name: Run the installation script\n      - run: ./.ci/test_installation_script.sh ${{ matrix.shell }}\n        name: \"Test installation script\"\n"
  },
  {
    "path": ".github/workflows/release-to-cargo.yml",
    "content": "name: release to cargo\non:\n  workflow_dispatch:\n  push:\n    tags: ['*']\njobs:\n  publish_to_crates_io:\n    runs-on: ubuntu-latest\n    name: Publish to crates.io\n    steps:\n      # set up\n      - uses: actions/checkout@v4\n\n      - uses: hecrj/setup-rust-action@v1\n        with:\n          rust-version: stable\n\n      - uses: Swatinem/rust-cache@v2\n\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n\n      - name: Publish to crates.io\n        run: cargo publish\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}\n          TERM: xterm\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: release\non:\n  push:\n    branches:\n      - master\n      - main\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  create_pull_request:\n    runs-on: ubuntu-latest\n    steps:\n      # set up\n      - uses: actions/checkout@v4\n\n      - uses: hecrj/setup-rust-action@v1\n        with:\n          rust-version: stable\n\n      - uses: Swatinem/rust-cache@v2\n\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n\n      # pnpm\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 20.x\n          cache: \"pnpm\"\n\n      - name: Get pnpm store directory\n        id: pnpm-cache\n        run: |\n          echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n\n      - uses: actions/cache@v4\n        name: Setup pnpm cache\n        with:\n          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n          restore-keys: |\n            ${{ runner.os }}-pnpm-store-\n\n      - name: Install Asciinema\n        run: |\n          pipx install asciinema\n\n      - name: Install Node.js project dependencies\n        run: pnpm install\n\n      - name: Create Release Pull Request\n        uses: changesets/action@v1\n        with:\n          version: \"pnpm version:prepare\"\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}\n          TERM: xterm\n"
  },
  {
    "path": ".github/workflows/rust.yml",
    "content": "name: Rust\n\non:\n  pull_request:\n  push:\n    branches:\n      - master\n\nconcurrency:\n  group: ci-${{ github.head_ref }}\n  cancel-in-progress: true\n\nenv:\n  RUST_VERSION: \"1.88\"\n\njobs:\n  fmt:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n      - uses: Swatinem/rust-cache@v2\n      - name: cargo fmt\n        run: cargo fmt -- --check\n\n  clippy:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n      - uses: Swatinem/rust-cache@v2\n      - name: cargo clippy\n        run: cargo clippy -- -D warnings\n\n  unit_tests:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-latest, macOS-latest, windows-latest]\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n      - uses: Swatinem/rust-cache@v2\n      - name: Run tests\n        run: cargo test\n\n  build_release:\n    runs-on: windows-latest\n    name: \"Release build for Windows\"\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n      - uses: Swatinem/rust-cache@v2\n      - name: Build release binary\n        run: cargo build --release\n        env:\n          RUSTFLAGS: \"-C target-feature=+crt-static\"\n      - uses: actions/upload-artifact@v4\n        with:\n          name: fnm-windows\n          path: target/release/fnm.exe\n\n  build_macos_release:\n    runs-on: macos-latest\n    name: \"Release build for macOS\"\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n          targets: x86_64-apple-darwin,aarch64-apple-darwin\n      - uses: Swatinem/rust-cache@v2\n      - name: Build release binary\n        run: |\n          cargo build --release --target x86_64-apple-darwin\n          strip target/x86_64-apple-darwin/release/fnm\n          cargo build --release --target aarch64-apple-darwin\n          strip target/aarch64-apple-darwin/release/fnm\n\n          mkdir -p target/release\n\n          # create a universal binary\n          lipo -create \\\n            target/x86_64-apple-darwin/release/fnm \\\n            target/aarch64-apple-darwin/release/fnm \\\n            -output target/release/fnm\n        env:\n          LZMA_API_STATIC: \"true\"\n      - name: Strip binary from debug symbols\n        run: strip target/release/fnm\n      - name: List dynamically linked libraries\n        run: otool -L target/release/fnm\n      - uses: actions/upload-artifact@v4\n        with:\n          name: fnm-macos\n          path: target/release/fnm\n\n  e2e_macos:\n    runs-on: macos-latest\n    needs: [build_macos_release]\n    name: \"e2e/macos\"\n    steps:\n      - uses: actions/checkout@v4\n      - name: install necessary shells\n        run: brew install fish zsh bash\n      - uses: actions/download-artifact@v4\n        with:\n          name: fnm-macos\n          path: target/release\n      - name: mark binary as executable\n        run: chmod +x target/release/fnm\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 18.x\n          cache: \"pnpm\"\n      - name: Get pnpm store directory\n        id: pnpm-cache\n        run: |\n          echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n      - uses: actions/cache@v4\n        name: Setup pnpm cache\n        with:\n          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n          restore-keys: |\n            ${{ runner.os }}-pnpm-store-\n      - run: pnpm install\n      - run: pnpm test\n        env:\n          FNM_TARGET_NAME: \"release\"\n          FORCE_COLOR: \"1\"\n\n  e2e_windows:\n    runs-on: windows-latest\n    needs: [build_release]\n    name: \"e2e/windows\"\n    steps:\n      - uses: actions/checkout@v4\n      - uses: actions/download-artifact@v4\n        with:\n          name: fnm-windows\n          path: target/release\n      - uses: MinoruSekine/setup-scoop@v4\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 18.x\n          cache: \"pnpm\"\n      - name: Get pnpm store directory\n        id: pnpm-cache\n        run: |\n          echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n      - uses: actions/cache@v4\n        name: Setup pnpm cache\n        with:\n          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n          restore-keys: |\n            ${{ runner.os }}-pnpm-store-\n      - run: pnpm install\n      - run: pnpm test\n        env:\n          FNM_TARGET_NAME: \"release\"\n          FORCE_COLOR: \"1\"\n\n  # e2e_windows_debug:\n  #   runs-on: windows-latest\n  #   name: \"e2e/windows/debug\"\n  #   environment: Debug\n  #   needs: [e2e_windows]\n  #   if: contains(join(needs.*.result, ','), 'failure')\n  #   steps:\n  #   - uses: actions/checkout@v3\n  #   - uses: actions/download-artifact@v3\n  #     with:\n  #       name: fnm-windows\n  #       path: target/release\n  #   - uses: pnpm/action-setup@v2.2.2\n  #     with:\n  #       run_install: false\n  #   - uses: actions/setup-node@v3\n  #     with:\n  #       node-version: 18.x\n  #       cache: 'pnpm'\n  #   - name: Get pnpm store directory\n  #     id: pnpm-cache\n  #     run: |\n  #       echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n  #   - uses: actions/cache@v3\n  #     name: Setup pnpm cache\n  #     with:\n  #       path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n  #       key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n  #       restore-keys: |\n  #         ${{ runner.os }}-pnpm-store-\n  #   - run: pnpm install\n  #   - name: 🐛 Debug Build\n  #     uses: mxschmitt/action-tmate@v3\n\n  e2e_linux:\n    runs-on: ubuntu-latest\n    needs: [build_static_linux_binary]\n    name: \"e2e/linux\"\n    steps:\n      - uses: actions/checkout@v4\n      - name: install necessary shells\n        run: sudo apt-get update && sudo apt-get install -y fish zsh bash\n      - uses: actions/download-artifact@v4\n        with:\n          name: fnm-linux\n          path: target/release\n      - name: mark binary as executable\n        run: chmod +x target/release/fnm\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 18.x\n          cache: \"pnpm\"\n      - name: Get pnpm store directory\n        id: pnpm-cache\n        run: |\n          echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n      - uses: actions/cache@v4\n        name: Setup pnpm cache\n        with:\n          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n          restore-keys: |\n            ${{ runner.os }}-pnpm-store-\n      - run: pnpm install\n      - run: pnpm test\n        env:\n          FNM_TARGET_NAME: \"release\"\n          FORCE_COLOR: \"1\"\n\n  build_static_linux_binary:\n    name: \"Build static Linux binary\"\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n          targets: x86_64-unknown-linux-musl\n      - uses: Swatinem/rust-cache@v2\n        with:\n          key: static-linux-binary\n      - name: Install musl tools\n        run: |\n          sudo apt-get update\n          sudo apt-get install -y --no-install-recommends musl-tools\n      - name: Build release binary\n        run: cargo build --release --target x86_64-unknown-linux-musl\n      - name: Strip binary from debug symbols\n        run: strip target/x86_64-unknown-linux-musl/release/fnm\n      - uses: actions/upload-artifact@v4\n        with:\n          name: fnm-linux\n          path: target/x86_64-unknown-linux-musl/release/fnm\n\n  build_static_arm_binary:\n    name: \"Build ARM binary\"\n    strategy:\n      matrix:\n        include:\n          - arch: arm64\n            rust_target: aarch64-unknown-linux-musl\n            docker_image: arm64v8/ubuntu\n            docker_platform: aarch64\n          - arch: arm32\n            rust_target: armv7-unknown-linux-gnueabihf\n            docker_image: arm32v7/ubuntu\n            docker_platform: armv7\n    runs-on: ubuntu-latest\n    env:\n      RUST_TARGET: ${{ matrix.rust_target }}\n    steps:\n      - uses: actions/checkout@v4\n      - name: Set up QEMU\n        id: qemu\n        uses: docker/setup-qemu-action@v3\n      - uses: hecrj/setup-rust-action@v2\n        with:\n          rust-version: ${{env.RUST_VERSION}}\n      - uses: Swatinem/rust-cache@v2\n        with:\n          key: arm-binary-${{ matrix.arch }}\n      - name: \"Download `cross` crate\"\n        run: cargo install cross\n      - name: \"Build release\"\n        run: cross build --target $RUST_TARGET --release\n      - uses: uraimo/run-on-arch-action@v2.1.2\n        name: Sanity test\n        with:\n          arch: ${{matrix.docker_platform}}\n          distro: ubuntu18.04\n\n          # Not required, but speeds up builds by storing container images in\n          # a GitHub package registry.\n          githubToken: ${{ github.token }}\n\n          env: |\n            RUST_LOG: fnm=debug\n\n          dockerRunArgs: |\n            --volume \"${PWD}/target/${{matrix.rust_target}}/release:/artifacts\"\n\n          # Set an output parameter `uname` for use in subsequent steps\n          run: |\n            echo \"Hello from $(uname -a)\"\n            /artifacts/fnm --version\n            echo \"fnm install 12.0.0\"\n            /artifacts/fnm install 12.0.0\n            echo \"fnm exec --using=12 -- node --version\"\n            /artifacts/fnm exec --using=12 -- node --version\n\n      - uses: actions/upload-artifact@v4\n        with:\n          name: fnm-${{ matrix.arch }}\n          path: target/${{ env.RUST_TARGET }}/release/fnm\n\n  ensure_commands_markdown_is_up_to_date:\n    runs-on: ubuntu-latest\n    name: Ensure command docs are up-to-date\n    needs: [build_static_linux_binary]\n    steps:\n      - uses: actions/checkout@v4\n      - name: install necessary shells\n        run: sudo apt-get update && sudo apt-get install -y fish zsh bash\n      - uses: actions/download-artifact@v4\n        with:\n          name: fnm-linux\n          path: target/release\n      - name: mark binary as executable\n        run: chmod +x target/release/fnm\n      - name: install fnm as binary\n        run: |\n          sudo install target/release/fnm /bin\n          fnm --version\n      - uses: pnpm/action-setup@v4.0.0\n        with:\n          run_install: false\n      - uses: actions/setup-node@v4\n        with:\n          node-version: 18.x\n          cache: \"pnpm\"\n      - name: Get pnpm store directory\n        id: pnpm-cache\n        run: |\n          echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n      - uses: actions/cache@v4\n        name: Setup pnpm cache\n        with:\n          path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n          key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n          restore-keys: |\n            ${{ runner.os }}-pnpm-store-\n      - run: pnpm install\n      - name: Generate command markdown\n        run: |\n          pnpm run generate-command-docs --check --binary-path=$(which fnm)\n\n      # TODO: use bnz\n      # run_e2e_benchmarks:\n      #   runs-on: ubuntu-latest\n      #   name: bench/linux\n      #   needs: [build_static_linux_binary]\n      #   permissions:\n      #     contents: write\n      #     pull-requests: write\n      #   steps:\n      #     - name: install necessary shells\n      #       run: sudo apt-get update && sudo apt-get install -y fish zsh bash hyperfine\n      #     - uses: actions/checkout@v3\n      #     - uses: actions/download-artifact@v3\n      #       with:\n      #         name: fnm-linux\n      #         path: target/release\n      #     - name: mark binary as executable\n      #       run: chmod +x target/release/fnm\n      #     - name: install fnm as binary\n      #       run: |\n      #         sudo install target/release/fnm /bin\n      #         fnm --version\n      #     - uses: pnpm/action-setup@v2.2.4\n      #       with:\n      #         run_install: false\n      #     - uses: actions/setup-node@v3\n      #       with:\n      #         node-version: 18.x\n      #         cache: \"pnpm\"\n      #     - name: Get pnpm store directory\n      #       id: pnpm-cache\n      #       run: |\n      #         echo \"::set-output name=pnpm_cache_dir::$(pnpm store path)\"\n      #     - uses: actions/cache@v3\n      #       name: Setup pnpm cache\n      #       with:\n      #         path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}\n      #         key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}\n      #         restore-keys: |\n      #           ${{ runner.os }}-pnpm-store-\n      #     - run: pnpm install\n      #     - name: Run benchmarks\n      #       env:\n      #         GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n      #         SHOULD_STORE: ${{ toJson(!github.event.pull_request) }}\n      #       id: benchmark\n      #       run: |\n      #         delimiter=\"$(openssl rand -hex 8)\"\n      #         echo \"markdown<<${delimiter}\" >> \"${GITHUB_OUTPUT}\"\n      #         node benchmarks/run.mjs --store=$SHOULD_STORE >> \"${GITHUB_OUTPUT}\"\n      #         echo \"${delimiter}\" >> \"${GITHUB_OUTPUT}\"\n      # - name: Create a PR comment\n      #   if: ${{ github.event.pull_request }}\n      #   uses: thollander/actions-comment-pull-request@v2\n      #   with:\n      #     message: |\n      #       ## Linux Benchmarks for ${{ github.event.pull_request.head.sha }}\n      #       ${{ steps.benchmark.outputs.markdown }}\n      #     comment_tag: \"benchy comment\"\n      #\n      # - name: Create a commit comment\n      #   if: ${{ !github.event.pull_request }}\n      #   uses: peter-evans/commit-comment@v2\n      #   with:\n      #     body: |\n      #       ## Linux Benchmarks\n      #       ${{ steps.benchmark.outputs.markdown }}\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules/\n.ci/screen_recording\n/benchmarks/results\n/target\n**/*.rs.bk\nfeature_tests/.tmp\n*.log\n/site/public\n.vercel\n.proxy\n"
  },
  {
    "path": ".kodiak.toml",
    "content": "version = 1\n"
  },
  {
    "path": ".node-version",
    "content": "20.14.0\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "## 1.31.0 (2022-02-16)\n\n## 1.39.0\n\n### Minor Changes\n\n- [#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.\n\n- [#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\n\n### Patch Changes\n\n- [#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\n\n- [#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.\n\n- [#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\n\n## 1.38.1\n\n### Patch Changes\n\n- [#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\n\n## 1.38.0\n\n### Minor Changes\n\n- [#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.\n\n  to disable it, add a `--resolve-engines=false` flag, and make sure to open an issue describing _why_.\n  It might feel like a breaking change but .nvmrc and .node-version have precedence so it should not.\n\n  I am all in favor of better experience and I believe supporting engines.node is a good direction.\n\n### Patch Changes\n\n- [#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\n\n- [#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\n\n- [#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\n\n## 1.37.2\n\n### Patch Changes\n\n- [#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\n\n- [#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\n\n- [#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`\n\n- [#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\n\n- [#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\n\n- [#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\n\n- [#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\n\n- [#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\n\n- [#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`\n\n- [#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\n\n## 1.37.1\n\n### Patch Changes\n\n- [#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\n\n## 1.37.0\n\n### Minor Changes\n\n- [#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\n\n### Patch Changes\n\n- [#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\n\n- [#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\n\n## 1.36.0\n\n### Minor Changes\n\n- [#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\n\n- [#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\n\n- [#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\n\n### Patch Changes\n\n- [#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)\n\n- [#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`\n\n- [#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\n\n- [#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)\n\n- [#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\n\n- [#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\n\n## 1.35.1\n\n### Patch Changes\n\n- [#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`\n\n## 1.35.0\n\n### Minor Changes\n\n- [#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\n\n### Patch Changes\n\n- [#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\n\n## 1.34.0\n\n### Minor Changes\n\n- Add --corepack-enabled flag for automatically enabling corepack on fnm install ([#960](https://github.com/Schniz/fnm/pull/960))\n\n### Patch Changes\n\n- modernize tty check (#973 by @tottoto) ([`48b2611`](https://github.com/Schniz/fnm/commit/48b2611e4b1c205f07dcbd50f2fff436becb77c1))\n\n- use cygwinpath to make the path posix-like on Windows Bash usage ([#960](https://github.com/Schniz/fnm/pull/960))\n\n- capitalize \"n\" to show default (#963 by @Joshuahuahua) ([`48b2611`](https://github.com/Schniz/fnm/commit/48b2611e4b1c205f07dcbd50f2fff436becb77c1))\n\n## 1.33.1\n\n### Patch Changes\n\n- remove upx compression from arm binaries because it fails to build on latest rust ([#875](https://github.com/Schniz/fnm/pull/875))\n\n## 1.33.0\n\n### Minor Changes\n\n- Replace `semver` with `node_semver` ([#816](https://github.com/Schniz/fnm/pull/816))\n\n- support `fnm install --latest` to install the latest Node.js version ([#859](https://github.com/Schniz/fnm/pull/859))\n\n## 1.32.0\n\n### Minor Changes\n\n- Add `--json` to `fnm env` to output the env vars as JSON ([#800](https://github.com/Schniz/fnm/pull/800))\n\n### Patch Changes\n\n- This updates the Changesets configurations. ([#783](https://github.com/Schniz/fnm/pull/783))\n\n- fix test: Use correct PATH for npm install test ([#768](https://github.com/Schniz/fnm/pull/768))\n\n- Make installation script respect `$XDG_DATA_HOME` ([#614](https://github.com/Schniz/fnm/pull/614))\n\n## 1.31.1\n\n### Patch Changes\n\n- 6e6bdd8: Add changesets\n\n#### Bugfix 🐛\n\n- [#671](https://github.com/Schniz/fnm/pull/671) fix native-creds errors (using the unpublished version of reqwest) ([@Schniz](https://github.com/Schniz))\n- [#663](https://github.com/Schniz/fnm/pull/663) remove .unwrap() and .expect() in shell code ([@Schniz](https://github.com/Schniz))\n- [#656](https://github.com/Schniz/fnm/pull/656) Remove unwrap in fnm env, make error more readable ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.30.1 (2022-01-30)\n\n#### Bugfix 🐛\n\n- [#652](https://github.com/Schniz/fnm/pull/652) Fix `fnm completions` ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.30.0 (2022-01-30)\n\n#### Bugfix 🐛\n\n- [#625](https://github.com/Schniz/fnm/pull/625) Revert from using sysinfo, but only on Unix machines ([@Schniz](https://github.com/Schniz))\n- [#638](https://github.com/Schniz/fnm/pull/638) Use local cache directory instead of temp directory for symlinks ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#617](https://github.com/Schniz/fnm/pull/617) fix(deps): update rust crate clap to v3 ([@renovate[bot]](https://github.com/apps/renovate))\n- [#630](https://github.com/Schniz/fnm/pull/630) Replace `snafu` with `thiserror` ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#637](https://github.com/Schniz/fnm/pull/637) [Documentation] Adds Additional info regarding .node-version ([@uchihamalolan](https://github.com/uchihamalolan))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Malolan B ([@uchihamalolan](https://github.com/uchihamalolan))\n\n## v1.29.2 (2022-01-06)\n\n#### Bugfix 🐛\n\n- [#626](https://github.com/Schniz/fnm/pull/626) Create the multishells directory if it is missing ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#598](https://github.com/Schniz/fnm/pull/598) Update README.md file emoji ([@lorensr](https://github.com/lorensr))\n- [#616](https://github.com/Schniz/fnm/pull/616) Use on cd by default ([@matthieubosquet](https://github.com/matthieubosquet))\n\n#### Committers: 3\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Loren ☺️ ([@lorensr](https://github.com/lorensr))\n- Matthieu Bosquet ([@matthieubosquet](https://github.com/matthieubosquet))\n\n## v1.29.1 (2021-12-28)\n\n#### Bugfix 🐛\n\n- [#613](https://github.com/Schniz/fnm/pull/613) Don't warn on `~/.fnm` yet ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.29.0 (2021-12-28)\n\n#### New Feature 🎉\n\n- [#607](https://github.com/Schniz/fnm/pull/607) Allow recursive version lookups ([@Schniz](https://github.com/Schniz))\n- [#416](https://github.com/Schniz/fnm/pull/416) Respect \\$XDG_DATA_HOME ([@samhh](https://github.com/samhh))\n\n#### Bugfix 🐛\n\n- [#603](https://github.com/Schniz/fnm/pull/603) (re)Include feature for (native) certificates ([@pfiaux](https://github.com/pfiaux))\n- [#605](https://github.com/Schniz/fnm/pull/605) Add a user-agent header ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#606](https://github.com/Schniz/fnm/pull/606) Migrate to Rust 2021 edition ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 3\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Patrick Fiaux ([@pfiaux](https://github.com/pfiaux))\n- Sam A. Horvath-Hunt ([@samhh](https://github.com/samhh))\n\n## v1.28.2 (2021-12-05)\n\n#### Bugfix 🐛\n\n- [#586](https://github.com/Schniz/fnm/pull/586) Revert the change to ureq ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#584](https://github.com/Schniz/fnm/pull/584) Add warning to symlink creation ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.28.1 (2021-11-17)\n\n#### Bugfix 🐛\n\n- [#576](https://github.com/Schniz/fnm/pull/576) First fix for slowess in fnm env ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.28.0 (2021-11-16)\n\n#### New Feature 🎉\n\n- [#556](https://github.com/Schniz/fnm/pull/556) Allow aliasing to the system version ([@Schniz](https://github.com/Schniz))\n- [#547](https://github.com/Schniz/fnm/pull/547) Replace reqwest with ureq for less dependencies and smaller file size ([@dnaka91](https://github.com/dnaka91))\n\n#### Bugfix 🐛\n\n- [#573](https://github.com/Schniz/fnm/pull/573) Infer shell with `sysinfo` crate ([@Schniz](https://github.com/Schniz))\n- [#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))\n\n#### Internal 🛠\n\n- [#554](https://github.com/Schniz/fnm/pull/554) Fix clippy & use musl target on Rust compiler for static compilation ([@dnaka91](https://github.com/dnaka91))\n\n#### Documentation 📝\n\n- [#545](https://github.com/Schniz/fnm/pull/545) docs(cli): Fix typo ([@SanchithHegde](https://github.com/SanchithHegde))\n- [#544](https://github.com/Schniz/fnm/pull/544) Replace error message with a more useful one ([@yonifra](https://github.com/yonifra))\n- [#537](https://github.com/Schniz/fnm/pull/537) Show log level options in help and error message ([@lucasweng](https://github.com/lucasweng))\n\n#### Committers: 5\n\n- Dominik Nakamura ([@dnaka91](https://github.com/dnaka91))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Jonathan Fraimorice ([@yonifra](https://github.com/yonifra))\n- Lucas Weng ([@lucasweng](https://github.com/lucasweng))\n- Sanchith Hegde ([@SanchithHegde](https://github.com/SanchithHegde))\n\n## v1.27.0 (2021-09-17)\n\n#### New Feature 🎉\n\n- [#519](https://github.com/Schniz/fnm/pull/519) Windows: Use junctions rather than symlinks ([@davidaurelio](https://github.com/davidaurelio))\n- [#489](https://github.com/Schniz/fnm/pull/489) Add unalias command ([@AlexMunoz](https://github.com/AlexMunoz))\n\n#### Bugfix 🐛\n\n- [#528](https://github.com/Schniz/fnm/pull/528) installation script: Use `=` instead of `==` ([@develoot](https://github.com/develoot))\n- [#512](https://github.com/Schniz/fnm/pull/512) fix(dep): Revert \"Include feature for (native) certificates #468\" ([@itotallyrock](https://github.com/itotallyrock))\n- [#514](https://github.com/Schniz/fnm/pull/514) Invoke fnm use on startup for PowerShell ([@naoey](https://github.com/naoey))\n\n#### Documentation 📝\n\n- [#529](https://github.com/Schniz/fnm/pull/529) Add Chocolatey installation instructions ([@CMeeg](https://github.com/CMeeg))\n- [#496](https://github.com/Schniz/fnm/pull/496) install.sh: print an exit message for missing deps ([@waldyrious](https://github.com/waldyrious))\n- [#516](https://github.com/Schniz/fnm/pull/516) More informative log level error message ([@waldyrious](https://github.com/waldyrious))\n- [#493](https://github.com/Schniz/fnm/pull/493) Add instructions to setup the file for Cmder ([@Lunchb0ne](https://github.com/Lunchb0ne))\n\n#### Committers: 8\n\n- Abhishek Aryan ([@Lunchb0ne](https://github.com/Lunchb0ne))\n- Alex Munoz ([@AlexMunoz](https://github.com/AlexMunoz))\n- Chris Meagher ([@CMeeg](https://github.com/CMeeg))\n- David Aurelio ([@davidaurelio](https://github.com/davidaurelio))\n- Jeffrey Meyer ([@itotallyrock](https://github.com/itotallyrock))\n- Kitae Kim ([@develoot](https://github.com/develoot))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n- [@naoey](https://github.com/naoey)\n\n## v1.26.0 (2021-07-15)\n\n#### Bugfix 🐛\n\n- [#484](https://github.com/Schniz/fnm/pull/484) fix: --install-if-missing when using version alias ([@AlexMunoz](https://github.com/AlexMunoz))\n- [#468](https://github.com/Schniz/fnm/pull/468) Include feature for (native) certificates ([@pfiaux](https://github.com/pfiaux))\n\n#### Documentation 📝\n\n- [#467](https://github.com/Schniz/fnm/pull/467) Add instructions for removing fnm ([@binyamin](https://github.com/binyamin))\n- [#461](https://github.com/Schniz/fnm/pull/461) Fix missing list-remote in command doc ([@binhonglee](https://github.com/binhonglee))\n\n#### Committers: 4\n\n- Alex Munoz ([@AlexMunoz](https://github.com/AlexMunoz))\n- BinHong Lee ([@binhonglee](https://github.com/binhonglee))\n- Binyamin Aron Green ([@binyamin](https://github.com/binyamin))\n- Patrick Fiaux ([@pfiaux](https://github.com/pfiaux))\n\n## v1.25.0 (2021-05-17)\n\n#### New Feature 🎉\n\n- [#436](https://github.com/Schniz/fnm/pull/436) feat: use arm for aarch64-darwin-node@16 platforms ([@pckilgore](https://github.com/pckilgore))\n\n#### Documentation 📝\n\n- [#432](https://github.com/Schniz/fnm/pull/432) Auto-generate command documentation markdown ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Patrick Kilgore ([@pckilgore](https://github.com/pckilgore))\n\n## v1.24.0 (2021-04-02)\n\n#### New Feature 🎉\n\n- [#421](https://github.com/Schniz/fnm/pull/421) Adding FNM_ARCH as an exported env var from `fnm env` ([@Schniz](https://github.com/Schniz))\n- [#417](https://github.com/Schniz/fnm/pull/417) Support Apple M1 by installing Rosetta Node builds ([@pckilgore](https://github.com/pckilgore))\n\n#### Bugfix 🐛\n\n- [#422](https://github.com/Schniz/fnm/pull/422) Create version symlinks in a nested directory ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Patrick Kilgore ([@pckilgore](https://github.com/pckilgore))\n\n## v1.23.2 (2021-03-24)\n\n#### Bugfix 🐛\n\n- [#413](https://github.com/Schniz/fnm/pull/413) Improve \"version not found\" error message ([@waldyrious](https://github.com/waldyrious))\n- [#414](https://github.com/Schniz/fnm/pull/414) More meaningful error message when a subprocess is killed ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n\n## v1.23.1 (2021-03-21)\n\n#### Bugfix 🐛\n\n- [#411](https://github.com/Schniz/fnm/pull/411) Call the fnm use-on-cd hook on fish initialization ([@Schniz](https://github.com/Schniz))\n- [#404](https://github.com/Schniz/fnm/pull/404) Ignore LogLevel on `fnm ls` ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#408](https://github.com/Schniz/fnm/pull/408) Fix ARM builds CI ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#405](https://github.com/Schniz/fnm/pull/405) Fix a couple typos ([@waldyrious](https://github.com/waldyrious))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n\n## v1.23.0 (2021-03-02)\n\n#### New Feature 🎉\n\n- [#403](https://github.com/Schniz/fnm/pull/403) Allow `fnm use` to use a file path ([@Schniz](https://github.com/Schniz))\n- [#401](https://github.com/Schniz/fnm/pull/401) Allow using filenames in --using= ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#398](https://github.com/Schniz/fnm/pull/398) `fnm exec`: Don't require double-dash ([@Schniz](https://github.com/Schniz))\n- [#389](https://github.com/Schniz/fnm/pull/389) Chore - Use a tier 1 target for Linux binary ([@kaioduarte](https://github.com/kaioduarte))\n- [#384](https://github.com/Schniz/fnm/pull/384) Do not list hidden directories as installed versions ([@scadu](https://github.com/scadu))\n\n#### Documentation 📝\n\n- [#397](https://github.com/Schniz/fnm/pull/397) Fix minor typos ([@leafrogers](https://github.com/leafrogers))\n- [#385](https://github.com/Schniz/fnm/pull/385) README: add symlink support on Windows ([@scadu](https://github.com/scadu))\n- [#377](https://github.com/Schniz/fnm/pull/377) Improvements to the README ([@waldyrious](https://github.com/waldyrious))\n\n#### Committers: 5\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Kaio Duarte ([@kaioduarte](https://github.com/kaioduarte))\n- Leaf Rogers ([@leafrogers](https://github.com/leafrogers))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n- Łukasz Jendrysik ([@scadu](https://github.com/scadu))\n\n## v1.22.9 (2021-01-22)\n\n#### Bugfix 🐛\n\n- [#368](https://github.com/Schniz/fnm/pull/368) Update 'ring' to '0.16.17' ([@gucheen](https://github.com/gucheen))\n- [#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))\n\n#### Documentation 📝\n\n- [#341](https://github.com/Schniz/fnm/pull/341) Update installation instructions ([@Schniz](https://github.com/Schniz))\n- [#329](https://github.com/Schniz/fnm/pull/329) Add scoop support ([@Armaldio](https://github.com/Armaldio))\n- [#334](https://github.com/Schniz/fnm/pull/334) Add installation instructions from cargo ([@zhmushan](https://github.com/zhmushan))\n\n#### Committers: 5\n\n- Cheng Gu ([@gucheen](https://github.com/gucheen))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Quentin Goinaud ([@Armaldio](https://github.com/Armaldio))\n- Thales Maciel ([@thales-maciel](https://github.com/thales-maciel))\n- 木杉 ([@zhmushan](https://github.com/zhmushan))\n\n## v1.22.8 (2020-11-10)\n\n#### Documentation 📝\n\n- [#327](https://github.com/Schniz/fnm/pull/327) Make ls and ls-remote aliases visible ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.22.7 (2020-11-09)\n\n#### New Feature 🎉\n\n- [#315](https://github.com/Schniz/fnm/pull/315) Add `list` alias for `ls` ([@probablykasper](https://github.com/probablykasper))\n\n#### Bugfix 🐛\n\n- [#326](https://github.com/Schniz/fnm/pull/326) Make config arguments globally available on all commands ([@Schniz](https://github.com/Schniz))\n- [#323](https://github.com/Schniz/fnm/pull/323) Escape `cd` calls in Bash's use-on-cd ([@Schniz](https://github.com/Schniz))\n- [#322](https://github.com/Schniz/fnm/pull/322) Run `fnm use` on shell initialization in Bash ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Kasper ([@probablykasper](https://github.com/probablykasper))\n\n## v1.22.6 (2020-11-04)\n\n#### Bugfix 🐛\n\n- [#317](https://github.com/Schniz/fnm/pull/317) Bring back --using-file flag with a deprecation warning. ([@bjornua](https://github.com/bjornua))\n\n#### Committers: 1\n\n- Bjørn Arnholtz ([@bjornua](https://github.com/bjornua))\n\n## v1.22.5 (2020-10-29)\n\n#### Bugfix 🐛\n\n- [#310](https://github.com/Schniz/fnm/pull/310) Better error handling in symlink replacement ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#307](https://github.com/Schniz/fnm/pull/307) Refer to homebrew/core formula instead of custom tap ([@jameschensmith](https://github.com/jameschensmith))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith))\n\n## v1.22.4 (2020-10-28)\n\n#### New Feature 🎉\n\n- [#304](https://github.com/Schniz/fnm/pull/304) Make the first installed version the default one ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#308](https://github.com/Schniz/fnm/pull/308) Allow unsuccessful symlink deletion in `fnm use` ([@Schniz](https://github.com/Schniz))\n- [#303](https://github.com/Schniz/fnm/pull/303) Add ARM handling to installation script ([@Schniz](https://github.com/Schniz))\n- [#289](https://github.com/Schniz/fnm/pull/289) Remove logs from automatic version switching in `--use-on-cd` ([@maxjacobson](https://github.com/maxjacobson))\n- [#301](https://github.com/Schniz/fnm/pull/301) UserVersion: Fix different parsing for leading `v` ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#306](https://github.com/Schniz/fnm/pull/306) Throw an error instead of panicking when can't infer shell ([@Schniz](https://github.com/Schniz))\n- [#297](https://github.com/Schniz/fnm/pull/297) Update CI badge ([@jameschensmith](https://github.com/jameschensmith))\n\n#### Committers: 3\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith))\n- Max Jacobson ([@maxjacobson](https://github.com/maxjacobson))\n\n## v1.22.3 (2020-10-26)\n\n#### New Feature 🎉\n\n- [#292](https://github.com/Schniz/fnm/pull/292) Add uninstall command ([@Schniz](https://github.com/Schniz))\n- [#276](https://github.com/Schniz/fnm/pull/276) Add pre-built binaries for ARM32 and ARM64 ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#290](https://github.com/Schniz/fnm/pull/290) Fix shell inference in VSCode ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#287](https://github.com/Schniz/fnm/pull/287) Remove `--multi` from install script ([@jameschensmith](https://github.com/jameschensmith))\n\n#### Documentation 📝\n\n- [#295](https://github.com/Schniz/fnm/pull/295) Add a warning if MULTISHELL env var is not in PATH ([@Schniz](https://github.com/Schniz))\n- [#293](https://github.com/Schniz/fnm/pull/293) Add detailed error instead of panic regarding `fnm env` ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- James Chen-Smith ([@jameschensmith](https://github.com/jameschensmith))\n\n## v1.22.2 (2020-10-25)\n\n#### Bugfix 🐛\n\n- [#284](https://github.com/Schniz/fnm/pull/284) Fix npm not working because of wrong file copying ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#282](https://github.com/Schniz/fnm/pull/282) site: proxy the installation script ([@Schniz](https://github.com/Schniz))\n- [#271](https://github.com/Schniz/fnm/pull/271) Update README for Windows instructions ([@Schniz](https://github.com/Schniz))\n- [#281](https://github.com/Schniz/fnm/pull/281) docs: removed mentions of --multi from README ([@folke](https://github.com/folke))\n\n#### Committers: 2\n\n- Folke Lemaitre ([@folke](https://github.com/folke))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.22.1 (2020-10-25)\n\n#### Internal 🛠\n\n- [#279](https://github.com/Schniz/fnm/pull/279) Remove UPX binary compression for now ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.22.0 (2020-10-25)\n\n#### Bugfix 🐛\n\n- [#275](https://github.com/Schniz/fnm/pull/275) Fix moving a node installation across mounting points ([@jaythomas](https://github.com/jaythomas))\n\n#### Internal 🛠\n\n- [#274](https://github.com/Schniz/fnm/pull/274) Add ARM arch support in downloads ([@jaythomas](https://github.com/jaythomas))\n- [#266](https://github.com/Schniz/fnm/pull/266) Use separate config file for fish config ([@wesbaker](https://github.com/wesbaker))\n\n#### Committers: 3\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Jay Thomas ([@jaythomas](https://github.com/jaythomas))\n- Wes Baker ([@wesbaker](https://github.com/wesbaker))\n\n## v1.22.0-beta-1 (2020-10-07)\n\n#### New Feature 🎉\n\n- [#244](https://github.com/Schniz/fnm/pull/244) Allow using homebrew to install with the installation script ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#225](https://github.com/Schniz/fnm/pull/225) Remove unused condition ([@joliss](https://github.com/joliss))\n\n#### Internal 🛠\n\n- [#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))\n- [#243](https://github.com/Schniz/fnm/pull/243) Add installation script testing ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#247](https://github.com/Schniz/fnm/pull/247) fixed a typo ([@0xflotus](https://github.com/0xflotus))\n- [#245](https://github.com/Schniz/fnm/pull/245) Shorten the installation script ([@Schniz](https://github.com/Schniz))\n- [#237](https://github.com/Schniz/fnm/pull/237) docs: add explanation of uninstall command to README ([@kazushisan](https://github.com/kazushisan))\n- [#235](https://github.com/Schniz/fnm/pull/235) Mention fnm omf plugin for Fish users ([@idkjs](https://github.com/idkjs))\n\n#### Committers: 5\n\n- 0xflotus ([@0xflotus](https://github.com/0xflotus))\n- Alain Armand ([@idkjs](https://github.com/idkjs))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Jo Liss ([@joliss](https://github.com/joliss))\n- Kazushi Konosu ([@kazushisan](https://github.com/kazushisan))\n\n## v1.21.0 (2020-06-07)\n\n#### New Feature 🎉\n\n- [#220](https://github.com/Schniz/fnm/pull/220) Add `current` command to retrieve the current Node version ([@vladimyr](https://github.com/vladimyr))\n- [#210](https://github.com/Schniz/fnm/pull/210) Allow aliasing and removing an alias ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#217](https://github.com/Schniz/fnm/pull/217) Set version on new shell initialization in fish ([@jaredramirez](https://github.com/jaredramirez))\n- [#207](https://github.com/Schniz/fnm/pull/207) Format dotfiles versions before comparison ([@amitdahan](https://github.com/amitdahan))\n\n#### Committers: 4\n\n- Amit Dahan ([@amitdahan](https://github.com/amitdahan))\n- Dario Vladović ([@vladimyr](https://github.com/vladimyr))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Jared Ramirez ([@jaredramirez](https://github.com/jaredramirez))\n\n## v1.20.0 (2020-03-22)\n\n#### New Feature 🎉\n\n- [#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))\n\n#### Bugfix 🐛\n\n- [#199](https://github.com/Schniz/fnm/pull/199) Fix typo criterias -> criteria ([@waldyrious](https://github.com/waldyrious))\n\n#### Documentation 📝\n\n- [#204](https://github.com/Schniz/fnm/pull/204) Improve eval expression in `README.md` ([@loliee](https://github.com/loliee))\n\n#### Committers: 3\n\n- Corentin Leruth ([@tatchi](https://github.com/tatchi))\n- Maxime Loliée ([@loliee](https://github.com/loliee))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n\n## v1.19.0 (2020-03-09)\n\n#### New Feature 🎉\n\n- [#194](https://github.com/Schniz/fnm/pull/194) Add `fnm exec` to run commands with the fnm environment ([@Schniz](https://github.com/Schniz))\n- [#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))\n- [#190](https://github.com/Schniz/fnm/pull/190) Add majorVersion option to ls-remote ([@tatchi](https://github.com/tatchi))\n\n#### Bugfix 🐛\n\n- [#200](https://github.com/Schniz/fnm/pull/200) Do not repeat installation prompt for unrecognized versions ([@tatchi](https://github.com/tatchi))\n- [#197](https://github.com/Schniz/fnm/pull/197) Fix capitalization of message in Use.re ([@waldyrious](https://github.com/waldyrious))\n\n#### Internal 🛠\n\n- [#202](https://github.com/Schniz/fnm/pull/202) Update rely ([@tatchi](https://github.com/tatchi))\n- [#192](https://github.com/Schniz/fnm/pull/192) Bump ocaml to 4.08 ([@tatchi](https://github.com/tatchi))\n\n#### Committers: 3\n\n- Corentin Leruth ([@tatchi](https://github.com/tatchi))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Waldir Pimenta ([@waldyrious](https://github.com/waldyrious))\n\n## v1.18.1 (2019-12-30)\n\n#### Bugfix 🐛\n\n- [#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))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.18.0 (2019-12-23)\n\n#### New Feature 🎉\n\n- [#176](https://github.com/Schniz/fnm/pull/176) Specify the release to the install script ([@chrisdaley](https://github.com/chrisdaley))\n\n#### Bugfix 🐛\n\n- [#177](https://github.com/Schniz/fnm/pull/177) Fix \"illegal instruction\" errors on some CPUs ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#179](https://github.com/Schniz/fnm/pull/179) Bump lwt version ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Chris Daley ([@chrisdaley](https://github.com/chrisdaley))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.17.0 (2019-11-26)\n\n#### Bugfix 🐛\n\n- [#169](https://github.com/Schniz/fnm/pull/169) Support spaces in directory name in Bash ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#172](https://github.com/Schniz/fnm/pull/172) Revert into using `ocaml-tls` instead of `ocaml-ssl` ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.16.0 (2019-10-27)\n\n#### New Feature 🎉\n\n- [#146](https://github.com/Schniz/fnm/pull/146) Add support for `lts/*` ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#150](https://github.com/Schniz/fnm/pull/150) Add missing log level to `env` output for Fish shell ([@thomsj](https://github.com/thomsj))\n\n#### Internal 🛠\n\n- [#154](https://github.com/Schniz/fnm/pull/154) Run all feature tests ([@Schniz](https://github.com/Schniz))\n- [#148](https://github.com/Schniz/fnm/pull/148) Make `env` smoke test pass when run with fish ([@thomsj](https://github.com/thomsj))\n- [#153](https://github.com/Schniz/fnm/pull/153) Add missing `exit 1`s to `partial_semver` tests ([@thomsj](https://github.com/thomsj))\n- [#151](https://github.com/Schniz/fnm/pull/151) Add a CI check for code formatting ([@Schniz](https://github.com/Schniz))\n- [#149](https://github.com/Schniz/fnm/pull/149) Update to v6.17.1 in `partial_semver` feature test ([@thomsj](https://github.com/thomsj))\n- [#143](https://github.com/Schniz/fnm/pull/143) Try to install new deps ([@Schniz](https://github.com/Schniz))\n- [#142](https://github.com/Schniz/fnm/pull/142) Drop buildsInSource ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#157](https://github.com/Schniz/fnm/pull/157) Rename `--base-dir` to `--fnm-dir` in README ([@thomsj](https://github.com/thomsj))\n- [#158](https://github.com/Schniz/fnm/pull/158) Uncapitalise \"Node\" in `--multi` description ([@thomsj](https://github.com/thomsj))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- James Thomson ([@thomsj](https://github.com/thomsj))\n\n## v1.15.0 (2019-09-23)\n\n#### Bugfix 🐛\n\n- [#138](https://github.com/Schniz/fnm/pull/138) Do uninstallation in steps ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#132](https://github.com/Schniz/fnm/pull/132) Fix spelling of availability in install.sh ([@trevershick](https://github.com/trevershick))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Trever Shick ([@trevershick](https://github.com/trevershick))\n\n## v1.14.0 (2019-08-20)\n\n#### New Feature 🎉\n\n- [#134](https://github.com/Schniz/fnm/pull/134) Alias -v to --version ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#131](https://github.com/Schniz/fnm/pull/131) Deprecates MacOS installation using the script in favor of Homebrew ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#133](https://github.com/Schniz/fnm/pull/133) Fix Windows build once again! ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.13.0 (2019-07-15)\n\n#### New Feature 🎉\n\n- [#129](https://github.com/Schniz/fnm/pull/129) Alias latest versions on installation ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#125](https://github.com/Schniz/fnm/pull/125) format versions in `uninstall` ([@Schniz](https://github.com/Schniz))\n- [#114](https://github.com/Schniz/fnm/pull/114) installation script: use $INSTALL_DIR instead of hard-coded $HOME/.fnm ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#130](https://github.com/Schniz/fnm/pull/130) Fix issues related to help pages ([@Schniz](https://github.com/Schniz))\n- [#123](https://github.com/Schniz/fnm/pull/123) Fix typo in successfully ([@pavelloz](https://github.com/pavelloz))\n- [#118](https://github.com/Schniz/fnm/pull/118) Add note about upgrading ([@pavelloz](https://github.com/pavelloz))\n- [#119](https://github.com/Schniz/fnm/pull/119) Remove \"Homebrew\" from future plans as it is done ([@pavelloz](https://github.com/pavelloz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Paweł Kowalski ([@pavelloz](https://github.com/pavelloz))\n\n## v1.12.0 (2019-06-06)\n\n#### New Feature 🎉\n\n- [#106](https://github.com/Schniz/fnm/pull/106) Add `default`, as a shortcut for `alias default` ([@dangdennis](https://github.com/dangdennis))\n- [#104](https://github.com/Schniz/fnm/pull/104) Add a 'debug' log level ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#88](https://github.com/Schniz/fnm/pull/88) Successfully build on Windows ([@ulrikstrid](https://github.com/ulrikstrid))\n\n#### Committers: 3\n\n- Dennis Dang ([@dangdennis](https://github.com/dangdennis))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Ulrik Strid ([@ulrikstrid](https://github.com/ulrikstrid))\n\n## v1.11.0 (2019-05-27)\n\n#### New Feature 🎉\n\n- [#98](https://github.com/Schniz/fnm/pull/98) Add `uninstall` command ([@tatchi](https://github.com/tatchi))\n- [#97](https://github.com/Schniz/fnm/pull/97) Add the ability to use system version of Node ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#103](https://github.com/Schniz/fnm/pull/103) Fix missing aliases due to newer `realpath` ([@Schniz](https://github.com/Schniz))\n- [#99](https://github.com/Schniz/fnm/pull/99) fix EACCES error when installing an already downloaded version ([@tatchi](https://github.com/tatchi))\n\n#### Internal 🛠\n\n- [#101](https://github.com/Schniz/fnm/pull/101) Move from base to core ([@ulrikstrid](https://github.com/ulrikstrid))\n- [#102](https://github.com/Schniz/fnm/pull/102) Implement `realpath` instead of binding to C library ([@Schniz](https://github.com/Schniz))\n- [#100](https://github.com/Schniz/fnm/pull/100) Add Semver to library, an simple non-spec implementation of semver ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 3\n\n- Corentin Leruth ([@tatchi](https://github.com/tatchi))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Ulrik Strid ([@ulrikstrid](https://github.com/ulrikstrid))\n\n## v1.10.0 (2019-05-01)\n\n#### New Feature 🎉\n\n- [#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))\n\n#### Documentation 📝\n\n- [#95](https://github.com/Schniz/fnm/pull/95) Shorten installation script url ([@vladimyr](https://github.com/vladimyr))\n\n#### Committers: 2\n\n- Dario Vladović ([@vladimyr](https://github.com/vladimyr))\n- Tomer Ohana ([@ohana54](https://github.com/ohana54))\n\n## v1.9.1 (2019-04-14)\n\n#### Bugfix 🐛\n\n- [#91](https://github.com/Schniz/fnm/pull/91) Fix `fnm env` for fish shell. ([@hwartig](https://github.com/hwartig))\n- [#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))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Harald Wartig ([@hwartig](https://github.com/hwartig))\n\n## v1.9.0 (2019-03-18)\n\n#### New Feature 🎉\n\n- [#86](https://github.com/Schniz/fnm/pull/86) Add support for interactive installation for use ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#85](https://github.com/Schniz/fnm/pull/85) Update README.md ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.8.0 (2019-03-13)\n\n#### Bugfix 🐛\n\n- [#83](https://github.com/Schniz/fnm/pull/83) fix: remove unmatched quote written in the fish config file ([@thomasmarcel](https://github.com/thomasmarcel))\n\n#### Internal 🛠\n\n- [#84](https://github.com/Schniz/fnm/pull/84) Strip binaries to make them smaller ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Thomas Alcala Schneider ([@thomasmarcel](https://github.com/thomasmarcel))\n\n## v1.7.2 (2019-03-07)\n\n#### Bugfix 🐛\n\n- [#79](https://github.com/Schniz/fnm/pull/79) Guard from more non-existent directories errors ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.7.1 (2019-03-05)\n\n#### Bugfix 🐛\n\n- [#77](https://github.com/Schniz/fnm/pull/77) Fix \"command not found: elsif\" error ([@jletey](https://github.com/jletey))\n\n#### Internal 🛠\n\n- [#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))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- John Letey ([@jletey](https://github.com/jletey))\n\n## v1.7.0 (2019-03-04)\n\n#### New Feature 🎉\n\n- [#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))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.6.2 (2019-03-04)\n\n#### Bugfix 🐛\n\n- [#72](https://github.com/Schniz/fnm/pull/72) Fix alias paths ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#70](https://github.com/Schniz/fnm/pull/70) Fix installation script parameters docs ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.6.1 (2019-02-26)\n\n#### Bugfix 🐛\n\n- [#69](https://github.com/Schniz/fnm/pull/69) Fix version inference by throwing on http 404 again ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.6.0 (2019-02-25)\n\n#### New Feature 🎉\n\n- [#57](https://github.com/Schniz/fnm/pull/57) Switch to cohttp(lwt) instead of curl ([@tatchi](https://github.com/tatchi))\n\n#### Bugfix 🐛\n\n- [#64](https://github.com/Schniz/fnm/pull/64) Throw on errors in installation script ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#67](https://github.com/Schniz/fnm/pull/67) Use `perl-utils` instead of custom written `shasum` ([@Schniz](https://github.com/Schniz))\n- [#66](https://github.com/Schniz/fnm/pull/66) Use newer esy ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Corentin Leruth ([@tatchi](https://github.com/tatchi))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.5.1 (2019-02-22)\n\n#### Bugfix 🐛\n\n- [#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))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.5.0 (2019-02-21)\n\n#### New Feature 🎉\n\n- [#60](https://github.com/Schniz/fnm/pull/60) Disable colors for non-tty devices ([@Schniz](https://github.com/Schniz))\n- [#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))\n- [#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))\n\n#### Bugfix 🐛\n\n- [#58](https://github.com/Schniz/fnm/pull/58) Adding check for OSX during writing for bash shell ([@maxknee](https://github.com/maxknee))\n- [#56](https://github.com/Schniz/fnm/pull/56) Correct status code on `install` failures ([@ranyitz](https://github.com/ranyitz))\n\n#### Internal 🛠\n\n- [#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))\n\n#### Documentation 📝\n\n- [#49](https://github.com/Schniz/fnm/pull/49) Add a `--fnm-dir` option to `fnm env` ([@Schniz](https://github.com/Schniz))\n- [#50](https://github.com/Schniz/fnm/pull/50) Added CHANGELOG ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 4\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- Jordan Davidson ([@from-nibly](https://github.com/from-nibly))\n- Max Knee ([@maxknee](https://github.com/maxknee))\n- Ran Yitzhaki ([@ranyitz](https://github.com/ranyitz))\n\n## v1.4.0 (2019-02-18)\n\n#### New Feature 🎉\n\n- [#45](https://github.com/Schniz/fnm/pull/45) Use exit code 1 on errors on `fnm use` ([@Schniz](https://github.com/Schniz))\n- [#42](https://github.com/Schniz/fnm/pull/42) Add support for .node-version files ([@Dean177](https://github.com/Dean177))\n\n#### Documentation 📝\n\n- [#44](https://github.com/Schniz/fnm/pull/44) Quick fix for the dev environment setup ([@AdamGS](https://github.com/AdamGS))\n\n#### Committers: 3\n\n- Adam Gutglick ([@AdamGS](https://github.com/AdamGS))\n- Dean Merchant ([@Dean177](https://github.com/Dean177))\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.3.0 (2019-02-14)\n\n#### New Feature 🎉\n\n- [#36](https://github.com/Schniz/fnm/pull/36) Support Node.js mirrors ([@Schniz](https://github.com/Schniz))\n- [#30](https://github.com/Schniz/fnm/pull/30) Aliases and multishell support ([@Schniz](https://github.com/Schniz))\n- [#37](https://github.com/Schniz/fnm/pull/37) Don't throw on existing installation ([@Schniz](https://github.com/Schniz))\n- [#27](https://github.com/Schniz/fnm/pull/27) skip installation if the version is already installed ([@kentac55](https://github.com/kentac55))\n\n#### Documentation 📝\n\n- [#22](https://github.com/Schniz/fnm/pull/22) Add a LICENSE file ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 2\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n- [@kentac55](https://github.com/kentac55)\n\n## v1.2.1 (2019-02-11)\n\n#### Bugfix 🐛\n\n- [#25](https://github.com/Schniz/fnm/pull/25) CI (fnm-linux => fnm) ([@Schniz](https://github.com/Schniz))\n\n#### Internal 🛠\n\n- [#21](https://github.com/Schniz/fnm/pull/21) Add feature test for Fish shell ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#23](https://github.com/Schniz/fnm/pull/23) Add installation script ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.2.0 (2019-01-30)\n\n#### New Feature 🎉\n\n- [#17](https://github.com/Schniz/fnm/pull/17) Use xz files instead of gz ([@Schniz](https://github.com/Schniz))\n\n#### Bugfix 🐛\n\n- [#16](https://github.com/Schniz/fnm/pull/16) Make `fnm --version` show the correct version ([@Schniz](https://github.com/Schniz))\n- [#15](https://github.com/Schniz/fnm/pull/15) Don't throw in nonexistent directory on `fnm ls` ([@Schniz](https://github.com/Schniz))\n\n#### Documentation 📝\n\n- [#13](https://github.com/Schniz/fnm/pull/13) Added short docs to the README ([@Schniz](https://github.com/Schniz))\n\n#### Committers: 1\n\n- Gal Schlezinger ([@Schniz](https://github.com/Schniz))\n\n## v1.1.0 (2019-01-27)\n\n#### New Feature 🎉\n\n- [#10](https://github.com/Schniz/fnm/pull/10) Add fish shell setup to `env` command and README ([@elliottsj](https://github.com/elliottsj))\n\n#### Committers: 1\n\n- Spencer Elliott ([@elliottsj](https://github.com/elliottsj))\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"fnm\"\nversion = \"1.39.0\"\nauthors = [\"Gal Schlezinger <gal@spitfire.co.il>\"]\nedition = \"2021\"\nbuild = \"build.rs\"\nlicense = \"GPL-3.0\"\nrepository = \"https://github.com/Schniz/fnm\"\ndescription = \"Fast and simple Node.js version manager\"\n\n[dependencies]\nserde = { version = \"1.0.203\", features = [\"derive\"] }\nclap = { version = \"4.5.4\", features = [\"derive\", \"env\"] }\nserde_json = \"1.0.117\"\nchrono = { version = \"0.4.38\", features = [\"serde\", \"now\"], default-features = false }\ntar = \"0.4.40\"\nxz2 = \"0.1.7\"\nnode-semver = \"2.1.0\"\netcetera = \"0.8.0\"\ncolored = \"2.1.0\"\nzip = \"2.1.0\"\ntempfile = \"3.10.1\"\nindoc = \"2.0.5\"\nlog = \"0.4.21\"\nenv_logger = \"0.11.3\"\nencoding_rs_io = \"0.1.7\"\nreqwest = { version = \"0.12.4\", features = [\"blocking\", \"json\", \"rustls-tls\", \"rustls-tls-native-roots\", \"brotli\"], default-features = false }\nurl = \"2.5.0\"\nsysinfo = \"0.30.12\"\nthiserror = \"1.0.61\"\nclap_complete = \"4.5.2\"\nanyhow = \"1.0.86\"\nindicatif = { version = \"0.17.8\", features = [\"improved_unicode\"] }\nflate2 = \"1.0.30\"\nmiette = { version = \"7.2.0\", features = [\"fancy\"] }\n\n[dev-dependencies]\npretty_assertions = \"1.4.0\"\nduct = \"0.13.7\"\ntest-log = \"0.2.16\"\nhttp = \"1.1.0\"\n\n[build-dependencies]\nembed-resource = \"2.4.2\"\n\n[target.'cfg(windows)'.dependencies]\ncsv = \"1.3.0\"\njunction = \"1.1.0\"\n\n[features]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\">\n  Fast Node Manager (<code>fnm</code>)\n  <img alt=\"Amount of downloads\" src=\"https://img.shields.io/github/downloads/Schniz/fnm/total.svg?style=flat\" />\n  <a href=\"https://github.com/Schniz/fnm/actions\"><img src=\"https://img.shields.io/github/actions/workflow/status/Schniz/fnm/rust.yml?branch=master&label=workflow\" alt=\"GitHub Actions workflow status\" /></a>\n</h1>\n\n> 🚀 Fast and simple Node.js version manager, built in Rust\n\n<div align=\"center\">\n  <img src=\"./docs/fnm.svg\" alt=\"Blazing fast!\">\n</div>\n\n## Features\n\n🌎 Cross-platform support (macOS, Windows, Linux)\n\n✨ Single file, easy installation, instant startup\n\n🚀 Built with speed in mind\n\n📂 Works with `.node-version` and `.nvmrc` files\n\n## Installation\n\n### Using a script (macOS/Linux)\n\nFor `bash`, `zsh` and `fish` shells, there's an [automatic installation script](./.ci/install.sh).\n\nFirst ensure that `curl` and `unzip` are already installed on your operating system. Then execute:\n\n```sh\ncurl -fsSL https://fnm.vercel.app/install | bash\n```\n\n#### Upgrade\n\nOn macOS, it is as simple as `brew upgrade fnm`.\n\nOn 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:\n\n```sh\ncurl -fsSL https://fnm.vercel.app/install | bash -s -- --skip-shell\n```\n\n#### Parameters\n\n`--install-dir`\n\nSet 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).\n\n> **Note:** On macOS, this option is only meaningful when using `--force-install` since Homebrew is the default installation method.\n\n`--skip-shell`\n\nSkip 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`\n\n`--force-install`\n\nmacOS installations using the installation script are deprecated in favor of the Homebrew formula, but this forces the script to install using it anyway.\n\nExample:\n\n```sh\ncurl -fsSL https://fnm.vercel.app/install | bash -s -- --install-dir \"./.fnm\" --skip-shell\n```\n\n### Manually\n\n#### Using Homebrew (macOS/Linux)\n\n```sh\nbrew install fnm\n```\n\nThen, [set up your shell for fnm](#shell-setup)\n\n#### Using Winget (Windows)\n\n```sh\nwinget install Schniz.fnm\n```\n\n#### Using Scoop (Windows)\n\n```sh\nscoop install fnm\n```\n\nThen, [set up your shell for fnm](#shell-setup)\n\n#### Using Chocolatey (Windows)\n\n```sh\nchoco install fnm\n```\n\nThen, [set up your shell for fnm](#shell-setup)\n\n#### Using Cargo (Linux/macOS/Windows)\n\n```sh\ncargo install fnm\n```\n\nThen, [set up your shell for fnm](#shell-setup)\n\n#### Using a release binary (Linux/macOS/Windows)\n\n- Download the [latest release binary](https://github.com/Schniz/fnm/releases) for your system\n- Make it available globally on `PATH` environment variable\n- [Set up your shell for fnm](#shell-setup)\n\n### Removing\n\nTo 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).\n\n## Completions\n\nfnm ships its completions with the binary:\n\n```sh\nfnm completions --shell <SHELL>\n```\n\nWhere `<SHELL>` can be one of the supported shells:\n\n- `bash`\n- `zsh`\n- `fish`\n- `powershell`\n\nPlease follow your shell instructions to install them.\n\n### Shell Setup\n\nEnvironment variables need to be setup before you can start using fnm.\nThis is done by evaluating the output of `fnm env`.\n\n> [!TIP]\n> 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.\n\n> [!NOTE]\n> Check out the [Configuration](./docs/configuration.md) section to enable highly\n> recommended features, like automatic version switching.\n\nAdding a `.node-version` to your project is as simple as:\n\n```bash\n$ node --version\nv14.18.3\n$ node --version > .node-version\n```\n\nCheck out the following guides for the shell you use:\n\n#### Bash\n\nAdd the following to your `.bashrc` profile:\n\n```bash\neval \"$(fnm env --use-on-cd --shell bash)\"\n```\n\n#### Zsh\n\nAdd the following to your `.zshrc` profile:\n\n```zsh\neval \"$(fnm env --use-on-cd --shell zsh)\"\n```\n\n#### Fish shell\n\nCreate `~/.config/fish/conf.d/fnm.fish` and add this line to it:\n\n```fish\nfnm env --use-on-cd --shell fish | source\n```\n\n#### PowerShell\n\nAdd the following to the end of your profile file:\n\n```powershell\nfnm env --use-on-cd --shell powershell | Out-String | Invoke-Expression\n```\n\n- For macOS/Linux, the profile is located at `~/.config/powershell/Microsoft.PowerShell_profile.ps1`\n- For Windows location is either:\n  - `%userprofile%\\Documents\\WindowsPowerShell\\Microsoft.PowerShell_profile.ps1` Powershell 5\n  - `%userprofile%\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1` Powershell 6+\n- To create the profile file you can run this in PowerShell:\n  ```powershell\n  if (-not (Test-Path $profile)) { New-Item $profile -Force }\n  ```\n- To edit your profile run this in PowerShell:\n  ```powershell\n  Invoke-Item $profile\n  ```\n\n#### Windows Command Prompt aka Batch aka WinCMD\n\nfnm 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:\n\n```batch\n@echo off\n:: for /F will launch a new instance of cmd so we create a guard to prevent an infnite loop\nif not defined FNM_AUTORUN_GUARD (\n    set \"FNM_AUTORUN_GUARD=AutorunGuard\"\n    FOR /f \"tokens=*\" %%z IN ('fnm env --use-on-cd') DO CALL %%z\n)\n```\n\n#### Usage with Cmder\n\nUsage 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.\nThen you can do something like this:\n\n- Make a .cmd file to invoke it\n\n```batch\n:: %CMDER_ROOT%\\bin\\fnm_init.cmd\n@echo off\nFOR /f \"tokens=*\" %%z IN ('fnm env --use-on-cd') DO CALL %%z\n```\n\n- Add it to the startup script\n\n```batch\n:: %CMDER_ROOT%\\config\\user_profile.cmd\ncall \"%CMDER_ROOT%\\bin\\fnm_init.cmd\"\n```\n\nYou can replace `%CMDER_ROOT%` with any other convenient path too.\n\n## [Configuration](./docs/configuration.md)\n\n[See the available configuration options for an extended configuration documentation](./docs/configuration.md)\n\n## [Usage](./docs/commands.md)\n\n[See the available commands for an extended usage documentation](./docs/commands.md)\n\n## Contributing\n\nPRs welcome :tada:\n\n### Developing:\n\n```sh\n# Install Rust\ngit clone https://github.com/Schniz/fnm.git\ncd fnm/\ncargo build\n```\n\n### Running Binary:\n\n```sh\ncargo run -- --help # Will behave like `fnm --help`\n```\n\n### Running Tests:\n\n```sh\ncargo test\n```\n"
  },
  {
    "path": "benchmarks/basic/fnm",
    "content": "#!/bin/bash\n\neval \"$(fnm env --shell=bash)\"\nfnm install v10.11.0\nfnm use v10.11.0\nnode -v\n"
  },
  {
    "path": "benchmarks/basic/nvm",
    "content": "#!/bin/bash\n\nexport NVM_DIR=\"$HOME/.nvm\"\n\\. \"$NVM_DIR/nvm.sh\"  # This loads nvm\n\nnvm install v10.11.0\nnvm use v10.11.0\nnode -v\n"
  },
  {
    "path": "benchmarks/run",
    "content": "#!/bin/bash\n\nset -e\n\nexport FNM_DIR\n\nBASE_DIR=\"$(dirname \"$(realpath \"$0\")\")\"\ncd \"$BASE_DIR\" || exit 1\n\nFNM_DIR=\"$(mktemp -d)\"\nexport PATH=\"$BASE_DIR/../target/release:$PATH\"\n\nmkdir results 2>/dev/null || :\n\nif [ ! -f \"$BASE_DIR/../target/release/fnm\" ]; then\n  echo \"Can't access the release version of fnm.rs\"\n  exit 1\nfi\n\nif ! command -v hyperfine >/dev/null 2>&1; then\n  echo \"Can't access Hyperfine. Are you sure it is installed?\"\n  echo \"  if not, visit https://github.com/sharkdp/hyperfine\"\n  exit 1\nfi\n\n# Running it with warmup means we're going to have the versions\n# pre-installed. I think it is good because you open your shell more times\n# than you install Node versions.\nhyperfine \\\n  --warmup=2 \\\n  --min-runs=40 \\\n  --time-unit=millisecond \\\n  --export-json=\"./results/basic.json\" \\\n  --export-markdown=\"./results/basic.md\" \\\n  \"basic/nvm\" \\\n  \"basic/fnm\"\n"
  },
  {
    "path": "benchmarks/run.mjs",
    "content": "// @ts-check\n\nimport z from \"zod\"\nimport os from \"node:os\"\nimport path from \"node:path\"\nimport fetch from \"node-fetch\"\nimport { execa } from \"execa\"\nimport { binary, command, flag, option } from \"cmd-ts\"\nimport Url from \"cmd-ts/dist/cjs/batteries/url.js\"\nimport { run } from \"cmd-ts\"\nimport fs from \"node:fs/promises\"\nimport { dedent } from \"ts-dedent\"\n\nconst HyperfineResult = z.object({\n  results: z.array(\n    z.object({\n      command: z.string(),\n      mean: z.number(),\n      stddev: z.number(),\n      median: z.number(),\n      user: z.number(),\n      system: z.number(),\n      min: z.number(),\n      max: z.number(),\n      times: z.array(z.number()),\n      exit_codes: z.array(z.literal(0)),\n    })\n  ),\n})\n\nconst BenchyResult = z.object({\n  data: z.object({\n    embed: z.object({\n      small: z.string(),\n      big: z.string(),\n\n      currentValue: z.number(),\n      lastValue: z.number().optional(),\n      diff: z\n        .object({\n          value: z.number(),\n          arrowImage: z.string(),\n        })\n        .optional(),\n    }),\n  }),\n})\n\nconst { HttpUrl } = Url\n\nconst cmd = command({\n  name: \"run-benchmarks\",\n  args: {\n    serverUrl: option({\n      long: \"server-url\",\n      type: HttpUrl,\n      defaultValue: () => new URL(\"https://benchy.hagever.com\"),\n      defaultValueIsSerializable: true,\n    }),\n    githubToken: option({\n      long: \"github-token\",\n      env: \"GITHUB_TOKEN\",\n    }),\n    shouldStore: flag({\n      long: \"store\",\n    }),\n  },\n  async handler({ serverUrl, githubToken, shouldStore }) {\n    const repoName = \"fnm\"\n    const repoOwner = \"schniz\"\n\n    const hyperfineResult = await runHyperfine()\n\n    if (!hyperfineResult.success) {\n      console.error(\n        `Can't run benchmarks: wrong data:`,\n        hyperfineResult.error.issues\n      )\n      process.exitCode = 1\n      return\n    }\n\n    const { results } = hyperfineResult.data\n\n    const url = new URL(\"/api/metrics\", serverUrl)\n    const trackedKeys = [\"median\", \"max\", \"mean\", \"min\", \"stddev\"]\n\n    const metrics = results\n      .flatMap((result) => {\n        return trackedKeys.map((key) => {\n          return {\n            displayName: `${result.command}/${key}`,\n            value: result[key] * 1000, // everything is in seconds\n            units: \"ms\",\n          }\n        })\n      })\n      .concat([\n        {\n          displayName: `binary size`,\n          value: await getFilesize(),\n          units: \"kb\",\n        },\n      ])\n      .map((metric) => {\n        return {\n          ...metric,\n          key: `${os.platform()}/${os.arch()}/${metric.displayName}`,\n        }\n      })\n\n    const embeds$ = metrics.map(async ({ key, value, displayName, units }) => {\n      const response = await fetch(String(url), {\n        method: \"PUT\",\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n        body: JSON.stringify({\n          coloring: \"lower-is-better\",\n          repoOwner,\n          repoName,\n          githubToken,\n          key,\n          value,\n        }),\n      })\n\n      if (!response.ok) {\n        throw new Error(`Response is not okay: ${response.status}`)\n      }\n\n      const { data } = BenchyResult.parse(await response.json())\n      return {\n        displayName,\n        units,\n        ...data.embed,\n      }\n    })\n\n    const embeds = await Promise.all(embeds$)\n\n    const table = (() => {\n      const rows = embeds\n        .map((data) => {\n          return dedent`\n            <tr>\n              <td><code>${data.displayName}</code></td>\n              <td><code>${round(data.currentValue, 2)}${data.units}</code></td>\n              <td>${\n                typeof data.lastValue === \"undefined\"\n                  ? \"\"\n                  : `<code>${round(data.lastValue, 2)}${data.units}</code>`\n              }</td>\n              <td>${\n                !data.diff\n                  ? \"<code>0</code>\"\n                  : dedent`\n                  <picture title=${JSON.stringify(\n                    data.diff.value > 0 ? \"increase\" : \"decrease\"\n                  )}>\n                    <img width=\"16\" valign=\"middle\" src=\"${\n                      data.diff.arrowImage\n                    }\">\n                  </picture>\n                  <code>${data.diff.value > 0 ? \"+\" : \"\"}${round(\n                      data.diff.value,\n                      2\n                    )}${data.units}</code>\n                    `\n              }</td>\n              <td>\n                <details><summary><img valign=\"middle\" src=\"${\n                  data.small\n                }\" /></summary><br/><img src=\"${data.big}\" /></details>\n              </td>\n            </tr>\n          `\n        })\n        .join(\"\\n\")\n      return dedent`\n        <table>\n          <thead>\n            <tr>\n              <th align=\"left\">benchmark</th>\n              <th>current value</th>\n              <th>last value</th>\n              <th>diff</th>\n              <th>trend</th>\n            </tr>\n          </thead>\n          <tbody>\n            ${rows}\n          </tbody>\n        </table>\n      `\n    })()\n\n    console.log(table)\n\n    if (shouldStore) {\n      const response = await fetch(String(url), {\n        method: \"POST\",\n        headers: {\n          \"Content-Type\": \"application/json\",\n        },\n        body: JSON.stringify({\n          repoOwner,\n          repoName,\n          githubToken,\n          metrics,\n        }),\n      })\n\n      if (!response.ok) {\n        throw new Error(`Response is not okay: ${response.status}`)\n      }\n\n      console.error(await response.json())\n    }\n  },\n})\n\n/**\n * @param {number} number\n * @param {number} digits\n */\nfunction round(number, digits) {\n  const pow = Math.pow(10, digits)\n  return Math.round(number * pow) / pow\n}\n\n/**\n * Returns the size of the `fnm` binary in kilobytes\n *\n * @returns number\n */\nasync function getFilesize() {\n  const fnmBinary = await execa(\"which\", [\"fnm\"])\n  const stat = await fs.stat(fnmBinary.stdout.trim())\n  return Math.round(stat.size / 1024)\n}\n\nasync function runHyperfine() {\n  const file = path.join(os.tmpdir(), `bench-${Date.now()}.json`)\n  await execa(\n    `hyperfine`,\n    [\n      \"--min-runs=20\",\n      `--export-json=${file}`,\n      \"--warmup=2\",\n      ...[\n        \"--command-name=fnm_basic\",\n        new URL(\"./basic/fnm\", import.meta.url).pathname,\n      ],\n      // ...[\n      //   \"--command-name=nvm_basic\",\n      //   new URL(\"./basic/nvm\", import.meta.url).pathname,\n      // ],\n    ],\n    {\n      stdout: process.stderr,\n      stderr: process.stderr,\n      stdin: \"ignore\",\n    }\n  )\n\n  const json = JSON.parse(await fs.readFile(file, \"utf8\"))\n  const parsed = HyperfineResult.safeParse(json)\n  return parsed\n}\n\nrun(binary(cmd), process.argv)\n"
  },
  {
    "path": "build.rs",
    "content": "fn main() {\n    embed_resource::compile(\"fnm-manifest.rc\", embed_resource::NONE);\n}\n"
  },
  {
    "path": "docs/commands.md",
    "content": "# `fnm`\n\n```\nA fast and simple Node.js manager\n\nUsage: fnm [OPTIONS] <COMMAND>\n\nCommands:\n  list-remote  List all remote Node.js versions [aliases: ls-remote]\n  list         List all locally installed Node.js versions [aliases: ls]\n  install      Install a new Node.js version [aliases: i]\n  use          Change Node.js version\n  env          Print and set up required environment variables for fnm\n  completions  Print shell completions to stdout\n  alias        Alias a version to a common name\n  unalias      Remove an alias definition\n  default      Set a version as the default version or get the current default version\n  current      Print the current Node.js version\n  exec         Run a command within fnm context\n  uninstall    Uninstall a Node.js version [aliases: uni]\n  help         Print this message or the help of the given subcommand(s)\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n\n  -V, --version\n          Print version\n```\n\n# `fnm list-remote`\n\n```\nList all remote Node.js versions\n\nUsage: fnm list-remote [OPTIONS]\n\nOptions:\n      --filter <FILTER>\n          Filter versions by a user-defined version or a semver range\n\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --lts [<LTS>]\n          Show only LTS versions (optionally filter by LTS codename)\n\n      --sort <SORT>\n          Version sorting order\n\n          [default: asc]\n\n          Possible values:\n          - desc: Sort versions in descending order (latest to earliest)\n          - asc:  Sort versions in ascending order (earliest to latest)\n\n      --latest\n          Only show the latest matching version\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm list`\n\n```\nList all locally installed Node.js versions\n\nUsage: fnm list [OPTIONS]\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm install`\n\n```\nInstall a new Node.js version\n\nUsage: fnm install [OPTIONS] [VERSION]\n\nArguments:\n  [VERSION]\n          A version string. Can be a partial semver or a LTS version name by the format lts/NAME\n\nOptions:\n      --lts\n          Install latest LTS\n\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --latest\n          Install latest version\n\n      --progress <PROGRESS>\n          Show an interactive progress bar for the download status\n\n          [default: auto]\n          [possible values: auto, never, always]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --use\n          Use the installed version immediately after installation\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm use`\n\n```\nChange Node.js version\n\nUsage: fnm use [OPTIONS] [VERSION]\n\nArguments:\n  [VERSION]\n\n\nOptions:\n      --install-if-missing\n          Install the version if it isn't installed yet\n\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --silent-if-unchanged\n          Don't output a message identifying the version being used if it will not change due to execution of this command\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm env`\n\n```\nPrint and set up required environment variables for fnm\n\nThis command generates a series of shell commands that should be evaluated by your shell to create a fnm-ready environment.\n\nEach 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`\n\nUsage: fnm env [OPTIONS]\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --shell <SHELL>\n          The shell syntax to use. Infers when missing\n\n          [possible values: bash, zsh, fish, powershell]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --json\n          Print JSON instead of shell commands\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --use-on-cd\n          Print the script to change Node versions every directory change\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm completions`\n\n```\nPrint shell completions to stdout\n\nUsage: fnm completions [OPTIONS]\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --shell <SHELL>\n          The shell syntax to use. Infers when missing\n\n          [possible values: bash, zsh, fish, powershell]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm alias`\n\n```\nAlias a version to a common name\n\nUsage: fnm alias [OPTIONS] <TO_VERSION> <NAME>\n\nArguments:\n  <TO_VERSION>\n\n\n  <NAME>\n\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm unalias`\n\n```\nRemove an alias definition\n\nUsage: fnm unalias [OPTIONS] <REQUESTED_ALIAS>\n\nArguments:\n  <REQUESTED_ALIAS>\n\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm default`\n\n```\nSet a version as the default version or get the current default version.\n\nThis is a shorthand for `fnm alias VERSION default`\n\nUsage: fnm default [OPTIONS] [VERSION]\n\nArguments:\n  [VERSION]\n\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm current`\n\n```\nPrint the current Node.js version\n\nUsage: fnm current [OPTIONS]\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm exec`\n\n```\nRun a command within fnm context\n\nExample:\n--------\nfnm exec --using=v12.0.0 node --version\n=> v12.0.0\n\nUsage: fnm exec [OPTIONS] [ARGUMENTS]...\n\nArguments:\n  [ARGUMENTS]...\n          The command to run\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --using <VERSION>\n          Either an explicit version, or a filename with the version written in it\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm uninstall`\n\n```\nUninstall a Node.js version\n\n> 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.\n\nUsage: fnm uninstall [OPTIONS] [VERSION]\n\nArguments:\n  [VERSION]\n\n\nOptions:\n      --node-dist-mirror <NODE_DIST_MIRROR>\n          <https://nodejs.org/dist/> mirror\n\n          [env: FNM_NODE_DIST_MIRROR]\n          [default: https://nodejs.org/dist]\n\n      --fnm-dir <BASE_DIR>\n          The root directory of fnm installations\n\n          [env: FNM_DIR]\n\n      --log-level <LOG_LEVEL>\n          The log level of fnm commands\n\n          [env: FNM_LOGLEVEL]\n          [default: info]\n          [possible values: quiet, error, info]\n\n      --arch <ARCH>\n          Override the architecture of the installed Node binary. Defaults to arch of fnm binary\n\n          [env: FNM_ARCH]\n\n      --version-file-strategy <VERSION_FILE_STRATEGY>\n          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\n\n          [env: FNM_VERSION_FILE_STRATEGY]\n          [default: local]\n\n          Possible values:\n          - local:     Use the local version of Node defined within the current directory\n          - recursive: Use the version of Node defined within the current directory and all parent directories\n\n      --corepack-enabled\n          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 <https://nodejs.org/api/corepack.html>\n\n          [env: FNM_COREPACK_ENABLED]\n\n      --resolve-engines [<RESOLVE_ENGINES>]\n          Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n          This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n\n          Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n          Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n                  In the future, disabling it might be a no-op, so it's worth knowing any reason to\n                  do that.\n\n          [env: FNM_RESOLVE_ENGINES]\n          [possible values: true, false]\n\n  -h, --help\n          Print help (see a summary with '-h')\n```\n\n# `fnm help`\n\n```\n\n```\n"
  },
  {
    "path": "docs/configuration.md",
    "content": "# Configuration\n\nfnm 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.\n\nAll 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)\"`\n\nHere’s a list of these features and capabilities:\n\n### `--use-on-cd`\n\n**✅ Highly recommended**\n\n`--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).\n\nThis allows you do avoid thinking about `fnm use`, and only `cd <DIR>` to make it work.\n\n### `--version-file-strategy=recursive`\n\n**✅ Highly recommended**\n\nMakes `fnm use` and `fnm install` take parent directories into account when looking for a version file (\"dotfile\")--when no argument was given.\n\nSo, let's say we have the following directory structure:\n\n```\nrepo/\n├── package.json\n├── .node-version <- with content: `20.0.0`\n└── packages/\n  └── my-package/ <- I am here\n    └── package.json\n```\n\nAnd I'm running the following command:\n\n```sh-session\nrepo/packages/my-package$ fnm use\n```\n\nThen fnm will switch to Node.js v20.0.0.\n\nWithout the explicit flag, the value is set to `local`, which will not traverse the directory tree and therefore will print:\n\n```sh-session\nrepo/packages/my-package$ fnm use\nerror: Can't find version in dotfiles. Please provide a version manually to the command.\n```\n\n### `--corepack-enabled`\n\n**🧪 Experimental**\n\nRuns [`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.\n\n### `--resolve-engines`\n\n**🧪 Experimental**\n\nTreats `package.json#engines#node` as a valid Node.js version file (\"dotfile\"). So, if you have a package.json with the following content:\n\n```json\n{\n  \"engines\": {\n    \"node\": \">=20 <21\"\n  }\n}\n```\n\nThen:\n\n- `fnm install` will install the latest satisfying Node.js 20.x version available in the Node.js dist server\n- `fnm use` will use the latest satisfying Node.js 20.x version available on your system, or prompt to install if no version matched.\n"
  },
  {
    "path": "docs/nightly.md",
    "content": "# Working with Node nightly builds\n\nfnm doesn't give you any shorthands to install nightly builds, but you can\ndo that by manually passing a \"dist mirror\" with the `--node-dist-mirror` flag. \n\n## Example usage\n\nHere's an example of installing Node 23.\n\nTo get a list of available versions run this:\n\n    fnm --node-dist-mirror https://nodejs.org/download/nightly/ ls-remote\n\nTo use and install nightly version run this:\n\n    fnm --node-dist-mirror https://nodejs.org/download/nightly/ use 23\n    # or\n    fnm --node-dist-mirror https://nodejs.org/download/nightly/ use v23.0.0-nightly202407253de7a4c374\n\nOnce you installed it you would be able to see that version in you list:\n\n    fnm ls\n\nAnd use it without providing `--node-dist-mirror` flag:\n\n    fnm use 23\n"
  },
  {
    "path": "e2e/__snapshots__/aliases.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash aliasing versions: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 6.11.3\nfnm install 8.11.3\nfnm alias 8.11 oldie\nfnm alias 6 older\nfnm default older\n((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)\n((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)\nfnm use older\nif [ \"$(node --version)\" != \"v6.11.3\" ]; then\n  echo \"Expected node version to be v6.11.3. Got $(node --version)\"\n  exit 1\nfi\nfnm use oldie\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\nfnm use default\nif [ \"$(node --version)\" != \"v6.11.3\" ]; then\n  echo \"Expected node version to be v6.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash allows to install an lts if version missing: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm use --install-if-missing\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\"\n`;\n\nexports[`Bash can alias the system node: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm alias system my_system\n(fnm ls) | grep my_system || (echo \"Expected output to contain my_system\" && exit 1)\nfnm alias system default\nfnm alias my_system my_system2\n(fnm ls) | grep my_system2 || (echo \"Expected output to contain my_system2\" && exit 1)\n(fnm use my_system) | grep 'Bypassing fnm' || (echo \"Expected output to contain 'Bypassing fnm'\" && exit 1)\nfnm unalias my_system\n(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)\"\n`;\n\nexports[`Bash errors when alias is not found: Bash 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\n(fnm use 2>&1) | grep 'Requested version lts-latest is not' || (echo \"Expected output to contain 'Requested version lts-latest is not'\" && exit 1)\"\n`;\n\nexports[`Bash installs aliases when corepack is enabled: Bash 1`] = `\n\"set -e\neval \"$(fnm env --corepack-enabled)\"\nfnm use --install-if-missing\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\"\n`;\n\nexports[`Bash unalias a version: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 11.10.0\nfnm install 8.11.3\nfnm alias 8.11.3 version8\n(fnm ls) | grep version8 || (echo \"Expected output to contain version8\" && exit 1)\nfnm unalias version8\n(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)\"\n`;\n\nexports[`Bash unalias errors if alias not found: Bash 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\n(fnm unalias lts 2>&1) | grep 'Requested alias lts not found' || (echo \"Expected output to contain 'Requested alias lts not found'\" && exit 1)\"\n`;\n\nexports[`Fish aliasing versions: Fish 1`] = `\n\"fnm env | source\nfnm install 6.11.3\nfnm install 8.11.3\nfnm alias 8.11 oldie\nfnm alias 6 older\nfnm default older\nbegin; 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\nbegin; 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\nfnm use older\nset ____test____ (node --version)\nif test \"$____test____\" != \"v6.11.3\"\n  echo \"Expected node version to be v6.11.3. Got $____test____\"\n  exit 1\nend\nfnm use oldie\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\nfnm use default\nset ____test____ (node --version)\nif test \"$____test____\" != \"v6.11.3\"\n  echo \"Expected node version to be v6.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish allows to install an lts if version missing: Fish 1`] = `\n\"fnm env | source\nfnm use --install-if-missing\nbegin; fnm ls; end | grep lts-latest; or echo \"Expected output to contain lts-latest\" && exit 1\"\n`;\n\nexports[`Fish can alias the system node: Fish 1`] = `\n\"fnm env | source\nfnm alias system my_system\nbegin; fnm ls; end | grep my_system; or echo \"Expected output to contain my_system\" && exit 1\nfnm alias system default\nfnm alias my_system my_system2\nbegin; fnm ls; end | grep my_system2; or echo \"Expected output to contain my_system2\" && exit 1\nbegin; fnm use my_system; end | grep 'Bypassing fnm'; or echo \"Expected output to contain 'Bypassing fnm'\" && exit 1\nfnm unalias my_system\nbegin; 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\"\n`;\n\nexports[`Fish errors when alias is not found: Fish 1`] = `\n\"fnm env --log-level=error | source\nbegin; 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\"\n`;\n\nexports[`Fish installs aliases when corepack is enabled: Fish 1`] = `\n\"fnm env --corepack-enabled | source\nfnm use --install-if-missing\nbegin; fnm ls; end | grep lts-latest; or echo \"Expected output to contain lts-latest\" && exit 1\"\n`;\n\nexports[`Fish unalias a version: Fish 1`] = `\n\"fnm env | source\nfnm install 11.10.0\nfnm install 8.11.3\nfnm alias 8.11.3 version8\nbegin; fnm ls; end | grep version8; or echo \"Expected output to contain version8\" && exit 1\nfnm unalias version8\nbegin; 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\"\n`;\n\nexports[`Fish unalias errors if alias not found: Fish 1`] = `\n\"fnm env --log-level=error | source\nbegin; 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\"\n`;\n\nexports[`PowerShell aliasing versions: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install 6.11.3\nfnm install 8.11.3\nfnm alias 8.11 oldie\nfnm alias 6 older\nfnm default older\n$($__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__ })\n$($__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__ })\nfnm use older\nif ( \"$(node --version)\" -ne \"v6.11.3\" ) { echo \"Expected node version to be v6.11.3. Got $(node --version)\"; exit 1 }\nfnm use oldie\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\nfnm use default\nif ( \"$(node --version)\" -ne \"v6.11.3\" ) { echo \"Expected node version to be v6.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell allows to install an lts if version missing: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm use --install-if-missing\n$($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`PowerShell can alias the system node: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm alias system my_system\n$($__out__ = $(fnm ls | Select-String my_system); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\nfnm alias system default\nfnm alias my_system my_system2\n$($__out__ = $(fnm ls | Select-String my_system2); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\n$($__out__ = $(fnm use my_system | Select-String 'Bypassing fnm'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\nfnm unalias my_system\n$($__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__ })\"\n`;\n\nexports[`PowerShell errors when alias is not found: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --log-level=error | Out-String | Invoke-Expression\n$($__out__ = $(fnm use 2>&1 | Select-String 'Requested version lts-latest is not'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`PowerShell installs aliases when corepack is enabled: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --corepack-enabled | Out-String | Invoke-Expression\nfnm use --install-if-missing\n$($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`PowerShell unalias a version: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install 11.10.0\nfnm install 8.11.3\nfnm alias 8.11.3 version8\n$($__out__ = $(fnm ls | Select-String version8); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\nfnm unalias version8\n$($__out__ = $(fnm use version8 2>&1 | Select-String 'Requested version version8 is not currently installed'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`PowerShell unalias errors if alias not found: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --log-level=error | Out-String | Invoke-Expression\n$($__out__ = $(fnm unalias lts 2>&1 | Select-String 'Requested alias lts not found'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`Zsh aliasing versions: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 6.11.3\nfnm install 8.11.3\nfnm alias 8.11 oldie\nfnm alias 6 older\nfnm default older\n((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)\n((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)\nfnm use older\nif [ \"$(node --version)\" != \"v6.11.3\" ]; then\n  echo \"Expected node version to be v6.11.3. Got $(node --version)\"\n  exit 1\nfi\nfnm use oldie\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\nfnm use default\nif [ \"$(node --version)\" != \"v6.11.3\" ]; then\n  echo \"Expected node version to be v6.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh allows to install an lts if version missing: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm use --install-if-missing\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\"\n`;\n\nexports[`Zsh can alias the system node: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm alias system my_system\n(fnm ls) | grep my_system || (echo \"Expected output to contain my_system\" && exit 1)\nfnm alias system default\nfnm alias my_system my_system2\n(fnm ls) | grep my_system2 || (echo \"Expected output to contain my_system2\" && exit 1)\n(fnm use my_system) | grep 'Bypassing fnm' || (echo \"Expected output to contain 'Bypassing fnm'\" && exit 1)\nfnm unalias my_system\n(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)\"\n`;\n\nexports[`Zsh errors when alias is not found: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\n(fnm use 2>&1) | grep 'Requested version lts-latest is not' || (echo \"Expected output to contain 'Requested version lts-latest is not'\" && exit 1)\"\n`;\n\nexports[`Zsh installs aliases when corepack is enabled: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --corepack-enabled)\"\nfnm use --install-if-missing\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\"\n`;\n\nexports[`Zsh unalias a version: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 11.10.0\nfnm install 8.11.3\nfnm alias 8.11.3 version8\n(fnm ls) | grep version8 || (echo \"Expected output to contain version8\" && exit 1)\nfnm unalias version8\n(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)\"\n`;\n\nexports[`Zsh unalias errors if alias not found: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\n(fnm unalias lts 2>&1) | grep 'Requested alias lts not found' || (echo \"Expected output to contain 'Requested alias lts not found'\" && exit 1)\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/basic.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash .node-version: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash .nvmrc: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash \\`fnm ls\\` with nothing installed: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nif [ \"$(fnm ls)\" != \"* system\" ]; then\n  echo \"Expected fnm ls to be * system. Got $(fnm ls)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash basic usage: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\nfnm use v8.11.3\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash package.json engines.node with semver range: Bash 1`] = `\n\"set -e\neval \"$(fnm env --resolve-engines)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v6.17.0\" ]; then\n  echo \"Expected node version to be v6.17.0. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash package.json engines.node: Bash 1`] = `\n\"set -e\neval \"$(fnm env --resolve-engines)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash resolves partial semver: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 6\nfnm use 6\nif [ \"$(node --version)\" != \"v6.17.1\" ]; then\n  echo \"Expected node version to be v6.17.1. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash when .node-version and .nvmrc are in sync, it throws no error: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v11.10.0\" ]; then\n  echo \"Expected node version to be v11.10.0. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish .node-version: Fish 1`] = `\n\"fnm env | source\nfnm install\nfnm use\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish .nvmrc: Fish 1`] = `\n\"fnm env | source\nfnm install\nfnm use\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish \\`fnm ls\\` with nothing installed: Fish 1`] = `\n\"fnm env | source\nset ____test____ (fnm ls)\nif test \"$____test____\" != \"* system\"\n  echo \"Expected fnm ls to be * system. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish basic usage: Fish 1`] = `\n\"fnm env | source\nfnm install v8.11.3\nfnm use v8.11.3\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish package.json engines.node with semver range: Fish 1`] = `\n\"fnm env --resolve-engines | source\nfnm install\nfnm use\nset ____test____ (node --version)\nif test \"$____test____\" != \"v6.17.0\"\n  echo \"Expected node version to be v6.17.0. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish package.json engines.node: Fish 1`] = `\n\"fnm env --resolve-engines | source\nfnm install\nfnm use\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish resolves partial semver: Fish 1`] = `\n\"fnm env | source\nfnm install 6\nfnm use 6\nset ____test____ (node --version)\nif test \"$____test____\" != \"v6.17.1\"\n  echo \"Expected node version to be v6.17.1. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish when .node-version and .nvmrc are in sync, it throws no error: Fish 1`] = `\n\"fnm env | source\nfnm install\nfnm use\nset ____test____ (node --version)\nif test \"$____test____\" != \"v11.10.0\"\n  echo \"Expected node version to be v11.10.0. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell .node-version: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install\nfnm use\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell .nvmrc: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install\nfnm use\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell \\`fnm ls\\` with nothing installed: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nif ( \"$(fnm ls)\" -ne \"* system\" ) { echo \"Expected fnm ls to be * system. Got $(fnm ls)\"; exit 1 }\"\n`;\n\nexports[`PowerShell basic usage: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install v8.11.3\nfnm use v8.11.3\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell package.json engines.node with semver range: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --resolve-engines | Out-String | Invoke-Expression\nfnm install\nfnm use\nif ( \"$(node --version)\" -ne \"v6.17.0\" ) { echo \"Expected node version to be v6.17.0. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell package.json engines.node: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --resolve-engines | Out-String | Invoke-Expression\nfnm install\nfnm use\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell resolves partial semver: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install 6\nfnm use 6\nif ( \"$(node --version)\" -ne \"v6.17.1\" ) { echo \"Expected node version to be v6.17.1. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`PowerShell when .node-version and .nvmrc are in sync, it throws no error: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install\nfnm use\nif ( \"$(node --version)\" -ne \"v11.10.0\" ) { echo \"Expected node version to be v11.10.0. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`Zsh .node-version: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh .nvmrc: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh \\`fnm ls\\` with nothing installed: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nif [ \"$(fnm ls)\" != \"* system\" ]; then\n  echo \"Expected fnm ls to be * system. Got $(fnm ls)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh basic usage: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\nfnm use v8.11.3\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh package.json engines.node with semver range: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --resolve-engines)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v6.17.0\" ]; then\n  echo \"Expected node version to be v6.17.0. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh package.json engines.node: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --resolve-engines)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh resolves partial semver: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install 6\nfnm use 6\nif [ \"$(node --version)\" != \"v6.17.1\" ]; then\n  echo \"Expected node version to be v6.17.1. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh when .node-version and .nvmrc are in sync, it throws no error: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\nif [ \"$(node --version)\" != \"v11.10.0\" ]; then\n  echo \"Expected node version to be v11.10.0. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/corepack.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash installs corepack: Bash 1`] = `\n\"set -e\neval \"$(fnm env --corepack-enabled)\"\nfnm install 18\nfnm exec --using=18 node test-pnpm-corepack.js\"\n`;\n\nexports[`Fish installs corepack: Fish 1`] = `\n\"fnm env --corepack-enabled | source\nfnm install 18\nfnm exec --using=18 node test-pnpm-corepack.js\"\n`;\n\nexports[`PowerShell installs corepack: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --corepack-enabled | Out-String | Invoke-Expression\nfnm install 18\nfnm exec --using=18 node test-pnpm-corepack.js\"\n`;\n\nexports[`Zsh installs corepack: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --corepack-enabled)\"\nfnm install 18\nfnm exec --using=18 node test-pnpm-corepack.js\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/current.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash current returns the current Node.js version set in fnm: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nif [ \"$(fnm current)\" != \"none\" ]; then\n  echo \"Expected currently activated version to be none. Got $(fnm current)\"\n  exit 1\nfi\nfnm install v8.11.3\nfnm install v10.10.0\nfnm use v8.11.3\nif [ \"$(fnm current)\" != \"v8.11.3\" ]; then\n  echo \"Expected currently activated version to be v8.11.3. Got $(fnm current)\"\n  exit 1\nfi\nfnm use v10.10.0\nif [ \"$(fnm current)\" != \"v10.10.0\" ]; then\n  echo \"Expected currently activated version to be v10.10.0. Got $(fnm current)\"\n  exit 1\nfi\nfnm use system\nif [ \"$(fnm current)\" != \"system\" ]; then\n  echo \"Expected currently activated version to be system. Got $(fnm current)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish current returns the current Node.js version set in fnm: Fish 1`] = `\n\"fnm env | source\nset ____test____ (fnm current)\nif test \"$____test____\" != \"none\"\n  echo \"Expected currently activated version to be none. Got $____test____\"\n  exit 1\nend\nfnm install v8.11.3\nfnm install v10.10.0\nfnm use v8.11.3\nset ____test____ (fnm current)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected currently activated version to be v8.11.3. Got $____test____\"\n  exit 1\nend\nfnm use v10.10.0\nset ____test____ (fnm current)\nif test \"$____test____\" != \"v10.10.0\"\n  echo \"Expected currently activated version to be v10.10.0. Got $____test____\"\n  exit 1\nend\nfnm use system\nset ____test____ (fnm current)\nif test \"$____test____\" != \"system\"\n  echo \"Expected currently activated version to be system. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell current returns the current Node.js version set in fnm: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nif ( \"$(fnm current)\" -ne \"none\" ) { echo \"Expected currently activated version to be none. Got $(fnm current)\"; exit 1 }\nfnm install v8.11.3\nfnm install v10.10.0\nfnm use v8.11.3\nif ( \"$(fnm current)\" -ne \"v8.11.3\" ) { echo \"Expected currently activated version to be v8.11.3. Got $(fnm current)\"; exit 1 }\nfnm use v10.10.0\nif ( \"$(fnm current)\" -ne \"v10.10.0\" ) { echo \"Expected currently activated version to be v10.10.0. Got $(fnm current)\"; exit 1 }\nfnm use system\nif ( \"$(fnm current)\" -ne \"system\" ) { echo \"Expected currently activated version to be system. Got $(fnm current)\"; exit 1 }\"\n`;\n\nexports[`Zsh current returns the current Node.js version set in fnm: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nif [ \"$(fnm current)\" != \"none\" ]; then\n  echo \"Expected currently activated version to be none. Got $(fnm current)\"\n  exit 1\nfi\nfnm install v8.11.3\nfnm install v10.10.0\nfnm use v8.11.3\nif [ \"$(fnm current)\" != \"v8.11.3\" ]; then\n  echo \"Expected currently activated version to be v8.11.3. Got $(fnm current)\"\n  exit 1\nfi\nfnm use v10.10.0\nif [ \"$(fnm current)\" != \"v10.10.0\" ]; then\n  echo \"Expected currently activated version to be v10.10.0. Got $(fnm current)\"\n  exit 1\nfi\nfnm use system\nif [ \"$(fnm current)\" != \"system\" ]; then\n  echo \"Expected currently activated version to be system. Got $(fnm current)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/env.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash outputs json: Bash 1`] = `\n\"set -e\nfnm env --json > file.json\"\n`;\n\nexports[`Fish outputs json: Fish 1`] = `\"fnm env --json > file.json\"`;\n\nexports[`PowerShell outputs json: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --json | Out-File file.json -Encoding UTF8\"\n`;\n\nexports[`Zsh outputs json: Zsh 1`] = `\n\"set -e\nfnm env --json > file.json\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/exec.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash \\`exec\\` usage: Bash 1`] = `\n\"set -e\nfnm install\nfnm install v6.10.0\nfnm install v10.10.0\nif [ \"$(fnm exec -- node -v)\" != \"v8.10.0\" ]; then\n  echo \"Expected version file exec to be v8.10.0. Got $(fnm exec -- node -v)\"\n  exit 1\nfi\nif [ \"$(fnm exec --using=6 -- node -v)\" != \"v6.10.0\" ]; then\n  echo \"Expected exec:6 node -v to be v6.10.0. Got $(fnm exec --using=6 -- node -v)\"\n  exit 1\nfi\nif [ \"$(fnm exec --using=10 -- node -v)\" != \"v10.10.0\" ]; then\n  echo \"Expected exec:6 node -v to be v10.10.0. Got $(fnm exec --using=10 -- node -v)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish \\`exec\\` usage: Fish 1`] = `\n\"fnm install\nfnm install v6.10.0\nfnm install v10.10.0\nset ____test____ (fnm exec -- node -v)\nif test \"$____test____\" != \"v8.10.0\"\n  echo \"Expected version file exec to be v8.10.0. Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm exec --using=6 -- node -v)\nif test \"$____test____\" != \"v6.10.0\"\n  echo \"Expected exec:6 node -v to be v6.10.0. Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm exec --using=10 -- node -v)\nif test \"$____test____\" != \"v10.10.0\"\n  echo \"Expected exec:6 node -v to be v10.10.0. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell \\`exec\\` usage: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm install\nfnm install v6.10.0\nfnm install v10.10.0\nif ( \"$(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 }\nif ( \"$(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 }\nif ( \"$(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 }\"\n`;\n\nexports[`Zsh \\`exec\\` usage: Zsh 1`] = `\n\"set -e\nfnm install\nfnm install v6.10.0\nfnm install v10.10.0\nif [ \"$(fnm exec -- node -v)\" != \"v8.10.0\" ]; then\n  echo \"Expected version file exec to be v8.10.0. Got $(fnm exec -- node -v)\"\n  exit 1\nfi\nif [ \"$(fnm exec --using=6 -- node -v)\" != \"v6.10.0\" ]; then\n  echo \"Expected exec:6 node -v to be v6.10.0. Got $(fnm exec --using=6 -- node -v)\"\n  exit 1\nfi\nif [ \"$(fnm exec --using=10 -- node -v)\" != \"v10.10.0\" ]; then\n  echo \"Expected exec:6 node -v to be v10.10.0. Got $(fnm exec --using=10 -- node -v)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/existing-installation.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash warns about an existing installation: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\n(fnm install v8.11.3 2>&1) | grep 'already installed' || (echo \"Expected output to contain 'already installed'\" && exit 1)\"\n`;\n\nexports[`Fish warns about an existing installation: Fish 1`] = `\n\"fnm env | source\nfnm install v8.11.3\nbegin; fnm install v8.11.3 2>&1; end | grep 'already installed'; or echo \"Expected output to contain 'already installed'\" && exit 1\"\n`;\n\nexports[`PowerShell warns about an existing installation: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install v8.11.3\n$($__out__ = $(fnm install v8.11.3 2>&1 | Select-String 'already installed'); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`Zsh warns about an existing installation: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\n(fnm install v8.11.3 2>&1) | grep 'already installed' || (echo \"Expected output to contain 'already installed'\" && exit 1)\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/latest-lts.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash installs latest lts: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install --lts\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\nfnm use 'lts/*'\"\n`;\n\nexports[`Fish installs latest lts: Fish 1`] = `\n\"fnm env | source\nfnm install --lts\nbegin; fnm ls; end | grep lts-latest; or echo \"Expected output to contain lts-latest\" && exit 1\nfnm use 'lts/*'\"\n`;\n\nexports[`PowerShell installs latest lts: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install --lts\n$($__out__ = $(fnm ls | Select-String lts-latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\nfnm use 'lts/*'\"\n`;\n\nexports[`Zsh installs latest lts: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install --lts\n(fnm ls) | grep lts-latest || (echo \"Expected output to contain lts-latest\" && exit 1)\nfnm use 'lts/*'\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/latest.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash installs latest: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install --latest\n(fnm ls) | grep latest || (echo \"Expected output to contain latest\" && exit 1)\nfnm use 'latest'\"\n`;\n\nexports[`Fish installs latest: Fish 1`] = `\n\"fnm env | source\nfnm install --latest\nbegin; fnm ls; end | grep latest; or echo \"Expected output to contain latest\" && exit 1\nfnm use 'latest'\"\n`;\n\nexports[`PowerShell installs latest: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install --latest\n$($__out__ = $(fnm ls | Select-String latest); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\nfnm use 'latest'\"\n`;\n\nexports[`Zsh installs latest: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install --latest\n(fnm ls) | grep latest || (echo \"Expected output to contain latest\" && exit 1)\nfnm use 'latest'\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/log-level.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash \"quiet\" log level: Bash 1`] = `\n\"set -e\neval \"$(fnm env --log-level=quiet)\"\nif [ \"$(fnm install v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm use v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm alias v8.11.3 something)\" != \"\" ]; then\n  echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"\n  exit 1\nfi\"\n`;\n\nexports[`Bash error log level: Bash 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\nif [ \"$(fnm install v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm use v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm alias v8.11.3 something)\" != \"\" ]; then\n  echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"\n  exit 1\nfi\n(fnm alias abcd efg 2>&1) | grep \"find requested version\" || (echo \"Expected output to contain \"find requested version\"\" && exit 1)\"\n`;\n\nexports[`Fish \"quiet\" log level: Fish 1`] = `\n\"fnm env --log-level=quiet | source\nset ____test____ (fnm install v8.11.3)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm install to be . Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm use v8.11.3)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm use to be . Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm alias v8.11.3 something)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm alias to be . Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`Fish error log level: Fish 1`] = `\n\"fnm env --log-level=error | source\nset ____test____ (fnm install v8.11.3)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm install to be . Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm use v8.11.3)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm use to be . Got $____test____\"\n  exit 1\nend\nset ____test____ (fnm alias v8.11.3 something)\nif test \"$____test____\" != \"\"\n  echo \"Expected fnm alias to be . Got $____test____\"\n  exit 1\nend\nbegin; fnm alias abcd efg 2>&1; end | grep \"find requested version\"; or echo \"Expected output to contain \"find requested version\"\" && exit 1\"\n`;\n\nexports[`PowerShell \"quiet\" log level: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --log-level=quiet | Out-String | Invoke-Expression\nif ( \"$(fnm install v8.11.3)\" -ne \"\" ) { echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"; exit 1 }\nif ( \"$(fnm use v8.11.3)\" -ne \"\" ) { echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"; exit 1 }\nif ( \"$(fnm alias v8.11.3 something)\" -ne \"\" ) { echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"; exit 1 }\"\n`;\n\nexports[`PowerShell error log level: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --log-level=error | Out-String | Invoke-Expression\nif ( \"$(fnm install v8.11.3)\" -ne \"\" ) { echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"; exit 1 }\nif ( \"$(fnm use v8.11.3)\" -ne \"\" ) { echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"; exit 1 }\nif ( \"$(fnm alias v8.11.3 something)\" -ne \"\" ) { echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"; exit 1 }\n$($__out__ = $(fnm alias abcd efg 2>&1 | Select-String \"find requested version\"); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`Zsh \"quiet\" log level: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --log-level=quiet)\"\nif [ \"$(fnm install v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm use v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm alias v8.11.3 something)\" != \"\" ]; then\n  echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"\n  exit 1\nfi\"\n`;\n\nexports[`Zsh error log level: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --log-level=error)\"\nif [ \"$(fnm install v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm install to be . Got $(fnm install v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm use v8.11.3)\" != \"\" ]; then\n  echo \"Expected fnm use to be . Got $(fnm use v8.11.3)\"\n  exit 1\nfi\nif [ \"$(fnm alias v8.11.3 something)\" != \"\" ]; then\n  echo \"Expected fnm alias to be . Got $(fnm alias v8.11.3 something)\"\n  exit 1\nfi\n(fnm alias abcd efg 2>&1) | grep \"find requested version\" || (echo \"Expected output to contain \"find requested version\"\" && exit 1)\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/multishell.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash multishell changes don't affect parent: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\nfnm install v11.9.0\necho 'set -e\neval \"$(fnm env)\"\nfnm use v11\nif [ \"$(node --version)\" != \"v11.9.0\" ]; then\n  echo \"Expected node version to be v11.9.0. Got $(node --version)\"\n  exit 1\nfi' | bash\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish multishell changes don't affect parent: Fish 1`] = `\n\"fnm env | source\nfnm install v8.11.3\nfnm install v11.9.0\nfish -c 'fnm env | source\nfnm use v11\nset ____test____ (node --version)\nif test \"$____test____\" != \"v11.9.0\"\n  echo \"Expected node version to be v11.9.0. Got $____test____\"\n  exit 1\nend'\nset ____test____ (node --version)\nif test \"$____test____\" != \"v8.11.3\"\n  echo \"Expected node version to be v8.11.3. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell multishell changes don't affect parent: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install v8.11.3\nfnm install v11.9.0\necho '$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm use v11\nif ( \"$(node --version)\" -ne \"v11.9.0\" ) { echo \"Expected node version to be v11.9.0. Got $(node --version)\"; exit 1 }' | pwsh -NoProfile\nif ( \"$(node --version)\" -ne \"v8.11.3\" ) { echo \"Expected node version to be v8.11.3. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`Zsh multishell changes don't affect parent: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v8.11.3\nfnm install v11.9.0\necho 'set -e\neval \"$(fnm env)\"\nfnm use v11\nif [ \"$(node --version)\" != \"v11.9.0\" ]; then\n  echo \"Expected node version to be v11.9.0. Got $(node --version)\"\n  exit 1\nfi' | zsh\nif [ \"$(node --version)\" != \"v8.11.3\" ]; then\n  echo \"Expected node version to be v8.11.3. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/nvmrc-lts.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash uses .nvmrc with lts definition: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\n(fnm ls) | grep lts-dubnium || (echo \"Expected output to contain lts-dubnium\" && exit 1)\"\n`;\n\nexports[`Fish uses .nvmrc with lts definition: Fish 1`] = `\n\"fnm env | source\nfnm install\nfnm use\nbegin; fnm ls; end | grep lts-dubnium; or echo \"Expected output to contain lts-dubnium\" && exit 1\"\n`;\n\nexports[`PowerShell uses .nvmrc with lts definition: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install\nfnm use\n$($__out__ = $(fnm ls | Select-String lts-dubnium); if ($__out__ -eq $null) { exit 1 } else { $__out__ })\"\n`;\n\nexports[`Zsh uses .nvmrc with lts definition: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install\nfnm use\n(fnm ls) | grep lts-dubnium || (echo \"Expected output to contain lts-dubnium\" && exit 1)\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/old-versions.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash download old Node.js 0.10.x: Bash 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v0.10.36\nfnm use v0.10.36\nif [ \"$(node --version)\" != \"v0.10.36\" ]; then\n  echo \"Expected node version to be v0.10.36. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish download old Node.js 0.10.x: Fish 1`] = `\n\"fnm env | source\nfnm install v0.10.36\nfnm use v0.10.36\nset ____test____ (node --version)\nif test \"$____test____\" != \"v0.10.36\"\n  echo \"Expected node version to be v0.10.36. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell download old Node.js 0.10.x: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env | Out-String | Invoke-Expression\nfnm install v0.10.36\nfnm use v0.10.36\nif ( \"$(node --version)\" -ne \"v0.10.36\" ) { echo \"Expected node version to be v0.10.36. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`Zsh download old Node.js 0.10.x: Zsh 1`] = `\n\"set -e\neval \"$(fnm env)\"\nfnm install v0.10.36\nfnm use v0.10.36\nif [ \"$(node --version)\" != \"v0.10.36\" ]; then\n  echo \"Expected node version to be v0.10.36. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/uninstall.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash uninstalls a version: Bash 1`] = `\n\"set -e\nfnm i 12.0.0\nfnm alias 12.0.0 hello\n((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)\nfnm uni hello\nif [ \"$(fnm ls)\" != \"* system\" ]; then\n  echo \"Expected fnm ls to be * system. Got $(fnm ls)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish uninstalls a version: Fish 1`] = `\n\"fnm i 12.0.0\nfnm alias 12.0.0 hello\nbegin; 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\nfnm uni hello\nset ____test____ (fnm ls)\nif test \"$____test____\" != \"* system\"\n  echo \"Expected fnm ls to be * system. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell uninstalls a version: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm i 12.0.0\nfnm alias 12.0.0 hello\n$($__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__ })\nfnm uni hello\nif ( \"$(fnm ls)\" -ne \"* system\" ) { echo \"Expected fnm ls to be * system. Got $(fnm ls)\"; exit 1 }\"\n`;\n\nexports[`Zsh uninstalls a version: Zsh 1`] = `\n\"set -e\nfnm i 12.0.0\nfnm alias 12.0.0 hello\n((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)\nfnm uni hello\nif [ \"$(fnm ls)\" != \"* system\" ]; then\n  echo \"Expected fnm ls to be * system. Got $(fnm ls)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/__snapshots__/use-on-cd.test.ts.snap",
    "content": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Bash use on cd: Bash 1`] = `\n\"set -e\neval \"$(fnm env --use-on-cd)\"\nfnm install v8.11.3\nfnm install v12.22.12\ncd subdir\nif [ \"$(node --version)\" != \"v12.22.12\" ]; then\n  echo \"Expected node version to be v12.22.12. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n\nexports[`Fish use on cd: Fish 1`] = `\n\"fnm env --use-on-cd | source\nfnm install v8.11.3\nfnm install v12.22.12\ncd subdir\nset ____test____ (node --version)\nif test \"$____test____\" != \"v12.22.12\"\n  echo \"Expected node version to be v12.22.12. Got $____test____\"\n  exit 1\nend\"\n`;\n\nexports[`PowerShell use on cd: PowerShell 1`] = `\n\"$ErrorActionPreference = \"Stop\"\nfnm env --use-on-cd | Out-String | Invoke-Expression\nfnm install v8.11.3\nfnm install v12.22.12\ncd subdir\nif ( \"$(node --version)\" -ne \"v12.22.12\" ) { echo \"Expected node version to be v12.22.12. Got $(node --version)\"; exit 1 }\"\n`;\n\nexports[`Zsh use on cd: Zsh 1`] = `\n\"set -e\neval \"$(fnm env --use-on-cd)\"\nfnm install v8.11.3\nfnm install v12.22.12\ncd subdir\nif [ \"$(node --version)\" != \"v12.22.12\" ]; then\n  echo \"Expected node version to be v12.22.12. Got $(node --version)\"\n  exit 1\nfi\"\n`;\n"
  },
  {
    "path": "e2e/aliases.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\nimport { writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport getStderr from \"./shellcode/get-stderr.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`installs aliases when corepack is enabled`, async () => {\n      await writeFile(path.join(testCwd(), \".node-version\"), \"lts/*\")\n      await script(shell)\n        .then(shell.env({ corepackEnabled: true }))\n        .then(shell.call(\"fnm\", [\"use\", \"--install-if-missing\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"lts-latest\"),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`allows to install an lts if version missing`, async () => {\n      await writeFile(path.join(testCwd(), \".node-version\"), \"lts/*\")\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"use\", \"--install-if-missing\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"lts-latest\"),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`errors when alias is not found`, async () => {\n      await writeFile(path.join(testCwd(), \".node-version\"), \"lts/*\")\n      await script(shell)\n        .then(shell.env({ logLevel: \"error\" }))\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"use\"])),\n            \"'Requested version lts-latest is not'\",\n          ),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`unalias a version`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"11.10.0\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"alias\", \"8.11.3\", \"version8\"]))\n        .then(shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"version8\"))\n        .then(shell.call(\"fnm\", [\"unalias\", \"version8\"]))\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"use\", \"version8\"])),\n            \"'Requested version version8 is not currently installed'\",\n          ),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`unalias errors if alias not found`, async () => {\n      await script(shell)\n        .then(shell.env({ logLevel: \"error\" }))\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"unalias\", \"lts\"])),\n            \"'Requested alias lts not found'\",\n          ),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`can alias the system node`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"alias\", \"system\", \"my_system\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"my_system\"),\n        )\n        .then(shell.call(\"fnm\", [\"alias\", \"system\", \"default\"]))\n        .then(shell.call(\"fnm\", [\"alias\", \"my_system\", \"my_system2\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"my_system2\"),\n        )\n        .then(\n          shell.scriptOutputContains(\n            shell.call(\"fnm\", [\"use\", \"my_system\"]),\n            \"'Bypassing fnm'\",\n          ),\n        )\n        .then(shell.call(\"fnm\", [\"unalias\", \"my_system\"]))\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"use\", \"my_system\"])),\n            \"'Requested version my_system is not currently installed'\",\n          ),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`aliasing versions`, async () => {\n      const installedVersions = shell.call(\"fnm\", [\"ls\"])\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"6.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"alias\", \"8.11\", \"oldie\"]))\n        .then(shell.call(\"fnm\", [\"alias\", \"6\", \"older\"]))\n        .then(shell.call(\"fnm\", [\"default\", \"older\"]))\n        .then(\n          shell.scriptOutputContains(\n            shell.scriptOutputContains(installedVersions, \"8.11.3\"),\n            \"oldie\",\n          ),\n        )\n        .then(\n          shell.scriptOutputContains(\n            shell.scriptOutputContains(installedVersions, \"6.11.3\"),\n            \"older\",\n          ),\n        )\n        .then(shell.call(\"fnm\", [\"use\", \"older\"]))\n        .then(testNodeVersion(shell, \"v6.11.3\"))\n        .then(shell.call(\"fnm\", [\"use\", \"oldie\"]))\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .then(shell.call(\"fnm\", [\"use\", \"default\"]))\n        .then(testNodeVersion(shell, \"v6.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/basic.test.ts",
    "content": "import { writeFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(`basic usage`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v8.11.3\"]))\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`.nvmrc`, async () => {\n      await writeFile(join(testCwd(), \".nvmrc\"), \"v8.11.3\")\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`.node-version`, async () => {\n      await writeFile(join(testCwd(), \".node-version\"), \"v8.11.3\")\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`package.json engines.node`, async () => {\n      await writeFile(\n        join(testCwd(), \"package.json\"),\n        JSON.stringify({ engines: { node: \"8.11.3\" } }),\n      )\n      await script(shell)\n        .then(shell.env({ resolveEngines: true }))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`package.json engines.node with semver range`, async () => {\n      await writeFile(\n        join(testCwd(), \"package.json\"),\n        JSON.stringify({ engines: { node: \"^6 < 6.17.1\" } }),\n      )\n      await script(shell)\n        .then(shell.env({ resolveEngines: true }))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(testNodeVersion(shell, \"v6.17.0\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`resolves partial semver`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"6\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"6\"]))\n        .then(testNodeVersion(shell, \"v6.17.1\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(\"`fnm ls` with nothing installed\", async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"ls\"]),\n            \"* system\",\n            \"fnm ls\",\n          ),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`when .node-version and .nvmrc are in sync, it throws no error`, async () => {\n      await writeFile(join(testCwd(), \".nvmrc\"), \"v11.10.0\")\n      await writeFile(join(testCwd(), \".node-version\"), \"v11.10.0\")\n\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(testNodeVersion(shell, \"v11.10.0\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/corepack.test.ts",
    "content": "import fs from \"fs\"\nimport { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\nimport path from \"path\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport { createRequire } from \"module\"\n\nconst require = createRequire(import.meta.url)\nconst whichPath = require.resolve(\"which\")\n\nconst nodescript = `\n  const which = require(${JSON.stringify(whichPath)});\n  const pnpmBinary = which.sync('pnpm')\n  const nodeBinary = which.sync('node')\n\n  const binPath = require('path').dirname(nodeBinary);\n\n  if (!pnpmBinary.includes(binPath)) {\n    console.log('pnpm not found in current Node.js bin', { binPath, pnpmBinary });\n    process.exit(1);\n  }\n  const scriptContents = require('fs').readFileSync(pnpmBinary, 'utf8');\n  console.log('scriptContents', scriptContents)\n  if (!scriptContents.includes('corepack')) {\n    console.log('corepack not found in pnpm script');\n    process.exit(1);\n  }\n`\n\nfor (const shell of [Bash, Fish, PowerShell, Zsh]) {\n  describe(shell, () => {\n    test(`installs corepack`, async () => {\n      const cwd = testCwd()\n      const filepath = path.join(cwd, \"test-pnpm-corepack.js\")\n      fs.writeFileSync(filepath, nodescript)\n\n      await script(shell)\n        .then(shell.env({ corepackEnabled: true }))\n        .then(shell.call(\"fnm\", [\"install\", \"18\"]))\n        .then(\n          shell.call(\"fnm\", [\n            \"exec\",\n            \"--using=18\",\n            \"node\",\n            \"test-pnpm-corepack.js\",\n          ])\n        )\n        .takeSnapshot(shell)\n        // .addExtraEnvVar(\"RUST_LOG\", \"fnm=debug\")\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/current.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(`current returns the current Node.js version set in fnm`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"current\"]),\n            \"none\",\n            \"currently activated version\"\n          )\n        )\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v10.10.0\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v8.11.3\"]))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"current\"]),\n            \"v8.11.3\",\n            \"currently activated version\"\n          )\n        )\n        .then(shell.call(\"fnm\", [\"use\", \"v10.10.0\"]))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"current\"]),\n            \"v10.10.0\",\n            \"currently activated version\"\n          )\n        )\n        .then(shell.call(\"fnm\", [\"use\", \"system\"]))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"current\"]),\n            \"system\",\n            \"currently activated version\"\n          )\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/describe.ts",
    "content": "import { WinCmd } from \"./shellcode/shells.js\"\nimport { Shell } from \"./shellcode/shells/types.js\"\n\nexport default function describe(\n  shell: Pick<Shell, \"name\">,\n  fn: () => void\n): void {\n  if (shell === WinCmd) {\n    // wincmd tests do not work right now and I don't have a Windows machine to fix it\n    // maybe in the future when I have some time to spin a VM to check what's happening.\n    return globalThis.describe.skip(\"WinCmd\", fn)\n  }\n\n  globalThis.describe(shell.name(), fn)\n}\n"
  },
  {
    "path": "e2e/env.test.ts",
    "content": "import { readFile } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(`outputs json`, async () => {\n      const filename = `file.json`\n      await script(shell)\n        .then(\n          shell.redirectOutput(shell.call(\"fnm\", [\"env\", \"--json\"]), {\n            output: filename,\n          }),\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n\n      if (shell.currentlySupported()) {\n        const file = await readFile(join(testCwd(), filename), \"utf8\")\n        expect(JSON.parse(file)).toEqual({\n          FNM_ARCH: expect.any(String),\n          FNM_DIR: expect.any(String),\n          FNM_LOGLEVEL: \"info\",\n          FNM_MULTISHELL_PATH: expect.any(String),\n          FNM_NODE_DIST_MIRROR: expect.any(String),\n          FNM_RESOLVE_ENGINES: \"true\",\n          FNM_COREPACK_ENABLED: \"false\",\n          FNM_VERSION_FILE_STRATEGY: \"local\",\n        })\n      }\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/exec.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(\"`exec` usage\", async () => {\n      await fs.writeFile(path.join(testCwd(), \".nvmrc\"), \"v8.10.0\")\n\n      await script(shell)\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v6.10.0\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v10.10.0\"]))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"exec\", \"--\", \"node\", \"-v\"]),\n            \"v8.10.0\",\n            \"version file exec\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"exec\", \"--using=6\", \"--\", \"node\", \"-v\"]),\n            \"v6.10.0\",\n            \"exec:6 node -v\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"exec\", \"--using=10\", \"--\", \"node\", \"-v\"]),\n            \"v10.10.0\",\n            \"exec:6 node -v\"\n          )\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/existing-installation.test.ts",
    "content": "import getStderr from \"./shellcode/get-stderr.js\"\nimport { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`warns about an existing installation`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"install\", \"v8.11.3\"])),\n            \"'already installed'\"\n          )\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/latest-lts.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`installs latest lts`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"--lts\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"lts-latest\")\n        )\n        .then(shell.call(\"fnm\", [\"use\", \"'lts/*'\"]))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/latest.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`installs latest`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"--latest\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"latest\")\n        )\n        .then(shell.call(\"fnm\", [\"use\", \"'latest'\"]))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/log-level.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\nimport getStderr from \"./shellcode/get-stderr.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`\"quiet\" log level`, async () => {\n      await script(shell)\n        .then(shell.env({ logLevel: \"quiet\" }))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"install\", \"v8.11.3\"]),\n            \"\",\n            \"fnm install\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"use\", \"v8.11.3\"]),\n            \"\",\n            \"fnm use\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"alias\", \"v8.11.3\", \"something\"]),\n            \"\",\n            \"fnm alias\"\n          )\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(\"error log level\", async () => {\n      await script(shell)\n        .then(shell.env({ logLevel: \"error\" }))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"install\", \"v8.11.3\"]),\n            \"\",\n            \"fnm install\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"use\", \"v8.11.3\"]),\n            \"\",\n            \"fnm use\"\n          )\n        )\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"alias\", \"v8.11.3\", \"something\"]),\n            \"\",\n            \"fnm alias\"\n          )\n        )\n        .then(\n          shell.scriptOutputContains(\n            getStderr(shell.call(\"fnm\", [\"alias\", \"abcd\", \"efg\"])),\n            `\"find requested version\"`\n          )\n        )\n\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/multishell.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`multishell changes don't affect parent`, async () => {\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v11.9.0\"]))\n        .then(\n          shell.inSubShell(\n            script(shell)\n              .then(shell.env({}))\n              .then(shell.call(\"fnm\", [\"use\", \"v11\"]))\n              .then(testNodeVersion(shell, \"v11.9.0\"))\n              .asLine()\n          )\n        )\n        .then(testNodeVersion(shell, \"v8.11.3\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/nvmrc-lts.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport describe from \"./describe.js\"\nimport testCwd from \"./shellcode/test-cwd.js\"\n\nfor (const shell of [Bash, Fish, PowerShell, Zsh]) {\n  describe(shell, () => {\n    test(`uses .nvmrc with lts definition`, async () => {\n      await fs.writeFile(path.join(testCwd(), \".nvmrc\"), `lts/dubnium`)\n\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\"]))\n        .then(shell.call(\"fnm\", [\"use\"]))\n        .then(\n          shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"lts-dubnium\")\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/old-versions.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport describe from \"./describe.js\"\nimport os from \"node:os\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(`download old Node.js 0.10.x`, async () => {\n      const testCase = script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v0.10.36\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v0.10.36\"]))\n        .then(testNodeVersion(shell, \"v0.10.36\"))\n        .takeSnapshot(shell)\n\n      if (os.platform() === \"win32\") {\n        console.warn(`test skipped as 0.10.x isn't prebuilt for windows`)\n      } else {\n        await testCase.execute(shell)\n      }\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/shellcode/get-stderr.ts",
    "content": "export default function getStderr(script: string): string {\n  return `${script} 2>&1`\n}\n"
  },
  {
    "path": "e2e/shellcode/script.ts",
    "content": "import { ScriptLine, Shell } from \"./shells/types.js\"\nimport { execa, type ExecaChildProcess } from \"execa\"\nimport testTmpDir from \"./test-tmp-dir.js\"\nimport { Writable } from \"node:stream\"\nimport { dedent } from \"ts-dedent\"\nimport testCwd from \"./test-cwd.js\"\nimport path, { join } from \"node:path\"\nimport { writeFile } from \"node:fs/promises\"\nimport chalk from \"chalk\"\nimport testBinDir from \"./test-bin-dir.js\"\nimport { rmSync } from \"node:fs\"\n\nclass Script {\n  constructor(\n    private readonly config: {\n      fnmDir: string\n    },\n    private readonly lines: ScriptLine[],\n    private readonly extraEnvVars: Record<string, string> = {}\n  ) {}\n  then(line: ScriptLine): Script {\n    return new Script(this.config, [...this.lines, line])\n  }\n\n  takeSnapshot(shell: Pick<Shell, \"name\">): this {\n    const script = this.lines.join(\"\\n\")\n    expect(script).toMatchSnapshot(shell.name())\n\n    return this\n  }\n\n  addExtraEnvVar(name: string, value: string): this {\n    return new Script(\n      this.config,\n      this.lines,\n      Object.assign({}, this.extraEnvVars, { [name]: value })\n    ) as this\n  }\n\n  async execute(\n    shell: Pick<\n      Shell,\n      \"binaryName\" | \"launchArgs\" | \"currentlySupported\" | \"forceFile\"\n    >\n  ): Promise<void> {\n    if (!shell.currentlySupported()) {\n      return\n    }\n\n    const args = [...shell.launchArgs()]\n\n    if (shell.forceFile) {\n      let filename = join(testTmpDir(), \"script\")\n      if (typeof shell.forceFile === \"string\") {\n        filename = filename + shell.forceFile\n      }\n      await writeFile(filename, [...this.lines, \"exit 0\"].join(\"\\n\"))\n      args.push(filename)\n    }\n\n    const child = execa(shell.binaryName(), args, {\n      stdio: [shell.forceFile ? \"ignore\" : \"pipe\", \"pipe\", \"pipe\"],\n      cwd: testCwd(),\n      env: (() => {\n        const newProcessEnv: Record<string, string> = {\n          ...this.extraEnvVars,\n          ...removeAllFnmEnvVars(process.env),\n          PATH: [testBinDir(), fnmTargetDir(), process.env.PATH]\n            .filter(Boolean)\n            .join(path.delimiter),\n          FNM_DIR: this.config.fnmDir,\n          FNM_NODE_DIST_MIRROR: \"http://localhost:8080\",\n        }\n\n        delete newProcessEnv.NODE_OPTIONS\n        return newProcessEnv\n      })(),\n      extendEnv: false,\n      reject: false,\n    })\n\n    if (child.stdin) {\n      const childStdin = child.stdin\n\n      for (const line of this.lines) {\n        await write(childStdin, `${line}\\n`)\n      }\n\n      await write(childStdin, \"exit 0\\n\")\n    }\n\n    const { stdout, stderr } = streamOutputsAndBuffer(child)\n\n    const finished = await child\n\n    if (finished.failed) {\n      console.error(\n        dedent`\n          Script failed.\n            code ${finished.exitCode}\n            signal ${finished.signal}\n\n          stdout:\n          ${padAllLines(stdout.join(\"\"), 2)}\n\n          stderr:\n          ${padAllLines(stderr.join(\"\"), 2)}\n        `\n      )\n\n      throw new Error(\n        `Script failed on ${testCwd()} with code ${finished.exitCode}`\n      )\n    }\n  }\n\n  asLine(): ScriptLine {\n    return this.lines.join(\"\\n\")\n  }\n}\n\nfunction streamOutputsAndBuffer(child: ExecaChildProcess) {\n  const stdout: string[] = []\n  const stderr: string[] = []\n  const testName = expect.getState().currentTestName ?? \"unknown\"\n  const testPath = expect.getState().testPath ?? \"unknown\"\n\n  const stdoutPrefix = chalk.cyan.dim(`[stdout] ${testPath}/${testName}: `)\n  const stderrPrefix = chalk.magenta.dim(`[stderr] ${testPath}/${testName}: `)\n\n  if (child.stdout) {\n    child.stdout.on(\"data\", (data) => {\n      const lines = data.toString().trim().split(/\\r?\\n/)\n      for (const line of lines) {\n        process.stdout.write(`${stdoutPrefix}${line}\\n`)\n      }\n      stdout.push(data.toString())\n    })\n  }\n\n  if (child.stderr) {\n    child.stderr.on(\"data\", (data) => {\n      const lines = data.toString().trim().split(/\\r?\\n/)\n      for (const line of lines) {\n        process.stdout.write(`${stderrPrefix}${line}\\n`)\n      }\n      stderr.push(data.toString())\n    })\n  }\n\n  return { stdout, stderr }\n}\n\nfunction padAllLines(text: string, padding: number): string {\n  return text\n    .split(\"\\n\")\n    .map((line) => \" \".repeat(padding) + line)\n    .join(\"\\n\")\n}\n\nfunction write(writable: Writable, text: string): Promise<void> {\n  return new Promise<void>((resolve, reject) => {\n    writable.write(text, (err) => {\n      if (err) return reject(err)\n      return resolve()\n    })\n  })\n}\n\nexport function script(shell: Pick<Shell, \"dieOnErrors\">): Script {\n  const fnmDir = path.join(testTmpDir(), \"fnm\")\n  rmSync(join(fnmDir, \"aliases\"), { recursive: true, force: true })\n  return new Script({ fnmDir }, shell.dieOnErrors ? [shell.dieOnErrors()] : [])\n}\n\nfunction removeAllFnmEnvVars(obj: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n  const result: NodeJS.ProcessEnv = {}\n  for (const [key, value] of Object.entries(obj)) {\n    if (!key.startsWith(\"FNM_\")) {\n      result[key] = value\n    }\n  }\n  return result\n}\n\nfunction fnmTargetDir(): string {\n  return path.join(\n    process.cwd(),\n    \"target\",\n    process.env.FNM_TARGET_NAME ?? \"debug\"\n  )\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/cmdCall.ts",
    "content": "import { define, ScriptLine } from \"./types.js\"\n\nexport type HasCall = {\n  call: (binary: string, args: string[]) => ScriptLine\n}\n\nexport const cmdCall = {\n  all: define<HasCall>({\n    call: (binary: string, args: string[]) =>\n      `${binary} ${args.join(\" \")}` as ScriptLine,\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/cmdEnv.ts",
    "content": "import { ScriptLine, define } from \"./types.js\"\n\ntype EnvConfig = {\n  executableName: string\n  useOnCd: boolean\n  logLevel: string\n  corepackEnabled: boolean\n  resolveEngines: boolean\n  nodeDistMirror: string\n}\nexport type HasEnv = { env(cfg: Partial<EnvConfig>): ScriptLine }\n\nfunction stringify(envConfig: Partial<EnvConfig> = {}) {\n  const {\n    useOnCd,\n    logLevel,\n    corepackEnabled,\n    resolveEngines,\n    executableName = \"fnm\",\n    nodeDistMirror,\n  } = envConfig\n  return [\n    `${executableName} env`,\n    useOnCd && \"--use-on-cd\",\n    logLevel && `--log-level=${logLevel}`,\n    corepackEnabled && \"--corepack-enabled\",\n    resolveEngines && `--resolve-engines`,\n    nodeDistMirror && `--node-dist-mirror=${JSON.stringify(nodeDistMirror)}`,\n  ]\n    .filter(Boolean)\n    .join(\" \")\n}\n\nexport const cmdEnv = {\n  bash: define<HasEnv>({\n    env: (envConfig) => `eval \"$(${stringify(envConfig)})\"`,\n  }),\n  fish: define<HasEnv>({\n    env: (envConfig) => `${stringify(envConfig)} | source`,\n  }),\n  powershell: define<HasEnv>({\n    env: (envConfig) =>\n      `${stringify(envConfig)} | Out-String | Invoke-Expression`,\n  }),\n  wincmd: define<HasEnv>({\n    env: (envConfig) =>\n      `FOR /f \"tokens=*\" %i IN ('${stringify(envConfig)}') DO CALL %i`,\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/expect-command-output.ts",
    "content": "import { dedent } from \"ts-dedent\"\nimport { define, ScriptLine } from \"./types.js\"\n\nexport type HasExpectCommandOutput = {\n  hasCommandOutput(\n    script: ScriptLine,\n    output: string,\n    message: string\n  ): ScriptLine\n}\n\nexport const cmdExpectCommandOutput = {\n  bash: define<HasExpectCommandOutput>({\n    hasCommandOutput(script, output, message) {\n      return dedent`\n        if [ \"$(${script})\" != \"${output}\" ]; then\n          echo \"Expected ${message} to be ${output}. Got $(${script})\"\n          exit 1\n        fi\n      `\n    },\n  }),\n  fish: define<HasExpectCommandOutput>({\n    hasCommandOutput(script, output, message) {\n      return dedent`\n        set ____test____ (${script})\n        if test \"$____test____\" != \"${output}\"\n          echo \"Expected ${message} to be ${output}. Got $____test____\"\n          exit 1\n        end\n      `\n    },\n  }),\n  powershell: define<HasExpectCommandOutput>({\n    hasCommandOutput(script, output, message) {\n      return dedent`\n        if ( \"$(${script})\" -ne \"${output}\" ) { echo \"Expected ${message} to be ${output}. Got $(${script})\"; exit 1 }\n      `\n    },\n  }),\n  wincmd: define<HasExpectCommandOutput>({\n    hasCommandOutput(script, output, message) {\n      return dedent`\n        ${script} | findstr ${output}\n        if %errorlevel% neq 0 (\n          echo Expected ${message} to be ${output}\n          exit 1\n        )\n      `\n    },\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/output-contains.ts",
    "content": "import { define, ScriptLine } from \"./types.js\"\n\nexport type HasOutputContains = {\n  scriptOutputContains(script: ScriptLine, substring: string): ScriptLine\n}\n\nexport const cmdHasOutputContains = {\n  bash: define<HasOutputContains>({\n    scriptOutputContains: (script, substring) => {\n      return `(${script}) | grep ${substring} || (echo \"Expected output to contain ${substring}\" && exit 1)`\n    },\n  }),\n  fish: define<HasOutputContains>({\n    scriptOutputContains: (script, substring) => {\n      return `begin; ${script}; end | grep ${substring}; or echo \"Expected output to contain ${substring}\" && exit 1`\n    },\n  }),\n  powershell: define<HasOutputContains>({\n    scriptOutputContains: (script, substring) => {\n      const inner: string = `${script} | Select-String ${substring}`\n      return `$($__out__ = $(${inner}); if ($__out__ -eq $null) { exit 1 } else { $__out__ })`\n    },\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/redirect-output.ts",
    "content": "import { ScriptLine, define } from \"./types.js\"\n\ntype RedirectOutputOpts = { output: string }\nexport type HasRedirectOutput = {\n  redirectOutput(childCommand: ScriptLine, opts: RedirectOutputOpts): string\n}\n\nexport const redirectOutput = {\n  bash: define<HasRedirectOutput>({\n    redirectOutput: (childCommand, opts) => `${childCommand} > ${opts.output}`,\n  }),\n  powershell: define<HasRedirectOutput>({\n    redirectOutput: (childCommand, opts) =>\n      `${childCommand} | Out-File ${opts.output} -Encoding UTF8`,\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/sub-shell.ts",
    "content": "import { ScriptLine, define } from \"./types.js\"\nimport quote from \"shell-escape\"\n\ntype HasInSubShell = { inSubShell: (script: ScriptLine) => ScriptLine }\n\nexport const cmdInSubShell = {\n  bash: define<HasInSubShell>({\n    inSubShell: (script) => `echo ${quote([script])} | bash`,\n  }),\n  zsh: define<HasInSubShell>({\n    inSubShell: (script) => `echo ${quote([script])} | zsh`,\n  }),\n  fish: define<HasInSubShell>({\n    inSubShell: (script) => `fish -c ${quote([script])}`,\n  }),\n  powershell: define<HasInSubShell>({\n    inSubShell: (script) =>\n      `echo '${script.replace(/'/g, \"\\\\'\")}' | pwsh -NoProfile`,\n  }),\n}\n"
  },
  {
    "path": "e2e/shellcode/shells/types.ts",
    "content": "export type Shell = {\n  escapeText(str: string): string\n  binaryName(): string\n  currentlySupported(): boolean\n  name(): string\n  launchArgs(): string[]\n  dieOnErrors?(): string\n  forceFile?: true | string\n}\n\nexport type ScriptLine = string\n\nexport function define<S>(s: S): S {\n  return s\n}\n"
  },
  {
    "path": "e2e/shellcode/shells.ts",
    "content": "import { cmdCall } from \"./shells/cmdCall.js\"\nimport { cmdEnv } from \"./shells/cmdEnv.js\"\nimport { cmdExpectCommandOutput } from \"./shells/expect-command-output.js\"\nimport { cmdHasOutputContains } from \"./shells/output-contains.js\"\nimport { redirectOutput } from \"./shells/redirect-output.js\"\nimport { cmdInSubShell } from \"./shells/sub-shell.js\"\nimport { define, Shell } from \"./shells/types.js\"\n\nexport const Bash = {\n  ...define<Shell>({\n    binaryName: () => \"bash\",\n    currentlySupported: () => true,\n    name: () => \"Bash\",\n    launchArgs: () => [\"-i\"],\n    escapeText: (x) => x,\n    dieOnErrors: () => `set -e`,\n  }),\n  ...cmdEnv.bash,\n  ...cmdCall.all,\n  ...redirectOutput.bash,\n  ...cmdExpectCommandOutput.bash,\n  ...cmdHasOutputContains.bash,\n  ...cmdInSubShell.bash,\n}\n\nexport const Zsh = {\n  ...define<Shell>({\n    binaryName: () => \"zsh\",\n    currentlySupported: () => process.platform !== \"win32\",\n    name: () => \"Zsh\",\n    launchArgs: () => [],\n    escapeText: (x) => x,\n    dieOnErrors: () => `set -e`,\n  }),\n  ...cmdEnv.bash,\n  ...cmdCall.all,\n  ...redirectOutput.bash,\n  ...cmdExpectCommandOutput.bash,\n  ...cmdHasOutputContains.bash,\n  ...cmdInSubShell.zsh,\n}\n\nexport const Fish = {\n  ...define<Shell>({\n    binaryName: () => \"fish\",\n    currentlySupported: () => process.platform !== \"win32\",\n    name: () => \"Fish\",\n    launchArgs: () => [],\n    escapeText: (x) => x,\n    forceFile: true,\n  }),\n  ...cmdEnv.fish,\n  ...cmdCall.all,\n  ...redirectOutput.bash,\n  ...cmdExpectCommandOutput.fish,\n  ...cmdHasOutputContains.fish,\n  ...cmdInSubShell.fish,\n}\n\nexport const PowerShell = {\n  ...define<Shell>({\n    binaryName: () => \"pwsh\",\n    forceFile: \".ps1\",\n    currentlySupported: () => process.platform === \"win32\",\n    name: () => \"PowerShell\",\n    launchArgs: () => [\"-NoProfile\"],\n    escapeText: (x) => x,\n    dieOnErrors: () => `$ErrorActionPreference = \"Stop\"`,\n  }),\n  ...cmdEnv.powershell,\n  ...cmdCall.all,\n  ...redirectOutput.powershell,\n  ...cmdExpectCommandOutput.powershell,\n  ...cmdHasOutputContains.powershell,\n  ...cmdInSubShell.powershell,\n}\n\nexport const WinCmd = {\n  ...define<Shell>({\n    binaryName: () => \"cmd.exe\",\n    currentlySupported: () => process.platform === \"win32\",\n    name: () => \"Windows Command Prompt\",\n    launchArgs: () => [],\n    escapeText: (str) =>\n      str\n        .replace(/\\r/g, \"\")\n        .replace(/\\n/g, \"^\\n\\n\")\n        .replace(/\\%/g, \"%%\")\n        .replace(/\\|/g, \"^|\")\n        .replace(/\\(/g, \"^(\")\n        .replace(/\\)/g, \"^)\"),\n  }),\n  ...cmdEnv.wincmd,\n  ...cmdCall.all,\n  ...cmdExpectCommandOutput.wincmd,\n  ...redirectOutput.bash,\n}\n"
  },
  {
    "path": "e2e/shellcode/test-bin-dir.ts",
    "content": "import { mkdirSync } from \"node:fs\"\nimport path from \"node:path\"\nimport testTmpDir from \"./test-tmp-dir.js\"\n\nexport default function testBinDir() {\n  const dir = path.join(testTmpDir(), \"bin\")\n  mkdirSync(dir, { recursive: true })\n  return dir\n}\n"
  },
  {
    "path": "e2e/shellcode/test-cwd.ts",
    "content": "import { mkdirSync } from \"node:fs\"\nimport path from \"node:path\"\nimport testTmpDir from \"./test-tmp-dir.js\"\n\nexport default function testCwd() {\n  const dir = path.join(testTmpDir(), \"cwd\")\n  mkdirSync(dir, { recursive: true })\n  return dir\n}\n"
  },
  {
    "path": "e2e/shellcode/test-node-version.ts",
    "content": "import { HasCall } from \"./shells/cmdCall.js\"\nimport { ScriptLine } from \"./shells/types.js\"\nimport { HasExpectCommandOutput } from \"./shells/expect-command-output.js\"\n\nexport default function testNodeVersion<\n  S extends HasCall & HasExpectCommandOutput\n>(shell: S, version: string): ScriptLine {\n  const nodeVersion = shell.call(\"node\", [\"--version\"])\n  return shell.hasCommandOutput(nodeVersion, version, \"node version\")\n}\n"
  },
  {
    "path": "e2e/shellcode/test-tmp-dir.ts",
    "content": "import { mkdirSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\n\nexport default function testTmpDir(): string {\n  const testName = (expect.getState().currentTestName ?? \"unknown\")\n    .toLowerCase()\n    .replace(/[^a-z0-9]/gi, \"_\")\n    .replace(/_+/g, \"_\")\n  const tmpDir = join(tmpdir(), `shellcode/${testName}`)\n  mkdirSync(tmpDir, { recursive: true })\n\n  return tmpDir\n}\n"
  },
  {
    "path": "e2e/system-node.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport fs from \"node:fs/promises\"\nimport path from \"node:path\"\nimport describe from \"./describe.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport testBinDir from \"./shellcode/test-bin-dir.js\"\n\nfor (const shell of [Bash, Fish, PowerShell, WinCmd, Zsh]) {\n  describe(shell, () => {\n    // latest bash breaks this as it seems. gotta find a solution.\n    const t = process.platform === \"darwin\" && shell === Bash ? test.skip : test\n\n    t(`switches to system node`, async () => {\n      await writeCustomNode()\n\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v10.10.0\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v10\"]))\n        .then(testNodeVersion(shell, \"v10.10.0\"))\n        .then(shell.call(\"fnm\", [\"use\", \"system\"]))\n        .then(testNodeVersion(shell, \"custom\"))\n        .execute(shell)\n    })\n\n    t(`aliasing a system node`, async () => {\n      writeCustomNode()\n      const init = script(shell).then(shell.env({}))\n\n      await init\n        .then(shell.call(\"fnm\", [\"install\", \"v10.10.0\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v10\"]))\n        .then(shell.call(\"fnm\", [\"default\", \"10\"]))\n        .execute(shell)\n\n      await init\n        .then(testNodeVersion(shell, \"v10.10.0\"))\n        .then(shell.call(\"fnm\", [\"default\", \"system\"]))\n        .execute(shell)\n\n      await init.then(testNodeVersion(shell, \"custom\")).execute(shell)\n    })\n  })\n\n  async function writeCustomNode() {\n    const customNode = path.join(testBinDir(), \"node\")\n    if (process.platform === \"win32\" && [WinCmd, PowerShell].includes(shell)) {\n      await fs.writeFile(customNode + \".cmd\", \"@echo custom\")\n    } else {\n      await fs.writeFile(customNode, `#!/bin/bash\\n\\necho \"custom\"\\n`)\n      // set executable\n      await fs.chmod(customNode, 0o766)\n    }\n  }\n}\n"
  },
  {
    "path": "e2e/uninstall.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, Zsh } from \"./shellcode/shells.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell]) {\n  describe(shell, () => {\n    test(`uninstalls a version`, async () => {\n      await script(shell)\n        .then(shell.call(\"fnm\", [\"i\", \"12.0.0\"]))\n        .then(shell.call(\"fnm\", [\"alias\", \"12.0.0\", \"hello\"]))\n        .then(\n          shell.scriptOutputContains(\n            shell.scriptOutputContains(shell.call(\"fnm\", [\"ls\"]), \"v12.0.0\"),\n            \"hello\"\n          )\n        )\n        .then(shell.call(\"fnm\", [\"uni\", \"hello\"]))\n        .then(\n          shell.hasCommandOutput(\n            shell.call(\"fnm\", [\"ls\"]),\n            \"* system\",\n            \"fnm ls\"\n          )\n        )\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/use-on-cd.test.ts",
    "content": "import { writeFile, mkdir } from \"node:fs/promises\"\nimport { join } from \"node:path\"\nimport { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testCwd from \"./shellcode/test-cwd.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport describe from \"./describe.js\"\n\nfor (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n  describe(shell, () => {\n    test(`use on cd`, async () => {\n      await mkdir(join(testCwd(), \"subdir\"), { recursive: true })\n      await writeFile(join(testCwd(), \"subdir\", \".node-version\"), \"v12.22.12\")\n      await script(shell)\n        .then(shell.env({ useOnCd: true }))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v12.22.12\"]))\n        .then(shell.call(\"cd\", [\"subdir\"]))\n        .then(testNodeVersion(shell, \"v12.22.12\"))\n        .takeSnapshot(shell)\n        .execute(shell)\n    })\n\n    test(`uses current directory version immediately on env setup`, async () => {\n      await writeFile(join(testCwd(), \".node-version\"), \"v12.22.12\")\n      await script(shell)\n        .then(shell.env({}))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v12.22.12\"]))\n        .then(shell.call(\"fnm\", [\"use\", \"v8.11.3\"]))\n        .then(shell.env({ useOnCd: true }))\n        .then(testNodeVersion(shell, \"v12.22.12\"))\n        .execute(shell)\n    })\n\n    test(`with resolve-engines`, async () => {\n      await mkdir(join(testCwd(), \"subdir\"), { recursive: true })\n      await writeFile(\n        join(testCwd(), \"subdir\", \"package.json\"),\n        JSON.stringify({\n          name: \"hello\",\n          engines: {\n            node: \"v12.22.12\",\n          },\n        }),\n      )\n      await script(shell)\n        .then(shell.env({ useOnCd: true, resolveEngines: true }))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v12.22.12\"]))\n        .then(shell.call(\"cd\", [\"subdir\"]))\n        .then(testNodeVersion(shell, \"v12.22.12\"))\n        .execute(shell)\n    })\n\n    test(`works after sourcing env twice`, async () => {\n      await mkdir(join(testCwd(), \"subdir\"), { recursive: true })\n      await writeFile(join(testCwd(), \"subdir\", \".node-version\"), \"v12.22.12\")\n      await script(shell)\n        .then(shell.env({ useOnCd: true }))\n        .then(shell.env({ useOnCd: true }))\n        .then(shell.call(\"fnm\", [\"install\", \"v8.11.3\"]))\n        .then(shell.call(\"fnm\", [\"install\", \"v12.22.12\"]))\n        .then(shell.call(\"cd\", [\"subdir\"]))\n        .then(testNodeVersion(shell, \"v12.22.12\"))\n        .execute(shell)\n    })\n\n    test(`doesn't throw on missing env data`, async () => {\n      await mkdir(join(testCwd(), \"subdir\"), { recursive: true })\n      await writeFile(\n        join(testCwd(), \"subdir\", \"package.json\"),\n        JSON.stringify({\n          name: \"hello\",\n        }),\n      )\n      await script(shell)\n        .then(shell.env({ useOnCd: true, resolveEngines: true }))\n        .then(shell.call(\"cd\", [\"subdir\"]))\n        .execute(shell)\n    })\n  })\n}\n"
  },
  {
    "path": "e2e/windows-scoop.test.ts",
    "content": "import { script } from \"./shellcode/script.js\"\nimport { Bash, Fish, PowerShell, WinCmd, Zsh } from \"./shellcode/shells.js\"\nimport testNodeVersion from \"./shellcode/test-node-version.js\"\nimport describe from \"./describe.js\"\nimport os from \"node:os\"\nimport { execa } from \"execa\"\n\nif (os.platform() !== \"win32\") {\n  test.skip(\"scoop shims only work on Windows\", () => {})\n} else {\n  beforeAll(async () => {\n    // Create a scoop shim for tests\n    await execa(`scoop`, [\n      \"shim\",\n      \"add\",\n      \"fnm_release\",\n      \"target/release/fnm.exe\",\n    ])\n  })\n\n  for (const shell of [Bash, Zsh, Fish, PowerShell, WinCmd]) {\n    describe(shell, () => {\n      test(`scoop shims infer the shell`, async () => {\n        await script(shell)\n          .then(shell.env({ executableName: \"fnm_release\" }))\n          .then(shell.call(\"fnm_release\", [\"install\", \"v20.14.0\"]))\n          .then(shell.call(\"fnm_release\", [\"use\", \"v20.14.0\"]))\n          .then(testNodeVersion(shell, \"v20.14.0\"))\n          .execute(shell)\n      })\n    })\n  }\n}\n"
  },
  {
    "path": "fnm-manifest.rc",
    "content": "#define RT_MANIFEST 24\n1 RT_MANIFEST \"fnm.manifest\""
  },
  {
    "path": "fnm.manifest",
    "content": "<?xml version='1.0' encoding='utf-8' standalone='yes'?>\n<assembly\n    xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n    manifestVersion=\"1.0\"\n    >\n  <application xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n    <windowsSettings>\n      <longPathAware xmlns=\"http://schemas.microsoft.com/SMI/2016/WindowsSettings\">true</longPathAware>\n    </windowsSettings>\n  </application>\n</assembly>\n"
  },
  {
    "path": "jest.config.cjs",
    "content": "/** @type {import('ts-jest').JestConfigWithTsJest} */\nmodule.exports = {\n  preset: \"ts-jest/presets/default-esm\",\n  globalSetup: \"./jest.global-setup.js\",\n  globalTeardown: \"./jest.global-teardown.js\",\n  testEnvironment: \"node\",\n  testTimeout: 120000,\n  extensionsToTreatAsEsm: [\".ts\"],\n  testPathIgnorePatterns: [\"/node_modules/\", \"/dist/\", \"/target/\"],\n  moduleNameMapper: {\n    \"^(\\\\.{1,2}/.*)\\\\.js$\": \"$1\",\n    \"#ansi-styles\": \"ansi-styles/index.js\",\n    \"#supports-color\": \"supports-color/index.js\",\n  },\n  transform: {\n    // '^.+\\\\.[tj]sx?$' to process js/ts with `ts-jest`\n    // '^.+\\\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`\n    \"^.+\\\\.tsx?$\": [\n      \"ts-jest\",\n      {\n        useESM: true,\n      },\n    ],\n  },\n}\n"
  },
  {
    "path": "jest.global-setup.js",
    "content": "import { server } from \"./tests/proxy-server/index.mjs\"\n\nexport default function () {\n  server.listen(8080)\n}\n"
  },
  {
    "path": "jest.global-teardown.js",
    "content": "import { server } from \"./tests/proxy-server/index.mjs\"\n\nexport default () => {\n  server.close()\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"fnm\",\n  \"version\": \"1.39.0\",\n  \"private\": true,\n  \"repository\": \"git@github.com:Schniz/fnm.git\",\n  \"author\": \"Gal Schlezinger <gal@spitfire.co.il>\",\n  \"type\": \"module\",\n  \"packageManager\": \"pnpm@9.1.4\",\n  \"license\": \"GPLv3\",\n  \"scripts\": {\n    \"test\": \"cross-env NODE_OPTIONS='--experimental-vm-modules' jest\",\n    \"version:prepare\": \"changeset version && ./.ci/prepare-version.js\",\n    \"generate-command-docs\": \"./.ci/print-command-docs.js\"\n  },\n  \"changelog\": {\n    \"repo\": \"Schniz/fnm\",\n    \"labels\": {\n      \"PR: New Feature\": \"New Feature 🎉\",\n      \"PR: Bugfix\": \"Bugfix 🐛\",\n      \"PR: Internal\": \"Internal 🛠\",\n      \"PR: Documentation\": \"Documentation 📝\"\n    }\n  },\n  \"devDependencies\": {\n    \"@changesets/changelog-github\": \"0.5.1\",\n    \"@changesets/cli\": \"2.28.0\",\n    \"@types/jest\": \"^29.2.3\",\n    \"@types/node\": \"^18.11.9\",\n    \"@types/shell-escape\": \"^0.2.1\",\n    \"chalk\": \"^5.1.2\",\n    \"cmd-ts\": \"0.13.0\",\n    \"cross-env\": \"^7.0.3\",\n    \"execa\": \"7.2.0\",\n    \"jest\": \"^29.3.1\",\n    \"lerna-changelog\": \"2.2.0\",\n    \"node-fetch\": \"^3.3.0\",\n    \"p-retry\": \"^6.2.0\",\n    \"prettier\": \"3.5.1\",\n    \"pv\": \"1.0.1\",\n    \"shell-escape\": \"^0.2.0\",\n    \"svg-term-cli\": \"2.1.1\",\n    \"toml\": \"3.0.0\",\n    \"ts-dedent\": \"^2.2.0\",\n    \"ts-jest\": \"^29.0.3\",\n    \"typescript\": \"^5.0.0\",\n    \"which\": \"^3.0.1\",\n    \"zod\": \"^3.19.1\"\n  },\n  \"prettier\": {\n    \"semi\": false\n  }\n}\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n  \"extends\": [\"config:base\"],\n  \"labels\": [\"PR: Dependency Update\"],\n  \"packageRules\": [\n    {\n      \"packagePatterns\": [\"*\"],\n      \"minor\": {\n        \"groupName\": \"all non-major dependencies\",\n        \"groupSlug\": \"all-minor-patch\"\n      }\n    },\n    {\n      \"matchPackagePatterns\": [\"serde\", \"serde_json\"],\n      \"groupName\": \"serde\",\n      \"groupSlug\": \"serde\"\n    },\n    {\n      \"matchPackagePatterns\": [\"clap\", \"clap_*\"],\n      \"groupName\": \"clap-rs\",\n      \"groupSlug\": \"clap-rs\"\n    },\n    {\n      \"matchDepTypes\": [\"devDependencies\", \"dev-dependencies\"],\n      \"matchPackagePatterns\": [\"*\"],\n      \"automerge\": true,\n      \"groupName\": \"all dev dependencies\",\n      \"groupSlug\": \"all-dev-dependencies\"\n    },\n    {\n      \"matchPackagePatterns\": [\"uraimo/run-on-arch-action\"],\n      \"matchManagers\": [\"github-actions\"],\n      \"allowedVersions\": \"2.1.2\"\n    }\n  ],\n  \"lockFileMaintenance\": { \"enabled\": true }\n}\n"
  },
  {
    "path": "rust-toolchain.toml",
    "content": "[toolchain]\nchannel = \"1.88\"\ncomponents = [\"rustfmt\", \"clippy\"]\n"
  },
  {
    "path": "site/package.json",
    "content": "{\n  \"name\": \"fnm\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.js\",\n  \"author\": \"Gal Schlezinger\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"build\": \"rm -rf public; mkdir public; cp ../.ci/install.sh ./public/install.txt\"\n  }\n}\n"
  },
  {
    "path": "site/vercel.json",
    "content": "{\n  \"$schema\": \"https://openapi.vercel.sh/vercel.json\",\n  \"github\": {\n    \"silent\": true\n  },\n  \"redirects\": [\n    { \"source\": \"/\", \"destination\": \"https://github.com/Schniz/fnm\" }\n  ],\n  \"rewrites\": [{ \"source\": \"/install\", \"destination\": \"/install.txt\" }],\n  \"headers\": [\n    {\n      \"source\": \"/install\",\n      \"headers\": [\n        {\n          \"key\": \"Cache-Control\",\n          \"value\": \"public, max-age=3600\"\n        }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "src/alias.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::fs::{remove_symlink_dir, shallow_read_symlink, symlink_dir};\nuse crate::system_version;\nuse crate::version::Version;\nuse std::convert::TryInto;\nuse std::path::PathBuf;\n\npub fn create_alias(\n    config: &FnmConfig,\n    common_name: &str,\n    version: &Version,\n) -> std::io::Result<()> {\n    let aliases_dir = config.aliases_dir();\n    std::fs::create_dir_all(&aliases_dir)?;\n\n    let version_dir = version.installation_path(config);\n    let alias_dir = aliases_dir.join(common_name);\n\n    remove_symlink_dir(&alias_dir).ok();\n    symlink_dir(version_dir, &alias_dir)?;\n\n    Ok(())\n}\n\npub fn list_aliases(config: &FnmConfig) -> std::io::Result<Vec<StoredAlias>> {\n    let vec: Vec<_> = std::fs::read_dir(config.aliases_dir())?\n        .filter_map(Result::ok)\n        .filter_map(|x| TryInto::<StoredAlias>::try_into(x.path().as_path()).ok())\n        .collect();\n    Ok(vec)\n}\n\npub fn get_alias_by_name(config: &FnmConfig, alias_name: &str) -> Option<StoredAlias> {\n    let alias_path = config.aliases_dir().join(alias_name);\n    TryInto::<StoredAlias>::try_into(alias_path.as_path()).ok()\n}\n\n#[derive(Debug)]\npub struct StoredAlias {\n    alias_path: PathBuf,\n    destination_path: PathBuf,\n}\n\nimpl std::convert::TryInto<StoredAlias> for &std::path::Path {\n    type Error = std::io::Error;\n\n    fn try_into(self) -> Result<StoredAlias, Self::Error> {\n        let shallow_self = shallow_read_symlink(self)?;\n        let destination_path = if shallow_self == system_version::path() {\n            shallow_self\n        } else {\n            std::fs::canonicalize(&shallow_self)?\n        };\n        Ok(StoredAlias {\n            alias_path: PathBuf::from(self),\n            destination_path,\n        })\n    }\n}\n\nimpl StoredAlias {\n    pub fn s_ver(&self) -> &str {\n        if self.destination_path == system_version::path() {\n            system_version::display_name()\n        } else {\n            self.destination_path\n                .parent()\n                .unwrap()\n                .file_name()\n                .expect(\"must have basename\")\n                .to_str()\n                .unwrap()\n        }\n    }\n\n    pub fn name(&self) -> &str {\n        self.alias_path\n            .file_name()\n            .expect(\"must have basename\")\n            .to_str()\n            .unwrap()\n    }\n\n    pub fn path(&self) -> &std::path::Path {\n        &self.alias_path\n    }\n}\n"
  },
  {
    "path": "src/arch.rs",
    "content": "use crate::version::Version;\n\n#[derive(Clone, Copy, PartialEq, Eq, Debug)]\npub enum Arch {\n    X86,\n    X64,\n    X64Musl,\n    X64Glibc217,\n    Arm64,\n    Armv7l,\n    Ppc64le,\n    Ppc64,\n    S390x,\n}\n\nimpl Arch {\n    pub fn as_str(self) -> &'static str {\n        match self {\n            Arch::X86 => \"x86\",\n            Arch::X64 => \"x64\",\n            Arch::X64Musl => \"x64-musl\",\n            Arch::X64Glibc217 => \"x64-glibc-217\",\n            Arch::Arm64 => \"arm64\",\n            Arch::Armv7l => \"armv7l\",\n            Arch::Ppc64le => \"ppc64le\",\n            Arch::Ppc64 => \"ppc64\",\n            Arch::S390x => \"s390x\",\n        }\n    }\n}\n\n#[cfg(unix)]\n/// handle common case: Apple Silicon / Node < 16\npub fn get_safe_arch(arch: Arch, version: &Version) -> Arch {\n    use crate::system_info::{platform_arch, platform_name};\n\n    match (platform_name(), platform_arch(), version) {\n        (\"darwin\", \"arm64\", Version::Semver(v)) if v.major < 16 => Arch::X64,\n        _ => arch,\n    }\n}\n\n#[cfg(windows)]\n/// handle common case: Apple Silicon / Node < 16\npub fn get_safe_arch(arch: Arch, _version: &Version) -> Arch {\n    arch\n}\n\nimpl Default for Arch {\n    fn default() -> Arch {\n        match crate::system_info::platform_arch().parse() {\n            Ok(arch) => arch,\n            Err(e) => panic!(\"{}\", e.details),\n        }\n    }\n}\n\nimpl std::str::FromStr for Arch {\n    type Err = ArchError;\n    fn from_str(s: &str) -> Result<Arch, Self::Err> {\n        match s {\n            \"x86\" => Ok(Arch::X86),\n            \"x64\" => Ok(Arch::X64),\n            \"x64-musl\" => Ok(Arch::X64Musl),\n            \"x64-glibc-217\" => Ok(Arch::X64Glibc217),\n            \"arm64\" => Ok(Arch::Arm64),\n            \"armv7l\" => Ok(Arch::Armv7l),\n            \"ppc64le\" => Ok(Arch::Ppc64le),\n            \"ppc64\" => Ok(Arch::Ppc64),\n            \"s390x\" => Ok(Arch::S390x),\n            unknown => Err(ArchError::new(format!(\"Unknown Arch: {unknown}\"))),\n        }\n    }\n}\n\nimpl std::fmt::Display for Arch {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_str(self.as_str())\n    }\n}\n\n#[derive(Debug)]\npub struct ArchError {\n    details: String,\n}\n\nimpl ArchError {\n    fn new(msg: String) -> ArchError {\n        ArchError { details: msg }\n    }\n}\n\nimpl std::fmt::Display for ArchError {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_str(&self.details)\n    }\n}\n\nimpl std::error::Error for ArchError {\n    fn description(&self) -> &str {\n        &self.details\n    }\n}\n"
  },
  {
    "path": "src/archive/extract.rs",
    "content": "use std::error::Error as StdError;\nuse std::path::Path;\n\n#[derive(Debug)]\npub enum Error {\n    IoError(std::io::Error),\n    ZipError(zip::result::ZipError),\n    HttpError(crate::http::Error),\n}\n\nimpl std::fmt::Display for Error {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Self::IoError(x) => x.fmt(f),\n            Self::ZipError(x) => x.fmt(f),\n            Self::HttpError(x) => x.fmt(f),\n        }\n    }\n}\n\nimpl StdError for Error {}\n\nimpl From<std::io::Error> for Error {\n    fn from(err: std::io::Error) -> Self {\n        Self::IoError(err)\n    }\n}\n\nimpl From<zip::result::ZipError> for Error {\n    fn from(err: zip::result::ZipError) -> Self {\n        Self::ZipError(err)\n    }\n}\n\nimpl From<crate::http::Error> for Error {\n    fn from(err: crate::http::Error) -> Self {\n        Self::HttpError(err)\n    }\n}\n\npub trait Extract {\n    fn extract_into(self: Box<Self>, path: &Path) -> Result<(), Error>;\n}\n"
  },
  {
    "path": "src/archive/mod.rs",
    "content": "pub mod extract;\npub mod tar;\npub mod zip;\n\nuse std::io::Read;\nuse std::path::Path;\n\npub use self::extract::{Error, Extract};\n#[cfg(unix)]\nuse self::tar::Tar;\n\n#[cfg(windows)]\nuse self::zip::Zip;\n\npub enum Archive {\n    #[cfg(windows)]\n    Zip,\n    #[cfg(unix)]\n    TarXz,\n    #[cfg(unix)]\n    TarGz,\n}\n\nimpl Archive {\n    pub fn extract_archive_into(&self, path: &Path, response: impl Read) -> Result<(), Error> {\n        let extractor: Box<dyn Extract> = match self {\n            #[cfg(windows)]\n            Self::Zip => Box::new(Zip::new(response)),\n            #[cfg(unix)]\n            Self::TarXz => Box::new(Tar::Xz(response)),\n            #[cfg(unix)]\n            Self::TarGz => Box::new(Tar::Gz(response)),\n        };\n        extractor.extract_into(path)?;\n        Ok(())\n    }\n\n    pub fn file_extension(&self) -> &'static str {\n        match self {\n            #[cfg(windows)]\n            Self::Zip => \"zip\",\n            #[cfg(unix)]\n            Self::TarXz => \"tar.xz\",\n            #[cfg(unix)]\n            Self::TarGz => \"tar.gz\",\n        }\n    }\n\n    #[cfg(windows)]\n    pub fn supported() -> &'static [Self] {\n        &[Self::Zip]\n    }\n\n    #[cfg(unix)]\n    pub fn supported() -> &'static [Self] {\n        &[Self::TarXz, Self::TarGz]\n    }\n}\n"
  },
  {
    "path": "src/archive/tar.rs",
    "content": "use super::{extract::Error, Extract};\nuse std::{io::Read, path::Path};\n\npub enum Tar<R: Read> {\n    /// Tar archive with XZ compression\n    Xz(R),\n    /// Tar archive with Gzip compression\n    Gz(R),\n}\n\nimpl<R: Read> Tar<R> {\n    fn extract_into_impl<P: AsRef<Path>>(self, path: P) -> Result<(), Error> {\n        let stream: Box<dyn Read> = match self {\n            Self::Xz(response) => Box::new(xz2::read::XzDecoder::new(response)),\n            Self::Gz(response) => Box::new(flate2::read::GzDecoder::new(response)),\n        };\n        let mut tar_archive = tar::Archive::new(stream);\n        tar_archive.unpack(&path)?;\n        Ok(())\n    }\n}\n\nimpl<R: Read> Extract for Tar<R> {\n    fn extract_into(self: Box<Self>, path: &Path) -> Result<(), Error> {\n        self.extract_into_impl(path)\n    }\n}\n"
  },
  {
    "path": "src/archive/zip.rs",
    "content": "use super::extract::{Error, Extract};\nuse log::debug;\nuse std::fs;\nuse std::io::{self, Read};\nuse std::path::Path;\nuse tempfile::tempfile;\nuse zip::read::ZipArchive;\n\npub struct Zip<R: Read> {\n    response: R,\n}\n\nimpl<R: Read> Zip<R> {\n    #[allow(dead_code)]\n    pub fn new(response: R) -> Self {\n        Self { response }\n    }\n}\n\nimpl<R: Read> Extract for Zip<R> {\n    fn extract_into(mut self: Box<Self>, path: &Path) -> Result<(), Error> {\n        let mut tmp_zip_file = tempfile().expect(\"Can't get a temporary file\");\n\n        debug!(\"Created a temporary zip file\");\n        io::copy(&mut self.response, &mut tmp_zip_file)?;\n        debug!(\n            \"Wrote zipfile successfully. Now extracting into {}.\",\n            path.display()\n        );\n\n        let mut archive = ZipArchive::new(&mut tmp_zip_file)?;\n\n        for i in 0..archive.len() {\n            let mut file = archive.by_index(i)?;\n            let outpath = path.join(file.mangled_name());\n\n            {\n                let comment = file.comment();\n                if !comment.is_empty() {\n                    debug!(\"File {} comment: {}\", i, comment);\n                }\n            }\n\n            if file.name().ends_with('/') {\n                debug!(\n                    \"File {} extracted to \\\"{}\\\"\",\n                    i,\n                    outpath.as_path().display()\n                );\n                fs::create_dir_all(&outpath)?;\n            } else {\n                debug!(\n                    \"Extracting file {} to \\\"{}\\\" ({} bytes)\",\n                    i,\n                    outpath.as_path().display(),\n                    file.size()\n                );\n                if let Some(p) = outpath.parent() {\n                    if !p.exists() {\n                        fs::create_dir_all(p)?;\n                    }\n                }\n                let mut outfile = fs::File::create(&outpath)?;\n                io::copy(&mut file, &mut outfile)?;\n            }\n\n            // Get and Set permissions\n            #[cfg(unix)]\n            {\n                use std::os::unix::fs::PermissionsExt;\n\n                if let Some(mode) = file.unix_mode() {\n                    fs::set_permissions(&outpath, fs::Permissions::from_mode(mode))?;\n                }\n            }\n        }\n\n        Ok(())\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test_log::test]\n    fn test_zip_extraction() {\n        let temp_dir = &tempfile::tempdir().expect(\"Can't create a temp directory\");\n        let response = crate::http::get(\"https://nodejs.org/dist/v12.0.0/node-v12.0.0-win-x64.zip\")\n            .expect(\"Can't make request to Node v12.0.0 zip file\");\n        Box::new(Zip::new(response))\n            .extract_into(temp_dir.as_ref())\n            .expect(\"Can't unzip files\");\n        let node_file = temp_dir\n            .as_ref()\n            .join(\"node-v12.0.0-win-x64\")\n            .join(\"node.exe\");\n        assert!(node_file.exists());\n    }\n}\n"
  },
  {
    "path": "src/choose_version_for_user_input.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::fs;\nuse crate::installed_versions;\nuse crate::system_version;\nuse crate::user_version::UserVersion;\nuse crate::version::Version;\nuse colored::Colorize;\nuse log::info;\nuse std::path::{Path, PathBuf};\nuse thiserror::Error;\n\n#[derive(Debug)]\npub struct ApplicableVersion {\n    path: PathBuf,\n    version: Version,\n}\n\nimpl ApplicableVersion {\n    pub fn path(&self) -> &Path {\n        &self.path\n    }\n\n    pub fn version(&self) -> &Version {\n        &self.version\n    }\n}\n\npub fn choose_version_for_user_input<'a>(\n    requested_version: &'a UserVersion,\n    config: &'a FnmConfig,\n) -> Result<Option<ApplicableVersion>, Error> {\n    let all_versions = installed_versions::list(config.installations_dir())\n        .map_err(|source| Error::VersionListing { source })?;\n\n    let result = if let UserVersion::Full(Version::Bypassed) = requested_version {\n        info!(\n            \"Bypassing fnm: using {} node\",\n            system_version::display_name().cyan()\n        );\n        Some(ApplicableVersion {\n            path: system_version::path(),\n            version: Version::Bypassed,\n        })\n    } else if let Some(alias_name) = requested_version.alias_name() {\n        let alias_path = config.aliases_dir().join(&alias_name);\n        let system_path = system_version::path();\n        if matches!(fs::shallow_read_symlink(&alias_path), Ok(shallow_path) if shallow_path == system_path)\n        {\n            info!(\n                \"Bypassing fnm: using {} node\",\n                system_version::display_name().cyan()\n            );\n            Some(ApplicableVersion {\n                path: alias_path,\n                version: Version::Bypassed,\n            })\n        } else if alias_path.exists() {\n            info!(\"Using Node for alias {}\", alias_name.cyan());\n            Some(ApplicableVersion {\n                path: alias_path,\n                version: Version::Alias(alias_name),\n            })\n        } else {\n            return Err(Error::CantFindVersion {\n                requested_version: requested_version.clone(),\n            });\n        }\n    } else {\n        let current_version = requested_version.to_version(&all_versions, config);\n        current_version.map(|version| {\n            info!(\"Using Node {}\", version.to_string().cyan());\n            let path = config\n                .installations_dir()\n                .join(version.to_string())\n                .join(\"installation\");\n\n            ApplicableVersion {\n                path,\n                version: version.clone(),\n            }\n        })\n    };\n\n    Ok(result)\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't find requested version: {}\", requested_version)]\n    CantFindVersion { requested_version: UserVersion },\n    #[error(\"Can't list local installed versions: {}\", source)]\n    VersionListing { source: installed_versions::Error },\n}\n"
  },
  {
    "path": "src/cli.rs",
    "content": "use crate::commands;\nuse crate::commands::command::Command;\nuse crate::config::FnmConfig;\nuse clap::Parser;\n\n#[derive(clap::Parser, Debug)]\npub enum SubCommand {\n    /// List all remote Node.js versions\n    #[clap(name = \"list-remote\", bin_name = \"list-remote\", visible_aliases = &[\"ls-remote\"])]\n    LsRemote(commands::ls_remote::LsRemote),\n\n    /// List all locally installed Node.js versions\n    #[clap(name = \"list\", bin_name = \"list\", visible_aliases = &[\"ls\"])]\n    LsLocal(commands::ls_local::LsLocal),\n\n    /// Install a new Node.js version\n    #[clap(name = \"install\", bin_name = \"install\", visible_aliases = &[\"i\"])]\n    Install(commands::install::Install),\n\n    /// Change Node.js version\n    #[clap(name = \"use\", bin_name = \"use\")]\n    Use(commands::r#use::Use),\n\n    /// Print and set up required environment variables for fnm\n    ///\n    /// This command generates a series of shell commands that\n    /// should be evaluated by your shell to create a fnm-ready environment.\n    ///\n    /// Each shell has its own syntax of evaluating a dynamic expression.\n    /// For example, evaluating fnm on Bash and Zsh would look like `eval \"$(fnm env --shell bash)\"`.\n    /// In Fish, evaluating would look like `fnm env --shell fish | source`\n    #[clap(name = \"env\", bin_name = \"env\")]\n    Env(commands::env::Env),\n\n    /// Print shell completions to stdout\n    #[clap(name = \"completions\", bin_name = \"completions\")]\n    Completions(commands::completions::Completions),\n\n    /// Alias a version to a common name\n    #[clap(name = \"alias\", bin_name = \"alias\")]\n    Alias(commands::alias::Alias),\n\n    /// Remove an alias definition\n    #[clap(name = \"unalias\", bin_name = \"unalias\")]\n    Unalias(commands::unalias::Unalias),\n\n    /// Set a version as the default version or get the current default version.\n    ///\n    /// This is a shorthand for `fnm alias VERSION default`\n    #[clap(name = \"default\", bin_name = \"default\")]\n    Default(commands::default::Default),\n\n    /// Print the current Node.js version\n    #[clap(name = \"current\", bin_name = \"current\")]\n    Current(commands::current::Current),\n\n    /// Run a command within fnm context\n    ///\n    /// Example:\n    /// --------\n    /// fnm exec --using=v12.0.0 node --version\n    /// => v12.0.0\n    #[clap(name = \"exec\", bin_name = \"exec\", verbatim_doc_comment)]\n    Exec(commands::exec::Exec),\n\n    /// Uninstall a Node.js version\n    ///\n    /// > Warning: when providing an alias, it will remove the Node version the alias\n    /// > is pointing to, along with the other aliases that point to the same version.\n    #[clap(name = \"uninstall\", bin_name = \"uninstall\", visible_aliases = &[\"uni\"])]\n    Uninstall(commands::uninstall::Uninstall),\n}\n\nimpl SubCommand {\n    pub fn call(self, config: FnmConfig) {\n        match self {\n            Self::LsLocal(cmd) => cmd.call(config),\n            Self::LsRemote(cmd) => cmd.call(config),\n            Self::Install(cmd) => cmd.call(config),\n            Self::Env(cmd) => cmd.call(config),\n            Self::Use(cmd) => cmd.call(config),\n            Self::Completions(cmd) => cmd.call(config),\n            Self::Alias(cmd) => cmd.call(config),\n            Self::Default(cmd) => cmd.call(config),\n            Self::Current(cmd) => cmd.call(config),\n            Self::Exec(cmd) => cmd.call(config),\n            Self::Uninstall(cmd) => cmd.call(config),\n            Self::Unalias(cmd) => cmd.call(config),\n        }\n    }\n}\n\n/// A fast and simple Node.js manager.\n#[derive(clap::Parser, Debug)]\n#[clap(name = \"fnm\", version = env!(\"CARGO_PKG_VERSION\"), bin_name = \"fnm\")]\npub struct Cli {\n    #[clap(flatten)]\n    pub config: FnmConfig,\n    #[clap(subcommand)]\n    pub subcmd: SubCommand,\n}\n\npub fn parse() -> Cli {\n    Cli::parse()\n}\n"
  },
  {
    "path": "src/commands/alias.rs",
    "content": "use super::command::Command;\nuse crate::alias::create_alias;\nuse crate::choose_version_for_user_input::{\n    choose_version_for_user_input, Error as ApplicableVersionError,\n};\nuse crate::config::FnmConfig;\nuse crate::user_version::UserVersion;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct Alias {\n    pub(crate) to_version: UserVersion,\n    pub(crate) name: String,\n}\n\nimpl Command for Alias {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let applicable_version = choose_version_for_user_input(&self.to_version, config)\n            .map_err(|source| Error::CantUnderstandVersion { source })?\n            .ok_or(Error::VersionNotFound {\n                version: self.to_version,\n            })?;\n\n        create_alias(config, &self.name, applicable_version.version())\n            .map_err(|source| Error::CantCreateSymlink { source })?;\n\n        Ok(())\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't create symlink for alias: {}\", source)]\n    CantCreateSymlink { source: std::io::Error },\n    #[error(\"Version {} not found locally\", version)]\n    VersionNotFound { version: UserVersion },\n    #[error(transparent)]\n    CantUnderstandVersion { source: ApplicableVersionError },\n    #[error(\"A default version has not been set.\")]\n    DefaultAliasDoesNotExist,\n}\n"
  },
  {
    "path": "src/commands/command.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::outln;\nuse colored::Colorize;\n\npub trait Command: Sized {\n    type Error: std::error::Error;\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error>;\n\n    fn handle_error(err: Self::Error, config: &FnmConfig) {\n        let err_s = format!(\"{err}\");\n        outln!(config, Error, \"{} {}\", \"error:\".red().bold(), err_s.red());\n        std::process::exit(1);\n    }\n\n    fn call(self, config: FnmConfig) {\n        match self.apply(&config) {\n            Ok(()) => (),\n            Err(err) => Self::handle_error(err, &config),\n        }\n    }\n}\n"
  },
  {
    "path": "src/commands/completions.rs",
    "content": "use super::command::Command;\nuse crate::config::FnmConfig;\nuse crate::shell::{infer_shell, Shell};\nuse crate::{cli::Cli, shell::Shells};\nuse clap::{CommandFactory, Parser, ValueEnum};\nuse clap_complete::{Generator, Shell as ClapShell};\nuse thiserror::Error;\n\n#[derive(Parser, Debug)]\npub struct Completions {\n    /// The shell syntax to use. Infers when missing.\n    #[clap(long)]\n    shell: Option<Shells>,\n}\n\nimpl Command for Completions {\n    type Error = Error;\n\n    fn apply(self, _config: &FnmConfig) -> Result<(), Self::Error> {\n        let mut stdio = std::io::stdout();\n        let shell: Box<dyn Shell> = self\n            .shell\n            .map(Into::into)\n            .or_else(|| infer_shell())\n            .ok_or(Error::CantInferShell)?;\n        let shell: ClapShell = shell.into();\n        let mut app = Cli::command();\n        app.build();\n        shell.generate(&app, &mut stdio);\n        Ok(())\n    }\n}\n\n#[derive(Error, Debug)]\npub enum Error {\n    #[error(\n        \"{}\\n{}\\n{}\\n{}\",\n        \"Can't infer shell!\",\n        \"fnm can't infer your shell based on the process tree.\",\n        \"Maybe it is unsupported? we support the following shells:\",\n        shells_as_string()\n    )]\n    CantInferShell,\n}\n\nfn shells_as_string() -> String {\n    Shells::value_variants()\n        .iter()\n        .map(|x| format!(\"* {x}\"))\n        .collect::<Vec<_>>()\n        .join(\"\\n\")\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    #[cfg(not(windows))]\n    fn test_smoke() {\n        let config = FnmConfig::default();\n        Completions {\n            shell: Some(Shells::Bash),\n        }\n        .call(config);\n    }\n}\n"
  },
  {
    "path": "src/commands/current.rs",
    "content": "use super::command::Command;\nuse crate::config::FnmConfig;\nuse crate::current_version::{current_version, Error};\n\n#[derive(clap::Parser, Debug)]\npub struct Current {}\n\nimpl Command for Current {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let version_string = match current_version(config)? {\n            Some(ver) => ver.v_str(),\n            None => \"none\".into(),\n        };\n        println!(\"{version_string}\");\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/commands/default.rs",
    "content": "use super::alias::Alias;\nuse super::command::Command;\nuse crate::alias::get_alias_by_name;\nuse crate::config::FnmConfig;\nuse crate::user_version::UserVersion;\n\n#[derive(clap::Parser, Debug)]\npub struct Default {\n    version: Option<UserVersion>,\n}\n\nimpl Command for Default {\n    type Error = super::alias::Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        match self.version {\n            Some(version) => Alias {\n                name: \"default\".into(),\n                to_version: version,\n            }\n            .apply(config),\n            None => match get_alias_by_name(config, \"default\") {\n                Some(alias) => {\n                    println!(\"{}\", alias.s_ver());\n                    Ok(())\n                }\n                None => Err(Self::Error::DefaultAliasDoesNotExist),\n            },\n        }\n    }\n\n    fn handle_error(err: Self::Error, config: &FnmConfig) {\n        Alias::handle_error(err, config);\n    }\n}\n"
  },
  {
    "path": "src/commands/env.rs",
    "content": "use super::command::Command;\nuse super::r#use::Use;\nuse crate::config::FnmConfig;\nuse crate::fs::symlink_dir;\nuse crate::outln;\nuse crate::path_ext::PathExt;\nuse crate::shell::{infer_shell, Shell, Shells};\nuse clap::ValueEnum;\nuse colored::Colorize;\nuse std::collections::HashMap;\nuse std::fmt::Debug;\nuse std::io::IsTerminal;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug, Default)]\npub struct Env {\n    /// The shell syntax to use. Infers when missing.\n    #[clap(long)]\n    shell: Option<Shells>,\n    /// Print JSON instead of shell commands.\n    #[clap(long, conflicts_with = \"shell\")]\n    json: bool,\n    /// Deprecated. This is the default now.\n    #[clap(long, hide = true)]\n    multi: bool,\n    /// Print the script to change Node versions every directory change\n    #[clap(long)]\n    use_on_cd: bool,\n}\n\nfn generate_symlink_path() -> String {\n    format!(\n        \"{}_{}\",\n        std::process::id(),\n        chrono::Utc::now().timestamp_millis(),\n    )\n}\n\nfn make_symlink(config: &FnmConfig) -> Result<std::path::PathBuf, Error> {\n    let base_dir = config.multishell_storage().ensure_exists_silently();\n    let mut temp_dir = base_dir.join(generate_symlink_path());\n\n    while temp_dir.exists() {\n        temp_dir = base_dir.join(generate_symlink_path());\n    }\n\n    match symlink_dir(config.default_version_dir(), &temp_dir) {\n        Ok(()) => Ok(temp_dir),\n        Err(source) => Err(Error::CantCreateSymlink { source, temp_dir }),\n    }\n}\n\n#[inline]\nfn bool_as_str(value: bool) -> &'static str {\n    if value {\n        \"true\"\n    } else {\n        \"false\"\n    }\n}\n\nfn set_path_for_multishell(multishell_path: &std::path::Path) {\n    let path_for_node = if cfg!(windows) {\n        multishell_path.to_path_buf()\n    } else {\n        multishell_path.join(\"bin\")\n    };\n\n    let current_path = std::env::var_os(\"PATH\").unwrap_or_default();\n    let mut split_paths: Vec<_> = std::env::split_paths(&current_path).collect();\n    split_paths.insert(0, path_for_node);\n    if let Ok(new_path) = std::env::join_paths(split_paths) {\n        unsafe {\n            std::env::set_var(\"PATH\", new_path);\n        }\n    }\n}\n\nimpl Command for Env {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        if self.multi {\n            outln!(\n                config,\n                Error,\n                \"{} {} is deprecated. This is now the default.\",\n                \"warning:\".yellow().bold(),\n                \"--multi\".italic()\n            );\n        }\n\n        let multishell_path = make_symlink(config)?;\n        let base_dir = config.base_dir_with_default();\n\n        let env_vars = [\n            (\"FNM_MULTISHELL_PATH\", multishell_path.to_str().unwrap()),\n            (\n                \"FNM_VERSION_FILE_STRATEGY\",\n                config.version_file_strategy().as_str(),\n            ),\n            (\"FNM_DIR\", base_dir.to_str().unwrap()),\n            (\"FNM_LOGLEVEL\", config.log_level().as_str()),\n            (\"FNM_NODE_DIST_MIRROR\", config.node_dist_mirror.as_str()),\n            (\n                \"FNM_COREPACK_ENABLED\",\n                bool_as_str(config.corepack_enabled()),\n            ),\n            (\"FNM_RESOLVE_ENGINES\", bool_as_str(config.resolve_engines())),\n            (\"FNM_ARCH\", config.arch.as_str()),\n        ];\n\n        if self.json {\n            println!(\n                \"{}\",\n                serde_json::to_string(&HashMap::from(env_vars)).unwrap()\n            );\n            return Ok(());\n        }\n\n        let shell: Box<dyn Shell> = self\n            .shell\n            .map(Into::into)\n            .or_else(infer_shell)\n            .ok_or(Error::CantInferShell)?;\n\n        let binary_path = if cfg!(windows) {\n            shell.path(&multishell_path)\n        } else {\n            shell.path(&multishell_path.join(\"bin\"))\n        };\n\n        println!(\"{}\", binary_path?);\n\n        for (name, value) in &env_vars {\n            println!(\"{}\", shell.set_env_var(name, value));\n        }\n\n        if self.use_on_cd {\n            // Call `use` internally for the initial directory, so the shell doesn't\n            // need to spawn a subprocess after evaluating the env output.\n            set_path_for_multishell(&multishell_path);\n            let config_with_multishell =\n                config.clone().with_multishell_path(multishell_path.clone());\n            let use_cmd = Use {\n                version: None,\n                install_if_missing: false,\n                silent_if_unchanged: true,\n                info_to_stderr: true,\n            };\n            let should_force_stderr_color = !std::io::stdout().is_terminal()\n                && std::io::stderr().is_terminal()\n                && std::env::var_os(\"NO_COLOR\").is_none();\n            if should_force_stderr_color {\n                colored::control::set_override(true);\n            }\n            // Ignore errors - if there's no version file, that's fine\n            let _ = use_cmd.apply(&config_with_multishell);\n            if should_force_stderr_color {\n                colored::control::unset_override();\n            }\n\n            println!(\"{}\", shell.use_on_cd(config)?);\n        }\n        if let Some(v) = shell.rehash() {\n            println!(\"{v}\");\n        }\n\n        Ok(())\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\n        \"{}\\n{}\\n{}\\n{}\",\n        \"Can't infer shell!\",\n        \"fnm can't infer your shell based on the process tree.\",\n        \"Maybe it is unsupported? we support the following shells:\",\n        shells_as_string()\n    )]\n    CantInferShell,\n    #[error(\"Can't create the symlink for multishells at {temp_dir:?}. Maybe there are some issues with permissions for the directory? {source}\")]\n    CantCreateSymlink {\n        #[source]\n        source: std::io::Error,\n        temp_dir: std::path::PathBuf,\n    },\n    #[error(transparent)]\n    ShellError {\n        #[from]\n        source: anyhow::Error,\n    },\n}\n\nfn shells_as_string() -> String {\n    Shells::value_variants()\n        .iter()\n        .map(|x| format!(\"* {x}\"))\n        .collect::<Vec<_>>()\n        .join(\"\\n\")\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_smoke() {\n        let config = FnmConfig::default();\n        Env {\n            #[cfg(windows)]\n            shell: Some(Shells::Cmd),\n            #[cfg(not(windows))]\n            shell: Some(Shells::Bash),\n            ..Default::default()\n        }\n        .call(config);\n    }\n}\n"
  },
  {
    "path": "src/commands/exec.rs",
    "content": "use super::command::Command as Cmd;\nuse crate::choose_version_for_user_input::{\n    choose_version_for_user_input, Error as UserInputError,\n};\nuse crate::config::FnmConfig;\nuse crate::outln;\nuse crate::user_version::UserVersion;\nuse crate::user_version_reader::UserVersionReader;\nuse colored::Colorize;\nuse std::process::{Command, Stdio};\nuse thiserror::Error;\n\n#[derive(Debug, clap::Parser)]\n#[clap(trailing_var_arg = true)]\npub struct Exec {\n    /// Either an explicit version, or a filename with the version written in it\n    #[clap(long = \"using\")]\n    version: Option<UserVersionReader>,\n    /// Deprecated. This is the default now.\n    #[clap(long = \"using-file\", hide = true)]\n    using_file: bool,\n    /// The command to run\n    arguments: Vec<String>,\n}\n\nimpl Exec {\n    pub(crate) fn new_for_version(\n        version: &crate::version::Version,\n        cmd: &str,\n        arguments: &[&str],\n    ) -> Self {\n        let reader = UserVersionReader::Direct(UserVersion::Full(version.clone()));\n        let args: Vec<_> = std::iter::once(cmd)\n            .chain(arguments.iter().copied())\n            .map(String::from)\n            .collect();\n        Self {\n            version: Some(reader),\n            using_file: false,\n            arguments: args,\n        }\n    }\n}\n\nimpl Cmd for Exec {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        if self.using_file {\n            outln!(\n                config,\n                Error,\n                \"{} {} is deprecated. This is now the default.\",\n                \"warning:\".yellow().bold(),\n                \"--using-file\".italic()\n            );\n        }\n\n        let (binary, arguments) = self\n            .arguments\n            .split_first()\n            .ok_or(Error::NoBinaryProvided)?;\n\n        let version = self\n            .version\n            .unwrap_or_else(|| {\n                let current_dir = std::env::current_dir().unwrap();\n                UserVersionReader::Path(current_dir)\n            })\n            .into_user_version(config)\n            .ok_or(Error::CantInferVersion)?;\n\n        let applicable_version = choose_version_for_user_input(&version, config)\n            .map_err(|source| Error::ApplicableVersionError { source })?\n            .ok_or(Error::VersionNotFound { version })?;\n\n        #[cfg(windows)]\n        let bin_path = applicable_version.path().to_path_buf();\n\n        #[cfg(unix)]\n        let bin_path = applicable_version.path().join(\"bin\");\n\n        let path_env = {\n            let paths_env = std::env::var_os(\"PATH\").ok_or(Error::CantReadPathVariable)?;\n            let mut paths: Vec<_> = std::env::split_paths(&paths_env).collect();\n            paths.insert(0, bin_path);\n            std::env::join_paths(paths)\n                .map_err(|source| Error::CantAddPathToEnvironment { source })?\n        };\n\n        log::debug!(\"Running {} with PATH={:?}\", binary, path_env);\n\n        let exit_status = Command::new(binary)\n            .args(arguments)\n            .stdin(Stdio::inherit())\n            .stdout(Stdio::inherit())\n            .stderr(Stdio::inherit())\n            .env(\"PATH\", path_env)\n            .spawn()\n            .map_err(|source| Error::CantSpawnProgram {\n                source,\n                binary: binary.to_string(),\n            })?\n            .wait()\n            .expect(\"Failed to grab exit code\");\n\n        let code = exit_status.code().ok_or(Error::CantReadProcessExitCode)?;\n        std::process::exit(code);\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't spawn program: {source}\\nMaybe the program {} does not exist on not available in PATH?\", binary.bold())]\n    CantSpawnProgram {\n        source: std::io::Error,\n        binary: String,\n    },\n    #[error(\"Can't read path environment variable\")]\n    CantReadPathVariable,\n    #[error(\"Can't add path to environment variable: {}\", source)]\n    CantAddPathToEnvironment { source: std::env::JoinPathsError },\n    #[error(\"Can't find version in dotfiles. Please provide a version manually to the command.\")]\n    CantInferVersion,\n    #[error(\"Requested version {} is not currently installed\", version)]\n    VersionNotFound { version: UserVersion },\n    #[error(transparent)]\n    ApplicableVersionError {\n        #[from]\n        source: UserInputError,\n    },\n    #[error(\"Can't read exit code from process.\\nMaybe the process was killed using a signal?\")]\n    CantReadProcessExitCode,\n    #[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())]\n    NoBinaryProvided,\n}\n"
  },
  {
    "path": "src/commands/install.rs",
    "content": "use super::command::Command;\nuse super::r#use::Use;\nuse crate::alias::create_alias;\nuse crate::arch::get_safe_arch;\nuse crate::config::FnmConfig;\nuse crate::downloader::{install_node_dist, Error as DownloaderError};\nuse crate::lts::LtsType;\nuse crate::outln;\nuse crate::progress::ProgressConfig;\nuse crate::remote_node_index;\nuse crate::user_version::UserVersion;\nuse crate::user_version_reader::UserVersionReader;\nuse crate::version::Version;\nuse crate::version_files::get_user_version_for_directory;\nuse colored::Colorize;\nuse log::debug;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug, Default)]\npub struct Install {\n    /// A version string. Can be a partial semver or a LTS version name by the format lts/NAME\n    pub version: Option<UserVersion>,\n\n    /// Install latest LTS\n    #[clap(long, conflicts_with_all = &[\"version\", \"latest\"])]\n    pub lts: bool,\n\n    /// Install latest version\n    #[clap(long, conflicts_with_all = &[\"version\", \"lts\"])]\n    pub latest: bool,\n\n    /// Show an interactive progress bar for the download\n    /// status.\n    #[clap(long, default_value_t)]\n    #[arg(value_enum)]\n    pub progress: ProgressConfig,\n\n    /// Use the installed version immediately after installation\n    #[clap(long)]\n    pub r#use: bool,\n}\n\nimpl Install {\n    fn version(self) -> Result<Option<UserVersion>, Error> {\n        match self {\n            Self {\n                version: v,\n                lts: false,\n                latest: false,\n                ..\n            } => Ok(v),\n            Self {\n                version: None,\n                lts: true,\n                latest: false,\n                ..\n            } => Ok(Some(UserVersion::Full(Version::Lts(LtsType::Latest)))),\n            Self {\n                version: None,\n                lts: false,\n                latest: true,\n                ..\n            } => Ok(Some(UserVersion::Full(Version::Latest))),\n            _ => Err(Error::TooManyVersionsProvided),\n        }\n    }\n}\n\nimpl Command for Install {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let current_dir = std::env::current_dir().unwrap();\n        let show_progress = self.progress.enabled(config);\n        let use_installed = self.r#use;\n\n        let current_version = self\n            .version()?\n            .or_else(|| get_user_version_for_directory(current_dir, config))\n            .ok_or(Error::CantInferVersion)?;\n\n        let version = match current_version.clone() {\n            UserVersion::Full(Version::Semver(actual_version)) => Version::Semver(actual_version),\n            UserVersion::Full(v @ (Version::Bypassed | Version::Alias(_))) => {\n                return Err(Error::UninstallableVersion { version: v });\n            }\n            UserVersion::Full(Version::Lts(lts_type)) => {\n                let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror)\n                    .map_err(|source| Error::CantListRemoteVersions { source })?;\n                let picked_version = lts_type\n                    .pick_latest(&available_versions)\n                    .ok_or_else(|| Error::CantFindRelevantLts {\n                        lts_type: lts_type.clone(),\n                    })?\n                    .version\n                    .clone();\n                debug!(\n                    \"Resolved {} into Node version {}\",\n                    Version::Lts(lts_type).v_str().cyan(),\n                    picked_version.v_str().cyan()\n                );\n                picked_version\n            }\n            UserVersion::Full(Version::Latest) => {\n                let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror)\n                    .map_err(|source| Error::CantListRemoteVersions { source })?;\n                let picked_version = available_versions\n                    .last()\n                    .ok_or(Error::CantFindLatest)?\n                    .version\n                    .clone();\n                debug!(\n                    \"Resolved {} into Node version {}\",\n                    Version::Latest.v_str().cyan(),\n                    picked_version.v_str().cyan()\n                );\n                picked_version\n            }\n            current_version => {\n                let available_versions: Vec<_> = remote_node_index::list(&config.node_dist_mirror)\n                    .map_err(|source| Error::CantListRemoteVersions { source })?\n                    .drain(..)\n                    .map(|x| x.version)\n                    .collect();\n\n                current_version\n                    .to_version(&available_versions, config)\n                    .ok_or(Error::CantFindNodeVersion {\n                        requested_version: current_version,\n                    })?\n                    .clone()\n            }\n        };\n\n        // Automatically swap Apple Silicon to x64 arch for appropriate versions.\n        let safe_arch = get_safe_arch(config.arch, &version);\n\n        let version_str = format!(\"Node {}\", &version);\n        outln!(\n            config,\n            Info,\n            \"Installing {} ({})\",\n            version_str.cyan(),\n            safe_arch.as_str()\n        );\n\n        match install_node_dist(\n            &version,\n            &config.node_dist_mirror,\n            config.installations_dir(),\n            safe_arch,\n            show_progress,\n        ) {\n            Err(err @ DownloaderError::VersionAlreadyInstalled { .. }) => {\n                outln!(config, Error, \"{} {}\", \"warning:\".bold().yellow(), err);\n            }\n            Err(source) => Err(Error::DownloadError { source })?,\n            Ok(()) => {}\n        }\n\n        if !config.default_version_dir().exists() {\n            debug!(\"Tagging {} as the default version\", version.v_str().cyan());\n            create_alias(config, \"default\", &version)?;\n        }\n\n        if let Some(tagged_alias) = current_version.inferred_alias() {\n            tag_alias(config, &version, &tagged_alias)?;\n        }\n\n        if config.corepack_enabled() {\n            outln!(config, Info, \"Enabling corepack for {}\", version_str.cyan());\n            enable_corepack(&version, config)?;\n        }\n\n        if use_installed {\n            use_installed_version(&version, config)?;\n        }\n\n        Ok(())\n    }\n}\n\nfn tag_alias(config: &FnmConfig, matched_version: &Version, alias: &Version) -> Result<(), Error> {\n    let alias_name = alias.v_str();\n    debug!(\n        \"Tagging {} as alias for {}\",\n        alias_name.cyan(),\n        matched_version.v_str().cyan()\n    );\n    create_alias(config, &alias_name, matched_version)?;\n\n    Ok(())\n}\n\nfn enable_corepack(version: &Version, config: &FnmConfig) -> Result<(), Error> {\n    let corepack_path = version.installation_path(config);\n    let corepack_path = if cfg!(windows) {\n        corepack_path.join(\"corepack.cmd\")\n    } else {\n        corepack_path.join(\"bin\").join(\"corepack\")\n    };\n    super::exec::Exec::new_for_version(version, corepack_path.to_str().unwrap(), &[\"enable\"])\n        .apply(config)\n        .map_err(|source| Error::CorepackError { source })?;\n    Ok(())\n}\n\nfn use_installed_version(version: &Version, config: &FnmConfig) -> Result<(), Error> {\n    Use {\n        version: Some(UserVersionReader::Direct(UserVersion::Full(\n            version.clone(),\n        ))),\n        install_if_missing: false,\n        silent_if_unchanged: false,\n        info_to_stderr: false,\n    }\n    .apply(config)\n    .map_err(|source| Error::UseError {\n        source: Box::new(source),\n    })?;\n    Ok(())\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't download the requested binary: {}\", source)]\n    DownloadError { source: DownloaderError },\n    #[error(transparent)]\n    IoError {\n        #[from]\n        source: std::io::Error,\n    },\n    #[error(\"Can't enable corepack: {source}\")]\n    CorepackError {\n        #[from]\n        source: super::exec::Error,\n    },\n    #[error(transparent)]\n    UseError {\n        source: Box<<Use as Command>::Error>,\n    },\n    #[error(\"Can't find version in dotfiles. Please provide a version manually to the command.\")]\n    CantInferVersion,\n    #[error(transparent)]\n    CantListRemoteVersions { source: remote_node_index::Error },\n    #[error(\n        \"Can't find a Node version that matches {} in remote\",\n        requested_version\n    )]\n    CantFindNodeVersion { requested_version: UserVersion },\n    #[error(\"Can't find relevant LTS named {}\", lts_type)]\n    CantFindRelevantLts { lts_type: crate::lts::LtsType },\n    #[error(\"Can't find any versions in the upstream version index.\")]\n    CantFindLatest,\n    #[error(\"The requested version is not installable: {}\", version.v_str())]\n    UninstallableVersion { version: Version },\n    #[error(\"Too many versions provided. Please don't use --lts with a version string.\")]\n    TooManyVersionsProvided,\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use pretty_assertions::assert_eq;\n    use std::str::FromStr;\n\n    #[test]\n    fn test_set_default_on_new_installation() {\n        let base_dir = tempfile::tempdir().unwrap();\n        let config = FnmConfig::default().with_base_dir(Some(base_dir.path().to_path_buf()));\n        assert!(!config.default_version_dir().exists());\n\n        Install {\n            version: UserVersion::from_str(\"12.0.0\").ok(),\n            lts: false,\n            latest: false,\n            progress: ProgressConfig::Never,\n            r#use: false,\n        }\n        .apply(&config)\n        .expect(\"Can't install\");\n\n        assert!(config.default_version_dir().exists());\n        assert_eq!(\n            config.default_version_dir().canonicalize().ok(),\n            config\n                .installations_dir()\n                .join(\"v12.0.0\")\n                .join(\"installation\")\n                .canonicalize()\n                .ok()\n        );\n    }\n\n    #[test]\n    fn test_install_latest() {\n        let base_dir = tempfile::tempdir().unwrap();\n        let config = FnmConfig::default().with_base_dir(Some(base_dir.path().to_path_buf()));\n\n        Install {\n            version: None,\n            lts: false,\n            latest: true,\n            progress: ProgressConfig::Never,\n            r#use: false,\n        }\n        .apply(&config)\n        .expect(\"Can't install\");\n\n        let available_versions: Vec<_> =\n            remote_node_index::list(&config.node_dist_mirror).expect(\"Can't get node version list\");\n        let latest_version = available_versions.last().unwrap().version.clone();\n\n        assert!(config.installations_dir().exists());\n        assert!(config\n            .installations_dir()\n            .join(latest_version.to_string())\n            .join(\"installation\")\n            .canonicalize()\n            .unwrap()\n            .exists());\n    }\n}\n"
  },
  {
    "path": "src/commands/ls_local.rs",
    "content": "use crate::alias::{list_aliases, StoredAlias};\nuse crate::config::FnmConfig;\nuse crate::current_version::current_version;\nuse crate::version::Version;\nuse colored::Colorize;\nuse std::collections::HashMap;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct LsLocal {}\n\nimpl super::command::Command for LsLocal {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let base_dir = config.installations_dir();\n        let mut versions = crate::installed_versions::list(base_dir)\n            .map_err(|source| Error::CantListLocallyInstalledVersion { source })?;\n        versions.insert(0, Version::Bypassed);\n        versions.sort();\n        let aliases_hash =\n            generate_aliases_hash(config).map_err(|source| Error::CantReadAliases { source })?;\n        let curr_version = current_version(config).ok().flatten();\n\n        for version in versions {\n            let version_aliases = match aliases_hash.get(&version.v_str()) {\n                None => String::new(),\n                Some(versions) => {\n                    let version_string = versions\n                        .iter()\n                        .map(StoredAlias::name)\n                        .collect::<Vec<_>>()\n                        .join(\", \");\n                    format!(\" {}\", version_string.dimmed())\n                }\n            };\n\n            let version_str = format!(\"* {version}{version_aliases}\");\n\n            if curr_version == Some(version) {\n                println!(\"{}\", version_str.cyan());\n            } else {\n                println!(\"{version_str}\");\n            }\n        }\n        Ok(())\n    }\n}\n\nfn generate_aliases_hash(config: &FnmConfig) -> std::io::Result<HashMap<String, Vec<StoredAlias>>> {\n    let mut aliases = list_aliases(config)?;\n    let mut hashmap: HashMap<String, Vec<StoredAlias>> = HashMap::with_capacity(aliases.len());\n    for alias in aliases.drain(..) {\n        if let Some(value) = hashmap.get_mut(alias.s_ver()) {\n            value.push(alias);\n        } else {\n            hashmap.insert(alias.s_ver().into(), vec![alias]);\n        }\n    }\n    Ok(hashmap)\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't list locally installed versions: {}\", source)]\n    CantListLocallyInstalledVersion {\n        source: crate::installed_versions::Error,\n    },\n    #[error(\"Can't read aliases: {}\", source)]\n    CantReadAliases { source: std::io::Error },\n}\n"
  },
  {
    "path": "src/commands/ls_remote.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::remote_node_index;\nuse crate::user_version::UserVersion;\n\nuse colored::Colorize;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct LsRemote {\n    /// Filter versions by a user-defined version or a semver range\n    #[arg(long)]\n    filter: Option<UserVersion>,\n\n    /// Show only LTS versions (optionally filter by LTS codename)  \n    #[arg(long)]\n    #[expect(\n        clippy::option_option,\n        reason = \"clap Option<Option<T>> supports --x and --x=value syntaxes\"\n    )]\n    lts: Option<Option<String>>,\n\n    /// Version sorting order\n    #[arg(long, default_value = \"asc\")]\n    sort: SortingMethod,\n\n    /// Only show the latest matching version\n    #[arg(long)]\n    latest: bool,\n}\n\n#[derive(clap::ValueEnum, Clone, Debug, PartialEq)]\npub enum SortingMethod {\n    #[clap(name = \"desc\")]\n    /// Sort versions in descending order (latest to earliest)\n    Descending,\n    #[clap(name = \"asc\")]\n    /// Sort versions in ascending order (earliest to latest)\n    Ascending,\n}\n\n/// Drain all elements but the last one\nfn truncate_except_latest<T>(list: &mut Vec<T>) {\n    let len = list.len();\n    if len > 1 {\n        list.swap(0, len - 1);\n        list.truncate(1);\n    }\n}\n\nimpl super::command::Command for LsRemote {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let mut all_versions = remote_node_index::list(&config.node_dist_mirror)?;\n\n        if let Some(lts) = &self.lts {\n            match lts {\n                Some(codename) => all_versions.retain(|v| {\n                    v.lts\n                        .as_ref()\n                        .is_some_and(|v_lts| v_lts.eq_ignore_ascii_case(codename))\n                }),\n                None => all_versions.retain(|v| v.lts.is_some()),\n            }\n        }\n\n        if let Some(filter) = &self.filter {\n            all_versions.retain(|v| filter.matches(&v.version, config));\n        }\n\n        if self.latest {\n            truncate_except_latest(&mut all_versions);\n        }\n\n        if let SortingMethod::Descending = self.sort {\n            all_versions.reverse();\n        }\n\n        if all_versions.is_empty() {\n            eprintln!(\"{}\", \"No versions were found!\".red());\n            return Ok(());\n        }\n\n        for version in &all_versions {\n            print!(\"{}\", version.version);\n            if let Some(lts) = &version.lts {\n                print!(\"{}\", format!(\" ({lts})\").cyan());\n            }\n            println!();\n        }\n\n        Ok(())\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(transparent)]\n    RemoteListing {\n        #[from]\n        source: remote_node_index::Error,\n    },\n}\n\n#[cfg(test)]\nmod test {\n    use super::*;\n\n    #[test]\n    fn test_truncate_except_latest() {\n        let mut list = vec![1, 2, 3, 4, 5];\n        truncate_except_latest(&mut list);\n        assert_eq!(list, vec![5]);\n\n        let mut list: Vec<()> = vec![];\n        truncate_except_latest(&mut list);\n        assert_eq!(list, vec![]);\n\n        let mut list = vec![1];\n        truncate_except_latest(&mut list);\n        assert_eq!(list, vec![1]);\n    }\n}\n"
  },
  {
    "path": "src/commands/mod.rs",
    "content": "pub mod alias;\npub mod command;\npub mod completions;\npub mod current;\npub mod default;\npub mod env;\npub mod exec;\npub mod install;\npub mod ls_local;\npub mod ls_remote;\npub mod unalias;\npub mod uninstall;\npub mod r#use;\n"
  },
  {
    "path": "src/commands/unalias.rs",
    "content": "use super::command::Command;\nuse crate::fs::remove_symlink_dir;\nuse crate::user_version::UserVersion;\nuse crate::version::Version;\nuse crate::{choose_version_for_user_input, config::FnmConfig};\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct Unalias {\n    pub(crate) requested_alias: String,\n}\n\nimpl Command for Unalias {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let requested_version = choose_version_for_user_input::choose_version_for_user_input(\n            &UserVersion::Full(Version::Alias(self.requested_alias.clone())),\n            config,\n        )\n        .ok()\n        .flatten()\n        .ok_or(Error::AliasNotFound {\n            requested_alias: self.requested_alias,\n        })?;\n\n        remove_symlink_dir(requested_version.path())\n            .map_err(|source| Error::CantDeleteSymlink { source })?;\n\n        Ok(())\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't delete symlink: {}\", source)]\n    CantDeleteSymlink { source: std::io::Error },\n    #[error(\"Requested alias {} not found\", requested_alias)]\n    AliasNotFound { requested_alias: String },\n}\n"
  },
  {
    "path": "src/commands/uninstall.rs",
    "content": "use super::command::Command;\nuse crate::config::FnmConfig;\nuse crate::fs::remove_symlink_dir;\nuse crate::installed_versions;\nuse crate::outln;\nuse crate::user_version::UserVersion;\nuse crate::version::Version;\nuse crate::version_files::get_user_version_for_directory;\nuse colored::Colorize;\nuse log::debug;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct Uninstall {\n    version: Option<UserVersion>,\n}\n\nimpl Command for Uninstall {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let all_versions = installed_versions::list(config.installations_dir())\n            .map_err(|source| Error::VersionListingError { source })?;\n        let requested_version = self\n            .version\n            .or_else(|| {\n                let current_dir = std::env::current_dir().unwrap();\n                get_user_version_for_directory(current_dir, config)\n            })\n            .ok_or(Error::CantInferVersion)?;\n\n        if matches!(requested_version, UserVersion::Full(Version::Bypassed)) {\n            return Err(Error::CantUninstallSystemVersion);\n        }\n\n        let available_versions: Vec<&Version> = all_versions\n            .iter()\n            .filter(|v| requested_version.matches(v, config))\n            .collect();\n\n        if available_versions.len() >= 2 {\n            return Err(Error::PleaseBeMoreSpecificToDelete {\n                matched_versions: available_versions\n                    .iter()\n                    .map(std::string::ToString::to_string)\n                    .collect(),\n            });\n        }\n\n        let version = requested_version\n            .to_version(&all_versions, config)\n            .ok_or(Error::CantFindVersion)?;\n\n        let matching_aliases = version.find_aliases(config)?;\n        let root_path = version\n            .root_path(config)\n            .ok_or_else(|| Error::RootPathNotFound {\n                version: version.clone(),\n            })?;\n\n        debug!(\"Removing Node version from {:?}\", root_path);\n        std::fs::remove_dir_all(root_path)\n            .map_err(|source| Error::CantDeleteNodeVersion { source })?;\n        outln!(\n            config,\n            Info,\n            \"Node version {} was removed successfully\",\n            version.v_str().cyan()\n        );\n\n        for alias in matching_aliases {\n            debug!(\"Removing alias from {:?}\", alias.path());\n            remove_symlink_dir(alias.path())\n                .map_err(|source| Error::CantDeleteSymlink { source })?;\n            outln!(\n                config,\n                Info,\n                \"Alias {} was removed successfully\",\n                alias.name().cyan()\n            );\n        }\n\n        Ok(())\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't get locally installed versions: {}\", source)]\n    VersionListingError { source: installed_versions::Error },\n    #[error(\"Can't find version in dotfiles. Please provide a version manually to the command.\")]\n    CantInferVersion,\n    #[error(\"Can't uninstall system version\")]\n    CantUninstallSystemVersion,\n    #[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::<Vec<_>>().join(\"\\n\"))]\n    PleaseBeMoreSpecificToDelete { matched_versions: Vec<String> },\n    #[error(\"Can't find a matching version\")]\n    CantFindVersion,\n    #[error(\"Root path not found for version {}\", version)]\n    RootPathNotFound { version: Version },\n    #[error(\"io error: {}\", source)]\n    IoError {\n        #[from]\n        source: std::io::Error,\n    },\n    #[error(\"Can't delete Node.js version: {}\", source)]\n    CantDeleteNodeVersion { source: std::io::Error },\n    #[error(\"Can't delete symlink: {}\", source)]\n    CantDeleteSymlink { source: std::io::Error },\n}\n"
  },
  {
    "path": "src/commands/use.rs",
    "content": "use super::command::Command;\nuse super::install::Install;\nuse crate::current_version::current_version;\nuse crate::fs;\nuse crate::installed_versions;\nuse crate::outln;\nuse crate::shell;\nuse crate::system_version;\nuse crate::user_version::UserVersion;\nuse crate::version::Version;\nuse crate::version_file_strategy::VersionFileStrategy;\nuse crate::{config::FnmConfig, user_version_reader::UserVersionReader};\nuse colored::Colorize;\nuse std::path::Path;\nuse thiserror::Error;\n\n#[derive(clap::Parser, Debug)]\npub struct Use {\n    pub version: Option<UserVersionReader>,\n    /// Install the version if it isn't installed yet\n    #[clap(long)]\n    pub install_if_missing: bool,\n\n    /// Don't output a message identifying the version being used\n    /// if it will not change due to execution of this command\n    #[clap(long)]\n    pub silent_if_unchanged: bool,\n\n    /// Print informational output to stderr (used internally by `fnm env`)\n    #[clap(skip)]\n    pub info_to_stderr: bool,\n}\n\nimpl Command for Use {\n    type Error = Error;\n\n    fn apply(self, config: &FnmConfig) -> Result<(), Self::Error> {\n        let multishell_path = config.multishell_path().ok_or(Error::FnmEnvWasNotSourced)?;\n        warn_if_multishell_path_not_in_path_env_var(multishell_path, config);\n\n        let all_versions = installed_versions::list(config.installations_dir())\n            .map_err(|source| Error::VersionListingError { source })?;\n        let requested_version = self\n            .version\n            .unwrap_or_else(|| {\n                let current_dir = std::env::current_dir().unwrap();\n                UserVersionReader::Path(current_dir)\n            })\n            .into_user_version(config)\n            .ok_or_else(|| match config.version_file_strategy() {\n                VersionFileStrategy::Local => InferVersionError::Local,\n                VersionFileStrategy::Recursive => InferVersionError::Recursive,\n            })\n            .map_err(|source| Error::CantInferVersion { source });\n\n        // Swallow the missing version error if `silent_if_unchanged` was provided\n        let requested_version = match (self.silent_if_unchanged, requested_version) {\n            (true, Err(_)) => return Ok(()),\n            (_, v) => v?,\n        };\n\n        let (message, version_path) = if let UserVersion::Full(Version::Bypassed) =\n            requested_version\n        {\n            let message = format!(\n                \"Bypassing fnm: using {} node\",\n                system_version::display_name().cyan()\n            );\n            (message, system_version::path())\n        } else if let Some(alias_name) = requested_version.alias_name() {\n            let alias_path = config.aliases_dir().join(&alias_name);\n            let system_path = system_version::path();\n            if matches!(fs::shallow_read_symlink(&alias_path), Ok(shallow_path) if shallow_path == system_path)\n            {\n                let message = format!(\n                    \"Bypassing fnm: using {} node\",\n                    system_version::display_name().cyan()\n                );\n                (message, system_path)\n            } else if alias_path.exists() {\n                let message = format!(\"Using Node for alias {}\", alias_name.cyan());\n                (message, alias_path)\n            } else {\n                install_new_version(requested_version, config, self.install_if_missing)?;\n                return Ok(());\n            }\n        } else {\n            let current_version = requested_version.to_version(&all_versions, config);\n            if let Some(version) = current_version {\n                let version_path = config\n                    .installations_dir()\n                    .join(version.to_string())\n                    .join(\"installation\");\n                let message = format!(\"Using Node {}\", version.to_string().cyan());\n                (message, version_path)\n            } else {\n                install_new_version(requested_version, config, self.install_if_missing)?;\n                return Ok(());\n            }\n        };\n\n        if !self.silent_if_unchanged || will_version_change(&version_path, config) {\n            if self.info_to_stderr {\n                outln!(config, Error, \"{}\", message);\n            } else {\n                outln!(config, Info, \"{}\", message);\n            }\n        }\n\n        if let Some(multishells_path) = multishell_path.parent() {\n            std::fs::create_dir_all(multishells_path).map_err(|_err| {\n                Error::MultishellDirectoryCreationIssue {\n                    path: multishells_path.to_path_buf(),\n                }\n            })?;\n        }\n\n        replace_symlink(&version_path, multishell_path)\n            .map_err(|source| Error::SymlinkingCreationIssue { source })?;\n\n        Ok(())\n    }\n}\n\nfn will_version_change(resolved_path: &Path, config: &FnmConfig) -> bool {\n    let current_version_path = current_version(config)\n        .unwrap_or(None)\n        .map(|v| v.installation_path(config));\n\n    current_version_path.as_deref() != Some(resolved_path)\n}\n\nfn install_new_version(\n    requested_version: UserVersion,\n    config: &FnmConfig,\n    install_if_missing: bool,\n) -> Result<(), Error> {\n    if !install_if_missing && !should_install_interactively(&requested_version) {\n        return Err(Error::CantFindVersion {\n            version: requested_version,\n        });\n    }\n\n    Install {\n        version: Some(requested_version.clone()),\n        ..Install::default()\n    }\n    .apply(config)\n    .map_err(|source| Error::InstallError { source })?;\n\n    Use {\n        version: Some(UserVersionReader::Direct(requested_version)),\n        install_if_missing: true,\n        silent_if_unchanged: false,\n        info_to_stderr: false,\n    }\n    .apply(config)?;\n\n    Ok(())\n}\n\n/// Tries to delete `from`, and then tries to symlink `from` to `to` anyway.\n/// If the symlinking fails, it will return the errors in the following order:\n/// * The deletion error (if exists)\n/// * The creation error\n///\n/// This way, we can create a symlink if it is missing.\nfn replace_symlink(from: &std::path::Path, to: &std::path::Path) -> std::io::Result<()> {\n    let symlink_deletion_result = fs::remove_symlink_dir(to);\n    match fs::symlink_dir(from, to) {\n        ok @ Ok(()) => ok,\n        err @ Err(_) => symlink_deletion_result.and(err),\n    }\n}\n\nfn should_install_interactively(requested_version: &UserVersion) -> bool {\n    use std::io::{IsTerminal, Write};\n\n    if !(std::io::stdout().is_terminal() && std::io::stdin().is_terminal()) {\n        return false;\n    }\n\n    let error_message = format!(\n        \"fnm can't find an installed Node version matching {}.\",\n        requested_version.to_string().italic()\n    );\n    eprintln!(\"{}\", error_message.red());\n    let do_you_want = format!(\"Do you want to install it? {} [y/N]:\", \"answer\".bold());\n    eprint!(\"{} \", do_you_want.yellow());\n    std::io::stdout().flush().unwrap();\n    let mut s = String::new();\n    std::io::stdin()\n        .read_line(&mut s)\n        .expect(\"Can't read user input\");\n\n    s.trim().to_lowercase() == \"y\"\n}\n\nfn warn_if_multishell_path_not_in_path_env_var(\n    multishell_path: &std::path::Path,\n    config: &FnmConfig,\n) {\n    if let Some(path_var) = std::env::var_os(\"PATH\") {\n        let bin_path = if cfg!(unix) {\n            multishell_path.join(\"bin\")\n        } else {\n            multishell_path.to_path_buf()\n        };\n\n        let fixed_path = bin_path.to_str().and_then(shell::maybe_fix_windows_path);\n        let fixed_path = fixed_path.as_deref();\n\n        for path in std::env::split_paths(&path_var) {\n            if bin_path == path || fixed_path == path.to_str() {\n                return;\n            }\n        }\n    }\n\n    outln!(\n        config, Error,\n        \"{} {}\\n{}\\n{}\",\n        \"warning:\".yellow().bold(),\n        \"The current Node.js path is not on your PATH environment variable.\".yellow(),\n        \"You should setup your shell profile to evaluate `fnm env`, see https://github.com/Schniz/fnm#shell-setup on how to do this\".yellow(),\n        \"Check out our documentation for more information: https://fnm.vercel.app\".yellow()\n    );\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"Can't create the symlink: {}\", source)]\n    SymlinkingCreationIssue { source: std::io::Error },\n    #[error(transparent)]\n    InstallError { source: <Install as Command>::Error },\n    #[error(\"Can't get locally installed versions: {}\", source)]\n    VersionListingError { source: installed_versions::Error },\n    #[error(\"Requested version {} is not currently installed\", version)]\n    CantFindVersion { version: UserVersion },\n    #[error(transparent)]\n    CantInferVersion {\n        #[from]\n        source: InferVersionError,\n    },\n    #[error(\n        \"{}\\n{}\\n{}\",\n        \"We can't find the necessary environment variables to replace the Node version.\",\n        \"You should setup your shell profile to evaluate `fnm env`, see https://github.com/Schniz/fnm#shell-setup on how to do this\",\n        \"Check out our documentation for more information: https://fnm.vercel.app\"\n    )]\n    FnmEnvWasNotSourced,\n    #[error(\"Can't create the multishell directory: {}\", path.display())]\n    MultishellDirectoryCreationIssue { path: std::path::PathBuf },\n}\n\n#[derive(Debug, Error)]\npub enum InferVersionError {\n    #[error(\"Can't find version in dotfiles. Please provide a version manually to the command.\")]\n    Local,\n    #[error(\"Could not find any version to use. Maybe you don't have a default version set?\\nTry running `fnm default <VERSION>` to set one,\\nor create a .node-version file inside your project to declare a Node.js version.\")]\n    Recursive,\n}\n"
  },
  {
    "path": "src/config.rs",
    "content": "use crate::arch::Arch;\nuse crate::directories::Directories;\nuse crate::log_level::LogLevel;\nuse crate::path_ext::PathExt;\nuse crate::version_file_strategy::VersionFileStrategy;\nuse url::Url;\n\n#[derive(clap::Parser, Debug, Clone)]\npub struct FnmConfig {\n    /// <https://nodejs.org/dist/> mirror\n    #[clap(\n        long,\n        env = \"FNM_NODE_DIST_MIRROR\",\n        default_value = \"https://nodejs.org/dist\",\n        global = true,\n        hide_env_values = true\n    )]\n    pub node_dist_mirror: Url,\n\n    /// The root directory of fnm installations.\n    #[clap(\n        long = \"fnm-dir\",\n        env = \"FNM_DIR\",\n        global = true,\n        hide_env_values = true\n    )]\n    pub base_dir: Option<std::path::PathBuf>,\n\n    /// Where the current node version link is stored.\n    /// This value will be populated automatically by evaluating\n    /// `fnm env` in your shell profile. Read more about it using `fnm help env`\n    #[clap(long, env = \"FNM_MULTISHELL_PATH\", hide_env_values = true, hide = true)]\n    multishell_path: Option<std::path::PathBuf>,\n\n    /// The log level of fnm commands\n    #[clap(\n        long,\n        env = \"FNM_LOGLEVEL\",\n        default_value_t,\n        global = true,\n        hide_env_values = true\n    )]\n    log_level: LogLevel,\n\n    /// Override the architecture of the installed Node binary.\n    /// Defaults to arch of fnm binary.\n    #[clap(\n        long,\n        env = \"FNM_ARCH\",\n        default_value_t,\n        global = true,\n        hide_env_values = true,\n        hide_default_value = true\n    )]\n    pub arch: Arch,\n\n    /// A strategy for how to resolve the Node version. Used whenever `fnm use` or `fnm install` is\n    /// called without a version, or when `--use-on-cd` is configured on evaluation.\n    #[clap(\n        long,\n        env = \"FNM_VERSION_FILE_STRATEGY\",\n        default_value_t,\n        global = true,\n        hide_env_values = true\n    )]\n    version_file_strategy: VersionFileStrategy,\n\n    /// Enable corepack support for each new installation.\n    /// This will make fnm call `corepack enable` on every Node.js installation.\n    /// For more information about corepack see <https://nodejs.org/api/corepack.html>\n    #[clap(\n        long,\n        env = \"FNM_COREPACK_ENABLED\",\n        global = true,\n        hide_env_values = true\n    )]\n    corepack_enabled: bool,\n\n    /// Resolve `engines.node` field in `package.json` whenever a `.node-version` or `.nvmrc` file is not present.\n    /// This feature is enabled by default. To disable it, provide `--resolve-engines=false`.\n    ///\n    /// Note: `engines.node` can be any semver range, with the latest satisfying version being resolved.\n    /// Note 2: If you disable it, please open an issue on GitHub describing _why_ you disabled it.\n    ///         In the future, disabling it might be a no-op, so it's worth knowing any reason to\n    ///         do that.\n    #[clap(\n        long,\n        env = \"FNM_RESOLVE_ENGINES\",\n        global = true,\n        hide_env_values = true,\n        verbatim_doc_comment\n    )]\n    #[expect(\n        clippy::option_option,\n        reason = \"clap Option<Option<T>> supports --x and --x=value syntaxes\"\n    )]\n    resolve_engines: Option<Option<bool>>,\n\n    #[clap(skip)]\n    directories: Directories,\n}\n\nimpl Default for FnmConfig {\n    fn default() -> Self {\n        Self {\n            node_dist_mirror: Url::parse(\"https://nodejs.org/dist/\").unwrap(),\n            base_dir: None,\n            multishell_path: None,\n            log_level: LogLevel::Info,\n            arch: Arch::default(),\n            version_file_strategy: VersionFileStrategy::default(),\n            corepack_enabled: false,\n            resolve_engines: None,\n            directories: Directories::default(),\n        }\n    }\n}\n\nimpl FnmConfig {\n    pub fn version_file_strategy(&self) -> VersionFileStrategy {\n        self.version_file_strategy\n    }\n\n    pub fn corepack_enabled(&self) -> bool {\n        self.corepack_enabled\n    }\n\n    pub fn resolve_engines(&self) -> bool {\n        self.resolve_engines.flatten().unwrap_or(true)\n    }\n\n    pub fn multishell_path(&self) -> Option<&std::path::Path> {\n        match &self.multishell_path {\n            None => None,\n            Some(v) => Some(v.as_path()),\n        }\n    }\n\n    pub fn log_level(&self) -> LogLevel {\n        self.log_level\n    }\n\n    pub fn base_dir_with_default(&self) -> std::path::PathBuf {\n        if let Some(dir) = &self.base_dir {\n            return dir.clone();\n        }\n\n        self.directories.default_base_dir()\n    }\n\n    pub fn installations_dir(&self) -> std::path::PathBuf {\n        self.base_dir_with_default()\n            .join(\"node-versions\")\n            .ensure_exists_silently()\n    }\n\n    pub fn default_version_dir(&self) -> std::path::PathBuf {\n        self.aliases_dir().join(\"default\")\n    }\n\n    pub fn aliases_dir(&self) -> std::path::PathBuf {\n        self.base_dir_with_default()\n            .join(\"aliases\")\n            .ensure_exists_silently()\n    }\n\n    pub fn multishell_storage(&self) -> std::path::PathBuf {\n        self.directories.multishell_storage()\n    }\n\n    #[cfg(test)]\n    pub fn with_base_dir(mut self, base_dir: Option<std::path::PathBuf>) -> Self {\n        self.base_dir = base_dir;\n        self\n    }\n\n    pub fn with_multishell_path(mut self, multishell_path: std::path::PathBuf) -> Self {\n        self.multishell_path = Some(multishell_path);\n        self\n    }\n}\n"
  },
  {
    "path": "src/current_version.rs",
    "content": "use thiserror::Error;\n\nuse crate::config::FnmConfig;\nuse crate::system_version;\nuse crate::version::Version;\n\npub fn current_version(config: &FnmConfig) -> Result<Option<Version>, Error> {\n    let multishell_path = config.multishell_path().ok_or(Error::EnvNotApplied)?;\n\n    if multishell_path.read_link().ok() == Some(system_version::path()) {\n        return Ok(Some(Version::Bypassed));\n    }\n\n    if let Ok(resolved_path) = std::fs::canonicalize(multishell_path) {\n        let installation_path = resolved_path\n            .parent()\n            .expect(\"multishell path can't be in the root\");\n        let file_name = installation_path\n            .file_name()\n            .expect(\"Can't get filename\")\n            .to_str()\n            .expect(\"Invalid OS string\");\n        let version = Version::parse(file_name).map_err(|source| Error::VersionError {\n            source,\n            version: file_name.to_string(),\n        })?;\n        Ok(Some(version))\n    } else {\n        Ok(None)\n    }\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(\"`fnm env` was not applied in this context.\\nCan't find fnm's environment variables\")]\n    EnvNotApplied,\n    #[error(\"Can't read the version as a valid semver\")]\n    VersionError {\n        source: node_semver::SemverError,\n        version: String,\n    },\n}\n"
  },
  {
    "path": "src/default_version.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::version::Version;\nuse std::str::FromStr;\n\npub fn find_default_version(config: &FnmConfig) -> Option<Version> {\n    if let Ok(version_path) = config.default_version_dir().canonicalize() {\n        let file_name = version_path.parent()?.file_name()?;\n        Version::from_str(file_name.to_str()?).ok()?.into()\n    } else {\n        Some(Version::Alias(\"default\".into()))\n    }\n}\n"
  },
  {
    "path": "src/directories.rs",
    "content": "use etcetera::BaseStrategy;\nuse std::path::PathBuf;\n\nuse crate::path_ext::PathExt;\n\nfn xdg_dir(env: &str) -> Option<PathBuf> {\n    if cfg!(windows) {\n        let env_var = std::env::var_os(env)?;\n        Some(PathBuf::from(env_var))\n    } else {\n        // On non-Windows platforms, `etcetera` already handles XDG variables\n        None\n    }\n}\n\nfn runtime_dir(basedirs: &impl BaseStrategy) -> Option<PathBuf> {\n    xdg_dir(\"XDG_RUNTIME_DIR\").or_else(|| basedirs.runtime_dir())\n}\n\nfn state_dir(basedirs: &impl BaseStrategy) -> Option<PathBuf> {\n    xdg_dir(\"XDG_STATE_HOME\").or_else(|| basedirs.state_dir())\n}\n\nfn cache_dir(basedirs: &impl BaseStrategy) -> PathBuf {\n    xdg_dir(\"XDG_CACHE_HOME\").unwrap_or_else(|| basedirs.cache_dir())\n}\n\n/// A helper struct for directories in fnm that uses XDG Base Directory Specification\n/// if applicable for the platform.\n#[derive(Debug, Clone)]\npub struct Directories(\n    #[cfg(windows)] etcetera::base_strategy::Windows,\n    #[cfg(not(windows))] etcetera::base_strategy::Xdg,\n);\n\nimpl Default for Directories {\n    fn default() -> Self {\n        Self(etcetera::choose_base_strategy().expect(\"choosing base strategy\"))\n    }\n}\n\nimpl Directories {\n    pub fn strategy(&self) -> &impl BaseStrategy {\n        &self.0\n    }\n\n    pub fn default_base_dir(&self) -> PathBuf {\n        let strategy = self.strategy();\n        let modern = strategy.data_dir().join(\"fnm\");\n        if modern.exists() {\n            return modern;\n        }\n\n        let legacy = strategy.home_dir().join(\".fnm\");\n        if legacy.exists() {\n            return legacy;\n        }\n\n        #[cfg(target_os = \"macos\")]\n        {\n            let basedirs = etcetera::base_strategy::Apple::new().expect(\"Can't get home directory\");\n            let legacy = basedirs.data_dir().join(\"fnm\");\n            if legacy.exists() {\n                return legacy;\n            }\n        }\n\n        modern.ensure_exists_silently()\n    }\n\n    pub fn multishell_storage(&self) -> PathBuf {\n        let basedirs = self.strategy();\n        let dir = runtime_dir(basedirs)\n            .or_else(|| state_dir(basedirs))\n            .unwrap_or_else(|| cache_dir(basedirs));\n        dir.join(\"fnm_multishells\")\n    }\n}\n"
  },
  {
    "path": "src/directory_portal.rs",
    "content": "use log::debug;\nuse std::path::Path;\nuse tempfile::TempDir;\n\n/// A \"work-in-progress\" directory, which will \"teleport\" into the path\n/// given in `target` only on successful, guarding from invalid state in the file system.\n///\n/// Underneath, it uses `fs::rename`, so make sure to make the `temp_dir` inside the same\n/// mount as `target`. This is why we have the `new_in` constructor.\npub struct DirectoryPortal<P: AsRef<Path>> {\n    temp_dir: TempDir,\n    target: P,\n}\n\nimpl<P: AsRef<Path>> DirectoryPortal<P> {\n    /// Create a new portal which will keep the temp files in\n    /// a subdirectory of `parent_dir` until teleporting to `target`.\n    #[must_use]\n    pub fn new_in(parent_dir: impl AsRef<Path>, target: P) -> Self {\n        let temp_dir = TempDir::new_in(parent_dir).expect(\"Can't generate a temp directory\");\n        debug!(\"Created a temp directory in {:?}\", temp_dir.path());\n        Self { temp_dir, target }\n    }\n\n    pub fn teleport(self) -> std::io::Result<P> {\n        debug!(\n            \"Moving directory {:?} into {:?}\",\n            self.temp_dir.path(),\n            self.target.as_ref()\n        );\n        std::fs::rename(&self.temp_dir, &self.target)?;\n        Ok(self.target)\n    }\n}\n\nimpl<P: AsRef<Path>> std::ops::Deref for DirectoryPortal<P> {\n    type Target = Path;\n    fn deref(&self) -> &Self::Target {\n        self.as_ref()\n    }\n}\n\nimpl<P: AsRef<Path>> AsRef<Path> for DirectoryPortal<P> {\n    fn as_ref(&self) -> &Path {\n        self.temp_dir.as_ref()\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use pretty_assertions::assert_eq;\n    use tempfile::tempdir;\n\n    #[test_log::test]\n    fn test_portal() {\n        let tempdir = tempdir().expect(\"Can't generate a temp directory\");\n        let portal = DirectoryPortal::new_in(std::env::temp_dir(), tempdir.path().join(\"subdir\"));\n        let new_file_path = portal.to_path_buf().join(\"README.md\");\n        std::fs::write(new_file_path, \"Hello world!\").expect(\"Can't write file\");\n        let target = portal.teleport().expect(\"Can't close directory portal\");\n\n        let file_exists: Vec<_> = target\n            .read_dir()\n            .expect(\"Can't read dir\")\n            .map(|x| x.unwrap().file_name().into_string().unwrap())\n            .collect();\n\n        assert_eq!(file_exists, vec![\"README.md\"]);\n    }\n}\n"
  },
  {
    "path": "src/downloader.rs",
    "content": "use crate::arch::Arch;\nuse crate::archive::{Archive, Error as ExtractError};\nuse crate::directory_portal::DirectoryPortal;\nuse crate::progress::ResponseProgress;\nuse crate::version::Version;\nuse indicatif::ProgressDrawTarget;\nuse log::debug;\nuse std::path::Path;\nuse std::path::PathBuf;\nuse thiserror::Error;\nuse url::Url;\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(transparent)]\n    HttpError {\n        #[from]\n        source: crate::http::Error,\n    },\n    #[error(transparent)]\n    IoError {\n        #[from]\n        source: std::io::Error,\n    },\n    #[error(\"Can't extract the file: {}\", source)]\n    CantExtractFile {\n        #[from]\n        source: ExtractError,\n    },\n    #[error(\"The downloaded archive is empty\")]\n    TarIsEmpty,\n    #[error(\"{} for {} not found upstream.\\nYou can `fnm ls-remote` to see available versions or try a different `--arch`.\", version, arch)]\n    VersionNotFound { version: Version, arch: Arch },\n    #[error(\"Version already installed at {:?}\", path)]\n    VersionAlreadyInstalled { path: PathBuf },\n}\n\n#[cfg(unix)]\nfn filename_for_version(version: &Version, arch: Arch, ext: &str) -> String {\n    format!(\n        \"node-{node_ver}-{platform}-{arch}.{ext}\",\n        node_ver = &version,\n        platform = crate::system_info::platform_name(),\n        arch = arch,\n        ext = ext\n    )\n}\n\n#[cfg(windows)]\nfn filename_for_version(version: &Version, arch: Arch, ext: &str) -> String {\n    format!(\n        \"node-{node_ver}-win-{arch}.{ext}\",\n        node_ver = &version,\n        arch = arch,\n        ext = ext,\n    )\n}\n\nfn download_url(base_url: &Url, version: &Version, arch: Arch, ext: &str) -> Url {\n    Url::parse(&format!(\n        \"{}/{}/{}\",\n        base_url.as_str().trim_end_matches('/'),\n        version,\n        filename_for_version(version, arch, ext)\n    ))\n    .unwrap()\n}\n\n/// Install a Node package\npub fn install_node_dist<P: AsRef<Path>>(\n    version: &Version,\n    node_dist_mirror: &Url,\n    installations_dir: P,\n    arch: Arch,\n    show_progress: bool,\n) -> Result<(), Error> {\n    let installation_dir = PathBuf::from(installations_dir.as_ref()).join(version.v_str());\n\n    if installation_dir.exists() {\n        return Err(Error::VersionAlreadyInstalled {\n            path: installation_dir,\n        });\n    }\n\n    std::fs::create_dir_all(installations_dir.as_ref())?;\n\n    let temp_installations_dir = installations_dir.as_ref().join(\".downloads\");\n    std::fs::create_dir_all(&temp_installations_dir)?;\n\n    let portal = DirectoryPortal::new_in(&temp_installations_dir, installation_dir);\n\n    for extract in Archive::supported() {\n        let ext = extract.file_extension();\n        let url = download_url(node_dist_mirror, version, arch, ext);\n        debug!(\"Going to call for {}\", &url);\n        let response = crate::http::get(url.as_str())?;\n\n        if !response.status().is_success() {\n            continue;\n        }\n\n        debug!(\"Extracting response...\");\n        if show_progress {\n            extract.extract_archive_into(\n                portal.as_ref(),\n                ResponseProgress::new(response, ProgressDrawTarget::stderr()),\n            )?;\n        } else {\n            extract.extract_archive_into(portal.as_ref(), response)?;\n        }\n        debug!(\"Extraction completed\");\n\n        let installed_directory = std::fs::read_dir(&portal)?\n            .next()\n            .ok_or(Error::TarIsEmpty)??;\n        let installed_directory = installed_directory.path();\n\n        let renamed_installation_dir = portal.join(\"installation\");\n        std::fs::rename(installed_directory, renamed_installation_dir)?;\n\n        portal.teleport()?;\n\n        return Ok(());\n    }\n\n    Err(Error::VersionNotFound {\n        version: version.clone(),\n        arch,\n    })\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use crate::downloader::install_node_dist;\n    use crate::version::Version;\n    use pretty_assertions::assert_eq;\n    use tempfile::tempdir;\n\n    #[test_log::test]\n    fn test_installing_node_12() {\n        let installations_dir = tempdir().unwrap();\n        let node_path = install_in(installations_dir.path()).join(\"node\");\n\n        let stdout = duct::cmd(node_path.to_str().unwrap(), vec![\"--version\"])\n            .stdout_capture()\n            .run()\n            .expect(\"Can't run Node binary\")\n            .stdout;\n\n        let result = String::from_utf8(stdout).expect(\"Can't read `node --version` output\");\n\n        assert_eq!(result.trim(), \"v12.0.0\");\n    }\n\n    #[test_log::test]\n    fn test_installing_npm() {\n        let installations_dir = tempdir().unwrap();\n        let bin_dir = install_in(installations_dir.path());\n        let npm_path = bin_dir.join(if cfg!(windows) { \"npm.cmd\" } else { \"npm\" });\n\n        let stdout = duct::cmd(npm_path.to_str().unwrap(), vec![\"--version\"])\n            .env(\"PATH\", bin_dir)\n            .stdout_capture()\n            .run()\n            .expect(\"Can't run npm\")\n            .stdout;\n\n        let result = String::from_utf8(stdout).expect(\"Can't read npm output\");\n\n        assert_eq!(result.trim(), \"6.9.0\");\n    }\n\n    fn install_in(path: &Path) -> PathBuf {\n        let version = Version::parse(\"12.0.0\").unwrap();\n        let arch = Arch::X64;\n        let node_dist_mirror = Url::parse(\"https://nodejs.org/dist/\").unwrap();\n        install_node_dist(&version, &node_dist_mirror, path, arch, false)\n            .expect(\"Can't install Node 12\");\n\n        let mut location_path = path.join(version.v_str()).join(\"installation\");\n\n        if cfg!(unix) {\n            location_path.push(\"bin\");\n        }\n\n        location_path\n    }\n}\n"
  },
  {
    "path": "src/fs.rs",
    "content": "use std::path::Path;\n\n#[cfg(unix)]\npub fn symlink_dir<P: AsRef<Path>, U: AsRef<Path>>(from: P, to: U) -> std::io::Result<()> {\n    std::os::unix::fs::symlink(from, to)?;\n    Ok(())\n}\n\n#[cfg(windows)]\npub fn symlink_dir<P: AsRef<Path>, U: AsRef<Path>>(from: P, to: U) -> std::io::Result<()> {\n    junction::create(from, to)?;\n    Ok(())\n}\n\n#[cfg(windows)]\npub fn remove_symlink_dir<P: AsRef<Path>>(path: P) -> std::io::Result<()> {\n    std::fs::remove_dir(path)?;\n    Ok(())\n}\n\n#[cfg(unix)]\npub fn remove_symlink_dir<P: AsRef<Path>>(path: P) -> std::io::Result<()> {\n    std::fs::remove_file(path)?;\n    Ok(())\n}\n\npub fn shallow_read_symlink<P: AsRef<Path>>(path: P) -> std::io::Result<std::path::PathBuf> {\n    std::fs::read_link(path)\n}\n"
  },
  {
    "path": "src/http.rs",
    "content": "//! This module is an adapter for HTTP related operations.\n//! In the future, if we want to migrate to a different HTTP library,\n//! we can easily change this facade instead of multiple places in the crate.\n\nuse reqwest::{blocking::Client, IntoUrl};\n\n#[derive(Debug, thiserror::Error, miette::Diagnostic)]\n#[error(transparent)]\n#[diagnostic(code(\"fnm::http::error\"))]\npub struct Error(#[from] reqwest::Error);\npub type Response = reqwest::blocking::Response;\n\npub fn get(url: impl IntoUrl) -> Result<Response, Error> {\n    Ok(Client::new()\n        .get(url)\n        // Some sites require a user agent.\n        .header(\"User-Agent\", concat!(\"fnm \", env!(\"CARGO_PKG_VERSION\")))\n        .send()?)\n}\n"
  },
  {
    "path": "src/installed_versions.rs",
    "content": "use crate::version::Version;\nuse std::path::Path;\nuse thiserror::Error;\n\npub fn list<P: AsRef<Path>>(installations_dir: P) -> Result<Vec<Version>, Error> {\n    let mut vec = vec![];\n    for result_entry in installations_dir.as_ref().read_dir()? {\n        let entry = result_entry?;\n        if entry\n            .file_name()\n            .to_str()\n            .is_some_and(|s| s.starts_with('.'))\n        {\n            continue;\n        }\n\n        let path = entry.path();\n        let filename = path\n            .file_name()\n            .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?\n            .to_str()\n            .ok_or_else(|| std::io::Error::from(std::io::ErrorKind::NotFound))?;\n        let version = Version::parse(filename)?;\n        vec.push(version);\n    }\n    Ok(vec)\n}\n\n#[derive(Debug, Error)]\npub enum Error {\n    #[error(transparent)]\n    IoError {\n        #[from]\n        source: std::io::Error,\n    },\n    #[error(transparent)]\n    SemverError {\n        #[from]\n        source: node_semver::SemverError,\n    },\n}\n"
  },
  {
    "path": "src/log_level.rs",
    "content": "use std::fmt::Display;\n\nuse clap::ValueEnum;\n\n#[derive(Debug, Default, PartialEq, PartialOrd, Eq, Ord, Clone, Copy, ValueEnum)]\npub enum LogLevel {\n    Quiet,\n    Error,\n    #[default]\n    #[value(alias(\"all\"))]\n    Info,\n}\n\nimpl LogLevel {\n    pub fn as_str(self) -> &'static str {\n        match self {\n            Self::Quiet => \"quiet\",\n            Self::Info => \"info\",\n            Self::Error => \"error\",\n        }\n    }\n\n    pub fn is_writable(self, logging: Self) -> bool {\n        use std::cmp::Ordering;\n        matches!(self.cmp(&logging), Ordering::Greater | Ordering::Equal)\n    }\n\n    pub fn writer_for(self, logging: Self) -> Box<dyn std::io::Write> {\n        if self.is_writable(logging) {\n            match logging {\n                Self::Error => Box::from(std::io::stderr()),\n                _ => Box::from(std::io::stdout()),\n            }\n        } else {\n            Box::from(std::io::sink())\n        }\n    }\n\n    pub fn possible_values() -> &'static [&'static str; 4] {\n        &[\"quiet\", \"info\", \"all\", \"error\"]\n    }\n}\n\nimpl Display for LogLevel {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_str(self.as_str())\n    }\n}\n\n#[macro_export]\nmacro_rules! outln {\n    ($config:ident, $level:path, $($expr:expr),+) => {{\n        use $crate::log_level::LogLevel::*;\n        writeln!($config.log_level().writer_for($level), $($expr),+).expect(\"Can't write output\");\n    }}\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn test_is_writable() {\n        assert!(!LogLevel::Quiet.is_writable(LogLevel::Info));\n        assert!(!LogLevel::Error.is_writable(LogLevel::Info));\n        assert!(LogLevel::Info.is_writable(LogLevel::Info));\n        assert!(LogLevel::Info.is_writable(LogLevel::Error));\n    }\n}\n"
  },
  {
    "path": "src/lts.rs",
    "content": "use crate::remote_node_index::IndexedNodeVersion;\nuse std::fmt::Display;\n\n#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]\npub enum LtsType {\n    /// lts-*, lts/*\n    Latest,\n    /// lts-erbium, lts/erbium\n    CodeName(String),\n}\n\nimpl From<&str> for LtsType {\n    fn from(s: &str) -> Self {\n        if s == \"*\" || s == \"latest\" {\n            Self::Latest\n        } else {\n            Self::CodeName(s.to_string())\n        }\n    }\n}\n\nimpl Display for LtsType {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Self::Latest => f.write_str(\"latest\"),\n            Self::CodeName(s) => f.write_str(s),\n        }\n    }\n}\n\nimpl LtsType {\n    pub fn pick_latest<'vec>(\n        &self,\n        versions: &'vec [IndexedNodeVersion],\n    ) -> Option<&'vec IndexedNodeVersion> {\n        match self {\n            Self::Latest => versions.iter().filter(|x| x.lts.is_some()).next_back(),\n            Self::CodeName(s) => versions\n                .iter()\n                .filter(|x| match &x.lts {\n                    None => false,\n                    Some(x) => s.to_lowercase() == x.to_lowercase(),\n                })\n                .next_back(),\n        }\n    }\n}\n"
  },
  {
    "path": "src/main.rs",
    "content": "#![warn(rust_2018_idioms, clippy::all, clippy::pedantic)]\n#![allow(\n    clippy::enum_variant_names,\n    clippy::large_enum_variant,\n    clippy::module_name_repetitions,\n    clippy::similar_names\n)]\n\nmod alias;\nmod arch;\nmod archive;\nmod choose_version_for_user_input;\nmod cli;\nmod commands;\nmod config;\nmod current_version;\nmod directory_portal;\nmod downloader;\nmod fs;\nmod http;\nmod installed_versions;\nmod lts;\nmod package_json;\nmod path_ext;\nmod progress;\nmod remote_node_index;\nmod shell;\nmod system_info;\nmod system_version;\nmod user_version;\nmod user_version_reader;\nmod version;\nmod version_file_strategy;\nmod version_files;\n\n#[macro_use]\nmod log_level;\nmod default_version;\nmod directories;\nmod pretty_serde;\n\nfn main() {\n    env_logger::init();\n    let value = crate::cli::parse();\n    value.subcmd.call(value.config);\n}\n"
  },
  {
    "path": "src/package_json.rs",
    "content": "use serde::Deserialize;\n\n#[derive(Debug, Deserialize, Default)]\nstruct EnginesField {\n    node: Option<node_semver::Range>,\n}\n\n#[derive(Debug, Deserialize, Default)]\npub struct PackageJson {\n    engines: Option<EnginesField>,\n}\n\nimpl PackageJson {\n    pub fn node_range(&self) -> Option<&node_semver::Range> {\n        self.engines\n            .as_ref()\n            .and_then(|engines| engines.node.as_ref())\n    }\n}\n"
  },
  {
    "path": "src/path_ext.rs",
    "content": "use log::warn;\n\npub trait PathExt {\n    fn ensure_exists_silently(self) -> Self;\n}\n\nimpl<T: AsRef<std::path::Path>> PathExt for T {\n    /// Ensures a path is existing by creating it recursively\n    /// if it is missing. No error is emitted if the creation has failed.\n    fn ensure_exists_silently(self) -> Self {\n        if let Err(err) = std::fs::create_dir_all(self.as_ref()) {\n            warn!(\"Failed to create directory {:?}: {}\", self.as_ref(), err);\n        }\n        self\n    }\n}\n"
  },
  {
    "path": "src/pretty_serde.rs",
    "content": "use miette::SourceOffset;\n\n#[derive(Debug, thiserror::Error, miette::Diagnostic)]\n#[error(\"malformed json\\n{}\", self.report())]\npub struct DecodeError {\n    cause: serde_json::Error,\n    #[source_code]\n    input: String,\n    #[label(\"at this position\")]\n    location: SourceOffset,\n}\n\n#[derive(Debug, thiserror::Error, miette::Diagnostic)]\n#[error(\"\")]\npub struct ClonedError {\n    message: String,\n    #[source_code]\n    input: String,\n    #[label(\"{message}\")]\n    location: SourceOffset,\n}\n\nimpl DecodeError {\n    pub fn from_serde(input: impl Into<String>, cause: serde_json::Error) -> Self {\n        let input = input.into();\n        let location = SourceOffset::from_location(&input, cause.line(), cause.column());\n        DecodeError {\n            cause,\n            input,\n            location,\n        }\n    }\n\n    pub fn report(&self) -> String {\n        use colored::Colorize;\n        let report = miette::Report::from(ClonedError {\n            message: self.cause.to_string().italic().to_string(),\n            input: self.input.clone(),\n            location: self.location,\n        });\n\n        let mut output = String::new();\n\n        for line in format!(\"{report:?}\").lines().skip(1) {\n            use std::fmt::Write;\n            writeln!(&mut output, \"{line}\").unwrap();\n        }\n\n        output.white().to_string()\n    }\n}\n"
  },
  {
    "path": "src/progress.rs",
    "content": "use std::io::Read;\n\nuse indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};\nuse reqwest::blocking::Response;\n\npub struct ResponseProgress {\n    progress: Option<ProgressBar>,\n    response: Response,\n}\n\n#[derive(Default, Clone, Debug, clap::ValueEnum)]\npub enum ProgressConfig {\n    #[default]\n    Auto,\n    Never,\n    Always,\n}\n\nimpl ProgressConfig {\n    pub fn enabled(&self, config: &crate::config::FnmConfig) -> bool {\n        match self {\n            Self::Never => false,\n            Self::Always => true,\n            Self::Auto => config\n                .log_level()\n                .is_writable(crate::log_level::LogLevel::Info),\n        }\n    }\n}\n\nfn make_progress_bar(size: u64, target: ProgressDrawTarget) -> ProgressBar {\n    let bar = ProgressBar::with_draw_target(Some(size), target);\n\n    bar.set_style(\n        ProgressStyle::with_template(\n            \"{elapsed_precise:.white.dim} {wide_bar:.cyan} {bytes}/{total_bytes} ({bytes_per_sec}, {eta})\",\n        )\n        .unwrap()\n        .progress_chars(\"█▉▊▋▌▍▎▏  \"),\n    );\n\n    bar\n}\n\nimpl ResponseProgress {\n    pub fn new(response: Response, target: ProgressDrawTarget) -> Self {\n        Self {\n            progress: response\n                .content_length()\n                .map(|len| make_progress_bar(len, target)),\n            response,\n        }\n    }\n\n    pub fn finish(&self) {\n        if let Some(ref bar) = self.progress {\n            bar.finish();\n        }\n    }\n}\n\nimpl Read for ResponseProgress {\n    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {\n        let size = self.response.read(buf)?;\n\n        if let Some(ref bar) = self.progress {\n            bar.inc(size as u64);\n        }\n\n        Ok(size)\n    }\n}\n\nimpl Drop for ResponseProgress {\n    fn drop(&mut self) {\n        self.finish();\n        eprintln!();\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use indicatif::{ProgressDrawTarget, TermLike};\n    use reqwest::blocking::Response;\n    use std::{\n        io::Read,\n        sync::{Arc, Mutex},\n    };\n\n    use super::ResponseProgress;\n\n    const CONTENT_LENGTH: usize = 100;\n\n    #[derive(Debug)]\n    struct MockedTerm {\n        pub buf: Arc<Mutex<String>>,\n    }\n\n    impl TermLike for MockedTerm {\n        fn width(&self) -> u16 {\n            80\n        }\n\n        fn move_cursor_up(&self, _n: usize) -> std::io::Result<()> {\n            Ok(())\n        }\n\n        fn move_cursor_down(&self, _n: usize) -> std::io::Result<()> {\n            Ok(())\n        }\n\n        fn move_cursor_right(&self, _n: usize) -> std::io::Result<()> {\n            Ok(())\n        }\n\n        fn move_cursor_left(&self, _n: usize) -> std::io::Result<()> {\n            Ok(())\n        }\n\n        fn write_line(&self, s: &str) -> std::io::Result<()> {\n            self.buf.lock().unwrap().push_str(s);\n            Ok(())\n        }\n\n        fn write_str(&self, s: &str) -> std::io::Result<()> {\n            self.buf.lock().unwrap().push_str(s);\n            Ok(())\n        }\n\n        fn clear_line(&self) -> std::io::Result<()> {\n            Ok(())\n        }\n\n        fn flush(&self) -> std::io::Result<()> {\n            Ok(())\n        }\n    }\n\n    #[test]\n    fn test_reads_data_and_shows_progress() {\n        let response: Response = http::Response::builder()\n            .header(\"Content-Length\", CONTENT_LENGTH)\n            .body(\"a\".repeat(CONTENT_LENGTH))\n            .unwrap()\n            .into();\n\n        let mut buf = [0; CONTENT_LENGTH];\n\n        let out_buf = Arc::new(Mutex::new(String::new()));\n\n        let mut progress = ResponseProgress::new(\n            response,\n            ProgressDrawTarget::term_like(Box::new(MockedTerm {\n                buf: out_buf.clone(),\n            })),\n        );\n        let size = progress.read(&mut buf[..]).unwrap();\n\n        drop(progress);\n\n        assert_eq!(size, CONTENT_LENGTH);\n        assert_eq!(buf, \"a\".repeat(CONTENT_LENGTH).as_bytes());\n        assert!(out_buf.lock().unwrap().contains(&\"█\".repeat(40)));\n    }\n}\n"
  },
  {
    "path": "src/remote_node_index.rs",
    "content": "use crate::{pretty_serde::DecodeError, version::Version};\nuse serde::Deserialize;\nuse url::Url;\n\nmod lts_status {\n    use serde::{Deserialize, Deserializer};\n\n    #[derive(Deserialize, Debug, PartialEq, Eq)]\n    #[serde(untagged)]\n    enum LtsStatus {\n        Nope(bool),\n        Yes(String),\n    }\n\n    impl From<LtsStatus> for Option<String> {\n        fn from(status: LtsStatus) -> Self {\n            match status {\n                LtsStatus::Nope(_) => None,\n                LtsStatus::Yes(x) => Some(x),\n            }\n        }\n    }\n\n    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>\n    where\n        D: Deserializer<'de>,\n    {\n        Ok(LtsStatus::deserialize(deserializer)?.into())\n    }\n\n    #[cfg(test)]\n    mod tests {\n        use super::*;\n        use pretty_assertions::assert_eq;\n\n        #[derive(Deserialize)]\n        struct TestSubject {\n            #[serde(deserialize_with = \"deserialize\")]\n            lts: Option<String>,\n        }\n\n        #[test]\n        fn test_false_deserialization() {\n            let json = serde_json::json!({ \"lts\": false });\n            let subject: TestSubject =\n                serde_json::from_value(json).expect(\"Can't deserialize json\");\n            assert_eq!(subject.lts, None);\n        }\n\n        #[test]\n        fn test_value_deserialization() {\n            let json = serde_json::json!({ \"lts\": \"dubnium\" });\n            let subject: TestSubject =\n                serde_json::from_value(json).expect(\"Can't deserialize json\");\n            assert_eq!(subject.lts, Some(\"dubnium\".into()));\n        }\n    }\n}\n\n#[derive(Deserialize, Debug)]\npub struct IndexedNodeVersion {\n    pub version: Version,\n    #[serde(with = \"lts_status\")]\n    pub lts: Option<String>,\n    // pub date: chrono::NaiveDate,\n    // pub files: Vec<String>,\n}\n\n#[derive(Debug, thiserror::Error, miette::Diagnostic)]\npub enum Error {\n    #[error(\"can't get remote versions file: {0}\")]\n    #[diagnostic(transparent)]\n    Http(#[from] crate::http::Error),\n    #[error(\"can't decode remote versions file: {0}\")]\n    #[diagnostic(transparent)]\n    Decode(#[from] DecodeError),\n}\n\n/// Prints\n///\n/// ```rust\n/// use crate::remote_node_index::list;\n/// ```\npub fn list(base_url: &Url) -> Result<Vec<IndexedNodeVersion>, Error> {\n    let base_url = base_url.as_str().trim_end_matches('/');\n    let index_json_url = format!(\"{base_url}/index.json\");\n    let resp = crate::http::get(&index_json_url)?\n        .error_for_status()\n        .map_err(crate::http::Error::from)?;\n    let text = resp.text().map_err(crate::http::Error::from)?;\n    let mut value: Vec<IndexedNodeVersion> =\n        serde_json::from_str(&text[..]).map_err(|cause| DecodeError::from_serde(text, cause))?;\n    value.sort_by(|a, b| a.version.cmp(&b.version));\n    Ok(value)\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use pretty_assertions::assert_eq;\n\n    #[test]\n    fn test_list() {\n        let base_url = Url::parse(\"https://nodejs.org/dist\").unwrap();\n        let expected_version = Version::parse(\"12.0.0\").unwrap();\n        let mut versions = list(&base_url).expect(\"Can't get HTTP data\");\n        assert_eq!(\n            versions\n                .drain(..)\n                .find(|x| x.version == expected_version)\n                .map(|x| x.version),\n            Some(expected_version)\n        );\n    }\n}\n"
  },
  {
    "path": "src/shell/bash.rs",
    "content": "use crate::version_file_strategy::VersionFileStrategy;\n\nuse super::shell::Shell;\nuse indoc::formatdoc;\nuse std::path::Path;\n\n#[derive(Debug)]\npub struct Bash;\n\nimpl Shell for Bash {\n    fn to_clap_shell(&self) -> clap_complete::Shell {\n        clap_complete::Shell::Bash\n    }\n\n    fn path(&self, path: &Path) -> anyhow::Result<String> {\n        let path = path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Can't convert path to string\"))?;\n        let path =\n            super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string());\n        Ok(format!(\"export PATH={path:?}:\\\"$PATH\\\"\"))\n    }\n\n    fn set_env_var(&self, name: &str, value: &str) -> String {\n        format!(\"export {name}={value:?}\")\n    }\n\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String> {\n        let version_file_exists_condition = if config.resolve_engines() {\n            \"-f .node-version || -f .nvmrc || -f package.json\"\n        } else {\n            \"-f .node-version || -f .nvmrc\"\n        };\n        let autoload_hook = match config.version_file_strategy() {\n            VersionFileStrategy::Local => formatdoc!(\n                r\"\n                    if [[ {version_file_exists_condition} ]]; then\n                        fnm use --silent-if-unchanged\n                    fi\n                \",\n                version_file_exists_condition = version_file_exists_condition,\n            ),\n            VersionFileStrategy::Recursive => String::from(r\"fnm use --silent-if-unchanged\"),\n        };\n        Ok(formatdoc!(\n            r#\"\n                __fnm_use_if_file_found() {{\n                    {autoload_hook}\n                }}\n\n                __fnmcd() {{\n                    \\cd \"$@\" || return $?\n                    __fnm_use_if_file_found\n                }}\n\n                alias cd=__fnmcd\n            \"#,\n            autoload_hook = autoload_hook\n        ))\n    }\n}\n"
  },
  {
    "path": "src/shell/fish.rs",
    "content": "use crate::version_file_strategy::VersionFileStrategy;\n\nuse super::shell::Shell;\nuse indoc::formatdoc;\nuse std::path::Path;\n\n#[derive(Debug)]\npub struct Fish;\n\nimpl Shell for Fish {\n    fn to_clap_shell(&self) -> clap_complete::Shell {\n        clap_complete::Shell::Fish\n    }\n\n    fn path(&self, path: &Path) -> anyhow::Result<String> {\n        let path = path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Can't convert path to string\"))?;\n        let path =\n            super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string());\n        Ok(format!(\"set -gx PATH {path:?} $PATH;\"))\n    }\n\n    fn set_env_var(&self, name: &str, value: &str) -> String {\n        format!(\"set -gx {name} {value:?};\")\n    }\n\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String> {\n        let version_file_exists_condition = if config.resolve_engines() {\n            \"test -f .node-version -o -f .nvmrc -o -f package.json\"\n        } else {\n            \"test -f .node-version -o -f .nvmrc\"\n        };\n        let autoload_hook = match config.version_file_strategy() {\n            VersionFileStrategy::Local => formatdoc!(\n                r\"\n                    if {version_file_exists_condition}\n                        fnm use --silent-if-unchanged\n                    end\n                \",\n                version_file_exists_condition = version_file_exists_condition,\n            ),\n            VersionFileStrategy::Recursive => String::from(r\"fnm use --silent-if-unchanged\"),\n        };\n        Ok(formatdoc!(\n            r\"\n                function _fnm_autoload_hook --on-variable PWD --description 'Change Node version on directory change'\n                    status --is-command-substitution; and return\n                    {autoload_hook}\n                end\n            \",\n            autoload_hook = autoload_hook\n        ))\n    }\n}\n"
  },
  {
    "path": "src/shell/infer/mod.rs",
    "content": "mod unix;\n\nmod windows;\n\n#[cfg(unix)]\npub use self::unix::infer_shell;\n#[cfg(not(unix))]\npub use self::windows::infer_shell;\n\nfn shell_from_string(shell: &str) -> Option<Box<dyn super::Shell>> {\n    use super::{Bash, Fish, PowerShell, WindowsCmd, Zsh};\n    match shell {\n        \"sh\" | \"bash\" => return Some(Box::from(Bash)),\n        \"zsh\" => return Some(Box::from(Zsh)),\n        \"fish\" => return Some(Box::from(Fish)),\n        \"pwsh\" | \"powershell\" => return Some(Box::from(PowerShell)),\n        \"cmd\" => return Some(Box::from(WindowsCmd)),\n        cmd_name => log::debug!(\"binary is not a supported shell: {:?}\", cmd_name),\n    }\n    None\n}\n"
  },
  {
    "path": "src/shell/infer/unix.rs",
    "content": "#![cfg(unix)]\n\nuse crate::shell::Shell;\nuse log::debug;\nuse std::io::{Error, ErrorKind};\nuse thiserror::Error;\n\n#[derive(Debug)]\nstruct ProcessInfo {\n    parent_pid: Option<u32>,\n    command: String,\n}\n\nconst MAX_ITERATIONS: u8 = 10;\n\npub fn infer_shell() -> Option<Box<dyn Shell>> {\n    let mut pid = Some(std::process::id());\n    let mut visited = 0;\n\n    while let Some(current_pid) = pid {\n        if visited > MAX_ITERATIONS {\n            return None;\n        }\n\n        let process_info = get_process_info(current_pid)\n            .map_err(|err| {\n                debug!(\"{}\", err);\n                err\n            })\n            .ok()?;\n        let binary = process_info\n            .command\n            .trim_start_matches('-')\n            .split('/')\n            .next_back()?;\n\n        if let Some(shell) = super::shell_from_string(binary) {\n            return Some(shell);\n        }\n\n        pid = process_info.parent_pid;\n        visited += 1;\n    }\n\n    None\n}\n\nfn get_process_info(pid: u32) -> Result<ProcessInfo, ProcessInfoError> {\n    use std::io::{BufRead, BufReader};\n    use std::process::Command;\n\n    let buffer = Command::new(\"ps\")\n        .arg(\"-o\")\n        .arg(\"ppid,comm\")\n        .arg(pid.to_string())\n        .stdout(std::process::Stdio::piped())\n        .spawn()?\n        .stdout\n        .ok_or_else(|| Error::from(ErrorKind::UnexpectedEof))?;\n\n    let mut lines = BufReader::new(buffer).lines();\n\n    // skip header line\n    lines\n        .next()\n        .ok_or_else(|| Error::from(ErrorKind::UnexpectedEof))??;\n\n    let line = lines\n        .next()\n        .ok_or_else(|| Error::from(ErrorKind::NotFound))??;\n\n    let mut parts = line.split_whitespace();\n    let ppid = parts.next().ok_or_else(|| ProcessInfoError::Parse {\n        expectation: \"Can't read the ppid from ps, should be the first item in the table\",\n        got: line.to_string(),\n    })?;\n    let command = parts.next().ok_or_else(|| ProcessInfoError::Parse {\n        expectation: \"Can't read the command from ps, should be the second item in the table\",\n        got: line.to_string(),\n    })?;\n\n    Ok(ProcessInfo {\n        parent_pid: ppid.parse().ok(),\n        command: command.into(),\n    })\n}\n\n#[derive(Debug, Error)]\nenum ProcessInfoError {\n    #[error(\"Can't read process info: {source}\")]\n    Io {\n        #[source]\n        #[from]\n        source: std::io::Error,\n    },\n    #[error(\"Can't parse process info output. {expectation}. Got: {got}\")]\n    Parse {\n        got: String,\n        expectation: &'static str,\n    },\n}\n\n#[cfg(all(test, unix))]\nmod tests {\n    use super::*;\n    use pretty_assertions::assert_eq;\n    use std::process::{Command, Stdio};\n\n    #[test]\n    fn test_get_process_info() -> anyhow::Result<()> {\n        let subprocess = Command::new(\"bash\")\n            .stdin(Stdio::piped())\n            .stdout(Stdio::piped())\n            .stderr(Stdio::piped())\n            .spawn()?;\n        let process_info = get_process_info(subprocess.id());\n        let parent_pid = process_info.ok().and_then(|x| x.parent_pid);\n        assert_eq!(parent_pid, Some(std::process::id()));\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/shell/infer/windows.rs",
    "content": "#![cfg(not(unix))]\n\nuse crate::shell::Shell;\nuse log::{debug, warn};\nuse sysinfo::{ProcessRefreshKind, System, UpdateKind};\n\npub fn infer_shell() -> Option<Box<dyn Shell>> {\n    let mut system = System::new();\n    let mut current_pid = sysinfo::get_current_pid().ok();\n\n    system\n        .refresh_processes_specifics(ProcessRefreshKind::new().with_exe(UpdateKind::OnlyIfNotSet));\n\n    while let Some(pid) = current_pid {\n        if let Some(process) = system.process(pid) {\n            current_pid = process.parent();\n            debug!(\"pid {pid} parent process is {current_pid:?}\");\n            let process_name = process\n                .exe()\n                .and_then(|x| {\n                    tap_none(x.file_stem(), || {\n                        warn!(\"failed to get file stem from {:?}\", x);\n                    })\n                })\n                .and_then(|x| {\n                    tap_none(x.to_str(), || {\n                        warn!(\"failed to convert file stem to string: {:?}\", x);\n                    })\n                })\n                .map(str::to_lowercase);\n            if let Some(shell) = process_name\n                .as_ref()\n                .map(|x| &x[..])\n                .and_then(super::shell_from_string)\n            {\n                return Some(shell);\n            }\n        } else {\n            warn!(\"process not found for {pid}\");\n            current_pid = None;\n        }\n    }\n\n    None\n}\n\nfn tap_none<T, F>(opt: Option<T>, f: F) -> Option<T>\nwhere\n    F: FnOnce(),\n{\n    match &opt {\n        Some(_) => (),\n        None => f(),\n    };\n\n    opt\n}\n"
  },
  {
    "path": "src/shell/mod.rs",
    "content": "mod bash;\nmod fish;\nmod infer;\nmod powershell;\nmod windows_cmd;\nmod zsh;\n\n#[allow(clippy::module_inception)]\nmod shell;\nmod windows_compat;\n\npub use bash::Bash;\npub use fish::Fish;\npub use infer::infer_shell;\npub use powershell::PowerShell;\npub use shell::{Shell, Shells};\npub use windows_cmd::WindowsCmd;\npub use windows_compat::maybe_fix_windows_path;\npub use zsh::Zsh;\n"
  },
  {
    "path": "src/shell/powershell.rs",
    "content": "use crate::version_file_strategy::VersionFileStrategy;\n\nuse super::Shell;\nuse indoc::formatdoc;\nuse std::path::Path;\n\n#[derive(Debug)]\npub struct PowerShell;\n\nimpl Shell for PowerShell {\n    fn path(&self, path: &Path) -> anyhow::Result<String> {\n        let current_path =\n            std::env::var_os(\"PATH\").ok_or_else(|| anyhow::anyhow!(\"Can't read PATH env var\"))?;\n        let mut split_paths: Vec<_> = std::env::split_paths(&current_path).collect();\n        split_paths.insert(0, path.to_path_buf());\n        let new_path = std::env::join_paths(split_paths)\n            .map_err(|source| anyhow::anyhow!(\"Can't join paths: {}\", source))?;\n        let new_path = new_path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Can't read PATH\"))?;\n        Ok(self.set_env_var(\"PATH\", new_path))\n    }\n\n    fn set_env_var(&self, name: &str, value: &str) -> String {\n        format!(r#\"$env:{name} = \"{value}\"\"#)\n    }\n\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String> {\n        let version_file_exists_condition = if config.resolve_engines() {\n            \"(Test-Path .nvmrc) -Or (Test-Path .node-version) -Or (Test-Path package.json)\"\n        } else {\n            \"(Test-Path .nvmrc) -Or (Test-Path .node-version)\"\n        };\n        let autoload_hook = match config.version_file_strategy() {\n            VersionFileStrategy::Local => formatdoc!(\n                r\"\n                    If ({version_file_exists_condition}) {{ & fnm use --silent-if-unchanged }}\n                \",\n                version_file_exists_condition = version_file_exists_condition,\n            ),\n            VersionFileStrategy::Recursive => String::from(r\"fnm use --silent-if-unchanged\"),\n        };\n        Ok(formatdoc!(\n            r\"\n                function global:Set-FnmOnLoad {{ {autoload_hook} }}\n                function global:Set-LocationWithFnm {{ param($path); if ($path -eq $null) {{Set-Location}} else {{Set-Location $path}}; Set-FnmOnLoad }}\n                Set-Alias -Scope global cd_with_fnm Set-LocationWithFnm\n                Set-Alias -Option AllScope -Scope global cd Set-LocationWithFnm\n            \",\n            autoload_hook = autoload_hook\n        ))\n    }\n    fn to_clap_shell(&self) -> clap_complete::Shell {\n        clap_complete::Shell::PowerShell\n    }\n}\n"
  },
  {
    "path": "src/shell/shell.rs",
    "content": "use std::fmt::{Debug, Display};\nuse std::path::Path;\n\nuse clap::ValueEnum;\n\npub trait Shell: Debug {\n    fn path(&self, path: &Path) -> anyhow::Result<String>;\n    fn set_env_var(&self, name: &str, value: &str) -> String;\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String>;\n    fn rehash(&self) -> Option<&'static str> {\n        None\n    }\n    fn to_clap_shell(&self) -> clap_complete::Shell;\n}\n\n#[derive(Debug, Clone, ValueEnum)]\npub enum Shells {\n    Bash,\n    Zsh,\n    Fish,\n    #[clap(name = \"powershell\", alias = \"power-shell\")]\n    PowerShell,\n    #[cfg(windows)]\n    Cmd,\n}\n\nimpl Display for Shells {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Shells::Bash => f.write_str(\"bash\"),\n            Shells::Zsh => f.write_str(\"zsh\"),\n            Shells::Fish => f.write_str(\"fish\"),\n            Shells::PowerShell => f.write_str(\"powershell\"),\n            #[cfg(windows)]\n            Shells::Cmd => f.write_str(\"cmd\"),\n        }\n    }\n}\n\nimpl From<Shells> for Box<dyn Shell> {\n    fn from(shell: Shells) -> Box<dyn Shell> {\n        match shell {\n            Shells::Zsh => Box::from(super::zsh::Zsh),\n            Shells::Bash => Box::from(super::bash::Bash),\n            Shells::Fish => Box::from(super::fish::Fish),\n            Shells::PowerShell => Box::from(super::powershell::PowerShell),\n            #[cfg(windows)]\n            Shells::Cmd => Box::from(super::windows_cmd::WindowsCmd),\n        }\n    }\n}\n\nimpl From<Box<dyn Shell>> for clap_complete::Shell {\n    fn from(shell: Box<dyn Shell>) -> Self {\n        shell.to_clap_shell()\n    }\n}\n"
  },
  {
    "path": "src/shell/windows_cmd/cd.cmd",
    "content": "@echo off\ncd /d %*\nif \"%FNM_VERSION_FILE_STRATEGY%\" == \"recursive\" (\n  fnm use --silent-if-unchanged\n) else (\n  if exist .nvmrc (\n    fnm use --silent-if-unchanged\n  ) else (\n    if exist .node-version (\n      fnm use --silent-if-unchanged\n    )\n  )\n)\n@echo on\n"
  },
  {
    "path": "src/shell/windows_cmd/mod.rs",
    "content": "use super::shell::Shell;\nuse std::path::Path;\n\n#[derive(Debug)]\npub struct WindowsCmd;\n\nimpl Shell for WindowsCmd {\n    fn to_clap_shell(&self) -> clap_complete::Shell {\n        // TODO: move to Option\n        panic!(\"Shell completion is not supported for Windows Command Prompt. Maybe try using PowerShell for a better experience?\");\n    }\n\n    fn path(&self, path: &Path) -> anyhow::Result<String> {\n        let current_path =\n            std::env::var_os(\"path\").ok_or_else(|| anyhow::anyhow!(\"Can't read PATH env var\"))?;\n        let mut split_paths: Vec<_> = std::env::split_paths(&current_path).collect();\n        split_paths.insert(0, path.to_path_buf());\n        let new_path = std::env::join_paths(split_paths)\n            .map_err(|err| anyhow::anyhow!(\"Can't join paths: {}\", err))?;\n        let new_path = new_path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Can't convert path to string\"))?;\n        Ok(format!(\"SET PATH={new_path}\"))\n    }\n\n    fn set_env_var(&self, name: &str, value: &str) -> String {\n        format!(\"SET {name}={value}\")\n    }\n\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String> {\n        let path = config.base_dir_with_default().join(\"cd.cmd\");\n        create_cd_file_at(&path).map_err(|source| {\n            anyhow::anyhow!(\n                \"Can't create cd.cmd file for use-on-cd at {}: {}\",\n                path.display(),\n                source\n            )\n        })?;\n        let path = path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Can't read path to cd.cmd\"))?;\n        Ok(format!(\"doskey cd=\\\"{path}\\\" $*\",))\n    }\n}\n\nfn create_cd_file_at(path: &std::path::Path) -> std::io::Result<()> {\n    use std::io::Write;\n    let cmd_contents = include_bytes!(\"./cd.cmd\");\n    let mut file = std::fs::File::create(path)?;\n    file.write_all(cmd_contents)?;\n    Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn use_on_cd_quotes_macro_path() {\n        let base_dir = std::env::temp_dir().join(\"fnm cmd test with spaces\");\n        std::fs::create_dir_all(&base_dir).unwrap();\n        let config = crate::config::FnmConfig::default().with_base_dir(Some(base_dir.clone()));\n        let output = WindowsCmd.use_on_cd(&config).unwrap();\n\n        assert!(output.starts_with(\"doskey cd=\\\"\"));\n        assert!(output.ends_with(\"\\\" $*\"));\n        assert!(output.contains(\"with spaces\"));\n        assert!(output.contains(\"cd.cmd\"));\n\n        std::fs::remove_file(base_dir.join(\"cd.cmd\")).unwrap();\n        std::fs::remove_dir_all(base_dir).unwrap();\n    }\n}\n"
  },
  {
    "path": "src/shell/windows_compat.rs",
    "content": "/// On Bash for Windows, we need to convert the path from a Windows-style\n/// path to a Unix-style path. This is because Bash for Windows doesn't\n/// understand Windows-style paths. We use `cygpath` to do this conversion.\n/// If `cygpath` fails, we assume we're not on Bash for Windows and just\n/// return the original path.\npub fn maybe_fix_windows_path(path: &str) -> Option<String> {\n    if !cfg!(windows) {\n        return None;\n    }\n\n    let output = std::process::Command::new(\"cygpath\")\n        .arg(path)\n        .output()\n        .ok()?;\n    if output.status.success() {\n        let output = String::from_utf8(output.stdout).ok()?;\n        Some(output.trim().to_string())\n    } else {\n        None\n    }\n}\n"
  },
  {
    "path": "src/shell/zsh.rs",
    "content": "use crate::version_file_strategy::VersionFileStrategy;\n\nuse super::shell::Shell;\nuse indoc::formatdoc;\nuse std::path::Path;\n\n#[derive(Debug)]\npub struct Zsh;\n\nimpl Shell for Zsh {\n    fn to_clap_shell(&self) -> clap_complete::Shell {\n        clap_complete::Shell::Zsh\n    }\n\n    fn path(&self, path: &Path) -> anyhow::Result<String> {\n        let path = path\n            .to_str()\n            .ok_or_else(|| anyhow::anyhow!(\"Path is not valid UTF-8\"))?;\n        let path =\n            super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string());\n        Ok(format!(\"export PATH={path:?}:$PATH\"))\n    }\n\n    fn set_env_var(&self, name: &str, value: &str) -> String {\n        format!(\"export {name}={value:?}\")\n    }\n\n    fn rehash(&self) -> Option<&'static str> {\n        Some(\"rehash\")\n    }\n\n    fn use_on_cd(&self, config: &crate::config::FnmConfig) -> anyhow::Result<String> {\n        let version_file_exists_condition = if config.resolve_engines() {\n            \"-f .node-version || -f .nvmrc || -f package.json\"\n        } else {\n            \"-f .node-version || -f .nvmrc\"\n        };\n        let autoload_hook = match config.version_file_strategy() {\n            VersionFileStrategy::Local => formatdoc!(\n                r\"\n                    if [[ {version_file_exists_condition} ]]; then\n                        fnm use --silent-if-unchanged\n                    fi\n                \",\n                version_file_exists_condition = version_file_exists_condition,\n            ),\n            VersionFileStrategy::Recursive => String::from(r\"fnm use --silent-if-unchanged\"),\n        };\n        Ok(formatdoc!(\n            r\"\n                autoload -U add-zsh-hook\n                _fnm_autoload_hook () {{\n                    {autoload_hook}\n                }}\n\n                add-zsh-hook -D chpwd _fnm_autoload_hook\n                add-zsh-hook chpwd _fnm_autoload_hook\n            \",\n            autoload_hook = autoload_hook\n        ))\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn use_on_cd_removes_existing_hook_before_adding() {\n        let output = Zsh.use_on_cd(&crate::config::FnmConfig::default()).unwrap();\n        assert!(output.contains(\"add-zsh-hook -D chpwd _fnm_autoload_hook\"));\n    }\n}\n"
  },
  {
    "path": "src/system_info.rs",
    "content": "#[cfg(target_os = \"macos\")]\npub fn platform_name() -> &'static str {\n    \"darwin\"\n}\n\n#[cfg(target_os = \"linux\")]\npub fn platform_name() -> &'static str {\n    \"linux\"\n}\n\n#[cfg(all(\n    target_pointer_width = \"32\",\n    any(target_arch = \"arm\", target_arch = \"aarch64\")\n))]\npub fn platform_arch() -> &'static str {\n    \"armv7l\"\n}\n\n#[cfg(all(\n    target_pointer_width = \"32\",\n    not(any(target_arch = \"arm\", target_arch = \"aarch64\"))\n))]\npub fn platform_arch() -> &'static str {\n    \"x86\"\n}\n\n#[cfg(all(\n    target_pointer_width = \"64\",\n    any(target_arch = \"arm\", target_arch = \"aarch64\")\n))]\npub fn platform_arch() -> &'static str {\n    \"arm64\"\n}\n\n#[cfg(all(\n    target_pointer_width = \"64\",\n    not(any(target_arch = \"arm\", target_arch = \"aarch64\"))\n))]\npub fn platform_arch() -> &'static str {\n    \"x64\"\n}\n"
  },
  {
    "path": "src/system_version.rs",
    "content": "use std::path::PathBuf;\n\npub fn path() -> PathBuf {\n    let path_as_string = if cfg!(windows) {\n        \"Z:/_fnm_/Nothing/Should/Be/Here/installation\"\n    } else {\n        \"/dev/null/installation\"\n    };\n\n    PathBuf::from(path_as_string)\n}\n\npub fn display_name() -> &'static str {\n    \"system\"\n}\n"
  },
  {
    "path": "src/user_version.rs",
    "content": "use crate::version::Version;\nuse std::str::FromStr;\n\n#[derive(Clone, Debug)]\npub enum UserVersion {\n    OnlyMajor(u64),\n    MajorMinor(u64, u64),\n    SemverRange(node_semver::Range),\n    Full(Version),\n}\n\nimpl UserVersion {\n    pub fn to_version<'a, T>(\n        &self,\n        available_versions: T,\n        config: &crate::config::FnmConfig,\n    ) -> Option<&'a Version>\n    where\n        T: IntoIterator<Item = &'a Version>,\n    {\n        available_versions\n            .into_iter()\n            .filter(|x| self.matches(x, config))\n            .max()\n    }\n\n    pub fn alias_name(&self) -> Option<String> {\n        match self {\n            Self::Full(version) => version.alias_name(),\n            _ => None,\n        }\n    }\n\n    pub fn matches(&self, version: &Version, config: &crate::config::FnmConfig) -> bool {\n        match (self, version) {\n            (Self::Full(a), b) if a == b => true,\n            (Self::Full(user_version), maybe_alias) => {\n                match (user_version.alias_name(), maybe_alias.find_aliases(config)) {\n                    (None, _) | (_, Err(_)) => false,\n                    (Some(user_alias), Ok(aliases)) => {\n                        aliases.iter().any(|alias| alias.name() == user_alias)\n                    }\n                }\n            }\n            (Self::SemverRange(range), Version::Semver(semver)) => semver.satisfies(range),\n            (_, Version::Bypassed | Version::Lts(_) | Version::Alias(_) | Version::Latest) => false,\n            (Self::OnlyMajor(major), Version::Semver(other)) => *major == other.major,\n            (Self::MajorMinor(major, minor), Version::Semver(other)) => {\n                *major == other.major && *minor == other.minor\n            }\n        }\n    }\n\n    /// The inferred alias for the user version, if it exists.\n    pub fn inferred_alias(&self) -> Option<Version> {\n        match self {\n            UserVersion::Full(Version::Latest) => Some(Version::Latest),\n            UserVersion::Full(Version::Lts(lts_type)) => Some(Version::Lts(lts_type.clone())),\n            _ => None,\n        }\n    }\n}\n\nfn next_of<'a, T: FromStr, It: Iterator<Item = &'a str>>(i: &mut It) -> Option<T> {\n    let x = i.next()?;\n    T::from_str(x).ok()\n}\n\nimpl std::fmt::Display for UserVersion {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Self::Full(x) => x.fmt(f),\n            Self::SemverRange(x) => x.fmt(f),\n            Self::OnlyMajor(major) => write!(f, \"v{major}.x.x\"),\n            Self::MajorMinor(major, minor) => write!(f, \"v{major}.{minor}.x\"),\n        }\n    }\n}\n\nfn skip_first_v(str: &str) -> &str {\n    str.strip_prefix('v').unwrap_or(str)\n}\n\nimpl FromStr for UserVersion {\n    type Err = node_semver::SemverError;\n    fn from_str(s: &str) -> Result<UserVersion, Self::Err> {\n        match Version::parse(s) {\n            Ok(v) => Ok(Self::Full(v)),\n            Err(e) => {\n                let mut parts = skip_first_v(s.trim()).split('.');\n                match (next_of::<u64, _>(&mut parts), next_of::<u64, _>(&mut parts)) {\n                    (Some(major), None) => Ok(Self::OnlyMajor(major)),\n                    (Some(major), Some(minor)) => Ok(Self::MajorMinor(major, minor)),\n                    _ => Err(e),\n                }\n            }\n        }\n    }\n}\n\n#[cfg(test)]\nimpl PartialEq for UserVersion {\n    fn eq(&self, other: &Self) -> bool {\n        match (self, other) {\n            (Self::OnlyMajor(a), Self::OnlyMajor(b)) if a == b => true,\n            (Self::MajorMinor(a1, a2), Self::MajorMinor(b1, b2)) if (a1, a2) == (b1, b2) => true,\n            (Self::Full(v1), Self::Full(v2)) if v1 == v2 => true,\n            (_, _) => false,\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use crate::config::FnmConfig;\n\n    use super::*;\n\n    #[test]\n    fn test_parsing_only_major() {\n        let version = UserVersion::from_str(\"10\").ok();\n        assert_eq!(version, Some(UserVersion::OnlyMajor(10)));\n    }\n\n    #[test]\n    fn test_parsing_major_minor() {\n        let version = UserVersion::from_str(\"10.20\").ok();\n        assert_eq!(version, Some(UserVersion::MajorMinor(10, 20)));\n    }\n\n    #[test]\n    fn test_parsing_only_major_with_v() {\n        let version = UserVersion::from_str(\"v10\").ok();\n        assert_eq!(version, Some(UserVersion::OnlyMajor(10)));\n    }\n\n    #[test]\n    fn test_major_to_version() {\n        let expected = Version::parse(\"6.1.0\").unwrap();\n        let versions = vec![\n            Version::parse(\"6.0.0\").unwrap(),\n            Version::parse(\"6.0.1\").unwrap(),\n            expected.clone(),\n            Version::parse(\"7.0.1\").unwrap(),\n        ];\n        let result = UserVersion::OnlyMajor(6).to_version(&versions, &FnmConfig::default());\n\n        assert_eq!(result, Some(&expected));\n    }\n\n    #[test]\n    fn test_major_minor_to_version() {\n        let expected = Version::parse(\"6.0.1\").unwrap();\n        let versions = vec![\n            Version::parse(\"6.0.0\").unwrap(),\n            Version::parse(\"6.1.0\").unwrap(),\n            expected.clone(),\n            Version::parse(\"7.0.1\").unwrap(),\n        ];\n        let result = UserVersion::MajorMinor(6, 0).to_version(&versions, &FnmConfig::default());\n\n        assert_eq!(result, Some(&expected));\n    }\n\n    #[test]\n    fn test_semver_to_version() {\n        let expected = Version::parse(\"6.0.0\").unwrap();\n        let versions = vec![\n            expected.clone(),\n            Version::parse(\"6.1.0\").unwrap(),\n            Version::parse(\"6.0.1\").unwrap(),\n            Version::parse(\"7.0.1\").unwrap(),\n        ];\n        let result =\n            UserVersion::Full(expected.clone()).to_version(&versions, &FnmConfig::default());\n\n        assert_eq!(result, Some(&expected));\n    }\n}\n"
  },
  {
    "path": "src/user_version_reader.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::user_version::UserVersion;\nuse crate::version_files::{get_user_version_for_directory, get_user_version_for_file};\nuse std::path::PathBuf;\nuse std::str::FromStr;\n\n#[derive(Debug, Clone)]\npub enum UserVersionReader {\n    Direct(UserVersion),\n    Path(PathBuf),\n}\n\nimpl UserVersionReader {\n    pub fn into_user_version(self, config: &FnmConfig) -> Option<UserVersion> {\n        match self {\n            Self::Direct(uv) => Some(uv),\n            Self::Path(pathbuf) if pathbuf.is_file() => get_user_version_for_file(pathbuf, config),\n            Self::Path(pathbuf) => get_user_version_for_directory(pathbuf, config),\n        }\n    }\n}\n\nimpl FromStr for UserVersionReader {\n    type Err = node_semver::SemverError;\n\n    fn from_str(s: &str) -> Result<Self, Self::Err> {\n        let pathbuf = PathBuf::from_str(s);\n        let user_version = UserVersion::from_str(s);\n        match (user_version, pathbuf) {\n            (_, Ok(pathbuf)) if pathbuf.exists() => Ok(Self::Path(pathbuf)),\n            (Ok(user_version), _) => Ok(Self::Direct(user_version)),\n            (Err(user_version_err), _) => Err(user_version_err),\n        }\n    }\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n    use crate::version::Version;\n    use pretty_assertions::assert_eq;\n    use std::io::Write;\n    use tempfile::{NamedTempFile, TempDir};\n\n    #[test]\n    fn test_file_pathbuf_to_version() {\n        let mut file = NamedTempFile::new().unwrap();\n        file.write_all(b\"14\").unwrap();\n        let pathbuf = file.path().to_path_buf();\n\n        let user_version =\n            UserVersionReader::Path(pathbuf).into_user_version(&FnmConfig::default());\n        assert_eq!(user_version, Some(UserVersion::OnlyMajor(14)));\n    }\n\n    #[test]\n    fn test_directory_pathbuf_to_version() {\n        let directory = TempDir::new().unwrap();\n        let node_version_path = directory.path().join(\".node-version\");\n        std::fs::write(node_version_path, \"14\").unwrap();\n        let pathbuf = directory.path().to_path_buf();\n\n        let user_version =\n            UserVersionReader::Path(pathbuf).into_user_version(&FnmConfig::default());\n        assert_eq!(user_version, Some(UserVersion::OnlyMajor(14)));\n    }\n\n    #[test]\n    fn test_direct_to_version() {\n        let user_version = UserVersionReader::Direct(UserVersion::OnlyMajor(14))\n            .into_user_version(&FnmConfig::default());\n        assert_eq!(user_version, Some(UserVersion::OnlyMajor(14)));\n    }\n\n    #[test]\n    fn test_from_str_directory() {\n        let directory = TempDir::new().unwrap();\n        let node_version_path = directory.path().join(\".node-version\");\n        std::fs::write(node_version_path, \"14\").unwrap();\n        let pathbuf = directory.path().to_path_buf();\n\n        let user_version = UserVersionReader::from_str(pathbuf.to_str().unwrap());\n        assert!(matches!(user_version, Ok(UserVersionReader::Path(_))));\n    }\n\n    #[test]\n    fn test_from_str_file() {\n        let mut file = NamedTempFile::new().unwrap();\n        write!(file, \"14\").unwrap();\n        let pathbuf = file.path().to_path_buf();\n\n        let user_version = UserVersionReader::from_str(pathbuf.to_str().unwrap());\n        assert!(matches!(user_version, Ok(UserVersionReader::Path(_))));\n    }\n\n    #[test]\n    fn test_non_existing_path() {\n        let user_version =\n            UserVersionReader::from_str(\"/tmp/some_random_text_that_probably_does_not_exist\");\n        assert!(matches!(\n            user_version,\n            Ok(UserVersionReader::Direct(UserVersion::Full(\n                Version::Alias(_)\n            )))\n        ));\n    }\n\n    #[test]\n    fn test_a_version_number() {\n        let user_version = UserVersionReader::from_str(\"12.0\");\n        assert!(matches!(\n            user_version,\n            Ok(UserVersionReader::Direct(UserVersion::MajorMinor(12, 0)))\n        ));\n    }\n}\n"
  },
  {
    "path": "src/version.rs",
    "content": "use crate::alias;\nuse crate::config;\nuse crate::lts::LtsType;\nuse crate::system_version;\nuse std::str::FromStr;\n\n#[derive(Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]\npub enum Version {\n    Semver(node_semver::Version),\n    Lts(LtsType),\n    Alias(String),\n    Latest,\n    Bypassed,\n}\n\nfn first_letter_is_number(s: &str) -> bool {\n    s.chars().next().is_some_and(|x| x.is_ascii_digit())\n}\n\nimpl Version {\n    pub fn parse<S: AsRef<str>>(version_str: S) -> Result<Self, node_semver::SemverError> {\n        let lowercased = version_str.as_ref().to_lowercase();\n        if lowercased == system_version::display_name() {\n            Ok(Self::Bypassed)\n        } else if lowercased.starts_with(\"lts-\") || lowercased.starts_with(\"lts/\") {\n            let lts_type = LtsType::from(&lowercased[4..]);\n            Ok(Self::Lts(lts_type))\n        } else if first_letter_is_number(lowercased.trim_start_matches('v')) {\n            let version_plain = lowercased.trim_start_matches('v');\n            let sver = node_semver::Version::parse(version_plain)?;\n            Ok(Self::Semver(sver))\n        } else {\n            Ok(Self::Alias(lowercased))\n        }\n    }\n\n    pub fn alias_name(&self) -> Option<String> {\n        match self {\n            l @ (Self::Lts(_) | Self::Alias(_)) => Some(l.v_str()),\n            _ => None,\n        }\n    }\n\n    pub fn find_aliases(\n        &self,\n        config: &config::FnmConfig,\n    ) -> std::io::Result<Vec<alias::StoredAlias>> {\n        let aliases = alias::list_aliases(config)?\n            .drain(..)\n            .filter(|alias| alias.s_ver() == self.v_str())\n            .collect();\n        Ok(aliases)\n    }\n\n    pub fn v_str(&self) -> String {\n        format!(\"{self}\")\n    }\n\n    pub fn installation_path(&self, config: &config::FnmConfig) -> std::path::PathBuf {\n        match self {\n            Self::Bypassed => system_version::path(),\n            v @ (Self::Lts(_) | Self::Alias(_) | Self::Latest) => {\n                config.aliases_dir().join(v.alias_name().unwrap())\n            }\n            v @ Self::Semver(_) => config\n                .installations_dir()\n                .join(v.v_str())\n                .join(\"installation\"),\n        }\n    }\n\n    pub fn root_path(&self, config: &config::FnmConfig) -> Option<std::path::PathBuf> {\n        let path = self.installation_path(config);\n        let mut canon_path = path.canonicalize().ok()?;\n        canon_path.pop();\n        Some(canon_path)\n    }\n}\n\n// TODO: add a trait called BinPath that &Path and PathBuf implements\n// which adds the `.bin_path()` which works both on windows and unix :)\n\nimpl<'de> serde::Deserialize<'de> for Version {\n    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n    where\n        D: serde::Deserializer<'de>,\n    {\n        let version_str = String::deserialize(deserializer)?;\n        Version::parse(version_str).map_err(serde::de::Error::custom)\n    }\n}\n\nimpl std::fmt::Display for Version {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        match self {\n            Self::Bypassed => write!(f, \"{}\", system_version::display_name()),\n            Self::Lts(lts) => write!(f, \"lts-{lts}\"),\n            Self::Semver(semver) => write!(f, \"v{semver}\"),\n            Self::Alias(alias) => write!(f, \"{alias}\"),\n            Self::Latest => write!(f, \"latest\"),\n        }\n    }\n}\n\nimpl FromStr for Version {\n    type Err = node_semver::SemverError;\n    fn from_str(s: &str) -> Result<Version, Self::Err> {\n        Self::parse(s)\n    }\n}\n\nimpl PartialEq<node_semver::Version> for Version {\n    fn eq(&self, other: &node_semver::Version) -> bool {\n        match self {\n            Self::Bypassed | Self::Lts(_) | Self::Alias(_) | Self::Latest => false,\n            Self::Semver(v) => v == other,\n        }\n    }\n}\n"
  },
  {
    "path": "src/version_file_strategy.rs",
    "content": "use clap::ValueEnum;\nuse std::fmt::Display;\n\n#[derive(Debug, Clone, Copy, Default, ValueEnum)]\npub enum VersionFileStrategy {\n    /// Use the local version of Node defined within the current directory\n    #[default]\n    Local,\n    /// Use the version of Node defined within the current directory and all parent directories\n    Recursive,\n}\n\nimpl VersionFileStrategy {\n    pub fn as_str(self) -> &'static str {\n        match self {\n            VersionFileStrategy::Local => \"local\",\n            VersionFileStrategy::Recursive => \"recursive\",\n        }\n    }\n}\n\nimpl Display for VersionFileStrategy {\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n        f.write_str(self.as_str())\n    }\n}\n"
  },
  {
    "path": "src/version_files.rs",
    "content": "use crate::config::FnmConfig;\nuse crate::default_version;\nuse crate::package_json::PackageJson;\nuse crate::user_version::UserVersion;\nuse crate::version_file_strategy::VersionFileStrategy;\nuse encoding_rs_io::DecodeReaderBytes;\nuse log::info;\nuse std::io::Read;\nuse std::path::Path;\nuse std::str::FromStr;\n\nconst PATH_PARTS: [&str; 3] = [\".nvmrc\", \".node-version\", \"package.json\"];\n\npub fn get_user_version_for_directory(\n    path: impl AsRef<Path>,\n    config: &FnmConfig,\n) -> Option<UserVersion> {\n    match config.version_file_strategy() {\n        VersionFileStrategy::Local => get_user_version_for_single_directory(path, config),\n        VersionFileStrategy::Recursive => get_user_version_for_directory_recursive(path, config)\n            .or_else(|| {\n                info!(\"Did not find anything recursively. Falling back to default alias.\");\n                default_version::find_default_version(config).map(UserVersion::Full)\n            }),\n    }\n}\n\nfn get_user_version_for_directory_recursive(\n    path: impl AsRef<Path>,\n    config: &FnmConfig,\n) -> Option<UserVersion> {\n    let mut current_path = Some(path.as_ref());\n\n    while let Some(child_path) = current_path {\n        if let Some(version) = get_user_version_for_single_directory(child_path, config) {\n            return Some(version);\n        }\n\n        current_path = child_path.parent();\n    }\n\n    None\n}\n\nfn get_user_version_for_single_directory(\n    path: impl AsRef<Path>,\n    config: &FnmConfig,\n) -> Option<UserVersion> {\n    let path = path.as_ref();\n\n    for path_part in &PATH_PARTS {\n        let new_path = path.join(path_part);\n        info!(\n            \"Looking for version file in {}. exists? {}\",\n            new_path.display(),\n            new_path.exists()\n        );\n        if let Some(version) = get_user_version_for_file(&new_path, config) {\n            return Some(version);\n        }\n    }\n\n    None\n}\n\npub fn get_user_version_for_file(\n    path: impl AsRef<Path>,\n    config: &FnmConfig,\n) -> Option<UserVersion> {\n    let is_pkg_json = match path.as_ref().file_name() {\n        Some(name) => name == \"package.json\",\n        None => false,\n    };\n    let file = std::fs::File::open(path).ok()?;\n    let file = {\n        let mut reader = DecodeReaderBytes::new(file);\n        let mut version = String::new();\n        reader.read_to_string(&mut version).map(|_| version)\n    };\n\n    match (file, is_pkg_json, config.resolve_engines()) {\n        (_, true, false) => None,\n        (Err(err), _, _) => {\n            info!(\"Can't read file: {}\", err);\n            None\n        }\n        (Ok(version), false, _) => {\n            info!(\"Found string {:?} in version file\", version);\n            UserVersion::from_str(version.trim()).ok()\n        }\n        (Ok(pkg_json), true, true) => {\n            let pkg_json = serde_json::from_str::<PackageJson>(&pkg_json).ok();\n            let range: Option<node_semver::Range> =\n                pkg_json.as_ref().and_then(PackageJson::node_range).cloned();\n\n            if let Some(range) = range {\n                info!(\"Found package.json with {:?} in engines.node field\", range);\n                Some(UserVersion::SemverRange(range))\n            } else {\n                info!(\"No engines.node range found in package.json\");\n                None\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "tests/proxy-server/index.mjs",
    "content": "// @ts-check\n\nimport { createServer } from \"node:http\"\nimport path from \"node:path\"\nimport fs from \"node:fs\"\nimport crypto from \"node:crypto\"\nimport fetch from \"node-fetch\"\nimport chalk from \"chalk\"\nimport pRetry from \"p-retry\"\n\nconst baseDir = path.join(process.cwd(), \".proxy\")\ntry {\n  fs.mkdirSync(baseDir, { recursive: true })\n} catch (e) {}\n\n/** @type {Map<string, Promise<{ headers: Record<string, string>, body: ArrayBuffer }>>} */\nconst cache = new Map()\n\n/**\n * @param {object} opts\n * @param {string} opts.pathname\n * @param {string} opts.headersFilename\n * @param {string} opts.filename\n */\nconst download = async ({ pathname, filename, headersFilename }) => {\n  const response = await fetch(\n    \"https://nodejs.org/dist/\" + pathname.replace(/^\\/+/, \"\"),\n    {\n      compress: false,\n    },\n  )\n  const headers = Object.fromEntries(response.headers.entries())\n  headers.__status__ = String(response.status)\n  const body = await response.arrayBuffer()\n  fs.writeFileSync(headersFilename, JSON.stringify(headers))\n  fs.writeFileSync(filename, Buffer.from(body))\n  return { headers, body }\n}\n\nexport const server = createServer((req, res) => {\n  const pathname = req.url ?? \"/\"\n  const hash = crypto\n    .createHash(\"sha1\")\n    .update(pathname ?? \"/\")\n    .digest(\"hex\")\n  const extension = path.extname(pathname)\n  const filename = path.join(baseDir, hash) + extension\n  const headersFilename = path.join(baseDir, hash) + \".headers.json\"\n  try {\n    const { __status__ = \"200\", ...headers } = JSON.parse(\n      fs.readFileSync(headersFilename, \"utf-8\"),\n    )\n    const status = parseInt(__status__, 10)\n    const body = fs.createReadStream(filename)\n    console.log(chalk.green.dim(`[proxy] hit: ${pathname} -> ${filename}`))\n    res.writeHead(status, headers)\n    body.pipe(res)\n  } catch {\n    let promise = cache.get(filename)\n    if (!promise) {\n      console.log(chalk.red.dim(`[proxy] miss: ${pathname} -> ${filename}`))\n      promise = pRetry(\n        () => download({ pathname, headersFilename, filename }),\n        {\n          retries: 5,\n          maxTimeout: 5000,\n          onFailedAttempt: (error) => {\n            console.error(\n              chalk.red(\n                `[proxy] ${chalk.bold(\"error\")}: ${error.message}, retries left: ${error.retriesLeft}`,\n              ),\n            )\n          },\n        },\n      )\n      cache.set(filename, promise)\n      promise.finally(() => cache.delete(filename))\n    }\n\n    promise.then(\n      ({ headers: { __status__ = \"200\", ...headers }, body }) => {\n        res.writeHead(parseInt(__status__, 10), headers)\n        res.end(Buffer.from(body))\n      },\n      (err) => {\n        console.error(err)\n        res.writeHead(500)\n        res.end()\n      },\n    )\n  }\n})\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"moduleDetection\": \"force\",\n    \"module\": \"esnext\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true\n  }\n}\n"
  }
]