cli.zsh 20.3 KB
Newer Older
1
2
3
#!/usr/bin/env zsh

function omz {
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  [[ $# -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 "$@"
20
21
22
}

function _omz {
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  local -a cmds subcmds
  cmds=(
    'changelog:Print the changelog'
    'help:Usage information'
    'plugin:Manage plugins'
    'pr:Manage Oh My Zsh Pull Requests'
    'theme:Manage themes'
    'update:Update Oh My Zsh'
  )

  if (( CURRENT == 2 )); then
    _describe 'command' cmds
  elif (( CURRENT == 3 )); then
    case "$words[2]" in
      changelog) local -a refs
        refs=("${(@f)$(command git for-each-ref --format="%(refname:short):%(subject)" refs/heads refs/tags)}")
        _describe 'command' refs ;;
40
41
42
43
44
45
46
      plugin) subcmds=(
        'disable:Disable plugin(s)'
        'enable:Enable plugin(s)'
        'info:Get plugin information'
        'list:List plugins'
        'load:Load plugin(s)'
      )
47
        _describe 'command' subcmds ;;
48
      pr) subcmds=('clean:Delete all Pull Request branches' 'test:Test a Pull Request')
49
        _describe 'command' subcmds ;;
50
      theme) subcmds=('list:List themes' 'set:Set a theme in your .zshrc file' 'use:Load a theme')
51
52
53
        _describe 'command' subcmds ;;
    esac
  elif (( CURRENT == 4 )); then
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    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)
69
70
        local -aU plugins=("$ZSH"/plugins/*/{_*,*.plugin.zsh}(.N:h:t) "$ZSH_CUSTOM"/plugins/*/{_*,*.plugin.zsh}(.N:h:t))
        _describe 'plugin' plugins ;;
71
      theme::(set|use))
72
73
74
75
        local -aU 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
76
77
78
79
80
81
82
83
84
85
86
87
    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
88
89
90
91
92
93

        # 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=(${words[4,$(( CURRENT - 1))]})
94
        valid_plugins=(${valid_plugins:|args})
95

96
        _describe 'plugin' valid_plugins ;;
97
98
99
100
    esac
  fi

  return 0
101
102
103
104
}

compdef _omz omz

105
## Utility functions
106

107
function _omz::confirm {
108
109
110
111
112
113
114
115
116
117
118
119
120
  # 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
121
122
}

123
function _omz::log {
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
  # 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
148
149
}

150
151
152
## User-facing commands

function _omz::help {
153
  cat >&2 <<EOF
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
Usage: omz <command> [options]

Available commands:

  help                Print this help message
  changelog           Print the changelog
  plugin <command>    Manage plugins
  pr     <command>    Manage Oh My Zsh Pull Requests
  theme  <command>    Manage themes
  update              Update Oh My Zsh

EOF
}

function _omz::changelog {
  local version=${1:-HEAD} format=${3:-"--text"}

  if ! command git -C "$ZSH" show-ref --verify refs/heads/$version &>/dev/null && \
    ! command git -C "$ZSH" show-ref --verify refs/tags/$version &>/dev/null && \
    ! command git -C "$ZSH" rev-parse --verify "${version}^{commit}" &>/dev/null; then
174
    cat >&2 <<EOF
175
176
177
178
179
180
181
182
183
184
Usage: omz changelog [version]

NOTE: <version> must be a valid branch, tag or commit.
EOF
    return 1
  fi

  "$ZSH/tools/changelog.sh" "$version" "${2:-}" "$format"
}

185
function _omz::plugin {
186
  (( $# > 0 && $+functions[_omz::plugin::$1] )) || {
187
    cat >&2 <<EOF
188
189
190
191
Usage: omz plugin <command> [options]

Available commands:

192
193
194
195
196
  disable <plugin> Disable plugin(s)
  enable <plugin>  Enable plugin(s)
  info <plugin>    Get information of a plugin
  list             List all available Oh My Zsh plugins
  load <plugin>    Load plugin(s)
197
198

EOF
199
200
    return 1
  }
201

202
203
  local command="$1"
  shift
204

205
  _omz::plugin::$command "$@"
206
207
}

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
function _omz::plugin::disable {
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz plugin disable <plugin> [...]"
    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

229
230
231
232
233
234
  # Remove plugins substitution awk script
  local awk_subst_plugins="\
  gsub(/\s+(${(j:|:)dis_plugins})/, \"\") # with spaces before
  gsub(/(${(j:|:)dis_plugins})\s+/, \"\") # with spaces after
  gsub(/\((${(j:|:)dis_plugins})\)/, \"\") # without spaces (only plugin)
"
235
236
237
238
  # Disable plugins awk script
  local awk_script="
# if plugins=() is in oneline form, substitute disabled plugins and go to next line
/^\s*plugins=\([^#]+\).*\$/ {
239
  $awk_subst_plugins
240
241
242
243
244
245
246
  print \$0
  next
}

# if plugins=() is in multiline form, enable multi flag and disable plugins if they're there
/^\s*plugins=\(/ {
  multi=1
247
  $awk_subst_plugins
248
249
250
251
  print \$0
  next
}

252
# if multi flag is enabled and we find a valid closing parenthesis, remove plugins and disable multi flag
253
254
multi == 1 && /^[^#]*\)/ {
  multi=0
255
  $awk_subst_plugins
256
257
258
259
  print \$0
  next
}

260
261
262
multi == 1 && length(\$0) > 0 {
  $awk_subst_plugins
  if (length(\$0) > 0) print \$0
263
264
265
266
267
268
  next
}

{ print \$0 }
"

269
270
271
  awk "$awk_script" ~/.zshrc > ~/.zshrc.new \
  && command mv -f ~/.zshrc ~/.zshrc.bck \
  && command mv -f ~/.zshrc.new ~/.zshrc
272
273
274
275
276
277
278
279
280
281
282

  # 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 ! zsh -n ~/.zshrc; then
    _omz::log error "broken syntax in ~/.zshrc. Rolling back changes..."
283
284
    command mv -f ~/.zshrc ~/.zshrc.new
    command mv -f ~/.zshrc.bck ~/.zshrc
285
286
287
288
    return 1
  fi

  # Restart the zsh session if there were no errors
289
  _omz::log info "plugins disabled: ${(j:, :)dis_plugins}."
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343

  # Old zsh versions don't have ZSH_ARGZERO
  local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}"
  # Check whether to run a login shell
  [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh"
}

function _omz::plugin::enable {
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz plugin enable <plugin> [...]"
    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, substitute ) with new plugins and go to the next line
/^\s*plugins=\([^#]+\).*\$/ {
  sub(/\)/, \" $add_plugins&\")
  print \$0
  next
}

# if plugins=() is in multiline form, enable multi flag
/^\s*plugins=\(/ {
  multi=1
}

# if multi flag is enabled and we find a valid closing parenthesis,
# add new plugins and disable multi flag
multi == 1 && /^[^#]*\)/ {
  multi=0
  sub(/\)/, \" $add_plugins&\")
  print \$0
  next
}

{ print \$0 }
"

344
345
346
  awk "$awk_script" ~/.zshrc > ~/.zshrc.new \
  && command mv -f ~/.zshrc ~/.zshrc.bck \
  && command mv -f ~/.zshrc.new ~/.zshrc
347
348
349
350

  # Exit if the new .zshrc file wasn't created correctly
  [[ $? -eq 0 ]] || {
    local ret=$?
351
    _omz::log error "error enabling plugins."
352
353
354
355
356
357
    return $ret
  }

  # Exit if the new .zshrc file has syntax errors
  if ! zsh -n ~/.zshrc; then
    _omz::log error "broken syntax in ~/.zshrc. Rolling back changes..."
358
359
    command mv -f ~/.zshrc ~/.zshrc.new
    command mv -f ~/.zshrc.bck ~/.zshrc
360
361
362
363
    return 1
  fi

  # Restart the zsh session if there were no errors
364
  _omz::log info "plugins enabled: ${(j:, :)add_plugins}."
365
366
367
368
369
370
371

  # Old zsh versions don't have ZSH_ARGZERO
  local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}"
  # Check whether to run a login shell
  [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh"
}

372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
function _omz::plugin::info {
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz plugin info <plugin>"
    return 1
  fi

  local readme
  for readme in "$ZSH_CUSTOM/plugins/$1/README.md" "$ZSH/plugins/$1/README.md"; do
    if [[ -f "$readme" ]]; then
      (( ${+commands[less]} )) && less "$readme" || cat "$readme"
      return 0
    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
}

395
function _omz::plugin::list {
396
397
398
399
400
401
402
403
404
405
406
407
  local -a custom_plugins builtin_plugins
  custom_plugins=("$ZSH_CUSTOM"/plugins/*(-/N:t))
  builtin_plugins=("$ZSH"/plugins/*(-/N:t))

  # 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:"
408
    print -l ${(q-)custom_plugins} | column -x
409
410
411
412
413
414
  fi

  if (( ${#builtin_plugins} )); then
    (( ${#custom_plugins} )) && echo # add a line of separation

    print -P "%U%BBuilt-in plugins%b%u:"
415
    print -l ${(q-)builtin_plugins} | column -x
416
  fi
417
418
}

419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
function _omz::plugin::load {
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz plugin load <plugin> [...]"
    return 1
  fi

  local plugins=("$@")
  local plugin base has_completion=0

  for plugin in $plugins; 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 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
    if [[ -f "$base/_$plugin" ]]; then
      has_completion=1
    fi

    # 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
}

469
function _omz::pr {
470
  (( $# > 0 && $+functions[_omz::pr::$1] )) || {
471
    cat >&2 <<EOF
472
473
474
475
Usage: omz pr <command> [options]

Available commands:

476
477
  clean                       Delete all PR branches (ohmyzsh/pull-*)
  test <PR_number_or_URL>     Fetch PR #NUMBER and rebase against master
478
479

EOF
480
481
    return 1
  }
482

483
484
  local command="$1"
  shift
485

486
  _omz::pr::$command "$@"
487
488
489
}

function _omz::pr::clean {
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
  (
    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
  )
517
518
519
}

function _omz::pr::test {
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
  # 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: omz pr test <PR_NUMBER_or_URL>"
    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-<PR_NUMBER> 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 found the ohmyzsh git remote. Aborting..."
      return 1
    }
557

558
559
560
561
562
    # 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
563
564
    }

565
566
567
568
569
570
571
572
573
    # Rebase pull request branch against the current master
    _omz::log info "rebasing PR #$1..."
    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
    }
574

575
576
    _omz::log info "fetch of PR #${1} successful."
  )
577

578
579
  # If there was an error, abort running zsh to test the PR
  [[ $? -eq 0 ]] || return 1
580

581
582
583
  # Run zsh to test the changes
  _omz::log info "running \`zsh\` to test the changes. Run \`exit\` to go back."
  command zsh -l
584

585
586
587
588
  # 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
589

590
591
592
  (
    set -e
    builtin cd -q "$ZSH"
593

594
595
596
597
598
    command git checkout "$branch" -- || {
      _omz::log error "could not go back to the previous branch ('$branch')."
      return 1
    }
  )
599
}
600

601
function _omz::theme {
602
  (( $# > 0 && $+functions[_omz::theme::$1] )) || {
603
    cat >&2 <<EOF
604
605
606
607
Usage: omz theme <command> [options]

Available commands:

608
  list            List all available Oh My Zsh themes
609
610
  set <theme>     Set a theme in your .zshrc file
  use <theme>     Load a theme
611
612

EOF
613
614
    return 1
  }
615

616
617
  local command="$1"
  shift
618

619
  _omz::theme::$command "$@"
620
621
622
}

function _omz::theme::list {
623
  local -a custom_themes builtin_themes
624
625
  custom_themes=("$ZSH_CUSTOM"/**/*.zsh-theme(-.N:r:gs:"$ZSH_CUSTOM"/themes/:::gs:"$ZSH_CUSTOM"/:::))
  builtin_themes=("$ZSH"/themes/*.zsh-theme(-.N:t:r))
626
627
628
629
630
631
632
633
634

  # 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

  if (( ${#custom_themes} )); then
    print -P "%U%BCustom themes%b%u:"
635
    print -l ${(q-)custom_themes} | column -x
636
637
638
639
640
641
  fi

  if (( ${#builtin_themes} )); then
    (( ${#custom_themes} )) && echo # add a line of separation

    print -P "%U%BBuilt-in themes%b%u:"
642
    print -l ${(q-)builtin_themes} | column -x
643
  fi
644
645
}

646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
function _omz::theme::set {
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz theme set <theme>"
    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 && /^\s*ZSH_THEME=[^#]+.*$/ {
  set=1
  sub(/^\s*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
}
'

  awk "$awk_script" ~/.zshrc > ~/.zshrc.new \
  || {
    # Prepend ZSH_THEME= line to .zshrc if it doesn't exist
    cat <<EOF
ZSH_THEME="$1" # set by \`omz\`

EOF
    cat ~/.zshrc
  } > ~/.zshrc.new \
  && command mv -f ~/.zshrc ~/.zshrc.bck \
  && command mv -f ~/.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 ! zsh -n ~/.zshrc; then
    _omz::log error "broken syntax in ~/.zshrc. Rolling back changes..."
    command mv -f ~/.zshrc ~/.zshrc.new
    command mv -f ~/.zshrc.bck ~/.zshrc
    return 1
  fi

  # Restart the zsh session if there were no errors
  _omz::log info "'$1' theme set correctly."

  # Old zsh versions don't have ZSH_ARGZERO
  local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}"
  # Check whether to run a login shell
  [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh"
}

713
function _omz::theme::use {
714
715
716
717
718
719
720
721
722
723
724
725
726
  if [[ -z "$1" ]]; then
    echo >&2 "Usage: omz theme use <theme>"
    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
727
    _omz::log error "%B$1%b theme not found"
728
729
    return 1
  fi
730
731
}

732
function _omz::update {
733
734
  local last_commit=$(cd "$ZSH"; git rev-parse HEAD)

735
  # Run update script
736
737
738
739
740
741
  if [[ "$1" != --unattended ]]; then
    ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh" --interactive
  else
    ZSH="$ZSH" zsh -f "$ZSH/tools/upgrade.sh"
  fi

742
743
744
745
746
  # 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"
747

748
749
  # Restart the zsh session if there were changes
  if [[ "$1" != --unattended && "$(cd "$ZSH"; git rev-parse HEAD)" != "$last_commit" ]]; then
750
751
    # Old zsh versions don't have ZSH_ARGZERO
    local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}"
752
    # Check whether to run a login shell
753
    [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh"
754
  fi
755
}