Skip to content

Instantly share code, notes, and snippets.

@disq

disq/Makefile

Last active Jun 2, 2020
Embed
What would you like to do?
Makefile for golang
#
# Generic Go project makefile
#
# Example:
# make PREFIX= DESTDIR=/tmp/project-name-build install
#
# PREFIX is mostly unused, it would be used to expose the installation path to installed files
# For now, running "make install" with PREFIX= is OK (as long as DESTDIR is set)
#
# For capistrano, it would be something like this:
#
# export DESTDIR=/tmp/project-name-build
# export REALPREFIX=/opt/go/project-name/production/releases/1478000000
# make PREFIX=$REALPREFIX build # Just build it
# make PREFIX= install # Install with PREFIX= so that we don't have /opt/go/... under $DESTDIR
# scp -R $DESTDIR/* user@host:$REALPREFIX/
#
SRCDIR ?= .
PREFIX ?= /usr/local
GOROOT ?= /usr/local/go
GITFLAGS ?= GIT_DIR=${SRCDIR}/.git GIT_WORK_TREE=${SRCDIR}
ifeq ($(NOGIT),1)
GitSummary ?= Unknown
GitBranch ?= Unknown
else
GitSummary := $(shell ${GITFLAGS} git describe --tags --dirty --always)
GitBranch := $(shell ${GITFLAGS} git symbolic-ref -q --short HEAD)
endif
# Determine commands by looking into cmd/*
COMMANDS=$(wildcard ${SRCDIR}/cmd/*)
# Determine binary names by stripping out the dir names
BINS=$(foreach cmd,${COMMANDS},$(notdir ${cmd}))
ifeq (${COMMANDS},)
$(error Could not determine COMMANDS, set SRCDIR or run in source dir)
endif
ifeq (${BINS},)
$(error Could not determine BINS, set SRCDIR or run in source dir)
endif
LDFLAGS += -X main.GitSummary=${GitSummary} -X main.GitBranch=${GitBranch}
all:
# Fmt first, build later
$(MAKE) -C ${SRCDIR} fmt
$(MAKE) -C ${SRCDIR} build
transform: ${SRCDIR}/cmd/transform/main.go ${SRCDIR}/*.go
${GOROOT}/bin/go build ${GCFLAGS} -ldflags "${LDFLAGS}" ./$(<D)
testcmd: ${SRCDIR}/cmd/testcmd/main.go ${SRCDIR}/*.go
${GOROOT}/bin/go build ${GCFLAGS} -ldflags "${LDFLAGS}" ./$(<D)
build:
# Run parallel builds in sub-make
$(MAKE) -C ${SRCDIR} ${BINS}
fmt:
find ${SRCDIR} ! -path "*/vendor/*" -type f -name '*.go' -exec ${GOROOT}/bin/gofmt -l -s -w {} \;
clean:
@$(foreach bin,${BINS},rm -vf ${SRCDIR}/${bin};)
installdirs:
mkdir -p ${DESTDIR}${PREFIX}/{bin,}
install: build installdirs
@$(foreach bin,${BINS},cp -vf ${SRCDIR}/${bin} ${DESTDIR}${PREFIX}/bin/;)
uninstall:
@$(foreach bin,${BINS},rm -vf ${DESTDIR}${PREFIX}/bin/${bin};)
.PHONY: all build fmt clean installdirs install uninstall
#.ONESHELL: # Not sure if we need it
# Delete default suffixes and define .go
.SUFFIXES:
.SUFFIXES: .go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment