aboutsummaryrefslogtreecommitdiff
path: root/node_modules/strip-dirs/index.js
blob: 974af89bd50b648b19b863b584148077ecb7812e (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
/*!
 * strip-dirs | MIT (c) Shinnosuke Watanabe
 * https://github.com/shinnn/node-strip-dirs
*/
'use strict';

const path = require('path');
const util = require('util');

const isNaturalNumber = require('is-natural-number');

module.exports = function stripDirs(pathStr, count, option) {
  if (typeof pathStr !== 'string') {
    throw new TypeError(
      util.inspect(pathStr) +
      ' is not a string. First argument to strip-dirs must be a path string.'
    );
  }

  if (path.posix.isAbsolute(pathStr) || path.win32.isAbsolute(pathStr)) {
    throw new Error(`${pathStr} is an absolute path. strip-dirs requires a relative path.`);
  }

  if (!isNaturalNumber(count, {includeZero: true})) {
    throw new Error(
      'The Second argument of strip-dirs must be a natural number or 0, but received ' +
      util.inspect(count) +
      '.'
    );
  }

  if (option) {
    if (typeof option !== 'object') {
      throw new TypeError(
        util.inspect(option) +
        ' is not an object. Expected an object with a boolean `disallowOverflow` property.'
      );
    }

    if (Array.isArray(option)) {
      throw new TypeError(
        util.inspect(option) +
        ' is an array. Expected an object with a boolean `disallowOverflow` property.'
      );
    }

    if ('disallowOverflow' in option && typeof option.disallowOverflow !== 'boolean') {
      throw new TypeError(
        util.inspect(option.disallowOverflow) +
        ' is neither true nor false. `disallowOverflow` option must be a Boolean value.'
      );
    }
  } else {
    option = {disallowOverflow: false};
  }

  const pathComponents = path.normalize(pathStr).split(path.sep);

  if (pathComponents.length > 1 && pathComponents[0] === '.') {
    pathComponents.shift();
  }

  if (count > pathComponents.length - 1) {
    if (option.disallowOverflow) {
      throw new RangeError('Cannot strip more directories than there are.');
    }

    count = pathComponents.length - 1;
  }

  return path.join.apply(null, pathComponents.slice(count));
};