Friday, January 17, 2014

Using rake with Visual Studio 2010 or using rake tasks with parameters

I like ruby and I like rake to build my stuff.
Since most of the time I am coding C# with Visual Studio I wanted to use rake from within Visual Studio. You can add external tools to Visual Studio (Tools\External Tools …) but it is not possible to call rake directly with this feature.
So I wrote a small batch file which starts rake:

call rake –f C:\Tools\scripts\myrakefile.rb build[%1]

I added this batch file as External tool with the full path to the Project File that is currently selected in the Explorer View as an argument (dont't forget to check "Use Output window"):

How does this work?

The batch file calls rake and executes the build task in the rakefile. This task expects the project file it should build as parameter.
Here is the content of the rakefile:

msbuild = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe"
desc "Build .proj with MSBuild"
task :build, :project do |t, args| 
 # get the projectfile path from the arguments
 projectFile = args[:project]
 puts "Building #{projectFile}"
 output = `#{msbuild} #{projectFile} /t:rebuild /p:Configuration=DevEnvDebug`
 puts output  
 if output.include?("Build FAILED.")
  puts " "
  puts "***** There are Build errors! *****"
  fail
 end
end

So far you can select a project file in the solution explorer and the Select the new entry in the Tools menu “Build with rake” and you will see the output from the rake script in the output window. That is not very convenient.
So let’s assign a keyboard shortcut to our external tool:

Open “Tools\Options…” and select “Environment\Keyboard”. Type “Tools.External” in the “Show commands containing:” Now you see a bunch of entries like “Tools.ExternalCommand1”, “Tools.ExternalCommand2” and so on. Since in my case the batch file I added earlier as external tool is on the eighth position, I choose “Tools.ExternalCommand8” in the list. Now you can assign a shortcut for this command. I choose Alt + B, Alt + R. Don’t forget to press the Assign button.

Now you can simply select a Project in the Solution Explorer and press Alt + B, Alt + R and you can see the rake output in the output window.
If you want to call other rake tasks from within the build task which also expect some parameters just call it like this:

#assume there is a task called othertask which takes a parameter

Rake::Task["othertask"].invoke(parameter)

No comments:

Post a Comment