gitbatch-filepre-build-event

Batch file to add git branch into header file


I'm working on a C project, under git, and I would like to add the branch name into an header file.

This is my idea:

I have a version header file:

/* Define to prevent recursive inclusion -------------------------------------*/ 
#ifndef _VERSION_INTERFACE_H_
#define _VERSION_INTERFACE_H_
/* Includes ------------------------------------------------------------------*/
/* Exported defines ----------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
const char *gitBranch = "develop";
/* Exported macro ------------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/ 
#endif  /* _VERSION_INTERFACE_H_ */

and I would like to replace the string associated to gitBranch with the name of the current branch. In this way I can execute the batch file during the pre-build process and update the gitBranch variable.

I write a first version of a batch file:

@echo off
setlocal enabledelayedexpansion

SET GIT_CMD="C:\Program Files\Git\bin\git.exe"

rem Specify input file name
SET inputFileName=include\version_interface.h

rem String to find
SET stringToFind=const char *gitBranch

FOR /F "tokens=*" %%a in ( '"C:\Program Files\Git\bin\git.exe" branch --show-current' ) do SET branchName=%%a

rem String to replace
SET stringToReplace=%branchName%

for /F "tokens=*" %%n in (!infile!) do (
SET LINE=%%n
SET TMPR=!LINE:%stringToFind%=%stringToReplace%!
Echo !TMPR!>>tmp.txt
)

move tmp.txt %infile%
pause

but at the moment I cannot:

Any suggestion?

Thanks in advance for the help!

Best regards, Federico


Solution

  • Untested. Just make sure you add the correct file path to set infile=

    @echo off
    set "infile=C:\Path\to\FILE.h"
    for /f "tokens=*" %%a in ('"C:\Program Files\Git\bin\git.exe" branch --show-current' ) do set "branchName=%%a"
    for /f "delims=" %%i in ('type "%infile%" ^| find /v /n "" ^& break^>%infile%') do (
        setlocal enabledelayedexpansion
        set "line=%%i"
        set "line=!line:*]=!"
        if "!line:~0,21!" == "const char *gitBranch" set "line=const char *gitBranch ="%branchName%";"
        echo(!line!>>!infile!
        endlocal
     )