gitbatch-filecolorsoutput

BAT file text colors not working after Git failure


I have the following code in a BAT file that I run in a Windows 10 command prompt.

FOR /F %%a IN ('ECHO prompt $E ^| cmd') DO SET "ESC=%%a"

FOR /D %%f IN (%loc%) DO (
    PUSHD %%f
    IF EXIST %%f\.git (
        FOR /F "delims=" %%b IN ('git rev-parse --abbrev-ref HEAD') DO (
            FOR /F "delims=" %%s IN ('git status -sb -uno --ignore-submodules=all') DO (
                SET r=%%s
                FOR %%t IN ("%%s") DO (
                    IF "!r:behind=!" NEQ %%t (
                        ECHO %ESC%[33m%%f%ESC%[0m
                        @git pull origin %%b
                    ) ELSE (
                        ECHO %ESC%[36m%%f has no changes%ESC%[0m
                    )
                )
            )
        )
    )
    POPD
)

There is more code to set starting values, but this is the workhorse loop. Everything works fine as long as the '@git pull ...' command successfully pulls files. However, if it does not, as in the case shown, it stops displaying text with color and simply echoes the text with escape sequences. Here is an example (note the command prompt has white text on a black background without the color commands):

C:\Develop\Repo1 has no changes < this is blue text
C:\Develop\Repo2 has no changes < this is blue text
C:\Develop\Repo3 < this is yellow text, the following Git output is white text
From https://dev.azure.com/Home/_git/Repo3
 * branch            main       -> FETCH_HEAD
Updating 5a4f07a..4d923ef
error: Your local changes to the following files would be overwritten by merge:
        App.config
Please commit your changes or stash them before you merge.
Aborting
←[36mC:\Develop\Repo4 has no changes←[0m < This is white text, but should be blue without the escape sequences
←[36mC:\Develop\Repo5 has no changes←[0m < This is white text, but should be blue without the escape sequences

Also, note that if a subsequent Git repository is successful in pulling files, the text coloring starts working again. This leads me to believe there is something happening when the Git command 'aborts' that is affecting how the BAT file (or Command Prompt) treats the ESC character. Does anyone have any information or ideas about how to fix this?


Solution

  • For anyone who is having this problem, this is how I was able to resolve it. Still seems like a kluge though.

    ECHO %ESC%[33m%%f%ESC%[0m
    REM The file1/file2 stuff is here to allow the text coloring to work.
    REM Without this, the coloring stops working if Git can't successfully
    REM complete the pull. For some reason, it stop interpretting the ESC
    REM character properly.
    @git pull origin %%b > file1.txt 2> file2.txt
    type file1.txt
    type file2.txt
    del file1.txt
    del file2.txt