From f899f8af1170fdf3d422202545245da1e1ae0c6f Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Thu, 26 Nov 2026 12:10:44 +0900 Subject: [PATCH 1/2] fix(migrate): skip gitignored directories in the Vitest v5 preflight The preflight read every source-like file under each package, including directories that .gitignore excludes, so large ignored folders made vp migrate slow and memory-heavy. Skip those directories, and check all child directories of a folder in one native call so the ignore files are parsed once per directory. Invalid .gitignore lines are skipped like Git does, so they no longer stop vp migrate. Closes #3585 --- crates/vp_migration/src/file_walker.rs | 108 +++++++++++++++--- crates/vp_migration/src/lib.rs | 4 +- packages/cli/binding/index.cjs | 1 + packages/cli/binding/index.d.cts | 7 ++ packages/cli/binding/src/migration.rs | 11 ++ .../src/migration/__tests__/vitest-v5.spec.ts | 15 +++ .../cli/src/migration/migrator/vitest-v5.ts | 21 +++- 7 files changed, 143 insertions(+), 24 deletions(-) diff --git a/crates/vp_migration/src/file_walker.rs b/crates/vp_migration/src/file_walker.rs index f67df0978a..86c3e8c539 100644 --- a/crates/vp_migration/src/file_walker.rs +++ b/crates/vp_migration/src/file_walker.rs @@ -1,6 +1,9 @@ use std::path::{Path, PathBuf}; -use ignore::{WalkBuilder, gitignore::GitignoreBuilder}; +use ignore::{ + WalkBuilder, + gitignore::{Gitignore, GitignoreBuilder}, +}; use vp_error::Error; /// File extensions to process for import rewriting. @@ -24,30 +27,74 @@ pub fn is_directory_gitignored(root: &Path, directory: &Path) -> Result { + Ok(gitignored_children(root, parent, &[name])?[0]) + } + _ => Ok(false), + } +} + +/// Return the child directory names of `parent` that are not gitignored. Uses the +/// same rules as [`is_directory_gitignored`], but reads the ignore files once. +pub fn unignored_child_directories( + root: &Path, + parent: &Path, + names: Vec, +) -> Result, Error> { + if names.is_empty() { + return Ok(names); + } + let ignored = gitignored_children(root, parent, &names)?; + Ok(names + .into_iter() + .zip(ignored) + .filter(|(_, ignored)| !ignored) + .map(|(name, _)| name) + .collect()) +} + +fn gitignored_children( + root: &Path, + parent: &Path, + names: &[impl AsRef], +) -> Result, Error> { + let relative = parent + .strip_prefix(root) + .map_err(|_| Error::InvalidArgument("Ignore target must be inside the root".into()))?; let mut current = root.to_path_buf(); let mut matchers = Vec::new(); for component in relative.components() { - let ignore_file = current.join(".gitignore"); - if ignore_file.is_file() { - let mut builder = GitignoreBuilder::new(¤t); - if let Some(error) = builder.add(&ignore_file) { - return Err(error.into()); - } - matchers.push(builder.build()?); - } + add_ignore_file(¤t, &mut matchers)?; current.push(component); - // Deeper ignore files take precedence. Check each directory before - // descending: a negation cannot re-include an ignored parent directory. - let matched = matchers - .iter() - .rev() - .map(|matcher| matcher.matched(¤t, true)) - .find(|matched| !matched.is_none()); - if matched.is_some_and(|matched| matched.is_ignore()) { - return Ok(true); + // Check each directory before descending: a negation cannot + // re-include an ignored parent directory. + if is_ignored(&matchers, ¤t) { + return Ok(vec![true; names.len()]); } } - Ok(false) + add_ignore_file(¤t, &mut matchers)?; + Ok(names.iter().map(|name| is_ignored(&matchers, ¤t.join(name))).collect()) +} + +fn add_ignore_file(directory: &Path, matchers: &mut Vec) -> Result<(), Error> { + let ignore_file = directory.join(".gitignore"); + if ignore_file.is_file() { + let mut builder = GitignoreBuilder::new(directory); + let _ = builder.add(&ignore_file); + matchers.push(builder.build()?); + } + Ok(()) +} + +/// Deeper ignore files take precedence. +fn is_ignored(matchers: &[Gitignore], directory: &Path) -> bool { + matchers + .iter() + .rev() + .map(|matcher| matcher.matched(directory, true)) + .find(|matched| !matched.is_none()) + .is_some_and(|matched| matched.is_ignore()) } /// Find all TypeScript/JavaScript files in a directory, respecting gitignore @@ -156,9 +203,32 @@ mod tests { expected, "root: {root_rules:?}, package: {package_rules:?}" ); + assert_eq!( + unignored_child_directories(temp.path(), &package, vec![".vitest".into()]) + .unwrap() + .is_empty(), + expected, + "batch root: {root_rules:?}, package: {package_rules:?}" + ); } } + #[test] + fn test_invalid_gitignore_lines_are_skipped() { + let temp = tempdir().unwrap(); + fs::write(temp.path().join(".gitignore"), "{a,b\n.vitest/\n").unwrap(); + assert!(is_directory_gitignored(temp.path(), &temp.path().join(".vitest")).unwrap()); + assert_eq!( + unignored_child_directories( + temp.path(), + temp.path(), + vec![".vitest".into(), "src".into()] + ) + .unwrap(), + vec!["src".to_string()] + ); + } + #[test] fn test_directory_gitignore_boundary() { let temp = tempdir().unwrap(); diff --git a/crates/vp_migration/src/lib.rs b/crates/vp_migration/src/lib.rs index ac7a69dd3f..1f2829c935 100644 --- a/crates/vp_migration/src/lib.rs +++ b/crates/vp_migration/src/lib.rs @@ -21,7 +21,9 @@ mod source_analysis; mod task_cache; mod vite_config; -pub use file_walker::{WalkResult, find_ts_files, is_directory_gitignored}; +pub use file_walker::{ + WalkResult, find_ts_files, is_directory_gitignored, unignored_child_directories, +}; pub use import_rewriter::{ BatchRewriteResult, RewriteImportsOptions, find_retained_vitest_packages, rewrite_imports_in_directory, rewrite_imports_in_directory_with_options, diff --git a/packages/cli/binding/index.cjs b/packages/cli/binding/index.cjs index 163e896a97..c405a33220 100644 --- a/packages/cli/binding/index.cjs +++ b/packages/cli/binding/index.cjs @@ -1134,6 +1134,7 @@ module.exports.rewriteScripts = nativeBinding.rewriteScripts; module.exports.run = nativeBinding.run; module.exports.runCommand = nativeBinding.runCommand; module.exports.shouldPrintVitePlusHeader = nativeBinding.shouldPrintVitePlusHeader; +module.exports.unignoredChildDirectories = nativeBinding.unignoredChildDirectories; module.exports.upsertJsonConfig = nativeBinding.upsertJsonConfig; module.exports.vitePlusHeader = nativeBinding.vitePlusHeader; module.exports.wrapLazyPlugins = nativeBinding.wrapLazyPlugins; diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 5eda8ec76d..e6f486f170 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -4265,6 +4265,13 @@ export interface TaskCacheConfigResult { manualTasks: Array; } +/** Return the child directory names of `parent` that inherited `.gitignore` rules keep. */ +export declare function unignoredChildDirectories( + root: string, + parent: string, + names: Array, +): Array; + /** * Set the value of a top-level config key in a vite config file (upsert) * diff --git a/packages/cli/binding/src/migration.rs b/packages/cli/binding/src/migration.rs index d43ec08d38..c96d0cd8b7 100644 --- a/packages/cli/binding/src/migration.rs +++ b/packages/cli/binding/src/migration.rs @@ -97,6 +97,17 @@ pub fn is_directory_gitignored(root: String, directory: String) -> Result .map_err(anyhow::Error::from)?) } +/// Return the child directory names of `parent` that inherited `.gitignore` rules keep. +#[napi] +pub fn unignored_child_directories( + root: String, + parent: String, + names: Vec, +) -> Result> { + Ok(vp_migration::unignored_child_directories(Path::new(&root), Path::new(&parent), names) + .map_err(anyhow::Error::from)?) +} + /// Rewrite scripts json content using rules from rules_yaml /// /// # Arguments diff --git a/packages/cli/src/migration/__tests__/vitest-v5.spec.ts b/packages/cli/src/migration/__tests__/vitest-v5.spec.ts index 4c14fd8b14..35c80f05bf 100644 --- a/packages/cli/src/migration/__tests__/vitest-v5.spec.ts +++ b/packages/cli/src/migration/__tests__/vitest-v5.spec.ts @@ -721,6 +721,21 @@ describe('Vitest v5 config compatibility', () => { }, ); + it('does not read files in gitignored directories', () => { + const input = `import { test } from 'vitest';\ntest.sequential('works', () => {});`; + const root = project({ + '.gitignore': 'static/\n', + 'unit.test.js': input, + 'static/assets/bundle.test.js': input, + }); + const plan = planProject(root); + expect(plan.inputs.has(path.join(root, 'unit.test.js'))).toBe(true); + expect(plan.inputs.has(path.join(root, 'static/assets/bundle.test.js'))).toBe(false); + applyVitestV5Migration(plan); + expect(fs.readFileSync(path.join(root, 'unit.test.js'), 'utf8')).toContain('concurrent: false'); + expect(fs.readFileSync(path.join(root, 'static/assets/bundle.test.js'), 'utf8')).toBe(input); + }); + it.each<{ projects: string; files: Record }>([ { projects: `[{ extends: true, test: {} }]`, files: {} }, { diff --git a/packages/cli/src/migration/migrator/vitest-v5.ts b/packages/cli/src/migration/migrator/vitest-v5.ts index cd46c944b8..de6dda5cb7 100644 --- a/packages/cli/src/migration/migrator/vitest-v5.ts +++ b/packages/cli/src/migration/migrator/vitest-v5.ts @@ -17,7 +17,7 @@ import { } from 'verkit'; import { isScalar, parseDocument, visit } from 'yaml'; -import { isDirectoryGitignored } from '../../../binding/index.js'; +import { isDirectoryGitignored, unignoredChildDirectories } from '../../../binding/index.js'; import cliPackage from '../../../package.json' with { type: 'json' }; import type { WorkspaceInfoOptional } from '../../types/index.ts'; import { PackageManager } from '../../types/index.ts'; @@ -132,15 +132,28 @@ function dependency(pkg: JsonObject, name: string): string | undefined { function filesInProject(directory: string): Array { const files: Array = []; + const ignoreRoot = findGitRoot(directory) ?? directory; const walk = (current: string) => { if (current !== directory && fs.existsSync(path.join(current, 'package.json'))) { return; } - for (const entry of fs.readdirSync(current, { withFileTypes: true })) { + const entries = fs.readdirSync(current, { withFileTypes: true }); + const directories = new Set( + unignoredChildDirectories( + ignoreRoot, + current, + entries + .filter((entry) => entry.isDirectory() && !SKIP_DIRS.has(entry.name)) + .map((entry) => entry.name), + ), + ); + for (const entry of entries) { const file = path.join(current, entry.name); // Never follow symlinks into another package or outside the workspace. - if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) { - walk(file); + if (entry.isDirectory()) { + if (directories.has(entry.name)) { + walk(file); + } } else if ( entry.isFile() && !['.pnp.cjs', '.pnp.loader.mjs'].includes(entry.name) && From 2a1ab53653691db69af4665f4cb19e0b0fc24262 Mon Sep 17 00:00:00 2001 From: JongKyung Lee Date: Thu, 26 Nov 2026 13:19:56 +0900 Subject: [PATCH 2/2] test(migrate): cover gitignored directories in the Vitest v5 snapshot --- .../migration_vitest_v5/snapshots.toml | 11 ++++++ .../snapshots/gitignored_directories.md | 39 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots/gitignored_directories.md diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots.toml index 4adb0246c1..e6be273f00 100644 --- a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots.toml +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots.toml @@ -624,3 +624,14 @@ steps = [ ["node", "verify-benchmarks.mjs"], ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], ] + +[[case]] +name = "gitignored_directories" +vp = "global" +comment = "Skip gitignored directories and invalid .gitignore lines without failing migration." +steps = [ + { argv = ["vpt", "write-file", ".gitignore", "{a,b\nstatic/\n"], snapshot = false }, + { argv = ["vpt", "write-file", "static/bundle.test.ts", "import { test } from 'vitest';\ntest.sequential('ignored', () => {});\n"], snapshot = false }, + ["vp", "migrate", "--no-interactive", "--no-hooks", "--no-agent", "--no-editor"], + ["vpt", "print-file", "example.test.ts", "static/bundle.test.ts", ".gitignore"], +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots/gitignored_directories.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots/gitignored_directories.md new file mode 100644 index 0000000000..d2dae8dd02 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/migration_vitest_v5/snapshots/gitignored_directories.md @@ -0,0 +1,39 @@ +# gitignored_directories + +Skip gitignored directories and invalid .gitignore lines without failing migration. + +## `vpt write-file .gitignore '{a,b +static/ +'` + + +## `vpt write-file static/bundle.test.ts 'import { test } from '\''vitest'\''; +test.sequential('\''ignored'\'', () => {}); +'` + + +## `vp migrate --no-interactive --no-hooks --no-agent --no-editor` + +``` +VITE+ - The Unified Toolchain for the Web + +◇ Migrated . to Vite+ +• Node pnpm +• 2 files had imports rewritten +``` + +## `vpt print-file example.test.ts static/bundle.test.ts .gitignore` + +``` +import { expect, test } from 'vite-plus/test'; + +test('compatibility', { concurrent: false }, async () => { + await expect(Promise.resolve(42)).resolves.toBe(42); + expect(() => { throw new Error(''); }).toThrow(/^$/); +}); +import { test } from 'vitest'; +test.sequential('ignored', () => {}); +{a,b +static/ +.vitest/ +```