|
| 1 | +//----------------------------------------------------------------------- |
| 2 | +// <copyright file="RegexFileReplace.cs" company="Andrew Arnott"> |
| 3 | +// Copyright (c) Andrew Arnott. All rights reserved. |
| 4 | +// </copyright> |
| 5 | +//----------------------------------------------------------------------- |
| 6 | + |
| 7 | +namespace DotNetOpenAuth.BuildTasks { |
| 8 | + using System; |
| 9 | + using System.Collections.Generic; |
| 10 | + using System.IO; |
| 11 | + using System.Linq; |
| 12 | + using System.Reflection; |
| 13 | + using System.Text; |
| 14 | + using Microsoft.Build.BuildEngine; |
| 15 | + using Microsoft.Build.Framework; |
| 16 | + using Microsoft.Build.Utilities; |
| 17 | + using System.Text.RegularExpressions; |
| 18 | + |
| 19 | + public class RegexFileReplace : Task { |
| 20 | + /// <summary> |
| 21 | + /// Gets or sets the set of files to search. |
| 22 | + /// </summary> |
| 23 | + [Required] |
| 24 | + public ITaskItem[] Files { get; set; } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Gets or sets the files to save the changed files to. This may be the same as the input files to make the change in place. |
| 28 | + /// </summary> |
| 29 | + public ITaskItem[] OutputFiles { get; set; } |
| 30 | + |
| 31 | + public string Pattern { get; set; } |
| 32 | + |
| 33 | + public string Replacement { get; set; } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Executes this instance. |
| 37 | + /// </summary> |
| 38 | + public override bool Execute() { |
| 39 | + if (this.OutputFiles == null || this.OutputFiles.Length == 0) { |
| 40 | + this.OutputFiles = this.Files; |
| 41 | + } |
| 42 | + |
| 43 | + foreach (var file in this.Files) { |
| 44 | + string[] lines = File.ReadAllLines(file.ItemSpec); |
| 45 | + for (int i = 0; i < lines.Length; i++) { |
| 46 | + lines[i] = Regex.Replace(lines[i], this.Pattern, this.Replacement); |
| 47 | + } |
| 48 | + |
| 49 | + File.WriteAllLines(file.ItemSpec, lines); |
| 50 | + } |
| 51 | + |
| 52 | + return !this.Log.HasLoggedErrors; |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments