cli.zsh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #!/usr/bin/env zsh
  2. function omz {
  3. [[ $# -gt 0 ]] || {
  4. _omz::help
  5. return 1
  6. }
  7. local command="$1"
  8. shift
  9. # Subcommand functions start with _ so that they don't
  10. # appear as completion entries when looking for `omz`
  11. (( $+functions[_omz::$command] )) || {
  12. _omz::help
  13. return 1
  14. }
  15. _omz::$command "$@"
  16. }
  17. function _omz {
  18. local -a cmds subcmds
  19. cmds=(
  20. 'changelog:Print the changelog'
  21. 'help:Usage information'
  22. 'plugin:Manage plugins'
  23. 'pr:Manage Oh My Zsh Pull Requests'
  24. 'theme:Manage themes'
  25. 'update:Update Oh My Zsh'
  26. )
  27. if (( CURRENT == 2 )); then
  28. _describe 'command' cmds
  29. elif (( CURRENT == 3 )); then
  30. case "$words[2]" in
  31. changelog) local -a refs
  32. refs=("${(@f)$(command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}")
  33. _describe 'command' refs ;;
  34. plugin) subcmds=('info:Get plugin information' 'list:List plugins' 'load:Load plugin(s)')
  35. _describe 'command' subcmds ;;
  36. pr) subcmds=('test:Test a Pull Request' 'clean:Delete all Pull Request branches')
  37. _describe 'command' subcmds ;;
  38. theme) subcmds=('use:Load a theme' 'list:List themes')
  39. _describe 'command' subcmds ;;
  40. esac
  41. elif (( CURRENT == 4 )); then
  42. case "$words[2]::$words[3]" in
  43. plugin::(info|load))
  44. local -aU plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(.N:h:t))
  45. _describe 'plugin' plugins ;;
  46. theme::use)
  47. local -aU themes=("$ZSH"/themes/*.zsh-theme(.N:t:r) "$ZSH_CUSTOM"/**/*.zsh-theme(.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::))
  48. _describe 'theme' themes ;;
  49. esac
  50. elif (( CURRENT > 4 )); then
  51. case "$words[2]::$words[3]" in
  52. plugin::load)
  53. local -aU plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(.N:h:t))
  54. # Remove plugins already passed as arguments
  55. # NOTE: $(( CURRENT - 1 )) is the last plugin argument completely passed, i.e. that which
  56. # has a space after them. This is to avoid removing plugins partially passed, which makes
  57. # the completion not add a space after the completed plugin.
  58. local -a args=(${words[4,$(( CURRENT - 1))]})
  59. plugins=(${plugins:|args})
  60. _describe 'plugin' plugins ;;
  61. esac
  62. fi
  63. return 0
  64. }
  65. compdef _omz omz
  66. ## Utility functions
  67. function _omz::confirm {
  68. # If question supplied, ask it before reading the answer
  69. # NOTE: uses the logname of the caller function
  70. if [[ -n "$1" ]]; then
  71. _omz::log prompt "$1" "${${functrace[1]#_}%:*}"
  72. fi
  73. # Read one character
  74. read -r -k 1
  75. # If no newline entered, add a newline
  76. if [[ "$REPLY" != $'\n' ]]; then
  77. echo
  78. fi
  79. }
  80. function _omz::log {
  81. # if promptsubst is set, a message with `` or $()
  82. # will be run even if quoted due to `print -P`
  83. setopt localoptions nopromptsubst
  84. # $1 = info|warn|error|debug
  85. # $2 = text
  86. # $3 = (optional) name of the logger
  87. local logtype=$1
  88. local logname=${3:-${${functrace[1]#_}%:*}}
  89. # Don't print anything if debug is not active
  90. if [[ $logtype = debug && -z $_OMZ_DEBUG ]]; then
  91. return
  92. fi
  93. # Choose coloring based on log type
  94. case "$logtype" in
  95. prompt) print -Pn "%S%F{blue}$logname%f%s: $2" ;;
  96. debug) print -P "%F{white}$logname%f: $2" ;;
  97. info) print -P "%F{green}$logname%f: $2" ;;
  98. warn) print -P "%S%F{yellow}$logname%f%s: $2" ;;
  99. error) print -P "%S%F{red}$logname%f%s: $2" ;;
  100. esac >&2
  101. }
  102. ## User-facing commands
  103. function _omz::help {
  104. cat <<EOF
  105. Usage: omz <command> [options]
  106. Available commands:
  107. help Print this help message
  108. changelog Print the changelog
  109. plugin <command> Manage plugins
  110. pr <command> Manage Oh My Zsh Pull Requests
  111. theme <command> Manage themes
  112. update Update Oh My Zsh
  113. EOF
  114. }
  115. function _omz::changelog {
  116. local version=${1:-HEAD} format=${3:-"--text"}
  117. if ! command git -C "$ZSH" show-ref --verify refs/heads/$version &>/dev/null && \
  118. ! command git -C "$ZSH" show-ref --verify refs/tags/$version &>/dev/null && \
  119. ! command git -C "$ZSH" rev-parse --verify "${version}^{commit}" &>/dev/null; then
  120. cat <<EOF
  121. Usage: omz changelog [version]
  122. NOTE: <version> must be a valid branch, tag or commit.
  123. EOF
  124. return 1
  125. fi
  126. "$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format"
  127. }
  128. function _omz::plugin {
  129. (( $# > 0 && $+functions[_omz::plugin::$1] )) || {
  130. cat <<EOF
  131. Usage: omz plugin <command> [options]
  132. Available commands:
  133. info <plugin> Get information of a plugin
  134. list List all available Oh My Zsh plugins
  135. load <plugin> Load plugin(s)
  136. EOF
  137. return 1
  138. }
  139. local command="$1"
  140. shift
  141. _omz::plugin::$command "$@"
  142. }
  143. function _omz::plugin::info {
  144. if [[ -z "$1" ]]; then
  145. echo >&2 "Usage: omz plugin info <plugin>"
  146. return 1
  147. fi
  148. local readme
  149. for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do
  150. if [[ -f "$readme" ]]; then
  151. (( ${+commands[less]} )) && less "$readme" || cat "$readme"
  152. return 0
  153. fi
  154. done
  155. if [[ -d "$ZSH_CUSTOM/plugins/$1" || -d "$ZSH/plugins/$1" ]]; then
  156. _omz::log error "the '$1' plugin doesn't have a README file"
  157. else
  158. _omz::log error "'$1' plugin not found"
  159. fi
  160. return 1
  161. }
  162. function _omz::plugin::list {
  163. local -a custom_plugins builtin_plugins
  164. custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t))
  165. builtin_plugins=("$ZSH"/plugins/*(-/N:t))
  166. # If the command is being piped, print all found line by line
  167. if [[ ! -t 1 ]]; then
  168. print -l ${(q-)custom_plugins} ${(q-)builtin_plugins}
  169. return
  170. fi
  171. if (( ${#custom_plugins} )); then
  172. print -P "%U%BCustom plugins%b%u:"
  173. print -l ${(q-)custom_plugins} | column
  174. fi
  175. if (( ${#builtin_plugins} )); then
  176. (( ${#custom_plugins} )) && echo # add a line of separation
  177. print -P "%U%BBuilt-in plugins%b%u:"
  178. print -l ${(q-)builtin_plugins} | column
  179. fi
  180. }
  181. function _omz::plugin::load {
  182. if [[ -z "$1" ]]; then
  183. echo >&2 "Usage: omz plugin load <plugin> [...]"
  184. return 1
  185. fi
  186. local plugins=("$@")
  187. local plugin base has_completion=0
  188. for plugin in $plugins; do
  189. if [[ -d "$ZSH_CUSTOM/plugins/$plugin" ]]; then
  190. base="$ZSH_CUSTOM/plugins/$plugin"
  191. elif [[ -d "$ZSH/plugins/$plugin" ]]; then
  192. base="$ZSH/plugins/$plugin"
  193. else
  194. _omz::log warn "plugin '$plugin' not found"
  195. continue
  196. fi
  197. # Check if its a valid plugin
  198. if [[ ! -f "$base/_$plugin" && ! -f "$base/$plugin.plugin.zsh" ]]; then
  199. _omz::log warn "'$plugin' is not a valid plugin"
  200. continue
  201. # It it is a valid plugin, add its directory to $fpath unless it is already there
  202. elif (( ! ${fpath[(Ie)$base]} )); then
  203. fpath=("$base" $fpath)
  204. fi
  205. # Check if it has completion to reload compinit
  206. if [[ -f "$base/_$plugin" ]]; then
  207. has_completion=1
  208. fi
  209. # Load the plugin
  210. if [[ -f "$base/$plugin.plugin.zsh" ]]; then
  211. source "$base/$plugin.plugin.zsh"
  212. fi
  213. done
  214. # If we have completion, we need to reload the completion
  215. # We pass -D to avoid generating a new dump file, which would overwrite our
  216. # current one for the next session (and we don't want that because we're not
  217. # actually enabling the plugins for the next session).
  218. # Note that we still have to pass -d "$_comp_dumpfile", so that compinit
  219. # doesn't use the default zcompdump location (${ZDOTDIR:-$HOME}/.zcompdump).
  220. if (( has_completion )); then
  221. compinit -D -d "$_comp_dumpfile"
  222. fi
  223. }
  224. function _omz::pr {
  225. (( $# > 0 && $+functions[_omz::pr::$1] )) || {
  226. cat <<EOF
  227. Usage: omz pr <command> [options]
  228. Available commands:
  229. clean Delete all PR branches (ohmyzsh/pull-*)
  230. test <PR_number_or_URL> Fetch PR #NUMBER and rebase against master
  231. EOF
  232. return 1
  233. }
  234. local command="$1"
  235. shift
  236. _omz::pr::$command "$@"
  237. }
  238. function _omz::pr::clean {
  239. (
  240. set -e
  241. builtin cd -q "$ZSH"
  242. # Check if there are PR branches
  243. local fmt branches
  244. fmt="%(color:bold blue)%(align:18,right)%(refname:short)%(end)%(color:reset) %(color:dim bold red)%(objectname:short)%(color:reset) %(color:yellow)%(contents:subject)"
  245. branches="$(command git for-each-ref --sort=-committerdate --color --format="$fmt" "refs/heads/ohmyzsh/pull-*")"
  246. # Exit if there are no PR branches
  247. if [[ -z "$branches" ]]; then
  248. _omz::log info "there are no Pull Request branches to remove."
  249. return
  250. fi
  251. # Print found PR branches
  252. echo "$branches\n"
  253. # Confirm before removing the branches
  254. _omz::confirm "do you want remove these Pull Request branches? [Y/n] "
  255. # Only proceed if the answer is a valid yes option
  256. [[ "$REPLY" != [yY$'\n'] ]] && return
  257. _omz::log info "removing all Oh My Zsh Pull Request branches..."
  258. command git branch --list 'ohmyzsh/pull-*' | while read branch; do
  259. command git branch -D "$branch"
  260. done
  261. )
  262. }
  263. function _omz::pr::test {
  264. # Allow $1 to be a URL to the pull request
  265. if [[ "$1" = https://* ]]; then
  266. 1="${1:t}"
  267. fi
  268. # Check the input
  269. if ! [[ -n "$1" && "$1" =~ ^[[:digit:]]+$ ]]; then
  270. echo >&2 "Usage: omz pr test <PR_NUMBER_or_URL>"
  271. return 1
  272. fi
  273. # Save current git HEAD
  274. local branch
  275. branch=$(builtin cd -q "$ZSH"; git symbolic-ref --short HEAD) || {
  276. _omz::log error "error when getting the current git branch. Aborting..."
  277. return 1
  278. }
  279. # Fetch PR onto ohmyzsh/pull-<PR_NUMBER> branch and rebase against master
  280. # If any of these operations fail, undo the changes made
  281. (
  282. set -e
  283. builtin cd -q "$ZSH"
  284. # Get the ohmyzsh git remote
  285. command git remote -v | while read remote url _; do
  286. case "$url" in
  287. https://github.com/ohmyzsh/ohmyzsh(|.git)) found=1; break ;;
  288. git@github.com:ohmyzsh/ohmyzsh(|.git)) found=1; break ;;
  289. esac
  290. done
  291. (( $found )) || {
  292. _omz::log error "could not found the ohmyzsh git remote. Aborting..."
  293. return 1
  294. }
  295. # Fetch pull request head
  296. _omz::log info "fetching PR #$1 to ohmyzsh/pull-$1..."
  297. command git fetch -f "$remote" refs/pull/$1/head:ohmyzsh/pull-$1 || {
  298. _omz::log error "error when trying to fetch PR #$1."
  299. return 1
  300. }
  301. # Rebase pull request branch against the current master
  302. _omz::log info "rebasing PR #$1..."
  303. command git rebase master ohmyzsh/pull-$1 || {
  304. command git rebase --abort &>/dev/null
  305. _omz::log warn "could not rebase PR #$1 on top of master."
  306. _omz::log warn "you might not see the latest stable changes."
  307. _omz::log info "run \`zsh\` to test the changes."
  308. return 1
  309. }
  310. _omz::log info "fetch of PR #${1} successful."
  311. )
  312. # If there was an error, abort running zsh to test the PR
  313. [[ $? -eq 0 ]] || return 1
  314. # Run zsh to test the changes
  315. _omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back."
  316. command zsh -l
  317. # After testing, go back to the previous HEAD if the user wants
  318. _omz::confirm "do you want to go back to the previous branch? [Y/n] "
  319. # Only proceed if the answer is a valid yes option
  320. [[ "$REPLY" != [yY$'\n'] ]] && return
  321. (
  322. set -e
  323. builtin cd -q "$ZSH"
  324. command git checkout "$branch" -- || {
  325. _omz::log error "could not go back to the previous branch ('$branch')."
  326. return 1
  327. }
  328. )
  329. }
  330. function _omz::theme {
  331. (( $# > 0 && $+functions[_omz::theme::$1] )) || {
  332. cat <<EOF
  333. Usage: omz theme <command> [options]
  334. Available commands:
  335. list List all available Oh My Zsh themes
  336. use <theme> Load an Oh My Zsh theme
  337. EOF
  338. return 1
  339. }
  340. local command="$1"
  341. shift
  342. _omz::theme::$command "$@"
  343. }
  344. function _omz::theme::list {
  345. local -a custom_themes builtin_themes
  346. custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::))
  347. builtin_themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r))
  348. # If the command is being piped, print all found line by line
  349. if [[ ! -t 1 ]]; then
  350. print -l ${(q-)custom_themes} ${(q-)builtin_themes}
  351. return
  352. fi
  353. if (( ${#custom_themes} )); then
  354. print -P "%U%BCustom themes%b%u:"
  355. print -l ${(q-)custom_themes} | column
  356. fi
  357. if (( ${#builtin_themes} )); then
  358. (( ${#custom_themes} )) && echo # add a line of separation
  359. print -P "%U%BBuilt-in themes%b%u:"
  360. print -l ${(q-)builtin_themes} | column
  361. fi
  362. }
  363. function _omz::theme::use {
  364. if [[ -z "$1" ]]; then
  365. echo >&2 "Usage: omz theme use <theme>"
  366. return 1
  367. fi
  368. # Respect compatibility with old lookup order
  369. if [[ -f "$ZSH_CUSTOM/$1.zsh-theme" ]]; then
  370. source "$ZSH_CUSTOM/$1.zsh-theme"
  371. elif [[ -f "$ZSH_CUSTOM/themes/$1.zsh-theme" ]]; then
  372. source "$ZSH_CUSTOM/themes/$1.zsh-theme"
  373. elif [[ -f "$ZSH/themes/$1.zsh-theme" ]]; then
  374. source "$ZSH/themes/$1.zsh-theme"
  375. else
  376. _omz::log error "theme '$1' not found"
  377. return 1
  378. fi
  379. }
  380. function _omz::update {
  381. local last_commit=$(cd "$ZSH"; git rev-parse HEAD)
  382. # Run update script
  383. if [[ "$1" != --unattended ]]; then
  384. ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" --interactive
  385. else
  386. ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh"
  387. fi
  388. # Update last updated file
  389. zmodload zsh/datetime
  390. echo "LAST_EPOCH=$(( EPOCHSECONDS / 60 / 60 / 24 ))" >! "${ZSH_CACHE_DIR}/.zsh-update"
  391. # Remove update lock if it exists
  392. command rm -rf "$ZSH/log/update.lock"
  393. # Restart the zsh session if there were changes
  394. if [[ "$1" != --unattended && "$(cd "$ZSH"; git rev-parse HEAD)" != "$last_commit" ]]; then
  395. # Old zsh versions don't have ZSH_ARGZERO
  396. local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}"
  397. # Check whether to run a login shell
  398. [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh"
  399. fi
  400. }