thockin / go-build-template

A Makefile/Dockerfile example for Go projects.
Apache License 2.0
3.24k stars 430 forks source link

Nested cmd directories support #93

Open alok87 opened 11 months ago

alok87 commented 11 months ago
cmd/acquiring/server
       /acquiring/migrate

Fails with:

$ BINS=acquiring/api make build

# building for darwin/arm64
binary: bin/darwin_arm64/acquiring/server  mv: rename .go/bin/darwin_arm64/acquiring/server to bin/darwin_arm64/acquiring/server: No such file or directory
make: *** [.go/bin/darwin_arm64/acquiring/server.stamp] Error 1
alok87 commented 6 months ago

@thockin what is required to be done to support nested folders

cmd/folder1/folder2/main.go
cmd/folder1/main.go

BINS=cmd/folder1 make build BINS=cmd/folder1/folder make build

alok87 commented 6 months ago
# This is the target definition for all stampfiles.
# This will build the binary under ./.go and update the real binary iff needed.
STAMPS = $(foreach outbin,$(OUTBINS),.go/$(outbin).stamp)
.PHONY: $(STAMPS)
$(STAMPS): go-build
    echo -ne "binary: $(OUTBIN)  "
    if ! cmp -s .go/$(OUTBIN) $(OUTBIN); then  \
        mv .go/$(OUTBIN) $(OUTBIN);            \
        date >$@;                              \
        echo;                                  \
    else                                       \
        echo "(cached)";                       \
    fi

This part is failing when BIN has a nested path BINS=acquiring/server

alok87 commented 6 months ago

Ok got it the issue is Makefile is expecting the binary to be created at bin/darwin_arm64/acquiring/server but build.sh does not generate like that!

alok87 commented 6 months ago

We need to use GOBIN in the build.sh as it is building in a flat out way and not following the same structure of cmd/acquring/server

alok87 commented 6 months ago

This can start throwing binaries at the required folder which Makefile expects, but need more polishing and also go install part in the end needs a fix.

./build.sh needs a fix with below:

# Iterate through all Go packages under github.com/XXX/XXX/cmd
for pkg in $(go list github.com/XXX/XXX/cmd/...); do
    relative_path=$(echo "${pkg}" | sed 's|^github.com/razorpay/upi-switch/||')
    if [ -f "${relative_path}/main.go" ]; then

        # Identify main packages and create binaries
        binary_name=$(basename "${relative_path}")
        binary_path=$(echo "${relative_path}" | sed 's|^cmd/||')

        echo "relative_path: ${relative_path}" 
        echo "binary_name: ${binary_name}"
        echo "binary_path: ${binary_path}"

        # Construct binary_install_path
        binary_install_path="${GOPATH}/bin/${binary_path}"

        # Ensure the directory structure exists
        mkdir -p "${binary_install_path}"

        echo "go install -o ${binary_install_path}/${binary_name} -ldflags '-X ${pkg}/pkg/version.Version=${VERSION}' ${relative_path}"
        echo "--"
    fi
done
thockin commented 6 months ago

Note that GOBIN is hostile to cross-compiles.