_docker-compose 19 KB

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