Batch file to add git branch into header file

前提是你 提交于 2020-08-06 05:20:11

问题


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:

  • Update the branch name inside the header file.

Any suggestion?

Thanks in advance for the help!

Best regards, Federico


回答1:


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
 )


来源:https://stackoverflow.com/questions/63036816/batch-file-to-add-git-branch-into-header-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!