1
0

LicenseHeaderTest.cs 3.0 KB

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