_docker-compose 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #compdef docker-compose
  2. # Description
  3. # -----------
  4. # zsh completion for docker-compose
  5. # -------------------------------------------------------------------------
  6. # Authors
  7. # -------
  8. # * Steve Durrheimer <[email protected]>
  9. # -------------------------------------------------------------------------
  10. # Inspiration
  11. # -----------
  12. # * @albers docker-compose bash completion script
  13. # * @felixr docker zsh completion script : https://github.com/felixr/docker-zsh-completion
  14. # -------------------------------------------------------------------------
  15. __docker-compose_q() {
  16. docker-compose 2>/dev/null $compose_options "$@"
  17. }
  18. # All services defined in docker-compose.yml
  19. __docker-compose_all_services_in_compose_file() {
  20. local already_selected
  21. local -a services
  22. already_selected=$(echo $words | tr " " "|")
  23. __docker-compose_q config --services \
  24. | grep -Ev "^(${already_selected})$"
  25. }
  26. # All services, even those without an existing container
  27. __docker-compose_services_all() {
  28. [[ $PREFIX = -* ]] && return 1
  29. integer ret=1
  30. services=$(__docker-compose_all_services_in_compose_file)
  31. _alternative "args:services:($services)" && ret=0
  32. return ret
  33. }
  34. # All services that have an entry with the given key in their docker-compose.yml section
  35. __docker-compose_services_with_key() {
  36. local already_selected
  37. local -a buildable
  38. already_selected=$(echo $words | tr " " "|")
  39. # flatten sections to one line, then filter lines containing the key and return section name.
  40. __docker-compose_q config \
  41. | sed -n -e '/^services:/,/^[^ ]/p' \
  42. | sed -n 's/^ //p' \
  43. | awk '/^[a-zA-Z0-9]/{printf "\n"};{printf $0;next;}' \
  44. | grep " \+$1:" \
  45. | cut -d: -f1 \
  46. | grep -Ev "^(${already_selected})$"
  47. }
  48. # All services that are defined by a Dockerfile reference
  49. __docker-compose_services_from_build() {
  50. [[ $PREFIX = -* ]] && return 1
  51. integer ret=1
  52. buildable=$(__docker-compose_services_with_key build)
  53. _alternative "args:buildable services:($buildable)" && ret=0
  54. return ret
  55. }
  56. # All services that are defined by an image
  57. __docker-compose_services_from_image() {
  58. [[ $PREFIX = -* ]] && return 1
  59. integer ret=1
  60. pullable=$(__docker-compose_services_with_key image)
  61. _alternative "args:pullable services:($pullable)" && ret=0
  62. return ret
  63. }
  64. __docker-compose_get_services() {
  65. [[ $PREFIX = -* ]] && return 1
  66. integer ret=1
  67. local kind
  68. declare -a running paused stopped lines args services
  69. docker_status=$(docker ps > /dev/null 2>&1)
  70. if [ $? -ne 0 ]; then
  71. _message "Error! Docker is not running."
  72. return 1
  73. fi
  74. kind=$1
  75. shift
  76. [[ $kind =~ (stopped|all) ]] && args=($args -a)
  77. lines=(${(f)"$(_call_program commands docker $docker_options ps $args)"})
  78. services=(${(f)"$(_call_program commands docker-compose 2>/dev/null $compose_options ps -q)"})
  79. # Parse header line to find columns
  80. local i=1 j=1 k header=${lines[1]}
  81. declare -A begin end
  82. while (( j < ${#header} - 1 )); do
  83. i=$(( j + ${${header[$j,-1]}[(i)[^ ]]} - 1 ))
  84. j=$(( i + ${${header[$i,-1]}[(i) ]} - 1 ))
  85. k=$(( j + ${${header[$j,-1]}[(i)[^ ]]} - 2 ))
  86. begin[${header[$i,$((j-1))]}]=$i
  87. end[${header[$i,$((j-1))]}]=$k
  88. done
  89. lines=(${lines[2,-1]})
  90. # Container ID
  91. local line s name
  92. local -a names
  93. for line in $lines; do
  94. if [[ ${services[@]} == *"${line[${begin[CONTAINER ID]},${end[CONTAINER ID]}]%% ##}"* ]]; then
  95. names=(${(ps:,:)${${line[${begin[NAMES]},-1]}%% *}})
  96. for name in $names; do
  97. s="${${name%_*}#*_}:${(l:15:: :::)${${line[${begin[CREATED]},${end[CREATED]}]/ ago/}%% ##}}"
  98. s="$s, ${line[${begin[CONTAINER ID]},${end[CONTAINER ID]}]%% ##}"
  99. s="$s, ${${${line[${begin[IMAGE]},${end[IMAGE]}]}/:/\\:}%% ##}"
  100. if [[ ${line[${begin[STATUS]},${end[STATUS]}]} = Exit* ]]; then
  101. stopped=($stopped $s)
  102. else
  103. if [[ ${line[${begin[STATUS]},${end[STATUS]}]} = *\(Paused\)* ]]; then
  104. paused=($paused $s)
  105. fi
  106. running=($running $s)
  107. fi
  108. done
  109. fi
  110. done
  111. [[ $kind =~ (running|all) ]] && _describe -t services-running "running services" running "$@" && ret=0
  112. [[ $kind =~ (paused|all) ]] && _describe -t services-paused "paused services" paused "$@" && ret=0
  113. [[ $kind =~ (stopped|all) ]] && _describe -t services-stopped "stopped services" stopped "$@" && ret=0
  114. return ret
  115. }
  116. __docker-compose_pausedservices() {
  117. [[ $PREFIX = -* ]] && return 1
  118. __docker-compose_get_services paused "$@"
  119. }
  120. __docker-compose_stoppedservices() {
  121. [[ $PREFIX = -* ]] && return 1
  122. __docker-compose_get_services stopped "$@"
  123. }
  124. __docker-compose_runningservices() {
  125. [[ $PREFIX = -* ]] && return 1
  126. __docker-compose_get_services running "$@"
  127. }
  128. __docker-compose_services() {
  129. [[ $PREFIX = -* ]] && return 1
  130. __docker-compose_get_services all "$@"
  131. }
  132. __docker-compose_caching_policy() {
  133. oldp=( "$1"(Nmh+1) ) # 1 hour
  134. (( $#oldp ))
  135. }
  136. __docker-compose_commands() {
  137. local cache_policy
  138. zstyle -s ":completion:${curcontext}:" cache-policy cache_policy
  139. if [[ -z "$cache_policy" ]]; then
  140. zstyle ":completion:${curcontext}:" cache-policy __docker-compose_caching_policy
  141. fi
  142. if ( [[ ${+_docker_compose_subcommands} -eq 0 ]] || _cache_invalid docker_compose_subcommands) \
  143. && ! _retrieve_cache docker_compose_subcommands;
  144. then
  145. local -a lines
  146. lines=(${(f)"$(_call_program commands docker-compose 2>&1)"})
  147. _docker_compose_subcommands=(${${${lines[$((${lines[(i)Commands:]} + 1)),${lines[(I) *]}]}## #}/ ##/:})
  148. (( $#_docker_compose_subcommands > 0 )) && _store_cache docker_compose_subcommands _docker_compose_subcommands
  149. fi
  150. _describe -t docker-compose-commands "docker-compose command" _docker_compose_subcommands
  151. }
  152. __docker-compose_subcommand() {
  153. local opts_help opts_force_recreate opts_no_recreate opts_no_build opts_remove_orphans opts_timeout opts_no_color opts_no_deps
  154. opts_help='(: -)--help[Print usage]'
  155. opts_force_recreate="(--no-recreate)--force-recreate[Recreate containers even if their configuration and image haven't changed. Incompatible with --no-recreate.]"
  156. opts_no_recreate="(--force-recreate)--no-recreate[If containers already exist, don't recreate them. Incompatible with --force-recreate.]"
  157. opts_no_build="(--build)--no-build[Don't build an image, even if it's missing.]"
  158. opts_remove_orphans="--remove-orphans[Remove containers for services not defined in the Compose file]"
  159. opts_timeout=('(-t --timeout)'{-t,--timeout}"[Specify a shutdown timeout in seconds. (default: 10)]:seconds: ")
  160. opts_no_color='--no-color[Produce monochrome output.]'
  161. opts_no_deps="--no-deps[Don't start linked services.]"
  162. integer ret=1
  163. case "$words[1]" in
  164. (build)
  165. _arguments \
  166. $opts_help \
  167. "*--build-arg=[Set build-time variables for one service.]:<varname>=<value>: " \
  168. '--force-rm[Always remove intermediate containers.]' \
  169. '--no-cache[Do not use cache when building the image.]' \
  170. '--pull[Always attempt to pull a newer version of the image.]' \
  171. '*:services:__docker-compose_services_from_build' && ret=0
  172. ;;
  173. (bundle)
  174. _arguments \
  175. $opts_help \
  176. '--push-images[Automatically push images for any services which have a `build` option specified.]' \
  177. '(--output -o)'{--output,-o}'[Path to write the bundle file to. Defaults to "<project name>.dab".]:file:_files' && ret=0
  178. ;;
  179. (config)
  180. _arguments \
  181. $opts_help \
  182. '(--quiet -q)'{--quiet,-q}"[Only validate the configuration, don't print anything.]" \
  183. '--resolve-image-digests[Pin image tags to digests.]' \
  184. '--services[Print the service names, one per line.]' \
  185. '--volumes[Print the volume names, one per line.]' && ret=0
  186. ;;
  187. (create)
  188. _arguments \
  189. $opts_help \
  190. $opts_force_recreate \
  191. $opts_no_recreate \
  192. $opts_no_build \
  193. "(--no-build)--build[Build images before creating containers.]" \
  194. '*:services:__docker-compose_services_all' && ret=0
  195. ;;
  196. (down)
  197. _arguments \
  198. $opts_help \
  199. "--rmi[Remove images. Type must be one of: 'all': Remove all images used by any service. 'local': Remove only images that don't have a custom tag set by the \`image\` field.]:type:(all local)" \
  200. '(-v --volumes)'{-v,--volumes}"[Remove named volumes declared in the \`volumes\` section of the Compose file and anonymous volumes attached to containers.]" \
  201. $opts_remove_orphans && ret=0
  202. ;;
  203. (events)
  204. _arguments \
  205. $opts_help \
  206. '--json[Output events as a stream of json objects]' \
  207. '*:services:__docker-compose_services_all' && ret=0
  208. ;;
  209. (exec)
  210. _arguments \
  211. $opts_help \
  212. '-d[Detached mode: Run command in the background.]' \
  213. '--privileged[Give extended privileges to the process.]' \
  214. '--user=[Run the command as this user.]:username:_users' \
  215. '-T[Disable pseudo-tty allocation. By default `docker-compose exec` allocates a TTY.]' \
  216. '--index=[Index of the container if there are multiple instances of a service \[default: 1\]]:index: ' \
  217. '(-):running services:__docker-compose_runningservices' \
  218. '(-):command: _command_names -e' \
  219. '*::arguments: _normal' && ret=0
  220. ;;
  221. (help)
  222. _arguments ':subcommand:__docker-compose_commands' && ret=0
  223. ;;
  224. (images)
  225. _arguments \
  226. $opts_help \
  227. '-q[Only display IDs]' \
  228. '*:services:__docker-compose_services_all' && ret=0
  229. ;;
  230. (kill)
  231. _arguments \
  232. $opts_help \
  233. '-s[SIGNAL to send to the container. Default signal is SIGKILL.]:signal:_signals' \
  234. '*:running services:__docker-compose_runningservices' && ret=0
  235. ;;
  236. (logs)
  237. _arguments \
  238. $opts_help \
  239. '(-f --follow)'{-f,--follow}'[Follow log output]' \
  240. $opts_no_color \
  241. '--tail=[Number of lines to show from the end of the logs for each container.]:number of lines: ' \
  242. '(-t --timestamps)'{-t,--timestamps}'[Show timestamps]' \
  243. '*:services:__docker-compose_services_all' && ret=0
  244. ;;
  245. (pause)
  246. _arguments \
  247. $opts_help \
  248. '*:running services:__docker-compose_runningservices' && ret=0
  249. ;;
  250. (port)
  251. _arguments \
  252. $opts_help \
  253. '--protocol=[tcp or udp \[default: tcp\]]:protocol:(tcp udp)' \
  254. '--index=[index of the container if there are multiple instances of a service \[default: 1\]]:index: ' \
  255. '1:running services:__docker-compose_runningservices' \
  256. '2:port:_ports' && ret=0
  257. ;;
  258. (ps)
  259. _arguments \
  260. $opts_help \
  261. '-q[Only display IDs]' \
  262. '*:services:__docker-compose_services_all' && ret=0
  263. ;;
  264. (pull)
  265. _arguments \
  266. $opts_help \
  267. '--ignore-pull-failures[Pull what it can and ignores images with pull failures.]' \
  268. '*:services:__docker-compose_services_from_image' && ret=0
  269. ;;
  270. (push)
  271. _arguments \
  272. $opts_help \
  273. '--ignore-push-failures[Push what it can and ignores images with push failures.]' \
  274. '*:services:__docker-compose_services' && ret=0
  275. ;;
  276. (rm)
  277. _arguments \
  278. $opts_help \
  279. '(-f --force)'{-f,--force}"[Don't ask to confirm removal]" \
  280. '-v[Remove any anonymous volumes attached to containers]' \
  281. '*:stopped services:__docker-compose_stoppedservices' && ret=0
  282. ;;
  283. (run)
  284. _arguments \
  285. $opts_help \
  286. $opts_no_deps \
  287. '-d[Detached mode: Run container in the background, print new container name.]' \
  288. '*-e[KEY=VAL Set an environment variable (can be used multiple times)]:environment variable KEY=VAL: ' \
  289. '--entrypoint[Overwrite the entrypoint of the image.]:entry point: ' \
  290. '--name=[Assign a name to the container]:name: ' \
  291. '(-p --publish)'{-p,--publish=}"[Publish a container's port(s) to the host]" \
  292. '--rm[Remove container after run. Ignored in detached mode.]' \
  293. "--service-ports[Run command with the service's ports enabled and mapped to the host.]" \
  294. '-T[Disable pseudo-tty allocation. By default `docker-compose run` allocates a TTY.]' \
  295. '(-u --user)'{-u,--user=}'[Run as specified username or uid]:username or uid:_users' \
  296. '(-v --volume)*'{-v,--volume=}'[Bind mount a volume]:volume: ' \
  297. '(-w --workdir)'{-w,--workdir=}'[Working directory inside the container]:workdir: ' \
  298. '(-):services:__docker-compose_services' \
  299. '(-):command: _command_names -e' \
  300. '*::arguments: _normal' && ret=0
  301. ;;
  302. (scale)
  303. _arguments \
  304. $opts_help \
  305. $opts_timeout \
  306. '*:running services:__docker-compose_runningservices' && ret=0
  307. ;;
  308. (start)
  309. _arguments \
  310. $opts_help \
  311. '*:stopped services:__docker-compose_stoppedservices' && ret=0
  312. ;;
  313. (stop|restart)
  314. _arguments \
  315. $opts_help \
  316. $opts_timeout \
  317. '*:running services:__docker-compose_runningservices' && ret=0
  318. ;;
  319. (top)
  320. _arguments \
  321. $opts_help \
  322. '*:running services:__docker-compose_runningservices' && ret=0
  323. ;;
  324. (unpause)
  325. _arguments \
  326. $opts_help \
  327. '*:paused services:__docker-compose_pausedservices' && ret=0
  328. ;;
  329. (up)
  330. _arguments \
  331. $opts_help \
  332. '(--abort-on-container-exit)-d[Detached mode: Run containers in the background, print new container names. Incompatible with --abort-on-container-exit.]' \
  333. $opts_no_color \
  334. $opts_no_deps \
  335. $opts_force_recreate \
  336. $opts_no_recreate \
  337. $opts_no_build \
  338. "(--no-build)--build[Build images before starting containers.]" \
  339. "(-d)--abort-on-container-exit[Stops all containers if any container was stopped. Incompatible with -d.]" \
  340. '(-t --timeout)'{-t,--timeout}"[Use this timeout in seconds for container shutdown when attached or when containers are already running. (default: 10)]:seconds: " \
  341. $opts_remove_orphans \
  342. '*:services:__docker-compose_services_all' && ret=0
  343. ;;
  344. (version)
  345. _arguments \
  346. $opts_help \
  347. "--short[Shows only Compose's version number.]" && ret=0
  348. ;;
  349. (*)
  350. _message 'Unknown sub command' && ret=1
  351. ;;
  352. esac
  353. return ret
  354. }
  355. _docker-compose() {
  356. # Support for subservices, which allows for `compdef _docker docker-shell=_docker_containers`.
  357. # Based on /usr/share/zsh/functions/Completion/Unix/_git without support for `ret`.
  358. if [[ $service != docker-compose ]]; then
  359. _call_function - _$service
  360. return
  361. fi
  362. local curcontext="$curcontext" state line
  363. integer ret=1
  364. typeset -A opt_args
  365. local file_description
  366. if [[ -n ${words[(r)-f]} || -n ${words[(r)--file]} ]] ; then
  367. file_description="Specify an override docker-compose file (default: docker-compose.override.yml)"
  368. else
  369. file_description="Specify an alternate docker-compose file (default: docker-compose.yml)"
  370. fi
  371. _arguments -C \
  372. '(- :)'{-h,--help}'[Get help]' \
  373. '*'{-f,--file}"[${file_description}]:file:_files -g '*.yml'" \
  374. '(-p --project-name)'{-p,--project-name}'[Specify an alternate project name (default: directory name)]:project name:' \
  375. '--verbose[Show more output]' \
  376. '(- :)'{-v,--version}'[Print version and exit]' \
  377. '(-H --host)'{-H,--host}'[Daemon socket to connect to]:host:' \
  378. '--tls[Use TLS; implied by --tlsverify]' \
  379. '--tlscacert=[Trust certs signed only by this CA]:ca path:' \
  380. '--tlscert=[Path to TLS certificate file]:client cert path:' \
  381. '--tlskey=[Path to TLS key file]:tls key path:' \
  382. '--tlsverify[Use TLS and verify the remote]' \
  383. "--skip-hostname-check[Don't check the daemon's hostname against the name specified in the client certificate (for example if your docker host is an IP address)]" \
  384. '(-): :->command' \
  385. '(-)*:: :->option-or-argument' && ret=0
  386. local -a relevant_compose_flags relevant_docker_flags compose_options docker_options
  387. relevant_compose_flags=(
  388. "--file" "-f"
  389. "--host" "-H"
  390. "--project-name" "-p"
  391. "--tls"
  392. "--tlscacert"
  393. "--tlscert"
  394. "--tlskey"
  395. "--tlsverify"
  396. "--skip-hostname-check"
  397. )
  398. relevant_docker_flags=(
  399. "--host" "-H"
  400. "--tls"
  401. "--tlscacert"
  402. "--tlscert"
  403. "--tlskey"
  404. "--tlsverify"
  405. )
  406. for k in "${(@k)opt_args}"; do
  407. if [[ -n "${relevant_docker_flags[(r)$k]}" ]]; then
  408. docker_options+=$k
  409. if [[ -n "$opt_args[$k]" ]]; then
  410. docker_options+=$opt_args[$k]
  411. fi
  412. fi
  413. if [[ -n "${relevant_compose_flags[(r)$k]}" ]]; then
  414. compose_options+=$k
  415. if [[ -n "$opt_args[$k]" ]]; then
  416. compose_options+=$opt_args[$k]
  417. fi
  418. fi
  419. done
  420. case $state in
  421. (command)
  422. __docker-compose_commands && ret=0
  423. ;;
  424. (option-or-argument)
  425. curcontext=${curcontext%:*:*}:docker-compose-$words[1]:
  426. __docker-compose_subcommand && ret=0
  427. ;;
  428. esac
  429. return ret
  430. }
  431. _docker-compose "$@"