_docker-compose 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. #compdef docker-compose
  2. # Description
  3. # -----------
  4. # zsh completion for docker-compose
  5. # -------------------------------------------------------------------------
  6. # Authors
  7. # -------
  8. # * Steve Durrheimer <s.durrheimer@gmail.com>
  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. '--memory[Memory limit for the build container.]' \
  170. '--no-cache[Do not use cache when building the image.]' \
  171. '--pull[Always attempt to pull a newer version of the image.]' \
  172. '*:services:__docker-compose_services_from_build' && ret=0
  173. ;;
  174. (bundle)
  175. _arguments \
  176. $opts_help \
  177. '--push-images[Automatically push images for any services which have a `build` option specified.]' \
  178. '(--output -o)'{--output,-o}'[Path to write the bundle file to. Defaults to "<project name>.dab".]:file:_files' && ret=0
  179. ;;
  180. (config)
  181. _arguments \
  182. $opts_help \
  183. '(--quiet -q)'{--quiet,-q}"[Only validate the configuration, don't print anything.]" \
  184. '--resolve-image-digests[Pin image tags to digests.]' \
  185. '--services[Print the service names, one per line.]' \
  186. '--volumes[Print the volume names, one per line.]' && ret=0
  187. ;;
  188. (create)
  189. _arguments \
  190. $opts_help \
  191. $opts_force_recreate \
  192. $opts_no_recreate \
  193. $opts_no_build \
  194. "(--no-build)--build[Build images before creating containers.]" \
  195. '*:services:__docker-compose_services_all' && ret=0
  196. ;;
  197. (down)
  198. _arguments \
  199. $opts_help \
  200. "--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)" \
  201. '(-v --volumes)'{-v,--volumes}"[Remove named volumes declared in the \`volumes\` section of the Compose file and anonymous volumes attached to containers.]" \
  202. $opts_remove_orphans && ret=0
  203. ;;
  204. (events)
  205. _arguments \
  206. $opts_help \
  207. '--json[Output events as a stream of json objects]' \
  208. '*:services:__docker-compose_services_all' && ret=0
  209. ;;
  210. (exec)
  211. _arguments \
  212. $opts_help \
  213. '-d[Detached mode: Run command in the background.]' \
  214. '--privileged[Give extended privileges to the process.]' \
  215. '(-u --user)'{-u,--user=}'[Run the command as this user.]:username:_users' \
  216. '-T[Disable pseudo-tty allocation. By default `docker-compose exec` allocates a TTY.]' \
  217. '--index=[Index of the container if there are multiple instances of a service \[default: 1\]]:index: ' \
  218. '(-):running services:__docker-compose_runningservices' \
  219. '(-):command: _command_names -e' \
  220. '*::arguments: _normal' && ret=0
  221. ;;
  222. (help)
  223. _arguments ':subcommand:__docker-compose_commands' && ret=0
  224. ;;
  225. (images)
  226. _arguments \
  227. $opts_help \
  228. '-q[Only display IDs]' \
  229. '*:services:__docker-compose_services_all' && ret=0
  230. ;;
  231. (kill)
  232. _arguments \
  233. $opts_help \
  234. '-s[SIGNAL to send to the container. Default signal is SIGKILL.]:signal:_signals' \
  235. '*:running services:__docker-compose_runningservices' && ret=0
  236. ;;
  237. (logs)
  238. _arguments \
  239. $opts_help \
  240. '(-f --follow)'{-f,--follow}'[Follow log output]' \
  241. $opts_no_color \
  242. '--tail=[Number of lines to show from the end of the logs for each container.]:number of lines: ' \
  243. '(-t --timestamps)'{-t,--timestamps}'[Show timestamps]' \
  244. '*:services:__docker-compose_services_all' && ret=0
  245. ;;
  246. (pause)
  247. _arguments \
  248. $opts_help \
  249. '*:running services:__docker-compose_runningservices' && ret=0
  250. ;;
  251. (port)
  252. _arguments \
  253. $opts_help \
  254. '--protocol=[tcp or udp \[default: tcp\]]:protocol:(tcp udp)' \
  255. '--index=[index of the container if there are multiple instances of a service \[default: 1\]]:index: ' \
  256. '1:running services:__docker-compose_runningservices' \
  257. '2:port:_ports' && ret=0
  258. ;;
  259. (ps)
  260. _arguments \
  261. $opts_help \
  262. '-q[Only display IDs]' \
  263. '*:services:__docker-compose_services_all' && ret=0
  264. ;;
  265. (pull)
  266. _arguments \
  267. $opts_help \
  268. '--ignore-pull-failures[Pull what it can and ignores images with pull failures.]' \
  269. '*:services:__docker-compose_services_from_image' && ret=0
  270. ;;
  271. (push)
  272. _arguments \
  273. $opts_help \
  274. '--ignore-push-failures[Push what it can and ignores images with push failures.]' \
  275. '*:services:__docker-compose_services' && ret=0
  276. ;;
  277. (rm)
  278. _arguments \
  279. $opts_help \
  280. '(-f --force)'{-f,--force}"[Don't ask to confirm removal]" \
  281. '-v[Remove any anonymous volumes attached to containers]' \
  282. '*:stopped services:__docker-compose_stoppedservices' && ret=0
  283. ;;
  284. (run)
  285. _arguments \
  286. $opts_help \
  287. $opts_no_deps \
  288. '-d[Detached mode: Run container in the background, print new container name.]' \
  289. '*-e[KEY=VAL Set an environment variable (can be used multiple times)]:environment variable KEY=VAL: ' \
  290. '--entrypoint[Overwrite the entrypoint of the image.]:entry point: ' \
  291. '--name=[Assign a name to the container]:name: ' \
  292. '(-p --publish)'{-p,--publish=}"[Publish a container's port(s) to the host]" \
  293. '--rm[Remove container after run. Ignored in detached mode.]' \
  294. "--service-ports[Run command with the service's ports enabled and mapped to the host.]" \
  295. '-T[Disable pseudo-tty allocation. By default `docker-compose run` allocates a TTY.]' \
  296. '(-u --user)'{-u,--user=}'[Run as specified username or uid]:username or uid:_users' \
  297. '(-v --volume)*'{-v,--volume=}'[Bind mount a volume]:volume: ' \
  298. '(-w --workdir)'{-w,--workdir=}'[Working directory inside the container]:workdir: ' \
  299. '(-):services:__docker-compose_services' \
  300. '(-):command: _command_names -e' \
  301. '*::arguments: _normal' && ret=0
  302. ;;
  303. (scale)
  304. _arguments \
  305. $opts_help \
  306. $opts_timeout \
  307. '*:running services:__docker-compose_runningservices' && ret=0
  308. ;;
  309. (start)
  310. _arguments \
  311. $opts_help \
  312. '*:stopped services:__docker-compose_stoppedservices' && ret=0
  313. ;;
  314. (stop|restart)
  315. _arguments \
  316. $opts_help \
  317. $opts_timeout \
  318. '*:running services:__docker-compose_runningservices' && ret=0
  319. ;;
  320. (top)
  321. _arguments \
  322. $opts_help \
  323. '*:running services:__docker-compose_runningservices' && ret=0
  324. ;;
  325. (unpause)
  326. _arguments \
  327. $opts_help \
  328. '*:paused services:__docker-compose_pausedservices' && ret=0
  329. ;;
  330. (up)
  331. _arguments \
  332. $opts_help \
  333. '(--abort-on-container-exit)-d[Detached mode: Run containers in the background, print new container names. Incompatible with --abort-on-container-exit.]' \
  334. $opts_no_color \
  335. $opts_no_deps \
  336. $opts_force_recreate \
  337. $opts_no_recreate \
  338. $opts_no_build \
  339. "(--no-build)--build[Build images before starting containers.]" \
  340. "(-d)--abort-on-container-exit[Stops all containers if any container was stopped. Incompatible with -d.]" \
  341. '(-t --timeout)'{-t,--timeout}"[Use this timeout in seconds for container shutdown when attached or when containers are already running. (default: 10)]:seconds: " \
  342. $opts_remove_orphans \
  343. '*:services:__docker-compose_services_all' && ret=0
  344. ;;
  345. (version)
  346. _arguments \
  347. $opts_help \
  348. "--short[Shows only Compose's version number.]" && ret=0
  349. ;;
  350. (*)
  351. _message 'Unknown sub command' && ret=1
  352. ;;
  353. esac
  354. return ret
  355. }
  356. _docker-compose() {
  357. # Support for subservices, which allows for `compdef _docker docker-shell=_docker_containers`.
  358. # Based on /usr/share/zsh/functions/Completion/Unix/_git without support for `ret`.
  359. if [[ $service != docker-compose ]]; then
  360. _call_function - _$service
  361. return
  362. fi
  363. local curcontext="$curcontext" state line
  364. integer ret=1
  365. typeset -A opt_args
  366. local file_description
  367. if [[ -n ${words[(r)-f]} || -n ${words[(r)--file]} ]] ; then
  368. file_description="Specify an override docker-compose file (default: docker-compose.override.yml)"
  369. else
  370. file_description="Specify an alternate docker-compose file (default: docker-compose.yml)"
  371. fi
  372. _arguments -C \
  373. '(- :)'{-h,--help}'[Get help]' \
  374. '*'{-f,--file}"[${file_description}]:file:_files -g '*.yml'" \
  375. '(-p --project-name)'{-p,--project-name}'[Specify an alternate project name (default: directory name)]:project name:' \
  376. '--verbose[Show more output]' \
  377. '(- :)'{-v,--version}'[Print version and exit]' \
  378. '(-H --host)'{-H,--host}'[Daemon socket to connect to]:host:' \
  379. '--tls[Use TLS; implied by --tlsverify]' \
  380. '--tlscacert=[Trust certs signed only by this CA]:ca path:' \
  381. '--tlscert=[Path to TLS certificate file]:client cert path:' \
  382. '--tlskey=[Path to TLS key file]:tls key path:' \
  383. '--tlsverify[Use TLS and verify the remote]' \
  384. "--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)]" \
  385. '(-): :->command' \
  386. '(-)*:: :->option-or-argument' && ret=0
  387. local -a relevant_compose_flags relevant_docker_flags compose_options docker_options
  388. relevant_compose_flags=(
  389. "--file" "-f"
  390. "--host" "-H"
  391. "--project-name" "-p"
  392. "--tls"
  393. "--tlscacert"
  394. "--tlscert"
  395. "--tlskey"
  396. "--tlsverify"
  397. "--skip-hostname-check"
  398. )
  399. relevant_docker_flags=(
  400. "--host" "-H"
  401. "--tls"
  402. "--tlscacert"
  403. "--tlscert"
  404. "--tlskey"
  405. "--tlsverify"
  406. )
  407. for k in "${(@k)opt_args}"; do
  408. if [[ -n "${relevant_docker_flags[(r)$k]}" ]]; then
  409. docker_options+=$k
  410. if [[ -n "$opt_args[$k]" ]]; then
  411. docker_options+=$opt_args[$k]
  412. fi
  413. fi
  414. if [[ -n "${relevant_compose_flags[(r)$k]}" ]]; then
  415. compose_options+=$k
  416. if [[ -n "$opt_args[$k]" ]]; then
  417. compose_options+=$opt_args[$k]
  418. fi
  419. fi
  420. done
  421. case $state in
  422. (command)
  423. __docker-compose_commands && ret=0
  424. ;;
  425. (option-or-argument)
  426. curcontext=${curcontext%:*:*}:docker-compose-$words[1]:
  427. __docker-compose_subcommand && ret=0
  428. ;;
  429. esac
  430. return ret
  431. }
  432. _docker-compose "$@"