schemastore 0.0.9

Fetch and match files against the SchemaStore catalog
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#![doc = include_str!("../README.md")]

extern crate alloc;

use alloc::collections::BTreeMap;

use globset::{Glob, GlobSet, GlobSetBuilder};

use schema_catalog::Catalog;

/// The URL of the `SchemaStore` catalog.
pub const CATALOG_URL: &str = "https://www.schemastore.org/api/json/catalog.json";

/// Parse a `SchemaStore` catalog from a `serde_json::Value`.
///
/// # Errors
///
/// Returns an error if the value does not match the expected catalog schema.
pub fn parse_catalog(value: serde_json::Value) -> Result<Catalog, serde_json::Error> {
    schema_catalog::parse_catalog_value(value)
}

/// A compiled `GlobSet` paired with the schema URL and original pattern for each index.
struct CompiledGlobSet {
    set: GlobSet,
    /// `(url, original_pattern)` for each compiled glob, in index order.
    entries: Vec<(String, String)>,
}

impl CompiledGlobSet {
    /// Build from a list of `(pattern, url)` pairs.
    /// Invalid patterns are silently skipped.
    fn build(patterns: &[(String, String)]) -> Self {
        let mut builder = GlobSetBuilder::new();
        let mut entries = Vec::new();
        for (pattern, url) in patterns {
            if let Ok(glob) = Glob::new(pattern) {
                builder.add(glob);
                entries.push((url.clone(), pattern.clone()));
            }
        }
        Self {
            set: builder.build().unwrap_or_else(|_| GlobSet::empty()),
            entries,
        }
    }

    /// Return the URL of the first matching pattern, or `None`.
    fn find_match(&self, path: &str, file_name: &str) -> Option<&str> {
        let matches = self.set.matches(path);
        if let Some(&idx) = matches.first() {
            return Some(&self.entries[idx].0);
        }
        let matches = self.set.matches(file_name);
        if let Some(&idx) = matches.first() {
            return Some(&self.entries[idx].0);
        }
        None
    }

    /// Return the `(url, matched_pattern)` for the first matching pattern, or `None`.
    fn find_match_detailed(&self, path: &str, file_name: &str) -> Option<(&str, &str)> {
        let matches = self.set.matches(path);
        if let Some(&idx) = matches.first() {
            let (url, pat) = &self.entries[idx];
            return Some((url, pat));
        }
        let matches = self.set.matches(file_name);
        if let Some(&idx) = matches.first() {
            let (url, pat) = &self.entries[idx];
            return Some((url, pat));
        }
        None
    }
}

/// Details about a catalog entry, stored for detailed match lookups.
#[derive(Debug, Clone)]
struct CatalogEntryInfo {
    name: String,
    description: String,
    file_match: Vec<String>,
}

/// Information about how a schema was matched from a catalog.
#[derive(Debug)]
pub struct SchemaMatch<'a> {
    /// The schema URL.
    pub url: &'a str,
    /// The specific glob pattern (or exact filename) that matched.
    pub matched_pattern: &'a str,
    /// All `fileMatch` globs from the catalog entry.
    pub file_match: &'a [String],
    /// Human-readable schema name from the catalog.
    pub name: &'a str,
    /// Description from the catalog entry, if present.
    pub description: Option<&'a str>,
}

/// Compiled catalog for fast filename matching.
///
/// Uses a three-tier lookup to avoid brute-force glob matching:
/// 1. **Exact filename** — O(log n) `BTreeMap` lookup for bare filenames
/// 2. **Extension-indexed `GlobSet`s** — compiled automaton per extension
/// 3. **Fallback `GlobSet`** — compiled automaton for patterns that can't be indexed
pub struct CompiledCatalog {
    /// Tier 1: exact filename → schema URL.
    exact_filename: BTreeMap<String, String>,
    /// Tier 2: file extension → compiled glob set with URLs.
    extension_sets: BTreeMap<String, CompiledGlobSet>,
    /// Tier 3: patterns that can't be classified into the above tiers.
    fallback_set: CompiledGlobSet,
    /// Reverse lookup: schema URL → schema name.
    url_to_name: BTreeMap<String, String>,
    /// Reverse lookup: schema URL → catalog entry info.
    url_to_entry: BTreeMap<String, CatalogEntryInfo>,
}

/// Returns `true` if the pattern is a bare filename (no glob meta-characters or path separators).
fn is_bare_filename(pattern: &str) -> bool {
    !pattern.contains('/')
        && !pattern.contains('*')
        && !pattern.contains('?')
        && !pattern.contains('[')
}

/// Try to extract a file extension from a glob pattern.
///
/// Looks for the last `.ext` segment where `ext` is alphanumeric (e.g. `.yml`, `.json`).
/// Returns `None` for patterns like `*` or `Dockerfile` with no extension.
fn extract_extension(pattern: &str) -> Option<&str> {
    let file_part = pattern.rsplit('/').next().unwrap_or(pattern);
    let dot_pos = file_part.rfind('.')?;
    let ext = &file_part[dot_pos..];
    // Only index clean extensions (no glob chars inside the extension)
    if ext.contains('*') || ext.contains('?') || ext.contains('[') {
        return None;
    }
    // Map back to the original pattern slice
    let offset = pattern.len() - file_part.len() + dot_pos;
    Some(&pattern[offset..])
}

impl CompiledCatalog {
    /// Compile a catalog into a tiered matcher.
    ///
    /// Entries with no `fileMatch` patterns are skipped.
    /// Bare filename patterns are stored in an exact-match `BTreeMap`.
    /// Patterns with a deterministic extension are compiled into per-extension `GlobSet`s.
    /// Everything else goes into a fallback `GlobSet`.
    pub fn compile(catalog: &Catalog) -> Self {
        let mut exact_filename: BTreeMap<String, String> = BTreeMap::new();
        let mut ext_patterns: BTreeMap<String, Vec<(String, String)>> = BTreeMap::new();
        let mut fallback_patterns: Vec<(String, String)> = Vec::new();
        let mut url_to_name: BTreeMap<String, String> = BTreeMap::new();
        let mut url_to_entry: BTreeMap<String, CatalogEntryInfo> = BTreeMap::new();

        for schema in &catalog.schemas {
            url_to_name
                .entry(schema.url.clone())
                .or_insert_with(|| schema.name.clone());
            url_to_entry
                .entry(schema.url.clone())
                .or_insert_with(|| CatalogEntryInfo {
                    name: schema.name.clone(),
                    description: schema.description.clone(),
                    file_match: schema.file_match.clone(),
                });

            for pattern in &schema.file_match {
                if pattern.starts_with('!') {
                    continue;
                }

                if is_bare_filename(pattern) {
                    exact_filename
                        .entry(pattern.clone())
                        .or_insert_with(|| schema.url.clone());
                } else if let Some(ext) = extract_extension(pattern) {
                    ext_patterns
                        .entry(ext.to_ascii_lowercase())
                        .or_default()
                        .push((pattern.clone(), schema.url.clone()));
                } else {
                    fallback_patterns.push((pattern.clone(), schema.url.clone()));
                }
            }
        }

        let extension_sets = ext_patterns
            .into_iter()
            .map(|(ext, patterns)| (ext, CompiledGlobSet::build(&patterns)))
            .collect();

        Self {
            exact_filename,
            extension_sets,
            fallback_set: CompiledGlobSet::build(&fallback_patterns),
            url_to_name,
            url_to_entry,
        }
    }

    /// Find the schema URL for a given file path.
    ///
    /// `path` is the full path string, `file_name` is the basename.
    /// Returns the first matching schema URL, or `None`.
    pub fn find_schema(&self, path: &str, file_name: &str) -> Option<&str> {
        // Tier 1: exact filename lookup
        if let Some(url) = self.exact_filename.get(file_name) {
            return Some(url);
        }

        // Tier 2: extension-indexed GlobSet
        if let Some(dot_pos) = file_name.rfind('.') {
            let ext = &file_name[dot_pos..];
            if let Some(compiled) = self.extension_sets.get(&ext.to_ascii_lowercase())
                && let Some(url) = compiled.find_match(path, file_name)
            {
                return Some(url);
            }
        }

        // Tier 3: fallback GlobSet
        self.fallback_set.find_match(path, file_name)
    }

    /// Find the schema for a given file path, returning detailed match info.
    ///
    /// Returns the URL, the matched pattern, all `fileMatch` globs, the schema
    /// name, and the description from the catalog entry.
    pub fn find_schema_detailed<'a>(
        &'a self,
        path: &str,
        file_name: &'a str,
    ) -> Option<SchemaMatch<'a>> {
        // Tier 1: exact filename lookup
        if let Some(url) = self.exact_filename.get(file_name)
            && let Some(entry) = self.url_to_entry.get(url.as_str())
        {
            return Some(SchemaMatch {
                url,
                matched_pattern: file_name,
                file_match: &entry.file_match,
                name: &entry.name,
                description: if entry.description.is_empty() {
                    None
                } else {
                    Some(&entry.description)
                },
            });
        }

        // Tier 2: extension-indexed GlobSet
        if let Some(dot_pos) = file_name.rfind('.') {
            let ext = &file_name[dot_pos..];
            if let Some(compiled) = self.extension_sets.get(&ext.to_ascii_lowercase())
                && let Some((url, pattern)) = compiled.find_match_detailed(path, file_name)
                && let Some(entry) = self.url_to_entry.get(url)
            {
                return Some(SchemaMatch {
                    url,
                    matched_pattern: pattern,
                    file_match: &entry.file_match,
                    name: &entry.name,
                    description: if entry.description.is_empty() {
                        None
                    } else {
                        Some(&entry.description)
                    },
                });
            }
        }

        // Tier 3: fallback GlobSet
        if let Some((url, pattern)) = self.fallback_set.find_match_detailed(path, file_name)
            && let Some(entry) = self.url_to_entry.get(url)
        {
            return Some(SchemaMatch {
                url,
                matched_pattern: pattern,
                file_match: &entry.file_match,
                name: &entry.name,
                description: if entry.description.is_empty() {
                    None
                } else {
                    Some(&entry.description)
                },
            });
        }

        None
    }

    /// Look up the human-readable schema name for a given URL.
    pub fn schema_name(&self, url: &str) -> Option<&str> {
        self.url_to_name.get(url).map(String::as_str)
    }
}

#[cfg(test)]
mod tests {
    use schema_catalog::SchemaEntry;

    use super::*;

    fn test_catalog() -> Catalog {
        Catalog {
            version: 1,
            schemas: vec![
                SchemaEntry {
                    name: "tsconfig".into(),
                    description: String::new(),
                    url: "https://json.schemastore.org/tsconfig.json".into(),
                    source_url: None,
                    file_match: vec!["tsconfig.json".into(), "tsconfig.*.json".into()],
                    versions: BTreeMap::new(),
                },
                SchemaEntry {
                    name: "package.json".into(),
                    description: String::new(),
                    url: "https://json.schemastore.org/package.json".into(),
                    source_url: None,
                    file_match: vec!["package.json".into()],
                    versions: BTreeMap::new(),
                },
                SchemaEntry {
                    name: "no-match".into(),
                    description: String::new(),
                    url: "https://example.com/no-match.json".into(),
                    source_url: None,
                    file_match: vec![],
                    versions: BTreeMap::new(),
                },
            ],
            ..Catalog::default()
        }
    }

    #[test]
    fn compile_and_match_basename() {
        let catalog = test_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema("tsconfig.json", "tsconfig.json"),
            Some("https://json.schemastore.org/tsconfig.json")
        );
    }

    #[test]
    fn compile_and_match_with_path() {
        let catalog = test_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema("project/tsconfig.json", "tsconfig.json"),
            Some("https://json.schemastore.org/tsconfig.json")
        );
    }

    #[test]
    fn compile_and_match_glob_pattern() {
        let catalog = test_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema("tsconfig.build.json", "tsconfig.build.json"),
            Some("https://json.schemastore.org/tsconfig.json")
        );
    }

    #[test]
    fn no_match_returns_none() {
        let catalog = test_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert!(
            compiled
                .find_schema("unknown.json", "unknown.json")
                .is_none()
        );
    }

    #[test]
    fn empty_file_match_skipped() {
        let catalog = test_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert!(
            compiled
                .find_schema("no-match.json", "no-match.json")
                .is_none()
        );
    }

    fn github_workflow_catalog() -> Catalog {
        Catalog {
            version: 1,
            schemas: vec![SchemaEntry {
                name: "GitHub Workflow".into(),
                description: String::new(),
                url: "https://www.schemastore.org/github-workflow.json".into(),
                source_url: None,
                file_match: vec![
                    "**/.github/workflows/*.yml".into(),
                    "**/.github/workflows/*.yaml".into(),
                ],
                versions: BTreeMap::new(),
            }],
            ..Catalog::default()
        }
    }

    #[test]
    fn github_workflow_matches_relative_path() {
        let catalog = github_workflow_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema(".github/workflows/ci.yml", "ci.yml"),
            Some("https://www.schemastore.org/github-workflow.json")
        );
    }

    #[test]
    fn github_workflow_matches_dot_slash_prefix() {
        let catalog = github_workflow_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema("./.github/workflows/ci.yml", "ci.yml"),
            Some("https://www.schemastore.org/github-workflow.json")
        );
    }

    #[test]
    fn github_workflow_matches_nested() {
        let catalog = github_workflow_catalog();
        let compiled = CompiledCatalog::compile(&catalog);

        assert_eq!(
            compiled.find_schema("myproject/.github/workflows/deploy.yaml", "deploy.yaml"),
            Some("https://www.schemastore.org/github-workflow.json")
        );
    }

    #[test]
    fn parse_catalog_from_json() -> anyhow::Result<()> {
        let json = r#"{"version":1,"schemas":[{"name":"test","description":"desc","url":"https://example.com/s.json","fileMatch":["*.json"]}]}"#;
        let value: serde_json::Value = serde_json::from_str(json)?;
        let catalog = parse_catalog(value)?;
        assert_eq!(catalog.schemas.len(), 1);
        assert_eq!(catalog.schemas[0].name, "test");
        Ok(())
    }
}