path-utils.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import os from "node:os"
  2. import path from "path"
  3. import { fileExists } from "./file-system.js"
  4. export function resolvePath(unresolvedPath) {
  5. return path.resolve(unresolvedPath.replace(/^~/, os.homedir()))
  6. }
  7. export async function firstFound(dirs, fileName) {
  8. // Note: This function depends on fileExists from file-system.js
  9. // Import it when using this function: import { fileExists } from './file-system.js'
  10. for (const dir of dirs) {
  11. const filePath = resolvePath(path.join(dir, fileName))
  12. const exists = await fileExists(filePath)
  13. if (exists) {
  14. return filePath
  15. }
  16. }
  17. return null
  18. }
  19. export function removeCwd(paths) {
  20. const cwd = `${process.cwd()}/`
  21. return paths.map(path => path.replace(cwd, ""))
  22. }
  23. export function removeBasePaths(baseDirs, fullPath) {
  24. return baseDirs.reduce((cleanedPath, dir) => {
  25. return cleanedPath.replace(dir, "")
  26. }, fullPath)
  27. }
  28. export function replaceFileExtension(filePath, newExtension) {
  29. if (!newExtension) {
  30. return filePath
  31. }
  32. return `${stripFileExtension(filePath)}${newExtension}`
  33. }
  34. export function stripFileExtension(filePath) {
  35. return path.join(
  36. path.dirname(filePath),
  37. path.basename(filePath, path.extname(filePath)),
  38. )
  39. }
  40. export function getCleanPath(filePath, meta) {
  41. return filePath.replace(meta.opts.runDir, "").replace(meta.opts.outDir, "/")
  42. }
  43. export function getHref(filePath, meta) {
  44. const route = getCleanPath(filePath, meta)
  45. if (route.includes("index.html")) {
  46. return route.replace("index.html", "")
  47. }
  48. return route.replace(".html", "")
  49. }
  50. export function slugifyString(str) {
  51. return str
  52. .toLowerCase()
  53. .trim()
  54. .replace(/[/\\?%@*:|"<>]/g, "-") // Replace invalid filename characters
  55. .replace(/\s+/g, "-") // Replace whitespace with dashes
  56. .replace(/-+/g, "-") // Collapse multiple dashes
  57. .replace(/\./g, "-") // Replace dots with dashes
  58. .replace(/^-+|-+$/g, "") // Trim leading/trailing dashes
  59. }