| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | /*! |
| 2 | * strip-dirs | MIT (c) Shinnosuke Watanabe |
| 3 | * https://github.com/shinnn/node-strip-dirs |
| 4 | */ |
| 5 | 'use strict'; |
| 6 | |
| 7 | const path = require('path'); |
| 8 | const util = require('util'); |
| 9 | |
| 10 | const isNaturalNumber = require('is-natural-number'); |
| 11 | |
| 12 | module.exports = function stripDirs(pathStr, count, option) { |
| 13 | if (typeof pathStr !== 'string') { |
| 14 | throw new TypeError( |
| 15 | util.inspect(pathStr) + |
| 16 | ' is not a string. First argument to strip-dirs must be a path string.' |
| 17 | ); |
| 18 | } |
| 19 | |
| 20 | if (path.posix.isAbsolute(pathStr) || path.win32.isAbsolute(pathStr)) { |
| 21 | throw new Error(`${pathStr} is an absolute path. strip-dirs requires a relative path.`); |
| 22 | } |
| 23 | |
| 24 | if (!isNaturalNumber(count, {includeZero: true})) { |
| 25 | throw new Error( |
| 26 | 'The Second argument of strip-dirs must be a natural number or 0, but received ' + |
| 27 | util.inspect(count) + |
| 28 | '.' |
| 29 | ); |
| 30 | } |
| 31 | |
| 32 | if (option) { |
| 33 | if (typeof option !== 'object') { |
| 34 | throw new TypeError( |
| 35 | util.inspect(option) + |
| 36 | ' is not an object. Expected an object with a boolean `disallowOverflow` property.' |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | if (Array.isArray(option)) { |
| 41 | throw new TypeError( |
| 42 | util.inspect(option) + |
| 43 | ' is an array. Expected an object with a boolean `disallowOverflow` property.' |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | if ('disallowOverflow' in option && typeof option.disallowOverflow !== 'boolean') { |
| 48 | throw new TypeError( |
| 49 | util.inspect(option.disallowOverflow) + |
| 50 | ' is neither true nor false. `disallowOverflow` option must be a Boolean value.' |
| 51 | ); |
| 52 | } |
| 53 | } else { |
| 54 | option = {disallowOverflow: false}; |
| 55 | } |
| 56 | |
| 57 | const pathComponents = path.normalize(pathStr).split(path.sep); |
| 58 | |
| 59 | if (pathComponents.length > 1 && pathComponents[0] === '.') { |
| 60 | pathComponents.shift(); |
| 61 | } |
| 62 | |
| 63 | if (count > pathComponents.length - 1) { |
| 64 | if (option.disallowOverflow) { |
| 65 | throw new RangeError('Cannot strip more directories than there are.'); |
| 66 | } |
| 67 | |
| 68 | count = pathComponents.length - 1; |
| 69 | } |
| 70 | |
| 71 | return path.join.apply(null, pathComponents.slice(count)); |
| 72 | }; |