monochange_hosting 0.6.3

Shared hosting utilities for monochange source providers
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
#![forbid(clippy::indexing_slicing)]

//! # `monochange_hosting`
//!
//! `monochange_hosting` packages the shared git and HTTP plumbing used by hosted source providers.
//!
//! Reach for this crate when you are implementing GitHub, Gitea, Forgejo, or GitLab release adapters and want one place for release-body rendering, change-request branch naming, JSON requests, and git branch orchestration.
//!
//! ## Why use it?
//!
//! - keep provider adapters focused on provider-specific payloads instead of repeated plumbing
//! - share one markdown rendering path for release bodies and release pull requests
//! - reuse one set of blocking HTTP helpers with consistent error messages
//!
//! ## Best for
//!
//! - implementing or testing hosted source adapters
//! - generating release pull request bodies from prepared manifests
//! - staging, committing, and pushing release branches through shared wrappers
//!
//! ## Public entry points
//!
//! - `release_body(source, manifest, target)` resolves the outward release body for a target
//! - `release_pull_request_body(manifest)` renders the provider change-request body
//! - `release_pull_request_branch(prefix, command)` normalizes the change-request branch name
//! - `get_json`, `post_json`, `patch_json`, and `put_json` wrap provider API requests
//! - `git_checkout_branch`, `git_stage_paths`, `git_commit_paths`, and `git_push_branch` wrap shared git operations
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;

use monochange_core::CommitMessage;
use monochange_core::MonochangeError;
use monochange_core::MonochangeResult;
use monochange_core::ProviderReleaseNotesSource;
use monochange_core::ReleaseManifest;
use monochange_core::ReleaseManifestChangelog;
use monochange_core::ReleaseManifestTarget;
use monochange_core::ReleaseOwnerKind;
use monochange_core::SourceConfiguration;
use monochange_core::git::git_checkout_branch_command;
use monochange_core::git::git_current_branch;
use monochange_core::git::git_push_branch_command;
use monochange_core::git::git_stage_all_command;
use monochange_core::git::git_stage_paths_command;
use monochange_core::git::run_command;
use monochange_core::git::run_git_commit_message;
use reqwest::Client;
use reqwest::header::HeaderMap;
use rustls::crypto::ring::default_provider as ring_provider;
use serde::Serialize;
use serde::de::DeserializeOwned;

static RUSTLS_PROVIDER_INSTALLED: OnceLock<()> = OnceLock::new();

/// Install the ring crypto provider as the default for rustls.
///
/// Required because monochange uses `reqwest` with the `rustls-no-provider` feature —
/// without an explicit provider, any HTTPS request panics with "No provider set".
///
/// Safe to call multiple times; subsequent calls are no-ops.
pub fn ensure_rustls_provider() {
	let () = RUSTLS_PROVIDER_INSTALLED.get_or_init(|| {
		let _ = ring_provider().install_default();
	});
}

/// Append release-note entries to a markdown body, normalizing bullet formatting.
pub fn push_body_entries(lines: &mut Vec<String>, entries: &[String]) {
	for (index, entry) in entries.iter().enumerate() {
		let trimmed = entry.trim();

		if trimmed.contains('\n') {
			lines.extend(trimmed.lines().map(ToString::to_string));
			if index + 1 < entries.len() {
				lines.push(String::new());
			}
			continue;
		}

		if trimmed.starts_with("- ") || trimmed.starts_with("* ") || trimmed.starts_with('#') {
			lines.push(trimmed.to_string());
		} else {
			lines.push(format!("- {trimmed}"));
		}
	}
}

/// Render a fallback release body when no changelog body is available.
pub fn minimal_release_body(manifest: &ReleaseManifest, target: &ReleaseManifestTarget) -> String {
	let mut lines = vec![format!("Release target `{}`", target.id), String::new()];

	if !target.members.is_empty() {
		lines.push(format!("Members: {}", target.members.join(", ")));
		lines.push(String::new());
	}

	let reasons = manifest
		.plan
		.decisions
		.iter()
		.filter(|decision| {
			target.kind == ReleaseOwnerKind::Package || target.members.contains(&decision.package)
		})
		.flat_map(|decision| decision.reasons.iter().cloned())
		.collect::<Vec<_>>();

	if reasons.is_empty() {
		lines.push("- prepare release".to_string());
	} else {
		for reason in reasons {
			lines.push(format!("- {reason}"));
		}
	}

	lines.join("\n")
}

/// Build the provider change-request branch for a release command.
pub fn release_pull_request_branch(branch_prefix: &str, command: &str) -> String {
	let command = command
		.chars()
		.map(|character| {
			if character.is_ascii_alphanumeric() {
				character.to_ascii_lowercase()
			} else {
				'-'
			}
		})
		.collect::<String>()
		.trim_matches('-')
		.to_string();

	let command = if command.is_empty() {
		"release".to_string()
	} else {
		command
	};

	format!("{}/{}", branch_prefix.trim_end_matches('/'), command)
}

/// Render the markdown body used for provider release requests.
pub fn release_pull_request_body(manifest: &ReleaseManifest) -> String {
	let mut lines = vec!["## Prepared release".to_string(), String::new()];
	lines.push(format!("- command: `{}`", manifest.command));

	for target in manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
	{
		lines.push(format!(
			"- {} `{}` -> `{}`",
			target.kind, target.id, target.tag_name
		));
	}

	if !manifest.release_targets.iter().any(|target| target.release) {
		lines.push("- no outward release targets".to_string());
	}

	lines.push(String::new());
	lines.push("## Release notes".to_string());

	for target in manifest
		.release_targets
		.iter()
		.filter(|target| target.release)
	{
		lines.push(String::new());
		lines.push(format!("### {} {}", target.id, target.version));

		if let Some(changelog) = manifest.changelogs.iter().find(|changelog| {
			changelog.owner_id == target.id && changelog.owner_kind == target.kind
		}) {
			for paragraph in &changelog.notes.summary {
				lines.push(String::new());
				lines.push(paragraph.clone());
			}

			for section in &changelog.notes.sections {
				if section.entries.is_empty() {
					continue;
				}
				lines.push(String::new());
				lines.push(format!("### {}", section.title));
				lines.push(String::new());
				push_body_entries(&mut lines, &section.entries);
			}
		} else {
			lines.push(String::new());
			lines.push(minimal_release_body(manifest, target));
		}
	}

	if !manifest.changed_files.is_empty() {
		lines.push(String::new());
		lines.push("## Changed files".to_string());
		lines.push(String::new());

		for path in &manifest.changed_files {
			lines.push(format!("- {}", path.display()));
		}
	}

	lines.join("\n")
}

/// Resolve the provider release body for one outward release target.
pub fn release_body(
	source: &SourceConfiguration,
	manifest: &ReleaseManifest,
	target: &ReleaseManifestTarget,
) -> Option<String> {
	match source.releases.source {
		ProviderReleaseNotesSource::GitHubGenerated => None,
		ProviderReleaseNotesSource::Monochange => Some(monochange_release_body(manifest, target)),
	}
}

fn monochange_release_body(manifest: &ReleaseManifest, target: &ReleaseManifestTarget) -> String {
	let target_changelog = manifest
		.changelogs
		.iter()
		.find(|changelog| changelog.owner_id == target.id && changelog.owner_kind == target.kind);
	let member_changelogs = uncovered_member_changelogs(manifest, target, target_changelog);

	match (target_changelog, member_changelogs.is_empty()) {
		(Some(changelog), true) => changelog.rendered.clone(),
		(Some(changelog), false) if changelog_has_release_notes(changelog) => {
			append_member_changelogs(&changelog.rendered, &member_changelogs)
		}
		(_, false) => grouped_member_release_body(target, &member_changelogs),
		(None, true) => minimal_release_body(manifest, target),
	}
}

fn uncovered_member_changelogs<'a>(
	manifest: &'a ReleaseManifest,
	target: &ReleaseManifestTarget,
	target_changelog: Option<&ReleaseManifestChangelog>,
) -> Vec<&'a ReleaseManifestChangelog> {
	if target.kind != ReleaseOwnerKind::Group {
		return Vec::new();
	}

	manifest
		.changelogs
		.iter()
		.filter(|changelog| {
			changelog.owner_kind == ReleaseOwnerKind::Package
				&& target.members.contains(&changelog.owner_id)
				&& changelog_has_release_notes(changelog)
				&& changelog_has_uncovered_notes(changelog, target_changelog)
		})
		.collect()
}

fn append_member_changelogs(
	rendered: &str,
	member_changelogs: &[&ReleaseManifestChangelog],
) -> String {
	let mut lines = vec![rendered.trim_end().to_string(), String::new()];
	push_member_changelogs(&mut lines, member_changelogs);
	lines.join("\n")
}

fn grouped_member_release_body(
	target: &ReleaseManifestTarget,
	member_changelogs: &[&ReleaseManifestChangelog],
) -> String {
	let title = if target.rendered_changelog_title.is_empty() {
		target.rendered_title.as_str()
	} else {
		target.rendered_changelog_title.as_str()
	};
	let title = if title.is_empty() {
		target.tag_name.as_str()
	} else {
		title
	};
	let mut lines = vec![format!("## {title}"), String::new()];
	lines.push(format!("Grouped release for `{}`.", target.id));
	lines.push(String::new());
	push_member_changelogs(&mut lines, member_changelogs);
	lines.join("\n")
}

fn push_member_changelogs(lines: &mut Vec<String>, changelogs: &[&ReleaseManifestChangelog]) {
	lines.push("## Member package changelogs".to_string());

	for changelog in changelogs {
		lines.push(String::new());
		lines.push(format!("### `{}`", changelog.owner_id));
		push_changelog_notes(lines, changelog);
	}
}

fn push_changelog_notes(lines: &mut Vec<String>, changelog: &ReleaseManifestChangelog) {
	for paragraph in &changelog.notes.summary {
		lines.push(String::new());
		lines.push(paragraph.clone());
	}

	for section in &changelog.notes.sections {
		if section.entries.is_empty() {
			continue;
		}
		lines.push(String::new());
		lines.push(format!("#### {}", section.title));
		lines.push(String::new());
		push_body_entries(lines, &section.entries);
	}
}

fn changelog_has_release_notes(changelog: &ReleaseManifestChangelog) -> bool {
	changelog.notes.sections.iter().any(|section| {
		section
			.entries
			.iter()
			.any(|entry| !is_empty_group_release_note(entry))
	})
}

fn is_empty_group_release_note(entry: &str) -> bool {
	entry.contains("No group-facing notes were recorded for this release")
}

fn changelog_has_uncovered_notes(
	changelog: &ReleaseManifestChangelog,
	target_changelog: Option<&ReleaseManifestChangelog>,
) -> bool {
	let Some(target_changelog) = target_changelog else {
		return true;
	};
	let covered_entries = target_changelog
		.notes
		.sections
		.iter()
		.flat_map(|section| &section.entries)
		.map(|entry| normalized_release_entry(entry))
		.collect::<Vec<_>>();

	changelog
		.notes
		.sections
		.iter()
		.flat_map(|section| &section.entries)
		.any(|entry| !covered_entries.contains(&normalized_release_entry(entry)))
}

fn normalized_release_entry(entry: &str) -> String {
	entry
		.lines()
		.filter(|line| !line.trim_start().starts_with("_Packages:"))
		.collect::<Vec<_>>()
		.join("\n")
		.trim()
		.to_string()
}

/// Build a blocking HTTP client for provider API calls.
///
/// Build a blocking HTTP client for provider API calls.
///
/// Installs the ring crypto provider for rustls if not already set, ensuring
/// HTTPS works with the `rustls-no-provider` feature flag.
pub fn build_http_client(provider: &str) -> MonochangeResult<Client> {
	ensure_rustls_provider();

	Client::builder().build().map_err(|error| {
		MonochangeError::Config(format!("failed to build {provider} HTTP client: {error}"))
	})
}

/// Perform a GET request that treats `404` as `Ok(None)`.
pub async fn get_optional_json<T>(
	client: &Client,
	headers: &HeaderMap,
	url: &str,
	provider: &str,
) -> MonochangeResult<Option<T>>
where
	T: DeserializeOwned,
{
	let response = client
		.get(url)
		.headers(headers.clone())
		.send()
		.await
		.map_err(|error| {
			MonochangeError::Config(format!("{provider} API GET `{url}` failed: {error}"))
		})?;
	if response.status().as_u16() == 404 {
		return Ok(None);
	}
	if !response.status().is_success() {
		return Err(MonochangeError::Config(format!(
			"{provider} API GET `{url}` failed with status {}",
			response.status()
		)));
	}
	response.json::<T>().await.map(Some).map_err(|error| {
		MonochangeError::Config(format!("{provider} API GET `{url}` failed: {error}"))
	})
}

/// Perform a GET request and deserialize a successful JSON response.
pub async fn get_json<T>(
	client: &Client,
	headers: &HeaderMap,
	url: &str,
	provider: &str,
) -> MonochangeResult<T>
where
	T: DeserializeOwned,
{
	let response = client
		.get(url)
		.headers(headers.clone())
		.send()
		.await
		.map_err(|error| {
			MonochangeError::Config(format!("{provider} API GET `{url}` failed: {error}"))
		})?;
	if !response.status().is_success() {
		return Err(MonochangeError::Config(format!(
			"{provider} API GET `{url}` failed with status {}",
			response.status()
		)));
	}
	response.json::<T>().await.map_err(|error| {
		MonochangeError::Config(format!("{provider} API GET `{url}` failed: {error}"))
	})
}

/// Perform a POST request and deserialize a successful JSON response.
pub async fn post_json<Body, Response>(
	client: &Client,
	headers: &HeaderMap,
	url: &str,
	body: &Body,
	provider: &str,
) -> MonochangeResult<Response>
where
	Body: Serialize + ?Sized,
	Response: DeserializeOwned,
{
	let response = client
		.post(url)
		.headers(headers.clone())
		.json(body)
		.send()
		.await
		.map_err(|error| {
			MonochangeError::Config(format!("{provider} API POST `{url}` failed: {error}"))
		})?;
	if !response.status().is_success() {
		return Err(MonochangeError::Config(format!(
			"{provider} API POST `{url}` failed with status {}",
			response.status()
		)));
	}
	response.json::<Response>().await.map_err(|error| {
		MonochangeError::Config(format!("{provider} API POST `{url}` failed: {error}"))
	})
}

/// Perform a PUT request and deserialize a successful JSON response.
pub async fn put_json<Body, Response>(
	client: &Client,
	headers: &HeaderMap,
	url: &str,
	body: &Body,
	provider: &str,
) -> MonochangeResult<Response>
where
	Body: Serialize + ?Sized,
	Response: DeserializeOwned,
{
	let response = client
		.put(url)
		.headers(headers.clone())
		.json(body)
		.send()
		.await
		.map_err(|error| {
			MonochangeError::Config(format!("{provider} API PUT `{url}` failed: {error}"))
		})?;
	if !response.status().is_success() {
		return Err(MonochangeError::Config(format!(
			"{provider} API PUT `{url}` failed with status {}",
			response.status()
		)));
	}
	response.json::<Response>().await.map_err(|error| {
		MonochangeError::Config(format!("{provider} API PUT `{url}` failed: {error}"))
	})
}

/// Perform a PATCH request and deserialize a successful JSON response.
pub async fn patch_json<Body, Response>(
	client: &Client,
	headers: &HeaderMap,
	url: &str,
	body: &Body,
	provider: &str,
) -> MonochangeResult<Response>
where
	Body: Serialize + ?Sized,
	Response: DeserializeOwned,
{
	let response = client
		.patch(url)
		.headers(headers.clone())
		.json(body)
		.send()
		.await
		.map_err(|error| {
			MonochangeError::Config(format!("{provider} API PATCH `{url}` failed: {error}"))
		})?;
	if !response.status().is_success() {
		return Err(MonochangeError::Config(format!(
			"{provider} API PATCH `{url}` failed with status {}",
			response.status()
		)));
	}
	response.json::<Response>().await.map_err(|error| {
		MonochangeError::Config(format!("{provider} API PATCH `{url}` failed: {error}"))
	})
}

/// Check out or reset the local release branch used for provider requests.
pub async fn git_checkout_branch(root: &Path, branch: &str, context: &str) -> MonochangeResult<()> {
	if matches!(git_current_branch(root).await.as_deref(), Ok(current) if current == branch) {
		return Ok(());
	}
	run_command(git_checkout_branch_command(root, branch), context).await
}

/// Stage every non-ignored changed path before creating a release commit.
pub async fn git_stage_paths(
	root: &Path,
	tracked_paths: &[PathBuf],
	context: &str,
	stage_all: bool,
) -> MonochangeResult<()> {
	// patch-coverage:ignore-start -- provider integration tests cover the staged command choice through adapters.
	let command = if stage_all {
		git_stage_all_command(root)
	} else {
		git_stage_paths_command(root, tracked_paths)
	};
	// patch-coverage:ignore-end
	run_command(command, context).await
}

/// Commit the prepared release changes, tolerating a no-op commit.
pub async fn git_commit_paths(
	root: &Path,
	message: &CommitMessage,
	context: &str,
	no_verify: bool,
) -> MonochangeResult<()> {
	run_git_commit_message(root, message, context, no_verify).await
}

/// Push the release branch to `origin` with `--force-with-lease`.
pub async fn git_push_branch(
	root: &Path,
	branch: &str,
	context: &str,
	no_verify: bool,
) -> MonochangeResult<()> {
	run_command(git_push_branch_command(root, branch, no_verify), context).await
}

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