Skip to content
Myr

[Perf] `nvm_echo`: use the `printf` shell builtin under zsh

Before adoption: this commit came in with the history the project adopted, so no landing records it.

In zsh, `command printf` skips the builtin and forks `/usr/bin/printf`.

authored by Cassidy Marble · committed by Jordan Harband · parent 1dd1d8c · Browse files · 2 files+51 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+51 added−2 removed

  • tests:+38 added−0 removed
  • other:+13 added−2 removed

2 files+51 added−2 removed

added:test/fast/Unit tests/nvm_echo+38 added
1#!/bin/sh23die () { echo "$@" ; exit 1; }45cleanup() {6 rm -rf "${TEST_DIR}"7}89: nvm.sh10\. ../../../nvm.sh1112TEST_DIR="$(pwd)/nvm_echo_tmp"13[ ! -e "${TEST_DIR}" ] && mkdir "${TEST_DIR}"1415# a `printf` that reports that it ran: `nvm_echo` must use a shell builtin16# rather than resolving `printf` through `PATH` (zsh's `command` skips the17# builtin and runs `/usr/bin/printf` on every call)18MOCK_BIN="${TEST_DIR}/bin"19mkdir -p "${MOCK_BIN}"20{21 echo '#!/bin/sh'22 echo "echo 'MOCKED-PRINTF'"23} > "${MOCK_BIN}/printf"24chmod +x "${MOCK_BIN}/printf"2526OUTPUT="$(nvm_echo 'hello world')"27[ "${OUTPUT}" = 'hello world' ] || die "expected 'hello world', got '${OUTPUT}'"2829OUTPUT="$(nvm_echo)"30[ -z "${OUTPUT}" ] || die "expected no output, got '${OUTPUT}'"3132OUTPUT="$(PATH="${MOCK_BIN}:${PATH}" nvm_echo 'no fork, please' 2>&1)"33[ "${OUTPUT}" = 'no fork, please' ] || die "for nvm_echo, expected 'no fork, please', got '${OUTPUT}'"3435OUTPUT="$(PATH="${MOCK_BIN}:${PATH}" nvm_echo_with_colors 'no fork, please' 2>&1)"36[ "${OUTPUT}" = 'no fork, please' ] || die "for nvm_echo_with_colors, expected 'no fork, please', got '${OUTPUT}'"3738cleanup
modified:nvm.sh+13 added-2 removed
20 unmodified lines
21 [ -t 1 ]22}2324nvm_echo() {25 # in zsh, `command printf` skips the builtin and runs `/usr/bin/printf`26 if [ -n "${ZSH_VERSION-}" ]; then27 # shellcheck disable=SC304428 builtin printf %s\\n "$*" 2>/dev/null29 else25 command printf %s\\n "$*" 2>/dev/null30 command printf %s\\n "$*" 2>/dev/null31 fi32}3334nvm_echo_with_colors() {35 if [ -n "${ZSH_VERSION-}" ]; then36 # shellcheck disable=SC304437 builtin printf %b\\n "$*" 2>/dev/null38 else29 command printf %b\\n "$*" 2>/dev/null39 command printf %b\\n "$*" 2>/dev/null40 fi41}4243nvm_cd() {44 \cd "$@"
5528 unmodified lines