1
0

LicenseHeaderTest.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.LastIndexOf("Rx.NET");
  31. Assert.False(idx < 0, $"Could not locate sources directory: {dir}");
  32. var newDir = dir.Substring(0, idx) + "Rx.NET/Source";
  33. var error = new StringBuilder();
  34. var count = ScanPath(newDir, error);
  35. if (error.Length != 0)
  36. {
  37. Assert.False(true, $"Files with no license header: {count}\r\n{error.ToString()}");
  38. }
  39. }
  40. int ScanPath(string path, StringBuilder error)
  41. {
  42. var count = 0;
  43. foreach (var file in Directory.EnumerateFiles(path, "*.cs", SearchOption.AllDirectories))
  44. {
  45. // exclusions
  46. if (file.Contains("obj/Debug")
  47. || file.Contains(@"obj\Debug")
  48. || file.Contains("AssemblyInfo.cs")
  49. || file.Contains(".Designer.cs")
  50. || file.Contains(".Generated.cs")
  51. || file.Contains("Uwp.DeviceRunner")
  52. || file.Contains(@"obj\Release")
  53. || file.Contains("obj/Release")
  54. )
  55. {
  56. continue;
  57. }
  58. // analysis
  59. string content = File.ReadAllText(file);
  60. if (!content.StartsWith(lines[0]))
  61. {
  62. count++;
  63. error.Append(file).Append("\r\n");
  64. if (fixHeaders)
  65. {
  66. StringBuilder newContent = new StringBuilder();
  67. string separator = content.Contains("\r\n") ? "\r\n" : "\n";
  68. foreach (var s in lines)
  69. {
  70. newContent.Append(s).Append(separator);
  71. }
  72. newContent.Append(content);
  73. File.WriteAllText(file, newContent.ToString());
  74. }
  75. }
  76. }
  77. return count;
  78. }
  79. }
  80. }