mdbook-lint 0.2.0

A fast markdown linter for mdBook
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
//! Rule provider system and lint engine.

use crate::error::Result;
use crate::registry::RuleRegistry;
use serde_json::Value;

/// Trait for rule providers to register rules with the engine
pub trait RuleProvider: Send + Sync {
    /// Unique identifier for this rule provider
    fn provider_id(&self) -> &'static str;

    /// Human-readable description of this rule provider
    fn description(&self) -> &'static str;

    /// Version of this rule provider
    fn version(&self) -> &'static str;

    /// Register all rules from this provider with the registry
    fn register_rules(&self, registry: &mut RuleRegistry);

    /// Provider-specific configuration schema
    fn config_schema(&self) -> Option<Value> {
        None
    }

    /// List of rule IDs that this provider registers
    fn rule_ids(&self) -> Vec<&'static str> {
        Vec::new()
    }

    /// Provider initialization hook
    fn initialize(&self) -> Result<()> {
        Ok(())
    }
}

/// Registry for managing rule providers and creating engines
#[derive(Default)]
pub struct PluginRegistry {
    providers: Vec<Box<dyn RuleProvider>>,
}

impl PluginRegistry {
    /// Create a new empty plugin registry
    pub fn new() -> Self {
        Self {
            providers: Vec::new(),
        }
    }

    /// Register a rule provider
    pub fn register_provider(&mut self, provider: Box<dyn RuleProvider>) -> Result<()> {
        // Initialize the provider
        provider.initialize()?;

        // Check for duplicate provider IDs
        let provider_id = provider.provider_id();
        if self
            .providers
            .iter()
            .any(|p| p.provider_id() == provider_id)
        {
            return Err(crate::error::MdBookLintError::plugin_error(format!(
                "Provider with ID '{provider_id}' is already registered"
            )));
        }

        self.providers.push(provider);
        Ok(())
    }

    /// Get all registered providers
    pub fn providers(&self) -> &[Box<dyn RuleProvider>] {
        &self.providers
    }

    /// Get a provider by ID
    pub fn get_provider(&self, id: &str) -> Option<&dyn RuleProvider> {
        self.providers
            .iter()
            .find(|p| p.provider_id() == id)
            .map(|p| p.as_ref())
    }

    /// Create a rule registry with all registered providers
    pub fn create_rule_registry(&self) -> Result<RuleRegistry> {
        let mut registry = RuleRegistry::new();

        for provider in &self.providers {
            provider.register_rules(&mut registry);
        }

        Ok(registry)
    }

    /// Create a lint engine with all registered providers
    pub fn create_engine(&self) -> Result<LintEngine> {
        let registry = self.create_rule_registry()?;
        Ok(LintEngine::with_registry(registry))
    }

    /// List all available rule IDs from all providers
    pub fn available_rule_ids(&self) -> Vec<String> {
        let mut rule_ids = Vec::new();

        for provider in &self.providers {
            for rule_id in provider.rule_ids() {
                rule_ids.push(rule_id.to_string());
            }
        }

        rule_ids.sort();
        rule_ids.dedup();
        rule_ids
    }

    /// Get provider information for debugging/introspection
    pub fn provider_info(&self) -> Vec<ProviderInfo> {
        self.providers
            .iter()
            .map(|p| ProviderInfo {
                id: p.provider_id().to_string(),
                description: p.description().to_string(),
                version: p.version().to_string(),
                rule_count: p.rule_ids().len(),
            })
            .collect()
    }
}

/// Information about a registered provider (for debugging/introspection)
#[derive(Debug, Clone)]
pub struct ProviderInfo {
    pub id: String,
    pub description: String,
    pub version: String,
    pub rule_count: usize,
}

/// Markdown linting engine
pub struct LintEngine {
    registry: RuleRegistry,
}

impl LintEngine {
    /// Create a new lint engine with no rules
    pub fn new() -> Self {
        Self {
            registry: RuleRegistry::new(),
        }
    }

    /// Create a lint engine with an existing rule registry
    pub fn with_registry(registry: RuleRegistry) -> Self {
        Self { registry }
    }

    /// Get the underlying rule registry
    pub fn registry(&self) -> &RuleRegistry {
        &self.registry
    }

    /// Get a mutable reference to the rule registry
    pub fn registry_mut(&mut self) -> &mut RuleRegistry {
        &mut self.registry
    }

    /// Lint a document with all registered rules
    pub fn lint_document(&self, document: &crate::Document) -> Result<Vec<crate::Violation>> {
        self.registry.check_document_optimized(document)
    }

    /// Lint a document with specific configuration
    pub fn lint_document_with_config(
        &self,
        document: &crate::Document,
        config: &crate::Config,
    ) -> Result<Vec<crate::Violation>> {
        self.registry
            .check_document_optimized_with_config(document, config)
    }

    /// Lint content string directly (convenience method)
    pub fn lint_content(&self, content: &str, path: &str) -> Result<Vec<crate::Violation>> {
        let document = crate::Document::new(content.to_string(), std::path::PathBuf::from(path))?;
        self.lint_document(&document)
    }

    /// Get all available rule IDs
    pub fn available_rules(&self) -> Vec<&'static str> {
        self.registry.rule_ids()
    }

    /// Get enabled rules based on configuration
    pub fn enabled_rules(&self, config: &crate::Config) -> Vec<&dyn crate::rule::Rule> {
        self.registry.get_enabled_rules(config)
    }
}

impl Default for LintEngine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rule::{Rule, RuleCategory, RuleMetadata};
    use std::path::PathBuf;

    // Test rule for plugin system testing
    struct TestRule;

    impl Rule for TestRule {
        fn id(&self) -> &'static str {
            "TEST001"
        }
        fn name(&self) -> &'static str {
            "test-rule"
        }
        fn description(&self) -> &'static str {
            "A test rule"
        }
        fn metadata(&self) -> RuleMetadata {
            RuleMetadata::stable(RuleCategory::Structure)
        }
        fn check_with_ast<'a>(
            &self,
            _document: &crate::Document,
            _ast: Option<&'a comrak::nodes::AstNode<'a>>,
        ) -> Result<Vec<crate::Violation>> {
            Ok(vec![])
        }
    }

    // Test provider
    struct TestProvider;

    impl RuleProvider for TestProvider {
        fn provider_id(&self) -> &'static str {
            "test-provider"
        }
        fn description(&self) -> &'static str {
            "Test provider"
        }
        fn version(&self) -> &'static str {
            "0.1.0"
        }

        fn register_rules(&self, registry: &mut RuleRegistry) {
            registry.register(Box::new(TestRule));
        }

        fn rule_ids(&self) -> Vec<&'static str> {
            vec!["TEST001"]
        }
    }

    #[test]
    fn test_plugin_registry_basic() {
        let mut registry = PluginRegistry::new();
        assert_eq!(registry.providers().len(), 0);

        registry.register_provider(Box::new(TestProvider)).unwrap();
        assert_eq!(registry.providers().len(), 1);

        let provider = registry.get_provider("test-provider").unwrap();
        assert_eq!(provider.provider_id(), "test-provider");
        assert_eq!(provider.description(), "Test provider");
    }

    #[test]
    fn test_plugin_registry_duplicate_id() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();

        // Should fail with duplicate ID
        let result = registry.register_provider(Box::new(TestProvider));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("already registered")
        );
    }

    #[test]
    fn test_create_engine_from_registry() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();

        let engine = registry.create_engine().unwrap();
        let rule_ids = engine.available_rules();
        assert!(rule_ids.contains(&"TEST001"));
    }

    #[test]
    fn test_available_rule_ids() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();

        let rule_ids = registry.available_rule_ids();
        assert_eq!(rule_ids, vec!["TEST001"]);
    }

    #[test]
    fn test_provider_info() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();

        let info = registry.provider_info();
        assert_eq!(info.len(), 1);
        assert_eq!(info[0].id, "test-provider");
        assert_eq!(info[0].description, "Test provider");
        assert_eq!(info[0].version, "0.1.0");
        assert_eq!(info[0].rule_count, 1);
    }

    #[test]
    fn test_get_provider_not_found() {
        let registry = PluginRegistry::new();
        assert!(registry.get_provider("nonexistent").is_none());
    }

    #[test]
    fn test_create_rule_registry() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();

        let rule_registry = registry.create_rule_registry().unwrap();
        assert!(!rule_registry.is_empty());
    }

    // Test provider with initialization failure
    struct FailingProvider;

    impl RuleProvider for FailingProvider {
        fn provider_id(&self) -> &'static str {
            "failing-provider"
        }
        fn description(&self) -> &'static str {
            "Failing test provider"
        }
        fn version(&self) -> &'static str {
            "0.1.0"
        }
        fn register_rules(&self, _registry: &mut RuleRegistry) {}
        fn initialize(&self) -> Result<()> {
            Err(crate::error::MdBookLintError::plugin_error(
                "Initialization failed",
            ))
        }
    }

    #[test]
    fn test_provider_initialization_failure() {
        let mut registry = PluginRegistry::new();
        let result = registry.register_provider(Box::new(FailingProvider));
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Initialization failed")
        );
    }

    // Test provider with config schema
    struct ConfigurableProvider;

    impl RuleProvider for ConfigurableProvider {
        fn provider_id(&self) -> &'static str {
            "configurable-provider"
        }
        fn description(&self) -> &'static str {
            "Configurable test provider"
        }
        fn version(&self) -> &'static str {
            "0.1.0"
        }
        fn register_rules(&self, _registry: &mut RuleRegistry) {}
        fn config_schema(&self) -> Option<Value> {
            Some(serde_json::json!({
                "type": "object",
                "properties": {
                    "enabled": {"type": "boolean"}
                }
            }))
        }
    }

    #[test]
    fn test_provider_with_config_schema() {
        let provider = ConfigurableProvider;
        let schema = provider.config_schema();
        assert!(schema.is_some());
        let schema = schema.unwrap();
        assert_eq!(schema["type"], "object");
    }

    #[test]
    fn test_lint_engine_with_registry() {
        let mut rule_registry = RuleRegistry::new();
        rule_registry.register(Box::new(TestRule));

        let engine = LintEngine::with_registry(rule_registry);
        let rules = engine.available_rules();
        assert!(rules.contains(&"TEST001"));
    }

    #[test]
    fn test_lint_engine_api() {
        let mut registry = PluginRegistry::new();
        registry.register_provider(Box::new(TestProvider)).unwrap();
        let engine = registry.create_engine().unwrap();

        // Test basic content linting
        let _violations = engine.lint_content("# Test\n", "test.md").unwrap();

        // Test document linting
        let document =
            crate::Document::new("# Test".to_string(), PathBuf::from("test.md")).unwrap();
        let _violations = engine.lint_document(&document).unwrap();
    }
}