Skip to content
Source
Sign inSign up
TanStack/cli
Open History to see the last commit

edge-path.ts

77 lines1.6 KB

1export function normalizePath(path: string): string {
2 const normalized = path.replace(/\\/g, '/')
3 const isAbsolute = normalized.startsWith('/')
4 const parts: Array<string> = []
5​
6 for (const part of normalized.split('/')) {
7 if (!part || part === '.') {
8 continue
9 }
10 if (part === '..') {
11 if (parts.length && parts[parts.length - 1] !== '..') {
12 parts.pop()
13 } else if (!isAbsolute) {
14 parts.push(part)
15 }
16 continue
17 }
18 parts.push(part)
19 }
20​
21 const joined = parts.join('/')
22 if (isAbsolute) {
23 return joined ? `/${joined}` : '/'
24 }
25​
26 return joined || '.'
28​
29export function joinPaths(...paths: Array<string | undefined>): string {
30 const filtered = paths.filter(
31 (path): path is string => typeof path === 'string' && path.length > 0,
32 )
33 if (!filtered.length) {
34 return '.'
35 }
36​
37 return normalizePath(filtered.join('/'))
39​
40export function basenamePath(path: string): string {
41 const normalized = normalizePath(path)
42 if (normalized === '/') {
43 return ''
44 }
45​
46 return normalized.split('/').pop() ?? ''
48​
49export function dirnamePath(path: string): string {
50 const normalized = normalizePath(path)
51 if (normalized === '/') {
52 return '/'
53 }
54​
55 const parts = normalized.split('/')
56 parts.pop()
57​
58 if (!parts.length) {
59 return '.'
60 }
61​
62 if (parts.length === 1 && parts[0] === '') {
63 return '/'
64 }
65​
66 return parts.join('/') || '.'
68​
69export function extnamePath(path: string): string {
70 const basename = basenamePath(path)
71 const index = basename.lastIndexOf('.')
72 if (index <= 0) {
73 return ''
74 }
75​
76 return basename.slice(index)