Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/poor-sites-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'vite-plugin-static-copy': patch
---

improve performance of internal `isSubdirectoryOrEqual` function
39 changes: 38 additions & 1 deletion src/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,43 @@
import { describe, expect, test } from 'vitest'
import { groupTargetsByDirectoryTree } from './utils'
import { isSubdirectoryOrEqual, groupTargetsByDirectoryTree } from './utils'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import os from 'node:os'

const _dirname = path.dirname(fileURLToPath(import.meta.url))
const isWindows = os.platform() === 'win32'

describe('isSubdirectoryOrEqual', () => {
const cases: readonly [a: string, b: string, expected: boolean][] = [
['./', '.', true],
['./', './', true],
['.', './', true],
['./index.ts', './', true],
['./foo/', './', true],
['./foo/bar', './', true],
['./foo/bar.js', './', true],
['..', './', false],
['../', './', false],
['../test', './', false],
['../test/', './', false],
...(isWindows
? ([
['C:/', 'C:/', true],
['C:\\', 'C:/', true],
['C:/', 'D:/', false],
['C:\\', 'D:/', false]
] satisfies readonly [string, string, boolean][])
: [])
]

const resolve = (p: string) => path.resolve(_dirname, p)

for (const [a, b, expected] of cases) {
test(`isSubdirectoryOrEqual(${a}, ${b})`, () => {
expect(isSubdirectoryOrEqual(resolve(a), resolve(b))).toBe(expected)
})
}
})

describe('groupTargetsByDirectoryTree', () => {
const defineCase = (input: string[], expected: string[][]) => ({
Expand Down
14 changes: 8 additions & 6 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@ type ResolvedTarget = SimpleTarget & {
resolvedSrc: string
}

const isSubdirectoryOrEqual = (a: string, b: string) => {
const relative = path.relative(b, a)
return (
!relative ||
(!relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
)
/**
* Whether a is a subdirectory of b or equal to b
*
* @param a absolute path
* @param b absolute path
*/
export const isSubdirectoryOrEqual = (a: string, b: string) => {
return a.startsWith(b + path.sep) || a === b
}

export const groupTargetsByDirectoryTree = <T extends { resolvedDest: string }>(
Expand Down