///
/// Copyright © 2003-2008 JetBrains s.r.o.
/// You may distribute under the terms of the GNU General Public License, as published by the Free Software Foundation, version 2 (see License.txt in the repository root folder).
///
using System;
using System.Text.RegularExpressions;
using JetBrains.Build.Common.Infra;
using Microsoft.Build.Framework;
namespace JetBrains.Build.Common.Tasks
{
///
/// Performs RegexReplace on a string.
///
public class Replace : TaskBase
{
#region Attributes
///
/// Gets or sets whether the search should be case-sensitive.
///
[Required]
public bool CaseSensitive
{
get
{
return (bool)Bag[AttributeName.CaseSensitive];
}
set
{
Bag[AttributeName.CaseSensitive] = value;
}
}
///
/// Gets or sets whether the task should fail when no replacements were made.
///
public bool FailOnNoMatch { get; set; }
///
/// Gets whether there were any replacements, that is, the string was ever matched.
///
[Output]
public bool IsMatch { get; set; }
///
/// On input, specifies the source text on which the replace should be performed.
/// On output, gives the results of the replacement.
///
[Output]
[Required]
public string Text
{
get
{
return (string)Bag[AttributeName.Text];
}
set
{
Bag[AttributeName.Text] = value;
}
}
///
/// Gets or sets the matching pattern.
///
[Required]
public string What
{
get
{
return (string)Bag[AttributeName.What];
}
set
{
Bag[AttributeName.What] = value;
}
}
///
/// Gets or sets the replacement string.
///
public string With
{
get
{
return (string)Bag[AttributeName.With];
}
set
{
Bag[AttributeName.With] = value;
}
}
#endregion
#region Overrides
///
/// The method to be overriden in inheriting tasks.
/// Throw an exception in case of an errror.
///
protected override void ExecuteTask()
{
var regex = new Regex(GetStringValue(AttributeName.What), RegexOptions.Singleline | (GetValue(AttributeName.CaseSensitive) ? 0 : RegexOptions.IgnoreCase));
string sWith = With ?? "";
string sWhat = GetStringValue(AttributeName.Text);
// Check for the matches
IsMatch = regex.IsMatch(sWhat);
if((!IsMatch) && (FailOnNoMatch))
throw new InvalidOperationException(string.Format("The input string does not match the search pattern."));
// Replace
Text = regex.Replace(sWhat, sWith);
}
#endregion
}
}