Add git hash of project repository to source code as text

Hi,

I have a project in a git repository and I would like to get the git hash into the source so it can be queried later.

I can pass
-DGITVERSION=\"$(git describe --abbrev=6 --dirty --always --tags)\"
to mbed compile command but I would like to define the macro in one of the configuration files (mbed_app.json).
I added a macro definition in mbed_app.json like this

{
    "config": {
        "gitver": {
            "help": "Project git version",
            "value": "\"$(git describe --abbrev=6 --dirty --always --tags)\"",
            "macro_name": "GITVERSION"
        }

but the git describe command is not executed and just the text of the value field is asigned to GITVERSION.

Is there a way to achieve this?

Hello Fabián,

I’m afraid neither the online compiler nor the Mbed Studio support custom commands. Nor does the mbed-cli tool let you do it directly (run mbed compile -h to check for all available options). That’s why to run more commands in sequence (pre-build + build + post-build) I usually create a batch file. For example:

build_my_program.bat:

git describe --abbrev=6 --dirty --always --tags
mbed compile ...

Best regards, Zoltan

Thanks Zoltan.

I wanted to avoid the use of a script but for now there is no alternative.

Regards.

By using CLI 2 which is CMake based. You can add to the CMakeLists.txt in project directory the following (adapted from here) :

# git commit hash macro
execute_process(
  COMMAND git log -1 --format=%h
  WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
  OUTPUT_VARIABLE GIT_COMMIT_HASH
  OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_definitions("-DGIT_COMMIT_HASH=\"${GIT_COMMIT_HASH}\"")

Later use GIT_COMMIT_HASH in your code.