monochange_dart 0.5.1

Dart and Flutter workspace discovery for monochange
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
#![forbid(clippy::indexing_slicing)]

//! # `monochange_dart`
//!
//! <!-- {=monochangeDartCrateDocs|trim|linePrefix:"//! ":true} -->
//! `monochange_dart` discovers Dart and Flutter packages for the shared planner.
//!
//! Reach for this crate when you need to scan `pubspec.yaml` files, expand Dart or Flutter workspaces, and normalize package metadata into `monochange_core` records.
//!
//! ## Why use it?
//!
//! - cover both pure Dart and Flutter package layouts with one adapter
//! - normalize pubspec metadata and dependency edges for shared release planning
//! - detect Flutter packages without maintaining a separate discovery path
//!
//! ## Best for
//!
//! - scanning Dart or Flutter monorepos into normalized workspace records
//! - reusing the same planning pipeline for mobile and non-mobile packages
//! - discovering Flutter packages without a dedicated Flutter-only adapter layer
//!
//! ## Public entry points
//!
//! - `discover_dart_packages(root)` discovers Dart and Flutter workspaces plus standalone packages
//! - `DartAdapter` exposes the shared adapter interface
//!
//! ## Scope
//!
//! - `pubspec.yaml` workspace expansion
//! - Dart package parsing
//! - Flutter package detection
//! - normalized dependency extraction
//! <!-- {/monochangeDartCrateDocs} -->

pub mod analysis;

use std::collections::BTreeSet;
use std::collections::HashSet;
use std::fmt::Write as _;
use std::fs;
use std::path::Path;
use std::path::PathBuf;

pub use analysis::DartSemanticAnalyzer;
pub use analysis::semantic_analyzer;
use glob::glob;
use monochange_core::AdapterDiscovery;
use monochange_core::DependencyKind;
use monochange_core::DiscoveryPathFilter;
use monochange_core::Ecosystem;
use monochange_core::EcosystemAdapter;
use monochange_core::LockfileCommandExecution;
use monochange_core::MonochangeError;
use monochange_core::MonochangeResult;
use monochange_core::PackageDependency;
use monochange_core::PackageRecord;
use monochange_core::PublishState;
use monochange_core::ShellConfig;
use monochange_core::SourceConfiguration;
use monochange_core::normalize_path;
use monochange_publish::PublishRequest;
use semver::Version;
use serde_yaml_ng::Mapping;
use serde_yaml_ng::Value;
use walkdir::DirEntry;
use walkdir::WalkDir;

pub mod lints;

pub const PUBSPEC_FILE: &str = "pubspec.yaml";

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DartVersionedFileKind {
	Manifest,
	Lock,
}

pub fn write_dart_placeholder_manifest(
	dir: &Path,
	request: &PublishRequest,
	source: Option<&SourceConfiguration>,
) -> MonochangeResult<()> {
	let repository =
		source.map(|source| format!("https://github.com/{}/{}", source.owner, source.repo));
	let mut rendered = format!(
		"name: {}\nversion: {}\ndescription: Placeholder package published by monochange.\n",
		request.package_name, request.version
	);
	if let Some(repository) = repository {
		let _ = writeln!(rendered, "repository: {repository}");
	}
	fs::write(dir.join("pubspec.yaml"), rendered).map_err(|error| {
		MonochangeError::Io(format!("failed to write placeholder pubspec.yaml: {error}"))
	})
}

/// Classify a Dart or Flutter versioned file path.
pub fn supported_versioned_file_kind(path: &Path) -> Option<DartVersionedFileKind> {
	let file_name = path
		.file_name()
		.and_then(|name| name.to_str())
		.unwrap_or_default();
	match file_name {
		"pubspec.lock" => Some(DartVersionedFileKind::Lock),
		_ if path.extension().and_then(|ext| ext.to_str()) == Some("yaml")
			|| path.extension().and_then(|ext| ext.to_str()) == Some("yml") =>
		{
			Some(DartVersionedFileKind::Manifest)
		}
		_ => None,
	}
}

/// Discover lockfiles that should be refreshed for `package`.
pub fn discover_lockfiles(package: &PackageRecord) -> Vec<PathBuf> {
	let manifest_dir = package
		.manifest_path
		.parent()
		.map_or_else(|| package.workspace_root.clone(), Path::to_path_buf);
	let scope = if manifest_dir == package.workspace_root {
		manifest_dir.clone()
	} else {
		package.workspace_root.clone()
	};

	let mut discovered = [scope.join("pubspec.lock")]
		.into_iter()
		.filter(|path| path.exists())
		.collect::<Vec<_>>();

	if discovered.is_empty() && scope != manifest_dir {
		discovered.extend(
			[manifest_dir.join("pubspec.lock")]
				.into_iter()
				.filter(|path| path.exists()),
		);
	}

	discovered
}

/// Return the default lockfile refresh commands for `package`.
pub fn default_lockfile_commands(package: &PackageRecord) -> Vec<LockfileCommandExecution> {
	let command = match package.ecosystem {
		Ecosystem::Flutter => "flutter pub get",
		Ecosystem::Dart => "dart pub get",
		_ => return Vec::new(),
	};

	discover_lockfiles(package)
		.into_iter()
		.map(|lockfile| {
			LockfileCommandExecution {
				command: command.to_string(),
				cwd: lockfile
					.parent()
					.unwrap_or(&package.workspace_root)
					.to_path_buf(),
				shell: ShellConfig::None,
			}
		})
		.collect()
}

/// Update dependency sections inside a parsed `pubspec.yaml` mapping.
pub fn update_dependency_fields(
	mapping: &mut Mapping,
	fields: &[&str],
	versioned_deps: &std::collections::BTreeMap<String, String>,
) {
	for field in fields {
		let Some(Value::Mapping(section)) = mapping.get_mut(Value::String(field.to_string()))
		else {
			continue;
		};

		for (dep_name, dep_version) in versioned_deps {
			let key = Value::String(dep_name.clone());

			if section.contains_key(&key) {
				section.insert(key, Value::String(dep_version.clone()));
			}
		}
	}
}

#[must_use = "the manifest update result must be checked"]
/// Update `pubspec.yaml` text while preserving the existing layout.
pub fn update_manifest_text(
	contents: &str,
	owner_version: Option<&str>,
	fields: &[&str],
	versioned_deps: &std::collections::BTreeMap<String, String>,
) -> MonochangeResult<String> {
	serde_yaml_ng::from_str::<Mapping>(contents).map_err(|error| {
		MonochangeError::Config(format!("failed to parse pubspec yaml: {error}"))
	})?;

	let line_ranges = yaml_line_ranges(contents);
	let mut replacements = Vec::<((usize, usize), String)>::new();

	if let Some(owner_version) = owner_version
		&& let Some(span) = find_yaml_scalar_for_key(contents, &line_ranges, 0, "version")
	{
		replacements.push((
			span,
			render_yaml_scalar(&contents[span.0..span.1], owner_version),
		));
	}

	for field in fields {
		let Some(section_index) = find_yaml_key_line(contents, &line_ranges, 0, field) else {
			continue;
		};

		for (dep_name, dep_version) in versioned_deps {
			if let Some(span) =
				find_yaml_dependency_scalar(contents, &line_ranges, section_index, dep_name)
			{
				replacements.push((
					span,
					render_yaml_scalar(&contents[span.0..span.1], dep_version),
				));
			}
		}
	}

	replacements.sort_by_key(|right| std::cmp::Reverse(right.0.0));

	let mut updated = contents.to_string();
	for ((start, end), replacement) in replacements {
		updated.replace_range(start..end, &replacement);
	}

	Ok(updated)
}

fn yaml_line_ranges(contents: &str) -> Vec<(usize, usize)> {
	let mut ranges = Vec::new();
	let mut start = 0usize;
	for (index, ch) in contents.char_indices() {
		if ch == '\n' {
			ranges.push((start, index));
			start = index + 1;
		}
	}
	if start <= contents.len() {
		ranges.push((start, contents.len()));
	}
	ranges
}

fn find_yaml_scalar_for_key(
	contents: &str,
	line_ranges: &[(usize, usize)],
	indent: usize,
	key: &str,
) -> Option<(usize, usize)> {
	let line_index = find_yaml_key_line(contents, line_ranges, indent, key)?;
	let range = *line_ranges.get(line_index)?;
	parse_yaml_line(contents, range).and_then(|line| line.value_span)
}

fn find_yaml_key_line(
	contents: &str,
	line_ranges: &[(usize, usize)],
	indent: usize,
	key: &str,
) -> Option<usize> {
	line_ranges.iter().position(|range| {
		parse_yaml_line(contents, *range)
			.is_some_and(|line| line.indent == indent && line.key == key)
	})
}

fn find_yaml_dependency_scalar(
	contents: &str,
	line_ranges: &[(usize, usize)],
	section_index: usize,
	dep_name: &str,
) -> Option<(usize, usize)> {
	let section = parse_yaml_line(contents, *line_ranges.get(section_index)?)?;
	let section_indent = section.indent;
	let mut index = section_index + 1;
	while let Some(range) = line_ranges.get(index) {
		let Some(line) = parse_yaml_line(contents, *range) else {
			index += 1;
			continue;
		};
		if line.indent <= section_indent {
			break;
		}
		if line.key == dep_name {
			if let Some(value_span) = line.value_span {
				return Some(value_span);
			}
			let dep_indent = line.indent;
			let mut nested_index = index + 1;
			while let Some(nested_range) = line_ranges.get(nested_index) {
				let Some(nested_line) = parse_yaml_line(contents, *nested_range) else {
					nested_index += 1;
					continue;
				};
				if nested_line.indent <= dep_indent {
					break;
				}
				if nested_line.key == "version" {
					return nested_line.value_span;
				}
				nested_index += 1;
			}
			return None;
		}
		index += 1;
	}
	None
}

struct ParsedYamlLine<'a> {
	indent: usize,
	key: &'a str,
	value_span: Option<(usize, usize)>,
}

fn parse_yaml_line(contents: &str, range: (usize, usize)) -> Option<ParsedYamlLine<'_>> {
	let line = &contents[range.0..range.1];
	let trimmed = line.trim_start_matches([' ', '\t']);
	if trimmed.is_empty() || trimmed.starts_with('#') {
		return None;
	}
	let indent = line.len() - trimmed.len();
	let colon = trimmed.find(':')?;
	let key = trimmed[..colon].trim();
	if key.is_empty() {
		return None;
	}
	let value_span = yaml_value_span(line, range.0, indent + colon + 1);
	Some(ParsedYamlLine {
		indent,
		key,
		value_span,
	})
}

fn yaml_value_span(
	line: &str,
	line_start: usize,
	value_start_in_line: usize,
) -> Option<(usize, usize)> {
	let suffix = line.get(value_start_in_line..)?;
	let value_offset = suffix.find(|ch: char| !matches!(ch, ' ' | '\t'))?;
	let value = &suffix[value_offset..];
	if value.starts_with('#') {
		return None;
	}
	let span_start = line_start + value_start_in_line + value_offset;
	let span_end = if let Some(quote) = value
		.chars()
		.next()
		.filter(|quote| *quote == '"' || *quote == '\'')
	{
		let quote_end = find_yaml_quote_end(value, quote)?;
		span_start + quote_end + 1
	} else {
		let comment_index = value.find('#').unwrap_or(value.len());
		let trimmed_end = value[..comment_index].trim_end_matches([' ', '\t']).len();
		span_start + trimmed_end
	};
	(span_end > span_start).then_some((span_start, span_end))
}

fn find_yaml_quote_end(value: &str, quote: char) -> Option<usize> {
	let mut chars = value.char_indices();
	chars.next()?;
	for (index, ch) in chars {
		if ch == quote {
			return Some(index);
		}
	}
	None
}

fn render_yaml_scalar(existing: &str, value: &str) -> String {
	if existing.starts_with('"') && existing.ends_with('"') {
		return format!("\"{value}\"");
	}
	if existing.starts_with('\'') && existing.ends_with('\'') {
		return format!("'{value}'");
	}
	value.to_string()
}

/// Update versions embedded in a parsed `pubspec.lock` mapping.
pub fn update_pubspec_lock(
	mapping: &mut Mapping,
	raw_versions: &std::collections::BTreeMap<String, String>,
) {
	let Some(Value::Mapping(packages)) = mapping.get_mut(Value::String("packages".to_string()))
	else {
		return;
	};
	for (name, version) in raw_versions {
		let key = Value::String(name.clone());
		let Some(Value::Mapping(entry)) = packages.get_mut(&key) else {
			continue;
		};
		entry.insert(
			Value::String("version".to_string()),
			Value::String(version.clone()),
		);
	}
}

pub struct DartAdapter;

/// Return the shared Dart and Flutter ecosystem adapter.
#[must_use]
pub const fn adapter() -> DartAdapter {
	DartAdapter
}

impl EcosystemAdapter for DartAdapter {
	fn ecosystem(&self) -> Ecosystem {
		Ecosystem::Dart
	}

	fn discover(&self, root: &Path) -> MonochangeResult<AdapterDiscovery> {
		discover_dart_packages(root)
	}

	fn load_configured(
		&self,
		root: &Path,
		package_path: &Path,
	) -> MonochangeResult<Option<PackageRecord>> {
		load_configured_dart_package(root, package_path)
	}

	fn supported_versioned_file_kind(&self, path: &Path) -> bool {
		supported_versioned_file_kind(path).is_some()
	}

	fn validate_versioned_file(
		&self,
		full_path: &Path,
		display_path: &str,
		custom_fields: Option<&[String]>,
	) -> MonochangeResult<()> {
		validate_versioned_file(full_path, display_path, custom_fields)
	}
}

#[tracing::instrument(skip_all)]
#[must_use = "the discovery result must be checked"]
/// Discover Dart and Flutter packages rooted at `root`.
pub fn discover_dart_packages(root: &Path) -> MonochangeResult<AdapterDiscovery> {
	let workspace_manifests = find_workspace_manifests(root);
	let mut included_manifests = HashSet::new();
	let mut packages = Vec::new();
	let mut warnings = Vec::new();

	for workspace_manifest in workspace_manifests {
		let (workspace_packages, workspace_warnings) =
			discover_workspace_packages(&workspace_manifest)?;
		warnings.extend(workspace_warnings);
		for package in workspace_packages {
			included_manifests.insert(package.manifest_path.clone());
			packages.push(package);
		}
	}

	for manifest_path in find_all_manifests(root) {
		if included_manifests.contains(&manifest_path) {
			continue;
		}

		if let Some(package) =
			parse_manifest(&manifest_path, manifest_path.parent().unwrap_or(root))?
		{
			packages.push(package);
		}
	}

	packages.sort_by(|left, right| left.id.cmp(&right.id));
	packages.dedup_by(|left, right| left.id == right.id);
	tracing::debug!(packages = packages.len(), "discovered dart packages");

	Ok(AdapterDiscovery { packages, warnings })
}

/// Load one explicitly configured Dart/Flutter package without walking the repo.
#[must_use = "the package result must be checked"]
pub fn load_configured_dart_package(
	root: &Path,
	package_path: &Path,
) -> MonochangeResult<Option<PackageRecord>> {
	let manifest_path =
		if package_path.file_name().and_then(|name| name.to_str()) == Some(PUBSPEC_FILE) {
			package_path.to_path_buf()
		} else {
			package_path.join(PUBSPEC_FILE)
		};
	parse_manifest(&manifest_path, manifest_path.parent().unwrap_or(root))
}

fn find_workspace_manifests(root: &Path) -> Vec<PathBuf> {
	let mut manifests = find_all_manifests(root)
		.into_iter()
		.filter(|manifest_path| has_workspace_section(manifest_path).unwrap_or(false))
		.collect::<Vec<_>>();
	manifests.sort();
	manifests
}

fn discover_workspace_packages(
	workspace_manifest: &Path,
) -> MonochangeResult<(Vec<PackageRecord>, Vec<String>)> {
	let parsed = parse_yaml_manifest(workspace_manifest)?;
	let workspace_root = workspace_manifest
		.parent()
		.unwrap_or_else(|| Path::new("."));
	let patterns = yaml_array_strings(&parsed, "workspace");
	let mut warnings = Vec::new();
	let manifests = expand_workspace_patterns(workspace_root, &patterns, &mut warnings);
	let mut packages = Vec::new();

	for manifest_path in manifests {
		if let Some(package) = parse_manifest(&manifest_path, workspace_root)? {
			packages.push(package);
		}
	}

	Ok((packages, warnings))
}

fn expand_workspace_patterns(
	root: &Path,
	patterns: &[String],
	warnings: &mut Vec<String>,
) -> BTreeSet<PathBuf> {
	let filter = DiscoveryPathFilter::new(root);
	let mut manifests = BTreeSet::new();
	for pattern in patterns {
		let joined_pattern = root.join(pattern).to_string_lossy().to_string();
		let matches = glob(&joined_pattern)
			.into_iter()
			.flat_map(|paths| paths.filter_map(Result::ok))
			.map(|path| normalize_path(&path))
			.filter(|path| filter.allows(path))
			.collect::<Vec<_>>();
		if matches.is_empty() {
			warnings.push(format!(
				"dart workspace pattern `{pattern}` under {} matched no packages",
				root.display()
			));
		}

		for matched_path in matches {
			let manifest_path = if matched_path.is_dir() {
				matched_path.join(PUBSPEC_FILE)
			} else {
				matched_path
			};
			if manifest_path.file_name().and_then(|name| name.to_str()) == Some(PUBSPEC_FILE)
				&& manifest_path.exists()
				&& filter.allows(&manifest_path)
			{
				manifests.insert(manifest_path);
			}
		}
	}
	manifests
}

fn parse_manifest(
	manifest_path: &Path,
	workspace_root: &Path,
) -> MonochangeResult<Option<PackageRecord>> {
	let parsed = parse_yaml_manifest(manifest_path)?;
	let Some(name) = yaml_string(&parsed, "name") else {
		return Ok(None);
	};
	let ecosystem = if parsed.get(Value::String("flutter".to_string())).is_some() {
		Ecosystem::Flutter
	} else {
		Ecosystem::Dart
	};
	let version = yaml_string(&parsed, "version").and_then(|value| Version::parse(&value).ok());
	let publish_state = manifest_publish_state(&parsed);

	let mut package = PackageRecord::new(
		ecosystem,
		name,
		manifest_path.to_path_buf(),
		workspace_root.to_path_buf(),
		version,
		publish_state,
	);
	package.declared_dependencies = parse_dependencies(&parsed);
	Ok(Some(package))
}

fn manifest_publish_state(parsed: &Mapping) -> PublishState {
	match parsed.get(Value::String("publish_to".to_string())) {
		Some(Value::String(value)) if value == "none" => PublishState::Private,
		Some(Value::Bool(false)) => PublishState::Private,
		_ => PublishState::Public,
	}
}

fn parse_dependencies(parsed: &Mapping) -> Vec<PackageDependency> {
	["dependencies", "dev_dependencies"]
		.into_iter()
		.filter_map(|section| {
			yaml_mapping(parsed, section).map(|dependencies| (section, dependencies))
		})
		.flat_map(|(section, dependencies)| {
			dependencies.iter().map(move |(name, value)| {
				PackageDependency {
					name: name.as_str().unwrap_or_default().to_string(),
					kind: DependencyKind::Runtime,
					version_constraint: match value {
						Value::String(text) => Some(text.clone()),
						Value::Mapping(mapping) => {
							mapping
								.get(Value::String("version".to_string()))
								.and_then(Value::as_str)
								.map(ToString::to_string)
						}
						_ => None,
					},
					optional: false,
					source_field: Some(section.to_string()),
				}
			})
		})
		.filter(|dependency| !dependency.name.is_empty())
		.collect()
}

fn has_workspace_section(manifest_path: &Path) -> MonochangeResult<bool> {
	let parsed = parse_yaml_manifest(manifest_path)?;
	Ok(parsed
		.get(Value::String("workspace".to_string()))
		.and_then(Value::as_sequence)
		.is_some_and(|items| !items.is_empty()))
}

fn parse_yaml_manifest(manifest_path: &Path) -> MonochangeResult<Mapping> {
	let contents = fs::read_to_string(manifest_path).map_err(|error| {
		MonochangeError::Io(format!(
			"failed to read {}: {error}",
			manifest_path.display()
		))
	})?;
	serde_yaml_ng::from_str::<Mapping>(&contents).map_err(|error| {
		MonochangeError::Discovery(format!(
			"failed to parse {}: {error}",
			manifest_path.display()
		))
	})
}

fn yaml_string(mapping: &Mapping, key: &str) -> Option<String> {
	mapping
		.get(Value::String(key.to_string()))
		.and_then(Value::as_str)
		.map(ToString::to_string)
}

/// Return the default dependency-version prefix for this ecosystem.
/// Validate that a Dart versioned file contains a readable version field.
pub fn validate_versioned_file(
	full_path: &Path,
	display_path: &str,
	_custom_fields: Option<&[String]>,
) -> MonochangeResult<()> {
	let contents = fs::read_to_string(full_path).map_err(|error| {
		MonochangeError::Config(format!(
			"versioned file `{display_path}` is not readable: {error}"
		))
	})?;
	let yaml: Value = serde_yaml_ng::from_str(&contents).map_err(|error| {
		MonochangeError::Config(format!(
			"versioned file `{display_path}` is not valid YAML: {error}"
		))
	})?;

	if yaml
		.get("version")
		.and_then(|value| value.as_str())
		.is_none()
	{
		return Err(MonochangeError::Config(format!(
			"versioned file `{display_path}` does not contain a `version` string field"
		)));
	}

	Ok(())
}

#[must_use]
pub fn default_dependency_version_prefix() -> &'static str {
	"^"
}

/// Return the manifest fields that usually contain dependency versions.
#[must_use]
pub fn default_dependency_fields() -> &'static [&'static str] {
	&["dependencies", "dev_dependencies"]
}
fn yaml_mapping<'map>(mapping: &'map Mapping, key: &str) -> Option<&'map Mapping> {
	mapping
		.get(Value::String(key.to_string()))
		.and_then(Value::as_mapping)
}

fn yaml_array_strings(mapping: &Mapping, key: &str) -> Vec<String> {
	mapping
		.get(Value::String(key.to_string()))
		.and_then(Value::as_sequence)
		.map(|items| {
			items
				.iter()
				.filter_map(Value::as_str)
				.map(ToString::to_string)
				.collect::<Vec<_>>()
		})
		.unwrap_or_default()
}

fn find_all_manifests(root: &Path) -> Vec<PathBuf> {
	let filter = DiscoveryPathFilter::new(root);
	WalkDir::new(root)
		.into_iter()
		.filter_entry(|entry| filter.should_descend(entry.path()))
		.filter_map(Result::ok)
		.filter(|entry| entry.file_name() == PUBSPEC_FILE)
		.map(DirEntry::into_path)
		.map(|path| normalize_path(&path))
		.collect()
}

#[cfg(test)]
#[path = "__tests__/lib_tests.rs"]
mod tests;