UNPKG

2.49 kBJavaScriptView Raw
1/**
2 * @fileoverview Common helpers for operations on filenames and paths
3 * @author Ian VanSchooten
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const path = require("path");
12
13//------------------------------------------------------------------------------
14// Private
15//------------------------------------------------------------------------------
16
17/**
18 * Replace Windows with posix style paths
19 *
20 * @param {string} filepath Path to convert
21 * @returns {string} Converted filepath
22 */
23function convertPathToPosix(filepath) {
24 const normalizedFilepath = path.normalize(filepath);
25 const posixFilepath = normalizedFilepath.replace(/\\/gu, "/");
26
27 return posixFilepath;
28}
29
30/**
31 * Converts an absolute filepath to a relative path from a given base path
32 *
33 * For example, if the filepath is `/my/awesome/project/foo.bar`,
34 * and the base directory is `/my/awesome/project/`,
35 * then this function should return `foo.bar`.
36 *
37 * path.relative() does something similar, but it requires a baseDir (`from` argument).
38 * This function makes it optional and just removes a leading slash if the baseDir is not given.
39 *
40 * It does not take into account symlinks (for now).
41 *
42 * @param {string} filepath Path to convert to relative path. If already relative,
43 * it will be assumed to be relative to process.cwd(),
44 * converted to absolute, and then processed.
45 * @param {string} [baseDir] Absolute base directory to resolve the filepath from.
46 * If not provided, all this function will do is remove
47 * a leading slash.
48 * @returns {string} Relative filepath
49 */
50function getRelativePath(filepath, baseDir) {
51 const absolutePath = path.isAbsolute(filepath)
52 ? filepath
53 : path.resolve(filepath);
54
55 if (baseDir) {
56 if (!path.isAbsolute(baseDir)) {
57 throw new Error(`baseDir should be an absolute path: ${baseDir}`);
58 }
59 return path.relative(baseDir, absolutePath);
60 }
61 return absolutePath.replace(/^\//u, "");
62
63}
64
65//------------------------------------------------------------------------------
66// Public Interface
67//------------------------------------------------------------------------------
68
69module.exports = {
70 convertPathToPosix,
71 getRelativePath
72};