flatten-path.js 1.4 KB

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