Last active
February 24, 2016 17:51
-
-
Save dakotahawkins/713c2d9d58783db98265 to your computer and use it in GitHub Desktop.
Build-log HEAD's commit ID in Windows without access to Git: Behold, the rare and terrible native batch!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@ECHO OFF | |
SETLOCAL ENABLEDELAYEDEXPANSION | |
ECHO. | |
ECHO ================================================================================ | |
REM Walk up looking for the "root" directory, containing .git | |
SET ROOTDIR=%~dp0 | |
:GetRootDir | |
FOR /F "delims=" %%I IN ("!ROOTDIR!") DO SET ROOTDIR=%%~dpI | |
FOR /F "delims=" %%I IN ("!ROOTDIR!") DO IF "%%~pI" EQU "\" GOTO :GotRootDir | |
IF EXIST !ROOTDIR!.git GOTO :GotRootDir | |
SET ROOTDIR=!ROOTDIR!..\ | |
GOTO :GetRootDir | |
:GotRootDir | |
IF NOT EXIST !ROOTDIR!NUL GOTO Error | |
SET OUTFILE=!ROOTDIR!BuildFiles\BuildCommitID.txt | |
REM Spit out the build's commit ID | |
IF EXIST !OUTFILE! DEL "!OUTFILE!" | |
IF "%BUILD_VCS_NUMBER%" neq "" ( | |
ECHO %BUILD_VCS_NUMBER%> "!OUTFILE!" | |
) ELSE ( | |
SET GIT_DIR= | |
IF EXIST !ROOTDIR!.git\NUL ( | |
REM Found .git dir | |
SET GIT_DIR=!ROOTDIR!.git\ | |
) ELSE ( | |
IF EXIST !ROOTDIR!.git ( | |
REM Found .git file, like for a worktree or something | |
FOR /F "usebackq tokens=2*" %%I IN ("!ROOTDIR!.git") DO ( | |
IF "!GIT_DIR!"=="" ( | |
SET GIT_DIR=%%I\ | |
SET GIT_DIR=!GIT_DIR:/=\! | |
) | |
) | |
) | |
) | |
IF "!GIT_DIR!" neq "" ( | |
IF EXIST !GIT_DIR!NUL ( | |
REM Read head ref from git dir's HEAD file | |
SET HEAD_REF_FILE= | |
FOR /F "usebackq tokens=2*" %%I IN ("!GIT_DIR!HEAD") DO ( | |
IF "!HEAD_REF_FILE!"=="" ( | |
SET HEAD_REF_FILE=%%I | |
SET HEAD_REF_FILE=!HEAD_REF_FILE:/=\! | |
) | |
) | |
IF EXIST !GIT_DIR!commondir ( | |
REM git dir was probably pointing to a worktree subdirectory, fix it to point to the | |
REM real deal. | |
SET REAL_GIT_DIR= | |
FOR /F "usebackq delims=" %%I IN ("!GIT_DIR!commondir") DO ( | |
IF "!REAL_GIT_DIR!"=="" ( | |
SET REAL_GIT_DIR=!GIT_DIR!%%I\ | |
SET REAL_GIT_DIR=!REAL_GIT_DIR:/=\! | |
) | |
) | |
SET GIT_DIR=!REAL_GIT_DIR! | |
) | |
REM Obtain HEAD's commit ID from the head ref file we found earlier | |
IF EXIST !GIT_DIR!!HEAD_REF_FILE! ( | |
TYPE "!GIT_DIR!!HEAD_REF_FILE!"> "!OUTFILE!" | |
) | |
) | |
) | |
) | |
IF EXIST !OUTFILE! ( | |
ECHO Build commit ID written to "!OUTFILE!": | |
TYPE "!OUTFILE!" | |
) ELSE ( | |
GOTO Error | |
) | |
ECHO ================================================================================ | |
ECHO. | |
EXIT /B 0 | |
:Error | |
ECHO Unable to identify build commit ID. | |
ECHO ================================================================================ | |
ECHO. | |
EXIT /B 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment