docker-run 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if test -z "${IMAGE}" ; then
  13. # shellcheck disable=SC2016
  14. IMAGE=$(grep ^image: "${MAIN_DIR}/.gitlab-ci.yml" | \
  15. sed -e 's,^image: ,,g' | sed -e 's,\$CI_REGISTRY,registry.gitlab.com,g')
  16. fi
  17. declare -a docker_opts=(
  18. -i
  19. --rm
  20. --user "$(id -u):$(id -g)"
  21. --workdir "$(pwd)"
  22. --security-opt label=disable
  23. --network host
  24. )
  25. declare -a mountpoints=(
  26. "${MAIN_DIR}"
  27. "$(pwd)"
  28. )
  29. # Empty GIT_DIR means that we are not in a workdir, *and* git is too old
  30. # to know about worktrees, so we're not in a worktree either. So it means
  31. # we're in the main git working copy, and thus we don't need to mount the
  32. # .git directory.
  33. if [ "${GIT_DIR}" ]; then
  34. # GIT_DIR in the main working copy (when git supports worktrees) will
  35. # be just '.git', but 'docker run' needs an absolute path. If it is
  36. # not absolute, GIT_DIR is relative to MAIN_DIR. If it's an absolute
  37. # path already (in a wordir), then that's a noop.
  38. GIT_DIR="$(cd "${MAIN_DIR}"; readlink -e "${GIT_DIR}")"
  39. mountpoints+=( "${GIT_DIR}" )
  40. # 'repo' stores .git/objects separately.
  41. if [ -L "${GIT_DIR}/objects" ]; then
  42. # GITDIR is already an absolute path, but for symetry
  43. # with the above, keep the same cd+readlink construct.
  44. OBJECTS_DIR="$(cd "${MAIN_DIR}"; readlink -e "${GIT_DIR}/objects")"
  45. mountpoints+=( "${OBJECTS_DIR}" )
  46. fi
  47. fi
  48. if [ "${BR2_DL_DIR}" ]; then
  49. mountpoints+=( "${BR2_DL_DIR}" )
  50. docker_opts+=( --env BR2_DL_DIR )
  51. fi
  52. # shellcheck disable=SC2013 # can't use while-read because of the assignment
  53. for dir in $(printf '%s\n' "${mountpoints[@]}" |LC_ALL=C sort -u); do
  54. docker_opts+=( --mount "type=bind,src=${dir},dst=${dir}" )
  55. done
  56. if tty -s; then
  57. docker_opts+=( -t )
  58. fi
  59. exec docker run "${docker_opts[@]}" "${IMAGE}" "${@}"