contrib/zsh_completion
author Pierre-Yves David <pierre-yves.david@octobus.net>
Tue, 15 Dec 2020 18:04:23 +0100
changeset 46568 0d840b9d200d
parent 42526 0c0e54bcea9b
permissions -rw-r--r--
copies-rust: track "overwrites" directly within CopySource Overwrite are "rare enough" that explicitly keeping track of them is going to be "cheap", or at least much cheaper that issuing many `is_ancestor` calls. Even a simple implementation using no specific optimisation (eg: using the generic HashSet type) yield good result in most cases. They are interesting optimization to can do on top of that. We will implement them in later changesets. We tried different approach to speed up the overwrite detection and this one seems the most promising. Without further optimization, we already see sizable speedup on various cases. Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 363753 revs, 5.138169 s, 4.482399 s, -0.655770 s, × 0.8724, 12 µs/rev mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 362229 revs, 5.127809 s, 4.480366 s, -0.647443 s, × 0.8737, 12 µs/rev mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 359344 revs, 4.971136 s, 4.369070 s, -0.602066 s, × 0.8789, 12 µs/rev mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 192665 revs, 1.741678 s, 1.592506 s, -0.149172 s, × 0.9144, 8 µs/rev However, some of the case doing a lot of overwrite get significantly slower. The one with a really problematic slowdown are the special "head reducing" merge in mozilla-try so I am not too worried about them. In addition, further changeset are going to improve the performance of all this. Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 97052 revs, 1.343373 s, 2.119204 s, +0.775831 s, × 1.5775, 21 µs/rev mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 228985 revs, 40.314822 s, 87.824489 s, +47.509667 s, × 2.1785, 383 µs/rev mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 382065 revs, 20.048029 s, 43.304637 s, +23.256608 s, × 2.1600, 113 µs/rev Full benchmark below: Repo Case Source-Rev Dest-Rev # of revisions old time new time Difference Factor time per rev --------------------------------------------------------------------------------------------------------------------------------------------------------------- mercurial x_revs_x_added_0_copies ad6b123de1c7 39cfcef4f463 : 1 revs, 0.000042 s, 0.000043 s, +0.000001 s, × 1.0238, 43 µs/rev mercurial x_revs_x_added_x_copies 2b1c78674230 0c1d10351869 : 6 revs, 0.000110 s, 0.000114 s, +0.000004 s, × 1.0364, 19 µs/rev mercurial x000_revs_x000_added_x_copies 81f8ff2a9bf2 dd3267698d84 : 1032 revs, 0.004945 s, 0.004937 s, -0.000008 s, × 0.9984, 4 µs/rev pypy x_revs_x_added_0_copies aed021ee8ae8 099ed31b181b : 9 revs, 0.000192 s, 0.000339 s, +0.000147 s, × 1.7656, 37 µs/rev pypy x_revs_x000_added_0_copies 4aa4e1f8e19a 359343b9ac0e : 1 revs, 0.000049 s, 0.000049 s, +0.000000 s, × 1.0000, 49 µs/rev pypy x_revs_x_added_x_copies ac52eb7bbbb0 72e022663155 : 7 revs, 0.000112 s, 0.000202 s, +0.000090 s, × 1.8036, 28 µs/rev pypy x_revs_x00_added_x_copies c3b14617fbd7 ace7255d9a26 : 1 revs, 0.000323 s, 0.000409 s, +0.000086 s, × 1.2663, 409 µs/rev pypy x_revs_x000_added_x000_copies df6f7a526b60 a83dc6a2d56f : 6 revs, 0.010042 s, 0.011984 s, +0.001942 s, × 1.1934, 1997 µs/rev pypy x000_revs_xx00_added_0_copies 89a76aede314 2f22446ff07e : 4785 revs, 0.049813 s, 0.050820 s, +0.001007 s, × 1.0202, 10 µs/rev pypy x000_revs_x000_added_x_copies 8a3b5bfd266e 2c68e87c3efe : 6780 revs, 0.079937 s, 0.087953 s, +0.008016 s, × 1.1003, 12 µs/rev pypy x000_revs_x000_added_x000_copies 89a76aede314 7b3dda341c84 : 5441 revs, 0.059412 s, 0.062902 s, +0.003490 s, × 1.0587, 11 µs/rev pypy x0000_revs_x_added_0_copies d1defd0dc478 c9cb1334cc78 : 43645 revs, 0.533769 s, 0.679234 s, +0.145465 s, × 1.2725, 15 µs/rev pypy x0000_revs_xx000_added_0_copies bf2c629d0071 4ffed77c095c : 2 revs, 0.013147 s, 0.013095 s, -0.000052 s, × 0.9960, 6547 µs/rev pypy x0000_revs_xx000_added_x000_copies 08ea3258278e d9fa043f30c0 : 11316 revs, 0.110680 s, 0.120910 s, +0.010230 s, × 1.0924, 10 µs/rev netbeans x_revs_x_added_0_copies fb0955ffcbcd a01e9239f9e7 : 2 revs, 0.000085 s, 0.000087 s, +0.000002 s, × 1.0235, 43 µs/rev netbeans x_revs_x000_added_0_copies 6f360122949f 20eb231cc7d0 : 2 revs, 0.000107 s, 0.000107 s, +0.000000 s, × 1.0000, 53 µs/rev netbeans x_revs_x_added_x_copies 1ada3faf6fb6 5a39d12eecf4 : 3 revs, 0.000175 s, 0.000186 s, +0.000011 s, × 1.0629, 62 µs/rev netbeans x_revs_x00_added_x_copies 35be93ba1e2c 9eec5e90c05f : 9 revs, 0.000720 s, 0.000754 s, +0.000034 s, × 1.0472, 83 µs/rev netbeans x000_revs_xx00_added_0_copies eac3045b4fdd 51d4ae7f1290 : 1421 revs, 0.010019 s, 0.010443 s, +0.000424 s, × 1.0423, 7 µs/rev netbeans x000_revs_x000_added_x_copies e2063d266acd 6081d72689dc : 1533 revs, 0.015602 s, 0.015697 s, +0.000095 s, × 1.0061, 10 µs/rev netbeans x000_revs_x000_added_x000_copies ff453e9fee32 411350406ec2 : 5750 revs, 0.058759 s, 0.063528 s, +0.004769 s, × 1.0812, 11 µs/rev netbeans x0000_revs_xx000_added_x000_copies 588c2d1ced70 1aad62e59ddd : 66949 revs, 0.491550 s, 0.545515 s, +0.053965 s, × 1.1098, 8 µs/rev mozilla-central x_revs_x_added_0_copies 3697f962bb7b 7015fcdd43a2 : 2 revs, 0.000087 s, 0.000089 s, +0.000002 s, × 1.0230, 44 µs/rev mozilla-central x_revs_x000_added_0_copies dd390860c6c9 40d0c5bed75d : 8 revs, 0.000268 s, 0.000265 s, -0.000003 s, × 0.9888, 33 µs/rev mozilla-central x_revs_x_added_x_copies 8d198483ae3b 14207ffc2b2f : 9 revs, 0.000181 s, 0.000381 s, +0.000200 s, × 2.1050, 42 µs/rev mozilla-central x_revs_x00_added_x_copies 98cbc58cc6bc 446a150332c3 : 7 revs, 0.000661 s, 0.000672 s, +0.000011 s, × 1.0166, 96 µs/rev mozilla-central x_revs_x000_added_x000_copies 3c684b4b8f68 0a5e72d1b479 : 3 revs, 0.003256 s, 0.003497 s, +0.000241 s, × 1.0740, 1165 µs/rev mozilla-central x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.066749 s, 0.073204 s, +0.006455 s, × 1.0967, 12200 µs/rev mozilla-central x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.006462 s, 0.006482 s, +0.000020 s, × 1.0031, 4 µs/rev mozilla-central x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.004919 s, 0.005066 s, +0.000147 s, × 1.0299, 123 µs/rev mozilla-central x000_revs_x000_added_x000_copies 7c97034feb78 4407bd0c6330 : 7839 revs, 0.062421 s, 0.065707 s, +0.003286 s, × 1.0526, 8 µs/rev mozilla-central x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.026633 s, 0.026800 s, +0.000167 s, × 1.0063, 43 µs/rev mozilla-central x0000_revs_xx000_added_x000_copies f78c615a656c 96a38b690156 : 30263 revs, 0.197792 s, 0.203856 s, +0.006064 s, × 1.0307, 6 µs/rev mozilla-central x00000_revs_x0000_added_x0000_copies 6832ae71433c 4c222a1d9a00 : 153721 revs, 1.259970 s, 1.293394 s, +0.033424 s, × 1.0265, 8 µs/rev mozilla-central x00000_revs_x00000_added_x000_copies 76caed42cf7c 1daa622bbe42 : 204976 revs, 1.689184 s, 1.698239 s, +0.009055 s, × 1.0054, 8 µs/rev mozilla-try x_revs_x_added_0_copies aaf6dde0deb8 9790f499805a : 2 revs, 0.000865 s, 0.000875 s, +0.000010 s, × 1.0116, 437 µs/rev mozilla-try x_revs_x000_added_0_copies d8d0222927b4 5bb8ce8c7450 : 2 revs, 0.000893 s, 0.000891 s, -0.000002 s, × 0.9978, 445 µs/rev mozilla-try x_revs_x_added_x_copies 092fcca11bdb 936255a0384a : 4 revs, 0.000172 s, 0.000292 s, +0.000120 s, × 1.6977, 73 µs/rev mozilla-try x_revs_x00_added_x_copies b53d2fadbdb5 017afae788ec : 2 revs, 0.001159 s, 0.003939 s, +0.002780 s, × 3.3986, 1969 µs/rev mozilla-try x_revs_x000_added_x000_copies 20408ad61ce5 6f0ee96e21ad : 1 revs, 0.031621 s, 0.033027 s, +0.001406 s, × 1.0445, 33027 µs/rev mozilla-try x_revs_x0000_added_x0000_copies effb563bb7e5 c07a39dc4e80 : 6 revs, 0.068571 s, 0.073703 s, +0.005132 s, × 1.0748, 12283 µs/rev mozilla-try x000_revs_xx00_added_0_copies 6100d773079a 04a55431795e : 1593 revs, 0.006452 s, 0.006469 s, +0.000017 s, × 1.0026, 4 µs/rev mozilla-try x000_revs_x000_added_x_copies 9f17a6fc04f9 2d37b966abed : 41 revs, 0.005443 s, 0.005278 s, -0.000165 s, × 0.9697, 128 µs/rev mozilla-try x000_revs_x000_added_x000_copies 1346fd0130e4 4c65cbdabc1f : 6657 revs, 0.063180 s, 0.064995 s, +0.001815 s, × 1.0287, 9 µs/rev mozilla-try x0000_revs_x_added_0_copies 63519bfd42ee a36a2a865d92 : 40314 revs, 0.293564 s, 0.301041 s, +0.007477 s, × 1.0255, 7 µs/rev mozilla-try x0000_revs_x_added_x_copies 9fe69ff0762d bcabf2a78927 : 38690 revs, 0.286595 s, 0.285575 s, -0.001020 s, × 0.9964, 7 µs/rev mozilla-try x0000_revs_xx000_added_x_copies 156f6e2674f2 4d0f2c178e66 : 8598 revs, 0.083256 s, 0.085597 s, +0.002341 s, × 1.0281, 9 µs/rev mozilla-try x0000_revs_xx000_added_0_copies 9eec5917337d 67118cc6dcad : 615 revs, 0.027282 s, 0.027118 s, -0.000164 s, × 0.9940, 44 µs/rev mozilla-try x0000_revs_xx000_added_x000_copies 89294cd501d9 7ccb2fc7ccb5 : 97052 revs, 1.343373 s, 2.119204 s, +0.775831 s, × 1.5775, 21 µs/rev mozilla-try x0000_revs_x0000_added_x0000_copies e928c65095ed e951f4ad123a : 52031 revs, 0.665737 s, 0.701479 s, +0.035742 s, × 1.0537, 13 µs/rev mozilla-try x00000_revs_x_added_0_copies 6a320851d377 1ebb79acd503 : 363753 revs, 5.138169 s, 4.482399 s, -0.655770 s, × 0.8724, 12 µs/rev mozilla-try x00000_revs_x00000_added_0_copies dc8a3ca7010e d16fde900c9c : 34414 revs, 0.573276 s, 0.574082 s, +0.000806 s, × 1.0014, 16 µs/rev mozilla-try x00000_revs_x_added_x_copies 5173c4b6f97c 95d83ee7242d : 362229 revs, 5.127809 s, 4.480366 s, -0.647443 s, × 0.8737, 12 µs/rev mozilla-try x00000_revs_x000_added_x_copies 9126823d0e9c ca82787bb23c : 359344 revs, 4.971136 s, 4.369070 s, -0.602066 s, × 0.8789, 12 µs/rev mozilla-try x00000_revs_x0000_added_x0000_copies 8d3fafa80d4b eb884023b810 : 192665 revs, 1.741678 s, 1.592506 s, -0.149172 s, × 0.9144, 8 µs/rev mozilla-try x00000_revs_x00000_added_x0000_copies 1b661134e2ca 1ae03d022d6d : 228985 revs, 40.314822 s, 87.824489 s, +47.509667 s, × 2.1785, 383 µs/rev mozilla-try x00000_revs_x00000_added_x000_copies 9b2a99adc05e 8e29777b48e6 : 382065 revs, 20.048029 s, 43.304637 s, +23.256608 s, × 2.1600, 113 µs/rev private : 459513 revs, 37.179470 s, 33.853687 s, -3.325783 s, × 0.9105, 73 µs/rev Differential Revision: https://phab.mercurial-scm.org/D9644

#compdef hg chg

# Zsh completion script for mercurial.  Rename this file to _hg and copy
# it into your zsh function path (/usr/share/zsh/site-functions for
# instance)
#
# If you do not want to install it globally, you can copy it somewhere
# else and add that directory to $fpath. This must be done before
# compinit is called. If the file is copied to ~/.zsh.d, your ~/.zshrc
# file could look like this:
#
# fpath=("$HOME/.zsh.d" $fpath)
# autoload -U compinit
# compinit
#
# Copyright (C) 2005, 2006 Steve Borho <steve@borho.org>
# Copyright (C) 2006-10 Brendan Cully <brendan@kublai.com>
#
# Permission is hereby granted, without written agreement and without
# licence or royalty fees, to use, copy, modify, and distribute this
# software and to distribute modified versions of this software for any
# purpose, provided that the above copyright notice and the following
# two paragraphs appear in all copies of this software.
#
# In no event shall the authors be liable to any party for direct,
# indirect, special, incidental, or consequential damages arising out of
# the use of this software and its documentation, even if the authors
# have been advised of the possibility of such damage.
#
# The authors specifically disclaim any warranties, including, but not
# limited to, the implied warranties of merchantability and fitness for
# a particular purpose.  The software provided hereunder is on an "as
# is" basis, and the authors have no obligation to provide maintenance,
# support, updates, enhancements, or modifications.

emulate -LR zsh
setopt extendedglob

local curcontext="$curcontext" state line
typeset -A _hg_cmd_globals

_hg() {
  local cmd _hg_root
  integer i=2
  _hg_cmd_globals=()

  while (( i < $#words ))
  do
    case "$words[$i]" in
      -R|--repository)
        eval _hg_root="$words[$i+1]"
        _hg_cmd_globals+=("$words[$i]" "$_hg_root")
        (( i += 2 ))
        continue
      ;;
      -R*)
        _hg_cmd_globals+="$words[$i]"
        eval _hg_root="${words[$i]#-R}"
       (( i++ ))
       continue
      ;;
      --cwd|--config)
        # pass along arguments to hg completer
        _hg_cmd_globals+=("$words[$i]" "$words[$i+1]")
        (( i += 2 ))
        continue
      ;;
      -*)
        # skip option
        (( i++ ))
        continue
      ;;
    esac
    if [[ -z "$cmd" ]]
    then
      cmd="$words[$i]"
      words[$i]=()
      (( CURRENT-- ))
    fi
    (( i++ ))
  done

  if [[ -z "$cmd" ]]
  then
    _arguments -s -S : $_hg_global_opts \
    ':mercurial command:_hg_commands'
    return
  fi

  # resolve abbreviations and aliases
  if ! (( $+functions[_hg_cmd_${cmd}] ))
  then
    local cmdexp
    (( $#_hg_cmd_list )) || _hg_get_commands

    cmdexp=$_hg_cmd_list[(r)${cmd}*]
    if [[ $cmdexp == $_hg_cmd_list[(R)${cmd}*] ]]
    then
      # might be nice to rewrite the command line with the expansion
      cmd="$cmdexp"
    fi
    if [[ -n $_hg_alias_list[$cmd] ]]
    then
      cmd=$_hg_alias_list[$cmd]
    fi
  fi

  curcontext="${curcontext%:*:*}:hg-${cmd}:"

  zstyle -s ":completion:$curcontext:" cache-policy update_policy

  if [[ -z "$update_policy" ]]
  then
    zstyle ":completion:$curcontext:" cache-policy _hg_cache_policy
  fi

  if (( $+functions[_hg_cmd_${cmd}] ))
  then
    _hg_cmd_${cmd}
  else
    # complete unknown commands normally
    _arguments -s -S : $_hg_global_opts \
      '*:files:_hg_files'
  fi
}

_hg_cache_policy() {
  typeset -a old

  # cache for a minute
  old=( "$1"(mm+10) )
  (( $#old )) && return 0

  return 1
}

_hg_get_commands() {
  typeset -ga _hg_cmd_list
  typeset -gA _hg_alias_list
  local hline cmd cmdalias

  _call_program hg HGPLAINEXCEPT=alias hg debugcomplete -v | while read -A hline
  do
    cmd=$hline[1]
    _hg_cmd_list+=($cmd)

    for cmdalias in $hline[2,-1]
    do
      _hg_cmd_list+=($cmdalias)
      _hg_alias_list+=($cmdalias $cmd)
    done
  done
}

_hg_commands() {
  (( $#_hg_cmd_list )) || _hg_get_commands
  _describe -t commands 'mercurial command' _hg_cmd_list
}

_hg_revrange() {
  compset -P 1 '*:'
  _hg_labels "$@"
}

_hg_labels() {
  labels=("${(f)$(_hg_cmd debugnamecomplete)}")
  (( $#labels )) && _describe -t labels 'labels' labels
}

_hg_bookmarks() {
  typeset -a bookmark bookmarks

  _hg_cmd bookmarks | while read -A bookmark
  do
    if test -z ${bookmark[-1]:#[0-9]*}
    then
      bookmarks+=($bookmark[-2])
    fi
  done
  (( $#bookmarks )) && _describe -t bookmarks 'bookmarks' bookmarks
}

_hg_branches() {
  typeset -a branches
  local branch

  _hg_cmd branches | while read branch
  do
    branches+=(${branch/ #[0-9]#:*})
  done
  (( $#branches )) && _describe -t branches 'branches' branches
}

# likely merge candidates
_hg_mergerevs() {
  typeset -a heads branches
  local revset='sort(head() and not ., -rev)'

  heads=(${(f)"$(_hg_cmd log -r '$revset' --template '{rev}:{branch}\\n')"})
  (( $#heads )) && _describe -t heads 'heads' heads

  branches=(${(S)heads/#*:/})
  (( $#branches )) && _describe -t branches 'branches' branches
}

_hg_files() {
  if [[ -n "$_hg_root" ]]
  then
    [[ -d "$_hg_root/.hg" ]] || return
    case "$_hg_root" in
      /*)
        _files -W $_hg_root
      ;;
      *)
        _files -W $PWD/$_hg_root
      ;;
    esac
  else
    _files
  fi
}

_hg_status() {
  [[ -d $PREFIX ]] || PREFIX=$PREFIX:h
  status_files=(${(ps:\0:)"$(_hg_cmd status -0n$1 ./$PREFIX)"})
}

_hg_unknown() {
  typeset -a status_files
  _hg_status u
  _wanted files expl 'unknown files' _multi_parts / status_files
}

_hg_missing() {
  typeset -a status_files
  _hg_status d
  _wanted files expl 'missing files' _multi_parts / status_files
}

_hg_committable() {
  typeset -a status_files
  _hg_status mar
  _wanted files expl 'modified, added or removed files' _multi_parts / status_files
}

_hg_resolve() {
  local rstate rpath

  [[ -d $PREFIX ]] || PREFIX=$PREFIX:h

  _hg_cmd resolve -l ./$PREFIX -T '{mergestatus}\ {relpath\(path\)}\\n' | while read rstate rpath
  do
    [[ $rstate == 'R' ]] && resolved_files+=($rpath)
    [[ $rstate == 'U' ]] && unresolved_files+=($rpath)
  done
}

_hg_resolved() {
  typeset -a resolved_files unresolved_files
  _hg_resolve
  _wanted files expl 'resolved files' _multi_parts / resolved_files
}

_hg_unresolved() {
  typeset -a resolved_files unresolved_files
  _hg_resolve
  _wanted files expl 'unresolved files' _multi_parts / unresolved_files
}

_hg_config() {
    typeset -a items
    items=(${${(%f)"$(_call_program hg hg showconfig)"}%%\=*})
    (( $#items )) && _describe -t config 'config item' items
}

_hg_internal_merge_tools=(
  \\:dump \\:fail \\:forcedump \\:local \\:merge \\:merge-local \\:merge-other
  \\:merge3 \\:other \\:prompt \\:tagmerge \\:union
)

_hg_merge_tools() {
  typeset -a external_tools
  _describe -t internal_tools 'internal merge tools' _hg_internal_merge_tools
  external_tools=(${(f)"$(_hg_cmd showconfig merge-tools | cut -d . -f 2)"})
  (( $#external_tools )) && _describe -t external_tools 'external merge tools' external_tools
}

_hg_shelves() {
  shelves=("${(f)$(_hg_cmd shelve -ql)}")
  (( $#shelves )) && _describe -t shelves 'shelves' shelves
}

_hg_addremove() {
  _alternative 'files:unknown files:_hg_unknown' \
    'files:missing files:_hg_missing'
}

_hg_ssh_urls() {
  if [[ -prefix */ ]]
  then
    if zstyle -T ":completion:${curcontext}:files" remote-access
    then
      local host=${PREFIX%%/*}
      typeset -a remdirs
      compset -p $(( $#host + 1 ))
      local rempath=${(M)PREFIX##*/}
      local cacheid="hg:${host}-${rempath//\//_}"
      cacheid=${cacheid%[-_]}
      compset -P '*/'
      if _cache_invalid "$cacheid" || ! _retrieve_cache "$cacheid"
      then
        remdirs=(${${(M)${(f)"$(_call_program files ssh -a -x $host ls -1FL "${(q)rempath}")"}##*/}%/})
        _store_cache "$cacheid" remdirs
      fi
      _describe -t directories 'remote directory' remdirs -S/
    else
      _message 'remote directory'
    fi
  else
    if compset -P '*@'
    then
      _hosts -S/
    else
      _alternative 'hosts:remote host name:_hosts -S/' \
        'users:user:_users -S@'
    fi
  fi
}

_hg_urls() {
  if compset -P bundle://
  then
    _files
  elif compset -P ssh://
  then
    _hg_ssh_urls
  elif [[ -prefix *: ]]
  then
    _urls
  else
    local expl
    compset -S '[^:]*'
    _wanted url-schemas expl 'URL schema' compadd -S '' - \
      http:// https:// ssh:// bundle://
  fi
}

_hg_paths() {
  typeset -a paths pnames
  _hg_cmd paths | while read -A pnames
  do
    paths+=($pnames[1])
  done
  (( $#paths )) && _describe -t path-aliases 'repository alias' paths
}

_hg_remote() {
  _alternative 'path-aliases:repository alias:_hg_paths' \
    'directories:directory:_files -/' \
    'urls:URL:_hg_urls'
}

_hg_clone_dest() {
  _alternative 'directories:directory:_files -/' \
    'urls:URL:_hg_urls'
}

_hg_add_help_topics=(
    config dates diffs environment extensions filesets glossary hgignore hgweb
    merge-tools multirevs obsolescence patterns phases revisions revsets
    subrepos templating urls
)

_hg_help_topics() {
    local topics
    (( $#_hg_cmd_list )) || _hg_get_commands
    topics=($_hg_cmd_list $_hg_add_help_topics)
    _describe -t help_topics 'help topics' topics
}

# Common options
_hg_global_opts=(
    '(--repository -R)'{-R+,--repository=}'[repository root directory or name of overlay bundle file]:repository:_files -/'
    '--cwd=[change working directory]:new working directory:_files -/'
    '(--noninteractive -y)'{-y,--noninteractive}'[do not prompt, automatically pick the first choice for all prompts]'
    '(--verbose -v)'{-v,--verbose}'[enable additional output]'
    '*--config=[set/override config option]:defined config items:_hg_config'
    '(--quiet -q)'{-q,--quiet}'[suppress output]'
    '(--help -h)'{-h,--help}'[display help and exit]'
    '--debug[enable debugging output]'
    '--debugger[start debugger]'
    '--encoding=[set the charset encoding]:encoding'
    '--encodingmode=[set the charset encoding mode]:encoding mode'
    '--traceback[always print a traceback on exception]'
    '--time[time how long the command takes]'
    '--profile[print command execution profile]'
    '--version[output version information and exit]'
    '--hidden[consider hidden changesets]'
    '--color=[when to colorize]:when:(true false yes no always auto never debug)'
    '--pager=[when to paginate (default: auto)]:when:(true false yes no always auto never)'
)

_hg_pat_opts=(
  '*'{-I+,--include=}'[include names matching the given patterns]:pattern:_files -W $(_hg_cmd root) -/'
  '*'{-X+,--exclude=}'[exclude names matching the given patterns]:pattern:_files -W $(_hg_cmd root) -/')

_hg_date_user_opts=(
  '(--currentdate -D)'{-D,--currentdate}'[record the current date as commit date]'
  '(--currentuser -U)'{-U,--currentuser}'[record the current user as committer]'
  '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date'
  '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user')

_hg_gitlike_opts=(
  '(--git -g)'{-g,--git}'[use git extended diff format]')

_hg_diff_opts=(
  $_hg_gitlike_opts
  '(--text -a)'{-a,--text}'[treat all files as text]'
  '--binary[generate binary diffs in git mode (default)]'
  '--nodates[omit dates from diff headers]'
)

_hg_mergetool_opts=(
  '(--tool -t)'{-t+,--tool=}'[specify merge tool]:merge tool:_hg_merge_tools'
)

_hg_dryrun_opts=(
  '(--dry-run -n)'{-n,--dry-run}'[do not perform actions, just print output]')

_hg_ignore_space_opts=(
  '(--ignore-all-space -w)'{-w,--ignore-all-space}'[ignore white space when comparing lines]'
  '(--ignore-space-change -b)'{-b,--ignore-space-change}'[ignore changes in the amount of white space]'
  '(--ignore-blank-lines -B)'{-B,--ignore-blank-lines}'[ignore changes whose lines are all blank]'
  '(--ignore-space-at-eol -Z)'{-Z,--ignore-space-at-eol}'[ignore changes in whitespace at EOL]'
)

_hg_template_opts=(
  '(--template -T)'{-T+,--template=}'[display with template]:template'
)

_hg_log_opts=(
  $_hg_global_opts $_hg_template_opts $_hg_gitlike_opts
  '(--limit -l)'{-l+,--limit=}'[limit number of changes displayed]:limit'
  '(--no-merges -M)'{-M,--no-merges}'[do not show merges]'
  '(--patch -p)'{-p,--patch}'[show patch]'
  '--stat[output diffstat-style summary of changes]'
  '(--graph -G)'{-G,--graph}'[show the revision DAG]'
)

_hg_commit_opts=(
  '(-m --message -l --logfile --edit -e)'{-e,--edit}'[edit commit message]'
  '(-e --edit -l --logfile --message -m)'{-m+,--message=}'[use <text> as commit message]:message'
  '(-e --edit -m --message --logfile -l)'{-l+,--logfile=}'[read the commit message from <file>]:log file:_files')

_hg_remote_opts=(
  '(--ssh -e)'{-e+,--ssh=}'[specify ssh command to use]:command'
  '--remotecmd=[specify hg command to run on the remote side]:remote command'
  '--insecure[do not verify server certificate (ignoring web.cacerts config)]'
)

_hg_clone_opts=(
  $_hg_remote_opts
  '(--noupdate -U)'{-U,--noupdate}'[do not update the new working directory]'
  '--pull[use pull protocol to copy metadata]'
  '--stream[clone with minimal data processing]'
)

_hg_subrepos_opts=(
  '(--subrepos -S)'{-S,--subrepos}'[recurse into subrepositories]')

_hg_cmd() {
  _call_program hg HGPLAIN=1 hg "$_hg_cmd_globals[@]" "$@" 2> /dev/null
}

_hg_cmd_add() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts $_hg_subrepos_opts \
  '*:unknown files:_hg_unknown'
}

_hg_cmd_addremove() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts $_hg_subrepos_opts \
  '(--similarity -s)'{-s+,--similarity=}'[guess renamed files by similarity (0<=s<=100)]:similarity' \
  '*:unknown or missing files:_hg_addremove'
}

_hg_cmd_annotate() {
  _arguments -s -S : $_hg_global_opts $_hg_ignore_space_opts $_hg_pat_opts \
  '(--rev -r)'{-r+,--rev=}'[annotate the specified revision]:revision:_hg_labels' \
  "--no-follow[don't follow copies and renames]" \
  '(--text -a)'{-a,--text}'[treat all files as text]' \
  '(--user -u)'{-u,--user}'[list the author (long with -v)]' \
  '(--file -f)'{-f,--file}'[list the filename]' \
  '(--date -d)'{-d,--date}'[list the date (short with -q)]' \
  '(--number -n)'{-n,--number}'[list the revision number (default)]' \
  '(--changeset -c)'{-c,--changeset}'[list the changeset]' \
  '(--line-number -l)'{-l,--line-number}'[show line number at the first appearance]' \
  '*:files:_hg_files'
}

_hg_cmd_archive() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_subrepos_opts \
  '--no-decode[do not pass files through decoders]' \
  '(--prefix -p)'{-p+,--prefix=}'[directory prefix for files in archive]:prefix' \
  '(--rev -r)'{-r+,--rev=}'[revision to distribute]:revision:_hg_labels' \
  '(--type -t)'{-t+,--type=}'[type of distribution to create]:archive type:(files tar tbz2 tgz uzip zip)' \
  '*:destination:_files'
}

_hg_cmd_backout() {
  _arguments -s -S : $_hg_global_opts $_hg_mergetool_opts $_hg_pat_opts \
    '--merge[merge with old dirstate parent after backout]' \
    '--no-commit[do not commit]' \
    '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date' \
    '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user' \
    '(--rev -r 1)'{-r+,--rev=}'[revision to backout]:revision:_hg_labels' \
    '(--message -m)'{-m+,--message=}'[use <text> as commit message]:text' \
    '(--logfile -l)'{-l+,--logfile=}'[read commit message from <file>]:log file:_files' \
    ':revision:_hg_labels'
}

_hg_cmd_bisect() {
  _arguments -s -S : $_hg_global_opts \
  '(-)'{-r,--reset}'[reset bisect state]' \
  '(--extend -e)'{-e,--extend}'[extend the bisect range]' \
  '(--good -g --bad -b --skip -s --reset -r)'{-g,--good}'[mark changeset good]'::revision:_hg_labels \
  '(--good -g --bad -b --skip -s --reset -r)'{-b,--bad}'[mark changeset bad]'::revision:_hg_labels \
  '(--good -g --bad -b --skip -s --reset -r)'{-s,--skip}'[skip testing changeset]' \
  '(--command -c --noupdate -U)'{-c+,--command=}'[use command to check changeset state]':commands:_command_names \
  '(--command -c --noupdate -U)'{-U,--noupdate}'[do not update to target]'
}

_hg_cmd_bookmarks() {
  _arguments -s -S : $_hg_global_opts \
  '(--force -f)'{-f,--force}'[force]' \
  '(--inactive -i --delete -d --list -l)'{-i,--inactive}'[mark a bookmark inactive]' \
  '(--rev -r --delete -d --rename -m --list -l)'{-r+,--rev=}'[revision]:revision:_hg_labels' \
  '(--rev -r --delete -d --rename -m --list -l --inactive -i)'{-d,--delete}'[delete a given bookmark]' \
  '(--rev -r --delete -d --rename -m --list -l)'{-m+,--rename=}'[rename a given bookmark]:bookmark:_hg_bookmarks' \
  '(--inactive -i --delete -d --list -l)'{-l,--list}'[list existing bookmarks]' \
  ':bookmark:_hg_bookmarks'
}

_hg_cmd_branch() {
  _arguments -s -S : $_hg_global_opts \
  '(--force -f)'{-f,--force}'[set branch name even if it shadows an existing branch]' \
  '(--clean -C)'{-C,--clean}'[reset branch name to parent branch name]'
}

_hg_cmd_branches() {
  _arguments -s -S : $_hg_global_opts \
  '(--closed -c)'{-c,--closed}'[show normal and closed branches]'
}

_hg_cmd_bundle() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts \
  '(--force -f)'{-f,--force}'[run even when the destination is unrelated]' \
  '(2)*--base=[a base changeset assumed to be available at the destination]:revision:_hg_labels' \
  '*'{-b+,--branch=}'[a specific branch you would like to bundle]:branch:_hg_branches' \
  '*'{-r+,--rev=}'[a changeset intended to be added to the destination]:revision:_hg_labels' \
  '(--all -a)'{-a,--all}'[bundle all changesets in the repository]' \
  '(--type -t)'{-t+,--type=}'[bundle compression type to use (default: bzip2)]:bundle type' \
  ':output file:_files' \
  ':destination repository:_files -/'
}

_hg_cmd_cat() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts \
  '(--output -o)'{-o+,--output=}'[print output to file with formatted name]:format string' \
  '(--rev -r)'{-r+,--rev=}'[print the given revision]:revision:_hg_labels' \
  '--decode[apply any matching decode filter]' \
  '*:file:_hg_files'
}

_hg_cmd_clone() {
  _arguments -s -S : $_hg_global_opts $_hg_clone_opts \
  '*'{-r+,--rev=}'[do not clone everything, but include this changeset and its ancestors]:revision' \
  '(--updaterev -u)'{-u+,--updaterev=}'[revision, tag, or branch to check out]:revision' \
  '*'{-b+,--branch=}"[do not clone everything, but include this branch's changesets and their ancestors]:branch" \
  ':source repository:_hg_remote' \
  ':destination:_hg_clone_dest'
}

_hg_cmd_commit() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_subrepos_opts \
  '(--addremove -A)'{-A,--addremove}'[mark new/missing files as added/removed before committing]' \
  '(--message -m)'{-m+,--message=}'[use <text> as commit message]:text' \
  '(--logfile -l)'{-l+,--logfile=}'[read commit message from <file>]:log file:_files' \
  '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date' \
  '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user' \
  '--amend[amend the parent of the working directory]' \
  '--close-branch[mark a branch head as closed]' \
  '(--interactive -i)'{-i,--interactive}'[use interactive mode]' \
  '(--secret -s)'{-s,--secret}'[use the secret phase for committing]' \
  '*:file:_hg_committable'
}

_hg_cmd_copy() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts \
  '(--after -A)'{-A,--after}'[record a copy that has already occurred]' \
  '(--force -f)'{-f,--force}'[forcibly copy over an existing managed file]' \
  '*:file:_hg_files'
}

_hg_cmd_diff() {
  local context state state_descr line ret=1
  typeset -A opt_args

  _arguments -s -S : $_hg_global_opts $_hg_diff_opts $_hg_ignore_space_opts \
                     $_hg_pat_opts $_hg_subrepos_opts \
  '*'{-r+,--rev=}'[revision]:revision:_hg_revrange' \
  '--noprefix[omit a/ and b/ prefixes from filenames]' \
  '(--show-function -p)'{-p,--show-function}'[show which function each change is in]' \
  '(--change -c)'{-c+,--change=}'[change made by revision]:revision:_hg_labels' \
  '--reverse[produce a diff that undoes the changes]' \
  '(--unified -U)'{-U+,--unified=}'[number of lines of context to show]:count' \
  '--stat[output diffstat-style summary of changes]' \
  '--root=[produce diffs relative to subdirectory]:directory:_files -/' \
  '*:file:->diff_files' && ret=0

  if [[ $state == 'diff_files' ]]
  then
    if [[ -n ${opt_args[(I)-r|--rev]} ]]
    then
      _hg_files && ret=0
    else
      _hg_committable && ret=0
    fi
  fi

  return ret
}

_hg_cmd_export() {
  _arguments -s -S : $_hg_global_opts $_hg_diff_opts \
  '(--bookmark -B)'{-B+,--bookmark=}'[export changes only reachable by given bookmark]:bookmark:_hg_bookmarks' \
  '(--output -o)'{-o+,--output=}'[print output to file with formatted name]:format string' \
  '--switch-parent[diff against the second parent]' \
  '*'{-r+,--rev=}'[revisions to export]:revision:_hg_labels' \
  '*:revision:_hg_labels'
}

_hg_cmd_files() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_subrepos_opts \
  '(--rev -r)'{-r+,--rev=}'[search the repository as it is in revision]:revision:_hg_labels' \
  '(--print0 -0)'{-0,--print0}'[end filenames with NUL, for use with xargs]' \
  '*:file:_hg_files'
}

_hg_cmd_forget() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts \
  '(--interactive -i)'{-i,--interactive}'[use interactive mode]' \
  '*:file:_hg_files'
}

_hg_cmd_graft() {
  _arguments -s -S : $_hg_global_opts $_hg_dryrun_opts \
                     $_hg_date_user_opts $_hg_mergetool_opts \
  '*'{-r+,--rev=}'[revisions to graft]:revision:_hg_labels' \
  '(--continue -c --abort -a)'{-c,--continue}'[resume interrupted graft]' \
  '(--continue -c --abort -a)'{-a,--abort}'[abort interrupted graft]' \
  '(--edit -e)'{-e,--edit}'[invoke editor on commit messages]' \
  '--log[append graft info to log message]' \
  "--no-commit[don't commit, just apply the changes in working directory]" \
  '(--force -f)'{-f,--force}'[force graft]' \
  '*:revision:_hg_labels'
}

_hg_cmd_grep() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts \
  '(--print0 -0)'{-0,--print0}'[end fields with NUL]' \
  '--diff[print all revisions when the term was introduced or removed]' \
  '(--text -a)'{-a,--text}'[treat all files as text]' \
  '(--follow -f)'{-f,--follow}'[follow changeset history, or file history across copies and renames]' \
  '(--ignore-case -i)'{-i,--ignore-case}'[ignore case when matching]' \
  '(--files-with-matches -l)'{-l,--files-with-matches}'[print only filenames and revisions that match]' \
  '(--line-number -n)'{-n,--line-number}'[print matching line numbers]' \
  '*'{-r+,--rev=}'[only search files changed within revision range]:revision:_hg_revrange' \
  '(--user -u)'{-u,--user}'[list the author (long with -v)]' \
  '(--date -d)'{-d,--date}'[list the date (short with -q)]' \
  '1:search pattern:' \
  '*:files:_hg_files'
}

_hg_cmd_heads() {
  _arguments -s -S : $_hg_global_opts $_hg_template_opts \
  '(--topo -t)'{-t,--topo}'[show topological heads only]' \
  '(--closed -c)'{-c,--closed}'[show normal and closed branch heads]' \
  '(--rev -r)'{-r+,--rev=}'[show only heads which are descendants of revision]:revision:_hg_labels'
}

_hg_cmd_help() {
  _arguments -s -S : $_hg_global_opts \
  '(--extension -e)'{-e,--extension}'[show only help for extensions]' \
  '(--command -c)'{-c,--command}'[show only help for commands]' \
  '(--keyword -k)'{-k,--keyword}'[show topics matching keyword]' \
  '*'{-s+,--system=}'[show help for specific platform(s)]:platform:(windows vms plan9 unix)' \
  '*:mercurial help topic:_hg_help_topics'
}

_hg_cmd_identify() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts \
  '(--rev -r)'{-r+,--rev=}'[identify the specified revision]:revision:_hg_labels' \
  '(--num -n)'{-n,--num}'[show local revision number]' \
  '(--id -i)'{-i,--id}'[show global revision id]' \
  '(--branch -b)'{-b,--branch}'[show branch]' \
  '(--bookmarks -B)'{-B,--bookmarks}'[show bookmarks]' \
  '(--tags -t)'{-t,--tags}'[show tags]'
}

_hg_cmd_import() {
  _arguments -s -S : $_hg_global_opts $_hg_commit_opts \
  '(--strip -p)'{-p+,--strip=}'[directory strip option for patch (default: 1)]:count' \
  '--bypass[apply patch without touching the working directory]' \
  '--no-commit[do not commit, just update the working directory]' \
  '--partial[commit even if some hunks fail]' \
  '--exact[abort if patch would apply lossily]' \
  '--prefix=[apply patch to subdirectory]:directory:_files -/' \
  '--import-branch[use any branch information in patch (implied by --exact)]' \
  '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date' \
  '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user' \
  '(--similarity -s)'{-s+,--similarity=}'[guess renamed files by similarity (0<=s<=100)]:similarity' \
  '*:patch:_files'
}

_hg_cmd_incoming() {
  _arguments -s -S : $_hg_log_opts $_hg_remote_opts $_hg_subrepos_opts \
  '(--force -f)'{-f,--force}'[run even if remote repository is unrelated]' \
  '*'{-r+,--rev=}'[a remote changeset intended to be added]:revision:_hg_labels' \
  '(--newest-first -n)'{-n,--newest-first}'[show newest record first]' \
  '--bundle=[file to store the bundles into]:bundle file:_files' \
  '(--bookmarks -B)'{-B,--bookmarks}'[compare bookmarks]' \
  '*'{-b+,--branch=}'[a specific branch you would like to pull]:branch:_hg_branches' \
  ':source:_hg_remote'
}

_hg_cmd_init() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts \
  ':directory:_files -/'
}

_hg_cmd_locate() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts \
  '(--rev -r)'{-r+,--rev=}'[search the repository as it is in revision]:revision:_hg_labels' \
  '(--print0 -0)'{-0,--print0}'[end filenames with NUL, for use with xargs]' \
  '(--fullpath -f)'{-f,--fullpath}'[print complete paths from the filesystem root]' \
  '*:search pattern:_hg_files'
}

_hg_cmd_log() {
  _arguments -s -S : $_hg_log_opts $_hg_pat_opts \
  '(--follow -f)'{-f,--follow}'[follow changeset history, or file history across copies and renames]' \
  '(--copies -C)'{-C,--copies}'[show copied files]' \
  '*'{-k+,--keyword=}'[search for a keyword]:keyword' \
  '*'{-r+,--rev=}'[show the specified revision or revset]:revision:_hg_revrange' \
  '--removed[include revisions where files were removed]' \
  '(--only-merges -m)'{-m,--only-merges}'[show only merges]' \
  '*'{-P+,--prune=}'[do not display revision or any of its ancestors]:revision:_hg_labels' \
  '*'{-b+,--branch=}'[show changesets within the given named branch]:branch:_hg_branches' \
  '*'{-u+,--user=}'[revisions committed by user]:user' \
  '(--date -d)'{-d+,--date=}'[show revisions matching date spec]:date' \
  '*:files:_hg_files'
}

_hg_cmd_manifest() {
  _arguments -s -S : $_hg_global_opts \
  '--all[list files from all revisions]' \
  '(--rev -r)'{-r+,--rev=}'[revision to display]:revision:_hg_labels' \
  ':revision:_hg_labels'
}

_hg_cmd_merge() {
  _arguments -s -S : $_hg_global_opts $_hg_mergetool_opts \
  '(--rev -r 1)'{-r+,--rev=}'[revision to merge]:revision:_hg_mergerevs' \
  '(--preview -P)'{-P,--preview}'[review revisions to merge (no merge is performed)]' \
  '(- :)--abort[abort the ongoing merge]' \
  ':revision:_hg_mergerevs'
}

_hg_cmd_outgoing() {
  _arguments -s -S : $_hg_log_opts $_hg_remote_opts $_hg_subrepos_opts \
  '(--force -f)'{-f,--force}'[run even when the destination is unrelated]' \
  '*'{-r+,--rev=}'[a changeset intended to be included in the destination]:revision:_hg_revrange' \
  '(--newest-first -n)'{-n,--newest-first}'[show newest record first]' \
  '(--bookmarks -B)'{-B,--bookmarks}'[compare bookmarks]' \
  '*'{-b+,--branch=}'[a specific branch you would like to push]:branch:_hg_branches' \
  ':destination:_hg_remote'
}

_hg_cmd_parents() {
  _arguments -s -S : $_hg_global_opts $_hg_template_opts \
  '(--rev -r)'{-r+,--rev=}'[show parents of the specified revision]:revision:_hg_labels' \
  ':last modified file:_hg_files'
}

_hg_cmd_paths() {
  _arguments -s -S : $_hg_global_opts \
  ':path:_hg_paths'
}

_hg_cmd_phase() {
  _arguments -s -S : $_hg_global_opts \
  '(--public -p --draft -d --secret -s)'{-p,--public}'[set changeset phase to public]' \
  '(--public -p --draft -d --secret -s)'{-d,--draft}'[set changeset phase to draft]' \
  '(--public -p --draft -d --secret -s)'{-s,--secret}'[set changeset phase to secret]' \
  '(--force -f)'{-f,--force}'[allow to move boundary backward]' \
  '*'{-r+,--rev=}'[target revision]:revision:_hg_labels' \
  '*:revision:_hg_labels'
}

_hg_cmd_pull() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts \
  '(--force -f)'{-f,--force}'[run even when the remote repository is unrelated]' \
  '(--update -u)'{-u,--update}'[update to new branch head if new descendants were pulled]' \
  '*'{-r+,--rev=}'[a remote changeset intended to be added]:revision:_hg_labels' \
  '*'{-B+,--bookmark=}'[bookmark to pull]:bookmark:_hg_bookmarks' \
  '*'{-b+,--branch=}'[a specific branch you would like to pull]:branch:_hg_branches' \
  ':source:_hg_remote'
}

_hg_cmd_push() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts \
  '(--force -f)'{-f,--force}'[force push]' \
  '*'{-r+,--rev=}'[a changeset intended to be included in the destination]:revision:_hg_labels' \
  '*'{-B+,--bookmark=}'[bookmark to push]:bookmark:_hg_bookmarks' \
  '*'{-b+,--branch=}'[a specific branch you would like to push]:branch:_hg_branches' \
  '--new-branch[allow pushing a new branch]' \
  ':destination:_hg_remote'
}

_hg_cmd_remove() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts $_hg_subrepos_opts \
  '(--after -A)'{-A,--after}'[record delete for missing files]' \
  '(--force -f)'{-f,--force}'[forget added files, delete modified files]' \
  '*:file:_hg_files'
}

_hg_cmd_rename() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts \
  '(--after -A)'{-A,--after}'[record a rename that has already occurred]' \
  '(--force -f)'{-f,--force}'[forcibly copy over an existing managed file]' \
  '*:file:_hg_files'
}

_hg_cmd_resolve() {
  local context state state_descr line ret=1
  typeset -A opt_args

  _arguments -s -S : $_hg_global_opts $_hg_mergetool_opts $_hg_pat_opts \
  '(--all -a)'{-a,--all}'[select all unresolved files]' \
  '(--no-status -n)'{-n,--no-status}'[hide status prefix]' \
  '(--list -l --mark -m --unmark -u)'{-l,--list}'[list state of files needing merge]:*:merged files:->resolve_files' \
  '(--mark -m --list -l --unmark -u)'{-m,--mark}'[mark files as resolved]:*:unresolved files:_hg_unresolved' \
  '(--unmark -u --list -l --mark -m)'{-u,--unmark}'[mark files as unresolved]:*:resolved files:_hg_resolved' \
  '*:file:_hg_unresolved' && ret=0

  if [[ $state == 'resolve_files' ]]
  then
    _alternative 'files:resolved files:_hg_resolved' \
      'files:unresolved files:_hg_unresolved' && ret=0
  fi

  return ret
}

_hg_cmd_revert() {
  local context state state_descr line ret=1
  typeset -A opt_args

  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_dryrun_opts \
  '(--all -a :)'{-a,--all}'[revert all changes when no arguments given]' \
  '(--rev -r)'{-r+,--rev=}'[revert to the specified revision]:revision:_hg_labels' \
  '(--no-backup -C)'{-C,--no-backup}'[do not save backup copies of files]' \
  '(--date -d)'{-d+,--date=}'[tipmost revision matching date]:date' \
  '(--interactive -i)'{-i,--interactive}'[interactively select the changes]' \
  '*:file:->revert_files' && ret=0

  if [[ $state == 'revert_files' ]]
  then
    if [[ -n ${opt_args[(I)-r|--rev]} ]]
    then
      _hg_files && ret=0
    else
      typeset -a status_files
      _hg_status mard
      _wanted files expl 'modified, added, removed or deleted file' _multi_parts / status_files && ret=0
    fi
  fi

  return ret
}

_hg_cmd_rollback() {
  _arguments -s -S : $_hg_global_opts $_hg_dryrun_opts \
  '(--force -f)'{-f,--force}'[ignore safety measures]' \
}

_hg_cmd_serve() {
  _arguments -s -S : $_hg_global_opts $_hg_subrepos_opts \
  '(--accesslog -A)'{-A+,--accesslog=}'[name of access log file to write to]:log file:_files' \
  '(--errorlog -E)'{-E+,--errorlog=}'[name of error log file to write to]:log file:_files' \
  '(--daemon -d)'{-d,--daemon}'[run server in background]' \
  '(--port -p)'{-p+,--port=}'[port to listen on (default: 8000)]:listen port' \
  '(--address -a)'{-a+,--address=}'[address to listen on (default: all interfaces)]:interface address' \
  '--prefix=[prefix path to serve from (default: server root)]:directory:_files' \
  '(--name -n)'{-n+,--name=}'[name to show in web pages (default: working directory)]:repository name' \
  '--web-conf=[name of the hgweb config file]:config file:_files' \
  '--pid-file=[name of file to write process ID to]:pid file:_files' \
  '--cmdserver[for remote clients]' \
  '(--templates -t)'{-t+,--templates=}'[web template directory]:template dir:_files -/' \
  '--style=[template style to use]:style' \
  '--stdio[for remote clients]' \
  '(--ipv6 -6)'{-6,--ipv6}'[use IPv6 in addition to IPv4]' \
  '--certificate=[SSL certificate file]:certificate file:_files' \
  '--print-url[start and print only the URL]'
}

_hg_cmd_showconfig() {
  _arguments -s -S : $_hg_global_opts \
  '(--untrusted -u)'{-u,--untrusted}'[show untrusted configuration options]' \
  '(--edit -e)'{-e,--edit}'[edit user config]' \
  '(--local -l --global -g)'{-l,--local}'[edit repository config]' \
  '(--local -l --global -g)'{-g,--global}'[edit global config]' \
  '*:config item:_hg_config'
}

_hg_cmd_status() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_subrepos_opts \
  '(--all -A)'{-A,--all}'[show status of all files]' \
  '(--modified -m)'{-m,--modified}'[show only modified files]' \
  '(--added -a)'{-a,--added}'[show only added files]' \
  '(--removed -r)'{-r,--removed}'[show only removed files]' \
  '(--deleted -d)'{-d,--deleted}'[show only deleted (but tracked) files]' \
  '(--clean -c)'{-c,--clean}'[show only files without changes]' \
  '(--unknown -u)'{-u,--unknown}'[show only unknown (not tracked) files]' \
  '(--ignored -i)'{-i,--ignored}'[show only ignored files]' \
  '(--no-status -n)'{-n,--no-status}'[hide status prefix]' \
  '(--copies -C)'{-C,--copies}'[show source of copied files]' \
  '(--print0 -0)'{-0,--print0}'[end filenames with NUL, for use with xargs]' \
  '*--rev=[show difference from revision]:revision:_hg_labels' \
  '--change=[list the changed files of a revision]:revision:_hg_labels' \
  '*:files:_files'
}

_hg_cmd_summary() {
  _arguments -s -S : $_hg_global_opts \
  '--remote[check for push and pull]'
}

_hg_cmd_tag() {
  _arguments -s -S : $_hg_global_opts \
  '(--local -l)'{-l,--local}'[make the tag local]' \
  '(--message -m)'{-m+,--message=}'[message for tag commit log entry]:message' \
  '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date' \
  '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user' \
  '(--rev -r)'{-r+,--rev=}'[revision to tag]:revision:_hg_labels' \
  '(--force -f)'{-f,--force}'[force tag]' \
  '--remove[remove a tag]' \
  '(--edit -e)'{-e,--edit}'[edit commit message]' \
  ':tag name:'
}

_hg_cmd_tip() {
  _arguments -s -S : $_hg_global_opts $_hg_gitlike_opts $_hg_template_opts \
  '(--patch -p)'{-p,--patch}'[show patch]'
}

_hg_cmd_unbundle() {
  _arguments -s -S : $_hg_global_opts \
  '(--update -u)'{-u,--update}'[update to new branch head if changesets were unbundled]' \
  '*:files:_files'
}

_hg_cmd_update() {
  _arguments -s -S : $_hg_global_opts $_hg_mergetool_opts \
  '(--clean -C)'{-C,--clean}'[discard uncommitted changes (no backup)]' \
  '(--check -c)'{-c,--check}'[require clean working directory]' \
  '(--merge -m)'{-m,--merge}'[merge uncommitted changes]' \
  '(--date -d)'{-d+,--date=}'[tipmost revision matching date]:date' \
  '(--rev -r 1)'{-r+,--rev=}'[revision]:revision:_hg_labels' \
  ':revision:_hg_labels'
}

## extensions ##

# HGK
_hg_cmd_view() {
  _arguments -s -S : $_hg_global_opts \
  '(--limit -l)'{-l+,--limit=}'[limit number of changes displayed]:limit' \
  ':revision range:_hg_labels'
}

# MQ
_hg_qseries() {
  typeset -a patches
  patches=(${(f)"$(_hg_cmd qseries)"})
  (( $#patches )) && _describe -t hg-patches 'patches' patches
}

_hg_qapplied() {
  typeset -a patches
  patches=(${(f)"$(_hg_cmd qapplied)"})
  if (( $#patches ))
  then
    patches+=(qbase qtip)
    _describe -t hg-applied-patches 'applied patches' patches
  fi
}

_hg_qunapplied() {
  typeset -a patches
  patches=(${(f)"$(_hg_cmd qunapplied)"})
  (( $#patches )) && _describe -t hg-unapplied-patches 'unapplied patches' patches
}

# unapplied, including guarded patches
_hg_qdeletable() {
  typeset -a unapplied
  unapplied=(${(f)"$(_hg_cmd qseries)"})
  for p in $(_hg_cmd qapplied)
  do
    unapplied=(${unapplied:#$p})
  done

  (( $#unapplied )) && _describe -t hg-allunapplied-patches 'all unapplied patches' unapplied
}

_hg_qguards() {
  typeset -a guards
  local guard
  compset -P "+|-"
  _hg_cmd qselect -s | while read guard
  do
    guards+=(${guard#(+|-)})
  done
  (( $#guards )) && _describe -t hg-guards 'guards' guards
}

_hg_qseries_opts=(
  '(--summary -s)'{-s,--summary}'[print first line of patch header]')

_hg_cmd_qapplied() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts \
  '(--last -1)'{-1,--last}'[show only the preceding applied patch]' \
  '*:patch:_hg_qapplied'
}

_hg_cmd_qclone() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts $_hg_clone_opts \
  '(--patches -p)'{-p+,--patches=}'[location of source patch repository]:' \
  ':source repository:_hg_remote' \
  ':destination:_hg_clone_dest'
}

_hg_cmd_qdelete() {
  _arguments -s -S : $_hg_global_opts \
  '(--keep -k)'{-k,--keep}'[keep patch file]' \
  '*'{-r+,--rev=}'[stop managing a revision]:applied patch:_hg_revrange' \
  '*:unapplied patch:_hg_qdeletable'
}

_hg_cmd_qdiff() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_diff_opts \
                     $_hg_ignore_space_opts \
  '*:pattern:_hg_files'
}

_hg_cmd_qfinish() {
  _arguments -s -S : $_hg_global_opts \
  '(--applied -a)'{-a,--applied}'[finish all applied patches]' \
  '*:patch:_hg_qapplied'
}

_hg_cmd_qfold() {
  _arguments -s -S : $_hg_global_opts $_hg_commit_opts \
  '(--keep -k)'{-k,--keep}'[keep folded patch files]' \
  '(--force -f)'{-f,--force}'[overwrite any local changes]' \
  '--no-backup[do not save backup copies of files]' \
  '*:unapplied patch:_hg_qunapplied'
}

_hg_cmd_qgoto() {
  _arguments -s -S : $_hg_global_opts \
  '(--force -f)'{-f,--force}'[overwrite any local changes]' \
  '--keep-changes[tolerate non-conflicting local changes]' \
  '--no-backup[do not save backup copies of files]' \
  ':patch:_hg_qseries'
}

_hg_cmd_qguard() {
  _arguments -s -S : $_hg_global_opts \
  '(--list -l)'{-l,--list}'[list all patches and guards]' \
  '(--none -n)'{-n,--none}'[drop all guards]' \
  ':patch:_hg_qseries' \
  '*:guards:_hg_qguards'
}

_hg_cmd_qheader() {
  _arguments -s -S : $_hg_global_opts \
  ':patch:_hg_qseries'
}

_hg_cmd_qimport() {
  _arguments -s -S : $_hg_global_opts $_hg_gitlike_opts \
  '(--existing -e)'{-e,--existing}'[import file in patch directory]' \
  '(--name -n 2)'{-n+,--name=}'[name of patch file]:name' \
  '(--force -f)'{-f,--force}'[overwrite existing files]' \
  '*'{-r+,--rev=}'[place existing revisions under mq control]:revision:_hg_revrange' \
  '(--push -P)'{-P,--push}'[qpush after importing]' \
  '*:patch:_files'
}

_hg_cmd_qnew() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_commit_opts $_hg_date_user_opts $_hg_gitlike_opts \
  ':patch:'
}

_hg_cmd_qnext() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts
}

_hg_cmd_qpop() {
  _arguments -s -S : $_hg_global_opts \
  '(--all -a :)'{-a,--all}'[pop all patches]' \
  '(--force -f)'{-f,--force}'[forget any local changes to patched files]' \
  '--keep-changes[tolerate non-conflicting local changes]' \
  '--no-backup[do not save backup copies of files]' \
  ':patch:_hg_qapplied'
}

_hg_cmd_qprev() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts
}

_hg_cmd_qpush() {
  _arguments -s -S : $_hg_global_opts \
  '(--all -a :)'{-a,--all}'[apply all patches]' \
  '(--list -l)'{-l,--list}'[list patch name in commit text]' \
  '(--force -f)'{-f,--force}'[apply on top of local changes]' \
  '(--exact -e)'{-e,--exact}'[apply the target patch to its recorded parent]' \
  '--move[reorder patch series and apply only the patch]' \
  '--keep-changes[tolerate non-conflicting local changes]' \
  '--no-backup[do not save backup copies of files]' \
  ':patch:_hg_qunapplied'
}

_hg_cmd_qrefresh() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts $_hg_commit_opts $_hg_date_user_opts $_hg_gitlike_opts \
  '(--short -s)'{-s,--short}'[refresh only files already in the patch and specified files]' \
  '*:files:_hg_files'
}

_hg_cmd_qrename() {
  _arguments -s -S : $_hg_global_opts \
  ':patch:_hg_qunapplied' \
  ':destination:'
}

_hg_cmd_qselect() {
  _arguments -s -S : $_hg_global_opts \
  '(--none -n :)'{-n,--none}'[disable all guards]' \
  '(--series -s :)'{-s,--series}'[list all guards in series file]' \
  '--pop[pop to before first guarded applied patch]' \
  '--reapply[pop, then reapply patches]' \
  '*:guards:_hg_qguards'
}

_hg_cmd_qseries() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts \
  '(--missing -m)'{-m,--missing}'[print patches not in series]'
}

_hg_cmd_qunapplied() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts \
  '(--first -1)'{-1,--first}'[show only the first patch]'
}

_hg_cmd_qtop() {
  _arguments -s -S : $_hg_global_opts $_hg_qseries_opts
}

_hg_cmd_strip() {
  _arguments -s -S : $_hg_global_opts \
  '(--force -f)'{-f,--force}'[force removal of changesets, discard uncommitted changes (no backup)]' \
  '--no-backup[do not save backup bundle]' \
  '(--keep -k)'{-k,--keep}'[do not modify working directory during strip]' \
  '*'{-B+,--bookmark=}'[remove revisions only reachable from given bookmark]:bookmark:_hg_bookmarks' \
  '*'{-r+,--rev=}'[strip specified revision]:revision:_hg_labels' \
  '*:revision:_hg_labels'
}

# Patchbomb
_hg_cmd_email() {
  _arguments -s -S : $_hg_global_opts $_hg_remote_opts $_hg_gitlike_opts \
  '--plain[omit hg patch header]' \
  '--body[send patches as inline message text (default)]' \
  '(--outgoing -o)'{-o,--outgoing}'[send changes not found in the target repository]' \
  '(--bundle -b)'{-b,--bundle}'[send changes not in target as a binary bundle]' \
  '(--bookmark -B)'{-B+,--bookmark=}'[send changes only reachable by given bookmark]:bookmark:_hg_bookmarks' \
  '--bundlename=[name of the bundle attachment file (default: bundle)]:name' \
  '*'{-r+,--rev=}'[a revision to send]:revision:_hg_revrange' \
  '--force[run even when remote repository is unrelated (with -b/--bundle)]' \
  '*--base=[a base changeset to specify instead of a destination (with -b/--bundle)]:revision:_hg_labels' \
  '--intro[send an introduction email for a single patch]' \
  '(--inline -i --attach -a)'{-a,--attach}'[send patches as attachments]' \
  '(--attach -a --inline -i)'{-i,--inline}'[send patches as inline attachments]' \
  '*--bcc=[email addresses of blind carbon copy recipients]:email' \
  '*'{-c+,--cc=}'[email addresses of copy recipients]:email' \
  '--confirm[ask for confirmation before sending]' \
  '(--diffstat -d)'{-d,--diffstat}'[add diffstat output to messages]' \
  '--date=[use the given date as the sending date]:date' \
  '--desc=[use the given file as the series description]:files:_files' \
  '(--from -f)'{-f+,--from=}'[email address of sender]:email' \
  '(--test -n)'{-n,--test}'[print messages that would be sent]' \
  '(--mbox -m)'{-m+,--mbox=}'[write messages to mbox file instead of sending them]:file:_files' \
  '*--reply-to=[email addresses replies should be sent to]:email' \
  '(--subject -s)'{-s+,--subject=}'[subject of first message (intro or single patch)]:subject' \
  '--in-reply-to=[message identifier to reply to]:msgid' \
  '*--flag=[flags to add in subject prefixes]:flag' \
  '*'{-t+,--to=}'[email addresses of recipients]:email' \
  ':revision:_hg_revrange'
}

# Rebase
_hg_cmd_rebase() {
  _arguments -s -S : $_hg_global_opts $_hg_commit_opts $_hg_mergetool_opts $_hg_dryrun_opts  \
  '*'{-r+,--rev=}'[rebase these revisions]:revision:_hg_revrange' \
  '(--source -s --base -b)'{-s+,--source=}'[rebase the specified changeset and descendants]:revision:_hg_labels' \
  '(--source -s --base -b)'{-b+,--base=}'[rebase everything from branching point of specified changeset]:revision:_hg_labels' \
  '(--dest -d)'{-d+,--dest=}'[rebase onto the specified changeset]:revision:_hg_labels' \
  '--collapse[collapse the rebased changesets]' \
  '(--keep -k)'{-k,--keep}'[keep original changesets]' \
  '--keepbranches[keep original branch names]' \
  '(--continue -c --abort -a)'{-c,--continue}'[continue an interrupted rebase]' \
  '(--continue -c --abort -a)'{-a,--abort}'[abort an interrupted rebase]' \
}

# Record
_hg_cmd_record() {
  _arguments -s -S : $_hg_global_opts $_hg_commit_opts $_hg_pat_opts \
                     $_hg_ignore_space_opts $_hg_subrepos_opts \
  '(--addremove -A)'{-A,--addremove}'[mark new/missing files as added/removed before committing]' \
  '--close-branch[mark a branch as closed, hiding it from the branch list]' \
  '--amend[amend the parent of the working dir]' \
  '(--date -d)'{-d+,--date=}'[record the specified date as commit date]:date' \
  '(--user -u)'{-u+,--user=}'[record the specified user as committer]:user'
}

_hg_cmd_qrecord() {
  _arguments -s -S : $_hg_global_opts $_hg_commit_opts $_hg_date_user_opts $_hg_gitlike_opts \
                     $_hg_pat_opts $_hg_ignore_space_opts $_hg_subrepos_opts
}

# Convert
_hg_cmd_convert() {
_arguments -s -S : $_hg_global_opts \
  '(--source-type -s)'{-s+,--source-type=}'[source repository type]:type:(hg cvs darcs git svn mtn gnuarch bzr p4)' \
  '(--dest-type -d)'{-d+,--dest-type=}'[destination repository type]:type:(hg svn)' \
  '*'{-r+,--rev=}'[import up to source revision]:revision' \
  '(--authormap -A)'{-A+,--authormap=}'[remap usernames using this file]:file:_files' \
  '--filemap=[remap file names using contents of file]:file:_files' \
  '--full[apply filemap changes by converting all files again]' \
  '--splicemap=[splice synthesized history into place]:file:_files' \
  '--branchmap=[change branch names while converting]:file:_files' \
  '--branchsort[try to sort changesets by branches]' \
  '--datesort[try to sort changesets by date]' \
  '--sourcesort[preserve source changesets order]' \
  '--closesort[try to reorder closed revisions]'
}

# Purge
_hg_cmd_purge() {
  _arguments -s -S : $_hg_global_opts $_hg_pat_opts \
  '(--abort-on-err -a)'{-a,--abort-on-err}'[abort if an error occurs]' \
  '--all[purge ignored files too]' \
  '--dirs[purge empty directories]' \
  '--files[purge files]' \
  '(--print -p)'{-p,--print}'[print filenames instead of deleting them]' \
  '(--print0 -0)'{-0,--print0}'[end filenames with NUL, for use with xargs (implies -p/--print)]'
}

# Shelve
_hg_cmd_shelve() {
  local context state state_descr line ret=1
  typeset -A opt_args

  _arguments -s -S : $_hg_global_opts $_hg_pat_opts \
  '(--addremove -A)'{-A,--addremove}'[mark new/missing files as added/removed before shelving]' \
  '(--unknown -u)'{-u,--unknown}'[store unknown files in the shelve]' \
  '(--name -n :)--cleanup[delete all shelved changes]' \
  '--date=[shelve with the specified commit date]:date' \
  '(--delete -d)'{-d,--delete}'[delete the named shelved change(s)]' \
  '(--edit -e)'{-e,--edit}'[invoke editor on commit messages]' \
  '(--list -l)'{-l,--list}'[list current shelves]' \
  '(--message -m)'{-m+,--message=}'[use text as shelve message]:text' \
  '(--name -n)'{-n+,--name=}'[use the given name for the shelved commit]:name' \
  '(--patch -p)'{-p,--patch}'[output patches for changes]' \
  '(--interactive -i)'{-i,--interactive}'[interactive mode, only works while creating a shelve]' \
  '--stat[output diffstat-style summary of changes]' \
  '*:file:->shelve_files' && ret=0

  if [[ $state == 'shelve_files' ]]
  then
    if [[ -n ${opt_args[(I)-d|--delete|-l|--list|-p|--patch|--stat]} ]]
    then
      _hg_shelves && ret=0
    else
      typeset -a status_files
      _hg_status mard
      _wanted files expl 'modified, added, removed or deleted file' _multi_parts / status_files && ret=0
    fi
  fi

  return ret
}

_hg_cmd_unshelve() {
  _arguments -s -S : $_hg_global_opts $_hg_mergetool_opts \
  '(--abort -a --continue -c --name -n :)'{-a,--abort}'[abort an incomplete unshelve operation]' \
  '(--abort -a --continue -c --name -n :)'{-c,--continue}'[continue an incomplete unshelve operation]' \
  '(--keep -k)'{-k,--keep}'[keep shelve after unshelving]' \
  '(--name -n :)'{-n+,--name=}'[restore shelved change with given name]:shelve:_hg_shelves' \
  ':shelve:_hg_shelves'
}

_hg "$@"