FileTree.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @author sw5678
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import Utils from "../Utils.mjs";
  8. import {INPUT_DELIM_OPTIONS} from "../lib/Delim.mjs";
  9. /**
  10. * Unique operation
  11. */
  12. class FileTree extends Operation {
  13. /**
  14. * Unique constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "File Tree";
  19. this.module = "Default";
  20. this.description = "Creates file tree from list of file paths (similar to the tree command in Linux)";
  21. this.inputType = "string";
  22. this.outputType = "string";
  23. this.args = [
  24. {
  25. name: "File Path Delimiter",
  26. type: "binaryString",
  27. value: "/"
  28. },
  29. {
  30. name: "Delimiter",
  31. type: "option",
  32. value: INPUT_DELIM_OPTIONS
  33. }
  34. ];
  35. }
  36. /**
  37. * @param {string} input
  38. * @param {Object[]} args
  39. * @returns {string}
  40. */
  41. run(input, args) {
  42. // Set up arrow and pipe for nice output display
  43. const ARROW = "|---";
  44. const PIPE = "| ";
  45. // Get args from input
  46. const fileDelim = args[0];
  47. const entryDelim = Utils.charRep(args[1]);
  48. // Store path to print
  49. const completedList = [];
  50. const printList = [];
  51. // Loop through all entries
  52. const filePaths = input.split(entryDelim).unique().sort();
  53. for (let i = 0; i < filePaths.length; i++) {
  54. // Split by file delimiter
  55. let path = filePaths[i].split(fileDelim);
  56. if (path[0] === "") {
  57. path = path.slice(1, path.length);
  58. }
  59. for (let j = 0; j < path.length; j++) {
  60. let printLine;
  61. let key;
  62. if (j === 0) {
  63. printLine = path[j];
  64. key = path[j];
  65. } else {
  66. printLine = PIPE.repeat(j-1) + ARROW + path[j];
  67. key = path.slice(0, j+1).join("/");
  68. }
  69. // Check to see we have already added that path
  70. if (!completedList.includes(key)) {
  71. completedList.push(key);
  72. printList.push(printLine);
  73. }
  74. }
  75. }
  76. return printList.join("\n");
  77. }
  78. }
  79. export default FileTree;