LicenseHeaderTest.cs 2.9 KB

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