rewrite docker-env to be more expandable; add more switches to docker-env; fix tags and cmd tab complete in docker-env

This commit is contained in:
Daniel_I_Am 2022-05-27 21:03:33 +02:00
parent 7e60676483
commit 169aa7961b

View File

@ -162,10 +162,8 @@ function see() {
}
function docker-env() {
port=
workdir=/work_dir
volumes=("$(pwd):/work_dir")
envvars=()
run_command_switches=()
workdir="/work_dir"
while
do
@ -174,16 +172,9 @@ function docker-env() {
shift
break
;;
-p)
port="$2"
shift
;;
-e)
envvars+=("$2")
shift
;;
-v)
volumes+=("$2")
-[pevhmu])
run_command_switches+=("$1")
run_command_switches+=("$2")
shift
;;
-w)
@ -212,6 +203,9 @@ Options:
-e VAR=value Add environment variable VAR with value
-v <volume> Bind mount a volume
-w workdir Set working directory (default=/work_dir)
-h hostname Container host name
-m limit Memory limit
-u user Username or UID (format: <name|uid>[:<group|gid>])
EOS
return 1
fi
@ -224,20 +218,9 @@ EOS
index=$(docker ps -a --filter "name=docker-env-$image_repository-*" --format '{% raw %}{{.Names}}{% endraw %}' | perl -e 'my $max = 0; while (<>) {my ($n) = $_ =~ /(\d+)$/; if ($n > $max) { $max = $n };}; print $max+1;')
name="docker-env-$image_repository-$index"
run_command="docker run --rm -it --name \"$name\""
run_command="docker run --rm -it --name \"$name\" -v $(pwd):/work_dir "
if [ ! -z "$port" ]
then
run_command+=" -p \"$port\""
fi
for volume in $volumes
do
run_command+=" -v \"$volume\""
done
for envvar in $envvars
do
run_command+=" -e \"$envvar\""
done
run_command+="${run_command_switches[*]}"
run_command+=" -w \"$workdir\" \"$image\" $cmd"
@ -251,9 +234,12 @@ function _docker-env() {
_arguments \
"*-p[Publish a containers port(s) to the host]:port:" \
"*-e[Set environment variables]:env:" \
"*-v[Bind mount a volume]:volume:" \
"*-e[Set environment variables]:" \
"*-v[Bind mount a volume]:" \
"-w[Working directory inside the container]" \
"-h[Container host name]" \
"-m[Memory limit]" \
"-u[Username or UID (format: (<name|uid>|(<name|uid>:<group|gid>)))]" \
"(-p -e -v -w)--[Explicitely stop switches and start positional arguments]" \
"(-p -e -v -w --)1:Container image:->image" \
"*:Container CMD:->cmd"
@ -264,7 +250,7 @@ function _docker-env() {
# if so strip everything up to that colon from further completion matching
if compset -P -1 '*:'; then
# Get the tags for the current image and use those for completion
local tags=$(docker image ls --filter 'dangling=false' --filter 'reference='"${words[-1]}"'*' --format '{% raw %}{{.Tag}}{% endraw %}' | sed 's/:/\\:/g' | uniq)
local tags=($(docker image ls --filter 'dangling=false' --filter 'reference='"${words[-1]}"'*' --format '{% raw %}{{.Tag}}{% endraw %}' | sed 's/:/\\:/g' | uniq))
# Add tags for autocompletion. If none exist, then show latest
if [ {% raw %}${#tags}{% endraw %} -gt 0 ]; then
@ -278,7 +264,7 @@ function _docker-env() {
fi
;;
cmd)
_default
_command_names
;;
esac
}