Tuesday, June 1, 2010

PSAKE Template Expansion

Several months ago I was in the market for a build solution. The two that caught my attention were James Kovac’s PSAKE and Derick Bailey’s Albacore. Derick and crew have put a lot of work into the Albacore project and it shows. The feature set is remarkable and Albacore is a cinch to use. However, I need to keep my project dependencies to a minimum and for me Ruby is too much. So I went with PSAKE.
One thing I did reluctantly give up by using PSAKE was the template expansion features Derick put into Albacore. After a fairly thorough search I found that no one had a decent solution or they were keeping their find to themselves. The solutions that I did find required a bit of XML which I was aggressively staying away from. With shortage of time I had to make my own.
For my solution I chose to follow Derick’s choice of YAML files for the template data files and how these keys are represented in the templates. To me this is a more understandable format and I had most of my templates setup to use Albacore already. In case you are not familiar with how Albacore’s expandtemplates work:
Your template data file details key value pairs in YAML format.

value_1: this is some value 
value_2: this is another value

Your template file would represent these like :





If the process works correctly, you end up with:

 



What you are here for


The first step was getting the key value pairs in a usable format. To do this you have to read the data file and create a hashtable from each line. This is how you accomplish this in Powershell:

$data_values = @{}    
foreach($line in $template_data) {
$d= $line.IndexOf(":")
$length = $line.Length
$data_values.add($line.Substring(0,$d).Trim() ,
$line.Substring($d+1, ($length-($d+1))))
}

Once the data file has been hashed, you need to read the contents of the file and perform the replacements:
[string] $template_text = [System.IO.File]::ReadAllText($template_file)     
if ($debug -eq $true) {
echo $template_text
echo ""
echo "--------------------------------------------"
echo ""
echo "Replacing values"
}

foreach ($item in $data_values.Keys) {
if ($template_text -eq $null) {
throw "There is a problem with text template"
}

if ($debug -eq $true) {
echo " -- #{$item} with " $data_values.Get_Item($item)
}

$template_text = $template_text.Replace("#{$item}",
$data_values.Get_Item($item).Trim())
}

Finally you create the destination file:

$template_text | sc -path $destination_file


Conclusion

This is the first useful function I have created for my PSAKE builds and have placed it on github here.

0 comments:

Post a Comment