flatten-path.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var path = require('path');
  2. /**
  3. * Flatten the path to the desired depth
  4. *
  5. * @param {File} file - vinyl file
  6. * @param {Object} options
  7. * @return {String}
  8. */
  9. function flattenPath(file, opts) {
  10. var topLevels;
  11. var bottomLevels = 0;
  12. var dirs;
  13. var topPath = [];
  14. var bottomPath = [];
  15. var newPath = [];
  16. var fileName = path.basename(file.path);
  17. if (!opts.includeParents) {
  18. return fileName;
  19. }
  20. opts = opts.includeParents;
  21. if (Array.isArray(opts)) {
  22. topLevels = Math.abs(opts[0]);
  23. bottomLevels = Math.abs(opts[1]);
  24. } else if (opts >= 0) {
  25. topLevels = opts;
  26. } else {
  27. bottomLevels = Math.abs(opts);
  28. }
  29. dirs = path.dirname(file.relative).split(path.sep);
  30. if (topLevels + bottomLevels > dirs.length) {
  31. return file.relative;
  32. }
  33. while (topLevels > 0) {
  34. topPath.push(dirs.shift());
  35. topLevels--;
  36. }
  37. while (bottomLevels > 0) {
  38. bottomPath.unshift(dirs.pop());
  39. bottomLevels--;
  40. }
  41. newPath = topPath.concat(bottomPath);
  42. newPath.push(fileName);
  43. return path.join.apply(path, newPath);
  44. }
  45. module.exports = flattenPath