user2532296
user2532296

Reputation: 848

Unable to print git commit hash (using git --pretty) when runing inside a Makefile

I am trying to get the version (first 7 characters of the commit hash) of a file using the "git --pretty" format inside a Makefile.

Below is my Makefile

#CUR_LOC_VERSION:= $(shell git log --pretty=format:%H -n1 -- | grep -o '^.\{7\}') # works
CUR_LOC_VERSION:= $(shell git log --pretty=format:%H -n1 -- ../inter/local.py | grep -o '^.\{7\}') # doesn't work, returns empty string
$(info $$CUR_LOC_VERSION is [${CUR_LOC_VERSION}])

I am expecting it to show a commit hash but it returns empty string.

$CUR_LOC_VERSION is []

But the above command runs fine when running directly inside the shell (instead of calling through a Makefile.).

Any pointers highly appreciated.

Directory structure.

.
|-- inter
|   |-- local.py
|
`-- vhdl
    |-- Makefile

Upvotes: 0

Views: 352

Answers (1)

MadScientist
MadScientist

Reputation: 100876

I can't explain why your current version doesn't work. But note, if you want to get a specific size of the abbreviated hash you can do that directly without needing to use grep. Just run:

git log -n1 --format=%h --abbrev=7

The %h format option shows an abbreviated hash, and the --abbrev says how many characters to use.

Based on more investigation above, my suspicion is that your working directory when you run this is not what you think it is. If I run git log -n1 -- nosuchfile (using a non-existent file) I don't get any error message, like I'd expect; I just get no output. That's kind of confusing, but it leads me to believe that ../inter/local.py doesn't exist when you run this git command. Try adding pwd to your shell command so it prints out the working directory before running git:

CUR_LOC_VERSION:= $(shell pwd; git log --format=%h -n1 -- ../inter/local.py)

and see what the output is.

Upvotes: 3

Related Questions