PageRenderTime 44ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Mercurial.Net.Tests/Hooks/HookTestUtilities.cs

#
C# | 85 lines | 79 code | 6 blank | 0 comment | 9 complexity | 76ace6d25364583462580f47ca4bbebf MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Mercurial.Net.Tests.Hook;
  7. namespace Mercurial.Tests.Hooks
  8. {
  9. public static class HookTestUtilities
  10. {
  11. public static int Count(this string text, string textToCountOccurancesOf)
  12. {
  13. int originalLength = text.Length;
  14. text = text.Replace(textToCountOccurancesOf, string.Empty);
  15. int replacedLength = text.Length;
  16. return (originalLength - replacedLength) / textToCountOccurancesOf.Length;
  17. }
  18. public static void SetHook(this Repository repository, string hookName, params string[] arguments)
  19. {
  20. arguments = new string[] { hookName }.Concat(arguments ?? new string[0]).ToArray();
  21. string argumentString = string.Join(" ", arguments.Select(s => "\"" + s + "\"").ToArray());
  22. string[] lines;
  23. string hgrcPath = Path.Combine(Path.Combine(repository.Path, ".hg"), "hgrc");
  24. if (File.Exists(hgrcPath))
  25. lines = File.ReadAllLines(hgrcPath);
  26. else
  27. lines = new string[0];
  28. string hookCommand = string.Format(
  29. CultureInfo.InvariantCulture, "{0}=\"{1}\" {2}",
  30. hookName,
  31. typeof(Program).Assembly.Location,
  32. argumentString);
  33. var modifiedLines = new List<string>();
  34. bool inHooks = false;
  35. bool hookAdded = false;
  36. foreach (string line in lines)
  37. {
  38. if (inHooks)
  39. {
  40. if (line.StartsWith("["))
  41. {
  42. if (!hookAdded)
  43. {
  44. modifiedLines.Add(hookCommand);
  45. hookAdded = true;
  46. }
  47. modifiedLines.Add(line);
  48. inHooks = false;
  49. }
  50. else
  51. {
  52. if (line.StartsWith(hookName + "="))
  53. {
  54. modifiedLines.Add(hookCommand);
  55. hookAdded = true;
  56. }
  57. else
  58. modifiedLines.Add(line);
  59. }
  60. }
  61. else
  62. {
  63. if (line == "[hooks]")
  64. {
  65. modifiedLines.Add(line);
  66. inHooks = true;
  67. }
  68. }
  69. }
  70. if (!hookAdded)
  71. {
  72. if (!inHooks)
  73. modifiedLines.Add("[hooks]");
  74. modifiedLines.Add(hookCommand);
  75. }
  76. File.WriteAllLines(hgrcPath, modifiedLines.ToArray());
  77. }
  78. }
  79. }