LicenseHeaderTest.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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/")
  43. || file.Contains(@"\obj\")
  44. || file.Contains("AssemblyInfo.cs")
  45. || file.Contains(".Designer.cs")
  46. || file.Contains(".Generated.cs")
  47. || file.Contains("Uwp.DeviceRunner")
  48. )
  49. {
  50. continue;
  51. }
  52. // analysis
  53. var content = File.ReadAllText(file);
  54. if (!content.StartsWith(Lines[0]))
  55. {
  56. count++;
  57. error.Append(file).Append("\r\n");
  58. if (FixHeaders)
  59. {
  60. var newContent = new StringBuilder();
  61. var separator = content.Contains("\r\n") ? "\r\n" : "\n";
  62. foreach (var s in Lines)
  63. {
  64. newContent.Append(s).Append(separator);
  65. }
  66. newContent.Append(content);
  67. File.WriteAllText(file, newContent.ToString());
  68. }
  69. }
  70. }
  71. return count;
  72. }
  73. }
  74. }