check_for_upgrade.sh 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # Migrate .zsh-update file to $ZSH_CACHE_DIR
  2. if [[ -f ~/.zsh-update && ! -f "${ZSH_CACHE_DIR}/.zsh-update" ]]; then
  3. mv ~/.zsh-update "${ZSH_CACHE_DIR}/.zsh-update"
  4. fi
  5. # Get user's update preferences
  6. #
  7. # Supported update modes:
  8. # - prompt (default): the user is asked before updating when it's time to update
  9. # - auto: the update is performed automatically when it's time
  10. # - reminder: a reminder is shown to the user when it's time to update
  11. # - background-alpha: an experimental update-on-the-background option
  12. # - disabled: automatic update is turned off
  13. zstyle -s ':omz:update' mode update_mode || {
  14. update_mode=prompt
  15. # If the mode zstyle setting is not set, support old-style settings
  16. [[ "$DISABLE_UPDATE_PROMPT" != true ]] || update_mode=auto
  17. [[ "$DISABLE_AUTO_UPDATE" != true ]] || update_mode=disabled
  18. }
  19. # Cancel update if:
  20. # - the automatic update is disabled
  21. # - the current user doesn't have write permissions nor owns the $ZSH directory
  22. # - is not run from a tty
  23. # - git is unavailable on the system
  24. # - $ZSH is not a git repository
  25. if [[ "$update_mode" = disabled ]] \
  26. || [[ ! -w "$ZSH" || ! -O "$ZSH" ]] \
  27. || [[ ! -t 1 && ${POWERLEVEL9K_INSTANT_PROMPT:-off} == off ]] \
  28. || ! command git --version 2>&1 >/dev/null \
  29. || (builtin cd -q "$ZSH"; ! command git rev-parse --is-inside-work-tree &>/dev/null); then
  30. unset update_mode
  31. return
  32. fi
  33. function current_epoch() {
  34. zmodload zsh/datetime
  35. echo $(( EPOCHSECONDS / 60 / 60 / 24 ))
  36. }
  37. function is_update_available() {
  38. local branch
  39. branch=${"$(builtin cd -q "$ZSH"; git config --local oh-my-zsh.branch)":-master}
  40. local remote remote_url remote_repo
  41. remote=${"$(builtin cd -q "$ZSH"; git config --local oh-my-zsh.remote)":-origin}
  42. remote_url=$(builtin cd -q "$ZSH"; git config remote.$remote.url)
  43. local repo
  44. case "$remote_url" in
  45. https://github.com/*) repo=${${remote_url#https://github.com/}%.git} ;;
  46. git@github.com:*) repo=${${remote_url#git@github.com:}%.git} ;;
  47. *)
  48. # If the remote is not using GitHub we can't check for updates
  49. # Let's assume there are updates
  50. return 0 ;;
  51. esac
  52. # If the remote repo is not the official one, let's assume there are updates available
  53. [[ "$repo" = ohmyzsh/ohmyzsh ]] || return 0
  54. local api_url="https://api.github.com/repos/${repo}/commits/${branch}"
  55. # Get local HEAD. If this fails assume there are updates
  56. local local_head
  57. local_head=$(builtin cd -q "$ZSH"; git rev-parse $branch 2>/dev/null) || return 0
  58. # Get remote HEAD. If no suitable command is found assume there are updates
  59. # On any other error, skip the update (connection may be down)
  60. local remote_head
  61. remote_head=$(
  62. if (( ${+commands[curl]} )); then
  63. curl --connect-timeout 2 -fsSL -H 'Accept: application/vnd.github.v3.sha' $api_url 2>/dev/null
  64. elif (( ${+commands[wget]} )); then
  65. wget -T 2 -O- --header='Accept: application/vnd.github.v3.sha' $api_url 2>/dev/null
  66. elif (( ${+commands[fetch]} )); then
  67. HTTP_ACCEPT='Accept: application/vnd.github.v3.sha' fetch -T 2 -o - $api_url 2>/dev/null
  68. else
  69. exit 0
  70. fi
  71. ) || return 1
  72. # Compare local and remote HEADs (if they're equal there are no updates)
  73. [[ "$local_head" != "$remote_head" ]] || return 1
  74. # If local and remote HEADs don't match, check if there's a common ancestor
  75. # If the merge-base call fails, $remote_head might not be downloaded so assume there are updates
  76. local base
  77. base=$(builtin cd -q "$ZSH"; git merge-base $local_head $remote_head 2>/dev/null) || return 0
  78. # If the common ancestor ($base) is not $remote_head,
  79. # the local HEAD is older than the remote HEAD
  80. [[ $base != $remote_head ]]
  81. }
  82. function update_last_updated_file() {
  83. local exit_status="$1" error="$2"
  84. if [[ -z "${1}${2}" ]]; then
  85. echo "LAST_EPOCH=$(current_epoch)" >! "${ZSH_CACHE_DIR}/.zsh-update"
  86. return
  87. fi
  88. cat >! "${ZSH_CACHE_DIR}/.zsh-update" <<EOD
  89. LAST_EPOCH=$(current_epoch)
  90. EXIT_STATUS=${exit_status}
  91. ERROR='${error//\'/’}'
  92. EOD
  93. }
  94. function update_ohmyzsh() {
  95. local verbose_mode
  96. zstyle -s ':omz:update' verbose verbose_mode || verbose_mode=default
  97. # Force verbose mode to silent if p10k instant prompt is enabled
  98. if [[ ${POWERLEVEL9K_INSTANT_PROMPT:-off} != "off" ]]; then
  99. verbose_mode=silent
  100. fi
  101. if [[ "$update_mode" != background-alpha ]] \
  102. && LANG= ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" -i -v $verbose_mode; then
  103. update_last_updated_file
  104. return $?
  105. fi
  106. local exit_status error
  107. if error=$(LANG= ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" -i -v silent 2>&1); then
  108. update_last_updated_file 0 "Update successful"
  109. else
  110. exit_status=$?
  111. update_last_updated_file $exit_status "$error"
  112. return $exit_status
  113. fi
  114. }
  115. function has_typed_input() {
  116. # Created by Philippe Troin <phil@fifi.org>
  117. # https://zsh.org/mla/users/2022/msg00062.html
  118. emulate -L zsh
  119. zmodload zsh/zselect
  120. # Back up stty settings prior to disabling canonical mode
  121. # Consider that no input can be typed if stty fails
  122. # (this might happen if stdin is not a terminal)
  123. local termios
  124. termios=$(stty --save 2>/dev/null) || return 1
  125. {
  126. # Disable canonical mode so that typed input counts
  127. # regardless of whether Enter was pressed
  128. stty -icanon
  129. # Poll stdin (fd 0) for data ready to be read
  130. zselect -t 0 -r 0
  131. return $?
  132. } always {
  133. # Restore stty settings
  134. stty $termios
  135. }
  136. }
  137. function handle_update() {
  138. () {
  139. emulate -L zsh
  140. local epoch_target mtime option LAST_EPOCH
  141. # Remove lock directory if older than a day
  142. zmodload zsh/datetime
  143. zmodload -F zsh/stat b:zstat
  144. if mtime=$(zstat +mtime "$ZSH/log/update.lock" 2>/dev/null); then
  145. if (( (mtime + 3600 * 24) < EPOCHSECONDS )); then
  146. command rm -rf "$ZSH/log/update.lock"
  147. fi
  148. fi
  149. # Check for lock directory
  150. if ! command mkdir "$ZSH/log/update.lock" 2>/dev/null; then
  151. return
  152. fi
  153. # Remove lock directory on exit. `return $ret` is important for when trapping a SIGINT:
  154. # The return status from the function is handled specially. If it is zero, the signal is
  155. # assumed to have been handled, and execution continues normally. Otherwise, the shell
  156. # will behave as interrupted except that the return status of the trap is retained.
  157. # This means that for a CTRL+C, the trap needs to return the same exit status so that
  158. # the shell actually exits what it's running.
  159. trap "
  160. ret=\$?
  161. unset update_mode
  162. unset -f current_epoch is_update_available update_last_updated_file update_ohmyzsh handle_update 2>/dev/null
  163. command rm -rf '$ZSH/log/update.lock'
  164. return \$ret
  165. " EXIT INT QUIT
  166. # Create or update .zsh-update file if missing or malformed
  167. if ! source "${ZSH_CACHE_DIR}/.zsh-update" 2>/dev/null || [[ -z "$LAST_EPOCH" ]]; then
  168. update_last_updated_file
  169. return
  170. fi
  171. # Number of days before trying to update again
  172. zstyle -s ':omz:update' frequency epoch_target || epoch_target=${UPDATE_ZSH_DAYS:-13}
  173. # Test if enough time has passed until the next update
  174. if (( ( $(current_epoch) - $LAST_EPOCH ) < $epoch_target )); then
  175. return
  176. fi
  177. # Test if Oh My Zsh directory is a git repository
  178. if ! (builtin cd -q "$ZSH" && LANG= git rev-parse &>/dev/null); then
  179. echo >&2 "[oh-my-zsh] Can't update: not a git repository."
  180. return
  181. fi
  182. # Check if there are updates available before proceeding
  183. if ! is_update_available; then
  184. update_last_updated_file
  185. return
  186. fi
  187. # If in reminder mode or user has typed input, show reminder and exit
  188. if [[ "$update_mode" = reminder ]] || { [[ "$update_mode" != background-alpha ]] && has_typed_input }; then
  189. printf '\r\e[0K' # move cursor to first column and clear whole line
  190. echo "[oh-my-zsh] It's time to update! You can do that by running \`omz update\`"
  191. return 0
  192. fi
  193. # Don't ask for confirmation before updating if in auto mode
  194. if [[ "$update_mode" = (auto|background-alpha) ]]; then
  195. update_ohmyzsh
  196. return $?
  197. fi
  198. # Ask for confirmation and only update on 'y', 'Y' or Enter
  199. # Otherwise just show a reminder for how to update
  200. echo -n "[oh-my-zsh] Would you like to update? [Y/n] "
  201. read -r -k 1 option
  202. [[ "$option" = $'\n' ]] || echo
  203. case "$option" in
  204. [yY$'\n']) update_ohmyzsh ;;
  205. [nN]) update_last_updated_file ;&
  206. *) echo "[oh-my-zsh] You can update manually by running \`omz update\`" ;;
  207. esac
  208. }
  209. unset update_mode
  210. unset -f current_epoch is_update_available update_last_updated_file update_ohmyzsh handle_update
  211. }
  212. case "$update_mode" in
  213. background-alpha)
  214. autoload -Uz add-zsh-hook
  215. _omz_bg_update() {
  216. # do the update in a subshell
  217. (handle_update) &|
  218. # register update results function
  219. add-zsh-hook precmd _omz_bg_update_status
  220. # deregister background function
  221. add-zsh-hook -d precmd _omz_bg_update
  222. unset -f _omz_bg_update
  223. }
  224. _omz_bg_update_status() {
  225. {
  226. local LAST_EPOCH EXIT_STATUS ERROR
  227. if [[ ! -f "$ZSH_CACHE_DIR"/.zsh-update ]]; then
  228. return 1
  229. fi
  230. # check update results until timeout is reached
  231. . "$ZSH_CACHE_DIR/.zsh-update"
  232. if [[ -z "$EXIT_STATUS" || -z "$ERROR" ]]; then
  233. return 1
  234. fi
  235. if [[ "$EXIT_STATUS" -eq 0 ]]; then
  236. print -P "\n%F{green}[oh-my-zsh] Update successful.%f"
  237. return 0
  238. elif [[ "$EXIT_STATUS" -ne 0 ]]; then
  239. print -P "\n%F{red}[oh-my-zsh] There was an error updating:%f"
  240. printf "\n${fg[yellow]}%s${reset_color}" "$ERROR"
  241. return 0
  242. fi
  243. } always {
  244. if (( TRY_BLOCK_ERROR == 0 )); then
  245. # if last update results have been handled, remove them from the status file
  246. update_last_updated_file
  247. # deregister background function
  248. add-zsh-hook -d precmd _omz_bg_update_status
  249. unset -f _omz_bg_update_status
  250. fi
  251. }
  252. }
  253. add-zsh-hook precmd _omz_bg_update
  254. ;;
  255. *)
  256. handle_update ;;
  257. esac