releasaurus-core 0.16.0

A comprehensive release automation tool that streamlines the software release process across multiple programming languages and forge platforms
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
//! Manager that wraps forge implementations
use async_trait::async_trait;
use std::sync::OnceLock;
use url::Url;

use crate::{
    analyzer::release::Tag,
    config::Config,
    error::Result,
    file_loader::FileLoader,
    forge::{
        request::{
            Commit, CreateCommitRequest, CreatePrRequest,
            CreateReleaseBranchRequest, ForgeCommit, GetFileContentRequest,
            GetPrRequest, PrLabelsRequest, PullRequest, ReleaseByTagResponse,
            UpdatePrRequest,
        },
        traits::Forge,
    },
};

pub struct ForgeOptions {
    pub dry_run: bool,
}

pub struct ForgeManager {
    forge: Box<dyn Forge>,
    repo_name: OnceLock<String>,
    default_branch: OnceLock<String>,
    release_link_base_url: OnceLock<Url>,
    compare_link_base_url: OnceLock<Url>,
    options: ForgeOptions,
}

impl ForgeManager {
    /// Create Gitea client with token authentication and API base URL
    /// configuration for self-hosted instances.
    pub fn new(forge: Box<dyn Forge>, options: ForgeOptions) -> Self {
        Self {
            forge,
            repo_name: OnceLock::new(),
            default_branch: OnceLock::new(),
            release_link_base_url: OnceLock::new(),
            compare_link_base_url: OnceLock::new(),
            options,
        }
    }

    pub fn repo_name(&self) -> &str {
        self.repo_name.get_or_init(|| self.forge.repo_name())
    }

    pub fn release_link_base_url(&self) -> &Url {
        self.release_link_base_url
            .get_or_init(|| self.forge.release_link_base_url())
    }

    pub fn compare_link_base_url(&self) -> &Url {
        self.compare_link_base_url
            .get_or_init(|| self.forge.compare_link_base_url())
    }

    pub fn default_branch(&self) -> &str {
        self.default_branch
            .get_or_init(|| self.forge.default_branch())
    }

    pub async fn get_file_content(
        &self,
        req: GetFileContentRequest,
    ) -> Result<Option<String>> {
        log::debug!("Loading file: {} (branch: {:?})", req.path, req.branch);

        let result = self.forge.get_file_content(req).await;

        if let Err(e) = &result {
            log::error!("Failed to load file: {}", e);
        }

        result
    }

    pub async fn load_config(&self, branch: Option<String>) -> Result<Config> {
        log::info!("Loading configuration from forge (branch: {:?})", branch);

        let result = self.forge.load_config(branch).await;

        if let Err(e) = &result {
            log::error!("Failed to load configuration: {}", e);
        }

        result
    }

    pub async fn get_release_by_tag(
        &self,
        tag: &str,
    ) -> Result<ReleaseByTagResponse> {
        self.forge.get_release_by_tag(tag).await
    }

    pub async fn get_latest_tag_for_prefix(
        &self,
        prefix: &str,
        branch: &str,
    ) -> Result<Option<Tag>> {
        self.forge.get_latest_tag_for_prefix(prefix, branch).await
    }

    pub async fn get_commits(
        &self,
        branch: Option<String>,
        sha: Option<String>,
    ) -> Result<Vec<ForgeCommit>> {
        log::debug!(
            "getting commits for branch [{:?}] starting from sha: {:?}",
            branch,
            sha
        );
        self.forge.get_commits(branch, sha).await
    }

    pub async fn get_open_release_pr(
        &self,
        req: GetPrRequest,
    ) -> Result<Option<PullRequest>> {
        log::info!(
            "Looking for open release PR: base={}, head={}",
            req.base_branch,
            req.head_branch
        );

        let result = self.forge.get_open_release_pr(req).await;

        match &result {
            Ok(Some(pr)) => log::info!("Found open PR #{}", pr.number),
            Ok(None) => log::debug!("No open PR found"),
            Err(e) => log::error!("Error searching for open PR: {}", e),
        }

        result
    }

    pub async fn get_merged_release_pr(
        &self,
        req: GetPrRequest,
    ) -> Result<Option<PullRequest>> {
        log::info!(
            "Looking for merged release PR: base={}, head={}",
            req.base_branch,
            req.head_branch
        );

        let result = self.forge.get_merged_release_pr(req).await;

        match &result {
            Ok(Some(pr)) => log::info!("Found merged PR #{}", pr.number),
            Ok(None) => log::warn!("No merged PR found"),
            Err(e) => log::error!("Error searching for merged PR: {}", e),
        }

        result
    }

    pub async fn create_release_branch(
        &self,
        req: CreateReleaseBranchRequest,
    ) -> Result<Commit> {
        if self.options.dry_run {
            log::warn!("dry_run: would create release branch: req: {:#?}", req);
            return Ok(Commit { sha: "fff".into() });
        }

        log::info!(
            "Creating release branch: {} from {}",
            req.release_branch,
            req.base_branch
        );

        let result = self.forge.create_release_branch(req).await;

        match &result {
            Ok(commit) => {
                log::info!("Created release branch with commit: {}", commit.sha)
            }
            Err(e) => log::error!("Failed to create release branch: {}", e),
        }

        result
    }

    pub async fn create_commit(
        &self,
        req: CreateCommitRequest,
    ) -> Result<Commit> {
        if self.options.dry_run {
            log::warn!("dry_run: would create commit: req: {:#?}", req);
            return Ok(Commit { sha: "fff".into() });
        }

        log::info!(
            "Creating commit on branch: {} ({} file changes)",
            req.target_branch,
            req.file_changes.len()
        );

        let result = self.forge.create_commit(req).await;

        match &result {
            Ok(commit) => log::info!("Created commit: {}", commit.sha),
            Err(e) => log::error!("Failed to create commit: {}", e),
        }

        result
    }

    pub async fn tag_commit(&self, tag_name: &str, sha: &str) -> Result<()> {
        if self.options.dry_run {
            log::warn!(
                "dry_run: would tag commit: tag={}, sha={}",
                tag_name,
                sha
            );
            return Ok(());
        }

        log::info!("Tagging commit: tag={}, sha={}", tag_name, sha);

        let result = self.forge.tag_commit(tag_name, sha).await;

        match &result {
            Ok(_) => log::info!("Successfully created tag: {}", tag_name),
            Err(e) => log::error!("Failed to create tag {}: {}", tag_name, e),
        }

        result
    }

    pub async fn create_pr(&self, req: CreatePrRequest) -> Result<PullRequest> {
        if self.options.dry_run {
            log::warn!(
                "dry_run: would create PR: {} -> {}",
                req.head_branch,
                req.base_branch
            );
            return Ok(PullRequest {
                number: 0,
                sha: "fff".into(),
                body: req.body,
            });
        }

        log::info!(
            "Creating pull request: {} -> {}",
            req.head_branch,
            req.base_branch
        );

        let result = self.forge.create_pr(req).await;

        match &result {
            Ok(pr) => log::info!("Created pull request #{}", pr.number),
            Err(e) => log::error!("Failed to create pull request: {}", e),
        }

        result
    }

    pub async fn update_pr(&self, req: UpdatePrRequest) -> Result<()> {
        if self.options.dry_run {
            log::warn!("dry_run: would update PR: req: {:#?}", req);
            return Ok(());
        }

        log::info!("Updating pull request #{}", req.pr_number);

        let result = self.forge.update_pr(req).await;

        if let Err(e) = &result {
            log::error!("Failed to update PR: {}", e);
        }

        result
    }

    pub async fn replace_pr_labels(&self, req: PrLabelsRequest) -> Result<()> {
        if self.options.dry_run {
            log::warn!(
                "dry_run: would replace PR #{} labels with: {:?}",
                req.pr_number,
                req.labels
            );
            return Ok(());
        }

        log::info!(
            "Replacing labels on PR #{} with: {:?}",
            req.pr_number,
            req.labels
        );

        let result = self.forge.replace_pr_labels(req).await;

        if let Err(e) = &result {
            log::error!("Failed to update labels on PR: {}", e);
        }

        result
    }

    pub async fn create_release(
        &self,
        tag: &str,
        sha: &str,
        notes: &str,
    ) -> Result<()> {
        if self.options.dry_run {
            log::warn!(
                "dry_run: would create release: tag: {tag}, sha: {sha}, notes {notes}"
            );
            return Ok(());
        }

        log::info!("Creating release: tag={}, sha={}", tag, sha);

        let result = self.forge.create_release(tag, sha, notes).await;

        match &result {
            Ok(_) => log::info!("Successfully created release: {}", tag),
            Err(e) => log::error!("Failed to create release {}: {}", tag, e),
        }

        result
    }
}

#[async_trait]
impl FileLoader for ForgeManager {
    async fn load_file(
        &self,
        branch: Option<String>,
        path: String,
    ) -> Result<Option<String>> {
        self.get_file_content(GetFileContentRequest { branch, path })
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        file_loader::FileLoader,
        forge::{request::GetFileContentRequest, traits::MockForge},
    };

    #[tokio::test]
    async fn file_loader_returns_file_content() {
        let mut mock_forge = MockForge::new();
        mock_forge
            .expect_get_file_content()
            .with(mockall::predicate::eq(GetFileContentRequest {
                branch: Some("main".to_string()),
                path: "package.json".to_string(),
            }))
            .returning(|_| Ok(Some(r#"{"version":"1.0.0"}"#.to_string())));

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: false },
        );

        let result = manager
            .load_file(Some("main".to_string()), "package.json".to_string())
            .await
            .unwrap()
            .unwrap();

        assert!(result.contains("1.0.0"));
    }

    #[tokio::test]
    async fn file_loader_returns_none_when_file_not_found() {
        let mut mock_forge = MockForge::new();
        mock_forge.expect_get_file_content().returning(|_| Ok(None));

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: false },
        );

        let result = manager
            .load_file(None, "missing.txt".to_string())
            .await
            .unwrap();

        assert!(result.is_none());
    }

    #[tokio::test]
    async fn dry_run_prevents_create_release_branch() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        let req = CreateReleaseBranchRequest {
            base_branch: "main".into(),
            release_branch: "release-branch".into(),
            message: "chore: release".into(),
            file_changes: vec![],
        };
        let result = manager.create_release_branch(req).await.unwrap();

        assert_eq!(result.sha, "fff");
    }

    #[tokio::test]
    async fn dry_run_prevents_tag_commit() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        manager.tag_commit("v1.0.0", "abc123").await.unwrap();
    }

    #[tokio::test]
    async fn dry_run_prevents_create_pr() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        let req = CreatePrRequest {
            title: "test".to_string(),
            body: "test body".to_string(),
            head_branch: "branch".to_string(),
            base_branch: "main".to_string(),
        };
        let result = manager.create_pr(req).await.unwrap();

        assert_eq!(result.number, 0);
        assert_eq!(result.sha, "fff");
    }

    #[tokio::test]
    async fn dry_run_prevents_update_pr() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        let req = UpdatePrRequest {
            pr_number: 42,
            title: "Updated title".to_string(),
            body: "Updated body".to_string(),
        };
        manager.update_pr(req).await.unwrap();
    }

    #[tokio::test]
    async fn dry_run_prevents_replace_pr_labels() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        let req = PrLabelsRequest {
            pr_number: 42,
            labels: vec!["release".to_string()],
        };
        manager.replace_pr_labels(req).await.unwrap();
    }

    #[tokio::test]
    async fn dry_run_prevents_create_release() {
        let mock_forge = MockForge::new();

        let manager = ForgeManager::new(
            Box::new(mock_forge),
            ForgeOptions { dry_run: true },
        );

        manager
            .create_release("v1.0.0", "abc123", "Release notes")
            .await
            .unwrap();
    }
}