path-format.tsx 830 B

123456789101112131415161718192021222324
  1. import path from "path"
  2. import { abbreviateHome } from "../runtime"
  3. import { useLocation } from "./location"
  4. import { useTuiPaths } from "./runtime"
  5. export function usePathFormatter() {
  6. const paths = useTuiPaths()
  7. const location = useLocation()
  8. return {
  9. path: () => location()?.directory || paths.cwd,
  10. format: (input?: string) => formatPath(input, location()?.directory || paths.cwd, paths.home),
  11. }
  12. }
  13. function formatPath(input: string | undefined, base: string, home: string) {
  14. if (typeof input !== "string" || !input) return ""
  15. const absolute = path.isAbsolute(input) ? input : path.resolve(base, input)
  16. const relative = path.relative(base, absolute)
  17. if (!relative) return "."
  18. if (relative !== ".." && !relative.startsWith(".." + path.sep)) return relative
  19. return abbreviateHome(absolute, home)
  20. }