Delete a git branch local and remote

This is a continuation of my earlier post about pruning deleted branches

To delete a local branch 

git branch -d <branch_name>

or you can ‘force’ a delete if you have uncommitted changes
The -D is the same as --delete --force

git branch -D <branch_name>

To delete the branch remotely, simply do …

git push --delete <remote_name> <branch_name>

You can also do it like that if you prefer.

git push <remote_name> --delete <branch_name>

Again, you can use -d.

If you want to delete a remote and local branch, it is easier to first delete the remote branch and then the local branch.

You can then go ahead and prune all the branches.

git fetch --all --prune

How to delete/prune old local git branches

When you delete a branch with git, and push those changes, you might see that your local repo still has that branch in the list


git fetch -p && git branch -vv | awk '/: gone]/{print $1}' | xargs git branch -d

What this basically does is fetch all the branches and all the ones with a ‘gone’ attribute, (meaning deleted remotely), then we will remove them.

You can view the branches and what their attribute is yourself by typing

git branch -vv

Of course, you need to prune the branches on the remote git server

git remote prune origin

To make sure all is good, just re-list your branches, (local and remote)

git branch --vv -a

How to unit test a config file, (ConfigurationSection)

To unit test a ConfigurationSection in c# you need to do a couple of thing in your unit test
Of course, we do not want to change anything in the assembly being tested.

  • Create your own ConfigurationSection class
  • ‘Fake’ your own configuration file.
  • Test that you have the expected behaviour
    • For required values
    • Optional values

In your test application, create your own configuration loader class
It uses your configuration section as a template.

  internal class Loader where T : ConfigurationSection
  {
    // The filename that will contain the test contents.
    private string _fileName;
 
    // the instance we are testing
    public T Instance { get; }
 
    // the section we want to 'test' as well as the complete fake content
    public Loader(string section, string content)
    {
      File.WriteAllText(FileName, content);
      if (File.Exists(FileName))
      {
        var fileMap = new ExeConfigurationFileMap
        {
          ExeConfigFilename = FileName
        };
        var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None, true);
        Instance = config.GetSection(section) as T;
      }
    }

Of course we also need to clean up things a little.
The file we created needs to be removed, you could also have this in your test teardown.

    ~Loader()
    {
      if (_fileName != null)
      {
        try
        {
          File.Delete(_fileName);
        }
        catch
        {
          // it will get deleted at some other point.
          // as it is a temp file the OS will/should remove ut
        }
        _fileName = null;
      }
    }

Creating the fake test file.

    private string FileName
    {
      get
      {
        if (_fileName != null)
        {
          return _fileName;
        }
        _fileName = Path.GetTempPath() + Guid.NewGuid() + ".config";
        return _fileName;
      }
    }
  }

Now testing the config is fairly straight forward, (using NUnit in this case)

(using the sample config content, my parser does not escape it properl)

<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
<configSections>
<section name=""blah"" type=""BlahConfiguration,MyApp.Blah"" />
</configSections>
<blah>
</blah>
</configuration>

    // in this example BlahConfiguration allows no values 
    public void SectionCanBeEmpty()
    {
      // sample configuration file.
      const string content =  // see content above;
 
      Loader<BlahConfiguration> cl = null;
      Assert.DoesNotThrow( () => cl = new ConfigLoader<BlahConfiguration>("blah", content));
      Assert.That( cl.Instance.Strings.Count == 0 );
    }

So now you can create your tests and just pass the values you want to test, default values for example, that values are loaded properly and so on.

Migrating from MSTest to NUnit

I am using VS2015 and VS2017 and I needed to migrate from Microsoft Unit tests to NUnit.

Those are the steps are followed.

  • In VS2015/2017 Select the “Package manager console” tab
    Select the correct project, (drop down combo), and type
 install-package nunit
  • Or using Nuget manager
    • Select the correct project.
    • Select NUnit, (just the plain ‘NUnit’ for now).
  • In your test project, look for “using Microsoft.VisualStudio.TestTools.UnitTesting;
    Replace with “using NUnit.Framework;“, (of course you will now have a whole bunch of errors.)
  • Look and replace
    • [TestClass] replace with [TestFixture]
    • [TestMethod] replace with [Test]
    • Remove code that looks like “[ExpectedException(typeof(xyz), “some text”)]” and surround the actual code that is expected to throw
Assert.Throws<xyz>(() => { BadCode(); });

NB: Note you might need to change a couple of other values

  • [TestInitialize] to [SetUp]
  • [TestCleanup] to [TearDown]
  • [TestClassInitialize] to [TestFixtureSetUp]
  • [TestClassCleanup] to [TestFixtureTearDown]

And a few other functions will need to change as well but for the most part they start with Assert.... and are fairly close(tm) to the Microsoft counterparts.

 

Deleting folders that refuse to be deleted…

Sometimes when you want to delete a folder in windows you get a very useful message “Could not find this item… this is no longer located in …”, (yes, the very item you just tried to delete).

So after a bit of cursing, making sure that you are indeed the admin of this box, praying to the windows gods you realise that maybe Windows Explorer is at fault.

Not to worry you think, you open up a cmd line console and navigate to the parent of the offending folder.

And like a true hacker you type

“rd c:\my\bad\folder”

only to be told once again, “The system cannot find the file specified.”

At this point your realise that the folder has spaces… so you think “no problem, I will quote the folder” and you now type

‘rd “c:\my\bad\folder “‘

with the correct number of spaces in the folder name.

Long story short… you cannot do that.

You cannot rename the folder, (I know you will try anyway, but you can’t)

So you Googled for a solution and here you are…

what you need to do is tell the command line to not trim the folder name and to do that, you have to add “\?\” in front, so now you type

‘rd /s /q “\\?\c:\my\bad\folder “‘

Complete with the extra spaces and so on… (I added the /s and /q flags because you forgot that the directory is not empty)

Debug Google test with Eclipse

You can add the google test library to Eclipse so you can compile the code, but you might want to actually build the whole thing at once without having to link libraries and whatever.

Of course this is possible as the full code is given to you…

  • Go to the Google Test Github project and download the latest release.
  • Unpack it whereever you want, and, of course make note of the project.
    We will call that folder <gfolder>
  • You then need to include the Google test file path, in eclipse,
    • The root of Google folder, “C/C++ build > Settings > Includes > Add include path” for <gfolder>
    • The include folder, “C/C++ build > Settings > Includes > Add include path” for <gfolder>, where the source files are included.

Then in you main( … ){ … } where you would normally include #include “gtest/gtest.h” or #include <gtest/gtest.h> add “#include “src/gtest-all.cc””

#include “src/gtest-all.cc”
#include “gtest/gtest.h”

int main(int argc, char** argv)
{
printf(“Running main() from gtest_main.cc\n”);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

vs2015/2013 – Cannot see unit tests in Test Explorer window

If have some unitests in Visual Studio 2015 or 2013 but you cannot see them in your “Test Explorer window”

If you look in your output window, (under “Show output from:” > “test)

An exception was thrown while initializing part “Microsoft.VisualStudio.TestWindow.UI.TestWindowToolWindowControl”.

The solution is just to delete the VS2013/VS2015 cache folder, located either in

%LOCALAPPDATA%\Microsoft\VisualStudio\12.0\ComponentModelCache

For VS2013, or

%LOCALAPPDATA%\Microsoft\VisualStudio\14.0\ComponentModelCache

For VS2015

Git and submodule

Sometimes things get a little out of sync in your submodule folder, your ‘root’ project sometimes report something like

\ In the git branch
[branch = +0 ~1 -0 !]>

Or even  something along the lines of

\ In the submodule folder
[(7cd98ce...)]>

Showing that you are no longer on the correct branch, (for the submodule).

One one way to clean it all up is to do.

\ In the submodule folder
git checkout master
git pull
git push origin HEAD:master
git checkout master

Assuming that you have no other changes to commit

\ In the root folder
git clean -fd
git pull
git submodule update --init --recursive
git submodule update

And that should clear everything

Powershell cheatsheet for C++/C#

This is just a small post to help my ageing memory remember where things are located.

  • Powershell C#
    Locate the dll, System.Management.Automation.dll, and add it to your project, (or add it via Nuget).

    • See this blog for a good introduction on creating a project, (works for vs2015).
  • Check what version is installed
    • According to the official site you need to check the registry
      HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1
      or
      HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3
      And check that the value Install is set to ‘1’.
  • Debuging
    • The external program is C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    • But the actual location is:
      • Powershell 1: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine\{ApplicationBase}
      • Powershell 3:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine\{ApplicationBase}
    • Launching from debuger:
      • For a script:
        PowerShell -Command “& {.\myscript.ps1}” or
        PowerShell -File “.\myscript.ps1”
      • For a CmdLet/Module:
        -noexit -command “&{ import-module .\AMPowerShellCmdLets.dll -Verbose}”
  • Some links

Using Github from command line

This assumes that you have all the permissions needed to access your repo, (passwords and so on).

Start Git Shell and navigate to your local repo.

Create a branch

git checkout -b <branch-name>
git push <remote-name> <branch-name>

In the case of github the remote name is ‘origin’

Source

Add your changes to the branch

git add .

The ‘.’ means ‘everything’ that was changed.

You can use ‘status’ to check what needs to be staged, (or what has been staged).

git status

Commit branch

git commit -m "You message here"

Push branch
The first time you need to tell where you are pushing this to.

git push --set-upstream <remote-name> <branch-name>

The afterwards you just need to do…

git push

Delete your branch

To remotely delete it

git push <remote-name> --delete <branch-name>

To locally delete it


git branch --delete <branch-name>

Source