cursus 0.9.3

Library crate for the cursus release management CLI
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
use std::sync::Arc;

use crate::cli::prepare::ReleaseInfo;
use crate::cli::prepare::git_lifecycle::*;
use crate::command::CommandRunner;
use crate::command::test_support::{DispatchingCommandRunner, RecordingCommandRunner};
use crate::filesystem::LocalFilesystem;
use crate::model::config;

// ── stage_and_commit ──────────────────────────────────────────────────────

#[tokio::test]
async fn stage_and_commit_empty_releases_is_noop() {
	let dir = tempfile::tempdir().unwrap();
	let runner = Arc::new(RecordingCommandRunner::new(0));
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = stage_and_commit(
		&git,
		&[],
		&[],
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_ok());
}

#[tokio::test]
async fn stage_and_commit_dry_run_suppresses_git_commands() {
	let dir = tempfile::tempdir().unwrap();
	let release_infos = vec![ReleaseInfo {
		package_name: "my-pkg".to_string(),
		new_version: "1.0.0".parse().unwrap(),
		changelog_entry: String::new(),
	}];
	let inner = Arc::new(RecordingCommandRunner::new(0));
	let dry_run_runner =
		crate::command::DryRunCommandRunner::new(Arc::clone(&inner) as Arc<dyn CommandRunner>);
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::new(dry_run_runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = stage_and_commit(
		&git,
		&[],
		&release_infos,
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_ok());
	// DryRunCommandRunner suppresses run_mut calls — the inner recorder receives nothing.
	assert!(inner.invocations().is_empty());
}

#[tokio::test]
async fn extra_files_outside_repo_is_rejected() {
	// Create an outer temp dir with a repo subdir and a secret file alongside it.
	let outer = tempfile::tempdir().unwrap();
	let repo_dir = outer.path().join("repo");
	std::fs::create_dir(&repo_dir).unwrap();
	let secret = outer.path().join("secret.txt");
	std::fs::write(&secret, "secret").unwrap();
	// "../secret.txt" from repo_dir resolves to outer/secret.txt (outside the repo).
	let extra_files = vec!["../secret.txt".to_string()];
	let release_infos = vec![ReleaseInfo {
		package_name: "my-pkg".to_string(),
		new_version: "1.0.0".parse().unwrap(),
		changelog_entry: String::new(),
	}];
	let runner = Arc::new(RecordingCommandRunner::new(0));
	let dir_abs = crate::path::AbsolutePath::new(&repo_dir).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = stage_and_commit(
		&git,
		&extra_files,
		&release_infos,
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("resolves outside the repository root")
	);
}

#[cfg(unix)]
#[tokio::test]
async fn extra_files_symlink_outside_repo_is_rejected() {
	let dir = tempfile::tempdir().unwrap();
	// Create a symlink inside the tempdir pointing to /tmp (outside the repo).
	let symlink_path = dir.path().join("escape");
	std::os::unix::fs::symlink("/tmp", &symlink_path).unwrap();
	let extra_files = vec!["escape".to_string()];
	let release_infos = vec![ReleaseInfo {
		package_name: "my-pkg".to_string(),
		new_version: "1.0.0".parse().unwrap(),
		changelog_entry: String::new(),
	}];
	let runner = Arc::new(RecordingCommandRunner::new(0));
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = stage_and_commit(
		&git,
		&extra_files,
		&release_infos,
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("resolves outside the repository root")
	);
}

#[tokio::test]
async fn extra_files_nonexistent_is_skipped() {
	let dir = tempfile::tempdir().unwrap();
	let extra_files = vec!["does-not-exist.txt".to_string()];
	let release_infos = vec![ReleaseInfo {
		package_name: "my-pkg".to_string(),
		new_version: "1.0.0".parse().unwrap(),
		changelog_entry: String::new(),
	}];
	let runner = Arc::new(RecordingCommandRunner::new(0));
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	// Should succeed (non-existent file is a warning, not an error).
	let result = stage_and_commit(
		&git,
		&extra_files,
		&release_infos,
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_ok());
}

#[tokio::test]
async fn extra_files_absolute_path_is_rejected() {
	let dir = tempfile::tempdir().unwrap();
	let extra_files = vec!["/etc/passwd".to_string()];
	let release_infos = vec![ReleaseInfo {
		package_name: "my-pkg".to_string(),
		new_version: "1.0.0".parse().unwrap(),
		changelog_entry: String::new(),
	}];
	let runner = Arc::new(RecordingCommandRunner::new(0));
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = stage_and_commit(
		&git,
		&extra_files,
		&release_infos,
		&[],
		"ci(release): version packages",
		&crate::filesystem::LocalFilesystem,
	)
	.await;
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("resolves outside the repository root")
	);
}

#[tokio::test]
async fn compute_release_branch_uses_flag_over_all() {
	assert_eq!(
		compute_release_branch(Some("my-branch"), "release/", "main").unwrap(),
		"my-branch"
	);
}

#[tokio::test]
async fn compute_release_branch_uses_config_prefix() {
	assert_eq!(
		compute_release_branch(None, "release/", "main").unwrap(),
		"release/main"
	);
}

#[tokio::test]
async fn compute_release_branch_uses_default_prefix() {
	assert_eq!(
		compute_release_branch(None, "cursus-release/", "main").unwrap(),
		"cursus-release/main"
	);
}

#[tokio::test]
async fn compute_release_branch_rejects_dash_prefix() {
	let result = compute_release_branch(Some("--detach"), "release/", "main");
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("must not start with '-'")
	);
}

#[tokio::test]
async fn compute_release_branch_rejects_single_dash() {
	let result = compute_release_branch(Some("-"), "release/", "main");
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("must not start with '-'")
	);
}

#[tokio::test]
async fn compute_release_branch_rejects_empty() {
	let result = compute_release_branch(Some(""), "release/", "main");
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("must not be empty")
	);
}

#[tokio::test]
async fn compute_release_branch_rejects_composed_leading_dash() {
	// config_prefix itself is attacker-controlled via .cursus/config.toml;
	// the composed result must still be rejected when it starts with '-'.
	let result = compute_release_branch(None, "--", "main");
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("must not start with '-'")
	);
}

#[tokio::test]
async fn compute_release_branch_rejects_composed_control_char() {
	// A current_branch containing a control character (e.g. BEL) must be
	// caught before the composed name reaches git.
	let result = compute_release_branch(None, "cursus-release/", "feat\x07ure");
	assert!(result.is_err());
	assert!(
		result
			.unwrap_err()
			.to_string()
			.contains("control character")
	);
}

#[tokio::test]
async fn check_dirty_tree_succeeds_when_clean() {
	let dir = tempfile::tempdir().unwrap();
	let runner = Arc::new(RecordingCommandRunner::new(0)); // empty stdout → clean
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = check_dirty_tree(&git).await;
	assert!(result.is_ok());
}

#[tokio::test]
async fn check_dirty_tree_fails_when_dirty() {
	let dir = tempfile::tempdir().unwrap();
	let runner = Arc::new(RecordingCommandRunner::new(0).with_stdout(b" M src/main.rs\n".to_vec()));
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let git = crate::git::GitWorkdir::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		dir_abs.clone(),
	);
	let result = check_dirty_tree(&git).await;
	assert!(result.is_err());
	assert!(
		result.unwrap_err().to_string().contains("dirty"),
		"Expected 'dirty' in error message"
	);
}

fn make_test_env(dir: &std::path::Path) -> crate::Env {
	let r = Arc::new(crate::command::test_support::RecordingCommandRunner::new(0))
		as Arc<dyn CommandRunner>;
	crate::Env::new(
		Arc::clone(&r),
		Arc::new(LocalFilesystem),
		Arc::new(crate::git::GitWorkdir::new(
			r,
			crate::path::AbsolutePath::new(dir).unwrap(),
		)),
	)
}

/// Sets up a temp dir with a Cargo project, branch strategy git config, and GitHub config.
async fn setup_branch_strategy_with_github() -> tempfile::TempDir {
	let dir = tempfile::tempdir().unwrap();
	std::fs::create_dir(dir.path().join(".git")).unwrap();
	let setup_env = make_test_env(dir.path());
	crate::model::config::Config::new()
		.with_cargo(crate::model::config::CargoConfig::enabled())
		.with_git(
			crate::model::config::GitConfig::enabled_config()
				.with_strategy(crate::model::config::Strategy::Branch),
		)
		.with_github(
			crate::model::config::GitHubConfig::enabled_config()
				.with_owner("acme".to_string())
				.with_repo("app".to_string())
				.with_pull_request_title("My Release PR".to_string()),
		)
		.save(setup_env.fs(), setup_env.git().path())
		.await
		.unwrap();
	std::fs::write(
		dir.path().join("Cargo.toml"),
		"[package]\nname = \"test-pkg\"\nversion = \"1.0.0\"\nedition = \"2024\"\n",
	)
	.unwrap();
	std::fs::create_dir_all(dir.path().join("src")).unwrap();
	std::fs::write(dir.path().join("src/lib.rs"), "").unwrap();
	let cursus_dir = dir.path().join(".cursus");
	std::fs::write(
		cursus_dir.join("change.md"),
		"+++\ntest-pkg = \"patch\"\n+++\n\nFix\n",
	)
	.unwrap();
	dir
}

#[tokio::test]
async fn cmd_prepare_branch_strategy_with_github_creates_pr() {
	use crate::forge::CodeForgeClient;
	use crate::forge::test_support::{CodeForgeInvocation, RecordingCodeForgeClient};
	let dir = setup_branch_strategy_with_github().await;
	let runner = Arc::new(DispatchingCommandRunner::new(0).on_with_args_stdout(
		"git",
		vec![
			"rev-parse".to_string(),
			"--abbrev-ref".to_string(),
			"HEAD".to_string(),
		],
		0,
		b"main\n".to_vec(),
	));
	let client = Arc::new(RecordingCodeForgeClient::new());
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let env = crate::Env::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		Arc::new(LocalFilesystem),
		Arc::new(crate::git::GitWorkdir::new(
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
			dir_abs.clone(),
		)),
	)
	.with_code_forge_client(Arc::clone(&client) as Arc<dyn CodeForgeClient>);
	let config = config::load(env.fs(), env.git().path())
		.await
		.unwrap()
		.unwrap();
	let args = crate::cli::prepare::PrepareArgs::default();

	let result = crate::cli::prepare::cmd_prepare(&args, false, &env, config).await;
	assert!(result.is_ok(), "Expected Ok, got: {result:?}");

	let invocations = client.invocations();
	let pr = invocations
		.iter()
		.find(|i| matches!(i, CodeForgeInvocation::CreatePullRequest { .. }));
	assert!(pr.is_some(), "Expected PR creation, got: {invocations:?}");
	if let Some(CodeForgeInvocation::CreatePullRequest { title, .. }) = pr {
		assert_eq!(title, "My Release PR");
	}
}

#[tokio::test]
async fn cmd_prepare_branch_strategy_pr_failure_is_fatal() {
	use crate::forge::CodeForgeClient;
	use crate::forge::test_support::RecordingCodeForgeClient;
	let dir = setup_branch_strategy_with_github().await;
	let runner = Arc::new(DispatchingCommandRunner::new(0).on_with_args_stdout(
		"git",
		vec![
			"rev-parse".to_string(),
			"--abbrev-ref".to_string(),
			"HEAD".to_string(),
		],
		0,
		b"main\n".to_vec(),
	));
	let client = Arc::new(RecordingCodeForgeClient::new().with_create_pr_failure());
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let env = crate::Env::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		Arc::new(LocalFilesystem),
		Arc::new(crate::git::GitWorkdir::new(
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
			dir_abs.clone(),
		)),
	)
	.with_code_forge_client(Arc::clone(&client) as Arc<dyn CodeForgeClient>);
	let config = config::load(env.fs(), env.git().path())
		.await
		.unwrap()
		.unwrap();
	let args = crate::cli::prepare::PrepareArgs::default();

	let result = crate::cli::prepare::cmd_prepare(&args, false, &env, config).await;
	assert!(
		result.is_err(),
		"PR failure should be fatal, got: {result:?}"
	);
}

#[tokio::test]
async fn cmd_prepare_no_code_forge_client_errors() {
	let dir = setup_branch_strategy_with_github().await;
	let runner = Arc::new(RecordingCommandRunner::new(0));
	// No github client — pre-flight check should error
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	let env = crate::Env::new(
		Arc::clone(&runner) as Arc<dyn CommandRunner>,
		Arc::new(LocalFilesystem),
		Arc::new(crate::git::GitWorkdir::new(
			Arc::clone(&runner) as Arc<dyn CommandRunner>,
			dir_abs.clone(),
		)),
	);
	let config = config::load(env.fs(), env.git().path())
		.await
		.unwrap()
		.unwrap();
	let args = crate::cli::prepare::PrepareArgs::default();

	let result = crate::cli::prepare::cmd_prepare(&args, false, &env, config).await;
	assert!(result.is_err(), "Expected Err without github client");
	let msg = format!("{:#}", result.unwrap_err());
	assert!(
		msg.contains("code forge client is unavailable"),
		"Expected 'code forge client is unavailable' error, got: {msg}"
	);
}

// ── check_forge_preconditions ─────────────────────────────────────────────

fn minimal_env_with(
	client: Arc<dyn crate::forge::CodeForgeClient>,
	gitlab_uses_job_token_only: bool,
) -> crate::Env {
	let dir = tempfile::tempdir().unwrap();
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	std::mem::forget(dir);
	let runner: Arc<dyn CommandRunner> = Arc::new(RecordingCommandRunner::new(0));
	let git = Arc::new(crate::git::GitWorkdir::new(Arc::clone(&runner), dir_abs));
	crate::Env::new(runner, Arc::new(LocalFilesystem), git)
		.with_code_forge_client(client)
		.with_gitlab_uses_job_token_only(gitlab_uses_job_token_only)
}

#[test]
fn check_forge_preconditions_succeeds_for_github_pat() {
	use crate::forge::test_support::RecordingCodeForgeClient;
	let client =
		Arc::new(RecordingCodeForgeClient::new()) as Arc<dyn crate::forge::CodeForgeClient>;
	let env = minimal_env_with(client, false);
	check_forge_preconditions(&env).expect("GitHub PAT path should succeed");
}

#[test]
fn check_forge_preconditions_succeeds_for_gitlab_with_pat() {
	use crate::forge::test_support::RecordingCodeForgeClient;
	let client = Arc::new(RecordingCodeForgeClient::new().with_forge_name("GitLab"))
		as Arc<dyn crate::forge::CodeForgeClient>;
	let env = minimal_env_with(client, false);
	check_forge_preconditions(&env).expect("GitLab with PAT (job_token_only=false) should succeed");
}

#[test]
fn check_forge_preconditions_bails_for_gitlab_with_job_token_only() {
	use crate::forge::test_support::RecordingCodeForgeClient;
	let client = Arc::new(RecordingCodeForgeClient::new().with_forge_name("GitLab"))
		as Arc<dyn crate::forge::CodeForgeClient>;
	let env = minimal_env_with(client, true);
	let result = check_forge_preconditions(&env);
	assert!(result.is_err(), "GitLab + job-token-only must bail");
	let msg = format!("{:#}", result.unwrap_err());
	assert!(
		msg.contains("GITLAB_TOKEN"),
		"Expected error message to name GITLAB_TOKEN, got: {msg}"
	);
	assert!(
		msg.contains("CI_JOB_TOKEN"),
		"Expected error message to name CI_JOB_TOKEN, got: {msg}"
	);
}

#[test]
fn check_forge_preconditions_bails_when_client_unavailable() {
	let dir = tempfile::tempdir().unwrap();
	let dir_abs = crate::path::AbsolutePath::new(dir.path()).unwrap();
	std::mem::forget(dir);
	let runner: Arc<dyn CommandRunner> = Arc::new(RecordingCommandRunner::new(0));
	let git = Arc::new(crate::git::GitWorkdir::new(Arc::clone(&runner), dir_abs));
	let env = crate::Env::new(runner, Arc::new(LocalFilesystem), git);
	// Default Env has no forge client configured (Err("No code forge client configured")).
	let result = check_forge_preconditions(&env);
	assert!(result.is_err());
	let msg = format!("{:#}", result.unwrap_err());
	assert!(
		msg.contains("code forge client is unavailable"),
		"Expected unavailable-client error, got: {msg}"
	);
}