do-next 0.0.0-2026.4.8

Pick your next Jira task & manage it from the terminal
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
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::{Context, Result};
use chrono::Utc;
use reqwest::{Client, RequestBuilder};
use serde_json::json;
use tokio::sync::RwLock;

use crate::jira::auth::Auth;
use crate::jira::oauth;
use crate::jira::types::{
    Attachment, Comment, FieldMeta, Issue, SearchResponse, Transition, TransitionsResponse,
};

const MAX_RESULTS: u32 = 100;

#[derive(Clone)]
pub struct JiraClient {
    client: Client,
    base_url: String,
    auth: Arc<RwLock<Auth>>,
}

impl JiraClient {
    pub fn new(site_url: String, auth: Auth) -> Result<Self> {
        let base_url = match &auth {
            Auth::Basic(_) => site_url,
            Auth::OAuth(o) => format!("https://api.atlassian.com/ex/jira/{}", o.cloud_id),
        };
        let client = Client::builder()
            .build()
            .context("Failed to build HTTP client")?;
        Ok(Self {
            client,
            base_url,
            auth: Arc::new(RwLock::new(auth)),
        })
    }

    async fn maybe_refresh(&self) -> Result<()> {
        let needs_refresh = {
            let auth = self.auth.read().await;
            match &*auth {
                Auth::OAuth(o) => o.expires_at - Utc::now() < chrono::Duration::seconds(60),
                Auth::Basic(_) => false,
            }
        };

        if needs_refresh {
            let mut auth = self.auth.write().await;
            // Double-check after acquiring write lock (another task may have refreshed).
            if let Auth::OAuth(o) = &*auth
                && o.expires_at - Utc::now() < chrono::Duration::seconds(60)
            {
                log::debug!("OAuth token expiring soon, refreshing");
                let refreshed = oauth::refresh_access_token(o).await?;
                oauth::save_oauth_tokens(&refreshed)?;
                *auth = Auth::OAuth(refreshed);
            }
        }

        Ok(())
    }

    async fn apply_auth(&self, req: RequestBuilder) -> RequestBuilder {
        let auth = self.auth.read().await;
        match &*auth {
            Auth::Basic(creds) => req.basic_auth(&creds.email, Some(&creds.api_token)),
            Auth::OAuth(creds) => req.bearer_auth(&creds.access_token),
        }
    }

    /// Fetch all issues matching a JQL query, paginating automatically.
    pub async fn fetch_jql(&self, jql: &str) -> Result<Vec<Issue>> {
        let mut all_issues = Vec::new();
        let mut start_at = 0u32;

        loop {
            let url = format!("{}/rest/api/3/search/jql", self.base_url);
            log::debug!("JQL request: startAt={start_at} jql={jql}");

            self.maybe_refresh().await?;
            let resp = self
                .apply_auth(self.client.get(&url))
                .await
                .query(&[
                    ("jql", jql),
                    ("maxResults", &MAX_RESULTS.to_string()),
                    ("startAt", &start_at.to_string()),
                    ("fields", "*all"),
                ])
                .send()
                .await
                .map_err(|e| {
                    log::error!("JQL send error: {e}");
                    let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&e);
                    while let Some(cause) = src {
                        log::error!("  caused by: {cause}");
                        src = cause.source();
                    }
                    e
                })
                .context("Failed to send JQL request")?;

            let status = resp.status();
            log::debug!("JQL response: HTTP {status}");
            if !status.is_success() {
                let body = resp.text().await.unwrap_or_default();
                log::error!("JQL API error {status}: {body}");
                anyhow::bail!("Jira API error {status}: {body}");
            }

            let page: SearchResponse = resp
                .json()
                .await
                .context("Failed to parse search response")?;
            let fetched = u32::try_from(page.issues.len()).unwrap_or(0);
            log::debug!("JQL page: fetched={fetched} isLast={}", page.is_last);
            let is_last = page.is_last;
            all_issues.extend(page.issues);

            if is_last || fetched == 0 {
                break;
            }
            start_at += fetched;
        }

        Ok(all_issues)
    }

    /// Fetch a single issue by key.
    pub async fn get_issue(&self, key: &str) -> Result<Issue> {
        let url = format!("{}/rest/api/3/issue/{key}", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch issue")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        resp.json().await.context("Failed to parse issue response")
    }

    /// Get available transitions for an issue.
    pub async fn get_transitions(&self, key: &str) -> Result<Vec<Transition>> {
        let url = format!("{}/rest/api/3/issue/{key}/transitions", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch transitions")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        let tr: TransitionsResponse = resp.json().await.context("Failed to parse transitions")?;
        Ok(tr.transitions)
    }

    /// Apply a transition to an issue.
    pub async fn post_transition(&self, key: &str, transition_id: &str) -> Result<()> {
        let url = format!("{}/rest/api/3/issue/{key}/transitions", self.base_url);
        let body = json!({ "transition": { "id": transition_id } });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.post(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to post transition")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Transition failed {status}: {body}");
        }
        Ok(())
    }

    /// Post a comment on an issue.
    pub async fn post_comment(&self, key: &str, body_text: &str) -> Result<Comment> {
        let url = format!("{}/rest/api/3/issue/{key}/comment", self.base_url);
        let body = json!({ "body": crate::jira::adf::markdown_to_adf(body_text) });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.post(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to post comment")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Post comment failed {status}: {body}");
        }

        resp.json()
            .await
            .context("Failed to parse comment response")
    }

    /// Upload a file as an attachment to an issue.
    pub async fn upload_attachment(
        &self,
        issue_key: &str,
        file_path: &std::path::Path,
    ) -> Result<Vec<Attachment>> {
        let url = format!("{}/rest/api/3/issue/{issue_key}/attachments", self.base_url);
        let filename = file_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .into_owned();
        let bytes = tokio::fs::read(file_path)
            .await
            .context("Failed to read file for upload")?;
        let part = reqwest::multipart::Part::bytes(bytes).file_name(filename);
        let form = reqwest::multipart::Form::new().part("file", part);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.post(&url))
            .await
            .header("X-Atlassian-Token", "no-check")
            .multipart(form)
            .send()
            .await
            .context("Failed to upload attachment")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Upload attachment failed {status}: {body}");
        }

        resp.json()
            .await
            .context("Failed to parse upload attachment response")
    }

    /// Assign an issue to the given account ID.
    #[allow(dead_code)]
    pub async fn set_assignee(&self, key: &str, account_id: &str) -> Result<()> {
        let url = format!("{}/rest/api/3/issue/{key}/assignee", self.base_url);
        let body = json!({ "accountId": account_id });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.put(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to set assignee")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Set assignee failed {status}: {body}");
        }
        Ok(())
    }

    /// Update a single field on an issue.
    #[allow(dead_code)]
    pub async fn update_field(
        &self,
        key: &str,
        field_id: &str,
        value: serde_json::Value,
    ) -> Result<()> {
        let url = format!("{}/rest/api/3/issue/{key}", self.base_url);
        let body = json!({ "fields": { field_id: value } });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.put(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to update field")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Update field failed {status}: {body}");
        }
        Ok(())
    }

    /// Move an issue to a different project by updating its project field.
    #[allow(dead_code)]
    pub async fn move_issue(&self, key: &str, target_project_key: &str) -> Result<()> {
        let url = format!("{}/rest/api/3/issue/{key}", self.base_url);
        let body = json!({
            "fields": {
                "project": { "key": target_project_key }
            }
        });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.put(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to move issue")?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Move issue failed {status}: {body}");
        }
        Ok(())
    }

    /// Get the currently authenticated user's username/name.
    pub async fn current_user(&self) -> Result<String> {
        #[derive(serde::Deserialize)]
        struct MyselfResponse {
            name: Option<String>,
            #[serde(rename = "accountId")]
            account_id: Option<String>,
        }

        let url = format!("{}/rest/api/3/myself", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch current user")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Fetch current user failed {status}: {body}");
        }

        let me: MyselfResponse = resp
            .json()
            .await
            .context("Failed to parse myself response")?;
        me.account_id
            .or(me.name)
            .ok_or_else(|| anyhow::anyhow!("Could not determine current user"))
    }

    /// Fetch all field definitions from this Jira instance.
    pub async fn get_all_fields(&self) -> Result<Vec<FieldMeta>> {
        let url = format!("{}/rest/api/3/field", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch field definitions")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        resp.json()
            .await
            .context("Failed to parse field definitions")
    }

    /// Fetch a single issue with all fields (`fields=*all`).
    pub async fn get_issue_all_fields(&self, key: &str) -> Result<serde_json::Value> {
        let url = format!("{}/rest/api/3/issue/{key}", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .query(&[("fields", "*all")])
            .send()
            .await
            .context("Failed to fetch issue")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        resp.json().await.context("Failed to parse issue response")
    }

    /// Fetch allowed values for a field via `GET /rest/api/3/issue/{key}/editmeta`.
    pub async fn get_field_options(
        &self,
        issue_key: &str,
        field_id: &str,
    ) -> Result<Vec<crate::jira::types::FieldOption>> {
        let url = format!("{}/rest/api/3/issue/{issue_key}/editmeta", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch editmeta")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        let body: serde_json::Value = resp
            .json()
            .await
            .context("Failed to parse editmeta response")?;

        let pointer = format!("/fields/{field_id}/allowedValues");
        let allowed = body
            .pointer(&pointer)
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        let options = allowed
            .into_iter()
            .filter_map(|item| {
                let value = item
                    .get("value")
                    .or_else(|| item.get("name"))
                    .and_then(|v| v.as_str())?
                    .to_string();
                Some(crate::jira::types::FieldOption { value })
            })
            .collect();

        Ok(options)
    }

    /// Fetch the raw editmeta JSON object for a single field.
    /// Useful for inspecting what keys Jira actually returns (e.g. to find where hint text lives).
    pub async fn get_editmeta_field_raw(
        &self,
        issue_key: &str,
        field_id: &str,
    ) -> Result<serde_json::Value> {
        let url = format!("{}/rest/api/3/issue/{issue_key}/editmeta", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch editmeta")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        let body: serde_json::Value = resp
            .json()
            .await
            .context("Failed to parse editmeta response")?;

        body.pointer(&format!("/fields/{field_id}"))
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Field '{field_id}' not found in editmeta"))
    }

    /// Fetch display names and schema types for a set of field IDs via
    /// `GET /rest/api/3/issue/{key}/editmeta`.
    /// Returns `(names, schemas)` where both are `field_id → value`.
    /// Unknown fields are silently omitted.
    pub async fn get_field_labels(
        &self,
        issue_key: &str,
        field_ids: &[&str],
    ) -> Result<(HashMap<String, String>, HashMap<String, String>)> {
        let url = format!("{}/rest/api/3/issue/{issue_key}/editmeta", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(&url))
            .await
            .send()
            .await
            .context("Failed to fetch editmeta")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Jira API error {status}: {body}");
        }

        let body: serde_json::Value = resp
            .json()
            .await
            .context("Failed to parse editmeta response")?;

        let mut names = HashMap::new();
        let mut schemas = HashMap::new();
        for field_id in field_ids {
            let name_ptr = format!("/fields/{field_id}/name");
            if let Some(name) = body.pointer(&name_ptr).and_then(|v| v.as_str()) {
                names.insert((*field_id).to_string(), name.to_string());
            }
            let schema_ptr = format!("/fields/{field_id}/schema/type");
            if let Some(schema_type) = body.pointer(&schema_ptr).and_then(|v| v.as_str()) {
                schemas.insert((*field_id).to_string(), schema_type.to_string());
            }
        }
        Ok((names, schemas))
    }

    /// Update the body of an existing comment.
    pub async fn update_comment(
        &self,
        issue_key: &str,
        comment_id: &str,
        new_body: &str,
    ) -> Result<Comment> {
        let url = format!(
            "{}/rest/api/3/issue/{issue_key}/comment/{comment_id}",
            self.base_url
        );
        let body = serde_json::json!({ "body": crate::jira::adf::markdown_to_adf(new_body) });
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.put(&url))
            .await
            .json(&body)
            .send()
            .await
            .context("Failed to update comment")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Update comment failed {status}: {body}");
        }
        resp.json().await.context("Failed to parse updated comment")
    }

    /// Delete a comment.
    pub async fn delete_comment(&self, issue_key: &str, comment_id: &str) -> Result<()> {
        let url = format!(
            "{}/rest/api/3/issue/{issue_key}/comment/{comment_id}",
            self.base_url
        );
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.delete(&url))
            .await
            .send()
            .await
            .context("Failed to delete comment")?;

        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Delete comment failed {status}: {body}");
        }
        Ok(())
    }

    /// Delete an attachment by its ID.
    pub async fn delete_attachment(&self, attachment_id: &str) -> Result<()> {
        let url = format!("{}/rest/api/3/attachment/{attachment_id}", self.base_url);
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.delete(&url))
            .await
            .send()
            .await
            .context("Failed to delete attachment")?;
        let status = resp.status();
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_default();
            anyhow::bail!("Delete attachment failed {status}: {body}");
        }
        Ok(())
    }

    /// Download the raw bytes of an attachment by its content URL.
    pub async fn download_attachment(&self, url: &str) -> Result<Vec<u8>> {
        self.maybe_refresh().await?;
        let resp = self
            .apply_auth(self.client.get(url))
            .await
            .send()
            .await
            .context("Failed to download attachment")?;
        let status = resp.status();
        if !status.is_success() {
            anyhow::bail!(
                "Failed to download {status}: {}",
                resp.text().await.unwrap_or_default()
            );
        }
        Ok(resp.bytes().await?.to_vec())
    }

    #[allow(dead_code)]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }
}