mdt_core 0.7.0

update markdown content anywhere using comments as template tags
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
use std::collections::HashMap;
use std::collections::HashSet;
use std::hash::BuildHasher;
use std::path::PathBuf;

use crate::Argument;
use crate::BlockType;
use crate::MdtError;
use crate::MdtResult;
use crate::Transformer;
use crate::TransformerType;
use crate::config::PaddingConfig;
use crate::project::ConsumerEntry;
use crate::project::ProjectContext;
use crate::project::ProviderEntry;

/// A warning about undefined template variables in a provider block.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TemplateWarning {
	/// Path to the file containing the provider block that uses the undefined
	/// variables.
	pub provider_file: PathBuf,
	/// Name of the provider block.
	pub block_name: String,
	/// The undefined variable references found in the template (e.g.,
	/// `["pkgg.version", "typo"]`).
	pub undefined_variables: Vec<String>,
}

/// Result of checking a project for stale consumers.
#[derive(Debug)]
#[non_exhaustive]
pub struct CheckResult {
	/// Consumer entries that are out of date.
	pub stale: Vec<StaleEntry>,
	/// Errors encountered while rendering templates. These are collected
	/// instead of aborting so that the check reports all problems at once.
	pub render_errors: Vec<RenderError>,
	/// Warnings about undefined template variables in provider blocks.
	pub warnings: Vec<TemplateWarning>,
}

impl CheckResult {
	/// Returns true if all consumers are up to date and no errors occurred.
	pub fn is_ok(&self) -> bool {
		self.stale.is_empty() && self.render_errors.is_empty()
	}

	/// Returns true if there are template render errors.
	pub fn has_errors(&self) -> bool {
		!self.render_errors.is_empty()
	}

	/// Returns true if there are warnings about undefined template variables.
	pub fn has_warnings(&self) -> bool {
		!self.warnings.is_empty()
	}
}

/// A template render error associated with a specific consumer block.
#[derive(Debug)]
#[non_exhaustive]
pub struct RenderError {
	/// Path to the file containing the consumer block.
	pub file: PathBuf,
	/// Name of the block whose template failed to render.
	pub block_name: String,
	/// The error message from the template engine.
	pub message: String,
	/// 1-indexed line number of the consumer's opening tag.
	pub line: usize,
	/// 1-indexed column number of the consumer's opening tag.
	pub column: usize,
}

/// A consumer entry that is out of date.
#[derive(Debug)]
#[non_exhaustive]
pub struct StaleEntry {
	/// Path to the file containing the stale consumer.
	pub file: PathBuf,
	/// Name of the block that is out of date.
	pub block_name: String,
	/// The current content between the consumer's tags.
	pub current_content: String,
	/// The expected content after applying provider content and transformers.
	pub expected_content: String,
	/// 1-indexed line number of the consumer's opening tag.
	pub line: usize,
	/// 1-indexed column number of the consumer's opening tag.
	pub column: usize,
}

/// Result of updating a project.
#[derive(Debug)]
#[non_exhaustive]
pub struct UpdateResult {
	/// Files that were modified and their new content.
	pub updated_files: HashMap<PathBuf, String>,
	/// Number of consumer blocks that were updated.
	pub updated_count: usize,
	/// Warnings about undefined template variables in provider blocks.
	pub warnings: Vec<TemplateWarning>,
}

/// Render provider content through minijinja using the given data context.
/// If data is empty or the content has no template syntax, returns the
/// content unchanged.
#[allow(clippy::implicit_hasher)]
pub fn render_template(
	content: &str,
	data: &HashMap<String, serde_json::Value>,
) -> MdtResult<String> {
	if data.is_empty() || !has_template_syntax(content) {
		return Ok(content.to_string());
	}

	let mut env = minijinja::Environment::new();
	env.set_keep_trailing_newline(true);
	env.set_undefined_behavior(minijinja::UndefinedBehavior::Chainable);
	env.add_template("__inline__", content)
		.map_err(|e| MdtError::TemplateRender(e.to_string()))?;

	let template = env
		.get_template("__inline__")
		.map_err(|e| MdtError::TemplateRender(e.to_string()))?;

	let ctx = minijinja::Value::from_serialize(data);
	template
		.render(ctx)
		.map_err(|e| MdtError::TemplateRender(e.to_string()))
}

/// Find template variables referenced in `content` that are not defined in
/// `data`. Returns the list of undefined variable names (with nested
/// attribute access like `"pkgg.version"`). This uses minijinja's static
/// analysis to detect undeclared variables, so it does not depend on
/// runtime control flow.
///
/// Returns an empty `Vec` when `data` is empty (no data configured means
/// template rendering is a no-op) or when the content has no template
/// syntax.
#[allow(clippy::implicit_hasher)]
pub fn find_undefined_variables(
	content: &str,
	data: &HashMap<String, serde_json::Value>,
) -> Vec<String> {
	if data.is_empty() || !has_template_syntax(content) {
		return Vec::new();
	}

	let mut env = minijinja::Environment::new();
	env.set_keep_trailing_newline(true);
	// We only need the template for static analysis, undefined behavior
	// doesn't affect undeclared_variables.
	let Ok(()) = env.add_template("__inline__", content) else {
		return Vec::new();
	};
	let Ok(template) = env.get_template("__inline__") else {
		return Vec::new();
	};

	// Get all undeclared variables with nested access (e.g., "pkg.version").
	let undeclared: HashSet<String> = template.undeclared_variables(true);

	// Also get top-level names so we can check both "pkg.version" (nested)
	// and "pkg" (top-level).
	let top_level_names: HashSet<String> = data.keys().cloned().collect();

	let mut undefined: Vec<String> = undeclared
		.into_iter()
		.filter(|var| {
			// Extract the top-level namespace from the variable reference.
			let top_level = var.split('.').next().unwrap_or(var);
			// A variable is truly undefined if its top-level namespace is
			// not present in the data context. Variables like "loop" or
			// "range" are minijinja builtins that we should not warn about.
			!top_level_names.contains(top_level) && !is_builtin_variable(top_level)
		})
		.collect();

	undefined.sort();
	undefined
}

/// Check whether a variable name is a minijinja builtin that should not
/// trigger an "undefined variable" warning.
fn is_builtin_variable(name: &str) -> bool {
	matches!(
		name,
		"loop" | "self" | "super" | "true" | "false" | "none" | "namespace" | "range" | "dict"
	)
}

/// Check whether content contains minijinja template syntax.
fn has_template_syntax(content: &str) -> bool {
	content.contains("{{") || content.contains("{%") || content.contains("{#")
}

/// Build a data context that merges base project data with block-specific
/// positional arguments. Consumer argument values are bound to the provider's
/// declared parameter names, with block args taking precedence over data
/// variables.
/// Build a data context that merges base project data with block-specific
/// positional arguments. Returns `None` if the argument count doesn't match.
pub fn build_render_context<S: BuildHasher + Clone>(
	base_data: &HashMap<String, serde_json::Value, S>,
	provider: &ProviderEntry,
	consumer: &ConsumerEntry,
) -> Option<HashMap<String, serde_json::Value, S>> {
	let param_count = provider.block.arguments.len();
	let arg_count = consumer.block.arguments.len();

	if param_count != arg_count && (param_count > 0 || arg_count > 0) {
		return None;
	}

	if provider.block.arguments.is_empty() {
		return Some(base_data.clone());
	}

	let mut data = base_data.clone();
	for (name, value) in provider
		.block
		.arguments
		.iter()
		.zip(consumer.block.arguments.iter())
	{
		data.insert(name.clone(), serde_json::Value::String(value.clone()));
	}
	Some(data)
}

/// Check whether all consumer blocks in the project are up to date.
/// Consumer blocks that reference non-existent providers are silently skipped.
/// Template render errors are collected rather than aborting, so the check
/// reports all problems in a single pass.
pub fn check_project(ctx: &ProjectContext) -> MdtResult<CheckResult> {
	let mut stale = Vec::new();
	let mut render_errors = Vec::new();
	let warnings = collect_template_warnings(ctx);

	for consumer in &ctx.project.consumers {
		match consumer.block.r#type {
			BlockType::Consumer => {
				let Some(provider) = ctx.project.providers.get(&consumer.block.name) else {
					continue;
				};

				let Some(render_data) = build_render_context(&ctx.data, provider, consumer) else {
					render_errors.push(RenderError {
						file: consumer.file.clone(),
						block_name: consumer.block.name.clone(),
						message: format!(
							"argument count mismatch: provider `{}` declares {} parameter(s), but \
							 consumer passes {}",
							consumer.block.name,
							provider.block.arguments.len(),
							consumer.block.arguments.len(),
						),
						line: consumer.block.opening.start.line,
						column: consumer.block.opening.start.column,
					});
					continue;
				};
				let rendered = match render_template(&provider.content, &render_data) {
					Ok(r) => r,
					Err(e) => {
						render_errors.push(RenderError {
							file: consumer.file.clone(),
							block_name: consumer.block.name.clone(),
							message: e.to_string(),
							line: consumer.block.opening.start.line,
							column: consumer.block.opening.start.column,
						});
						continue;
					}
				};
				let mut expected = apply_transformers_with_data(
					&rendered,
					&consumer.block.transformers,
					Some(&render_data),
				);
				if let Some(padding) = &ctx.padding {
					expected = pad_content_with_config(&expected, &consumer.content, padding);
				}

				if consumer.content != expected {
					stale.push(StaleEntry {
						file: consumer.file.clone(),
						block_name: consumer.block.name.clone(),
						current_content: consumer.content.clone(),
						expected_content: expected,
						line: consumer.block.opening.start.line,
						column: consumer.block.opening.start.column,
					});
				}
			}
			BlockType::Inline => {
				let Some(template) = consumer.block.arguments.first() else {
					render_errors.push(RenderError {
						file: consumer.file.clone(),
						block_name: consumer.block.name.clone(),
						message: "inline block requires one template argument, e.g. <!-- \
						          {~name:\"{{ pkg.version }}\"} -->"
							.to_string(),
						line: consumer.block.opening.start.line,
						column: consumer.block.opening.start.column,
					});
					continue;
				};
				let rendered = match render_template(template, &ctx.data) {
					Ok(r) => r,
					Err(e) => {
						render_errors.push(RenderError {
							file: consumer.file.clone(),
							block_name: consumer.block.name.clone(),
							message: e.to_string(),
							line: consumer.block.opening.start.line,
							column: consumer.block.opening.start.column,
						});
						continue;
					}
				};
				let expected = apply_transformers_with_data(
					&rendered,
					&consumer.block.transformers,
					Some(&ctx.data),
				);

				if consumer.content != expected {
					stale.push(StaleEntry {
						file: consumer.file.clone(),
						block_name: consumer.block.name.clone(),
						current_content: consumer.content.clone(),
						expected_content: expected,
						line: consumer.block.opening.start.line,
						column: consumer.block.opening.start.column,
					});
				}
			}
			BlockType::Provider => {}
		}
	}

	Ok(CheckResult {
		stale,
		render_errors,
		warnings,
	})
}

/// Compute the updated file contents for all consumer blocks.
pub fn compute_updates(ctx: &ProjectContext) -> MdtResult<UpdateResult> {
	let mut file_contents: HashMap<PathBuf, String> = HashMap::new();
	let mut updated_count = 0;
	let warnings = collect_template_warnings(ctx);

	// Group consumers by file
	let mut consumers_by_file: HashMap<PathBuf, Vec<&ConsumerEntry>> = HashMap::new();
	for consumer in &ctx.project.consumers {
		consumers_by_file
			.entry(consumer.file.clone())
			.or_default()
			.push(consumer);
	}

	for (file, consumers) in &consumers_by_file {
		let original = if let Some(content) = file_contents.get(file) {
			content.clone()
		} else {
			std::fs::read_to_string(file)?
		};

		let mut result = original.clone();
		let mut had_update = false;
		// Process consumers in reverse offset order so earlier replacements
		// don't shift the positions of later ones.
		let mut sorted_consumers: Vec<&&ConsumerEntry> = consumers.iter().collect();
		sorted_consumers
			.sort_by(|a, b| b.block.opening.end.offset.cmp(&a.block.opening.end.offset));

		for consumer in sorted_consumers {
			let new_content = match consumer.block.r#type {
				BlockType::Consumer => {
					let Some(provider) = ctx.project.providers.get(&consumer.block.name) else {
						continue;
					};

					let Some(render_data) = build_render_context(&ctx.data, provider, consumer)
					else {
						continue; // Argument count mismatch — skip this consumer.
					};
					let rendered = render_template(&provider.content, &render_data)?;
					let mut new_content = apply_transformers_with_data(
						&rendered,
						&consumer.block.transformers,
						Some(&render_data),
					);
					if let Some(padding) = &ctx.padding {
						new_content =
							pad_content_with_config(&new_content, &consumer.content, padding);
					}
					new_content
				}
				BlockType::Inline => {
					let Some(template) = consumer.block.arguments.first() else {
						continue;
					};
					let rendered = render_template(template, &ctx.data)?;
					apply_transformers_with_data(
						&rendered,
						&consumer.block.transformers,
						Some(&ctx.data),
					)
				}
				BlockType::Provider => continue,
			};

			if consumer.content != new_content {
				let start = consumer.block.opening.end.offset;
				let end = consumer.block.closing.start.offset;

				if start <= end && end <= result.len() {
					let mut buf =
						String::with_capacity(result.len() - (end - start) + new_content.len());
					buf.push_str(&result[..start]);
					buf.push_str(&new_content);
					buf.push_str(&result[end..]);
					result = buf;
					had_update = true;
					updated_count += 1;
				}
			}
		}

		if had_update {
			file_contents.insert(file.clone(), result);
		}
	}

	Ok(UpdateResult {
		updated_files: file_contents,
		updated_count,
		warnings,
	})
}

/// Collect warnings about undefined template variables across all provider
/// blocks that have at least one consumer. Each provider is checked at most
/// once even if it has multiple consumers.
fn collect_template_warnings(ctx: &ProjectContext) -> Vec<TemplateWarning> {
	let mut warnings = Vec::new();
	let mut checked_providers: HashSet<String> = HashSet::new();

	// Only check providers that are actually referenced by consumers.
	for consumer in &ctx.project.consumers {
		if consumer.block.r#type != BlockType::Consumer {
			continue;
		}
		let name = &consumer.block.name;
		if checked_providers.contains(name) {
			continue;
		}
		checked_providers.insert(name.clone());

		let Some(provider) = ctx.project.providers.get(name) else {
			continue;
		};

		// Provider params are known variables — add them to the data context
		// so they don't trigger false undefined-variable warnings.
		let data_with_params = if provider.block.arguments.is_empty() {
			std::borrow::Cow::Borrowed(&ctx.data)
		} else {
			let mut data = ctx.data.clone();
			for param in &provider.block.arguments {
				data.entry(param.clone())
					.or_insert(serde_json::Value::String(String::new()));
			}
			std::borrow::Cow::Owned(data)
		};

		let undefined = find_undefined_variables(&provider.content, &data_with_params);
		if !undefined.is_empty() {
			warnings.push(TemplateWarning {
				provider_file: provider.file.clone(),
				block_name: name.clone(),
				undefined_variables: undefined,
			});
		}
	}

	warnings
}

/// Write the updated contents back to disk.
pub fn write_updates(updates: &UpdateResult) -> MdtResult<()> {
	for (path, content) in &updates.updated_files {
		std::fs::write(path, content)?;
	}
	Ok(())
}

/// Apply a sequence of transformers to content.
pub fn apply_transformers(content: &str, transformers: &[Transformer]) -> String {
	apply_transformers_with_data(content, transformers, None)
}

/// Apply a sequence of transformers to content with an optional data context.
/// The data context is used by data-dependent transformers like `if`.
#[allow(clippy::implicit_hasher)]
pub fn apply_transformers_with_data(
	content: &str,
	transformers: &[Transformer],
	data: Option<&HashMap<String, serde_json::Value>>,
) -> String {
	let mut result = content.to_string();

	for transformer in transformers {
		result = apply_transformer(&result, transformer, data);
	}

	result
}

fn apply_transformer(
	content: &str,
	transformer: &Transformer,
	data: Option<&HashMap<String, serde_json::Value>>,
) -> String {
	match transformer.r#type {
		TransformerType::Trim => content.trim().to_string(),
		TransformerType::TrimStart => content.trim_start().to_string(),
		TransformerType::TrimEnd => content.trim_end().to_string(),
		TransformerType::Indent => {
			let indent_str = get_string_arg(&transformer.args, 0).unwrap_or_default();
			let include_empty = get_bool_arg(&transformer.args, 1).unwrap_or(false);
			content
				.lines()
				.map(|line| {
					if line.is_empty() && !include_empty {
						String::new()
					} else {
						format!("{indent_str}{line}")
					}
				})
				.collect::<Vec<_>>()
				.join("\n")
		}
		TransformerType::Prefix => {
			let prefix = get_string_arg(&transformer.args, 0).unwrap_or_default();
			format!("{prefix}{content}")
		}
		TransformerType::Wrap => {
			let wrapper = get_string_arg(&transformer.args, 0).unwrap_or_default();
			format!("{wrapper}{content}{wrapper}")
		}
		TransformerType::CodeBlock => {
			let lang = get_string_arg(&transformer.args, 0).unwrap_or_default();
			format!("```{lang}\n{content}\n```")
		}
		TransformerType::Code => {
			format!("`{content}`")
		}
		TransformerType::Replace => {
			let search = get_string_arg(&transformer.args, 0).unwrap_or_default();
			let replacement = get_string_arg(&transformer.args, 1).unwrap_or_default();
			content.replace(&search, &replacement)
		}
		TransformerType::Suffix => {
			let suffix = get_string_arg(&transformer.args, 0).unwrap_or_default();
			format!("{content}{suffix}")
		}
		TransformerType::LinePrefix => {
			let prefix = get_string_arg(&transformer.args, 0).unwrap_or_default();
			let include_empty = get_bool_arg(&transformer.args, 1).unwrap_or(false);
			content
				.lines()
				.map(|line| {
					if line.is_empty() && !include_empty {
						String::new()
					} else if line.is_empty() {
						prefix.trim_end().to_string()
					} else {
						format!("{prefix}{line}")
					}
				})
				.collect::<Vec<_>>()
				.join("\n")
		}
		TransformerType::LineSuffix => {
			let suffix = get_string_arg(&transformer.args, 0).unwrap_or_default();
			let include_empty = get_bool_arg(&transformer.args, 1).unwrap_or(false);
			content
				.lines()
				.map(|line| {
					if line.is_empty() && !include_empty {
						String::new()
					} else if line.is_empty() {
						suffix.trim_start().to_string()
					} else {
						format!("{line}{suffix}")
					}
				})
				.collect::<Vec<_>>()
				.join("\n")
		}
		TransformerType::If => {
			let path = get_string_arg(&transformer.args, 0).unwrap_or_default();
			if is_data_path_truthy(data, &path) {
				content.to_string()
			} else {
				String::new()
			}
		}
	}
}

/// Look up a dot-separated path in the data context and return whether the
/// value is "truthy". A value is truthy if it exists and is not `false`,
/// `null`, `""`, or `0`.
fn is_data_path_truthy(data: Option<&HashMap<String, serde_json::Value>>, path: &str) -> bool {
	let Some(data) = data else {
		return false;
	};

	let mut parts = path.split('.');
	let Some(root) = parts.next() else {
		return false;
	};

	let Some(mut current) = data.get(root) else {
		return false;
	};

	for part in parts {
		match current {
			serde_json::Value::Object(map) => {
				let Some(next) = map.get(part) else {
					return false;
				};
				current = next;
			}
			_ => return false,
		}
	}

	is_json_value_truthy(current)
}

/// Check whether a JSON value is truthy.
/// A value is falsy if it is `null`, `false`, `""`, `0`, or `0.0`.
/// Everything else (including non-empty arrays and objects) is truthy.
fn is_json_value_truthy(value: &serde_json::Value) -> bool {
	match value {
		serde_json::Value::Null => false,
		serde_json::Value::Bool(b) => *b,
		serde_json::Value::Number(n) => {
			// 0 and 0.0 are falsy
			if let Some(i) = n.as_i64() {
				i != 0
			} else if let Some(u) = n.as_u64() {
				u != 0
			} else if let Some(f) = n.as_f64() {
				f != 0.0
			} else {
				true
			}
		}
		serde_json::Value::String(s) => !s.is_empty(),
		serde_json::Value::Array(_) | serde_json::Value::Object(_) => true,
	}
}

/// Validate that all transformer arguments are well-formed. Returns an error
/// for the first invalid transformer found.
pub fn validate_transformers(transformers: &[Transformer]) -> MdtResult<()> {
	for t in transformers {
		let (min, max) = match t.r#type {
			TransformerType::Trim
			| TransformerType::TrimStart
			| TransformerType::TrimEnd
			| TransformerType::Code => (0, 0),
			TransformerType::Prefix
			| TransformerType::Suffix
			| TransformerType::Wrap
			| TransformerType::CodeBlock => (0, 1),
			TransformerType::Indent | TransformerType::LinePrefix | TransformerType::LineSuffix => {
				(0, 2)
			}
			TransformerType::Replace => (2, 2),
			TransformerType::If => (1, 1),
		};

		if t.args.len() < min || t.args.len() > max {
			let expected = if min == max {
				format!("{min}")
			} else {
				format!("{min}-{max}")
			};
			return Err(MdtError::InvalidTransformerArgs {
				name: t.r#type.to_string(),
				expected,
				got: t.args.len(),
			});
		}
	}
	Ok(())
}

/// Pad content according to the padding configuration while preserving the
/// trailing line prefix from the original consumer content. When the closing
/// tag is preceded by a comment prefix (e.g., `//! ` or `/// `) that prefix
/// is part of the content range and must be preserved after replacement.
///
/// The `before` value controls blank lines between the opening tag and
/// content, and `after` controls blank lines between content and the closing
/// tag. Each value can be:
///
/// - `false` — No padding; content appears inline with the tag.
/// - `0` — Content on the very next line (one newline, no blank lines).
/// - `1` — One blank line between the tag and content.
/// - `2` — Two blank lines, and so on.
fn pad_content_with_config(
	new_content: &str,
	original_content: &str,
	padding: &PaddingConfig,
) -> String {
	// Extract the trailing prefix from the original content — everything after
	// the last newline. For example, in "\n//! old\n//! " the trailing prefix
	// is "//! ".
	let trailing_prefix = original_content
		.rfind('\n')
		.map_or("", |idx| &original_content[idx + 1..]);
	// Trimmed prefix for blank padding lines — avoids trailing whitespace
	// on empty lines (e.g., "//! " becomes "//!").
	let blank_line_prefix = trailing_prefix.trim_end();

	let mut result = String::with_capacity(new_content.len() + trailing_prefix.len() * 4 + 8);

	// Before padding: lines between opening tag and content
	match padding.before.line_count() {
		None => {
			// false — content inline with opening tag
		}
		Some(0) => {
			// Content on the very next line
			if !new_content.starts_with('\n') {
				result.push('\n');
			}
		}
		Some(n) => {
			// N blank lines between opening tag and content
			if !new_content.starts_with('\n') {
				result.push('\n');
			}
			for _ in 0..n {
				result.push_str(blank_line_prefix);
				result.push('\n');
			}
		}
	}

	result.push_str(new_content);

	// After padding: lines between content and closing tag
	match padding.after.line_count() {
		None => {
			// false — closing tag inline with content
		}
		Some(0) => {
			// Closing tag on the very next line
			if !new_content.ends_with('\n') {
				result.push('\n');
			}
			result.push_str(trailing_prefix);
		}
		Some(n) => {
			if !new_content.ends_with('\n') {
				result.push('\n');
			}
			for _ in 0..n {
				result.push_str(blank_line_prefix);
				result.push('\n');
			}
			result.push_str(trailing_prefix);
		}
	}

	result
}

fn get_string_arg(args: &[Argument], index: usize) -> Option<String> {
	args.get(index).map(|arg| {
		match arg {
			Argument::String(s) => s.clone(),
			Argument::Number(n) => n.to_string(),
			Argument::Boolean(b) => b.to_string(),
		}
	})
}

fn get_bool_arg(args: &[Argument], index: usize) -> Option<bool> {
	args.get(index).map(|arg| {
		match arg {
			Argument::Boolean(b) => *b,
			Argument::String(s) => s == "true",
			Argument::Number(n) => n.0 != 0.0,
		}
	})
}