Skip to content

Commit 698e599

Browse files
committedJun 17, 2022
feat(utils): add isChildPath util
1 parent d0217f8 commit 698e599

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { isChildPath } from '@vuepress/utils'
2+
3+
const testCases: [[string, string], boolean][] = [
4+
[['/foo', '/foo'], true],
5+
[['/foo', '/bar'], false],
6+
[['/foo', '/foo/bar'], false],
7+
[['/foo/bar', '/foo'], true],
8+
[['/foo', '/foo-bar'], false],
9+
[['/foo-bar', '/foo'], false],
10+
[['C:\\foo', 'C:\\foo'], true],
11+
[['C:\\foo', 'C:\\bar'], false],
12+
[['C:\\foo', 'C:\\foo\\bar'], false],
13+
[['C:\\foo\\bar', 'C:\\foo'], true],
14+
[['C:\\foo', 'C:\\foo-bar'], false],
15+
[['C:\\foo-bar', 'C:\\foo'], false],
16+
[['foo', 'foo'], false],
17+
[['foo', 'bar'], false],
18+
[['foo', 'foo/bar'], false],
19+
[['foo/bar', 'foo'], false],
20+
[['foo', 'foo-bar'], false],
21+
[['foo-bar', 'foo'], false],
22+
]
23+
24+
describe('utils > isChildPath', () => {
25+
describe('should check child path correctly', () => {
26+
testCases.forEach(([source, expected]) => {
27+
it(JSON.stringify(source), () => {
28+
expect(isChildPath(...source)).toBe(expected)
29+
})
30+
})
31+
})
32+
})

‎packages/@vuepress/utils/src/index.ts

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export * as path from 'upath'
99

1010
export * from './hasExportDefault'
1111
export * from './hash'
12+
export * from './isChildPath'
1213
export * from './logger'
1314
export * from './renderHead'
1415
export * from './renderHeadAttrs'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import * as path from 'upath'
2+
3+
/**
4+
* Check if `child` is a sub path of `parent` or not. Return `true` if
5+
* they are the same path
6+
*/
7+
export const isChildPath = (child: string, parent: string): boolean => {
8+
const childPath = path.normalize(child)
9+
const parentPath = path.normalize(parent)
10+
// path.win32.isAbsolute could check both win32 and posix absolute path correctly
11+
if (!path.win32.isAbsolute(childPath) || !path.win32.isAbsolute(parentPath)) {
12+
return false
13+
}
14+
const relativePath = path.relative(parentPath, childPath)
15+
return relativePath === '' || !relativePath.startsWith('..')
16+
}

0 commit comments

Comments
 (0)
Please sign in to comment.