docker-run 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/env bash
  2. set -o errexit -o pipefail
  3. DIR=$(dirname "${0}")
  4. MAIN_DIR=$(readlink -f "${DIR}/..")
  5. if [ -L "${MAIN_DIR}/.git/config" ]; then
  6. # Support git-new-workdir
  7. GIT_DIR="$(dirname "$(realpath "${MAIN_DIR}/.git/config")")"
  8. else
  9. # Support git-worktree
  10. GIT_DIR="$(cd "${MAIN_DIR}" && git rev-parse --no-flags --git-common-dir)"
  11. fi
  12. # shellcheck disable=SC2016
  13. IMAGE=$(grep ^image: "${MAIN_DIR}/.gitlab-ci.yml" | \
  14. sed -e 's,^image: ,,g' | sed -e 's,\$CI_REGISTRY,registry.gitlab.com,g')
  15. declare -a docker_opts=(
  16. -i
  17. --rm
  18. --user "$(id -u):$(id -g)"
  19. --mount "type=bind,src=${MAIN_DIR},dst=${MAIN_DIR}"
  20. --workdir "${MAIN_DIR}"
  21. )
  22. # Empty GIT_DIR means that we are not in a workdir, *and* git is too old
  23. # to know about worktrees, so we're not in a worktree either. So it means
  24. # we're in the main git working copy, and thus we don't need to mount the
  25. # .git directory.
  26. if [ "${GIT_DIR}" ]; then
  27. # GIT_DIR in the main working copy (when git supports worktrees) will
  28. # be just '.git', but 'docker run' needs an absolute path. If it is
  29. # not absolute, GIT_DIR is relative to MAIN_DIR. If it's an absolute
  30. # path already (in a wordir), then that's a noop.
  31. GIT_DIR="$(cd "${MAIN_DIR}"; readlink -e "${GIT_DIR}")"
  32. docker_opts+=( --mount "type=bind,src=${GIT_DIR},dst=${GIT_DIR}" )
  33. fi
  34. if tty -s; then
  35. docker_opts+=( -t )
  36. fi
  37. exec docker run "${docker_opts[@]}" "${IMAGE}" "${@}"