LicenseHeaderTest.cs 3.2 KB

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