ListAspect.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Quadarax.Foundation.Core.QConsole.Argument;
  2. using Quadarax.Foundation.Core.QConsole.Command.Base;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO.Abstractions;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace qdr.app.tools.qfu.Commands.Aspects
  10. {
  11. internal class ListAspect
  12. {
  13. #region *** Constants ***
  14. private const string ARG_LIST_NAME = "list";
  15. private const string ARG_LIST_HINT = "list";
  16. private const string ARG_LIST_DESCR = "Flag if defined, then first argument of target file represents text file with new line defined full file paths";
  17. #endregion
  18. #region *** Public Operations ***
  19. public static IEnumerable<AbstractArgument> SetupArguments()
  20. {
  21. return
  22. [
  23. new FlagArgument(ARG_LIST_NAME, ARG_LIST_DESCR, ARG_LIST_HINT, false)
  24. ];
  25. }
  26. public static string[] GetFiles(AbstractCommand context, IFileSystem fs,IEnumerable<string> defaultResult, bool checkValidity = false)
  27. {
  28. if (context == null)
  29. throw new ArgumentNullException(nameof(context), "Command context cannot be null.");
  30. var filesArgument = context.Arguments.First(x => string.Equals(x.Code, ARG_LIST_NAME));
  31. if (filesArgument.Value.Get() == null)
  32. throw new ArgumentException($"Argument '{ARG_LIST_NAME}' is not set.", ARG_LIST_NAME);
  33. if (!(bool)filesArgument.Value.Get()!)
  34. return defaultResult.ToArray();
  35. var listFileName = defaultResult.First();
  36. if (!fs.File.Exists(listFileName))
  37. throw new FileNotFoundException($"List file '{listFileName}' does not exist.");
  38. var files = fs.File.ReadAllLines(listFileName).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
  39. if (checkValidity)
  40. {
  41. var sb = new StringBuilder();
  42. foreach (var file in files)
  43. {
  44. if (string.IsNullOrEmpty(file))
  45. continue;
  46. if (!fs.File.Exists(file) && !fs.Directory.Exists(file))
  47. sb.AppendLine(file);
  48. }
  49. if (sb.Length > 0)
  50. throw new FileNotFoundException($"The following files do not exist:\n{sb.ToString()}");
  51. }
  52. return files;
  53. }
  54. #endregion
  55. }
  56. }