]> src.twobees.de Git - dotfiles.git/blob - stow/oh-my-zsh/.oh-my-zsh/tools/install.sh
initial
[dotfiles.git] / stow / oh-my-zsh / .oh-my-zsh / tools / install.sh
1 #!/bin/sh
2 #
3 # This script should be run via curl:
4 #   sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
5 # or via wget:
6 #   sh -c "$(wget -qO- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
7 # or via fetch:
8 #   sh -c "$(fetch -o - https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
9 #
10 # As an alternative, you can first download the install script and run it afterwards:
11 #   wget https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh
12 #   sh install.sh
13 #
14 # You can tweak the install behavior by setting variables when running the script. For
15 # example, to change the path to the Oh My Zsh repository:
16 #   ZSH=~/.zsh sh install.sh
17 #
18 # Respects the following environment variables:
19 #   ZSH     - path to the Oh My Zsh repository folder (default: $HOME/.oh-my-zsh)
20 #   REPO    - name of the GitHub repo to install from (default: ohmyzsh/ohmyzsh)
21 #   REMOTE  - full remote URL of the git repo to install (default: GitHub via HTTPS)
22 #   BRANCH  - branch to check out immediately after install (default: master)
23 #
24 # Other options:
25 #   CHSH       - 'no' means the installer will not change the default shell (default: yes)
26 #   RUNZSH     - 'no' means the installer will not run zsh after the install (default: yes)
27 #   KEEP_ZSHRC - 'yes' means the installer will not replace an existing .zshrc (default: no)
28 #
29 # You can also pass some arguments to the install script to set some these options:
30 #   --skip-chsh: has the same behavior as setting CHSH to 'no'
31 #   --unattended: sets both CHSH and RUNZSH to 'no'
32 #   --keep-zshrc: sets KEEP_ZSHRC to 'yes'
33 # For example:
34 #   sh install.sh --unattended
35 # or:
36 #   sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
37 #
38 set -e
39
40 # Make sure important variables exist if not already defined
41 #
42 # $USER is defined by login(1) which is not always executed (e.g. containers)
43 # POSIX: https://pubs.opengroup.org/onlinepubs/009695299/utilities/id.html
44 USER=${USER:-$(id -u -n)}
45 # $HOME is defined at the time of login, but it could be unset. If it is unset,
46 # a tilde by itself (~) will not be expanded to the current user's home directory.
47 # POSIX: https://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap08.html#tag_08_03
48 HOME="${HOME:-$(getent passwd $USER 2>/dev/null | cut -d: -f6)}"
49 # macOS does not have getent, but this works even if $HOME is unset
50 HOME="${HOME:-$(eval echo ~$USER)}"
51
52
53 # Track if $ZSH was provided
54 custom_zsh=${ZSH:+yes}
55
56 # Default settings
57 ZSH="${ZSH:-$HOME/.oh-my-zsh}"
58 REPO=${REPO:-ohmyzsh/ohmyzsh}
59 REMOTE=${REMOTE:-https://github.com/${REPO}.git}
60 BRANCH=${BRANCH:-master}
61
62 # Other options
63 CHSH=${CHSH:-yes}
64 RUNZSH=${RUNZSH:-yes}
65 KEEP_ZSHRC=${KEEP_ZSHRC:-no}
66
67
68 command_exists() {
69   command -v "$@" >/dev/null 2>&1
70 }
71
72 user_can_sudo() {
73   # Check if sudo is installed
74   command_exists sudo || return 1
75   # The following command has 3 parts:
76   #
77   # 1. Run `sudo` with `-v`. Does the following:
78   #    • with privilege: asks for a password immediately.
79   #    • without privilege: exits with error code 1 and prints the message:
80   #      Sorry, user <username> may not run sudo on <hostname>
81   #
82   # 2. Pass `-n` to `sudo` to tell it to not ask for a password. If the
83   #    password is not required, the command will finish with exit code 0.
84   #    If one is required, sudo will exit with error code 1 and print the
85   #    message:
86   #    sudo: a password is required
87   #
88   # 3. Check for the words "may not run sudo" in the output to really tell
89   #    whether the user has privileges or not. For that we have to make sure
90   #    to run `sudo` in the default locale (with `LANG=`) so that the message
91   #    stays consistent regardless of the user's locale.
92   #
93   ! LANG= sudo -n -v 2>&1 | grep -q "may not run sudo"
94 }
95
96 # The [ -t 1 ] check only works when the function is not called from
97 # a subshell (like in `$(...)` or `(...)`, so this hack redefines the
98 # function at the top level to always return false when stdout is not
99 # a tty.
100 if [ -t 1 ]; then
101   is_tty() {
102     true
103   }
104 else
105   is_tty() {
106     false
107   }
108 fi
109
110 # This function uses the logic from supports-hyperlinks[1][2], which is
111 # made by Kat Marchán (@zkat) and licensed under the Apache License 2.0.
112 # [1] https://github.com/zkat/supports-hyperlinks
113 # [2] https://crates.io/crates/supports-hyperlinks
114 #
115 # Copyright (c) 2021 Kat Marchán
116 #
117 # Licensed under the Apache License, Version 2.0 (the "License");
118 # you may not use this file except in compliance with the License.
119 # You may obtain a copy of the License at
120 #
121 #     http://www.apache.org/licenses/LICENSE-2.0
122 #
123 # Unless required by applicable law or agreed to in writing, software
124 # distributed under the License is distributed on an "AS IS" BASIS,
125 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
126 # See the License for the specific language governing permissions and
127 # limitations under the License.
128 supports_hyperlinks() {
129   # $FORCE_HYPERLINK must be set and be non-zero (this acts as a logic bypass)
130   if [ -n "$FORCE_HYPERLINK" ]; then
131     [ "$FORCE_HYPERLINK" != 0 ]
132     return $?
133   fi
134
135   # If stdout is not a tty, it doesn't support hyperlinks
136   is_tty || return 1
137
138   # DomTerm terminal emulator (domterm.org)
139   if [ -n "$DOMTERM" ]; then
140     return 0
141   fi
142
143   # VTE-based terminals above v0.50 (Gnome Terminal, Guake, ROXTerm, etc)
144   if [ -n "$VTE_VERSION" ]; then
145     [ $VTE_VERSION -ge 5000 ]
146     return $?
147   fi
148
149   # If $TERM_PROGRAM is set, these terminals support hyperlinks
150   case "$TERM_PROGRAM" in
151   Hyper|iTerm.app|terminology|WezTerm) return 0 ;;
152   esac
153
154   # kitty supports hyperlinks
155   if [ "$TERM" = xterm-kitty ]; then
156     return 0
157   fi
158
159   # Windows Terminal also supports hyperlinks
160   if [ -n "$WT_SESSION" ]; then
161     return 0
162   fi
163
164   # Konsole supports hyperlinks, but it's an opt-in setting that can't be detected
165   # https://github.com/ohmyzsh/ohmyzsh/issues/10964
166   # if [ -n "$KONSOLE_VERSION" ]; then
167   #   return 0
168   # fi
169
170   return 1
171 }
172
173 # Adapted from code and information by Anton Kochkov (@XVilka)
174 # Source: https://gist.github.com/XVilka/8346728
175 supports_truecolor() {
176   case "$COLORTERM" in
177   truecolor|24bit) return 0 ;;
178   esac
179
180   case "$TERM" in
181   iterm           |\
182   tmux-truecolor  |\
183   linux-truecolor |\
184   xterm-truecolor |\
185   screen-truecolor) return 0 ;;
186   esac
187
188   return 1
189 }
190
191 fmt_link() {
192   # $1: text, $2: url, $3: fallback mode
193   if supports_hyperlinks; then
194     printf '\033]8;;%s\033\\%s\033]8;;\033\\\n' "$2" "$1"
195     return
196   fi
197
198   case "$3" in
199   --text) printf '%s\n' "$1" ;;
200   --url|*) fmt_underline "$2" ;;
201   esac
202 }
203
204 fmt_underline() {
205   is_tty && printf '\033[4m%s\033[24m\n' "$*" || printf '%s\n' "$*"
206 }
207
208 # shellcheck disable=SC2016 # backtick in single-quote
209 fmt_code() {
210   is_tty && printf '`\033[2m%s\033[22m`\n' "$*" || printf '`%s`\n' "$*"
211 }
212
213 fmt_error() {
214   printf '%sError: %s%s\n' "${FMT_BOLD}${FMT_RED}" "$*" "$FMT_RESET" >&2
215 }
216
217 setup_color() {
218   # Only use colors if connected to a terminal
219   if ! is_tty; then
220     FMT_RAINBOW=""
221     FMT_RED=""
222     FMT_GREEN=""
223     FMT_YELLOW=""
224     FMT_BLUE=""
225     FMT_BOLD=""
226     FMT_RESET=""
227     return
228   fi
229
230   if supports_truecolor; then
231     FMT_RAINBOW="
232       $(printf '\033[38;2;255;0;0m')
233       $(printf '\033[38;2;255;97;0m')
234       $(printf '\033[38;2;247;255;0m')
235       $(printf '\033[38;2;0;255;30m')
236       $(printf '\033[38;2;77;0;255m')
237       $(printf '\033[38;2;168;0;255m')
238       $(printf '\033[38;2;245;0;172m')
239     "
240   else
241     FMT_RAINBOW="
242       $(printf '\033[38;5;196m')
243       $(printf '\033[38;5;202m')
244       $(printf '\033[38;5;226m')
245       $(printf '\033[38;5;082m')
246       $(printf '\033[38;5;021m')
247       $(printf '\033[38;5;093m')
248       $(printf '\033[38;5;163m')
249     "
250   fi
251
252   FMT_RED=$(printf '\033[31m')
253   FMT_GREEN=$(printf '\033[32m')
254   FMT_YELLOW=$(printf '\033[33m')
255   FMT_BLUE=$(printf '\033[34m')
256   FMT_BOLD=$(printf '\033[1m')
257   FMT_RESET=$(printf '\033[0m')
258 }
259
260 setup_ohmyzsh() {
261   # Prevent the cloned repository from having insecure permissions. Failing to do
262   # so causes compinit() calls to fail with "command not found: compdef" errors
263   # for users with insecure umasks (e.g., "002", allowing group writability). Note
264   # that this will be ignored under Cygwin by default, as Windows ACLs take
265   # precedence over umasks except for filesystems mounted with option "noacl".
266   umask g-w,o-w
267
268   echo "${FMT_BLUE}Cloning Oh My Zsh...${FMT_RESET}"
269
270   command_exists git || {
271     fmt_error "git is not installed"
272     exit 1
273   }
274
275   ostype=$(uname)
276   if [ -z "${ostype%CYGWIN*}" ] && git --version | grep -Eq 'msysgit|windows'; then
277     fmt_error "Windows/MSYS Git is not supported on Cygwin"
278     fmt_error "Make sure the Cygwin git package is installed and is first on the \$PATH"
279     exit 1
280   fi
281
282   # Manual clone with git config options to support git < v1.7.2
283   git init --quiet "$ZSH" && cd "$ZSH" \
284   && git config core.eol lf \
285   && git config core.autocrlf false \
286   && git config fsck.zeroPaddedFilemode ignore \
287   && git config fetch.fsck.zeroPaddedFilemode ignore \
288   && git config receive.fsck.zeroPaddedFilemode ignore \
289   && git config oh-my-zsh.remote origin \
290   && git config oh-my-zsh.branch "$BRANCH" \
291   && git remote add origin "$REMOTE" \
292   && git fetch --depth=1 origin \
293   && git checkout -b "$BRANCH" "origin/$BRANCH" || {
294     [ ! -d "$ZSH" ] || {
295       cd -
296       rm -rf "$ZSH" 2>/dev/null
297     }
298     fmt_error "git clone of oh-my-zsh repo failed"
299     exit 1
300   }
301   # Exit installation directory
302   cd -
303
304   echo
305 }
306
307 setup_zshrc() {
308   # Keep most recent old .zshrc at .zshrc.pre-oh-my-zsh, and older ones
309   # with datestamp of installation that moved them aside, so we never actually
310   # destroy a user's original zshrc
311   echo "${FMT_BLUE}Looking for an existing zsh config...${FMT_RESET}"
312
313   # Must use this exact name so uninstall.sh can find it
314   OLD_ZSHRC=~/.zshrc.pre-oh-my-zsh
315   if [ -f ~/.zshrc ] || [ -h ~/.zshrc ]; then
316     # Skip this if the user doesn't want to replace an existing .zshrc
317     if [ "$KEEP_ZSHRC" = yes ]; then
318       echo "${FMT_YELLOW}Found ~/.zshrc.${FMT_RESET} ${FMT_GREEN}Keeping...${FMT_RESET}"
319       return
320     fi
321     if [ -e "$OLD_ZSHRC" ]; then
322       OLD_OLD_ZSHRC="${OLD_ZSHRC}-$(date +%Y-%m-%d_%H-%M-%S)"
323       if [ -e "$OLD_OLD_ZSHRC" ]; then
324         fmt_error "$OLD_OLD_ZSHRC exists. Can't back up ${OLD_ZSHRC}"
325         fmt_error "re-run the installer again in a couple of seconds"
326         exit 1
327       fi
328       mv "$OLD_ZSHRC" "${OLD_OLD_ZSHRC}"
329
330       echo "${FMT_YELLOW}Found old ~/.zshrc.pre-oh-my-zsh." \
331         "${FMT_GREEN}Backing up to ${OLD_OLD_ZSHRC}${FMT_RESET}"
332     fi
333     echo "${FMT_YELLOW}Found ~/.zshrc.${FMT_RESET} ${FMT_GREEN}Backing up to ${OLD_ZSHRC}${FMT_RESET}"
334     mv ~/.zshrc "$OLD_ZSHRC"
335   fi
336
337   echo "${FMT_GREEN}Using the Oh My Zsh template file and adding it to ~/.zshrc.${FMT_RESET}"
338
339   # Replace $HOME path with '$HOME' in $ZSH variable in .zshrc file
340   omz=$(echo "$ZSH" | sed "s|^$HOME/|\$HOME/|")
341   sed "s|^export ZSH=.*$|export ZSH=\"${omz}\"|" "$ZSH/templates/zshrc.zsh-template" > ~/.zshrc-omztemp
342   mv -f ~/.zshrc-omztemp ~/.zshrc
343
344   echo
345 }
346
347 setup_shell() {
348   # Skip setup if the user wants or stdin is closed (not running interactively).
349   if [ "$CHSH" = no ]; then
350     return
351   fi
352
353   # If this user's login shell is already "zsh", do not attempt to switch.
354   if [ "$(basename -- "$SHELL")" = "zsh" ]; then
355     return
356   fi
357
358   # If this platform doesn't provide a "chsh" command, bail out.
359   if ! command_exists chsh; then
360     cat <<EOF
361 I can't change your shell automatically because this system does not have chsh.
362 ${FMT_BLUE}Please manually change your default shell to zsh${FMT_RESET}
363 EOF
364     return
365   fi
366
367   echo "${FMT_BLUE}Time to change your default shell to zsh:${FMT_RESET}"
368
369   # Prompt for user choice on changing the default login shell
370   printf '%sDo you want to change your default shell to zsh? [Y/n]%s ' \
371     "$FMT_YELLOW" "$FMT_RESET"
372   read -r opt
373   case $opt in
374     y*|Y*|"") ;;
375     n*|N*) echo "Shell change skipped."; return ;;
376     *) echo "Invalid choice. Shell change skipped."; return ;;
377   esac
378
379   # Check if we're running on Termux
380   case "$PREFIX" in
381     *com.termux*) termux=true; zsh=zsh ;;
382     *) termux=false ;;
383   esac
384
385   if [ "$termux" != true ]; then
386     # Test for the right location of the "shells" file
387     if [ -f /etc/shells ]; then
388       shells_file=/etc/shells
389     elif [ -f /usr/share/defaults/etc/shells ]; then # Solus OS
390       shells_file=/usr/share/defaults/etc/shells
391     else
392       fmt_error "could not find /etc/shells file. Change your default shell manually."
393       return
394     fi
395
396     # Get the path to the right zsh binary
397     # 1. Use the most preceding one based on $PATH, then check that it's in the shells file
398     # 2. If that fails, get a zsh path from the shells file, then check it actually exists
399     if ! zsh=$(command -v zsh) || ! grep -qx "$zsh" "$shells_file"; then
400       if ! zsh=$(grep '^/.*/zsh$' "$shells_file" | tail -n 1) || [ ! -f "$zsh" ]; then
401         fmt_error "no zsh binary found or not present in '$shells_file'"
402         fmt_error "change your default shell manually."
403         return
404       fi
405     fi
406   fi
407
408   # We're going to change the default shell, so back up the current one
409   if [ -n "$SHELL" ]; then
410     echo "$SHELL" > ~/.shell.pre-oh-my-zsh
411   else
412     grep "^$USER:" /etc/passwd | awk -F: '{print $7}' > ~/.shell.pre-oh-my-zsh
413   fi
414
415   echo "Changing your shell to $zsh..."
416
417   # Check if user has sudo privileges to run `chsh` with or without `sudo`
418   #
419   # This allows the call to succeed without password on systems where the
420   # user does not have a password but does have sudo privileges, like in
421   # Google Cloud Shell.
422   #
423   # On systems that don't have a user with passwordless sudo, the user will
424   # be prompted for the password either way, so this shouldn't cause any issues.
425   #
426   if user_can_sudo; then
427     sudo -k chsh -s "$zsh" "$USER"  # -k forces the password prompt
428   else
429     chsh -s "$zsh" "$USER"          # run chsh normally
430   fi
431
432   # Check if the shell change was successful
433   if [ $? -ne 0 ]; then
434     fmt_error "chsh command unsuccessful. Change your default shell manually."
435   else
436     export SHELL="$zsh"
437     echo "${FMT_GREEN}Shell successfully changed to '$zsh'.${FMT_RESET}"
438   fi
439
440   echo
441 }
442
443 # shellcheck disable=SC2183  # printf string has more %s than arguments ($FMT_RAINBOW expands to multiple arguments)
444 print_success() {
445   printf '%s         %s__      %s           %s        %s       %s     %s__   %s\n'      $FMT_RAINBOW $FMT_RESET
446   printf '%s  ____  %s/ /_    %s ____ ___  %s__  __  %s ____  %s_____%s/ /_  %s\n'      $FMT_RAINBOW $FMT_RESET
447   printf '%s / __ \\%s/ __ \\  %s / __ `__ \\%s/ / / / %s /_  / %s/ ___/%s __ \\ %s\n'  $FMT_RAINBOW $FMT_RESET
448   printf '%s/ /_/ /%s / / / %s / / / / / /%s /_/ / %s   / /_%s(__  )%s / / / %s\n'      $FMT_RAINBOW $FMT_RESET
449   printf '%s\\____/%s_/ /_/ %s /_/ /_/ /_/%s\\__, / %s   /___/%s____/%s_/ /_/  %s\n'    $FMT_RAINBOW $FMT_RESET
450   printf '%s    %s        %s           %s /____/ %s       %s     %s          %s....is now installed!%s\n' $FMT_RAINBOW $FMT_GREEN $FMT_RESET
451   printf '\n'
452   printf '\n'
453   printf "%s %s %s\n" "Before you scream ${FMT_BOLD}${FMT_YELLOW}Oh My Zsh!${FMT_RESET} look over the" \
454     "$(fmt_code "$(fmt_link ".zshrc" "file://$HOME/.zshrc" --text)")" \
455     "file to select plugins, themes, and options."
456   printf '\n'
457   printf '%s\n' "• Follow us on Twitter: $(fmt_link @ohmyzsh https://twitter.com/ohmyzsh)"
458   printf '%s\n' "• Join our Discord community: $(fmt_link "Discord server" https://discord.gg/ohmyzsh)"
459   printf '%s\n' "• Get stickers, t-shirts, coffee mugs and more: $(fmt_link "Planet Argon Shop" https://shop.planetargon.com/collections/oh-my-zsh)"
460   printf '%s\n' $FMT_RESET
461 }
462
463 main() {
464   # Run as unattended if stdin is not a tty
465   if [ ! -t 0 ]; then
466     RUNZSH=no
467     CHSH=no
468   fi
469
470   # Parse arguments
471   while [ $# -gt 0 ]; do
472     case $1 in
473       --unattended) RUNZSH=no; CHSH=no ;;
474       --skip-chsh) CHSH=no ;;
475       --keep-zshrc) KEEP_ZSHRC=yes ;;
476     esac
477     shift
478   done
479
480   setup_color
481
482   if ! command_exists zsh; then
483     echo "${FMT_YELLOW}Zsh is not installed.${FMT_RESET} Please install zsh first."
484     exit 1
485   fi
486
487   if [ -d "$ZSH" ]; then
488     echo "${FMT_YELLOW}The \$ZSH folder already exists ($ZSH).${FMT_RESET}"
489     if [ "$custom_zsh" = yes ]; then
490       cat <<EOF
491
492 You ran the installer with the \$ZSH setting or the \$ZSH variable is
493 exported. You have 3 options:
494
495 1. Unset the ZSH variable when calling the installer:
496    $(fmt_code "ZSH= sh install.sh")
497 2. Install Oh My Zsh to a directory that doesn't exist yet:
498    $(fmt_code "ZSH=path/to/new/ohmyzsh/folder sh install.sh")
499 3. (Caution) If the folder doesn't contain important information,
500    you can just remove it with $(fmt_code "rm -r $ZSH")
501
502 EOF
503     else
504       echo "You'll need to remove it if you want to reinstall."
505     fi
506     exit 1
507   fi
508
509   setup_ohmyzsh
510   setup_zshrc
511   setup_shell
512
513   print_success
514
515   if [ $RUNZSH = no ]; then
516     echo "${FMT_YELLOW}Run zsh to try it out.${FMT_RESET}"
517     exit
518   fi
519
520   exec zsh -l
521 }
522
523 main "$@"