| 1 |
/* |
| 2 |
* Copyright (C) 2024 Red Hat, Inc. |
| 3 |
* SPDX-License-Identifier: LGPL-2.1-or-later |
| 4 |
*/ |
| 5 |
|
| 6 |
function drop_slashes(path : string): string { |
| 7 |
// Drop all trailing slashes, but never drop the first character. |
| 8 |
let pos = path.length; |
| 9 |
while (pos > 1 && path[pos - 1] == "/") |
| 10 |
pos -= 1; |
| 11 |
return pos == path.length ? path : path.substring(0, pos); |
| 12 |
} |
| 13 |
|
| 14 |
export function dirname(path : string): string { |
| 15 |
const norm = drop_slashes(path); |
| 16 |
const pos = norm.lastIndexOf("/"); |
| 17 |
if (pos < 0) |
| 18 |
return "."; |
| 19 |
else if (pos == 0) |
| 20 |
return "/"; |
| 21 |
else |
| 22 |
return drop_slashes(norm.substring(0, pos)); |
| 23 |
} |
| 24 |
|
| 25 |
export function basename(path : string): string { |
| 26 |
const norm = drop_slashes(path); |
| 27 |
const pos = norm.lastIndexOf("/"); |
| 28 |
if (pos < 0) |
| 29 |
return norm; |
| 30 |
else if (pos === 0 && norm.length === 1) |
| 31 |
return "/"; |
| 32 |
else |
| 33 |
return norm.substring(pos + 1); |
| 34 |
} |
| 35 |
|
| 36 |
export function path_join(dir: string, base: string) { |
| 37 |
const normdir = drop_slashes(dir); |
| 38 |
return (normdir === "/" ? "" : normdir) + "/" + base; |
| 39 |
} |