Skip to content

fix(install): extract the release outside the caller's working directory - #30

Open
matbrgz wants to merge 1 commit into
owenizedd:mainfrom
webminas:main
Open

matbrgz wants to merge 1 commit into
owenizedd:mainfrom
webminas:main

Conversation

@matbrgz

@matbrgz matbrgz commented Mar 4, 2025 •

Copy link
Copy Markdown

Rebased onto current main (v0.7.22) and rewritten. The original version of this PR was a rewrite of the v0.6.1 script and would have reverted work that has since landed on main — colors, the idempotent add_to_config, the download retry with backoff, and $HOME/.bun/bin on PATH are all kept. What is left is the delta that fixes actual bugs: 62 insertions, 40 deletions, no conflicts.

The info/info_bold helpers mentioned in the earlier review are gone from this PR, since they are already on main.

The main bug: the archive is extracted into the caller's working directory

tar -xvf "$exe_compressed" runs without -C, so the tarball is unpacked wherever the user happens to be standing when they pipe the script into bash. mv "$bum_folder_name/bum" and rm -r $bum_folder_name then operate on that same directory.

Two ways this breaks, both reproduced against the real v0.7.22 release on macOS (aarch64, bash 3.2):

Scenario main today This PR
CWD is not writable (curl | bash from a read-only or system directory) aborts: error: Failed on decompress the executable, and leaves a ~2 MB orphan bum.tar.gz behind in $BUM_INSTALL/bin installs cleanly, bum --version → 0.7.22
CWD already contains a bum-v0.7.22-<target> directory rm -r deletes the user's directory untouched
tar missing from PATH downloads 2 MB first, then fails with tar: command not found fails immediately with error: 'tar' is required to install bum but was not found in PATH

Fix: unpack into a mktemp -d scratch directory, with a trap ... EXIT that removes both the scratch directory and the downloaded tarball on every exit path — success or failure. Nothing is ever written to the caller's CWD.

Other fixes in the same pass

  • Dependency check up front. curl, tar, uname, mktemp, mkdir, mv, rm, chmod, grep, basename are verified before anything is downloaded. bun is deliberately excluded so the "install bun first" path stays reachable.
  • bun is detected with command -v instead of being executed (if ! bun &>/dev/null actually runs bun).
  • $refresh_command is printed again. It is computed for fish, zsh and bash and then never shown, so users never get the source ~/.bashrc / exec $SHELL hint. Restored at the end of the script.
  • Archive contents are verified before mv, so a malformed release gives a real message instead of a bare mv: No such file or directory.
  • "Add manually" message points at bash_configs[0]. It used $tilde_bash_config from the last iteration of the loop, which could suggest an $XDG_CONFIG_HOME path the user has never seen.
  • GITHUB=${GITHUB:-...} so an empty value falls back to github.com instead of producing an empty URL.
  • tildify matches with "$HOME/"* so a $HOME containing glob characters is not treated as a pattern.

ShellCheck

shellcheck -S style install.sh on current main reports 8 findings; this branch reports none.

  • SC2145 ×3 — $@ interpolated into a string in info, info_bold, success → $*
  • SC2027 + SC2086 — broken quoting in echo "bum was installed successfully to "$exe""
  • SC2086 — unquoted $exe in mv
  • SC2034 ×2 — Bold_Green and tilde_bin_dir are assigned and never used; both removed

The one remaining SC2088 is a false positive (tildify's ~ is literal display output) and is suppressed inline with a comment explaining why.

Testing

Run against the real v0.7.22 release on macOS aarch64-apple-darwin, bash 3.2, with an isolated $HOME and $BUM_INSTALL:

  1. Clean install from an empty CWD — binary installs, bum --version → 0.7.22, config block written, refresh hint printed, CWD still empty afterwards
  2. Second run — Configuration block already present, exactly one # bum block in the config, no leftover tarball
  3. Install from a read-only CWD — succeeds here, fails on main (table above)
  4. tar removed from PATH — fails fast with a clear message
  5. Machine without bun (installer stubbed out) — takes the install-bun path and completes
  6. shellcheck -S style clean, bash -n clean

@owenizedd

Copy link
Copy Markdown
Owner

Did you test this change?
And can you tell me which change fix the bugs?

Comment thread install.sh Outdated
info_bold() { echo -e "\e[1m$*\e[0m"; }

# --- Dependency Check ---
for cmd in bun curl tar uname mkdir mv rm; do

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is contradictory with line 18 no? you check bun here but will never reach line 18 (installing bun)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My fault. Fixing it.

@owenizedd

Copy link
Copy Markdown
Owner

I see that you added the info, I took this as reference from bun repo and I already push it to main for that particular code, however other improvements looks good if you updated it and tested to be working fine.

@matbrgz matbrgz left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Auto-revisão antes de responder ao mantenedor. @owenizedd perguntou em 05/03 "Did you test this change? And can you tell me which change fix the bugs?" e em 11/03 disse que já levou o info para o main. Reli o PR contra o main de hoje e há coisas que precisam ser resolvidas antes de qualquer merge — algumas são regressões em relação ao que o main já tem.

1. O PR volta a versão: v0.7.22 → v0.6.1

-VERSION="v0.7.22"     # main hoje
+VERSION="v0.6.1"      # este PR

Esse era o valor correto quando o PR foi aberto, mas o main avançou. Mergeando como está, o instalador passaria a baixar uma release 16 versões atrás. Precisa rebase.

2. A lógica de instalar o Bun automaticamente é inalcançável

A checagem de dependências roda antes e inclui bun:

# linha 10
for cmd in bun curl tar uname mkdir mv rm; do
    command -v "$cmd" >/dev/null 2>&1 || error "The command '$cmd' is required but not installed."
done

# linha 17 — nunca chega aqui se bun não existir
if ! command -v bun &>/dev/null; then
    info "Bun not found. Installing Bun..."
    curl -fsSL https://bun.sh/install | bash || error "Failed to install Bun."
fi

Se o Bun não estiver instalado — exatamente o caso que o bloco de baixo existe para tratar — o error() da linha 10 mata o script antes. O recurso anunciado na descrição do PR ("Added logic to automatically install Bun if it's not already available") é código morto.

Conserto: tirar bun da lista do laço e deixar só curl tar uname mkdir mv rm.

3. O PR remove o retry com backoff que o main tem hoje

O main tem download_with_retry(): 3 tentativas, espera exponencial (2s → 4s), --max-time crescente (30s → 60s → 90s). Este PR substitui tudo por um curl único:

curl --fail --location --progress-bar --output "$exe_compressed" "$bum_uri" \
    || error "Failed to download bum from \"$bum_uri\""

Para um instalador que roda via curl | bash em rede de qualidade variável, perder o retry é um retrocesso concreto.

4. O PR remove a proteção contra duplicar a configuração do shell

O main tem add_to_config() com guarda de idempotência:

if grep -q "^$marker" "$config_file" 2>/dev/null; then
    info "Configuration block already present in $config_file, skipping addition."
    return
fi

O add_commands_to_file() deste PR sempre anexa:

{
    echo -e "\n# bum"
    for command in "${commands[@]}"; do echo "$command"; done
} >> "$file"

Ou seja: rodar o instalador duas vezes deixa dois blocos # bum no .zshrc/.bashrc; rodar cinco vezes, cinco. É o tipo de coisa que o usuário só descobre quando o PATH está cheio de repetição.

5. As cores regridem, e o mantenedor já disse qual versão prefere

O main condiciona as cores a [[ -t 1 ]] (só colore quando a saída é um terminal) e usa Color_Off, Red, Dim, Bold_White. Este PR troca por:

error()     { echo -e "[ERROR] $*" >&2; exit 1; }
info()      { echo -e "[INFO] $*"; }
info_bold() { echo -e "\e[1m$*\e[0m"; }

Três problemas: perde a cor em error/info; o info_bold não checa TTY, então injeta \e[1m bruto quando a saída vai para arquivo ou pipe (o caso comum de curl ... | bash > log); e \e é menos portável que \033.

Some-se a isso que o @owenizedd já disse ter levado a versão dele (inspirada no repo do Bun) para o main. Esta parte do PR precisa simplesmente sair.

6. success() sumiu

O main tem success() (verde) e a usa no caminho de download bem-sucedido. O PR remove a função sem substituto.

O que de fato vale a pena manter

Separando o joio, estas partes são melhorias reais que o main não tem:

  • Extração em mktemp -d com trap 'rm -rf "${temp_dir:?}"' EXIT. O main extrai no diretório corrente e depois faz rm -r $bum_folder_name sem aspas — se $bum_folder_name estiver vazio ou contiver espaço, isso é perigoso. O :? do PR é a guarda certa.
  • Verificar que o binário existe antes do mv:
    if [[ -f "$temp_dir/$bum_folder_name/bum" ]]; then mv ... else error "Executable not found..."; fi
    O main faz mv "$bum_folder_name/bum" $exe direto, com $exe sem aspas.
  • Aspas e command -v em lugar de bun &>/dev/null. O main roda bun de verdade (executa o binário) só para testar existência; command -v é o correto.
  • GITHUB="${GITHUB:-https://github.com}" com :- em vez de -, e case "$arch" com aspas.
  • Erro explícito em cada passo (mkdir, tar, mv, chmod).

Sugestão de encaminhamento

Do jeito que está, o PR mistura ~6 melhorias legítimas com 4 regressões e um bug de ordenação. Eu proporia ao @owenizedd fatiar em um PR pequeno e testável, sobre o main atual, contendo só:

  1. mktemp -d + trap + ${var:?} nas remoções (a parte de maior valor)
  2. checagem de existência antes do mv, com aspas em $exe
  3. command -v bun no lugar de bun &>/dev/null
  4. checagem de dependências sem bun na lista
  5. aspas e :- nas expansões

…e deixando de fora as funções de log (item 5), o retry (item 3), o add_to_config (item 4) e o VERSION (item 1), que o main já resolve melhor.

Respondendo à pergunta do @owenizedd sobre qual mudança conserta qual bug: os consertos concretos são o (1) — extração fora do diretório corrente e rm protegido — e o (2) — falha explícita quando o tarball não traz o binário esperado, em vez de um mv silenciosamente quebrado. O resto é robustez e estilo.

`tar -xvf` ran without `-C`, so the archive was unpacked into whatever
directory the user happened to be in when piping the script to bash. That
fails outright when the CWD is not writable (reproduced: `curl | bash` from
a read-only directory aborts with "Failed on decompress the executable" and
leaves a ~2MB orphan bum.tar.gz in $BUM_INSTALL/bin), and it clobbers any
existing `bum-$VERSION-$target` directory on the way out via `rm -r`.

The archive is now unpacked into a `mktemp -d` scratch directory with a
`trap ... EXIT` that removes both the scratch directory and the downloaded
tarball on every exit path, successful or not.

Other fixes in the same pass:

- Check required commands up front (curl, tar, uname, mktemp, ...) so a
  missing tool fails immediately with a clear message instead of halfway
  through, after the download.
- `bun` is detected with `command -v` rather than by executing it, and is
  explicitly excluded from the dependency check so the "install bun first"
  path is actually reachable.
- Verify the executable exists inside the archive before `mv`, instead of
  letting `mv` fail with a bare shell error.
- Print `$refresh_command` at the end. It was computed for every shell and
  then never shown, so users were left without the `source ~/.bashrc` hint.
- Fall back to `bash_configs[0]` in the "add manually" message; it used the
  last candidate tried, which could suggest an XDG path the user has never
  seen.
- `GITHUB` honours `:-` so an empty value falls back to github.com.
- ShellCheck is now clean at `-S style`: SC2145 in info/info_bold/success
  (`$@` inside a string), SC2027/SC2086 in the install message, SC2086 on
  `mv ... $exe`, SC2034 for the unused Bold_Green and tilde_bin_dir. The
  single remaining SC2088 is suppressed inline, since tildify's `~` is
  literal display output by design.
- `tildify` matches with `"$HOME/"*` so a $HOME containing glob characters
  is not treated as a pattern.

Tested on macOS (aarch64-apple-darwin, bash 3.2) against the real v0.7.22
release: clean install, re-run is idempotent, install from a read-only CWD,
missing-dependency path, and the no-bun-installed path.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@matbrgz matbrgz changed the title Improve Installation Script Robustness and Compliance fix(install): extract the release outside the caller's working directory Sep 22, 2026
@matbrgz

matbrgz commented Sep 22, 2026

Copy link
Copy Markdown
Author

Answering both questions, and the branch is rebased onto current main (v0.7.22) — it was conflicting before, it is mergeable now.

On info/info_bold: removed from this PR. They are on main already, so they are no longer part of the diff. The PR went from 159+/170- down to 62+/40-, because the old version was a rewrite of the v0.6.1 script and would have reverted the colors, the idempotent add_to_config, the retry with backoff and $HOME/.bun/bin on PATH. All of that is kept as-is.

Which change fixes the bug: extracting into a temp dir instead of the caller's working directory.

tar -xvf "$exe_compressed" has no -C, so the archive is unpacked into whatever directory the user is standing in when they pipe the script to bash, and mv "$bum_folder_name/bum" / rm -r $bum_folder_name then work on that directory. Running curl | bash from a directory that is not writable aborts the whole install:

x bum-v0.7.22-aarch64-apple-darwin/: Can't create 'bum-v0.7.22-aarch64-apple-darwin': Permission denied
x bum-v0.7.22-aarch64-apple-darwin/bum: Failed to create dir '...': Permission denied
tar: Error exit delayed from previous errors.
error: Failed on decompress the executable

and it leaves a ~2 MB orphan bum.tar.gz in $BUM_INSTALL/bin. Same script from the same directory with this branch installs fine and bum --version returns 0.7.22. The other case is a CWD that already has a bum-v0.7.22-<target> directory in it — rm -r deletes it.

The fix is mktemp -d plus a trap ... EXIT that cleans up the scratch dir and the tarball on every exit path. Nothing touches the caller's CWD anymore.

Two smaller bugs fixed alongside it:

  • $refresh_command is computed for fish, zsh and bash and then never printed — the block that shows it got lost at some point, so nobody sees the source ~/.bashrc / exec $SHELL hint. Restored.
  • The "Manually add the directory to ..." fallback for bash prints $tilde_bash_config from the last loop iteration, which can point at an $XDG_CONFIG_HOME path the user has never seen. It now points at bash_configs[0].

Did you test this change: yes, against the real v0.7.22 release on macOS aarch64-apple-darwin, bash 3.2, with an isolated $HOME and $BUM_INSTALL so nothing touched my own setup.

  1. Clean install from an empty CWD — installs, bum --version → 0.7.22, config block written, refresh hint printed, CWD still empty
  2. Running it a second time — Configuration block already present, exactly one # bum block, no leftover tarball
  3. Install from a read-only CWD — succeeds on this branch, fails on main (output above)
  4. tar removed from PATH — fails immediately with error: 'tar' is required to install bum but was not found in PATH, instead of downloading 2 MB and only then hitting tar: command not found
  5. Machine with no bun (bun installer stubbed so it would not actually download) — takes the install-bun path and completes. Worth noting this one was broken in my own earlier version of this PR: bun was in the dependency-check loop that runs before the block that installs bun, so anyone without bun hit a hard error and never reached the install. bun is excluded from that list now and detected with command -v.
  6. shellcheck -S style and bash -n both clean

On ShellCheck: main reports 8 findings today (SC2145 ×3 in info/info_bold/success, SC2027 + SC2086 in the install message, SC2086 on mv ... $exe, SC2034 for the unused Bold_Green and tilde_bin_dir). This branch reports none. The single SC2088 left is a false positive — tildify's ~ is literal display output — and it is suppressed inline with a comment saying so.

Happy to split the ShellCheck cleanup into its own PR if you would rather keep the bug fix isolated.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants