MSBuild Task and Command-Line Tool for Token Replacement

June 18, 2012

Overview

TokenReplacer is a MSBuild Task and command-line tool for token replacement in text files. It was originally developed to support developer-specific configurations but may be used in any other situations where token replacement is required.

Both the MSBuild Task and the command-line tool take 4 arguments as input:

  • Template File - Mandatory argument. Must be an existing file;
  • Output File - Mandatory argument. File may not exist: will be created if it doesn't, will be overwritten if it does;
  • Tokens File - Optional argument. If specified but the file does not exist it will be ignored;
  • Defaults File - Optional argument. If specified but the file does not exist it will be ignored;

The following illustration shows the most common argument combinations and the outcomes in each situation.

Token replacer logic

In a normal situation all supported tokens will be defined in the Defaults File; tokens that must be overridden for a particular scenario/developer will be in the Tokens File. When TokenReplacer is run, the Template File contents are copied into the Output File with token replacement occurring during the process.

Token format and token files

Tokens have the following format in the template file:

{{TokenName}}

Token files are XML files with the following structure:

<tokens>
  <token name="TokenName">Token value</token>
</tokens>

Internally, TokenReplacer uses the Nustache library (.NET implementation of Mustache) so it is advisable that you read the Mustache manual in case you are interested in a little more than simple 1:1 token replacement.

MSBuild Task usage

1. Map the task to the assembly that contains the task implementation using the UsingTask element:

<UsingTask
   AssemblyFile="..\..\Binaries\TokenReplacerTask.dll"
   TaskName="TrompeLeCode.TokenReplacer.TokenReplacerTask" />

2. Use the task:

<TrompeLeCode.TokenReplacer.TokenReplacerTask
   TemplateFile="..." OutputFile="..." TokensFile="..." DefaultsFile="..." />

Command-line tool usage

TokenReplacer.exe template output [/T:tokens] [/D:defaults]

   template - Template file path
   output - Output file path
   tokens - Tokens file path
   defaults - Default tokens file path

Examples

The source code (see links bellow) includes 2 sample projects:

  • TokenReplacerTaskSample - Demonstrates the use of the TokenReplacer command-line tool in a post-build event (to see the actual command right-click the project node > Properties > Build Events > Post-build event command line).
  • TokenReplacerToolSample - Demonstrates the use of the TokenRelacer MSBuild task in the AfterBuild target (to see how the task is used the project file TokenReplacerTaskSample.csproj must be opened in a text editor).

Downloads

Binaries v1.0.0.0
Source Code + Binaries + Samples v1.0.0.0