Skip to content

Instantly share code, notes, and snippets.

@sharplet
Created April 19, 2021 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/39a2b83592ff22a7f50a1a140792d2b6 to your computer and use it in GitHub Desktop.
Save sharplet/39a2b83592ff22a7f50a1a140792d2b6 to your computer and use it in GitHub Desktop.
Use bin/run to run Swift commands found in a project's bin/ directory
#!/bin/sh
#
# bin/run: Run Swift commands in a project's bin/ directory.
#
# Drop-in replacement for `swift run`.
# Adds caching of built products based on source file contents.
#
# Usage:
# bin/run <command [options]> # Run named command defined in `bin/Package.swift`
#
# bin/run --build # Build out of date products
# bin/run --clean # Clean built products
# bin/run --resolve # Resolve package dependencies
# bin/run --update # Update package dependencies
# bin/run --shasum # Compute the cache key based on current source file contents
set -e
if [ -z ${SWIFTPM_CACHE_KEY_PATH+x} ]; then
export SWIFTPM_CACHE_KEY_PATH=bin/.build/contents.sha
fi
cache_key() {
(
cd bin
cat Package.resolved src/**/*.swift | shasum | cut -f1 -d' '
)
}
cache_valid() {
[ "$IGNORE_CACHE" != 1 ] \
&& [ -f "$SWIFTPM_CACHE_KEY_PATH" ] \
&& [ "$(cat "$SWIFTPM_CACHE_KEY_PATH")" = "$(cache_key)" ]
}
write_cache_key() {
if [ -n "$SWIFTPM_CACHE_KEY_PATH" ]; then
mkdir -p "$(dirname "$SWIFTPM_CACHE_KEY_PATH")"
cache_key > "$SWIFTPM_CACHE_KEY_PATH"
fi
}
swift() {
# subshell provides local variable scoping
(
swift_subcommand="$1"; shift
env SDKROOT=macosx swift "$swift_subcommand" --package-path bin "$@"
)
}
build_if_necessary() {
if ! cache_valid; then
swift build
write_cache_key
fi
}
if [ $# = 0 ]; then
echo >&2 "bin/run: Specify a subcommand to run."
exit 1
fi
case "$1" in
--build)
build_if_necessary
;;
--clean)
swift package clean
;;
--resolve)
swift package resolve
;;
--update)
shift
swift package update "$@"
;;
--shasum)
cache_key
;;
*)
build_if_necessary
swift run --skip-build "$@"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment