Last Updated: February 25, 2016
·
1.368K
· revgum

Build Event : Publishing application details

When troubleshooting a web application or web services, few things are more annoying than not knowing exactly what code is running on the server.

My goals are

  • Automatically gather details and copy them to the server while publishing

  • Provide a list of files published which weren't committed to the repository prior to publishing (it can happen..)

  • Give the front-end access to these details in an easily consumable fashion

  • Use the basic building blocks that are inherent in Git and Windows (I don't want to spend a whole lot of time implementing some framework or server that handles this for me, yet)

My solution is a batch file executed by a Build Event in Visual Studio which uses Git commands to collect information and generate a JSON formatted file which can be accessed by my app from the web server.

The Batch file (preBuild.bat in my project folder):

@echo off
set PROJECTDIR=%1app

REM Clean out old minified CSS and JS for the app and build artifacts
del %PROJECTDIR%\UI\static\css\app.min.css
del %PROJECTDIR%\UI\static\js\app.min.js
del %PROJECTDIR%\MSBuildOutput.txt

REM Print details of the Git branch, and any uncommitted files that were published.
setlocal EnableDelayedExpansion
set FILENAME=%PROJECTDIR%\UI\static\js\published_revision.js

set GIT="c:\Program Files (x86)\Git\bin\git.exe"
for /F %%n in ('%GIT% rev-parse --abbrev-ref HEAD') do set NAME=%%n
for /F %%h in ('%GIT% rev-parse HEAD') do set HASH=%%h
for /F "tokens=2-4 delims=/ " %%a in ('date /t') do (set DATE=%%c-%%a-%%b)
for /F "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set TIME=%%a%%b)
echo { > %FILENAME%
echo "published":"%DATE%_%TIME%", >> %FILENAME%
echo "branch":"%NAME%", >> %FILENAME%
echo "hash":"%HASH%", >> %FILENAME%
echo "uncommitted": [>> %FILENAME%
REM On the first line, don't print a comma in the array.. all subsequent lines have a comma prepended
set LINENO=0
for /F "tokens=*" %%l in ('%GIT% diff --name-only %HASH%') do (
    IF !LINENO! GTR 0 ( 
        echo ,"%%l" >> %FILENAME%
    ) ELSE (
        echo "%%l" >> %FILENAME%
    )
    set /a LINENO+=1
)
echo ]} >> %FILENAME%
exit 0

The Pre-Build Event:

$(SolutionDir)app\preBuild.bat $(SolutionDir)

An example of the JSON file:

{ 
    "published":"2013-03-15_1219", 
    "branch":"master", 
    "hash":"fe7bae4dfbe58lkdiefmxdf4df14f035a6bieur5", 
    "uncommitted": [
        "app/Global.asax.cs" 
    ] 
}