docker-run 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. --workdir "${MAIN_DIR}"
  20. )
  21. declare -a mountpoints=( "${MAIN_DIR}" )
  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. mountpoints+=( "${GIT_DIR}" )
  33. # 'repo' stores .git/objects separately.
  34. if [ -L "${GIT_DIR}/objects" ]; then
  35. # GITDIR is already an absolute path, but for symetry
  36. # with the above, keep the same cd+readlink construct.
  37. OBJECTS_DIR="$(cd "${MAIN_DIR}"; readlink -e "${GIT_DIR}/objects")"
  38. mountpoints+=( "${OBJECTS_DIR}" )
  39. fi
  40. fi
  41. if [ "${BR2_DL_DIR}" ]; then
  42. mountpoints+=( "${BR2_DL_DIR}" )
  43. docker_opts+=( --env BR2_DL_DIR )
  44. fi
  45. # shellcheck disable=SC2013 # can't use while-read because of the assignment
  46. for dir in $(printf '%s\n' "${mountpoints[@]}" |LC_ALL=C sort -u); do
  47. docker_opts+=( --mount "type=bind,src=${dir},dst=${dir}" )
  48. done
  49. if tty -s; then
  50. docker_opts+=( -t )
  51. fi
  52. exec docker run "${docker_opts[@]}" "${IMAGE}" "${@}"