CreateLzma.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 System;
  4. using System.IO;
  5. using System.Threading;
  6. using Microsoft.Build.Framework;
  7. using Microsoft.Build.Utilities;
  8. using Microsoft.DotNet.Archive;
  9. namespace RepoTasks
  10. {
  11. public class CreateLzma : Task, ICancelableTask
  12. {
  13. private readonly CancellationTokenSource _cts = new CancellationTokenSource();
  14. [Required]
  15. public string OutputPath { get; set; }
  16. [Required]
  17. public string[] Sources { get; set; }
  18. public void Cancel() => _cts.Cancel();
  19. public override bool Execute()
  20. {
  21. var progress = new MSBuildProgressReport(Log, _cts.Token);
  22. using (var archive = new IndexedArchive())
  23. {
  24. foreach (var source in Sources)
  25. {
  26. if (Directory.Exists(source))
  27. {
  28. var trimmedSource = source.TrimEnd(new []{ '\\', '/' });
  29. Log.LogMessage(MessageImportance.High, $"Adding directory: {trimmedSource}");
  30. archive.AddDirectory(trimmedSource, progress);
  31. }
  32. else
  33. {
  34. Log.LogMessage(MessageImportance.High, $"Adding file: {source}");
  35. archive.AddFile(source, Path.GetFileName(source));
  36. }
  37. }
  38. archive.Save(OutputPath, progress);
  39. }
  40. return !Log.HasLoggedErrors;
  41. }
  42. private class MSBuildProgressReport : IProgress<ProgressReport>
  43. {
  44. private TaskLoggingHelper _log;
  45. private readonly CancellationToken _cancellationToken;
  46. public MSBuildProgressReport(TaskLoggingHelper log, CancellationToken cancellationToken)
  47. {
  48. _log = log;
  49. _cancellationToken = cancellationToken;
  50. }
  51. public void Report(ProgressReport value)
  52. {
  53. var complete = (double)value.Ticks / value.Total;
  54. _log.LogMessage(MessageImportance.Low, $"Progress: {value.Phase} - {complete:P}");
  55. _cancellationToken.ThrowIfCancellationRequested(); // because LZMA apis don't take a cancellation token, throw from the logger (yes, its ugly, but it works.)
  56. }
  57. }
  58. }
  59. }