GetDocXmlFiles.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3. using Microsoft.Build.Framework;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. using System.Xml.Linq;
  9. namespace RepoTasks
  10. {
  11. /// <summary>
  12. /// Filters a list of .xml files to only those that are .NET Xml docs files
  13. /// </summary>
  14. public class GetDocXmlFiles : Microsoft.Build.Utilities.Task
  15. {
  16. [Required]
  17. public ITaskItem[] Files { get; set; }
  18. [Output]
  19. public ITaskItem[] XmlDocFiles { get; set; }
  20. public override bool Execute()
  21. {
  22. var xmlDocs = new ConcurrentBag<ITaskItem>();
  23. Parallel.ForEach(Files, f =>
  24. {
  25. try
  26. {
  27. using (var file = File.OpenRead(f.ItemSpec))
  28. using (var reader = new StreamReader(file))
  29. {
  30. string line;
  31. for (var i = 0; i < 2; i++)
  32. {
  33. line = reader.ReadLine();
  34. if (i == 0 && line.StartsWith("<?xml", StringComparison.Ordinal))
  35. {
  36. line = line.Substring(line.IndexOf("?>") + 2);
  37. }
  38. if (line.StartsWith("<doc>", StringComparison.OrdinalIgnoreCase) || line.StartsWith("<doc xml:", StringComparison.OrdinalIgnoreCase))
  39. {
  40. xmlDocs.Add(f);
  41. return;
  42. }
  43. }
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. Log.LogMessage(MessageImportance.Normal, $"Failed to read {f.ItemSpec}: {ex.ToString()}");
  49. }
  50. Log.LogMessage($"Did not detect {f.ItemSpec} as an xml doc file");
  51. });
  52. XmlDocFiles = xmlDocs.ToArray();
  53. Log.LogMessage($"Found {XmlDocFiles.Length} xml doc file(s)");
  54. return true;
  55. }
  56. }
  57. }