Skip to content

Instantly share code, notes, and snippets.

@j4zzcat
Last active January 19, 2020 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j4zzcat/16686664f655fa734a4b4558dd06fa29 to your computer and use it in GitHub Desktop.
Save j4zzcat/16686664f655fa734a4b4558dd06fa29 to your computer and use it in GitHub Desktop.
Dockerise a Ruby Gem
#!/usr/bin/env bash
GEM_NAME='pixie'
#
# Generic stuff
#
function fail {
local MESSAGE=${1}
local ERROR_CODE=${2}
local RC=${3}
[ -z "${MESSAGE}" ] && MESSAGE='No more details'
[ -z "${ERROR_CODE}" ] && ERROR_CODE='F00'
[ -z "${RC}" ] && RC=1
echo -e "[${GEM_NAME}:${ERROR_CODE}] ${MESSAGE}"
exit ${RC}
}
function fail_platform {
fail "Fuck off, platform '$(uname)' is not supported"
}
function stat {
local FILE=${1}
case $(uname) in
Darwin) /usr/bin/stat -f '%m' ${FILE} ;;
Linux) /usr/bin/stat --format '%Y' ${FILE} ;;
*) fail_platform ;;
esac
}
function epoch {
local TIME=${1}
local TZ=${2}
[ -z "${TZ}" ] && TZ='GMT'
case $(uname) in
Darwin) /bin/date -jf '%Y-%m-%dT%H:%M:%SZ%Z' ${TIME}Z${TZ} '+%s' ;;
Linux) /usr/bin/date '+%s' -d ${TIME}${TZ} ;;
*) fail_platform ;;
esac
}
function mktemp {
/usr/bin/mktemp "/tmp/${GEM_NAME}.XXXXX"
}
function docker_assert_supported_version {
local VERSION=$(docker --version | awk '{print $3}')
case ${VERSION} in
19*) ;; # ok
*) fail "Assertion failed. ${VERSION} is not supported" "F01" ;;
esac
}
function docker_assert_working {
local OUTPUT=$(mktemp)
docker images 1>${OUTPUT} 2>&1 \
|| fail "Assertion failed. Can't run 'docker' command\n$(cat ${OUTPUT})" "F02"
}
function docker_image_build_if_necessary {
local IMAGE=${1}
local FILE=${2}
local OUTPUT=$(mktemp)
docker inspect ${IMAGE} 1>${OUTPUT} 2>&1
if [ "${?}" != "0" ] ||
( local FILE_MOD_EPOCH=$(stat ${DOCKER_FILE})
local IMAGE_MOD_EPOCH=$(epoch $(cat ${OUTPUT} | awk '/\"LastTagTime\"/{print $2}' | awk -F. '{print $1}' | tr -d \") 'GMT')
return $(( !(${FILE_MOD_EPOCH} - ${IMAGE_MOD_EPOCH} > 0) ))); then
docker build --rm -f ${DOCKER_FILE} -t ${DOCKER_IMAGE} ${GEM_HOME}
fi
}
# Assumptions
case $(uname) in
Darwin) GEM_HOME=$(cd $(cd "$(dirname ${0})" ; pwd -P)/..; pwd -P) ;;
Linux) GEM_HOME=$(realpath $(dirname $(realpath ${0}))/..) ;;
*) fail_platform ;;
esac
GEM_VERSION=$(awk '/gem.version/{print $3}' ${GEM_HOME}/${GEM_NAME}.gemspec | tr -d \'\")
DOCKER_IMAGE="${GEM_NAME}:${GEM_VERSION}"
DOCKER_FILE="${GEM_HOME}/resource/runtime.dockerfile"
#
# Main
#
docker_assert_working
docker_assert_supported_version
docker_image_build_if_necessary ${DOCKER_IMAGE} ${DOCKER_FILE}
docker run -it --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /:/pixie/h:ro \
-v ${GEM_HOME}:/pixie/gem:ro \
-e RUBYOPT='-I /pixie/gem/lib' \
${DOCKER_IMAGE} \
ruby -e 'require "pixie"; Pixie::CommandLine.new.parse_and_run' -- ${@}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment