73539fd8c77c41e4d073286df177be1599ca7da8c11c90741a5c0923f97da5c6a5be0923e93dd9dce775b71a2b2afc800cf8e06aa8799179b1162c81175dbb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import _ from 'lodash';
  2. import Node from './Node';
  3. export default class BaseFolder extends Node {
  4. constructor(name, parent) {
  5. super(name, parent);
  6. this.children = Object.create(null);
  7. }
  8. get src() {
  9. if (!_.has(this, '_src')) {
  10. this._src = this.walk((node, src) => (src += node.src || ''), '', false);
  11. }
  12. return this._src;
  13. }
  14. get size() {
  15. if (!_.has(this, '_size')) {
  16. this._size = this.walk((node, size) => (size + node.size), 0, false);
  17. }
  18. return this._size;
  19. }
  20. getChild(name) {
  21. return this.children[name];
  22. }
  23. addChildModule(module) {
  24. const {name} = module;
  25. const currentChild = this.children[name];
  26. // For some reason we already have this node in children and it's a folder.
  27. if (currentChild && currentChild instanceof BaseFolder) return;
  28. if (currentChild) {
  29. // We already have this node in children and it's a module.
  30. // Merging it's data.
  31. currentChild.mergeData(module.data);
  32. } else {
  33. // Pushing new module
  34. module.parent = this;
  35. this.children[name] = module;
  36. }
  37. delete this._size;
  38. delete this._src;
  39. }
  40. addChildFolder(folder) {
  41. folder.parent = this;
  42. this.children[folder.name] = folder;
  43. delete this._size;
  44. delete this._src;
  45. return folder;
  46. }
  47. walk(walker, state = {}, deep = true) {
  48. let stopped = false;
  49. _.each(this.children, child => {
  50. if (deep && child.walk) {
  51. state = child.walk(walker, state, stop);
  52. } else {
  53. state = walker(child, state, stop);
  54. }
  55. if (stopped) return false;
  56. });
  57. return state;
  58. function stop(finalState) {
  59. stopped = true;
  60. return finalState;
  61. }
  62. }
  63. mergeNestedFolders() {
  64. if (!this.isRoot) {
  65. let childNames;
  66. while ((childNames = Object.keys(this.children)).length === 1) {
  67. const childName = childNames[0];
  68. const onlyChild = this.children[childName];
  69. if (onlyChild instanceof this.constructor) {
  70. this.name += `/${onlyChild.name}`;
  71. this.children = onlyChild.children;
  72. } else {
  73. break;
  74. }
  75. }
  76. }
  77. this.walk(child => {
  78. child.parent = this;
  79. if (child.mergeNestedFolders) {
  80. child.mergeNestedFolders();
  81. }
  82. }, null, false);
  83. }
  84. toChartData() {
  85. return {
  86. label: this.name,
  87. path: this.path,
  88. statSize: this.size,
  89. groups: _.invokeMap(this.children, 'toChartData')
  90. };
  91. }
  92. };