index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var path = require('path');
  3. var isNegated = require('is-negated-glob');
  4. var isAbsolute = require('is-absolute');
  5. module.exports = function(glob, options) {
  6. // default options
  7. var opts = options || {};
  8. // ensure cwd is absolute
  9. var cwd = path.resolve(opts.cwd ? opts.cwd : process.cwd());
  10. cwd = unixify(cwd);
  11. var rootDir = opts.root;
  12. // if `options.root` is defined, ensure it's absolute
  13. if (rootDir) {
  14. rootDir = unixify(rootDir);
  15. if (process.platform === 'win32' || !isAbsolute(rootDir)) {
  16. rootDir = unixify(path.resolve(rootDir));
  17. }
  18. }
  19. // trim starting ./ from glob patterns
  20. if (glob.slice(0, 2) === './') {
  21. glob = glob.slice(2);
  22. }
  23. // when the glob pattern is only a . use an empty string
  24. if (glob.length === 1 && glob === '.') {
  25. glob = '';
  26. }
  27. // store last character before glob is modified
  28. var suffix = glob.slice(-1);
  29. // check to see if glob is negated (and not a leading negated-extglob)
  30. var ing = isNegated(glob);
  31. glob = ing.pattern;
  32. // make glob absolute
  33. if (rootDir && glob.charAt(0) === '/') {
  34. glob = join(rootDir, glob);
  35. } else if (!isAbsolute(glob) || glob.slice(0, 1) === '\\') {
  36. glob = join(cwd, glob);
  37. }
  38. // if glob had a trailing `/`, re-add it now in case it was removed
  39. if (suffix === '/' && glob.slice(-1) !== '/') {
  40. glob += '/';
  41. }
  42. // re-add leading `!` if it was removed
  43. return ing.negated ? '!' + glob : glob;
  44. };
  45. function unixify(filepath) {
  46. return filepath.replace(/\\/g, '/');
  47. }
  48. function join(dir, glob) {
  49. if (dir.charAt(dir.length - 1) === '/') {
  50. dir = dir.slice(0, -1);
  51. }
  52. if (glob.charAt(0) === '/') {
  53. glob = glob.slice(1);
  54. }
  55. if (!glob) return dir;
  56. return dir + '/' + glob;
  57. }