Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

How do I save the git-diff from a makefile

I have a project that I compile using a makefile. I want to save the output of git diff into the executable when it is compiled. Simply assigning the output of git diff to a variable in the makefile, and then passing to the compiler e.g.

GIT_DIFF := $(shell git diff)

CXXFLAGS += -D$(GIT_DIFF)

fails because the parts of the string gets evaluated, for example newlines split the compile command into several non-sensical commands.

What is the best way to pass in the output of git diff at compile-time into a string I can use in C++ code?

question from:https://stackoverflow.com/questions/65911886/how-do-i-save-the-git-diff-from-a-makefile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a way to do this. Not too sure how robust or portable it is though. This solution assumes the shell is bash. In the makefile I have

GIT_DIFF := $(shell printf '%q
' "$$(git diff | awk '{ gsub(""","\"",$$$$1) ; print $$$$1 }' ORS='\n')" )

CXXFLAGS += -DGIT_DIFF="$(GIT_DIFF)"

and then in a header file I have

// Convert macro to a string constant
#define STRINGIFY1(x) #x
#define STRINGIFY(x) STRINGIFY1(x)

constexpr auto git_diff = STRINGIFY(GIT_DIFF)

(this is a C++11 project).

Unpacking that command a bit:

The string that's passed to the C++ code is full of escape sequences, so is not very readable. It can be converted back to something more readable by reversing the awk substition and using echo -e to evaluate the escaped characters (for some reason this needs to be done twice). So if the string is saved into a text file, say mygitdiff, then

echo -e $(echo -e "$(cat mygitdiff | awk '{ gsub("\"", """,$$1) ; print $$1 }' IRS='\n')")

should make it something readable.

This method is awkward, and the string that's passed to the C++ isn't very readable, so if anyone has a better solution, or suggestions for improvements, that would be very welcome!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...