do-next 0.0.0-2026.3.19

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
use std::collections::HashMap;

use anyhow::{Context, Result};
use reqwest::{Client, RequestBuilder};
use serde_json::json;

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

const MAX_RESULTS: u32 = 100;

#[derive(Clone)]
pub struct JiraClient {
    client: Client,
    base_url: String,
    credentials: Credentials,
}

impl JiraClient {
    pub fn new(base_url: String, credentials: Credentials) -> Result<Self> {
        let client = Client::builder()
            .build()
            .context("Failed to build HTTP client")?;
        Ok(Self {
            client,
            base_url,
            credentials,
        })
    }

    fn apply_auth(&self, req: RequestBuilder) -> RequestBuilder {
        match &self.credentials {
            Credentials::Token(token) => req.bearer_auth(token),
            Credentials::Basic { username, password } => req.basic_auth(username, Some(password)),
        }
    }

    /// 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/2/search", self.base_url);
            log::debug!("JQL request: startAt={start_at} jql={jql}");
            let resp = self
                .apply_auth(self.client.get(&url))
                .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);
            all_issues.extend(page.issues);

            if start_at + fetched >= page.total || 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/2/issue/{key}", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/issue/{key}/transitions", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/issue/{key}/transitions", self.base_url);
        let body = json!({ "transition": { "id": transition_id } });
        let resp = self
            .apply_auth(self.client.post(&url))
            .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/2/issue/{key}/comment", self.base_url);
        let body = json!({ "body": body_text });
        let resp = self
            .apply_auth(self.client.post(&url))
            .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")
    }

    /// Assign an issue to the given username (use "`currentUser()`" or actual username).
    #[allow(dead_code)]
    pub async fn set_assignee(&self, key: &str, username: &str) -> Result<()> {
        let url = format!("{}/rest/api/2/issue/{key}/assignee", self.base_url);
        let body = json!({ "name": username });
        let resp = self
            .apply_auth(self.client.put(&url))
            .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/2/issue/{key}", self.base_url);
        let body = json!({ "fields": { field_id: value } });
        let resp = self
            .apply_auth(self.client.put(&url))
            .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/2/issue/{key}", self.base_url);
        let body = json!({
            "fields": {
                "project": { "key": target_project_key }
            }
        });
        let resp = self
            .apply_auth(self.client.put(&url))
            .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/2/myself", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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.name
            .or(me.account_id)
            .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/2/field", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/issue/{key}", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/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/2/issue/{issue_key}/editmeta", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/issue/{issue_key}/editmeta", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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/2/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/2/issue/{issue_key}/editmeta", self.base_url);
        let resp = self
            .apply_auth(self.client.get(&url))
            .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))
    }

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