jira-cli 0.4.11

Agent-friendly Jira CLI with JSON output, structured exit codes, and schema introspection
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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! Project-scoped metadata and conservative normalization for issue writes.

use super::{ApiError, JiraClient, validate_issue_key};
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::BTreeMap;

mod validation;
use validation::{normalize_named_arrays, validate_required};

type Fields = BTreeMap<String, Value>;
const EPIC_LINK_SCHEMA: &str = "com.pyxis.greenhopper.jira:gh-epic-link";

#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct IssueType {
    #[serde(default)]
    id: String,
    name: String,
    #[serde(default)]
    subtask: bool,
    hierarchy_level: Option<i64>,
    fields: Option<Fields>,
}

impl IssueType {
    fn is_subtask(&self) -> bool {
        self.subtask
            || self.hierarchy_level == Some(-1)
            || matches!(
                self.name.to_ascii_lowercase().as_str(),
                "subtask" | "sub-task"
            )
    }
    fn is_epic(&self) -> bool {
        self.hierarchy_level == Some(1) || self.name.eq_ignore_ascii_case("Epic")
    }

    fn can_belong_to_epic(&self) -> bool {
        !self.is_subtask() && self.hierarchy_level.is_none_or(|level| level == 0) && !self.is_epic()
    }
}

pub(super) struct CreateMetadata {
    issue_type: IssueType,
    fields: Option<Fields>,
    subtask_types: Vec<Value>,
}

impl JiraClient {
    // Unsupported endpoints are optional. Authentication, rate limits, network
    // failures and server errors must not be mistaken for absent metadata.
    async fn optional_metadata(&self, path: &str) -> Result<Option<Value>, ApiError> {
        match self.get(path).await {
            Ok(value) => Ok(Some(value)),
            Err(ApiError::NotFound(_))
            | Err(ApiError::Api {
                status: 405 | 410 | 501,
                ..
            }) => Ok(None),
            Err(err) => Err(err),
        }
    }

    /// Cloud calls its arrays `issueTypes`/`fields`; DC uses `values`.
    async fn metadata_pages(
        &self,
        path: &str,
        array: &str,
    ) -> Result<Option<Vec<Value>>, ApiError> {
        let mut values = Vec::new();
        let mut start = 0;
        loop {
            let Some(page) = self
                .optional_metadata(&format!("{path}?startAt={start}&maxResults=100"))
                .await?
            else {
                if start == 0 {
                    return Ok(None);
                }
                return Err(ApiError::Other(
                    "Jira metadata pagination became unavailable".into(),
                ));
            };
            let items = page
                .get(array)
                .or_else(|| page.get("values"))
                .and_then(Value::as_array)
                .ok_or_else(|| {
                    ApiError::Other("Invalid Jira metadata page: missing items".into())
                })?;
            let next = start + items.len();
            if page["startAt"]
                .as_u64()
                .is_some_and(|n| n as usize != start)
            {
                return Err(ApiError::Other(
                    "Jira metadata pagination did not advance".into(),
                ));
            }
            values.extend(items.iter().cloned());
            let total = page["total"].as_u64().map(|n| n as usize);
            if page["isLast"] == true || total.is_some_and(|n| next >= n) {
                return Ok(Some(values));
            }
            if items.is_empty() {
                return Err(ApiError::Other(
                    "Jira metadata pagination did not advance".into(),
                ));
            }
            if total.is_none() && page["isLast"].as_bool().is_none() {
                return Err(ApiError::Other(
                    "Invalid Jira metadata page: missing pagination".into(),
                ));
            }
            start = next;
        }
    }

    async fn legacy_create_metadata(
        &self,
        project: &str,
    ) -> Result<Option<Vec<IssueType>>, ApiError> {
        let parameter = if project.bytes().all(|b| b.is_ascii_digit()) {
            "projectIds"
        } else {
            "projectKeys"
        };
        let project_query: String =
            reqwest::Url::parse_with_params("http://localhost", &[(parameter, project)])
                .expect("static URL")
                .query()
                .unwrap()
                .into();
        let Some(meta) = self
            .optional_metadata(&format!(
                "issue/createmeta?{project_query}&expand=projects.issuetypes.fields"
            ))
            .await?
        else {
            return Ok(None);
        };
        let projects = meta["projects"].as_array().ok_or_else(|| {
            ApiError::Other("Invalid Jira create metadata: missing projects".into())
        })?;
        let types = projects
            .iter()
            .find(|p| {
                p["key"]
                    .as_str()
                    .is_some_and(|key| key.eq_ignore_ascii_case(project))
                    || p["id"].as_str() == Some(project)
            })
            .map(|p| p["issuetypes"].clone())
            .unwrap_or(json!([]));
        decode(types).map(Some)
    }

    pub(super) async fn create_metadata(
        &self,
        project: &str,
        input: &str,
    ) -> Result<Option<CreateMetadata>, ApiError> {
        let path = format!("issue/createmeta/{}/issuetypes", encode_segment(project));
        let types: Vec<IssueType> = match self.metadata_pages(&path, "issueTypes").await? {
            Some(types) => decode(json!(types))?,
            None => match self.legacy_create_metadata(project).await? {
                Some(types) => types,
                None => return Ok(None),
            },
        };
        let options = types
            .iter()
            .map(|t| json!({"id": t.id, "name": t.name}))
            .collect::<Vec<_>>();
        let selected = match_option("issue type", input, &options, OptionMatch::NameOrId)?;
        let subtask_types = types
            .iter()
            .filter(|t| t.is_subtask())
            .map(|t| json!({"id": t.id, "name": t.name}))
            .collect();
        let issue_type = types[selected].clone();
        let fields = if let Some(fields) = &issue_type.fields {
            Some(fields.clone())
        } else {
            match self
                .metadata_pages(
                    &format!("{path}/{}", encode_segment(&issue_type.id)),
                    "fields",
                )
                .await?
            {
                Some(fields) => Some(
                    fields
                        .into_iter()
                        .map(|field| {
                            let key = field["fieldId"]
                                .as_str()
                                .or_else(|| field["key"].as_str())
                                .ok_or_else(|| {
                                    ApiError::Other(
                                        "Invalid Jira field metadata: missing field ID".into(),
                                    )
                                })?;
                            Ok((key.to_owned(), field))
                        })
                        .collect::<Result<_, ApiError>>()?,
                ),
                None => self
                    .legacy_create_metadata(project)
                    .await?
                    .and_then(|types| types.into_iter().find(|t| t.id == issue_type.id))
                    .and_then(|t| t.fields),
            }
        };
        Ok(Some(CreateMetadata {
            issue_type,
            fields,
            subtask_types,
        }))
    }

    pub(super) async fn issue_type_for_link(&self, key: &str) -> Result<IssueType, ApiError> {
        validate_issue_key(key)?;
        let issue: Value = self.get(&format!("issue/{key}?fields=issuetype")).await?;
        decode(issue["fields"]["issuetype"].clone())
    }

    async fn epic_field(&self, fields: Option<&Fields>) -> Result<String, ApiError> {
        if let Some(fields) = fields {
            // Cloud has retired Epic Link. DC can expose parent for subtasks
            // alongside Epic Link, so prefer the custom field there.
            if self.api_version >= 3 && fields.contains_key("parent") {
                return Ok("parent".into());
            }
            if let Some(id) = find_epic_field(fields)? {
                return Ok(id);
            }
            if fields.contains_key("parent") {
                return Ok("parent".into());
            }
        } else if self.api_version >= 3 {
            return Ok("parent".into());
        } else {
            let fields = self
                .list_fields()
                .await?
                .into_iter()
                .map(|field| {
                    (
                        field.id.clone(),
                        serde_json::to_value(field).expect("field serializes"),
                    )
                })
                .collect();
            if let Some(id) = find_epic_field(&fields)? {
                return Ok(id);
            }
        }
        Err(ApiError::InvalidInput(
            "Cannot resolve epic linkage: neither Epic Link nor an epic parent is available in this issue's metadata. Enable Epic Link on the create/edit screen or inspect `jira fields list` and use --field <ID>=<EPIC>.".into()
        ))
    }

    async fn set_epic(
        &self,
        fields: &mut Value,
        meta: Option<&Fields>,
        issue_type: &IssueType,
        epic: &str,
    ) -> Result<(), ApiError> {
        if !issue_type.can_belong_to_epic() {
            return Err(ApiError::InvalidInput(format!(
                "Issue type {:?} cannot be added to an Epic; use --epic {epic} with a standard issue type such as Story or Task. For a subtask, use --parent <STORY-OR-TASK>.",
                issue_type.name
            )));
        }
        let field = self.epic_field(meta).await?;
        validate_epic_override(fields, meta, &field)?;
        fields[&field] = if field == "parent" {
            json!({"key": epic})
        } else {
            json!(epic)
        };
        Ok(())
    }

    pub(super) async fn prepare_create(
        &self,
        fields: &mut Value,
        draft: &super::IssueDraft<'_>,
        custom: &[(String, Value)],
    ) -> Result<Option<CreateMetadata>, ApiError> {
        if draft.parent.is_some() && draft.epic.is_some() {
            return Err(ApiError::InvalidInput(
                "--parent and --epic cannot be used together".into(),
            ));
        }
        let input = fields["issuetype"]["id"]
            .as_str()
            .or_else(|| fields["issuetype"]["name"].as_str())
            .ok_or_else(|| ApiError::InvalidInput("issuetype requires a name or ID".into()))?
            .to_owned();
        let project = fields["project"]["key"]
            .as_str()
            .or_else(|| fields["project"]["id"].as_str())
            .ok_or_else(|| ApiError::InvalidInput("project requires a key or ID".into()))?;
        let meta = self.create_metadata(project, &input).await?;
        let fallback = IssueType {
            id: String::new(),
            name: input,
            subtask: false,
            hierarchy_level: None,
            fields: None,
        };
        let issue_type = meta.as_ref().map(|m| &m.issue_type).unwrap_or(&fallback);
        if meta.is_some() {
            fields["issuetype"] = named_id(&issue_type.id, &issue_type.name);
        }
        let field_meta = meta.as_ref().and_then(|m| m.fields.as_ref());
        if let Some(priority) = draft
            .priority
            .filter(|_| !custom.iter().any(|(key, _)| key == "priority"))
        {
            normalize_priority(fields, field_meta, priority)?;
        }
        normalize_named_arrays(fields, field_meta, custom)?;
        if let Some(key) = draft.epic.or(draft.parent) {
            let target = self.issue_type_for_link(key).await?;
            if draft.epic.is_some() && !target.is_epic() {
                return Err(ApiError::InvalidInput(format!(
                    "--epic {key} targets issue type {:?}, not an Epic",
                    target.name
                )));
            }
            if target.is_epic() {
                // The ordinary parent is added by this method only after we
                // know the target type, so an explicit --field stays detectable.
                self.set_epic(fields, field_meta, issue_type, key).await?;
            } else if fields.get("parent").is_none() {
                if let Some(meta) = &meta {
                    validate_parent_type(issue_type, &target, key, &meta.subtask_types)?;
                }
                fields["parent"] = json!({"key": key});
            }
        }
        if meta.is_some()
            && issue_type.is_subtask()
            && fields.get("parent").is_none_or(Value::is_null)
        {
            return Err(ApiError::InvalidInput(format!(
                "Issue type {:?} requires --parent <STORY-OR-TASK>",
                issue_type.name
            )));
        }
        validate_required(fields, field_meta, true)?;
        Ok(meta)
    }

    pub(super) async fn prepare_update(
        &self,
        key: &str,
        fields: &mut Value,
        update: &super::IssueUpdate<'_>,
        custom: &[(String, Value)],
    ) -> Result<Option<Fields>, ApiError> {
        let priority = update
            .priority
            .filter(|_| !custom.iter().any(|(key, _)| key == "priority"));
        if update.epic.is_some() && update.clear_epic {
            return Err(ApiError::InvalidInput(
                "--epic and --clear-epic cannot be used together".into(),
            ));
        }
        let meta = self
            .optional_metadata(&format!("issue/{key}/editmeta"))
            .await?
            .map(|meta| decode::<Fields>(meta["fields"].clone()))
            .transpose()?;
        if let Some(priority) = priority {
            normalize_priority(fields, meta.as_ref(), priority)?;
        }
        normalize_named_arrays(fields, meta.as_ref(), custom)?;
        if let Some(epic) = update.epic {
            if key.eq_ignore_ascii_case(epic) {
                return Err(ApiError::InvalidInput(
                    "An issue cannot be its own epic".into(),
                ));
            }
            let target = self.issue_type_for_link(epic).await?;
            if !target.is_epic() {
                return Err(ApiError::InvalidInput(format!(
                    "--epic {epic} targets issue type {:?}, not an Epic",
                    target.name
                )));
            }
            let issue_type = self.issue_type_for_link(key).await?;
            self.set_epic(fields, meta.as_ref(), &issue_type, epic)
                .await?;
        }
        if update.clear_epic {
            let issue_type = self.issue_type_for_link(key).await?;
            if !issue_type.can_belong_to_epic() {
                return Err(ApiError::InvalidInput(format!(
                    "Cannot use --clear-epic on issue type {:?}; only standard issues can have epic membership cleared",
                    issue_type.name
                )));
            }
            let field = self.epic_field(meta.as_ref()).await?;
            validate_epic_override(fields, meta.as_ref(), &field)?;
            fields[&field] = Value::Null;
        }
        validate_required(fields, meta.as_ref(), false)?;
        Ok(meta)
    }
}

fn validate_epic_override(
    fields: &Value,
    meta: Option<&Fields>,
    field: &str,
) -> Result<(), ApiError> {
    let conflict = meta
        .and_then(|meta| {
            meta.iter()
                .find(|(id, definition)| is_epic_field(id, definition) && fields.get(*id).is_some())
                .map(|(id, _)| id.as_str())
        })
        .or_else(|| fields.get("parent").map(|_| "parent"))
        .or_else(|| fields.get(field).map(|_| field));
    if let Some(conflict) = conflict {
        return Err(ApiError::InvalidInput(format!(
            "Epic linkage conflicts with --field {conflict}; specify the relationship only once"
        )));
    }
    Ok(())
}

fn validate_parent_type(
    child: &IssueType,
    parent: &IssueType,
    key: &str,
    subtask_types: &[Value],
) -> Result<(), ApiError> {
    if parent.is_subtask() {
        return Err(ApiError::InvalidInput(format!(
            "--parent {key} is a subtask and cannot have child issues; choose a Story or Task"
        )));
    }
    if let (Some(child_level), Some(parent_level)) = (child.hierarchy_level, parent.hierarchy_level)
    {
        if child_level + 1 == parent_level {
            return Ok(());
        }
        if parent_level != 0 {
            return Err(ApiError::InvalidInput(format!(
                "Issue type {:?} is not directly below parent type {:?} in the hierarchy",
                child.name, parent.name
            )));
        }
    } else if child.is_subtask() {
        return Ok(());
    }
    Err(ApiError::InvalidInput(format!(
        "--parent {key} requires a subtask issue type; selected {:?}. Choose --type from: {}",
        child.name,
        option_names(subtask_types)
    )))
}

fn decode<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, ApiError> {
    serde_json::from_value(value)
        .map_err(|err| ApiError::Other(format!("Invalid Jira metadata: {err}")))
}

fn encode_segment(value: &str) -> String {
    let mut url = reqwest::Url::parse("http://localhost").expect("static URL");
    url.path_segments_mut()
        .expect("URL supports paths")
        .push(value);
    url.path().trim_start_matches('/').into()
}

fn named_id(id: &str, name: &str) -> Value {
    if id.is_empty() {
        json!({"name": name})
    } else {
        json!({"id": id})
    }
}

pub(super) fn unresolved_option(input: &str) -> Value {
    let input = input.trim();
    if !input.is_empty() && input.bytes().all(|b| b.is_ascii_digit()) {
        json!({"id": input})
    } else {
        json!({"name": input})
    }
}

fn find_epic_field(fields: &Fields) -> Result<Option<String>, ApiError> {
    let schema_matches = fields
        .iter()
        .filter(|(_, f)| f["schema"]["custom"] == EPIC_LINK_SCHEMA)
        .map(|(id, _)| id)
        .collect::<Vec<_>>();
    let matches = if schema_matches.is_empty() {
        fields
            .iter()
            .filter(|(id, f)| is_epic_field(id, f))
            .map(|(id, _)| id)
            .collect::<Vec<_>>()
    } else {
        schema_matches
    };
    match matches.as_slice() {
        [] => Ok(None),
        [id] => Ok(Some((*id).clone())),
        _ => Err(ApiError::InvalidInput(format!(
            "Ambiguous Epic Link fields: {}; use --field <ID>=<EPIC> to choose one",
            matches.into_iter().cloned().collect::<Vec<_>>().join(", ")
        ))),
    }
}

fn is_epic_field(id: &str, field: &Value) -> bool {
    field["schema"]["custom"] == EPIC_LINK_SCHEMA
        || (id.starts_with("customfield_")
            && field["name"]
                .as_str()
                .is_some_and(|name| name.eq_ignore_ascii_case("Epic Link")))
}

fn normalize_priority(
    fields: &mut Value,
    meta: Option<&Fields>,
    input: &str,
) -> Result<(), ApiError> {
    let Some(meta) = meta else {
        return Ok(());
    };
    let priority = meta.get("priority").ok_or_else(|| ApiError::InvalidInput(
        "Priority is not available on this issue's create/edit screen; omit --priority to keep the project default or ask an administrator to enable it".into()
    ))?;
    if let Some(options) = priority["allowedValues"].as_array() {
        let selected = &options[match_option("priority", input, options, OptionMatch::Priority)?];
        fields["priority"] = named_id(
            selected["id"].as_str().unwrap_or(""),
            selected["name"].as_str().unwrap_or(input),
        );
    }
    Ok(())
}

/// Prefer an exact name/ID, then case-insensitive names, then a unique label
/// with a numeric rank removed, then prefixes. Never guess between ties.
#[derive(Clone, Copy, PartialEq)]
enum OptionMatch {
    NameOrId,
    Prefix,
    Priority,
}

fn match_option(
    field: &str,
    input: &str,
    options: &[Value],
    style: OptionMatch,
) -> Result<usize, ApiError> {
    let input = input.trim();
    let lower = input.to_lowercase();
    for tier in 0..4 {
        let candidates = options
            .iter()
            .enumerate()
            .filter(|(_, option)| {
                let name = option["name"].as_str().unwrap_or("");
                !input.is_empty()
                    && match tier {
                        0 => name == input || option["id"].as_str() == Some(input),
                        1 => name.to_lowercase() == lower,
                        2 => {
                            style == OptionMatch::Priority
                                && priority_label(name).to_lowercase() == lower
                        }
                        _ => {
                            style != OptionMatch::NameOrId
                                && (name.to_lowercase().starts_with(&lower)
                                    || (style == OptionMatch::Priority
                                        && priority_label(name).to_lowercase().starts_with(&lower)))
                        }
                    }
            })
            .map(|(index, _)| index)
            .collect::<Vec<_>>();
        if let [index] = candidates.as_slice() {
            return Ok(*index);
        }
        if candidates.len() > 1 {
            return Err(option_error(field, input, options, true));
        }
    }
    Err(option_error(field, input, options, false))
}

fn priority_label(name: &str) -> &str {
    let name = name.trim();
    let rest = name.trim_start_matches(|c: char| c.is_ascii_digit());
    if rest.len() != name.len() {
        let rest = rest.trim_start();
        if let Some(label) = rest.strip_prefix(['-', '\u{2013}', '\u{2014}', ':', '.']) {
            return label.trim();
        }
    }
    name
}

fn option_error(field: &str, input: &str, options: &[Value], ambiguous: bool) -> ApiError {
    ApiError::InvalidInput(format!(
        "{} {field} {input:?}; valid: {}",
        if ambiguous { "Ambiguous" } else { "Invalid" },
        option_names(options)
    ))
}

fn option_names(options: &[Value]) -> String {
    if options.is_empty() {
        return "(none available)".into();
    }
    options
        .iter()
        .map(|option| {
            let name = option["name"].as_str().unwrap_or("(unnamed)");
            match option["id"].as_str() {
                Some(id) => format!("{name:?} (ID {id})"),
                None => format!("{name:?}"),
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

pub(super) fn create_error(
    err: ApiError,
    meta: Option<&CreateMetadata>,
    draft: &super::IssueDraft<'_>,
) -> ApiError {
    write_error(
        err,
        meta.and_then(|m| m.fields.as_ref()),
        draft.priority,
        draft.epic.or(draft.parent),
    )
}

pub(super) fn write_error(
    err: ApiError,
    meta: Option<&Fields>,
    priority: Option<&str>,
    link: Option<&str>,
) -> ApiError {
    if let ApiError::Api {
        status: 400,
        mut message,
    } = err
    {
        if message.contains("priority")
            && let Some(input) = priority
        {
            message.push_str(&format!("; priority {input:?}"));
            if let Some(options) = meta
                .and_then(|m| m.get("priority"))
                .and_then(|p| p["allowedValues"].as_array())
            {
                message.push_str(&format!("; valid: {}", option_names(options)));
            } else {
                message.push_str("; use the exact project priority name or ID, or omit --priority to keep the default");
            }
        }
        for field in ["components", "fixVersions"] {
            if message.contains(field) {
                if let Some(options) = meta
                    .and_then(|m| m.get(field))
                    .and_then(|f| f["allowedValues"].as_array())
                {
                    message.push_str(&format!("; valid {field}: {}", option_names(options)));
                } else {
                    message.push_str(&format!(
                        "; use an exact project {field} name or ID, or omit the field"
                    ));
                }
            }
        }
        if let Some(key) = link
            && (message.contains("issuetype")
                || message.contains("parent")
                || meta.is_some_and(|m| {
                    m.iter()
                        .any(|(id, f)| is_epic_field(id, f) && message.contains(id))
                }))
        {
            message.push_str(&format!("; to add a Story or Task to an Epic use --epic {key}; subtasks require --parent <STORY-OR-TASK>. Check that Epic Link/parent is enabled on the create/edit screen"));
        }
        ApiError::Api {
            status: 400,
            message,
        }
    } else {
        err
    }
}