FileRegionReplace.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace HybridCLR.Editor.Template
  8. {
  9. public class FileRegionReplace
  10. {
  11. private readonly string _tplCode;
  12. private readonly Dictionary<string, string> _regionReplaceContents = new Dictionary<string, string>();
  13. public FileRegionReplace(string tplCode)
  14. {
  15. _tplCode = tplCode;
  16. }
  17. public void Replace(string regionName, string regionContent)
  18. {
  19. _regionReplaceContents.Add(regionName, regionContent);
  20. }
  21. public string GenFinalString()
  22. {
  23. string originContent = _tplCode;
  24. string resultContent = originContent;
  25. foreach (var c in _regionReplaceContents)
  26. {
  27. resultContent = ReplaceRegion(resultContent, c.Key, c.Value);
  28. }
  29. return resultContent;
  30. }
  31. public void Commit(string outputFile)
  32. {
  33. string dir = Path.GetDirectoryName(outputFile);
  34. Directory.CreateDirectory(dir);
  35. string resultContent = GenFinalString();
  36. var utf8WithoutBOM = new System.Text.UTF8Encoding(false);
  37. File.WriteAllText(outputFile, resultContent, utf8WithoutBOM);
  38. }
  39. public static string ReplaceRegion(string resultText, string region, string replaceContent)
  40. {
  41. int startIndex = resultText.IndexOf("//!!!{{" + region);
  42. if (startIndex == -1)
  43. {
  44. throw new Exception($"region:{region} start not find");
  45. }
  46. int endIndex = resultText.IndexOf("//!!!}}" + region);
  47. if (endIndex == -1)
  48. {
  49. throw new Exception($"region:{region} end not find");
  50. }
  51. int replaceStart = resultText.IndexOf('\n', startIndex);
  52. int replaceEnd = resultText.LastIndexOf('\n', endIndex);
  53. if (replaceStart == -1 || replaceEnd == -1)
  54. {
  55. throw new Exception($"region:{region} not find");
  56. }
  57. if (resultText.Substring(replaceStart, replaceEnd - replaceStart) == replaceContent)
  58. {
  59. return resultText;
  60. }
  61. resultText = resultText.Substring(0, replaceStart) + "\n" + replaceContent + "\n" + resultText.Substring(replaceEnd);
  62. return resultText;
  63. }
  64. }
  65. }