Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
]
Original file line number Diff line number Diff line change
@@ -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+ <version>
• Node <version> pnpm <version>
• 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/
```
108 changes: 89 additions & 19 deletions crates/vp_migration/src/file_walker.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -24,30 +27,74 @@ pub fn is_directory_gitignored(root: &Path, directory: &Path) -> Result<bool, Er
let relative = directory
.strip_prefix(root)
.map_err(|_| Error::InvalidArgument("Ignore target must be inside the root".into()))?;
match (directory.parent(), directory.file_name()) {
(Some(parent), Some(name)) if relative.components().next().is_some() => {
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<String>,
) -> Result<Vec<String>, 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<Path>],
) -> Result<Vec<bool>, 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(&current);
if let Some(error) = builder.add(&ignore_file) {
return Err(error.into());
}
matchers.push(builder.build()?);
}
add_ignore_file(&current, &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(&current, 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, &current) {
return Ok(vec![true; names.len()]);
}
}
Ok(false)
add_ignore_file(&current, &mut matchers)?;
Ok(names.iter().map(|name| is_ignored(&matchers, &current.join(name))).collect())
}

fn add_ignore_file(directory: &Path, matchers: &mut Vec<Gitignore>) -> 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
Expand Down Expand Up @@ -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();
Expand Down
4 changes: 3 additions & 1 deletion crates/vp_migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/cli/binding/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 7 additions & 0 deletions packages/cli/binding/index.d.cts
Original file line number Diff line number Diff line change
Expand Up @@ -4265,6 +4265,13 @@ export interface TaskCacheConfigResult {
manualTasks: Array<string>;
}

/** Return the child directory names of `parent` that inherited `.gitignore` rules keep. */
export declare function unignoredChildDirectories(
root: string,
parent: string,
names: Array<string>,
): Array<string>;

/**
* Set the value of a top-level config key in a vite config file (upsert)
*
Expand Down
11 changes: 11 additions & 0 deletions packages/cli/binding/src/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ pub fn is_directory_gitignored(root: String, directory: String) -> Result<bool>
.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<String>,
) -> Result<Vec<String>> {
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
Expand Down
15 changes: 15 additions & 0 deletions packages/cli/src/migration/__tests__/vitest-v5.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> }>([
{ projects: `[{ extends: true, test: {} }]`, files: {} },
{
Expand Down
21 changes: 17 additions & 4 deletions packages/cli/src/migration/migrator/vitest-v5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -132,15 +132,28 @@ function dependency(pkg: JsonObject, name: string): string | undefined {

function filesInProject(directory: string): Array<string> {
const files: Array<string> = [];
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) &&
Expand Down
Loading