Skip to content

Commit

Permalink
feat(utils): add isChildPath util
Browse files Browse the repository at this point in the history
  • Loading branch information
meteorlxy committed Jun 17, 2022
1 parent d0217f8 commit 698e599
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
32 changes: 32 additions & 0 deletions packages/@vuepress/utils/__tests__/isChildPath.spec.ts
@@ -0,0 +1,32 @@
import { isChildPath } from '@vuepress/utils'

const testCases: [[string, string], boolean][] = [
[['/foo', '/foo'], true],
[['/foo', '/bar'], false],
[['/foo', '/foo/bar'], false],
[['/foo/bar', '/foo'], true],
[['/foo', '/foo-bar'], false],
[['/foo-bar', '/foo'], false],
[['C:\\foo', 'C:\\foo'], true],
[['C:\\foo', 'C:\\bar'], false],
[['C:\\foo', 'C:\\foo\\bar'], false],
[['C:\\foo\\bar', 'C:\\foo'], true],
[['C:\\foo', 'C:\\foo-bar'], false],
[['C:\\foo-bar', 'C:\\foo'], false],
[['foo', 'foo'], false],
[['foo', 'bar'], false],
[['foo', 'foo/bar'], false],
[['foo/bar', 'foo'], false],
[['foo', 'foo-bar'], false],
[['foo-bar', 'foo'], false],
]

describe('utils > isChildPath', () => {
describe('should check child path correctly', () => {
testCases.forEach(([source, expected]) => {
it(JSON.stringify(source), () => {
expect(isChildPath(...source)).toBe(expected)
})
})
})
})
1 change: 1 addition & 0 deletions packages/@vuepress/utils/src/index.ts
Expand Up @@ -9,6 +9,7 @@ export * as path from 'upath'

export * from './hasExportDefault'
export * from './hash'
export * from './isChildPath'
export * from './logger'
export * from './renderHead'
export * from './renderHeadAttrs'
Expand Down
16 changes: 16 additions & 0 deletions packages/@vuepress/utils/src/isChildPath.ts
@@ -0,0 +1,16 @@
import * as path from 'upath'

/**
* Check if `child` is a sub path of `parent` or not. Return `true` if
* they are the same path
*/
export const isChildPath = (child: string, parent: string): boolean => {
const childPath = path.normalize(child)
const parentPath = path.normalize(parent)
// path.win32.isAbsolute could check both win32 and posix absolute path correctly
if (!path.win32.isAbsolute(childPath) || !path.win32.isAbsolute(parentPath)) {
return false
}
const relativePath = path.relative(parentPath, childPath)
return relativePath === '' || !relativePath.startsWith('..')
}

0 comments on commit 698e599

Please sign in to comment.