util.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. 'use strict';
  2. var fs = require('fs');
  3. var path = require('path');
  4. var commondir = require('commondir');
  5. var glob = require('glob');
  6. function notNullOrExclusion(file) {
  7. return file != null && file.charAt(0) !== '!';
  8. }
  9. exports.getCommonPath = function (filePath) {
  10. if (Array.isArray(filePath)) {
  11. filePath = filePath
  12. .filter(notNullOrExclusion)
  13. .map(this.getCommonPath.bind(this));
  14. return commondir(filePath);
  15. }
  16. var globStartIndex = filePath.indexOf('*');
  17. if (globStartIndex !== -1) {
  18. filePath = filePath.substring(0, globStartIndex + 1);
  19. } else if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
  20. return filePath;
  21. }
  22. return path.dirname(filePath);
  23. };
  24. exports.globify = function (filePath) {
  25. if (Array.isArray(filePath)) {
  26. return filePath.reduce((memo, pattern) => memo.concat(this.globify(pattern)), []);
  27. }
  28. if (glob.hasMagic(filePath)) {
  29. return filePath;
  30. }
  31. if (!fs.existsSync(filePath)) {
  32. // The target of a pattern who's not a glob and doesn't match an existing
  33. // entity on the disk is ambiguous. As such, match both files and directories.
  34. return [
  35. filePath,
  36. path.join(filePath, '**')
  37. ];
  38. }
  39. var fsStats = fs.statSync(filePath);
  40. if (fsStats.isFile()) {
  41. return filePath;
  42. }
  43. if (fsStats.isDirectory()) {
  44. return path.join(filePath, '**');
  45. }
  46. throw new Error('Only file path or directory path are supported.');
  47. };