Repository navigation
Conversation
|
Did you test this change? |
| info_bold() { echo -e "\e[1m$*\e[0m"; } | ||
|
|
||
| # --- Dependency Check --- | ||
| for cmd in bun curl tar uname mkdir mv rm; do |
There was a problem hiding this comment.
this is contradictory with line 18 no? you check bun here but will never reach line 18 (installing bun)
|
I see that you added the |
matbrgz
left a comment
There was a problem hiding this comment.
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 PREsse 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."
fiSe 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
fiO 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 -dcomtrap 'rm -rf "${temp_dir:?}"' EXIT. Omainextrai no diretório corrente e depois fazrm -r $bum_folder_namesem aspas — se$bum_folder_nameestiver vazio ou contiver espaço, isso é perigoso. O:?do PR é a guarda certa. - Verificar que o binário existe antes do
mv:Oif [[ -f "$temp_dir/$bum_folder_name/bum" ]]; then mv ... else error "Executable not found..."; fi
mainfazmv "$bum_folder_name/bum" $exedireto, com$exesem aspas. - Aspas e
command -vem lugar debun &>/dev/null. Omainrodabunde verdade (executa o binário) só para testar existência;command -vé o correto. GITHUB="${GITHUB:-https://github.com}"com:-em vez de-, ecase "$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ó:
mktemp -d+trap+${var:?}nas remoções (a parte de maior valor)- checagem de existência antes do
mv, com aspas em$exe command -v bunno lugar debun &>/dev/null- checagem de dependências sem
bunna lista - 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>
|
Answering both questions, and the branch is rebased onto current On Which change fixes the bug: extracting into a temp dir instead of the caller's working directory.
and it leaves a ~2 MB orphan The fix is Two smaller bugs fixed alongside it:
Did you test this change: yes, against the real
On ShellCheck: Happy to split the ShellCheck cleanup into its own PR if you would rather keep the bug fix isolated. |
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 onmain— colors, the idempotentadd_to_config, the download retry with backoff, and$HOME/.bun/binon PATH are all kept. What is left is the delta that fixes actual bugs: 62 insertions, 40 deletions, no conflicts.The
info/info_boldhelpers mentioned in the earlier review are gone from this PR, since they are already onmain.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"andrm -r $bum_folder_namethen operate on that same directory.Two ways this breaks, both reproduced against the real v0.7.22 release on macOS (aarch64, bash 3.2):
maintodaycurl | bashfrom a read-only or system directory)error: Failed on decompress the executable, and leaves a ~2 MB orphanbum.tar.gzbehind in$BUM_INSTALL/binbum --version→0.7.22bum-v0.7.22-<target>directoryrm -rdeletes the user's directorytarmissing from PATHtar: command not founderror: 'tar' is required to install bum but was not found in PATHFix: unpack into a
mktemp -dscratch directory, with atrap ... EXITthat 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
curl,tar,uname,mktemp,mkdir,mv,rm,chmod,grep,basenameare verified before anything is downloaded.bunis deliberately excluded so the "install bun first" path stays reachable.bunis detected withcommand -vinstead of being executed (if ! bun &>/dev/nullactually runs bun).$refresh_commandis printed again. It is computed for fish, zsh and bash and then never shown, so users never get thesource ~/.bashrc/exec $SHELLhint. Restored at the end of the script.mv, so a malformed release gives a real message instead of a baremv: No such file or directory.bash_configs[0]. It used$tilde_bash_configfrom the last iteration of the loop, which could suggest an$XDG_CONFIG_HOMEpath the user has never seen.GITHUB=${GITHUB:-...}so an empty value falls back to github.com instead of producing an empty URL.tildifymatches with"$HOME/"*so a$HOMEcontaining glob characters is not treated as a pattern.ShellCheck
shellcheck -S style install.shon currentmainreports 8 findings; this branch reports none.$@interpolated into a string ininfo,info_bold,success→$*echo "bum was installed successfully to "$exe""$exeinmvBold_Greenandtilde_bin_dirare assigned and never used; both removedThe 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.22release on macOSaarch64-apple-darwin, bash 3.2, with an isolated$HOMEand$BUM_INSTALL:bum --version→0.7.22, config block written, refresh hint printed, CWD still empty afterwardsConfiguration block already present, exactly one# bumblock in the config, no leftover tarballmain(table above)tarremoved from PATH — fails fast with a clear messagebun(installer stubbed out) — takes the install-bun path and completesshellcheck -S styleclean,bash -nclean