build.sh 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env bash
  2. set -e
  3. # Environment variable options:
  4. # - PLATFORMS: Platforms to build for (e.g. "windows/amd64,linux/amd64,darwin/amd64")
  5. export CLI_VERSION=$(git describe --tags 2>/dev/null || git rev-parse --short HEAD)
  6. export LC_ALL=C
  7. export LC_DATE=C
  8. make_ldflags() {
  9. local ldflags="-s -w -X 'github.com/yomorun/yomo/cli.Version=$CLI_VERSION'"
  10. echo "$ldflags"
  11. }
  12. build_for_platform() {
  13. local platform="$1"
  14. local ldflags="$2"
  15. local GOOS="${platform%/*}"
  16. local GOARCH="${platform#*/}"
  17. if [[ -z "$GOOS" || -z "$GOARCH" ]]; then
  18. echo "Invalid platform $platform" >&2
  19. return 1
  20. fi
  21. echo "Building $GOOS/$GOARCH"
  22. local output="yomo"
  23. if [[ "$GOOS" = "windows" ]]; then
  24. output="$output.exe"
  25. fi
  26. # compress to .tar.gz file
  27. local binfile="build/yomo-$GOARCH-$GOOS.tar.gz"
  28. local exit_val=0
  29. CGO_ENABLED=0 GOOS=$GOOS GOARCH=$GOARCH go build -o "build/$output" -ldflags "$ldflags" -trimpath ./cmd/yomo/main.go || exit_val=$?
  30. # compress compiled binary to .tar.gz
  31. # zip -r -j "$binfile" "$output"
  32. tar -C build -czvf "$binfile" "$output"
  33. rm -rf $output
  34. if [[ "$exit_val" -ne 0 ]]; then
  35. echo "Error: failed to build $GOOS/$GOARCH" >&2
  36. return $exit_val
  37. fi
  38. }
  39. if [ -z "$PLATFORMS" ]; then
  40. PLATFORMS="$(go env GOOS)/$(go env GOARCH)"
  41. fi
  42. platforms=(${PLATFORMS//,/ })
  43. ldflags="$(make_ldflags)"
  44. mkdir -p build
  45. rm -rf build/*
  46. echo "Starting build..."
  47. for platform in "${platforms[@]}"; do
  48. build_for_platform "$platform" "$ldflags"
  49. done
  50. echo "Build complete."
  51. ls -lh build/ | awk '{print $9, $5}'