LicenseHeaderTest.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.IO;
  5. using System.Text;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using Assert = Xunit.Assert;
  8. namespace Tests.System.Reactive.Tests
  9. {
  10. /// <summary>
  11. /// Verify that main classes and unit tests have a license header
  12. /// in the source files.
  13. /// </summary>
  14. [TestClass]
  15. public class LicenseHeaderTest
  16. {
  17. private static readonly bool FixHeaders = true;
  18. private static readonly string[] Lines =
  19. [
  20. "// Licensed to the .NET Foundation under one or more agreements.",
  21. "// The .NET Foundation licenses this file to you under the MIT License.",
  22. "// See the LICENSE file in the project root for more information.",
  23. ""
  24. ];
  25. [TestMethod]
  26. public void ScanFiles()
  27. {
  28. var dir = Directory.GetCurrentDirectory();
  29. var idx = dir.LastIndexOf("Rx.NET");
  30. Assert.False(idx < 0, $"Could not locate sources directory: {dir}");
  31. var newDir = Path.Combine(dir.Substring(0, idx), "Rx.NET", "Source");
  32. var error = new StringBuilder();
  33. var count = ScanPath(newDir, error);
  34. if (error.Length != 0)
  35. {
  36. Assert.False(true, $"Files with no license header: {count}\r\n{error}");
  37. }
  38. }
  39. private int ScanPath(string path, StringBuilder error)
  40. {
  41. var count = 0;
  42. foreach (var file in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories))
  43. {
  44. // exclusions
  45. if (file.Contains("/obj/")
  46. || file.Contains(@"\obj\")
  47. || file.Contains("AssemblyInfo.cs")
  48. || file.Contains(".Designer.cs")
  49. || file.Contains(".Generated.cs")
  50. || file.Contains(".verified.cs")
  51. || file.Contains("Uwp.DeviceRunner")
  52. )
  53. {
  54. continue;
  55. }
  56. // analysis
  57. var content = File.ReadAllText(file);
  58. if (!content.StartsWith(Lines[0]))
  59. {
  60. count++;
  61. error.Append(file).Append("\r\n");
  62. if (FixHeaders)
  63. {
  64. var newContent = new StringBuilder();
  65. var separator = content.Contains("\r\n") ? "\r\n" : "\n";
  66. foreach (var s in Lines)
  67. {
  68. newContent.Append(s).Append(separator);
  69. }
  70. newContent.Append(content);
  71. File.WriteAllText(file, newContent.ToString());
  72. }
  73. }
  74. }
  75. return count;
  76. }
  77. }
  78. }