user2569618
user2569618

Reputation: 687

In a Makefile, how can I fetch and assign a git commit hash to a variable?

A make all clones the git repo. I want to know what the commit hash is and assign the git commit hash to a variable which can be used later in the Makefile

e.g.

all: download
      echo '$(GIT_COMMIT)'

download:
      cd buildarea && git clone [email protected]:proj/project.git
      $(eval GIT_COMMIT = $(shell cd buildarea/project && git log -l --pretty=format:"%H"))
      echo '$(GIT_COMMIT)'

Upvotes: 11

Views: 14621

Answers (3)

Ruoding Tian
Ruoding Tian

Reputation: 81

This one also work if you trigger the make git_sha under subdirectory:

GIT_SHA_FETCH := $(shell git rev-parse HEAD | cut -c 1-8)
export GIT_SHA=$(GIT_SHA_FETCH)

git_sha:
    @echo GIT_SHA is $(GIT_SHA)

Upvotes: 0

Guildencrantz
Guildencrantz

Reputation: 1915

Because of the way that make evaluates the target the git clone executes after $(shell), so cd tries to move to a directory that doesn't exist yet. What you can do is simply perform the whole act in a single $(shell) call.

all: download
      echo '$(GIT_COMMIT)'

download:
      $(eval GIT_COMMIT = $(shell git clone [email protected]:proj/project.git buildarea/project && cd buildarea/project && git rev-parse HEAD))
      echo '$(GIT_COMMIT)'

Upvotes: 3

Eric
Eric

Reputation: 471

How about use shell function and 2 targets for it?

all: download getver

getver: VER=$(shell cd buildarea/project && git log -1 --pretty=format:"%H")
getver:
        @echo GIT_COMMIT=$(VER)

download:
        mkdir -p buildarea && cd buildarea && [email protected]:proj/project.git

Upvotes: 6

Related Questions