aboutsummaryrefslogtreecommitdiff
path: root/node_modules/parse-filepath/index.js
blob: fce6f2c3a81a2557960824d0564a2c50b8e8ef8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
'use strict';

var path = require('path');
var isAbsolute = require('is-absolute');
var pathRoot = require('path-root');
var MapCache = require('map-cache');
var cache = new MapCache();

module.exports = function(filepath) {
  if (typeof filepath !== 'string') {
    throw new TypeError('parse-filepath expects a string');
  }

  if (cache.has(filepath)) {
    return cache.get(filepath);
  }

  var obj = {};
  if (typeof path.parse === 'function') {
    obj = path.parse(filepath);
    obj.extname = obj.ext;
    obj.basename = obj.base;
    obj.dirname = obj.dir;
    obj.stem = obj.name;

  } else {
    define(obj, 'root', function() {
      return pathRoot(this.path);
    });

    define(obj, 'extname', function() {
      return path.extname(filepath);
    });

    define(obj, 'ext', function() {
      return this.extname;
    });

    define(obj, 'name', function() {
      return path.basename(filepath, this.ext);
    });

    define(obj, 'stem', function() {
      return this.name;
    });

    define(obj, 'base', function() {
      return this.name + this.ext;
    });

    define(obj, 'basename', function() {
      return this.base;
    });

    define(obj, 'dir', function() {
      return path.dirname(filepath);
    });

    define(obj, 'dirname', function() {
      return this.dir;
    });
  }

  obj.path = filepath;

  define(obj, 'absolute', function() {
    return path.resolve(this.path);
  });

  define(obj, 'isAbsolute', function() {
    return isAbsolute(this.path);
  });

  cache.set(filepath, obj);
  return obj;
};

function define(obj, prop, fn) {
  var cached;
  Object.defineProperty(obj, prop, {
    configurable: true,
    enumerable: true,
    set: function(val) {
      cached = val;
    },
    get: function() {
      return cached || (cached = fn.call(obj));
    }
  });
}