1
0

LicenseHeaderTest.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. "// Licensed to the .NET Foundation under one or more agreements.",
  20. "// The .NET Foundation licenses this file to you under the MIT License.",
  21. "// See the LICENSE file in the project root for more information.",
  22. ""
  23. };
  24. [TestMethod]
  25. public void ScanFiles()
  26. {
  27. var dir = Directory.GetCurrentDirectory();
  28. var idx = dir.LastIndexOf("Rx.NET");
  29. Assert.False(idx < 0, $"Could not locate sources directory: {dir}");
  30. var newDir = Path.Combine(dir.Substring(0, idx), "Rx.NET", "Source");
  31. var error = new StringBuilder();
  32. var count = ScanPath(newDir, error);
  33. if (error.Length != 0)
  34. {
  35. Assert.False(true, $"Files with no license header: {count}\r\n{error.ToString()}");
  36. }
  37. }
  38. private int ScanPath(string path, StringBuilder error)
  39. {
  40. var count = 0;
  41. foreach (var file in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories))
  42. {
  43. // exclusions
  44. if (file.Contains("/obj/")
  45. || file.Contains(@"\obj\")
  46. || file.Contains("AssemblyInfo.cs")
  47. || file.Contains(".Designer.cs")
  48. || file.Contains(".Generated.cs")
  49. || file.Contains(".verified.cs")
  50. || file.Contains("Uwp.DeviceRunner")
  51. )
  52. {
  53. continue;
  54. }
  55. // analysis
  56. var content = File.ReadAllText(file);
  57. if (!content.StartsWith(Lines[0]))
  58. {
  59. count++;
  60. error.Append(file).Append("\r\n");
  61. if (FixHeaders)
  62. {
  63. var newContent = new StringBuilder();
  64. var separator = content.Contains("\r\n") ? "\r\n" : "\n";
  65. foreach (var s in Lines)
  66. {
  67. newContent.Append(s).Append(separator);
  68. }
  69. newContent.Append(content);
  70. File.WriteAllText(file, newContent.ToString());
  71. }
  72. }
  73. }
  74. return count;
  75. }
  76. }
  77. }