devboy-cli 0.28.0

Command-line interface for devboy-tools — `devboy` binary. Primary distribution is npm (@devboy-tools/cli); `cargo install devboy-cli` is the secondary channel.
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
//! Test provider with Record/Replay support.
//!
//! Implements the Record & Replay pattern from ADR-003.

use std::env;

use async_trait::async_trait;
use devboy_core::{
    Comment, CreateCommentInput, CreateIssueInput, Discussion, Error, FileDiff, Issue, IssueFilter,
    IssueProvider, MergeRequest, MergeRequestProvider, MrFilter, Provider, ProviderResult, Result,
    UpdateIssueInput, User,
};
use devboy_github::GitHubClient;
use secrecy::SecretString;

use super::api_result::ApiResult;
use super::{FixtureProvider, TestMode};

/// Test provider that supports Record/Replay modes.
///
/// In Record mode: calls real API and saves responses to fixtures.
/// In Replay mode: loads data from fixtures.
pub struct TestProvider {
    mode: TestMode,
    provider_name: String,
    github_client: Option<GitHubClient>,
    fixture_provider: FixtureProvider,
}

impl TestProvider {
    /// Create a new test provider for GitHub.
    ///
    /// Detects mode based on GITHUB_TOKEN environment variable.
    pub fn github() -> Self {
        Self::new("github")
    }

    /// Create a new test provider.
    fn new(provider_name: &str) -> Self {
        let mode = TestMode::detect(provider_name);

        let github_client = if mode.is_record() && provider_name == "github" {
            // Get GitHub configuration from environment
            let token = env::var("GITHUB_TOKEN").ok();
            let owner = env::var("GITHUB_OWNER").unwrap_or_else(|_| "meteora-pro".to_string());
            let repo = env::var("GITHUB_REPO").unwrap_or_else(|_| "devboy-tools".to_string());

            token.map(|t| GitHubClient::new(&owner, &repo, SecretString::from(t)))
        } else {
            None
        };

        Self {
            mode,
            provider_name: provider_name.to_string(),
            github_client,
            fixture_provider: FixtureProvider::new(provider_name),
        }
    }

    /// Get the test mode.
    pub fn mode(&self) -> TestMode {
        self.mode
    }

    /// Get the provider name.
    pub fn name(&self) -> &str {
        &self.provider_name
    }

    /// Get issues with fallback support.
    pub async fn get_issues_with_fallback(&self, filter: IssueFilter) -> ApiResult<Vec<Issue>> {
        match self.mode {
            TestMode::Replay => {
                // Load from fixtures
                match self.fixture_provider.load_issues() {
                    Ok(issues) => ApiResult::Ok(issues),
                    Err(e) => ApiResult::ConfigError {
                        message: format!("Failed to load fixtures: {}", e),
                    },
                }
            }
            TestMode::Record => {
                let Some(client) = &self.github_client else {
                    return ApiResult::ConfigError {
                        message: "GitHub client not initialized".to_string(),
                    };
                };

                match client.get_issues(filter).await {
                    Ok(result) => {
                        let issues = result.items;
                        // Save to fixtures for future replay
                        if let Err(e) = self.fixture_provider.save_issues(&issues) {
                            eprintln!("⚠️  Failed to save fixtures: {}", e);
                        }
                        ApiResult::Ok(issues)
                    }
                    Err(e) => self.handle_api_error(e, || self.fixture_provider.load_issues()),
                }
            }
        }
    }

    /// Get merge requests with fallback support.
    pub async fn get_merge_requests_with_fallback(
        &self,
        filter: MrFilter,
    ) -> ApiResult<Vec<MergeRequest>> {
        match self.mode {
            TestMode::Replay => {
                // Load from fixtures
                match self.fixture_provider.load_merge_requests() {
                    Ok(mrs) => ApiResult::Ok(mrs),
                    Err(e) => ApiResult::ConfigError {
                        message: format!("Failed to load fixtures: {}", e),
                    },
                }
            }
            TestMode::Record => {
                let Some(client) = &self.github_client else {
                    return ApiResult::ConfigError {
                        message: "GitHub client not initialized".to_string(),
                    };
                };

                match client.get_merge_requests(filter).await {
                    Ok(result) => {
                        let mrs = result.items;
                        // Save to fixtures for future replay
                        if let Err(e) = self.fixture_provider.save_merge_requests(&mrs) {
                            eprintln!("⚠️  Failed to save fixtures: {}", e);
                        }
                        ApiResult::Ok(mrs)
                    }
                    Err(e) => {
                        self.handle_api_error(e, || self.fixture_provider.load_merge_requests())
                    }
                }
            }
        }
    }

    /// Get current user with fallback support.
    pub async fn get_current_user_with_fallback(&self) -> ApiResult<User> {
        match self.mode {
            TestMode::Replay => {
                // Return a mock user for replay mode
                ApiResult::Ok(User {
                    id: "1".to_string(),
                    username: "test-user".to_string(),
                    name: Some("Test User".to_string()),
                    email: None,
                    avatar_url: None,
                })
            }
            TestMode::Record => {
                let Some(client) = &self.github_client else {
                    return ApiResult::ConfigError {
                        message: "GitHub client not initialized".to_string(),
                    };
                };

                match client.get_current_user().await {
                    Ok(user) => ApiResult::Ok(user),
                    Err(e) => {
                        if e.is_auth_error() {
                            ApiResult::ConfigError {
                                message: format!("Authentication error: {}", e),
                            }
                        } else {
                            eprintln!("⚠️  API error, using mock user: {}", e);
                            ApiResult::Fallback {
                                data: User {
                                    id: "1".to_string(),
                                    username: "test-user".to_string(),
                                    name: Some("Test User".to_string()),
                                    email: None,
                                    avatar_url: None,
                                },
                                reason: format!("API error: {}", e),
                            }
                        }
                    }
                }
            }
        }
    }

    /// Handle API errors with fallback logic.
    ///
    /// - 401/403: Configuration error (test fails)
    /// - 5xx/Network: Fallback to fixtures
    fn handle_api_error<T, F>(&self, error: Error, load_fixture: F) -> ApiResult<T>
    where
        F: FnOnce() -> Result<T>,
    {
        // Authentication errors - test should fail
        if error.is_auth_error() {
            return ApiResult::ConfigError {
                message: format!("Authentication error: {}", error),
            };
        }

        // Check if retryable (5xx, network errors, etc.)
        if error.is_retryable() {
            eprintln!("⚠️  Retryable error, falling back to fixtures: {}", error);
            match load_fixture() {
                Ok(data) => ApiResult::Fallback {
                    data,
                    reason: format!("Retryable error: {}", error),
                },
                Err(e) => ApiResult::ConfigError {
                    message: format!("API failed and fixtures unavailable: {}", e),
                },
            }
        } else {
            // Non-retryable API errors - also try fallback
            eprintln!("⚠️  API error, falling back to fixtures: {}", error);
            match load_fixture() {
                Ok(data) => ApiResult::Fallback {
                    data,
                    reason: format!("API error: {}", error),
                },
                Err(e) => ApiResult::ConfigError {
                    message: format!("API failed and fixtures unavailable: {}", e),
                },
            }
        }
    }
}

/// Implement IssueProvider for TestProvider.
#[async_trait]
impl IssueProvider for TestProvider {
    async fn get_issues(&self, filter: IssueFilter) -> Result<ProviderResult<Issue>> {
        self.get_issues_with_fallback(filter)
            .await
            .into_result()
            .map(|v| v.into())
            .map_err(Error::Config)
    }

    async fn get_issue(&self, key: &str) -> Result<Issue> {
        // Find in the list
        let result = self.get_issues(IssueFilter::default()).await?;
        result
            .items
            .into_iter()
            .find(|i| i.key == key)
            .ok_or_else(|| Error::NotFound(format!("Issue {} not found", key)))
    }

    async fn create_issue(&self, _input: CreateIssueInput) -> Result<Issue> {
        Err(Error::Config(
            "Create issue not supported in tests".to_string(),
        ))
    }

    async fn update_issue(&self, _key: &str, _input: UpdateIssueInput) -> Result<Issue> {
        Err(Error::Config(
            "Update issue not supported in tests".to_string(),
        ))
    }

    async fn get_comments(&self, issue_key: &str) -> Result<ProviderResult<Comment>> {
        if self.mode.is_record() {
            let Some(client) = &self.github_client else {
                return Err(Error::Config("GitHub client not initialized".to_string()));
            };
            client.get_comments(issue_key).await
        } else {
            // In replay mode, return mock comments
            Ok(vec![Comment {
                id: "1".to_string(),
                body: "Test comment".to_string(),
                author: None,
                created_at: Some("2024-01-01T00:00:00Z".to_string()),
                updated_at: None,
                position: None,
            }]
            .into())
        }
    }

    async fn add_comment(&self, _issue_key: &str, _body: &str) -> Result<Comment> {
        Err(Error::Config(
            "Add comment not supported in tests".to_string(),
        ))
    }

    fn provider_name(&self) -> &'static str {
        "github"
    }
}

/// Implement MergeRequestProvider for TestProvider.
#[async_trait]
impl MergeRequestProvider for TestProvider {
    async fn get_merge_requests(&self, filter: MrFilter) -> Result<ProviderResult<MergeRequest>> {
        self.get_merge_requests_with_fallback(filter)
            .await
            .into_result()
            .map(|v| v.into())
            .map_err(Error::Config)
    }

    async fn get_merge_request(&self, key: &str) -> Result<MergeRequest> {
        let result = self.get_merge_requests(MrFilter::default()).await?;
        result
            .items
            .into_iter()
            .find(|mr| mr.key == key)
            .ok_or_else(|| Error::NotFound(format!("MR {} not found", key)))
    }

    async fn get_discussions(&self, mr_key: &str) -> Result<ProviderResult<Discussion>> {
        if self.mode.is_record() {
            let Some(client) = &self.github_client else {
                return Err(Error::Config("GitHub client not initialized".to_string()));
            };
            client.get_discussions(mr_key).await
        } else {
            // In replay mode, return mock discussions
            Ok(vec![Discussion {
                id: "1".to_string(),
                resolved: false,
                resolved_by: None,
                comments: vec![Comment {
                    id: "1".to_string(),
                    body: "Review comment".to_string(),
                    author: None,
                    created_at: Some("2024-01-01T00:00:00Z".to_string()),
                    updated_at: None,
                    position: None,
                }],
                position: None,
            }]
            .into())
        }
    }

    async fn get_diffs(&self, mr_key: &str) -> Result<ProviderResult<FileDiff>> {
        if self.mode.is_record() {
            let Some(client) = &self.github_client else {
                return Err(Error::Config("GitHub client not initialized".to_string()));
            };
            client.get_diffs(mr_key).await
        } else {
            // In replay mode, return mock diffs
            Ok(vec![FileDiff {
                file_path: "src/main.rs".to_string(),
                old_path: None,
                new_file: false,
                deleted_file: false,
                renamed_file: false,
                diff: "+added line\n-removed line".to_string(),
                additions: Some(1),
                deletions: Some(1),
            }]
            .into())
        }
    }

    async fn add_comment(&self, _mr_key: &str, _input: CreateCommentInput) -> Result<Comment> {
        Err(Error::Config(
            "Add comment not supported in tests".to_string(),
        ))
    }

    fn provider_name(&self) -> &'static str {
        "github"
    }
}

#[async_trait]
impl devboy_core::PipelineProvider for TestProvider {
    fn provider_name(&self) -> &'static str {
        "test"
    }
}

/// Implement Provider for TestProvider.
#[async_trait]
impl Provider for TestProvider {
    async fn get_current_user(&self) -> Result<User> {
        self.get_current_user_with_fallback()
            .await
            .into_result()
            .map_err(Error::Config)
    }
}

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

    #[tokio::test]
    async fn test_provider_replay_mode() {
        // Temporarily remove token to test replay mode
        temp_env::with_var_unset("GITHUB_TOKEN", || {
            let provider = TestProvider::github();
            assert!(provider.mode().is_replay());
        });
    }

    #[tokio::test]
    async fn test_provider_loads_fixtures_in_replay() {
        temp_env::async_with_vars([("GITHUB_TOKEN", None::<&str>)], async {
            let provider = TestProvider::github();
            let issues = provider
                .get_issues(IssueFilter::default())
                .await
                .unwrap()
                .items;
            assert!(!issues.is_empty());
            assert!(issues[0].key.starts_with("gh#"));
        })
        .await;
    }

    #[tokio::test]
    async fn test_provider_loads_mrs_in_replay() {
        temp_env::async_with_vars([("GITHUB_TOKEN", None::<&str>)], async {
            let provider = TestProvider::github();
            let mrs = provider
                .get_merge_requests(MrFilter::default())
                .await
                .unwrap()
                .items;
            assert!(!mrs.is_empty());
            assert!(mrs[0].key.starts_with("pr#"));
        })
        .await;
    }
}