knope 0.23.0

A command line tool for automating common development tasks
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
//! Integration tests for GitHub API interactions.
//!
//! These tests verify that Knope can correctly:
//! - Create releases on GitHub via the Release workflow
//! - Upload binary assets to GitHub releases
//! - Handle authentication errors gracefully
//!
//! All tests clean up after themselves by deleting any resources they create.

use std::{fs::write, path::Path, process::Command, time::Duration};

use reqwest::Client;
use serde::Deserialize;
use tokio::{fs::create_dir_all, time::sleep};

#[derive(Debug, Deserialize)]
struct Release {
    id: u64,
    tag_name: String,
}

#[derive(Debug, Deserialize)]
struct Asset {
    name: String,
}

fn github_env() -> (String, String, String) {
    let token = std::env::var("KNOPE_INTEGRATION_GITHUB_TOKEN")
        .expect("KNOPE_INTEGRATION_GITHUB_TOKEN must be set");
    let owner = std::env::var("KNOPE_INTEGRATION_GITHUB_OWNER")
        .expect("KNOPE_INTEGRATION_GITHUB_OWNER must be set");
    let repo = std::env::var("KNOPE_INTEGRATION_GITHUB_REPO")
        .expect("KNOPE_INTEGRATION_GITHUB_REPO must be set");
    (token, owner, repo)
}

fn ensure_gh_installed() {
    Command::new("gh")
        .arg("--version")
        .output()
        .expect("GitHub CLI (gh) is not installed or not in PATH");
}

use super::integration_helpers::{push_branch, redact_url_credentials};

fn http_client() -> Client {
    Client::builder()
        .user_agent("Knope")
        .timeout(Duration::from_secs(30))
        .build()
        .expect("Failed to build HTTP client")
}

fn git(dir: &Path, args: &[&str]) -> std::process::Output {
    Command::new("git")
        .args(args)
        .env("GIT_TERMINAL_PROMPT", "0")
        .current_dir(dir)
        .output()
        .expect("Failed to run git command")
}

fn assert_git(dir: &Path, args: &[&str]) {
    let output = git(dir, args);
    assert!(
        output.status.success(),
        "git {} failed:\nstdout: {}\nstderr: {}",
        args.join(" "),
        redact_url_credentials(&String::from_utf8_lossy(&output.stdout)),
        redact_url_credentials(&String::from_utf8_lossy(&output.stderr))
    );
}

/// Add a git remote without including the URL in any panic message, so that
/// tokens embedded in the URL are not leaked into test logs.
fn set_git_remote(dir: &Path, remote_url: &str) {
    let output = Command::new("git")
        .args(["remote", "add", "origin", remote_url])
        .current_dir(dir)
        .output()
        .expect("Failed to run git remote add");
    assert!(output.status.success(), "git remote add failed");
}

/// Set up a temporary directory with a Git repo, knope.toml, Cargo.toml, and CHANGELOG.md.
///
/// The repo is pre-configured at version `0.1.0` so that the `Release` step can immediately
/// create a GitHub release without needing `PrepareRelease` or a `git push` inside knope.
/// The caller is responsible for pushing the branch to the remote before running knope.
fn setup_test_repo(
    version: &str,
    token: &str,
    owner: &str,
    repo: &str,
    branch: &str,
    extra_knope_config: &str,
) -> tempfile::TempDir {
    let dir = tempfile::tempdir().expect("Failed to create temp dir");
    let path = dir.path();

    assert_git(path, &["init", "-b", branch]);
    assert_git(
        path,
        &["config", "user.email", "integration-test@knope.dev"],
    );
    assert_git(path, &["config", "user.name", "Knope Integration Test"]);

    let remote_url = format!("https://x-access-token:{token}@github.com/{owner}/{repo}.git");
    set_git_remote(path, &remote_url);

    // Workflow contains only the Release step: the repo is already at the right version,
    // so no PrepareRelease or git push is needed inside the knope workflow.
    let knope_toml = format!(
        r#"[package]
versioned_files = ["Cargo.toml"]
changelog = "CHANGELOG.md"
{extra_knope_config}
[[workflows]]
name = "release"

[[workflows.steps]]
type = "Release"

[github]
owner = "{owner}"
repo = "{repo}"
"#
    );
    std::fs::write(path.join("knope.toml"), knope_toml).expect("Failed to write knope.toml");
    // Version is already at 0.1.0; the Release step will detect there is no v0.1.0 tag yet
    // and create a GitHub release pointing at the current HEAD commit.
    std::fs::write(
        path.join("Cargo.toml"),
        format!("[package]\nname = \"integration-test\"\nversion = \"{version}\"\n"),
    )
    .expect("Failed to write Cargo.toml");
    std::fs::write(path.join("CHANGELOG.md"), "").expect("Failed to write CHANGELOG.md");

    assert_git(path, &["add", "."]);
    assert_git(path, &["commit", "-m", "chore: release"]);

    dir
}

async fn delete_release(client: &Client, token: &str, owner: &str, repo: &str, release_id: u64) {
    let url = format!("https://api.github.com/repos/{owner}/{repo}/releases/{release_id}");
    let _ = client
        .delete(&url)
        .header("Authorization", format!("token {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()
        .await;
}

async fn delete_tag(client: &Client, token: &str, owner: &str, repo: &str, tag: &str) {
    let url = format!("https://api.github.com/repos/{owner}/{repo}/git/refs/tags/{tag}");
    let _ = client
        .delete(&url)
        .header("Authorization", format!("token {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()
        .await;
}

async fn delete_branch(client: &Client, token: &str, owner: &str, repo: &str, branch: &str) {
    let url = format!("https://api.github.com/repos/{owner}/{repo}/git/refs/heads/{branch}");
    let _ = client
        .delete(&url)
        .header("Authorization", format!("token {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()
        .await;
}

async fn cleanup_release_by_tag(client: &Client, token: &str, owner: &str, repo: &str, tag: &str) {
    let url = format!("https://api.github.com/repos/{owner}/{repo}/releases/tags/{tag}");
    if let Ok(resp) = client
        .get(&url)
        .header("Authorization", format!("token {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()
        .await
    {
        if resp.status().is_success() {
            if let Ok(release) = resp.json::<Release>().await {
                delete_release(client, token, owner, repo, release.id).await;
            }
        }
    }
    delete_tag(client, token, owner, repo, tag).await;
}

/// Test that `knope release` creates a GitHub release via the real API.
///
/// Sets up a git repository pre-configured at version `0.1.0`, pushes the branch to
/// the remote, runs `knope release` (Release step only), then verifies the release
/// was actually created on GitHub.
#[tokio::test]
#[ignore = "requires external service credentials"]
async fn github_release_workflow() {
    let (token, owner, repo) = github_env();
    let client = http_client();
    let branch = "integration-test-release";
    let version = "0.1.0";
    let expected_tag = format!("v{version}");

    // Clean up any leftover resources from a previous failed run
    cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
    delete_branch(&client, &token, &owner, &repo, branch).await;

    let dir = setup_test_repo(version, &token, &owner, &repo, branch, "");
    let path = dir.path();

    // Push the branch so knope can resolve the HEAD commit SHA when creating the release.
    push_branch(path, branch);

    // Run knope release (Release step only — no PrepareRelease, no git push).
    let output = Command::new(env!("CARGO_BIN_EXE_knope"))
        .current_dir(path)
        .env("GITHUB_TOKEN", &token)
        .args(["release"])
        .output()
        .expect("Failed to run knope");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() {
        cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
        delete_branch(&client, &token, &owner, &repo, branch).await;
        panic!("knope release failed:\nstdout: {stdout}\nstderr: {stderr}");
    }

    // GitHub may take a moment to finalise a new release; poll with retries.
    let mut release_opt = None;
    for _ in 0..5 {
        let resp = client
            .get(format!(
                "https://api.github.com/repos/{owner}/{repo}/releases/tags/{expected_tag}"
            ))
            .header("Authorization", format!("token {token}"))
            .header("Accept", "application/vnd.github+json")
            .send()
            .await
            .expect("Failed to fetch release");
        if resp.status().is_success() {
            release_opt = Some(
                resp.json::<Release>()
                    .await
                    .expect("Failed to deserialize release"),
            );
            break;
        }
        tokio::time::sleep(Duration::from_secs(3)).await;
    }

    let Some(release) = release_opt else {
        cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
        delete_branch(&client, &token, &owner, &repo, branch).await;
        panic!("Release {expected_tag} should exist on GitHub after retries");
    };
    assert_eq!(release.tag_name, expected_tag);

    // Cleanup
    delete_release(&client, &token, &owner, &repo, release.id).await;
    delete_tag(&client, &token, &owner, &repo, &expected_tag).await;
    delete_branch(&client, &token, &owner, &repo, branch).await;
}

/// Test that `knope release` can upload binary assets to a GitHub release.
///
/// Configures assets in knope.toml, runs the release workflow, then verifies
/// the asset was uploaded to the created release.
#[tokio::test]
#[ignore = "requires external service credentials"]
async fn github_release_with_assets() {
    let (token, owner, repo) = github_env();
    let client = http_client();
    let branch = "integration-test-assets";
    let version = "0.2.0";
    let expected_tag = format!("v{version}");

    // Clean up leftovers
    cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
    delete_branch(&client, &token, &owner, &repo, branch).await;

    let asset_config = "\n[[package.assets]]\npath = \"dist/test-asset.txt\"\n";
    let dir = setup_test_repo(version, &token, &owner, &repo, branch, asset_config);
    let path = dir.path();

    // Create the asset file (it only needs to exist locally when knope runs, not in git).
    std::fs::create_dir_all(path.join("dist")).expect("Failed to create dist dir");
    std::fs::write(
        path.join("dist/test-asset.txt"),
        "Hello from knope integration tests!",
    )
    .expect("Failed to write asset");

    // Push the branch so knope can resolve the HEAD commit SHA when creating the release.
    push_branch(path, branch);

    // Run knope release (Release step only — no PrepareRelease, no git push).
    let output = Command::new(env!("CARGO_BIN_EXE_knope"))
        .current_dir(path)
        .env("GITHUB_TOKEN", &token)
        .args(["release"])
        .output()
        .expect("Failed to run knope");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() {
        cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
        delete_branch(&client, &token, &owner, &repo, branch).await;
        panic!("knope release with assets failed:\nstdout: {stdout}\nstderr: {stderr}");
    }

    // Poll for the release to appear.
    let mut release_opt = None;
    for _ in 0..5 {
        let resp = client
            .get(format!(
                "https://api.github.com/repos/{owner}/{repo}/releases/tags/{expected_tag}"
            ))
            .header("Authorization", format!("token {token}"))
            .header("Accept", "application/vnd.github+json")
            .send()
            .await
            .expect("Failed to fetch release");
        if resp.status().is_success() {
            release_opt = Some(
                resp.json::<Release>()
                    .await
                    .expect("Failed to deserialize release"),
            );
            break;
        }
        tokio::time::sleep(Duration::from_secs(3)).await;
    }

    let Some(release) = release_opt else {
        cleanup_release_by_tag(&client, &token, &owner, &repo, &expected_tag).await;
        delete_branch(&client, &token, &owner, &repo, branch).await;
        panic!("Release {expected_tag} should exist on GitHub after retries");
    };

    // Check assets
    let assets_url = format!(
        "https://api.github.com/repos/{owner}/{repo}/releases/{}/assets",
        release.id
    );
    let resp = client
        .get(&assets_url)
        .header("Authorization", format!("token {token}"))
        .header("Accept", "application/vnd.github+json")
        .send()
        .await
        .expect("Failed to fetch release assets");

    let assets: Vec<Asset> = resp.json().await.expect("Failed to deserialize assets");

    // Cleanup
    delete_release(&client, &token, &owner, &repo, release.id).await;
    delete_tag(&client, &token, &owner, &repo, &expected_tag).await;
    delete_branch(&client, &token, &owner, &repo, branch).await;

    assert!(
        assets.iter().any(|a| a.name == "test-asset.txt"),
        "Uploaded asset should appear in the release assets list"
    );
}

/// Test that Knope handles authentication errors gracefully.
///
/// Runs `knope release` with an invalid `GITHUB_TOKEN` and verifies
/// the command fails with a non-zero exit code.
#[tokio::test]
#[ignore = "requires external service credentials"]
async fn github_error_bad_token() {
    let (_token, owner, repo) = github_env();

    let dir = tempfile::tempdir().expect("Failed to create temp dir");
    let path = dir.path();

    assert_git(path, &["init"]);
    assert_git(
        path,
        &["config", "user.email", "integration-test@knope.dev"],
    );
    assert_git(path, &["config", "user.name", "Knope Integration Test"]);

    // Workflow with only the Release step — it will fail at the API call due to the bad token.
    let knope_toml = format!(
        r#"[package]
versioned_files = ["Cargo.toml"]
changelog = "CHANGELOG.md"

[[workflows]]
name = "release"

[[workflows.steps]]
type = "Release"

[github]
owner = "{owner}"
repo = "{repo}"
"#
    );
    std::fs::write(path.join("knope.toml"), knope_toml).expect("Failed to write knope.toml");
    std::fs::write(
        path.join("Cargo.toml"),
        "[package]\nname = \"integration-test\"\nversion = \"0.1.0\"\n",
    )
    .expect("Failed to write Cargo.toml");
    std::fs::write(path.join("CHANGELOG.md"), "").expect("Failed to write CHANGELOG.md");

    assert_git(path, &["add", "."]);
    assert_git(path, &["commit", "-m", "chore: release"]);

    // Run knope release with a bad token
    let output = Command::new(env!("CARGO_BIN_EXE_knope"))
        .current_dir(path)
        .env("GITHUB_TOKEN", "bad-token-value")
        .args(["release"])
        .output()
        .expect("Failed to run knope");

    assert!(
        !output.status.success(),
        "knope release should fail with a bad token"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !stderr.is_empty(),
        "Expected error output when using a bad token"
    );
}

/// Tests a few different related API calls for GitHub:
/// 1. Creating a pull request
/// 2. Looking up PR info for a commit
#[tokio::test]
#[ignore = "requires external service credentials"]
async fn pull_request_creation_and_info_lookup() {
    let base_branch = "integration-test-prs-base";
    let extra_knope_config = format!(
        r#"
    [release_notes]
    change_templates = [
        "* $summary by @$pr_author_login in #$pr_number",
        "* $summary by @$pr_author_login",
        "* $summary",
    ]
    [[workflows]]
    name = "pr"
    [[workflows.steps]]
    type = "CreatePullRequest"
    base = "{base_branch}"
    title = {{template = "Integration test PR"}}
    body = {{template = "This is an integration test PR for knope"}}

    [[workflows]]
    name = "prepare"
    [[workflows.steps]]
    type = "PrepareRelease"
    "#
    );

    let (token, owner, repo) = github_env();
    ensure_gh_installed();
    let client = http_client();

    let branch = "integration-test-prs-head";

    // Clean up leftovers
    delete_branch(&client, &token, &owner, &repo, branch).await;
    delete_branch(&client, &token, &owner, &repo, base_branch).await;

    let dir = setup_test_repo(
        "0.3.0",
        &token,
        &owner,
        &repo,
        base_branch,
        &extra_knope_config,
    );
    let path = dir.path();
    push_branch(path, base_branch);

    assert_git(path, &["checkout", "-b", branch]);
    create_dir_all(path.join(".changeset"))
        .await
        .expect("Failed to create .changeset dir");
    write(
        path.join(".changeset/test.md"),
        r"---
default: minor
---
# Test changeset",
    )
    .unwrap();

    assert_git(path, &["add", ".changeset/test.md"]);
    assert_git(path, &["commit", "-m", "feat: test commit"]);

    push_branch(path, branch);

    let output = Command::new(env!("CARGO_BIN_EXE_knope"))
        .current_dir(path)
        .env("GITHUB_TOKEN", &token)
        .args(["pr"])
        .output()
        .expect("Failed to run knope");

    assert!(
        output.status.success(),
        "knope pr command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let pr = get_pr_info(&token, &owner, &repo);
    merge_pr(&token, &owner, &repo, pr.number);

    // Run PrepareRelease and verify that the PR info is included in the changelog
    assert_git(path, &["checkout", branch]);
    assert_git(path, &["pull", "--rebase"]);
    wait_for_github_to_be_ready(&token, owner, repo, client, &pr).await;
    let output = Command::new(env!("CARGO_BIN_EXE_knope"))
        .current_dir(path)
        .env("RUST_LOG", "knope=debug")
        .env("GITHUB_TOKEN", token)
        .args(["prepare"])
        .output()
        .expect("Failed to run knope");
    assert!(
        output.status.success(),
        "knope prepare command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let changelog = std::fs::read_to_string(path.join("CHANGELOG.md")).unwrap();
    assert!(
        changelog.contains(pr.number.to_string().as_str()),
        "PR number should be included in the changelog, got {changelog}.\n Knope output: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    assert!(
        changelog.contains(pr.author.login.as_str()),
        "PR author should be included in the changelog, got {changelog}.\n Knope output: {}",
        String::from_utf8_lossy(&output.stdout)
    );
}

async fn wait_for_github_to_be_ready(
    token: &String,
    owner: String,
    repo: String,
    client: Client,
    pr: &PrInfo,
) {
    for attempt in 0..10u32 {
        sleep(Duration::from_secs(1)).await;
        let resp = client
            .get(format!(
                "https://api.github.com/repos/{owner}/{repo}/pulls/{}",
                pr.number
            ))
            .header("Authorization", format!("token {token}"))
            .header("Accept", "application/vnd.github+json")
            .send()
            .await
            .expect("Failed to fetch PR state");
        let pr_data: serde_json::Value = resp.json().await.expect("Failed to deserialize PR");
        if pr_data
            .get("merged")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false)
        {
            break;
        }
        assert!(
            attempt < 9,
            "PR {} did not show as merged after retries",
            pr.number
        );
    }
}

fn merge_pr(token: &str, owner: &str, repo: &str, pr_number: u64) {
    let output = Command::new("gh")
        .arg("pr")
        .arg("merge")
        .arg("--repo")
        .arg(format!("{owner}/{repo}"))
        .arg("--squash")
        .arg(pr_number.to_string())
        .env("GITHUB_TOKEN", token)
        .output()
        .expect("Failed to run gh");

    assert!(
        output.status.success(),
        "gh pr merge failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn get_pr_info(token: &str, owner: &str, repo: &str) -> PrInfo {
    let output = Command::new("gh")
        .arg("pr")
        .arg("list")
        .arg("--repo")
        .arg(format!("{owner}/{repo}"))
        .arg("--json")
        .arg("number,author")
        .arg("--head")
        .arg("integration-test-prs-head")
        .env("GITHUB_TOKEN", token)
        .output()
        .expect("Failed to run gh");

    serde_json::from_slice::<Vec<PrInfo>>(&output.stdout)
        .expect("Failed to parse gh output")
        .remove(0)
}

#[derive(serde::Deserialize)]
struct PrInfo {
    number: u64,
    author: PrAuthor,
}

#[derive(serde::Deserialize)]
struct PrAuthor {
    login: String,
}