eslint-plugin-sonarjs
Version:
76 lines (75 loc) • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ROOT_PATH = void 0;
exports.normalizePath = normalizePath;
exports.normalizeToAbsolutePath = normalizeToAbsolutePath;
exports.isAbsolutePath = isAbsolutePath;
exports.toUnixPath = toUnixPath;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
const posix_1 = require("node:path/posix");
const win32_1 = require("node:path/win32");
/**
* Root path constant for Unix filesystem
*/
exports.ROOT_PATH = '/';
const isWindows = process.platform === 'win32';
/**
* Normalizes a path to Unix format (forward slashes).
* For absolute paths on Windows, resolves them to ensure they have a drive letter.
* For relative paths, only converts slashes without resolving.
* Cross-platform behavior:
* - On Windows: all absolute paths are resolved with win32 to add drive letter
* - On Linux: paths are only converted (slashes), no resolution needed
* @param filePath the path to normalize
* @returns the normalized path as a branded UnixPath type
*/
function normalizePath(filePath) {
if (isWindows && isAbsolutePath(filePath)) {
// On Windows, resolve to add drive letter if missing
filePath = (0, win32_1.resolve)(filePath);
}
return toUnixPath(filePath);
}
/**
* Normalizes a path to an absolute Unix format.
* Guarantees the returned path is absolute.
* @param filePath the path to normalize
* @param baseDir base directory to resolve relative paths against
* @returns the normalized path as a branded AbsoluteUnixPath type
*/
function normalizeToAbsolutePath(filePath, baseDir = exports.ROOT_PATH) {
if (isAbsolutePath(filePath)) {
// On Windows, resolve to add drive letter if missing
filePath = (0, win32_1.resolve)(filePath);
}
else {
filePath = isWindows ? (0, win32_1.resolve)(baseDir, filePath) : (0, posix_1.resolve)(baseDir, filePath);
}
return toUnixPath(filePath);
}
function isAbsolutePath(path) {
// Check for Windows drive letter (e.g., 'c:', 'C:', 'D:')
// Node's isAbsolute considers 'c:' as relative (drive-relative), but we treat it as absolute
if (/^[a-zA-Z]:/.test(path)) {
return true;
}
return (0, posix_1.isAbsolute)(path) || (0, win32_1.isAbsolute)(path);
}
function toUnixPath(filePath) {
return filePath.replaceAll(/[\\/]+/g, '/');
}