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
3 changes: 3 additions & 0 deletions .changelog/invalid-source-glob-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Show an error instead of crashing the process when an `@source` pattern is not a valid glob (e.g. `@source not "./src/**/*.{js"`)
15 changes: 8 additions & 7 deletions crates/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,14 @@ pub struct CandidateWithPosition {
#[napi]
impl Scanner {
#[napi(constructor)]
pub fn new(opts: ScannerOptions) -> Self {
Self {
scanner: tailwindcss_oxide::Scanner::new(match opts.sources {
Some(sources) => sources.into_iter().map(Into::into).collect(),
None => vec![],
}),
}
pub fn new(opts: ScannerOptions) -> napi::Result<Self> {
let scanner = tailwindcss_oxide::Scanner::try_new(match opts.sources {
Some(sources) => sources.into_iter().map(Into::into).collect(),
None => vec![],
})
.map_err(|error| napi::Error::from_reason(error.to_string()))?;

Ok(Self { scanner })
}

#[napi]
Expand Down
110 changes: 87 additions & 23 deletions crates/oxide/src/scanner/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,41 @@ pub struct Scanner {
sources_scanned: bool,
}

/// An `@source` pattern that can't be compiled into a glob, e.g. `src/**/*.{js` with an unclosed
/// `{`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidSourceError(String);

impl std::fmt::Display for InvalidSourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}

impl std::error::Error for InvalidSourceError {}

/// The reason of a glob error, without the `error parsing glob '…'` prefix of `ignore`.
fn glob_error_reason(error: ignore::Error) -> String {
match error {
ignore::Error::Glob { err, .. } => err,
error => error.to_string(),
}
}

impl Scanner {
/// Creates a scanner for the given sources.
///
/// # Panics
///
/// Panics when a source pattern is not a valid glob. Use [`Scanner::try_new`] to handle that
/// error instead.
pub fn new(sources: Vec<PublicSourceEntry>) -> Self {
Self::try_new(sources).unwrap_or_else(|error| panic!("{error}"))
}

/// Creates a scanner for the given sources, or returns an error when a source pattern is not
/// a valid glob.
pub fn try_new(sources: Vec<PublicSourceEntry>) -> Result<Self, InvalidSourceError> {
init_tracing();

if *SHOULD_TRACE {
Expand All @@ -111,13 +144,13 @@ impl Scanner {
}
}

let walker = create_walker(&sources);
let walker = create_walker(&sources)?;

Self {
Ok(Self {
sources,
walker,
..Default::default()
}
})
}

pub fn scan(&mut self) -> Vec<String> {
Expand Down Expand Up @@ -711,17 +744,22 @@ fn walk_parallel(walker: &mut WalkBuilder) -> Vec<WalkEntry> {
///
/// This is the common setup shared between the full walker (with mtime tracking for re-scans)
/// and the parallel walker (without mtime tracking for the initial scan).
fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
///
/// Returns an error when a source pattern can't be compiled into a gitignore rule.
fn create_walker(sources: &Sources) -> Result<Option<WalkBuilder>, InvalidSourceError> {
let mut other_roots: FxHashSet<&PathBuf> = FxHashSet::default();
let mut first_root: Option<&PathBuf> = None;

let mut ignores: Vec<(&PathBuf, Vec<String>)> = Default::default();
let mut emit = |base, pattern| match ignores.last_mut() {
Some((prev_base, patterns)) if *prev_base == base => {
patterns.push(pattern);
// Gitignore rules per base. Each rule keeps the pattern of the source it comes from, so an
// invalid rule can be reported with the pattern of the `@source` instead of the rule itself.
// E.g.: `@source "src/**/*.{js"` results in the `!*.{js` rule.
let mut ignores: Vec<(&PathBuf, Vec<(String, &str)>)> = Default::default();
let mut emit = |base, rule, source_pattern| match ignores.last_mut() {
Some((prev_base, rules)) if *prev_base == base => {
rules.push((rule, source_pattern));
}
_ => {
ignores.push((base, vec![pattern]));
ignores.push((base, vec![(rule, source_pattern)]));
}
};

Expand All @@ -734,8 +772,11 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
other_roots.insert(base);
}
}
SourceEntry::Pattern { base, pattern } => {
let pattern = pattern.to_owned();
SourceEntry::Pattern {
base,
pattern: source_pattern,
} => {
let pattern = source_pattern.to_owned();

if first_root.is_none() {
first_root = Some(base);
Expand All @@ -745,18 +786,22 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {

if !pattern.contains("**") {
// Specific patterns should take precedence even over git-ignored files:
emit(base, format!("!{}", pattern));
emit(base, format!("!{}", pattern), source_pattern);
} else {
// Assumption: the pattern we receive will already be brace expanded. So
// `*.{html,jsx}` will result in two separate patterns: `*.html` and `*.jsx`.
if let Some(extension) = Path::new(&pattern).extension() {
// Extend auto source detection to include the extension
emit(base, format!("!*.{}", extension.to_string_lossy()));
emit(
base,
format!("!*.{}", extension.to_string_lossy()),
source_pattern,
);
}
}
}
SourceEntry::Ignored { base, pattern } => {
emit(base, pattern.to_owned());
emit(base, pattern.to_owned(), pattern);
}
SourceEntry::External { base } => {
if first_root.is_none() {
Expand All @@ -766,15 +811,19 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
}

// External sources should take precedence even over git-ignored files:
emit(base, "!/**/*".to_owned());
emit(base, "!/**/*".to_owned(), "/**/*");

// External sources should still disallow binary extensions:
emit(base, BINARY_EXTENSIONS_GLOB.clone());
emit(base, BINARY_EXTENSIONS_GLOB.clone(), "/**/*");
}
}
}

let mut builder = WalkBuilder::new(first_root?);
let Some(first_root) = first_root else {
return Ok(None);
};

let mut builder = WalkBuilder::new(first_root);

// We have to follow symlinks
builder.follow_links(true);
Expand Down Expand Up @@ -820,7 +869,7 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
// - my-project/apps/.gitignore
//
// Setting the require_git(true) flag conditionally allows us to do this.
for parent in first_root?.ancestors() {
for parent in first_root.ancestors() {
if parent.join(".git").exists() {
builder.require_git(true);
break;
Expand All @@ -837,12 +886,27 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
}

// Setup ignores based on `@source` definitions
for (base, patterns) in ignores {
for (base, rules) in ignores {
let mut ignore_builder = GitignoreBuilder::new(base);
for pattern in patterns {
ignore_builder.add_line(None, &pattern).unwrap();
for (rule, source_pattern) in rules {
ignore_builder.add_line(None, &rule).map_err(|error| {
// Rules like `!/src/` start with `!` and `/`, but they are relative to the `base`.
let pattern = base.join(source_pattern.trim_start_matches(['!', '/']));

InvalidSourceError(format!(
"The `@source` pattern `{}` is not a valid glob: {}",
pattern.display(),
glob_error_reason(error)
))
})?;
}
let ignore = ignore_builder.build().unwrap();
let ignore = ignore_builder.build().map_err(|error| {
InvalidSourceError(format!(
"The `@source` patterns in `{}` can't be compiled: {}",
base.display(),
glob_error_reason(error)
))
})?;
builder.add_gitignore(ignore);
}

Expand Down Expand Up @@ -903,7 +967,7 @@ fn create_walker(sources: &Sources) -> Option<WalkBuilder> {
true
});

Some(builder)
Ok(Some(builder))
}

#[cfg(test)]
Expand Down
44 changes: 44 additions & 0 deletions crates/oxide/tests/scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1800,6 +1800,50 @@ mod scanner {
assert_eq!(normalized_sources, vec!["**/*",]);
}

#[test]
fn it_should_error_on_invalid_source_globs() {
let dir = tempdir().unwrap().into_path();
create_files_in(&dir, &[("src/index.html", "")]);
let base = dunce::canonicalize(&dir).unwrap();

let unclosed = "unclosed alternate group; missing '}' (maybe escape '{' with '[{]'?)";
let unopened = "unopened alternate group; missing '{' (maybe escape '}' with '[}]'?)";

let mut cases = vec![
("@source not 'src/**/*.{js'", "src/**/*.{js", unclosed),
("@source 'src/**/*.{js'", "src/**/*.{js", unclosed),
("@source 'src/*.{js'", "src/*.{js", unclosed),
("@source not 'src/a}'", "src/a}", unopened),
(
"@source not 'src/[z-a].html'",
"src/[z-a].html",
"invalid range; 'z' > 'a'",
),
];

// A `\` is a path separator on Windows
#[cfg(not(windows))]
cases.push(("@source not 'src/a\\'", "src/a\\", "dangling '\\'"));

for (directive, pattern, reason) in cases {
let error = Scanner::try_new(vec![
public_source_entry_from_pattern(dir.clone(), "@source '**/*'"),
public_source_entry_from_pattern(dir.clone(), directive),
])
.expect_err(directive);

assert_eq!(
error.to_string().replace('\\', "/"),
format!(
"The `@source` pattern `{}` is not a valid glob: {reason}",
base.join(pattern).display()
)
.replace('\\', "/"),
"{directive}"
);
}
}

#[test]
fn it_should_include_defined_extensions_that_are_ignored_by_default() {
let ScanResult {
Expand Down
17 changes: 17 additions & 0 deletions packages/@tailwindcss-postcss/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,23 @@ describe('error recovery', () => {
)
})

test('fails the build when an `@source` pattern is not a valid glob, instead of crashing the process', async () => {
let from = path.join(dir, 'index.css')
let processor = postcss([tailwindcss({ base: dir, optimize: false })])

await writeFile(
path.join(dir, 'dependency.css'),
css`
@source not "./src/**/*.{js";
@tailwind utilities;
`,
)

await expect(processor.process(await readFile(from, 'utf8'), { from })).rejects.toThrow(
/The `@source` pattern `.*src[/\\]\*\*\/\*\.\{js` is not a valid glob: unclosed alternate group/,
)
})

test('keeps serving the last optimized output when a rebuild fails with `optimize` enabled', async () => {
let from = path.join(dir, 'index.css')
let processor = postcss([tailwindcss({ base: dir, optimize: true })])
Expand Down