Category Archives: git

Crusader for trailing-whitespace-free code

For whatever reason I hate trailing whitespaces. It might be just my pet peeve (although unjustified conversions with the ‘as’ operator instead of using just regular cast in C# are the winner in this category) because ultimately it is not something that is very important but still, trailing whitespaces annoy me. Sadly, even though I hate trailing whitespaces I tend to introduce them. One of my colleagues, who would flag all of the occurrences of trailing whitespaces in my pull requests even suspected I introduced them intentionally to check if code was being reviewed carefully. I am not that treacherous though and the reason was actually more mundane than that. I just did not see them. I did turn on the “View White Space” option in VS (which btw. made me hate trailing spaces even more) and started seeing all the trailing whitespaces introduced by other people but not by myself. The truth is that if you set Visual Studio to use the dark theme it is often hard to see a single trailing whitespace even with the “View White Space” option turned on. You would think that fixing all the trailing whitespaces in a project would fix the problem but I don’t think it actually would. Firstly, typically you don’t want to touch code that is not relevant to your change. Secondly, even if you fixed it as a separate change (which is actually not that difficult with regular expressions) you will inadvertently introduce a trailing whitespace or two in your very next commit. If you want to be careful and are using git you can do git diff {--cached} and it will highlight trailing whitespaces like this:
git-diff
It’s not the best experience though. You need to leave your editor to see if you have any problems and if you do you need to “map” the diff to your code to find all the lines that need to be fixed. This was driving me crazy so I decided to do something about this. The idea was to show trailing whitespaces in a visible way directly in the editor as soon as you introduced them. This is actually quite easy to do for Visual Studio – you just create an extensibility project (note you have to have Visual Studio SDK installed) – New Project, Template -> Visual C# -> Extensibility and select “Editor Text Adorment – modify a few lines and you are done. It literally took me no more than 2 hours to hack together an extension that does it. It highlights all the trailing whitespaces and dynamically checks if you have any trailing whitespaces in front of your cursor when you type – if you do it will highlight them too. This is how your VS looks like if you have trailing whitespaces:
trailing-spaces-vs
I did use this extension for the past three days (extensive QA rules!) and shared it with my colleague (the one who would before always complain about me introducing trailing whitespaces). It worked and did not feel obtrusive (granted we do not have a lot of trailing whitespaces in the projects we work on but it turned out we do have more than we thought we had). Now, if you are a crusader for trailing-whitespace-free code, you can try it too. (Actually, you can try it even if you aren’t.) I posted this extension on the VS gallery. You can just download the .vsix and double click it to install, or you can install it directly from VS by going to Tools->Extensions and Updates, selecting “Online” on the left side, typing the name (or just “Flagger”) and clicking install.
trailing-spaces-install
If you have too many whitespaces or just think it does not work for you you can uninstall or disable the extension by going to Tools -> Extensions and Updates find the Trailing Space Flagger in the installed extensions and click the “Remove” or “Disable” button:
uninstall-flagger
As usual, the code is open source – you can find it on github.

Safe Git Clean with MSBuild

I like to clean my source tree once in a while. Unfortunately msbuild {whateverproject}.csproj /t:Clean often falls short – for more complicated solutions with multiple projects some temporary files generated during the build almost always are left on the disk. Removing these should not be a big deal given that the important files are under source control – I can simply remove everything that is not tracked. With git you do that with git clean -xfd command and the files are gone. Usually, this is the (sad) moment when I realize that there was that file you forgot to add to the index or this directory that was not supposed to be added to the index but had some “temporary” data I have been using for a couple of weeks now. To save myself a grief I came up with an MSBuild target that saves everything that is going to be deleted to a backup directory before the clean up. This way even if I missed something not everything is lost – I can go to the backup directory and restore the file.
The target itself turned out quite simple. The biggest problem was to make git commands work with MSBuild. It’s possible to run git commands with Exec task. However Exec task does not capture results of the command. The only way I found to capture the results was to redirect the command output to a file and then read the file contents to an ItemGroup with ReadLinesFromFile task. Not ideal for sure but seems to work.
Using the target is easy as the target takes only two optional parameters – BackupDir and DeleteBackupDir. BackupDir is the path to a directory where files that are not tracked should be saved. If the value is not provided files will be saved to a subfolder of the %TEMP% folder. DeleteBackupDir tells whether to delete the BackupDir if one exists – ‘false’ is the default value. An exemplary command would be:
MSBuild {projectfile} /t:SafeGitClean /p:BackupDir=C:\temp\backup /p:DeleteBackupDir=false
The target itself looks as follows:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

  <Target Name="SafeGitClean">
    <PropertyGroup>
      <BackupDir Condition="'$(BackupDir)' == ''" >$(Temp)\SafeGitClean$([System.Guid]::NewGuid())</BackupDir>
      <DeleteBackupDir Condition="'$(DeleteBackupDir)' == ''">false</DeleteBackupDir>
      <TempFile>$(Temp)\SafeGitClean_UntrackedFiles$([System.Guid]::NewGuid())</TempFile>
    </PropertyGroup>
    
    <Message Text="$(BackupDir)" />

    <RemoveDir 
      Condition="'$(DeleteBackupDir)' == 'true' And Exists('$(BackupDir)')" 
      Directories="$(BackupDir)" />
    
    <Exec Command="git ls-files --other &gt; $(TempFile)" /> 

    <ReadLinesFromFile File="$(TempFile)">
      <Output TaskParameter="Lines" ItemName="UntrackedFile" />
    </ReadLinesFromFile>
        
    <ItemGroup>
      <UntrackedFileFixed Include="@(UntrackedFile->Replace('/', '\'))" />
    </ItemGroup>
    
    <Delete Files="$(TempFile)" TreatErrorsAsWarnings="true" />
      
    <Copy 
      SourceFiles="@(UntrackedFileFixed)" 
      DestinationFiles="@(UntrackedFileFixed->'$(BackupDir)\%(Identity)')" 
      OverwriteReadOnlyFiles="true" />
      
    <Exec Command="git clean -xfd" />      
  </Target>

</Project>

You can also find it in my github repo: https://github.com/moozzyk/MSBuild-Tasks

Pawel Kadluczka