From 5aef87b346470a006748e848772cfd4334143efa Mon Sep 17 00:00:00 2001 From: Robby Russell Date: Thu, 3 Dec 2026 06:10:42 -0800 Subject: [PATCH] perf(lib): autoload the omz CLI and omz_diagnostic_dump (#14071) Co-authored-by: Carlo Sala --- .github/workflows/main.yml | 4 +- completions/_omz | 104 ++++ functions/omz | 897 +++++++++++++++++++++++++++++ functions/omz_diagnostic_dump | 356 ++++++++++++ lib/cli.zsh | 1010 +-------------------------------- lib/diagnostics.zsh | 357 +----------- 6 files changed, 1366 insertions(+), 1362 deletions(-) create mode 100644 completions/_omz create mode 100644 functions/omz create mode 100644 functions/omz_diagnostic_dump diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 926093e2d..915296c0f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -37,10 +37,12 @@ jobs: run: | for file in ./oh-my-zsh.sh \ ./lib/*.zsh \ + ./functions/* \ + ./completions/_* \ ./plugins/*/*.plugin.zsh \ ./plugins/*/_* \ ./themes/*.zsh-theme; do - zsh -n "$file" || return 1 + zsh -n "$file" || exit 1 done collisions: diff --git a/completions/_omz b/completions/_omz new file mode 100644 index 000000000..18f491056 --- /dev/null +++ b/completions/_omz @@ -0,0 +1,104 @@ +#compdef omz + +local -a cmds subcmds +cmds=( + 'changelog:Print the changelog' + 'diagnose:Run configuration diagnostics' + 'help:Usage information' + 'plugin:Manage plugins' + 'pr:Manage Oh My Zsh Pull Requests' + 'reload:Reload the current zsh session' + 'shellsaver:Launch a whimsical terminal screensaver' + 'shop:Open the Oh My Zsh shop' + 'theme:Manage themes' + 'update:Update Oh My Zsh' + 'version:Show the version' +) + +if [[ "$words[2]" == (screensaver|shellsaver) ]] && (( CURRENT > 2 )); then + _arguments \ + '1:command:' \ + '2::scene:(aquarium logo hermit party)' \ + '--list[List available scenes]' \ + '--mono[Use the default foreground color]' \ + '--seconds[Exit after a number of seconds]:seconds:' \ + '--snapshot[Print a plain-text still]::frame:' \ + '--help[Show Shellsaver help]' + return +fi + +if (( CURRENT == 2 )); then + _describe 'command' cmds +elif (( CURRENT == 3 )); then + case "$words[2]" in + changelog) local -a refs + refs=("${(@f)$(builtin cd -q "$ZSH"; command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}") + _describe 'command' refs ;; + plugin) subcmds=( + 'disable:Disable plugin(s)' + 'enable:Enable plugin(s)' + 'info:Get plugin information' + 'list:List plugins' + 'load:Load plugin(s)' + ) + _describe 'command' subcmds ;; + pr) subcmds=('clean:Delete all Pull Request branches' 'test:Test a Pull Request') + _describe 'command' subcmds ;; + theme) subcmds=('list:List themes' 'set:Set a theme in your .zshrc file' 'use:Load a theme') + _describe 'command' subcmds ;; + esac +elif (( CURRENT == 4 )); then + case "${words[2]}::${words[3]}" in + plugin::(disable|enable|load)) + local -aU valid_plugins + + if [[ "${words[3]}" = disable ]]; then + # if command is "disable", only offer already enabled plugins + valid_plugins=($plugins) + else + valid_plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) + # if command is "enable", remove already enabled plugins + [[ "${words[3]}" = enable ]] && valid_plugins=(${valid_plugins:|plugins}) + fi + + _describe 'plugin' valid_plugins ;; + plugin::info) + local -aU plugins + plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) + _describe 'plugin' plugins ;; + plugin::list) + local -a opts + opts=('--enabled:List enabled plugins only') + _describe -o 'options' opts ;; + theme::(set|use)) + local -aU themes + themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r) "$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::)) + _describe 'theme' themes ;; + esac +elif (( CURRENT > 4 )); then + case "${words[2]}::${words[3]}" in + plugin::(enable|disable|load)) + local -aU valid_plugins + + if [[ "${words[3]}" = disable ]]; then + # if command is "disable", only offer already enabled plugins + valid_plugins=($plugins) + else + valid_plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) + # if command is "enable", remove already enabled plugins + [[ "${words[3]}" = enable ]] && valid_plugins=(${valid_plugins:|plugins}) + fi + + # Remove plugins already passed as arguments + # NOTE: $(( CURRENT - 1 )) is the last plugin argument completely passed, i.e. that which + # has a space after them. This is to avoid removing plugins partially passed, which makes + # the completion not add a space after the completed plugin. + local -a args + args=(${words[4,$(( CURRENT - 1))]}) + valid_plugins=(${valid_plugins:|args}) + + _describe 'plugin' valid_plugins ;; + esac +fi + +return 0 diff --git a/functions/omz b/functions/omz new file mode 100644 index 000000000..dcb901ace --- /dev/null +++ b/functions/omz @@ -0,0 +1,897 @@ +function omz { + setopt localoptions noksharrays + [[ $# -gt 0 ]] || { + _omz::help + return 1 + } + + local command="$1" + shift + + # Subcommand functions start with _ so that they don't + # appear as completion entries when looking for `omz` + (( ${+functions[_omz::$command]} )) || { + _omz::help + return 1 + } + + _omz::$command "$@" +} + +## Utility functions + +function _omz::confirm { + # If question supplied, ask it before reading the answer + # NOTE: uses the logname of the caller function + if [[ -n "$1" ]]; then + _omz::log prompt "$1" "${${functrace[1]#_}%:*}" + fi + + # Read one character + read -r -k 1 + + # If no newline entered, add a newline + if [[ "$REPLY" != $'\n' ]]; then + echo + fi +} + +function _omz::log { + # if promptsubst is set, a message with `` or $() + # will be run even if quoted due to `print -P` + setopt localoptions nopromptsubst + + # $1 = info|warn|error|debug + # $2 = text + # $3 = (optional) name of the logger + + local logtype=$1 + local logname=${3:-${${functrace[1]#_}%:*}} + + # Don't print anything if debug is not active + if [[ $logtype = debug && -z $_OMZ_DEBUG ]]; then + return + fi + + # Choose coloring based on log type + case "$logtype" in + prompt) print -Pn "%S%F{blue}$logname%f%s: $2" ;; + debug) print -P "%F{white}$logname%f: $2" ;; + info) print -P "%F{green}$logname%f: $2" ;; + warn) print -P "%S%F{yellow}$logname%f%s: $2" ;; + error) print -P "%S%F{red}$logname%f%s: $2" ;; + esac >&2 +} + +## User-facing commands + +function _omz::diagnose { + # Check the runtime locale: non-UTF-8 charsets are known to cause glitches + # such as duplicated characters at the prompt after completions. + # https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#i-see-duplicate-typed-characters-after-i-complete-a-command + # + # `lib/functions.zsh` loads the zsh/langinfo module at startup, so the + # CODESET parameter is already available without any subprocess; only fall + # back to `locale charmap` when that module is unavailable (zsh built without it). + local codeset="${langinfo[CODESET]:-}" + if [[ -z "$codeset" ]] && (( $+commands[locale] )); then + codeset="$(locale charmap 2>/dev/null)" + fi + + if [[ "${codeset:l}" = (utf-8|utf8) ]]; then + _omz::log info "locale charmap is UTF-8" + else + _omz::log warn "your locale is not UTF-8 (charmap: ${codeset:-unknown})" + _omz::log info "non-UTF-8 locales may cause glitches in completions and international characters" + _omz::log info "consider setting a UTF-8 locale, e.g.: export LANG=C.UTF-8" + return 1 + fi +} + +function _omz::help { + cat >&2 < [options] + +Available commands: + + diagnose Run configuration diagnostics + help Print this help message + changelog Print the changelog + plugin Manage plugins + pr Manage Oh My Zsh Pull Requests + reload Reload the current zsh session + shellsaver [scene] Launch a Shellsaver (aquarium by default) + shop Open the Oh My Zsh shop + theme Manage themes + update Update Oh My Zsh + version Show the version + +EOF +} + +function _omz::shellsaver { + command zsh -f "$ZSH/tools/shellsaver.zsh" "$@" +} + +# Hidden alias; only shellsaver is advertised in help and command completion. +function _omz::screensaver { + _omz::shellsaver "$@" +} + +function _omz::changelog { + local version=${1:-HEAD} format=${3:-"--text"} + + if ( + builtin cd -q "$ZSH" + ! command git show-ref --verify refs/heads/$version && \ + ! command git show-ref --verify refs/tags/$version && \ + ! command git rev-parse --verify "${version}^{commit}" + ) &>/dev/null; then + cat >&2 < must be a valid branch, tag or commit. +EOF + return 1 + fi + + ZSH="$ZSH" command zsh -f "$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format" +} + +function _omz::plugin { + (( $# > 0 && $+functions[$0::$1] )) || { + cat >&2 < [options] + +Available commands: + + disable Disable plugin(s) + enable Enable plugin(s) + info Get information of a plugin + list [--enabled] List Oh My Zsh plugins + load Load plugin(s) + +EOF + return 1 + } + + local command="$1" + shift + + $0::$command "$@" +} + +function _omz::plugin::disable { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" + return 1 + fi + + # Check that plugin is in $plugins + local -a dis_plugins + for plugin in "$@"; do + if [[ ${plugins[(Ie)$plugin]} -eq 0 ]]; then + _omz::log warn "plugin '$plugin' is not enabled." + continue + fi + dis_plugins+=("$plugin") + done + + # Exit if there are no enabled plugins to disable + if [[ ${#dis_plugins} -eq 0 ]]; then + return 1 + fi + + # Remove plugins substitution awk script + # A match consumes the whitespace around the plugin, so adjacent plugins + # can't match in the same pass: repeat until the line stops changing. + local awk_subst_plugins="\ + do { + prev = \$0 + + gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after + gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL + gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after + + gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after + gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after + gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses + + gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis + gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL + } while (\$0 != prev) +" + + # Disable plugins awk script + local awk_script=" +# if plugins=() is in oneline form, substitute disabled plugins and go to next line +/^[ \t]*plugins=\([^#]+\).*\$/ { + $awk_subst_plugins + print \$0 + next +} + +# if plugins=() is in multiline form, enable multi flag and disable plugins if they're there +/^[ \t]*plugins=\(/ { + multi=1 + $awk_subst_plugins + print \$0 + next +} + +# if multi flag is enabled and we find a valid closing parenthesis, remove plugins and disable multi flag +multi == 1 && /^[^#]*\)/ { + multi=0 + $awk_subst_plugins + print \$0 + next +} + +multi == 1 && length(\$0) > 0 { + $awk_subst_plugins + if (length(\$0) > 0) print \$0 + next +} + +{ print \$0 } +" + + local zdot="${ZDOTDIR:-$HOME}" + local zshrc="${${:-"${zdot}/.zshrc"}:A}" + awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ + && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ + && command mv -f "$zdot/.zshrc.new" "$zshrc" + + # Exit if the new .zshrc file wasn't created correctly + [[ $? -eq 0 ]] || { + local ret=$? + _omz::log error "error disabling plugins." + return $ret + } + + # Exit if the new .zshrc file has syntax errors + if ! command zsh -n "$zdot/.zshrc"; then + _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." + command mv -f "$zdot/.zshrc.bck" "$zshrc" + return 1 + fi + + # Restart the zsh session if there were no errors + _omz::log info "plugins disabled: ${(j:, :)dis_plugins}." + + # Only reload zsh if run in an interactive session + [[ ! -o interactive ]] || _omz::reload +} + +function _omz::plugin::enable { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" + return 1 + fi + + # Check that plugin is not in $plugins + local -a add_plugins + for plugin in "$@"; do + if [[ ${plugins[(Ie)$plugin]} -ne 0 ]]; then + _omz::log warn "plugin '$plugin' is already enabled." + continue + fi + add_plugins+=("$plugin") + done + + # Exit if there are no plugins to enable + if [[ ${#add_plugins} -eq 0 ]]; then + return 1 + fi + + # Enable plugins awk script + local awk_script=" +# if plugins=() is in oneline form (empty or not), substitute ) with new plugins and go to the next line +/^[ \t]*plugins=\([^#]*\).*\$/ { + sub(/\)/, \" $add_plugins&\") + print \$0 + next +} + +# if plugins=() is in multiline form, enable multi flag and indent by default with 2 spaces +/^[ \t]*plugins=\(/ { + multi=1 + indent=\" \" + print \$0 + next +} + +# if multi flag is enabled and we find a valid closing parenthesis, +# add new plugins with proper indent and disable multi flag +multi == 1 && /^[^#]*\)/ { + multi=0 + split(\"$add_plugins\",p,\" \") + for (i in p) { + print indent p[i] + } + print \$0 + next +} + +# if multi flag is enabled and we didn't find a closing parenthesis, +# get the indentation level to match when adding plugins +multi == 1 && /^[^#]*/ { + indent=\"\" + for (i = 1; i <= length(\$0); i++) { + char=substr(\$0, i, 1) + if (char == \" \" || char == \"\t\") { + indent = indent char + } else { + break + } + } +} + +{ print \$0 } +" + + local zdot="${ZDOTDIR:-$HOME}" + local zshrc="${${:-"${zdot}/.zshrc"}:A}" + awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ + && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ + && command mv -f "$zdot/.zshrc.new" "$zshrc" + + # Exit if the new .zshrc file wasn't created correctly + [[ $? -eq 0 ]] || { + local ret=$? + _omz::log error "error enabling plugins." + return $ret + } + + # Exit if the new .zshrc file has syntax errors + if ! command zsh -n "$zdot/.zshrc"; then + _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." + command mv -f "$zdot/.zshrc.bck" "$zshrc" + return 1 + fi + + # Restart the zsh session if there were no errors + _omz::log info "plugins enabled: ${(j:, :)add_plugins}." + + # Only reload zsh if run in an interactive session + [[ ! -o interactive ]] || _omz::reload +} + +function _omz::plugin::info { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " + return 1 + fi + + local readme + for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do + if [[ -f "$readme" ]]; then + # If being piped, just cat the README + if [[ ! -t 1 ]]; then + cat "$readme" + return $? + fi + + # Enrich the README display depending on the tools we have + # - glow: https://github.com/charmbracelet/glow + # - bat: https://github.com/sharkdp/bat + # - less: typical pager command + case 1 in + ${+commands[glow]}) glow -p "$readme" ;; + ${+commands[bat]}) bat -l md --style plain "$readme" ;; + ${+commands[less]}) less "$readme" ;; + *) cat "$readme" ;; + esac + return $? + fi + done + + if [[ -d "$ZSH_CUSTOM/plugins/$1" || -d "$ZSH/plugins/$1" ]]; then + _omz::log error "the '$1' plugin doesn't have a README file" + else + _omz::log error "'$1' plugin not found" + fi + + return 1 +} + +function _omz::plugin::list { + local -a custom_plugins builtin_plugins + + # If --enabled is provided, only list what's enabled + if [[ "$1" == "--enabled" ]]; then + local plugin + for plugin in "${plugins[@]}"; do + if [[ -d "${ZSH_CUSTOM}/plugins/${plugin}" ]]; then + custom_plugins+=("${plugin}") + elif [[ -d "${ZSH}/plugins/${plugin}" ]]; then + builtin_plugins+=("${plugin}") + fi + done + else + custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t)) + builtin_plugins=("$ZSH"/plugins/*(-/N:t)) + fi + + # If the command is being piped, print all found line by line + if [[ ! -t 1 ]]; then + print -l ${(q-)custom_plugins} ${(q-)builtin_plugins} + return + fi + + if (( ${#custom_plugins} )); then + print -P "%U%BCustom plugins%b%u:" + print -lac ${(q-)custom_plugins} + fi + + if (( ${#builtin_plugins} )); then + (( ${#custom_plugins} )) && echo # add a line of separation + + print -P "%U%BBuilt-in plugins%b%u:" + print -lac ${(q-)builtin_plugins} + fi +} + +function _omz::plugin::load { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" + return 1 + fi + + local plugin base has_completion=0 + for plugin in "$@"; do + if [[ -d "$ZSH_CUSTOM/plugins/$plugin" ]]; then + base="$ZSH_CUSTOM/plugins/$plugin" + elif [[ -d "$ZSH/plugins/$plugin" ]]; then + base="$ZSH/plugins/$plugin" + else + _omz::log warn "plugin '$plugin' not found" + continue + fi + + # Check if its a valid plugin + if [[ ! -f "$base/_$plugin" && ! -f "$base/$plugin.plugin.zsh" ]]; then + _omz::log warn "'$plugin' is not a valid plugin" + continue + # It is a valid plugin, add its directory to $fpath unless it is already there + elif (( ! ${fpath[(Ie)$base]} )); then + fpath=("$base" $fpath) + fi + + # Check if it has completion to reload compinit + local -a comp_files + comp_files=($base/_*(N)) + (( has_completion )) || has_completion=$(( $#comp_files > 0 )) + + # Load the plugin + if [[ -f "$base/$plugin.plugin.zsh" ]]; then + source "$base/$plugin.plugin.zsh" + fi + done + + # If we have completion, we need to reload the completion + # We pass -D to avoid generating a new dump file, which would overwrite our + # current one for the next session (and we don't want that because we're not + # actually enabling the plugins for the next session). + # Note that we still have to pass -d "$_comp_dumpfile", so that compinit + # doesn't use the default zcompdump location (${ZDOTDIR:-$HOME}/.zcompdump). + if (( has_completion )); then + compinit -D -d "$_comp_dumpfile" + fi +} + +function _omz::pr { + (( $# > 0 && $+functions[$0::$1] )) || { + cat >&2 < [options] + +Available commands: + + clean Delete all PR branches (ohmyzsh/pull-*) + test Fetch PR #NUMBER and rebase against master + +EOF + return 1 + } + + local command="$1" + shift + + $0::$command "$@" +} + +function _omz::pr::clean { + ( + set -e + builtin cd -q "$ZSH" + + # Check if there are PR branches + local fmt branches + fmt="%(color:bold blue)%(align:18,right)%(refname:short)%(end)%(color:reset) %(color:dim bold red)%(objectname:short)%(color:reset) %(color:yellow)%(contents:subject)" + branches="$(command git for-each-ref --sort=-committerdate --color --format="$fmt" "refs/heads/ohmyzsh/pull-*")" + + # Exit if there are no PR branches + if [[ -z "$branches" ]]; then + _omz::log info "there are no Pull Request branches to remove." + return + fi + + # Print found PR branches + echo "$branches\n" + # Confirm before removing the branches + _omz::confirm "do you want remove these Pull Request branches? [Y/n] " + # Only proceed if the answer is a valid yes option + [[ "$REPLY" != [yY$'\n'] ]] && return + + _omz::log info "removing all Oh My Zsh Pull Request branches..." + command git branch --list 'ohmyzsh/pull-*' | while read branch; do + command git branch -D "$branch" + done + ) +} + +function _omz::pr::test { + # Allow $1 to be a URL to the pull request + if [[ "$1" = https://* ]]; then + 1="${1:t}" + fi + + # Check the input + if ! [[ -n "$1" && "$1" =~ ^[[:digit:]]+$ ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " + return 1 + fi + + # Save current git HEAD + local branch + branch=$(builtin cd -q "$ZSH"; git symbolic-ref --short HEAD) || { + _omz::log error "error when getting the current git branch. Aborting..." + return 1 + } + + + # Fetch PR onto ohmyzsh/pull- branch and rebase against master + # If any of these operations fail, undo the changes made + ( + set -e + builtin cd -q "$ZSH" + + # Get the ohmyzsh git remote + command git remote -v | while read remote url _; do + case "$url" in + https://github.com/ohmyzsh/ohmyzsh(|.git)) found=1; break ;; + git@github.com:ohmyzsh/ohmyzsh(|.git)) found=1; break ;; + esac + done + + (( $found )) || { + _omz::log error "could not find the ohmyzsh git remote. Aborting..." + return 1 + } + + # Check if Pull Request has the "testers needed" label + _omz::log info "checking if PR #$1 has the 'testers needed' label..." + local pr_json label label_id="MDU6TGFiZWw4NzY1NTkwNA==" + pr_json=$( + curl -fsSL \ + -H "Accept: application/vnd.github+json" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + "https://api.github.com/repos/ohmyzsh/ohmyzsh/pulls/$1" + ) + + if [[ $? -gt 0 || -z "$pr_json" ]]; then + _omz::log error "error when trying to fetch PR #$1 from GitHub." + return 1 + fi + + # Check if the label is present with jq or grep + if (( $+commands[jq] )); then + label="$(command jq ".labels.[] | select(.node_id == \"$label_id\")" <<< "$pr_json")" + else + label="$(command grep "\"$label_id\"" <<< "$pr_json" 2>/dev/null)" + fi + + # If a maintainer hasn't labeled the PR to test, explain the security risk + if [[ -z "$label" ]]; then + _omz::log warn "PR #$1 does not have the 'testers needed' label. This means that the PR" + _omz::log warn "has not been reviewed by a maintainer and may contain malicious code." + + # Ask for explicit confirmation: user needs to type "yes" to continue + _omz::log prompt "Do you want to continue testing it? [yes/N] " + builtin read -r + if [[ "${REPLY:l}" != yes ]]; then + _omz::log error "PR test canceled. Please ask a maintainer to review and label the PR." + return 1 + else + _omz::log warn "Continuing to check out and test PR #$1. Be careful!" + fi + fi + + # Fetch pull request head + _omz::log info "fetching PR #$1 to ohmyzsh/pull-$1..." + command git fetch -f "$remote" refs/pull/$1/head:ohmyzsh/pull-$1 || { + _omz::log error "error when trying to fetch PR #$1." + return 1 + } + + # Rebase pull request branch against the current master + _omz::log info "rebasing PR #$1..." + local ret gpgsign + { + # Back up commit.gpgsign setting: use --local to get the current repository + # setting, not the global one. If --local is not a known option, it will + # exit with a 129 status code. + gpgsign=$(command git config --local commit.gpgsign 2>/dev/null) || ret=$? + [[ $ret -ne 129 ]] || gpgsign=$(command git config commit.gpgsign 2>/dev/null) + command git config commit.gpgsign false + + command git rebase master ohmyzsh/pull-$1 || { + command git rebase --abort &>/dev/null + _omz::log warn "could not rebase PR #$1 on top of master." + _omz::log warn "you might not see the latest stable changes." + _omz::log info "run \`zsh\` to test the changes." + return 1 + } + } always { + case "$gpgsign" in + "") command git config --unset commit.gpgsign ;; + *) command git config commit.gpgsign "$gpgsign" ;; + esac + } + + _omz::log info "fetch of PR #${1} successful." + ) + + # If there was an error, abort running zsh to test the PR + [[ $? -eq 0 ]] || return 1 + + # Run zsh to test the changes + _omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back." + command zsh -l + + # After testing, go back to the previous HEAD if the user wants + _omz::confirm "do you want to go back to the previous branch? [Y/n] " + # Only proceed if the answer is a valid yes option + [[ "$REPLY" != [yY$'\n'] ]] && return + + ( + set -e + builtin cd -q "$ZSH" + + command git checkout "$branch" -- || { + _omz::log error "could not go back to the previous branch ('$branch')." + return 1 + } + ) +} + +function _omz::shop { + local shop_url="https://commitgoods.com/collections/oh-my-zsh" + + _omz::log info "Opening Oh My Zsh shop in your browser..." + _omz::log info "$shop_url" + + open_command "$shop_url" +} + +function _omz::reload { + # Delete current completion cache + command rm -f $_comp_dumpfile $ZSH_COMPDUMP + + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve + # anything that is not absolute via $PATH at exec time (see #13919) + [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" +} + +function _omz::theme { + (( $# > 0 && $+functions[$0::$1] )) || { + cat >&2 < [options] + +Available commands: + + list List all available Oh My Zsh themes + set Set a theme in your .zshrc file + use Load a theme + +EOF + return 1 + } + + local command="$1" + shift + + $0::$command "$@" +} + +function _omz::theme::list { + local -a custom_themes builtin_themes + custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::)) + builtin_themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r)) + + # If the command is being piped, print all found line by line + if [[ ! -t 1 ]]; then + print -l ${(q-)custom_themes} ${(q-)builtin_themes} + return + fi + + # Print theme in use + if [[ -n "$ZSH_THEME" ]]; then + print -Pn "%U%BCurrent theme%b%u: " + [[ $ZSH_THEME = random ]] && echo "$RANDOM_THEME (via random)" || echo "$ZSH_THEME" + echo + fi + + # Print custom themes if there are any + if (( ${#custom_themes} )); then + print -P "%U%BCustom themes%b%u:" + print -lac ${(q-)custom_themes} + echo + fi + + # Print built-in themes + print -P "%U%BBuilt-in themes%b%u:" + print -lac ${(q-)builtin_themes} +} + +function _omz::theme::set { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " + return 1 + fi + + # Check that theme exists + if [[ ! -f "$ZSH_CUSTOM/$1.zsh-theme" ]] \ + && [[ ! -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]] \ + && [[ ! -f "$ZSH/themes/$1.zsh-theme" ]]; then + _omz::log error "%B$1%b theme not found" + return 1 + fi + + # Enable theme in .zshrc + local awk_script=' +!set && /^[ \t]*ZSH_THEME=[^#]+.*$/ { + set=1 + sub(/^[ \t]*ZSH_THEME=[^#]+.*$/, "ZSH_THEME=\"'$1'\" # set by `omz`") + print $0 + next +} + +{ print $0 } + +END { + # If no ZSH_THEME= line was found, return an error + if (!set) exit 1 +} +' + + local zdot="${ZDOTDIR:-$HOME}" + local zshrc="${${:-"${zdot}/.zshrc"}:A}" + awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ + || { + # Prepend ZSH_THEME= line to .zshrc if it doesn't exist + cat < "$zdot/.zshrc.new" \ + && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ + && command mv -f "$zdot/.zshrc.new" "$zshrc" + + # Exit if the new .zshrc file wasn't created correctly + [[ $? -eq 0 ]] || { + local ret=$? + _omz::log error "error setting theme." + return $ret + } + + # Exit if the new .zshrc file has syntax errors + if ! command zsh -n "$zdot/.zshrc"; then + _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." + command mv -f "$zdot/.zshrc.bck" "$zshrc" + return 1 + fi + + # Restart the zsh session if there were no errors + _omz::log info "'$1' theme set correctly." + + # Only reload zsh if run in an interactive session + [[ ! -o interactive ]] || _omz::reload +} + +function _omz::theme::use { + if [[ -z "$1" ]]; then + echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " + return 1 + fi + + # Respect compatibility with old lookup order + if [[ -f "$ZSH_CUSTOM/$1.zsh-theme" ]]; then + source "$ZSH_CUSTOM/$1.zsh-theme" + elif [[ -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]]; then + source "$ZSH_CUSTOM/themes/$1.zsh-theme" + elif [[ -f "$ZSH/themes/$1.zsh-theme" ]]; then + source "$ZSH/themes/$1.zsh-theme" + else + _omz::log error "%B$1%b theme not found" + return 1 + fi + + # Update theme settings + ZSH_THEME="$1" + [[ $1 = random ]] || unset RANDOM_THEME +} + +function _omz::update { + # Check if git command is available + (( $+commands[git] )) || { + _omz::log error "git is not installed. Aborting..." + return 1 + } + + # Check if --unattended was passed + [[ "$1" != --unattended ]] || { + _omz::log error "the \`\e[2m--unattended\e[0m\` flag is no longer supported, use the \`\e[2mupgrade.sh\e[0m\` script instead." + _omz::log error "for more information see https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#how-do-i-update-oh-my-zsh" + return 1 + } + + local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null) + [[ $? -eq 0 ]] || { + _omz::log error "\`$ZSH\` is not a git directory. Aborting..." + return 1 + } + + # Run update script + local verbose_mode cooldown_days + zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default + zstyle -s ':omz:update' cooldown cooldown_days || cooldown_days=0 + [[ $cooldown_days == <-> ]] || cooldown_days=0 + ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" -i -v $verbose_mode -c $cooldown_days || return $? + + # Update last updated file + zmodload zsh/datetime + echo "LAST_EPOCH=$(( EPOCHSECONDS / 60 / 60 / 24 ))" >! "${ZSH_CACHE_DIR}/.zsh-update" + # Remove update lock if it exists + command rm -rf "$ZSH/log/update.lock" + + # Restart the zsh session if there were changes + if [[ "$(builtin cd -q "$ZSH"; git rev-parse HEAD)" != "$last_commit" ]]; then + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve + # anything that is not absolute via $PATH at exec time (see #13919) + [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" + fi +} + +function _omz::version { + ( + builtin cd -q "$ZSH" + + # Get the version name: + # 1) try tag-like version + # 2) try branch name + # 3) try name-rev (tag~ or branch~) + local version + version=$(command git describe --tags HEAD 2>/dev/null) \ + || version=$(command git symbolic-ref --quiet --short HEAD 2>/dev/null) \ + || version=$(command git name-rev --no-undefined --name-only --exclude="remotes/*" HEAD 2>/dev/null) \ + || version="" + + # Get short hash for the current HEAD + local commit=$(command git rev-parse --short HEAD 2>/dev/null) + + # Show version and commit hash + printf "%s (%s)\n" "$version" "$commit" + ) +} + +omz "$@" diff --git a/functions/omz_diagnostic_dump b/functions/omz_diagnostic_dump new file mode 100644 index 000000000..c0147a320 --- /dev/null +++ b/functions/omz_diagnostic_dump @@ -0,0 +1,356 @@ +# omz_diagnostic_dump +# +# Diagnostic and debugging support for oh-my-zsh + +# omz_diagnostic_dump() +# +# Author: Andrew Janke +# +# Usage: +# +# omz_diagnostic_dump [-v] [-V] [file] +# +# NOTE: This is a work in progress. Its interface and behavior are going to change, +# and probably in non-back-compatible ways. +# +# Outputs a bunch of information about the state and configuration of +# oh-my-zsh, zsh, and the user's system. This is intended to provide a +# bunch of context for diagnosing your own or a third party's problems, and to +# be suitable for posting to public bug reports. +# +# The output is human-readable and its format may change over time. It is not +# suitable for parsing. All the output is in one single file so it can be posted +# as a gist or bug comment on GitHub. GitHub doesn't support attaching tarballs +# or other files to bugs; otherwise, this would probably have an option to produce +# tarballs that contain copies of the config and customization files instead of +# catting them all in to one file. +# +# This is intended to be widely portable, and run anywhere that oh-my-zsh does. +# Feel free to report any portability issues as bugs. +# +# This is written in a defensive style so it still works (and can detect) cases when +# basic functionality like echo and which have been redefined. In particular, almost +# everything is invoked with "builtin" or "command", to work in the face of user +# redefinitions. +# +# OPTIONS +# +# [file] Specifies the output file. If not given, a file in the current directory +# is selected automatically. +# +# -v Increase the verbosity of the dump output. May be specified multiple times. +# Verbosity levels: +# 0 - Basic info, shell state, omz configuration, git state +# 1 - (default) Adds key binding info and configuration file contents +# 2 - Adds zcompdump file contents +# +# -V Reduce the verbosity of the dump output. May be specified multiple times. +# +# TODO: +# * Multi-file capture +# * Add automatic gist uploading +# * Consider whether to move default output file location to TMPDIR. More robust +# but less user friendly. +# + +autoload -Uz is-at-least + +function omz_diagnostic_dump() { + emulate -L zsh + + builtin echo "Generating diagnostic dump; please be patient..." + + local thisfcn=omz_diagnostic_dump + local -A opts + local opt_verbose opt_noverbose opt_outfile + local timestamp=$(date +%Y%m%d-%H%M%S) + local outfile=omz_diagdump_$timestamp.txt + builtin zparseopts -A opts -D -- "v+=opt_verbose" "V+=opt_noverbose" + local verbose n_verbose=${#opt_verbose} n_noverbose=${#opt_noverbose} + (( verbose = 1 + n_verbose - n_noverbose )) + + if [[ ${#*} > 0 ]]; then + opt_outfile=$1 + fi + if [[ ${#*} > 1 ]]; then + builtin echo "$thisfcn: error: too many arguments" >&2 + return 1 + fi + if [[ -n "$opt_outfile" ]]; then + outfile="$opt_outfile" + fi + + # Always write directly to a file so terminal escape sequences are + # captured cleanly + _omz_diag_dump_one_big_text &> "$outfile" + if [[ $? != 0 ]]; then + builtin echo "$thisfcn: error while creating diagnostic dump; see $outfile for details" + fi + + builtin echo + builtin echo Diagnostic dump file created at: "$outfile" + builtin echo + builtin echo To share this with OMZ developers, post it as a gist on GitHub + builtin echo at "https://gist.github.com" and share the link to the gist. + builtin echo + builtin echo "WARNING: This dump file contains all your zsh and omz configuration files," + builtin echo "so don't share it publicly if there's sensitive information in them." + builtin echo + +} + +function _omz_diag_dump_one_big_text() { + local program programs progfile md5 + + builtin echo oh-my-zsh diagnostic dump + builtin echo + builtin echo $outfile + builtin echo + + # Basic system and zsh information + command date + command uname -a + builtin echo OSTYPE=$OSTYPE + builtin echo ZSH_VERSION=$ZSH_VERSION + builtin echo User: $USERNAME + builtin echo umask: $(umask) + builtin echo + _omz_diag_dump_os_specific_version + builtin echo + + # Installed programs + programs=(sh zsh ksh bash sed cat grep ls find git posh) + local progfile="" extra_str="" sha_str="" + for program in $programs; do + extra_str="" sha_str="" + progfile=$(builtin which $program) + if [[ $? == 0 ]]; then + if [[ -e $progfile ]]; then + if builtin whence shasum &>/dev/null; then + sha_str=($(command shasum $progfile)) + sha_str=$sha_str[1] + extra_str+=" SHA $sha_str" + fi + if [[ -h "$progfile" ]]; then + extra_str+=" ( -> ${progfile:A} )" + fi + fi + builtin printf '%-9s %-20s %s\n' "$program is" "$progfile" "$extra_str" + else + builtin echo "$program: not found" + fi + done + builtin echo + builtin echo Command Versions: + builtin echo "zsh: $(zsh --version)" + builtin echo "this zsh session: $ZSH_VERSION" + builtin echo "bash: $(bash --version | command grep bash)" + builtin echo "git: $(git --version)" + builtin echo "grep: $(grep --version)" + builtin echo + + # Core command definitions + _omz_diag_dump_check_core_commands || return 1 + builtin echo + + # ZSH Process state + builtin echo Process state: + builtin echo pwd: $PWD + if builtin whence pstree &>/dev/null; then + builtin echo Process tree for this shell: + pstree -p $$ + else + ps -fT + fi + builtin set | command grep -a '^\(ZSH\|plugins\|TERM\|LC_\|LANG\|precmd\|chpwd\|preexec\|FPATH\|TTY\|DISPLAY\|PATH\)\|OMZ' + builtin echo + #TODO: Should this include `env` instead of or in addition to `export`? + builtin echo Exported: + builtin echo $(builtin export | command sed 's/=.*//') + builtin echo + builtin echo Locale: + command locale + builtin echo + + # Zsh installation and configuration + builtin echo Zsh configuration: + builtin echo setopt: $(builtin setopt) + builtin echo + builtin echo zstyle: + builtin zstyle + builtin echo + builtin echo 'compaudit output:' + compaudit + builtin echo + builtin echo '$fpath directories:' + command ls -lad $fpath + builtin echo + + # Oh-my-zsh installation + builtin echo oh-my-zsh installation: + command ls -ld ~/.z* + command ls -ld ~/.oh* + builtin echo + builtin echo oh-my-zsh git state: + (builtin cd $ZSH && builtin echo "HEAD: $(git rev-parse HEAD)" && git remote -v && git status | command grep "[^[:space:]]") + if [[ $verbose -ge 1 ]]; then + (builtin cd $ZSH && git reflog --date=default | command grep pull) + fi + builtin echo + if [[ -e $ZSH_CUSTOM ]]; then + local custom_dir=$ZSH_CUSTOM + if [[ -h $custom_dir ]]; then + custom_dir=$(builtin cd $custom_dir && pwd -P) + fi + builtin echo "oh-my-zsh custom dir:" + builtin echo " $ZSH_CUSTOM ($custom_dir)" + (builtin cd ${custom_dir:h} && command find ${custom_dir:t} -name .git -prune -o -print) + builtin echo + fi + + # Key binding and terminal info + if [[ $verbose -ge 1 ]]; then + builtin echo "bindkey:" + builtin bindkey + builtin echo + builtin echo "infocmp:" + command infocmp -L + builtin echo + fi + + # Configuration file info + local zdotdir=${ZDOTDIR:-$HOME} + builtin echo "Zsh configuration files:" + local cfgfile cfgfiles + # Some files for bash that zsh does not use are intentionally included + # to help with diagnosing behavior differences between bash and zsh + cfgfiles=( /etc/zshenv /etc/zprofile /etc/zshrc /etc/zlogin /etc/zlogout + $zdotdir/.zshenv $zdotdir/.zprofile $zdotdir/.zshrc $zdotdir/.zlogin $zdotdir/.zlogout + ~/.zsh.pre-oh-my-zsh + /etc/bashrc /etc/profile ~/.bashrc ~/.profile ~/.bash_profile ~/.bash_logout ) + command ls -lad $cfgfiles 2>&1 + builtin echo + if [[ $verbose -ge 1 ]]; then + for cfgfile in $cfgfiles; do + _omz_diag_dump_echo_file_w_header $cfgfile + done + fi + builtin echo + builtin echo "Zsh compdump files:" + local dumpfile + local -U dumpfiles + dumpfiles=( $zdotdir/.zcompdump*(N) ${ZSH_COMPDUMP:h}/.zcompdump*(N) ) + (( $#dumpfiles )) && command ls -lad $dumpfiles + if [[ $verbose -ge 2 ]]; then + for dumpfile in $dumpfiles; do + _omz_diag_dump_echo_file_w_header $dumpfile + done + fi + +} + +function _omz_diag_dump_check_core_commands() { + builtin echo "Core command check:" + local redefined name builtins externals reserved_words + redefined=() + # All the zsh non-module builtin commands + # These are taken from the zsh reference manual for 5.0.2 + # Commands from modules should not be included. + # (For back-compatibility, if any of these are newish, they should be removed, + # or at least made conditional on the version of the current running zsh.) + # "history" is also excluded because OMZ is known to redefine that + reserved_words=( do done esac then elif else fi for case if while function + repeat time until select coproc nocorrect foreach end '!' '[[' '{' '}' + ) + builtins=( alias autoload bg bindkey break builtin bye cd chdir command + comparguments compcall compctl compdescribe compfiles compgroups compquote comptags + comptry compvalues continue dirs disable disown echo echotc echoti emulate + enable eval exec exit false fc fg functions getln getopts hash + jobs kill let limit log logout noglob popd print printf + pushd pushln pwd r read rehash return sched set setopt shift + source suspend test times trap true ttyctl type ulimit umask unalias + unfunction unhash unlimit unset unsetopt vared wait whence where which zcompile + zle zmodload zparseopts zregexparse zstyle ) + if is-at-least 5.1; then + reserved_words+=( declare export integer float local readonly typeset ) + else + builtins+=( declare export integer float local readonly typeset ) + fi + builtins_fatal=( builtin command local ) + externals=( zsh ) + for name in $reserved_words; do + if [[ $(builtin whence -w $name) != "$name: reserved" ]]; then + builtin echo "reserved word '$name' has been redefined" + builtin which $name + redefined+=$name + fi + done + for name in $builtins; do + if [[ $(builtin whence -w $name) != "$name: builtin" ]]; then + builtin echo "builtin '$name' has been redefined" + builtin which $name + redefined+=$name + fi + done + for name in $externals; do + if [[ $(builtin whence -w $name) != "$name: command" ]]; then + builtin echo "command '$name' has been redefined" + builtin which $name + redefined+=$name + fi + done + + if [[ -n "$redefined" ]]; then + builtin echo "SOME CORE COMMANDS HAVE BEEN REDEFINED: $redefined" + else + builtin echo "All core commands are defined normally" + fi + +} + +function _omz_diag_dump_echo_file_w_header() { + local file=$1 + if [[ ( -f $file || -h $file ) ]]; then + builtin echo "========== $file ==========" + if [[ -h $file ]]; then + builtin echo "========== ( => ${file:A} ) ==========" + fi + command cat $file + builtin echo "========== end $file ==========" + builtin echo + elif [[ -d $file ]]; then + builtin echo "File '$file' is a directory" + elif [[ ! -e $file ]]; then + builtin echo "File '$file' does not exist" + else + command ls -lad "$file" + fi +} + +function _omz_diag_dump_os_specific_version() { + local osname osver version_file version_files + case "$OSTYPE" in + darwin*) + osname=$(command sw_vers -productName) + osver=$(command sw_vers -productVersion) + builtin echo "OS Version: $osname $osver build $(sw_vers -buildVersion)" + ;; + cygwin) + command systeminfo | command head -n 4 | command tail -n 2 + ;; + esac + + if builtin which lsb_release >/dev/null; then + builtin echo "OS Release: $(command lsb_release -s -d)" + fi + + version_files=( /etc/*-release(N) /etc/*-version(N) /etc/*_version(N) ) + for version_file in $version_files; do + builtin echo "$version_file:" + command cat "$version_file" + builtin echo + done +} + + +omz_diagnostic_dump "$@" diff --git a/lib/cli.zsh b/lib/cli.zsh index fe6f7667f..81fe1c352 100644 --- a/lib/cli.zsh +++ b/lib/cli.zsh @@ -1,1007 +1,3 @@ -#!/usr/bin/env zsh - -function omz { - setopt localoptions noksharrays - [[ $# -gt 0 ]] || { - _omz::help - return 1 - } - - local command="$1" - shift - - # Subcommand functions start with _ so that they don't - # appear as completion entries when looking for `omz` - (( ${+functions[_omz::$command]} )) || { - _omz::help - return 1 - } - - _omz::$command "$@" -} - -function _omz { - local -a cmds subcmds - cmds=( - 'changelog:Print the changelog' - 'diagnose:Run configuration diagnostics' - 'help:Usage information' - 'plugin:Manage plugins' - 'pr:Manage Oh My Zsh Pull Requests' - 'reload:Reload the current zsh session' - 'shellsaver:Launch a whimsical terminal screensaver' - 'shop:Open the Oh My Zsh shop' - 'theme:Manage themes' - 'update:Update Oh My Zsh' - 'version:Show the version' - ) - - if [[ "$words[2]" == (screensaver|shellsaver) ]] && (( CURRENT > 2 )); then - _arguments \ - '1:command:' \ - '2::scene:(aquarium logo hermit party)' \ - '--list[List available scenes]' \ - '--mono[Use the default foreground color]' \ - '--seconds[Exit after a number of seconds]:seconds:' \ - '--snapshot[Print a plain-text still]::frame:' \ - '--help[Show Shellsaver help]' - return - fi - - if (( CURRENT == 2 )); then - _describe 'command' cmds - elif (( CURRENT == 3 )); then - case "$words[2]" in - changelog) local -a refs - refs=("${(@f)$(builtin cd -q "$ZSH"; command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}") - _describe 'command' refs ;; - plugin) subcmds=( - 'disable:Disable plugin(s)' - 'enable:Enable plugin(s)' - 'info:Get plugin information' - 'list:List plugins' - 'load:Load plugin(s)' - ) - _describe 'command' subcmds ;; - pr) subcmds=('clean:Delete all Pull Request branches' 'test:Test a Pull Request') - _describe 'command' subcmds ;; - theme) subcmds=('list:List themes' 'set:Set a theme in your .zshrc file' 'use:Load a theme') - _describe 'command' subcmds ;; - esac - elif (( CURRENT == 4 )); then - case "${words[2]}::${words[3]}" in - plugin::(disable|enable|load)) - local -aU valid_plugins - - if [[ "${words[3]}" = disable ]]; then - # if command is "disable", only offer already enabled plugins - valid_plugins=($plugins) - else - valid_plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) - # if command is "enable", remove already enabled plugins - [[ "${words[3]}" = enable ]] && valid_plugins=(${valid_plugins:|plugins}) - fi - - _describe 'plugin' valid_plugins ;; - plugin::info) - local -aU plugins - plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) - _describe 'plugin' plugins ;; - plugin::list) - local -a opts - opts=('--enabled:List enabled plugins only') - _describe -o 'options' opts ;; - theme::(set|use)) - local -aU themes - themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r) "$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::)) - _describe 'theme' themes ;; - esac - elif (( CURRENT > 4 )); then - case "${words[2]}::${words[3]}" in - plugin::(enable|disable|load)) - local -aU valid_plugins - - if [[ "${words[3]}" = disable ]]; then - # if command is "disable", only offer already enabled plugins - valid_plugins=($plugins) - else - valid_plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(-.N:h:t)) - # if command is "enable", remove already enabled plugins - [[ "${words[3]}" = enable ]] && valid_plugins=(${valid_plugins:|plugins}) - fi - - # Remove plugins already passed as arguments - # NOTE: $(( CURRENT - 1 )) is the last plugin argument completely passed, i.e. that which - # has a space after them. This is to avoid removing plugins partially passed, which makes - # the completion not add a space after the completed plugin. - local -a args - args=(${words[4,$(( CURRENT - 1))]}) - valid_plugins=(${valid_plugins:|args}) - - _describe 'plugin' valid_plugins ;; - esac - fi - - return 0 -} - -# If run from a script, do not set the completion function -if (( ${+functions[compdef]} )); then - compdef _omz omz -fi - -## Utility functions - -function _omz::confirm { - # If question supplied, ask it before reading the answer - # NOTE: uses the logname of the caller function - if [[ -n "$1" ]]; then - _omz::log prompt "$1" "${${functrace[1]#_}%:*}" - fi - - # Read one character - read -r -k 1 - - # If no newline entered, add a newline - if [[ "$REPLY" != $'\n' ]]; then - echo - fi -} - -function _omz::log { - # if promptsubst is set, a message with `` or $() - # will be run even if quoted due to `print -P` - setopt localoptions nopromptsubst - - # $1 = info|warn|error|debug - # $2 = text - # $3 = (optional) name of the logger - - local logtype=$1 - local logname=${3:-${${functrace[1]#_}%:*}} - - # Don't print anything if debug is not active - if [[ $logtype = debug && -z $_OMZ_DEBUG ]]; then - return - fi - - # Choose coloring based on log type - case "$logtype" in - prompt) print -Pn "%S%F{blue}$logname%f%s: $2" ;; - debug) print -P "%F{white}$logname%f: $2" ;; - info) print -P "%F{green}$logname%f: $2" ;; - warn) print -P "%S%F{yellow}$logname%f%s: $2" ;; - error) print -P "%S%F{red}$logname%f%s: $2" ;; - esac >&2 -} - -## User-facing commands - -function _omz::diagnose { - # Check the runtime locale: non-UTF-8 charsets are known to cause glitches - # such as duplicated characters at the prompt after completions. - # https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#i-see-duplicate-typed-characters-after-i-complete-a-command - # - # `lib/functions.zsh` loads the zsh/langinfo module at startup, so the - # CODESET parameter is already available without any subprocess; only fall - # back to `locale charmap` when that module is unavailable (zsh built without it). - local codeset="${langinfo[CODESET]:-}" - if [[ -z "$codeset" ]] && (( $+commands[locale] )); then - codeset="$(locale charmap 2>/dev/null)" - fi - - if [[ "${codeset:l}" = (utf-8|utf8) ]]; then - _omz::log info "locale charmap is UTF-8" - else - _omz::log warn "your locale is not UTF-8 (charmap: ${codeset:-unknown})" - _omz::log info "non-UTF-8 locales may cause glitches in completions and international characters" - _omz::log info "consider setting a UTF-8 locale, e.g.: export LANG=C.UTF-8" - return 1 - fi -} - -function _omz::help { - cat >&2 < [options] - -Available commands: - - diagnose Run configuration diagnostics - help Print this help message - changelog Print the changelog - plugin Manage plugins - pr Manage Oh My Zsh Pull Requests - reload Reload the current zsh session - shellsaver [scene] Launch a Shellsaver (aquarium by default) - shop Open the Oh My Zsh shop - theme Manage themes - update Update Oh My Zsh - version Show the version - -EOF -} - -function _omz::shellsaver { - command zsh -f "$ZSH/tools/shellsaver.zsh" "$@" -} - -# Hidden alias; only shellsaver is advertised in help and command completion. -function _omz::screensaver { - _omz::shellsaver "$@" -} - -function _omz::changelog { - local version=${1:-HEAD} format=${3:-"--text"} - - if ( - builtin cd -q "$ZSH" - ! command git show-ref --verify refs/heads/$version && \ - ! command git show-ref --verify refs/tags/$version && \ - ! command git rev-parse --verify "${version}^{commit}" - ) &>/dev/null; then - cat >&2 < must be a valid branch, tag or commit. -EOF - return 1 - fi - - ZSH="$ZSH" command zsh -f "$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format" -} - -function _omz::plugin { - (( $# > 0 && $+functions[$0::$1] )) || { - cat >&2 < [options] - -Available commands: - - disable Disable plugin(s) - enable Enable plugin(s) - info Get information of a plugin - list [--enabled] List Oh My Zsh plugins - load Load plugin(s) - -EOF - return 1 - } - - local command="$1" - shift - - $0::$command "$@" -} - -function _omz::plugin::disable { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" - return 1 - fi - - # Check that plugin is in $plugins - local -a dis_plugins - for plugin in "$@"; do - if [[ ${plugins[(Ie)$plugin]} -eq 0 ]]; then - _omz::log warn "plugin '$plugin' is not enabled." - continue - fi - dis_plugins+=("$plugin") - done - - # Exit if there are no enabled plugins to disable - if [[ ${#dis_plugins} -eq 0 ]]; then - return 1 - fi - - # Remove plugins substitution awk script - # A match consumes the whitespace around the plugin, so adjacent plugins - # can't match in the same pass: repeat until the line stops changing. - local awk_subst_plugins="\ - do { - prev = \$0 - - gsub(/[ \t]+(${(j:|:)dis_plugins})[ \t]+/, \" \") # with spaces before or after - gsub(/[ \t]+(${(j:|:)dis_plugins})$/, \"\") # with spaces before and EOL - gsub(/^(${(j:|:)dis_plugins})[ \t]+/, \"\") # with BOL and spaces after - - gsub(/\((${(j:|:)dis_plugins})[ \t]+/, \"(\") # with parenthesis before and spaces after - gsub(/[ \t]+(${(j:|:)dis_plugins})\)/, \")\") # with spaces before or parenthesis after - gsub(/\((${(j:|:)dis_plugins})\)/, \"()\") # with only parentheses - - gsub(/^(${(j:|:)dis_plugins})\)/, \")\") # with BOL and closing parenthesis - gsub(/\((${(j:|:)dis_plugins})$/, \"(\") # with opening parenthesis and EOL - } while (\$0 != prev) -" - - # Disable plugins awk script - local awk_script=" -# if plugins=() is in oneline form, substitute disabled plugins and go to next line -/^[ \t]*plugins=\([^#]+\).*\$/ { - $awk_subst_plugins - print \$0 - next -} - -# if plugins=() is in multiline form, enable multi flag and disable plugins if they're there -/^[ \t]*plugins=\(/ { - multi=1 - $awk_subst_plugins - print \$0 - next -} - -# if multi flag is enabled and we find a valid closing parenthesis, remove plugins and disable multi flag -multi == 1 && /^[^#]*\)/ { - multi=0 - $awk_subst_plugins - print \$0 - next -} - -multi == 1 && length(\$0) > 0 { - $awk_subst_plugins - if (length(\$0) > 0) print \$0 - next -} - -{ print \$0 } -" - - local zdot="${ZDOTDIR:-$HOME}" - local zshrc="${${:-"${zdot}/.zshrc"}:A}" - awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ - && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ - && command mv -f "$zdot/.zshrc.new" "$zshrc" - - # Exit if the new .zshrc file wasn't created correctly - [[ $? -eq 0 ]] || { - local ret=$? - _omz::log error "error disabling plugins." - return $ret - } - - # Exit if the new .zshrc file has syntax errors - if ! command zsh -n "$zdot/.zshrc"; then - _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." - command mv -f "$zdot/.zshrc.bck" "$zshrc" - return 1 - fi - - # Restart the zsh session if there were no errors - _omz::log info "plugins disabled: ${(j:, :)dis_plugins}." - - # Only reload zsh if run in an interactive session - [[ ! -o interactive ]] || _omz::reload -} - -function _omz::plugin::enable { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" - return 1 - fi - - # Check that plugin is not in $plugins - local -a add_plugins - for plugin in "$@"; do - if [[ ${plugins[(Ie)$plugin]} -ne 0 ]]; then - _omz::log warn "plugin '$plugin' is already enabled." - continue - fi - add_plugins+=("$plugin") - done - - # Exit if there are no plugins to enable - if [[ ${#add_plugins} -eq 0 ]]; then - return 1 - fi - - # Enable plugins awk script - local awk_script=" -# if plugins=() is in oneline form (empty or not), substitute ) with new plugins and go to the next line -/^[ \t]*plugins=\([^#]*\).*\$/ { - sub(/\)/, \" $add_plugins&\") - print \$0 - next -} - -# if plugins=() is in multiline form, enable multi flag and indent by default with 2 spaces -/^[ \t]*plugins=\(/ { - multi=1 - indent=\" \" - print \$0 - next -} - -# if multi flag is enabled and we find a valid closing parenthesis, -# add new plugins with proper indent and disable multi flag -multi == 1 && /^[^#]*\)/ { - multi=0 - split(\"$add_plugins\",p,\" \") - for (i in p) { - print indent p[i] - } - print \$0 - next -} - -# if multi flag is enabled and we didn't find a closing parenthesis, -# get the indentation level to match when adding plugins -multi == 1 && /^[^#]*/ { - indent=\"\" - for (i = 1; i <= length(\$0); i++) { - char=substr(\$0, i, 1) - if (char == \" \" || char == \"\t\") { - indent = indent char - } else { - break - } - } -} - -{ print \$0 } -" - - local zdot="${ZDOTDIR:-$HOME}" - local zshrc="${${:-"${zdot}/.zshrc"}:A}" - awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ - && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ - && command mv -f "$zdot/.zshrc.new" "$zshrc" - - # Exit if the new .zshrc file wasn't created correctly - [[ $? -eq 0 ]] || { - local ret=$? - _omz::log error "error enabling plugins." - return $ret - } - - # Exit if the new .zshrc file has syntax errors - if ! command zsh -n "$zdot/.zshrc"; then - _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." - command mv -f "$zdot/.zshrc.bck" "$zshrc" - return 1 - fi - - # Restart the zsh session if there were no errors - _omz::log info "plugins enabled: ${(j:, :)add_plugins}." - - # Only reload zsh if run in an interactive session - [[ ! -o interactive ]] || _omz::reload -} - -function _omz::plugin::info { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " - return 1 - fi - - local readme - for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do - if [[ -f "$readme" ]]; then - # If being piped, just cat the README - if [[ ! -t 1 ]]; then - cat "$readme" - return $? - fi - - # Enrich the README display depending on the tools we have - # - glow: https://github.com/charmbracelet/glow - # - bat: https://github.com/sharkdp/bat - # - less: typical pager command - case 1 in - ${+commands[glow]}) glow -p "$readme" ;; - ${+commands[bat]}) bat -l md --style plain "$readme" ;; - ${+commands[less]}) less "$readme" ;; - *) cat "$readme" ;; - esac - return $? - fi - done - - if [[ -d "$ZSH_CUSTOM/plugins/$1" || -d "$ZSH/plugins/$1" ]]; then - _omz::log error "the '$1' plugin doesn't have a README file" - else - _omz::log error "'$1' plugin not found" - fi - - return 1 -} - -function _omz::plugin::list { - local -a custom_plugins builtin_plugins - - # If --enabled is provided, only list what's enabled - if [[ "$1" == "--enabled" ]]; then - local plugin - for plugin in "${plugins[@]}"; do - if [[ -d "${ZSH_CUSTOM}/plugins/${plugin}" ]]; then - custom_plugins+=("${plugin}") - elif [[ -d "${ZSH}/plugins/${plugin}" ]]; then - builtin_plugins+=("${plugin}") - fi - done - else - custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t)) - builtin_plugins=("$ZSH"/plugins/*(-/N:t)) - fi - - # If the command is being piped, print all found line by line - if [[ ! -t 1 ]]; then - print -l ${(q-)custom_plugins} ${(q-)builtin_plugins} - return - fi - - if (( ${#custom_plugins} )); then - print -P "%U%BCustom plugins%b%u:" - print -lac ${(q-)custom_plugins} - fi - - if (( ${#builtin_plugins} )); then - (( ${#custom_plugins} )) && echo # add a line of separation - - print -P "%U%BBuilt-in plugins%b%u:" - print -lac ${(q-)builtin_plugins} - fi -} - -function _omz::plugin::load { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} [...]" - return 1 - fi - - local plugin base has_completion=0 - for plugin in "$@"; do - if [[ -d "$ZSH_CUSTOM/plugins/$plugin" ]]; then - base="$ZSH_CUSTOM/plugins/$plugin" - elif [[ -d "$ZSH/plugins/$plugin" ]]; then - base="$ZSH/plugins/$plugin" - else - _omz::log warn "plugin '$plugin' not found" - continue - fi - - # Check if its a valid plugin - if [[ ! -f "$base/_$plugin" && ! -f "$base/$plugin.plugin.zsh" ]]; then - _omz::log warn "'$plugin' is not a valid plugin" - continue - # It is a valid plugin, add its directory to $fpath unless it is already there - elif (( ! ${fpath[(Ie)$base]} )); then - fpath=("$base" $fpath) - fi - - # Check if it has completion to reload compinit - local -a comp_files - comp_files=($base/_*(N)) - (( has_completion )) || has_completion=$(( $#comp_files > 0 )) - - # Load the plugin - if [[ -f "$base/$plugin.plugin.zsh" ]]; then - source "$base/$plugin.plugin.zsh" - fi - done - - # If we have completion, we need to reload the completion - # We pass -D to avoid generating a new dump file, which would overwrite our - # current one for the next session (and we don't want that because we're not - # actually enabling the plugins for the next session). - # Note that we still have to pass -d "$_comp_dumpfile", so that compinit - # doesn't use the default zcompdump location (${ZDOTDIR:-$HOME}/.zcompdump). - if (( has_completion )); then - compinit -D -d "$_comp_dumpfile" - fi -} - -function _omz::pr { - (( $# > 0 && $+functions[$0::$1] )) || { - cat >&2 < [options] - -Available commands: - - clean Delete all PR branches (ohmyzsh/pull-*) - test Fetch PR #NUMBER and rebase against master - -EOF - return 1 - } - - local command="$1" - shift - - $0::$command "$@" -} - -function _omz::pr::clean { - ( - set -e - builtin cd -q "$ZSH" - - # Check if there are PR branches - local fmt branches - fmt="%(color:bold blue)%(align:18,right)%(refname:short)%(end)%(color:reset) %(color:dim bold red)%(objectname:short)%(color:reset) %(color:yellow)%(contents:subject)" - branches="$(command git for-each-ref --sort=-committerdate --color --format="$fmt" "refs/heads/ohmyzsh/pull-*")" - - # Exit if there are no PR branches - if [[ -z "$branches" ]]; then - _omz::log info "there are no Pull Request branches to remove." - return - fi - - # Print found PR branches - echo "$branches\n" - # Confirm before removing the branches - _omz::confirm "do you want remove these Pull Request branches? [Y/n] " - # Only proceed if the answer is a valid yes option - [[ "$REPLY" != [yY$'\n'] ]] && return - - _omz::log info "removing all Oh My Zsh Pull Request branches..." - command git branch --list 'ohmyzsh/pull-*' | while read branch; do - command git branch -D "$branch" - done - ) -} - -function _omz::pr::test { - # Allow $1 to be a URL to the pull request - if [[ "$1" = https://* ]]; then - 1="${1:t}" - fi - - # Check the input - if ! [[ -n "$1" && "$1" =~ ^[[:digit:]]+$ ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " - return 1 - fi - - # Save current git HEAD - local branch - branch=$(builtin cd -q "$ZSH"; git symbolic-ref --short HEAD) || { - _omz::log error "error when getting the current git branch. Aborting..." - return 1 - } - - - # Fetch PR onto ohmyzsh/pull- branch and rebase against master - # If any of these operations fail, undo the changes made - ( - set -e - builtin cd -q "$ZSH" - - # Get the ohmyzsh git remote - command git remote -v | while read remote url _; do - case "$url" in - https://github.com/ohmyzsh/ohmyzsh(|.git)) found=1; break ;; - git@github.com:ohmyzsh/ohmyzsh(|.git)) found=1; break ;; - esac - done - - (( $found )) || { - _omz::log error "could not find the ohmyzsh git remote. Aborting..." - return 1 - } - - # Check if Pull Request has the "testers needed" label - _omz::log info "checking if PR #$1 has the 'testers needed' label..." - local pr_json label label_id="MDU6TGFiZWw4NzY1NTkwNA==" - pr_json=$( - curl -fsSL \ - -H "Accept: application/vnd.github+json" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - "https://api.github.com/repos/ohmyzsh/ohmyzsh/pulls/$1" - ) - - if [[ $? -gt 0 || -z "$pr_json" ]]; then - _omz::log error "error when trying to fetch PR #$1 from GitHub." - return 1 - fi - - # Check if the label is present with jq or grep - if (( $+commands[jq] )); then - label="$(command jq ".labels.[] | select(.node_id == \"$label_id\")" <<< "$pr_json")" - else - label="$(command grep "\"$label_id\"" <<< "$pr_json" 2>/dev/null)" - fi - - # If a maintainer hasn't labeled the PR to test, explain the security risk - if [[ -z "$label" ]]; then - _omz::log warn "PR #$1 does not have the 'testers needed' label. This means that the PR" - _omz::log warn "has not been reviewed by a maintainer and may contain malicious code." - - # Ask for explicit confirmation: user needs to type "yes" to continue - _omz::log prompt "Do you want to continue testing it? [yes/N] " - builtin read -r - if [[ "${REPLY:l}" != yes ]]; then - _omz::log error "PR test canceled. Please ask a maintainer to review and label the PR." - return 1 - else - _omz::log warn "Continuing to check out and test PR #$1. Be careful!" - fi - fi - - # Fetch pull request head - _omz::log info "fetching PR #$1 to ohmyzsh/pull-$1..." - command git fetch -f "$remote" refs/pull/$1/head:ohmyzsh/pull-$1 || { - _omz::log error "error when trying to fetch PR #$1." - return 1 - } - - # Rebase pull request branch against the current master - _omz::log info "rebasing PR #$1..." - local ret gpgsign - { - # Back up commit.gpgsign setting: use --local to get the current repository - # setting, not the global one. If --local is not a known option, it will - # exit with a 129 status code. - gpgsign=$(command git config --local commit.gpgsign 2>/dev/null) || ret=$? - [[ $ret -ne 129 ]] || gpgsign=$(command git config commit.gpgsign 2>/dev/null) - command git config commit.gpgsign false - - command git rebase master ohmyzsh/pull-$1 || { - command git rebase --abort &>/dev/null - _omz::log warn "could not rebase PR #$1 on top of master." - _omz::log warn "you might not see the latest stable changes." - _omz::log info "run \`zsh\` to test the changes." - return 1 - } - } always { - case "$gpgsign" in - "") command git config --unset commit.gpgsign ;; - *) command git config commit.gpgsign "$gpgsign" ;; - esac - } - - _omz::log info "fetch of PR #${1} successful." - ) - - # If there was an error, abort running zsh to test the PR - [[ $? -eq 0 ]] || return 1 - - # Run zsh to test the changes - _omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back." - command zsh -l - - # After testing, go back to the previous HEAD if the user wants - _omz::confirm "do you want to go back to the previous branch? [Y/n] " - # Only proceed if the answer is a valid yes option - [[ "$REPLY" != [yY$'\n'] ]] && return - - ( - set -e - builtin cd -q "$ZSH" - - command git checkout "$branch" -- || { - _omz::log error "could not go back to the previous branch ('$branch')." - return 1 - } - ) -} - -function _omz::shop { - local shop_url="https://commitgoods.com/collections/oh-my-zsh" - - _omz::log info "Opening Oh My Zsh shop in your browser..." - _omz::log info "$shop_url" - - open_command "$shop_url" -} - -function _omz::reload { - # Delete current completion cache - command rm -f $_comp_dumpfile $ZSH_COMPDUMP - - # Old zsh versions don't have ZSH_ARGZERO - local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" - # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve - # anything that is not absolute via $PATH at exec time (see #13919) - [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" - # Check whether to run a login shell - [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" -} - -function _omz::theme { - (( $# > 0 && $+functions[$0::$1] )) || { - cat >&2 < [options] - -Available commands: - - list List all available Oh My Zsh themes - set Set a theme in your .zshrc file - use Load a theme - -EOF - return 1 - } - - local command="$1" - shift - - $0::$command "$@" -} - -function _omz::theme::list { - local -a custom_themes builtin_themes - custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::)) - builtin_themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r)) - - # If the command is being piped, print all found line by line - if [[ ! -t 1 ]]; then - print -l ${(q-)custom_themes} ${(q-)builtin_themes} - return - fi - - # Print theme in use - if [[ -n "$ZSH_THEME" ]]; then - print -Pn "%U%BCurrent theme%b%u: " - [[ $ZSH_THEME = random ]] && echo "$RANDOM_THEME (via random)" || echo "$ZSH_THEME" - echo - fi - - # Print custom themes if there are any - if (( ${#custom_themes} )); then - print -P "%U%BCustom themes%b%u:" - print -lac ${(q-)custom_themes} - echo - fi - - # Print built-in themes - print -P "%U%BBuilt-in themes%b%u:" - print -lac ${(q-)builtin_themes} -} - -function _omz::theme::set { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " - return 1 - fi - - # Check that theme exists - if [[ ! -f "$ZSH_CUSTOM/$1.zsh-theme" ]] \ - && [[ ! -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]] \ - && [[ ! -f "$ZSH/themes/$1.zsh-theme" ]]; then - _omz::log error "%B$1%b theme not found" - return 1 - fi - - # Enable theme in .zshrc - local awk_script=' -!set && /^[ \t]*ZSH_THEME=[^#]+.*$/ { - set=1 - sub(/^[ \t]*ZSH_THEME=[^#]+.*$/, "ZSH_THEME=\"'$1'\" # set by `omz`") - print $0 - next -} - -{ print $0 } - -END { - # If no ZSH_THEME= line was found, return an error - if (!set) exit 1 -} -' - - local zdot="${ZDOTDIR:-$HOME}" - local zshrc="${${:-"${zdot}/.zshrc"}:A}" - awk "$awk_script" "$zshrc" > "$zdot/.zshrc.new" \ - || { - # Prepend ZSH_THEME= line to .zshrc if it doesn't exist - cat < "$zdot/.zshrc.new" \ - && command cp -f "$zshrc" "$zdot/.zshrc.bck" \ - && command mv -f "$zdot/.zshrc.new" "$zshrc" - - # Exit if the new .zshrc file wasn't created correctly - [[ $? -eq 0 ]] || { - local ret=$? - _omz::log error "error setting theme." - return $ret - } - - # Exit if the new .zshrc file has syntax errors - if ! command zsh -n "$zdot/.zshrc"; then - _omz::log error "broken syntax in '"${zdot/#$HOME/\~}/.zshrc"'. Rolling back changes..." - command mv -f "$zdot/.zshrc.bck" "$zshrc" - return 1 - fi - - # Restart the zsh session if there were no errors - _omz::log info "'$1' theme set correctly." - - # Only reload zsh if run in an interactive session - [[ ! -o interactive ]] || _omz::reload -} - -function _omz::theme::use { - if [[ -z "$1" ]]; then - echo >&2 "Usage: ${(j: :)${(s.::.)0#_}} " - return 1 - fi - - # Respect compatibility with old lookup order - if [[ -f "$ZSH_CUSTOM/$1.zsh-theme" ]]; then - source "$ZSH_CUSTOM/$1.zsh-theme" - elif [[ -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]]; then - source "$ZSH_CUSTOM/themes/$1.zsh-theme" - elif [[ -f "$ZSH/themes/$1.zsh-theme" ]]; then - source "$ZSH/themes/$1.zsh-theme" - else - _omz::log error "%B$1%b theme not found" - return 1 - fi - - # Update theme settings - ZSH_THEME="$1" - [[ $1 = random ]] || unset RANDOM_THEME -} - -function _omz::update { - # Check if git command is available - (( $+commands[git] )) || { - _omz::log error "git is not installed. Aborting..." - return 1 - } - - # Check if --unattended was passed - [[ "$1" != --unattended ]] || { - _omz::log error "the \`\e[2m--unattended\e[0m\` flag is no longer supported, use the \`\e[2mupgrade.sh\e[0m\` script instead." - _omz::log error "for more information see https://github.com/ohmyzsh/ohmyzsh/wiki/FAQ#how-do-i-update-oh-my-zsh" - return 1 - } - - local last_commit=$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null) - [[ $? -eq 0 ]] || { - _omz::log error "\`$ZSH\` is not a git directory. Aborting..." - return 1 - } - - # Run update script - local verbose_mode cooldown_days - zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default - zstyle -s ':omz:update' cooldown cooldown_days || cooldown_days=0 - [[ $cooldown_days == <-> ]] || cooldown_days=0 - ZSH="$ZSH" command zsh -f "$ZSH/tools/upgrade.sh" -i -v $verbose_mode -c $cooldown_days || return $? - - # Update last updated file - zmodload zsh/datetime - echo "LAST_EPOCH=$(( EPOCHSECONDS / 60 / 60 / 24 ))" >! "${ZSH_CACHE_DIR}/.zsh-update" - # Remove update lock if it exists - command rm -rf "$ZSH/log/update.lock" - - # Restart the zsh session if there were changes - if [[ "$(builtin cd -q "$ZSH"; git rev-parse HEAD)" != "$last_commit" ]]; then - # Old zsh versions don't have ZSH_ARGZERO - local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" - # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve - # anything that is not absolute via $PATH at exec time (see #13919) - [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" - # Check whether to run a login shell - [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" - fi -} - -function _omz::version { - ( - builtin cd -q "$ZSH" - - # Get the version name: - # 1) try tag-like version - # 2) try branch name - # 3) try name-rev (tag~ or branch~) - local version - version=$(command git describe --tags HEAD 2>/dev/null) \ - || version=$(command git symbolic-ref --quiet --short HEAD 2>/dev/null) \ - || version=$(command git name-rev --no-undefined --name-only --exclude="remotes/*" HEAD 2>/dev/null) \ - || version="" - - # Get short hash for the current HEAD - local commit=$(command git rev-parse --short HEAD 2>/dev/null) - - # Show version and commit hash - printf "%s (%s)\n" "$version" "$commit" - ) -} +# Keep this library path available for custom overrides. +# Force zsh-style autoloading so the first invocation runs once under kshautoload. +autoload -Uz omz diff --git a/lib/diagnostics.zsh b/lib/diagnostics.zsh index ec66384f2..fb2a1064e 100644 --- a/lib/diagnostics.zsh +++ b/lib/diagnostics.zsh @@ -1,354 +1,3 @@ -# diagnostics.zsh -# -# Diagnostic and debugging support for oh-my-zsh - -# omz_diagnostic_dump() -# -# Author: Andrew Janke -# -# Usage: -# -# omz_diagnostic_dump [-v] [-V] [file] -# -# NOTE: This is a work in progress. Its interface and behavior are going to change, -# and probably in non-back-compatible ways. -# -# Outputs a bunch of information about the state and configuration of -# oh-my-zsh, zsh, and the user's system. This is intended to provide a -# bunch of context for diagnosing your own or a third party's problems, and to -# be suitable for posting to public bug reports. -# -# The output is human-readable and its format may change over time. It is not -# suitable for parsing. All the output is in one single file so it can be posted -# as a gist or bug comment on GitHub. GitHub doesn't support attaching tarballs -# or other files to bugs; otherwise, this would probably have an option to produce -# tarballs that contain copies of the config and customization files instead of -# catting them all in to one file. -# -# This is intended to be widely portable, and run anywhere that oh-my-zsh does. -# Feel free to report any portability issues as bugs. -# -# This is written in a defensive style so it still works (and can detect) cases when -# basic functionality like echo and which have been redefined. In particular, almost -# everything is invoked with "builtin" or "command", to work in the face of user -# redefinitions. -# -# OPTIONS -# -# [file] Specifies the output file. If not given, a file in the current directory -# is selected automatically. -# -# -v Increase the verbosity of the dump output. May be specified multiple times. -# Verbosity levels: -# 0 - Basic info, shell state, omz configuration, git state -# 1 - (default) Adds key binding info and configuration file contents -# 2 - Adds zcompdump file contents -# -# -V Reduce the verbosity of the dump output. May be specified multiple times. -# -# TODO: -# * Multi-file capture -# * Add automatic gist uploading -# * Consider whether to move default output file location to TMPDIR. More robust -# but less user friendly. -# - -autoload -Uz is-at-least - -function omz_diagnostic_dump() { - emulate -L zsh - - builtin echo "Generating diagnostic dump; please be patient..." - - local thisfcn=omz_diagnostic_dump - local -A opts - local opt_verbose opt_noverbose opt_outfile - local timestamp=$(date +%Y%m%d-%H%M%S) - local outfile=omz_diagdump_$timestamp.txt - builtin zparseopts -A opts -D -- "v+=opt_verbose" "V+=opt_noverbose" - local verbose n_verbose=${#opt_verbose} n_noverbose=${#opt_noverbose} - (( verbose = 1 + n_verbose - n_noverbose )) - - if [[ ${#*} > 0 ]]; then - opt_outfile=$1 - fi - if [[ ${#*} > 1 ]]; then - builtin echo "$thisfcn: error: too many arguments" >&2 - return 1 - fi - if [[ -n "$opt_outfile" ]]; then - outfile="$opt_outfile" - fi - - # Always write directly to a file so terminal escape sequences are - # captured cleanly - _omz_diag_dump_one_big_text &> "$outfile" - if [[ $? != 0 ]]; then - builtin echo "$thisfcn: error while creating diagnostic dump; see $outfile for details" - fi - - builtin echo - builtin echo Diagnostic dump file created at: "$outfile" - builtin echo - builtin echo To share this with OMZ developers, post it as a gist on GitHub - builtin echo at "https://gist.github.com" and share the link to the gist. - builtin echo - builtin echo "WARNING: This dump file contains all your zsh and omz configuration files," - builtin echo "so don't share it publicly if there's sensitive information in them." - builtin echo - -} - -function _omz_diag_dump_one_big_text() { - local program programs progfile md5 - - builtin echo oh-my-zsh diagnostic dump - builtin echo - builtin echo $outfile - builtin echo - - # Basic system and zsh information - command date - command uname -a - builtin echo OSTYPE=$OSTYPE - builtin echo ZSH_VERSION=$ZSH_VERSION - builtin echo User: $USERNAME - builtin echo umask: $(umask) - builtin echo - _omz_diag_dump_os_specific_version - builtin echo - - # Installed programs - programs=(sh zsh ksh bash sed cat grep ls find git posh) - local progfile="" extra_str="" sha_str="" - for program in $programs; do - extra_str="" sha_str="" - progfile=$(builtin which $program) - if [[ $? == 0 ]]; then - if [[ -e $progfile ]]; then - if builtin whence shasum &>/dev/null; then - sha_str=($(command shasum $progfile)) - sha_str=$sha_str[1] - extra_str+=" SHA $sha_str" - fi - if [[ -h "$progfile" ]]; then - extra_str+=" ( -> ${progfile:A} )" - fi - fi - builtin printf '%-9s %-20s %s\n' "$program is" "$progfile" "$extra_str" - else - builtin echo "$program: not found" - fi - done - builtin echo - builtin echo Command Versions: - builtin echo "zsh: $(zsh --version)" - builtin echo "this zsh session: $ZSH_VERSION" - builtin echo "bash: $(bash --version | command grep bash)" - builtin echo "git: $(git --version)" - builtin echo "grep: $(grep --version)" - builtin echo - - # Core command definitions - _omz_diag_dump_check_core_commands || return 1 - builtin echo - - # ZSH Process state - builtin echo Process state: - builtin echo pwd: $PWD - if builtin whence pstree &>/dev/null; then - builtin echo Process tree for this shell: - pstree -p $$ - else - ps -fT - fi - builtin set | command grep -a '^\(ZSH\|plugins\|TERM\|LC_\|LANG\|precmd\|chpwd\|preexec\|FPATH\|TTY\|DISPLAY\|PATH\)\|OMZ' - builtin echo - #TODO: Should this include `env` instead of or in addition to `export`? - builtin echo Exported: - builtin echo $(builtin export | command sed 's/=.*//') - builtin echo - builtin echo Locale: - command locale - builtin echo - - # Zsh installation and configuration - builtin echo Zsh configuration: - builtin echo setopt: $(builtin setopt) - builtin echo - builtin echo zstyle: - builtin zstyle - builtin echo - builtin echo 'compaudit output:' - compaudit - builtin echo - builtin echo '$fpath directories:' - command ls -lad $fpath - builtin echo - - # Oh-my-zsh installation - builtin echo oh-my-zsh installation: - command ls -ld ~/.z* - command ls -ld ~/.oh* - builtin echo - builtin echo oh-my-zsh git state: - (builtin cd $ZSH && builtin echo "HEAD: $(git rev-parse HEAD)" && git remote -v && git status | command grep "[^[:space:]]") - if [[ $verbose -ge 1 ]]; then - (builtin cd $ZSH && git reflog --date=default | command grep pull) - fi - builtin echo - if [[ -e $ZSH_CUSTOM ]]; then - local custom_dir=$ZSH_CUSTOM - if [[ -h $custom_dir ]]; then - custom_dir=$(builtin cd $custom_dir && pwd -P) - fi - builtin echo "oh-my-zsh custom dir:" - builtin echo " $ZSH_CUSTOM ($custom_dir)" - (builtin cd ${custom_dir:h} && command find ${custom_dir:t} -name .git -prune -o -print) - builtin echo - fi - - # Key binding and terminal info - if [[ $verbose -ge 1 ]]; then - builtin echo "bindkey:" - builtin bindkey - builtin echo - builtin echo "infocmp:" - command infocmp -L - builtin echo - fi - - # Configuration file info - local zdotdir=${ZDOTDIR:-$HOME} - builtin echo "Zsh configuration files:" - local cfgfile cfgfiles - # Some files for bash that zsh does not use are intentionally included - # to help with diagnosing behavior differences between bash and zsh - cfgfiles=( /etc/zshenv /etc/zprofile /etc/zshrc /etc/zlogin /etc/zlogout - $zdotdir/.zshenv $zdotdir/.zprofile $zdotdir/.zshrc $zdotdir/.zlogin $zdotdir/.zlogout - ~/.zsh.pre-oh-my-zsh - /etc/bashrc /etc/profile ~/.bashrc ~/.profile ~/.bash_profile ~/.bash_logout ) - command ls -lad $cfgfiles 2>&1 - builtin echo - if [[ $verbose -ge 1 ]]; then - for cfgfile in $cfgfiles; do - _omz_diag_dump_echo_file_w_header $cfgfile - done - fi - builtin echo - builtin echo "Zsh compdump files:" - local dumpfile - local -U dumpfiles - dumpfiles=( $zdotdir/.zcompdump*(N) ${ZSH_COMPDUMP:h}/.zcompdump*(N) ) - (( $#dumpfiles )) && command ls -lad $dumpfiles - if [[ $verbose -ge 2 ]]; then - for dumpfile in $dumpfiles; do - _omz_diag_dump_echo_file_w_header $dumpfile - done - fi - -} - -function _omz_diag_dump_check_core_commands() { - builtin echo "Core command check:" - local redefined name builtins externals reserved_words - redefined=() - # All the zsh non-module builtin commands - # These are taken from the zsh reference manual for 5.0.2 - # Commands from modules should not be included. - # (For back-compatibility, if any of these are newish, they should be removed, - # or at least made conditional on the version of the current running zsh.) - # "history" is also excluded because OMZ is known to redefine that - reserved_words=( do done esac then elif else fi for case if while function - repeat time until select coproc nocorrect foreach end '!' '[[' '{' '}' - ) - builtins=( alias autoload bg bindkey break builtin bye cd chdir command - comparguments compcall compctl compdescribe compfiles compgroups compquote comptags - comptry compvalues continue dirs disable disown echo echotc echoti emulate - enable eval exec exit false fc fg functions getln getopts hash - jobs kill let limit log logout noglob popd print printf - pushd pushln pwd r read rehash return sched set setopt shift - source suspend test times trap true ttyctl type ulimit umask unalias - unfunction unhash unlimit unset unsetopt vared wait whence where which zcompile - zle zmodload zparseopts zregexparse zstyle ) - if is-at-least 5.1; then - reserved_words+=( declare export integer float local readonly typeset ) - else - builtins+=( declare export integer float local readonly typeset ) - fi - builtins_fatal=( builtin command local ) - externals=( zsh ) - for name in $reserved_words; do - if [[ $(builtin whence -w $name) != "$name: reserved" ]]; then - builtin echo "reserved word '$name' has been redefined" - builtin which $name - redefined+=$name - fi - done - for name in $builtins; do - if [[ $(builtin whence -w $name) != "$name: builtin" ]]; then - builtin echo "builtin '$name' has been redefined" - builtin which $name - redefined+=$name - fi - done - for name in $externals; do - if [[ $(builtin whence -w $name) != "$name: command" ]]; then - builtin echo "command '$name' has been redefined" - builtin which $name - redefined+=$name - fi - done - - if [[ -n "$redefined" ]]; then - builtin echo "SOME CORE COMMANDS HAVE BEEN REDEFINED: $redefined" - else - builtin echo "All core commands are defined normally" - fi - -} - -function _omz_diag_dump_echo_file_w_header() { - local file=$1 - if [[ ( -f $file || -h $file ) ]]; then - builtin echo "========== $file ==========" - if [[ -h $file ]]; then - builtin echo "========== ( => ${file:A} ) ==========" - fi - command cat $file - builtin echo "========== end $file ==========" - builtin echo - elif [[ -d $file ]]; then - builtin echo "File '$file' is a directory" - elif [[ ! -e $file ]]; then - builtin echo "File '$file' does not exist" - else - command ls -lad "$file" - fi -} - -function _omz_diag_dump_os_specific_version() { - local osname osver version_file version_files - case "$OSTYPE" in - darwin*) - osname=$(command sw_vers -productName) - osver=$(command sw_vers -productVersion) - builtin echo "OS Version: $osname $osver build $(sw_vers -buildVersion)" - ;; - cygwin) - command systeminfo | command head -n 4 | command tail -n 2 - ;; - esac - - if builtin which lsb_release >/dev/null; then - builtin echo "OS Release: $(command lsb_release -s -d)" - fi - - version_files=( /etc/*-release(N) /etc/*-version(N) /etc/*_version(N) ) - for version_file in $version_files; do - builtin echo "$version_file:" - command cat "$version_file" - builtin echo - done -} - +# Keep this library path available for custom overrides. +# Force zsh-style autoloading so the first invocation runs once under kshautoload. +autoload -Uz omz_diagnostic_dump