release-plz 0.3.145

Update version and changelog based on semantic versioning and conventional commits
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
mod gh;

use std::io::Write;

use anyhow::Context;
use cargo_metadata::camino::{Utf8Path, Utf8PathBuf};
use release_plz_core::{Project, ReleaseMetadata, ReleaseMetadataBuilder};
use std::collections::HashSet;

const CARGO_REGISTRY_TOKEN: &str = "CARGO_REGISTRY_TOKEN";
const GITHUB_TOKEN: &str = "GITHUB_TOKEN";
const CUSTOM_GITHUB_TOKEN: &str = "RELEASE_PLZ_TOKEN";

pub fn init(manifest_path: &Utf8Path, toml_check: bool) -> anyhow::Result<()> {
    ensure_gh_is_installed()?;

    // Create a Project instance to check mandatory fields
    let metadata = cargo_utils::get_manifest_metadata(manifest_path)?;
    let project = Project::new(
        manifest_path,
        None,
        &HashSet::new(),
        &metadata,
        &NoopReleaseMetadataBuilder,
    )?;

    if toml_check {
        project.check_mandatory_fields()?;
    }

    // get the repo url early to verify that the github repository is configured correctly
    let repo_url = gh::repo_url()?;

    greet();
    let trusted_publishing = should_use_trusted_publishing()?;
    if trusted_publishing {
        print_settings_urls(&project)?;
    } else {
        store_cargo_token()?;
    }

    enable_pr_permissions(&repo_url)?;
    let github_token = store_github_token()?;
    write_actions_yaml(github_token, trusted_publishing)?;

    let secrets_stored = !trusted_publishing || github_token != GITHUB_TOKEN;
    print_recap(&repo_url, secrets_stored);
    Ok(())
}

fn actions_file_parent() -> Utf8PathBuf {
    Utf8Path::new(".github").join("workflows")
}

fn actions_file() -> Utf8PathBuf {
    actions_file_parent().join("release-plz.yml")
}

fn should_use_trusted_publishing() -> anyhow::Result<bool> {
    ask_confirmation(
        "👉 Do you want to use trusted publishing? (Recommended). Learn more at https://crates.io/docs/trusted-publishing.",
    )
}

fn print_settings_urls(project: &Project) -> anyhow::Result<()> {
    println!(
        "Enable trusted publishing for your crates. Note:
- The default workflow name is `release-plz.yml`.
- If you use an environment, edit the final workflow file.

Settings URLs:"
    );

    let publishable_packages = &project.publishable_packages();
    let settings_urls = publishable_packages.iter().map(|package| {
        let package_name = &package.name;
        format!("https://crates.io/crates/{package_name}/settings/new-trusted-publisher")
    });

    for url in settings_urls {
        println!("* {url}");
    }
    println!("\nType Enter when done.");

    read_stdin()?;

    Ok(())
}

fn greet() {
    println!(
        "👋 This process will guide you in setting up release-plz in your GitHub repository, using `gh` (the GitHub CLI) to store the necessary tokens in your repository secrets."
    );
}

fn store_cargo_token() -> anyhow::Result<()> {
    println!("👉 Paste your cargo registry token to store it in the GitHub actions repository secrets.
💡 You can create a crates.io token on https://crates.io/settings/tokens/new, specifying the following scopes: \"publish-new\" and \"publish-update\".");
    gh::store_secret(CARGO_REGISTRY_TOKEN)?;
    Ok(())
}

fn enable_pr_permissions(repo_url: &str) -> anyhow::Result<()> {
    println!("
👉 Go to {} and enable the option \"Allow GitHub Actions to create and approve pull requests\". Type Enter when done.", actions_settings_url(repo_url));
    read_stdin()?;
    Ok(())
}

fn store_github_token() -> anyhow::Result<&'static str> {
    let should_create_token = ask_confirmation(
        "👉 Do you want release-plz to use a GitHub Personal Access Token (PAT)? It's required to run CI on release PRs and to run workflows on tags.",
    )?;

    let github_token = if should_create_token {
        println!("
👉 Paste your GitHub PAT.
💡 Create a GitHub PAT following these instructions:

   1. Go to https://github.com/settings/personal-access-tokens/new.
   2. Under \"Only selected repositories\", select the repositories where you want to use the PAT, to give release-plz write access.
   3. Under \"Repository permissions\", assign \"Contents\" and \"Pull requests\" read and write permissions.

   If you have doubts, check the documentation: https://release-plz.dev/docs/github/token#use-a-personal-access-token.");

        // GitHub custom token
        let release_plz_token: &str = CUSTOM_GITHUB_TOKEN;
        gh::store_secret(release_plz_token)?;
        release_plz_token
    } else {
        // default github token
        GITHUB_TOKEN
    };
    Ok(github_token)
}

fn print_recap(repo_url: &str, secrets_stored: bool) {
    println!(
        "All done 🎉
- GitHub action file written to {}",
        actions_file()
    );

    if secrets_stored {
        println!(
            "- GitHub action secrets stored. Review them at {}",
            actions_secret_url(repo_url)
        );
    }

    println!("Enjoy automated releases 🤖");
}

fn read_stdin() -> anyhow::Result<String> {
    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .context("error while reading user input")?;
    Ok(input)
}

fn ask_confirmation(question: &str) -> anyhow::Result<bool> {
    print!("{question} (Y/n) ");
    std::io::stdout().flush().unwrap();
    let input = read_stdin()?;
    let input = input.trim().to_lowercase();
    Ok(input != "n")
}

fn write_actions_yaml(github_token: &str, trusted_publishing: bool) -> anyhow::Result<()> {
    let branch = gh::default_branch()?;
    let owner = gh::repo_owner()?;
    let action_yaml = action_yaml(&branch, github_token, &owner, trusted_publishing);
    fs_err::create_dir_all(actions_file_parent())
        .context("failed to create GitHub actions workflows directory")?;
    fs_err::write(actions_file(), action_yaml).context("error while writing GitHub action file")?;
    Ok(())
}

fn action_yaml(branch: &str, github_token: &str, owner: &str, trusted_publishing: bool) -> String {
    let github_token_secret = format!("${{{{ secrets.{github_token} }}}}");
    let is_default_token = github_token == GITHUB_TOKEN;
    let checkout_token_line = if is_default_token {
        "".to_string()
    } else {
        format!(
            "
          token: {github_token_secret}"
        )
    };

    let cargo_registry_token = if trusted_publishing {
        "${{ steps.auth.outputs.token }}".to_string()
    } else {
        format!("${{{{ secrets.{CARGO_REGISTRY_TOKEN} }}}}")
    };

    let id_token_permissions = if trusted_publishing {
        "
      id-token: write"
    } else {
        ""
    };

    let trusted_publishing_action = if trusted_publishing {
        "
      - name: Authenticate with crates.io
        uses: rust-lang/crates-io-auth-action@v1
        id: auth"
    } else {
        ""
    };

    let pr_cargo_registry_token = if trusted_publishing {
        // For public crates, the cargo registry token is not needed in the PR workflow.
        // So if we use trusted publishing, we can omit it.
        // Trusted publishing also works for private crates, and if that's your case, write the token manually.
        "".to_string()
    } else {
        // The crate might be private, so we add the token to the PR workflow.
        // If the crate is public, it won't hurt having it here. You can also remove it if you want.
        format!(
            "
          CARGO_REGISTRY_TOKEN: {cargo_registry_token}"
        )
    };

    format!(
        "name: Release-plz

on:
  push:
    branches:
      - {branch}

jobs:
  release-plz-release:
    name: Release-plz release
    runs-on: ubuntu-latest
    if: ${{{{ github.repository_owner == '{owner}' }}}}
    permissions:
      contents: write{id_token_permissions}
    steps:
      - &checkout
        name: Checkout repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0{checkout_token_line}
      - &install-rust
        name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable{trusted_publishing_action}
      - name: Run release-plz
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: {github_token_secret}
          CARGO_REGISTRY_TOKEN: {cargo_registry_token}

  release-plz-pr:
    name: Release-plz PR
    runs-on: ubuntu-latest
    if: ${{{{ github.repository_owner == '{owner}' }}}}
    permissions:
      pull-requests: write
      contents: write
    concurrency:
      group: release-plz-${{{{ github.ref }}}}
      cancel-in-progress: false
    steps:
      - *checkout
      - *install-rust
      - name: Run release-plz
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: {github_token_secret}{pr_cargo_registry_token}
"
    )
}

fn ensure_gh_is_installed() -> anyhow::Result<()> {
    anyhow::ensure!(
        gh::is_gh_installed(),
        "❌ gh cli is not installed. I need it to store GitHub actions repository secrets. Please install it from https://docs.github.com/en/github-cli/github-cli/quickstart."
    );
    Ok(())
}

fn actions_settings_url(repo_url: &str) -> String {
    format!("{}/actions", repo_settings_url(repo_url))
}

fn actions_secret_url(repo_url: &str) -> String {
    format!("{}/secrets/actions", repo_settings_url(repo_url))
}

fn repo_settings_url(repo_url: &str) -> String {
    format!("{repo_url}/settings")
}

struct NoopReleaseMetadataBuilder;

impl ReleaseMetadataBuilder for NoopReleaseMetadataBuilder {
    fn get_release_metadata(&self, _package_name: &str) -> Option<ReleaseMetadata> {
        // This needs to be `Some`, otherwise release-plz doesn't find any public packages.
        Some(ReleaseMetadata {
            release_name_template: None,
            tag_name_template: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn actions_yaml_string_is_correct() {
        expect_test::expect![[r#"
            name: Release-plz

            on:
              push:
                branches:
                  - main

            jobs:
              release-plz-release:
                name: Release-plz release
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  contents: write
                steps:
                  - &checkout
                    name: Checkout repository
                    uses: actions/checkout@v5
                    with:
                      fetch-depth: 0
                  - &install-rust
                    name: Install Rust toolchain
                    uses: dtolnay/rust-toolchain@stable
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release
                    env:
                      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
                      CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

              release-plz-pr:
                name: Release-plz PR
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  pull-requests: write
                  contents: write
                concurrency:
                  group: release-plz-${{ github.ref }}
                  cancel-in-progress: false
                steps:
                  - *checkout
                  - *install-rust
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release-pr
                    env:
                      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
                      CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        "#]]
        .assert_eq(&action_yaml("main", GITHUB_TOKEN, "owner", false));
    }

    #[test]
    fn actions_yaml_string_with_custom_token_is_correct() {
        expect_test::expect![[r#"
            name: Release-plz

            on:
              push:
                branches:
                  - main

            jobs:
              release-plz-release:
                name: Release-plz release
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  contents: write
                steps:
                  - &checkout
                    name: Checkout repository
                    uses: actions/checkout@v5
                    with:
                      fetch-depth: 0
                      token: ${{ secrets.RELEASE_PLZ_TOKEN }}
                  - &install-rust
                    name: Install Rust toolchain
                    uses: dtolnay/rust-toolchain@stable
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release
                    env:
                      GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
                      CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

              release-plz-pr:
                name: Release-plz PR
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  pull-requests: write
                  contents: write
                concurrency:
                  group: release-plz-${{ github.ref }}
                  cancel-in-progress: false
                steps:
                  - *checkout
                  - *install-rust
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release-pr
                    env:
                      GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
                      CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        "#]]
        .assert_eq(&action_yaml("main", CUSTOM_GITHUB_TOKEN, "owner", false));
    }
}

#[test]
fn actions_yaml_string_with_trusted_publishing_is_correct() {
    expect_test::expect![[r#"
            name: Release-plz

            on:
              push:
                branches:
                  - main

            jobs:
              release-plz-release:
                name: Release-plz release
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  contents: write
                  id-token: write
                steps:
                  - &checkout
                    name: Checkout repository
                    uses: actions/checkout@v5
                    with:
                      fetch-depth: 0
                      token: ${{ secrets.RELEASE_PLZ_TOKEN }}
                  - &install-rust
                    name: Install Rust toolchain
                    uses: dtolnay/rust-toolchain@stable
                  - name: Authenticate with crates.io
                    uses: rust-lang/crates-io-auth-action@v1
                    id: auth
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release
                    env:
                      GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
                      CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}

              release-plz-pr:
                name: Release-plz PR
                runs-on: ubuntu-latest
                if: ${{ github.repository_owner == 'owner' }}
                permissions:
                  pull-requests: write
                  contents: write
                concurrency:
                  group: release-plz-${{ github.ref }}
                  cancel-in-progress: false
                steps:
                  - *checkout
                  - *install-rust
                  - name: Run release-plz
                    uses: release-plz/action@v0.5
                    with:
                      command: release-pr
                    env:
                      GITHUB_TOKEN: ${{ secrets.RELEASE_PLZ_TOKEN }}
        "#]]
    .assert_eq(&action_yaml("main", CUSTOM_GITHUB_TOKEN, "owner", true));
}