monochange 0.7.0

Manage versions and releases for your multiplatform, multilanguage monorepo
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
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Path;
use std::process::Command as ProcessCommand;

use glob::Pattern;
use monochange_analysis::AnalysisConfig;
use monochange_analysis::ChangeFrame;
use monochange_config::load_workspace_configuration;
use monochange_core::BumpSeverity;
use monochange_core::ChangeSignal;
use monochange_core::ChangesetAffectedSettings;
use monochange_core::ChangesetPolicyEvaluation;
use monochange_core::ChangesetPolicyStatus;
use monochange_core::MonochangeError;
use monochange_core::MonochangeResult;
use monochange_core::PackageRecord;
use monochange_core::PublishState;
use monochange_core::SourceConfiguration;
use monochange_core::WorkspaceConfiguration;
use monochange_core::git::git_current_branch;

/// Evaluate pull-request changeset coverage for the supplied changed paths.
///
/// This is the library entry point behind `mc step:affected-packages` and the
/// GitHub changeset-policy workflow. It loads the workspace configuration, resolves
/// changed files against configured packages, reads any attached changesets, and
/// returns a structured pass/skip/fail report.
pub async fn affected_packages(
	root: &Path,
	changed_paths: &[String],
	labels: &[String],
) -> MonochangeResult<ChangesetPolicyEvaluation> {
	// Load and validate configuration
	let configuration = load_workspace_configuration(root)?;
	let verify = &configuration.changesets.affected;

	if !verify.enabled {
		return Err(MonochangeError::Config(
			"changeset verification requires `[changesets.affected].enabled = true`".to_string(),
		));
	}

	// Normalize labels and changed paths
	let labels = labels
		.iter()
		.map(|label| label.trim().to_string())
		.filter(|label| !label.is_empty())
		.collect::<Vec<_>>();
	let changed_paths = changed_paths
		.iter()
		.map(|path| normalize_changed_path(path))
		.filter(|path| !path.is_empty())
		.collect::<Vec<_>>();

	if let Some((current_branch, branch_prefix)) =
		current_branch_matches_pull_request_branch_prefix(root, configuration.source.as_ref()).await
	{
		return Ok(skipped_pull_request_branch_evaluation(
			labels,
			changed_paths,
			&current_branch,
			&branch_prefix,
		));
	}

	// Identify skip labels and changeset paths
	let matched_skip_labels = labels
		.iter()
		.filter(|label| {
			verify
				.skip_labels
				.iter()
				.any(|candidate| candidate == *label)
		})
		.cloned()
		.collect::<Vec<_>>();
	let changeset_paths = changed_paths
		.iter()
		.filter(|path| is_changeset_markdown_path(path))
		.cloned()
		.collect::<Vec<_>>();

	// Classify changed paths against package definitions
	let ignored_path_patterns = compile_patterns(&verify.ignored_paths);
	let changed_path_patterns = compile_patterns(&verify.changed_paths);
	let configured_changelog_paths =
		configured_changelog_paths(&configuration.packages, &configuration.groups);
	let package_matchers = configuration
		.packages
		.iter()
		.map(PackagePathMatcher::new)
		.collect::<Vec<_>>();

	let mut matched_paths = Vec::new();
	let mut ignored_paths = Vec::new();
	let mut affected_package_ids = BTreeSet::new();
	for path in changed_paths
		.iter()
		.filter(|path| !is_changeset_markdown_path(path))
	{
		if path_matches_compiled_patterns(path, &ignored_path_patterns) {
			ignored_paths.push(path.clone());
			continue;
		}

		if configured_changelog_paths.contains(path.as_str()) {
			ignored_paths.push(path.clone());
			continue;
		}

		if path_matches_compiled_patterns(path, &changed_path_patterns) {
			matched_paths.push(path.clone());
			affected_package_ids.extend(
				configuration
					.packages
					.iter()
					.map(|package| package.id.clone()),
			);
			continue;
		}

		let mut matched_any_package = false;
		let mut ignored_by_package = false;
		for matcher in &package_matchers {
			match matcher.classify(path) {
				PackagePathMatch::Touched => {
					matched_any_package = true;
					affected_package_ids.insert(matcher.package.id.clone());
				}
				PackagePathMatch::Ignored => {
					ignored_by_package = true;
				}
				PackagePathMatch::Unmatched => {}
			}
		}
		if matched_any_package {
			matched_paths.push(path.clone());
		} else if ignored_by_package {
			ignored_paths.push(path.clone());
		}
	}

	let mut covered_package_ids = BTreeSet::new();
	let mut errors = Vec::new();
	if !changeset_paths.is_empty() {
		let config_packages = configuration_package_records(&configuration);
		match covered_package_ids_from_changesets(
			root,
			&configuration,
			&changeset_paths,
			&config_packages,
		) {
			Ok(coverage) => {
				covered_package_ids = coverage.covered_package_ids;
			}
			Err(policy_errors) => {
				errors.extend(policy_errors);
			}
		}
	}

	let uncovered_package_ids = affected_package_ids
		.difference(&covered_package_ids)
		.cloned()
		.collect::<Vec<_>>();
	if matched_skip_labels.is_empty() && !uncovered_package_ids.is_empty() {
		errors.push(format!(
			"changed packages are not covered by attached changesets: {}",
			uncovered_package_ids.join(", ")
		));
	}

	let warnings = Vec::new();
	let affected_package_ids = affected_package_ids.into_iter().collect::<Vec<_>>();
	let covered_package_ids = covered_package_ids.into_iter().collect::<Vec<_>>();
	let required =
		!affected_package_ids.is_empty() && verify.required && matched_skip_labels.is_empty();
	let status = match (
		errors.is_empty(),
		matched_skip_labels.is_empty(),
		affected_package_ids.is_empty(),
	) {
		(false, ..) => ChangesetPolicyStatus::Failed,
		(true, false, _) => ChangesetPolicyStatus::Skipped,
		(true, true, true) => ChangesetPolicyStatus::NotRequired,
		(true, true, false) => ChangesetPolicyStatus::Passed,
	};
	let summary = match status {
		ChangesetPolicyStatus::Failed
			if errors
				.iter()
				.any(|error| error.contains("not covered by attached changesets")) =>
		{
			format!(
				"changeset verification failed: attached changesets do not cover {} changed package{}",
				uncovered_package_ids.len(),
				if uncovered_package_ids.len() == 1 { "" } else { "s" }
			)
		}
		ChangesetPolicyStatus::Failed => {
			"changeset verification failed: one or more attached changeset files are invalid"
				.to_string()
		}
		ChangesetPolicyStatus::Skipped => format!(
			"changeset verification skipped because the change has an allowed label: {}",
			matched_skip_labels.join(", ")
		),
		ChangesetPolicyStatus::NotRequired => {
			"changeset verification passed: no configured packages were affected by the changed files"
				.to_string()
		}
		ChangesetPolicyStatus::Passed => format!(
			"changeset verification passed: attached changesets cover {} changed package{}",
			affected_package_ids.len(),
			if affected_package_ids.len() == 1 { "" } else { "s" }
		),
	};

	let mut evaluation = ChangesetPolicyEvaluation {
		status,
		required,
		enforce: false,
		summary,
		comment: None,
		labels,
		matched_skip_labels,
		changed_paths,
		matched_paths,
		ignored_paths,
		changeset_paths,
		affected_package_ids,
		covered_package_ids,
		uncovered_package_ids,
		warnings,
		errors,
	};
	if evaluation.status == ChangesetPolicyStatus::Failed && verify.comment_on_failure {
		evaluation.comment = Some(render_changeset_verification_comment(verify, &evaluation));
	}

	Ok(evaluation)
}

async fn current_branch_matches_pull_request_branch_prefix(
	root: &Path,
	source: Option<&SourceConfiguration>,
) -> Option<(String, String)> {
	let source = source?;
	let branch_prefix = source.pull_requests.branch_prefix.trim();
	if branch_prefix.is_empty() {
		return None;
	}

	let current_branch = git_current_branch(root).await.ok()?;
	current_branch
		.starts_with(branch_prefix)
		.then(|| (current_branch, branch_prefix.to_string()))
}

fn skipped_pull_request_branch_evaluation(
	labels: Vec<String>,
	changed_paths: Vec<String>,
	current_branch: &str,
	branch_prefix: &str,
) -> ChangesetPolicyEvaluation {
	ChangesetPolicyEvaluation {
		status: ChangesetPolicyStatus::Skipped,
		required: false,
		enforce: false,
		summary: format!(
			"changeset verification skipped because current branch `{current_branch}` starts with release pull request branch prefix `{branch_prefix}`"
		),
		comment: None,
		labels,
		matched_skip_labels: Vec::new(),
		changed_paths,
		matched_paths: Vec::new(),
		ignored_paths: Vec::new(),
		changeset_paths: Vec::new(),
		affected_package_ids: Vec::new(),
		covered_package_ids: Vec::new(),
		uncovered_package_ids: Vec::new(),
		warnings: Vec::new(),
		errors: Vec::new(),
	}
}

/// Backwards-compatible alias for [`affected_packages`].
pub async fn verify_changesets(
	root: &Path,
	changed_paths: &[String],
	labels: &[String],
) -> MonochangeResult<ChangesetPolicyEvaluation> {
	affected_packages(root, changed_paths, labels).await
}

/// Backwards-compatible alias for [`affected_packages`].
pub async fn evaluate_changeset_policy(
	root: &Path,
	changed_paths: &[String],
	labels: &[String],
) -> MonochangeResult<ChangesetPolicyEvaluation> {
	affected_packages(root, changed_paths, labels).await
}

pub(crate) fn compute_changed_paths_since(
	root: &Path,
	since_rev: &str,
) -> MonochangeResult<Vec<String>> {
	let mut diff_command = ProcessCommand::new("git");
	diff_command
		.args(["diff", "--name-only", since_rev])
		.current_dir(root);
	clear_git_env(&mut diff_command);
	let diff_output = diff_command.output().map_err(|error| {
		MonochangeError::Config(format!(
			"failed to run git diff --name-only {since_rev}: {error}"
		))
	})?;
	if !diff_output.status.success() {
		let stderr = String::from_utf8_lossy(&diff_output.stderr);
		return Err(MonochangeError::Config(format!(
			"git diff --name-only {since_rev} failed: {stderr}"
		)));
	}
	let mut paths: BTreeSet<String> = String::from_utf8_lossy(&diff_output.stdout)
		.lines()
		.map(|line| line.trim().to_string())
		.filter(|line| !line.is_empty())
		.collect();

	let mut untracked_command = ProcessCommand::new("git");
	untracked_command
		.args(["ls-files", "--others", "--exclude-standard"])
		.current_dir(root);
	clear_git_env(&mut untracked_command);
	let untracked_output = untracked_command
		.output()
		.map_err(|error| MonochangeError::Config(format!("failed to run git ls-files: {error}")))?;
	if untracked_output.status.success() {
		for line in String::from_utf8_lossy(&untracked_output.stdout).lines() {
			let path = line.trim().to_string();
			if !path.is_empty() {
				paths.insert(path);
			}
		}
	}

	Ok(paths.into_iter().collect())
}

pub(crate) fn normalize_changed_path(path: &str) -> String {
	let normalized = path.trim().replace('\\', "/");
	let normalized = normalized.trim_start_matches("./");
	normalized.trim_matches('/').to_string()
}

pub(crate) fn is_changeset_markdown_path(path: &str) -> bool {
	path.starts_with(".changeset/")
		&& Path::new(path)
			.extension()
			.is_some_and(|extension| extension.eq_ignore_ascii_case("md"))
}

struct PackagePathMatcher<'a> {
	package: &'a monochange_core::PackageDefinition,
	package_root: String,
	package_root_prefix: String,
	additional_patterns: Vec<Pattern>,
	ignored_patterns: Vec<Pattern>,
}

impl<'a> PackagePathMatcher<'a> {
	fn new(package: &'a monochange_core::PackageDefinition) -> Self {
		let package_root = normalize_changed_path(&package.path.to_string_lossy());
		let package_root_prefix = format!("{package_root}/");

		Self {
			package,
			package_root,
			package_root_prefix,
			additional_patterns: compile_patterns(&package.additional_paths),
			ignored_patterns: compile_patterns(&package.ignored_paths),
		}
	}

	fn classify(&self, path: &str) -> PackagePathMatch {
		let relative_path =
			package_relative_path(path, &self.package_root, &self.package_root_prefix);
		if matches_any_compiled_package_pattern(path, relative_path, &self.additional_patterns) {
			return PackagePathMatch::Touched;
		}
		if relative_path.is_none() {
			return PackagePathMatch::Unmatched;
		}
		if self.is_ignored(path) {
			return PackagePathMatch::Ignored;
		}
		PackagePathMatch::Touched
	}

	fn is_ignored(&self, path: &str) -> bool {
		let relative_path =
			package_relative_path(path, &self.package_root, &self.package_root_prefix);
		relative_path.is_some()
			&& matches_any_compiled_package_pattern(path, relative_path, &self.ignored_patterns)
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PackagePathMatch {
	Touched,
	Ignored,
	Unmatched,
}

struct ChangesetCoverage {
	covered_package_ids: BTreeSet<String>,
	signals: Vec<ChangeSignal>,
}

fn covered_package_ids_from_changesets(
	root: &Path,
	configuration: &WorkspaceConfiguration,
	changeset_paths: &[String],
	packages: &[PackageRecord],
) -> Result<ChangesetCoverage, Vec<String>> {
	let changeset_load_context =
		monochange_config::build_changeset_load_context(configuration, packages);
	let mut covered_package_ids = BTreeSet::new();
	let mut signals = Vec::new();
	let mut errors = Vec::new();

	for changeset_path in changeset_paths {
		let absolute_path = root.join(changeset_path);
		if !absolute_path.exists() {
			errors.push(format!(
				"attached changeset `{changeset_path}` does not exist in the checked-out workspace"
			));
			continue;
		}
		match monochange_config::load_changeset_file_with_context(
			&absolute_path,
			&changeset_load_context,
		) {
			Ok(loaded) => {
				for signal in loaded.signals {
					covered_package_ids.insert(signal.package_id.clone());
					signals.push(signal);
				}
			}
			Err(error) => errors.push(error.render()),
		}
	}

	if errors.is_empty() {
		Ok(ChangesetCoverage {
			covered_package_ids,
			signals,
		})
	} else {
		Err(errors)
	}
}

pub(crate) fn check_changeset_bump_alignment(
	root: &Path,
	base_ref: &str,
	evaluation: &mut ChangesetPolicyEvaluation,
) -> MonochangeResult<()> {
	if evaluation.changeset_paths.is_empty() {
		return Ok(());
	}

	let configuration = load_workspace_configuration(root)?;
	let packages = configuration_package_records(&configuration);
	let coverage = covered_package_ids_from_changesets(
		root,
		&configuration,
		&evaluation.changeset_paths,
		&packages,
	)
	.map_err(|errors| MonochangeError::Config(errors.join("\n")))?;
	let requested_bumps = requested_bumps_by_package(&coverage.signals);
	// patch-coverage:ignore-start -- explicit-version-only changesets have no requested bump to compare against API classification.
	if requested_bumps.is_empty() {
		return Ok(());
	}
	// patch-coverage:ignore-end

	let frame = ChangeFrame::CustomRange {
		base: base_ref.to_string(),
		head: "HEAD".to_string(),
	};
	let analysis = monochange_analysis::analyze_changes(root, &frame, &AnalysisConfig::default())?;
	let report = crate::change_classify::classification_report(
		&analysis,
		crate::change_classify::DependencyPropagation::None,
	);
	let mut recommended_bumps = BTreeMap::new();
	// patch-coverage:ignore-start -- loop close is instrumented inconsistently while package-id and package-name inserts are covered.
	for package in &report.packages {
		recommended_bumps.insert(package.package_id.clone(), package.recommendation);
		recommended_bumps.insert(package.package_name.clone(), package.recommendation);
	}
	// patch-coverage:ignore-end

	apply_bump_alignment(requested_bumps, &recommended_bumps, evaluation);
	if !evaluation.errors.is_empty() {
		// patch-coverage:ignore-start -- failure message is exercised by affected changeset CI; error comparison is covered by bump alignment unit tests.
		evaluation.status = ChangesetPolicyStatus::Failed;
		evaluation.summary =
			"changeset verification failed: one or more changeset bumps underestimate API impact"
				.to_string();
		// patch-coverage:ignore-end
	}

	Ok(())
}

pub(crate) fn apply_bump_alignment(
	requested_bumps: BTreeMap<String, BumpSeverity>,
	recommended_bumps: &BTreeMap<String, BumpSeverity>,
	evaluation: &mut ChangesetPolicyEvaluation,
) {
	for (package_id, requested_bump) in requested_bumps {
		let recommended_bump = recommended_bumps
			.get(&package_id)
			.copied()
			.unwrap_or(BumpSeverity::None);
		if requested_bump < recommended_bump {
			evaluation.errors.push(format!(
				"changeset bump for `{package_id}` is insufficient: requested `{requested_bump}`, API classification recommends `{recommended_bump}`"
			));
		} else if requested_bump > recommended_bump {
			evaluation.warnings.push(format!(
				"changeset bump for `{package_id}` may be excessive: requested `{requested_bump}`, API classification recommends `{recommended_bump}`"
			));
		}
	}
}

fn requested_bumps_by_package(signals: &[ChangeSignal]) -> BTreeMap<String, BumpSeverity> {
	let mut requested_bumps = BTreeMap::new();
	for signal in signals {
		let Some(requested_bump) = signal.requested_bump else {
			continue;
		};
		requested_bumps
			.entry(signal.package_id.clone())
			.and_modify(|existing| {
				if requested_bump > *existing {
					*existing = requested_bump;
				}
			})
			.or_insert(requested_bump);
	}
	requested_bumps
}

pub(crate) fn configuration_package_records(
	configuration: &WorkspaceConfiguration,
) -> Vec<PackageRecord> {
	configuration
		.packages
		.iter()
		.map(|package| {
			PackageRecord {
				id: package.id.clone(),
				name: package.id.clone(),
				ecosystem: package.package_type.into(),
				manifest_path: configuration
					.root_path
					.join(&package.path)
					.join(".monochange-config-package"),
				workspace_root: configuration.root_path.clone(),
				current_version: None,
				publish_state: PublishState::Unpublished,
				version_group_id: None,
				metadata: BTreeMap::new(),
				declared_dependencies: Vec::new(),
			}
		})
		.collect()
}

fn compile_patterns(patterns: &[String]) -> Vec<Pattern> {
	patterns
		.iter()
		.filter_map(|pattern| Pattern::new(pattern).ok())
		.collect()
}

fn path_matches_compiled_patterns(path: &str, patterns: &[Pattern]) -> bool {
	patterns.iter().any(|pattern| pattern.matches(path))
}

fn configured_changelog_paths(
	packages: &[monochange_core::PackageDefinition],
	groups: &[monochange_core::GroupDefinition],
) -> BTreeSet<String> {
	packages
		.iter()
		.filter_map(|package| package.changelog.as_ref())
		.map(|target| normalize_changed_path(&target.path.to_string_lossy()))
		.chain(
			groups
				.iter()
				.filter_map(|group| group.changelog.as_ref())
				.map(|target| normalize_changed_path(&target.path.to_string_lossy())),
		)
		.collect()
}

fn package_relative_path<'path>(
	path: &'path str,
	package_root: &str,
	package_root_prefix: &str,
) -> Option<&'path str> {
	path.strip_prefix(package_root_prefix)
		.or_else(|| (path == package_root).then_some(""))
}

fn matches_any_compiled_package_pattern(
	path: &str,
	relative_path: Option<&str>,
	patterns: &[Pattern],
) -> bool {
	patterns.iter().any(|pattern| {
		pattern.matches(path)
			|| relative_path.is_some_and(|relative_path| pattern.matches(relative_path))
	})
}

fn clear_git_env(command: &mut ProcessCommand) {
	for variable in [
		"GIT_DIR",
		"GIT_WORK_TREE",
		"GIT_COMMON_DIR",
		"GIT_INDEX_FILE",
		"GIT_OBJECT_DIRECTORY",
		"GIT_ALTERNATE_OBJECT_DIRECTORIES",
	] {
		command.env_remove(variable);
	}
}

fn render_changeset_verification_comment(
	verify: &ChangesetAffectedSettings,
	evaluation: &ChangesetPolicyEvaluation,
) -> String {
	let mut lines = vec![
		"### monochange changeset verification failed".to_string(),
		String::new(),
		evaluation.summary.clone(),
	];
	if !evaluation.matched_paths.is_empty() {
		lines.push(String::new());
		lines.push("Changed package paths:".to_string());
		for path in &evaluation.matched_paths {
			lines.push(format!("- `{path}`"));
		}
	}
	if !evaluation.affected_package_ids.is_empty() {
		lines.push(String::new());
		lines.push("Affected packages:".to_string());
		for package_id in &evaluation.affected_package_ids {
			lines.push(format!("- `{package_id}`"));
		}
	}
	if !evaluation.changeset_paths.is_empty() {
		lines.push(String::new());
		lines.push("Attached changeset files:".to_string());
		for path in &evaluation.changeset_paths {
			lines.push(format!("- `{path}`"));
		}
	}
	if !evaluation.errors.is_empty() {
		lines.push(String::new());
		lines.push("Errors:".to_string());
		for error in &evaluation.errors {
			lines.push(format!("- {error}"));
		}
	}
	if !verify.skip_labels.is_empty() {
		lines.push(String::new());
		lines.push("Allowed skip labels:".to_string());
		for label in &verify.skip_labels {
			lines.push(format!("- `{label}`"));
		}
	}
	lines.push(String::new());
	lines.push("How to fix:".to_string());
	lines.push("- add or update a `.changeset/*.md` file so it references every changed package or owning group".to_string());
	lines.push(
		"- for example: `mc change --package <id> --bump patch --reason \"describe the change\"`"
			.to_string(),
	);
	if !verify.skip_labels.is_empty() {
		lines.push(
			"- or apply one of the configured skip labels when no release note is required"
				.to_string(),
		);
	}
	lines.join("\n")
}

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