build.bzl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. def _go_command(ctx):
  2. output = ctx.attr.output
  3. if ctx.attr.os == "windows":
  4. output = output + ".exe"
  5. output_file = ctx.actions.declare_file(ctx.attr.os + "/" + ctx.attr.arch + "/" + ctx.attr.ver + "/" + output)
  6. pkg = ctx.attr.pkg
  7. ld_flags = "-s -w -buildid="
  8. if ctx.attr.ld:
  9. ld_flags = ld_flags + " " + ctx.attr.ld
  10. options = [
  11. "go",
  12. "build",
  13. "-trimpath",
  14. "-o", output_file.path,
  15. "-ldflags", "'%s'" % ld_flags,
  16. "-tags", "'%s'" % ctx.attr.gotags,
  17. pkg,
  18. ]
  19. command = " ".join(options)
  20. envs = [
  21. "CGO_ENABLED=0",
  22. "GOOS="+ctx.attr.os,
  23. "GOARCH="+ctx.attr.arch,
  24. "GO111MODULE=on",
  25. "GOCACHE=${TMPDIR}/gocache"
  26. ]
  27. if ctx.attr.mips: # https://github.com/golang/go/issues/27260
  28. envs+=["GOMIPS="+ctx.attr.mips]
  29. envs+=["GOMIPS64="+ctx.attr.mips]
  30. envs+=["GOMIPSLE="+ctx.attr.mips]
  31. envs+=["GOMIPS64LE="+ctx.attr.mips]
  32. if ctx.attr.arm:
  33. envs+=["GOARM="+ctx.attr.arm]
  34. switchToPwd="cd ${SPWD} && "
  35. command = switchToPwd + " ".join(envs) + " " + command
  36. ctx.actions.run_shell(
  37. outputs = [output_file],
  38. command = command,
  39. use_default_shell_env = True,
  40. )
  41. runfiles = ctx.runfiles(files = [output_file])
  42. return [DefaultInfo(executable = output_file, runfiles = runfiles)]
  43. foreign_go_binary = rule(
  44. _go_command,
  45. attrs = {
  46. 'pkg': attr.string(),
  47. 'output': attr.string(),
  48. 'os': attr.string(mandatory=True),
  49. 'arch': attr.string(mandatory=True),
  50. 'ver': attr.string(mandatory=True),
  51. 'mips': attr.string(),
  52. 'arm': attr.string(),
  53. 'ld': attr.string(),
  54. 'gotags': attr.string(),
  55. },
  56. executable = True,
  57. )