lin-cli 0.4.0

A fast CLI for Linear
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
use anyhow::{Result, bail};
use serde_json::json;

use crate::api::client::LinearClient;
use crate::api::queries::*;
use crate::api::resolve;
use crate::api::types::*;
use crate::api::upload;
use crate::output;

pub async fn view(client: &LinearClient, id: &str) -> Result<()> {
    let data: IssueData = client
        .execute(ISSUE_QUERY, Some(json!({ "id": id })))
        .await?;

    let issue = data.issue;

    output::print_header(&format!("{}{}", issue.identifier, issue.title));

    if let Some(ref state) = issue.state {
        output::print_field("Status", &state.name);
    }
    if let Some(ref assignee) = issue.assignee {
        output::print_field("Assignee", &assignee.name);
    }
    if let Some(ref team) = issue.team {
        output::print_field("Team", &team.name);
    }
    if let Some(ref project) = issue.project {
        output::print_field("Project", &project.name);
    }
    if let Some(priority) = issue.priority {
        let label = match priority as i32 {
            0 => "None",
            1 => "Urgent",
            2 => "High",
            3 => "Medium",
            4 => "Low",
            _ => "Unknown",
        };
        output::print_field("Priority", label);
    }

    if let Some(ref labels) = issue.labels
        && !labels.nodes.is_empty()
    {
        let names: Vec<&str> = labels.nodes.iter().map(|l| l.name.as_str()).collect();
        output::print_field("Labels", &names.join(", "));
    }

    if let Some(ref parent) = issue.parent {
        output::print_field(
            "Parent",
            &format!("{}{}", parent.identifier, parent.title),
        );
    }

    if let Some(ref children) = issue.children
        && !children.nodes.is_empty()
    {
        println!();
        output::print_header("Sub-issues");
        for child in &children.nodes {
            println!("  {}{}", child.identifier, child.title);
        }
    }

    if let Some(ref desc) = issue.description
        && !desc.is_empty()
    {
        println!();
        output::print_header("Description");
        println!("  {desc}");
    }

    println!();
    if let Some(ref created) = issue.created_at {
        output::print_field("Created", &output::format_date(created));
    }
    if let Some(ref updated) = issue.updated_at {
        output::print_field("Updated", &output::format_date(updated));
    }
    if let Some(ref due) = issue.due_date {
        output::print_field("Due", due);
    }
    if let Some(ref url) = issue.url {
        output::print_field("URL", url);
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn create(
    client: &LinearClient,
    title: &str,
    team: &str,
    description: Option<&str>,
    priority: Option<i32>,
    assignee: Option<&str>,
    project: Option<&str>,
    label_ids: Option<&[String]>,
    labels: Option<&[String]>,
    parent: Option<&str>,
    attachment_path: Option<&str>,
) -> Result<()> {
    let team_id = resolve::resolve_team_identifier(client, team).await?;

    let mut input = IssueCreateInput {
        title: title.to_string(),
        team_id,
        ..Default::default()
    };
    input.description = description.map(|s| s.to_string());
    input.priority = priority;
    input.assignee_id = match assignee {
        Some(aid) => Some(resolve::resolve_user_identifier(client, aid).await?),
        None => None,
    };
    input.project_id = match project {
        Some(p) => Some(resolve::resolve_project_identifier(client, p).await?),
        None => None,
    };

    // Resolve label names to IDs and merge with explicit label_ids
    let mut all_label_ids: Vec<String> = label_ids.map(|ids| ids.to_vec()).unwrap_or_default();
    if let Some(names) = labels {
        let resolved = resolve::resolve_label_names(client, names).await?;
        all_label_ids.extend(resolved);
    }
    if !all_label_ids.is_empty() {
        input.label_ids = Some(all_label_ids);
    }

    // Resolve parent if it's an identifier
    if let Some(pid) = parent {
        let resolved = resolve::resolve_issue_identifier(client, pid).await?;
        input.parent_id = Some(resolved);
    }

    let data: IssueCreateData = client
        .execute(ISSUE_CREATE_MUTATION, Some(json!({ "input": input })))
        .await?;

    if !data.issue_create.success {
        bail!("Failed to create issue");
    }

    if let Some(issue) = data.issue_create.issue {
        output::print_success(&format!("Created {}{}", issue.identifier, issue.title));
        if let Some(ref url) = issue.url {
            output::print_field("URL", url);
        }

        // Handle attachment upload
        if let Some(file_path) = attachment_path {
            let asset_url = upload::upload_file(client, file_path).await?;
            let filename = std::path::Path::new(file_path)
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| "attachment".to_string());
            upload::create_attachment(client, &issue.id, &asset_url, &filename).await?;
            output::print_success(&format!("Attached: {}", filename));
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub async fn edit(
    client: &LinearClient,
    id: &str,
    title: Option<String>,
    description: Option<String>,
    priority: Option<i32>,
    assignee: Option<String>,
    state: Option<String>,
    project: Option<String>,
    label_ids: Option<Vec<String>>,
    labels: Option<Vec<String>>,
    remove_labels: Option<Vec<String>>,
    parent: Option<String>,
    attachment_path: Option<String>,
) -> Result<()> {
    // Resolve label names
    let mut final_label_ids = label_ids;

    if labels.is_some() || remove_labels.is_some() {
        // Need to fetch current labels to merge
        let issue_data: IssueData = client
            .execute(ISSUE_QUERY, Some(json!({ "id": id })))
            .await?;
        let mut current_ids: Vec<String> = issue_data
            .issue
            .labels
            .map(|l| l.nodes.into_iter().map(|n| n.id).collect())
            .unwrap_or_default();

        // Add new labels by name
        if let Some(ref names) = labels {
            let resolved = resolve::resolve_label_names(client, names).await?;
            for lid in resolved {
                if !current_ids.contains(&lid) {
                    current_ids.push(lid);
                }
            }
        }

        // Remove labels by name
        if let Some(ref names) = remove_labels {
            let resolved = resolve::resolve_label_names(client, names).await?;
            current_ids.retain(|id| !resolved.contains(id));
        }

        // Merge with explicit label_ids if provided
        if let Some(ref explicit) = final_label_ids {
            for lid in explicit {
                if !current_ids.contains(lid) {
                    current_ids.push(lid.clone());
                }
            }
        }

        final_label_ids = Some(current_ids);
    }

    // Resolve parent if it's an identifier
    let resolved_parent = if let Some(ref pid) = parent {
        Some(resolve::resolve_issue_identifier(client, pid).await?)
    } else {
        None
    };

    let resolved_assignee = match assignee {
        Some(aid) => Some(resolve::resolve_user_identifier(client, &aid).await?),
        None => None,
    };

    let resolved_project = match project {
        Some(ref p) => Some(resolve::resolve_project_identifier(client, p).await?),
        None => None,
    };

    let input = IssueUpdateInput {
        title,
        description,
        priority,
        assignee_id: resolved_assignee,
        state_id: state,
        project_id: resolved_project,
        label_ids: final_label_ids,
        parent_id: resolved_parent,
    };

    let data: IssueUpdateData = client
        .execute(
            ISSUE_UPDATE_MUTATION,
            Some(json!({ "id": id, "input": input })),
        )
        .await?;

    if !data.issue_update.success {
        bail!("Failed to update issue");
    }

    if let Some(issue) = data.issue_update.issue {
        output::print_success(&format!("Updated {}{}", issue.identifier, issue.title));

        // Handle attachment upload
        if let Some(ref file_path) = attachment_path {
            let asset_url = upload::upload_file(client, file_path).await?;
            let filename = std::path::Path::new(file_path.as_str())
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| "attachment".to_string());
            upload::create_attachment(client, &issue.id, &asset_url, &filename).await?;
            output::print_success(&format!("Attached: {}", filename));
        }
    }

    Ok(())
}

pub async fn search(
    client: &LinearClient,
    query: &str,
    project: Option<&str>,
    team: Option<&str>,
    assignee: Option<&str>,
    status: Option<&str>,
    limit: i32,
) -> Result<()> {
    let mut filter = json!({});
    if let Some(pid) = project {
        let resolved = resolve::resolve_project_identifier(client, pid).await?;
        filter["project"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(tid) = team {
        let resolved = resolve::resolve_team_identifier(client, tid).await?;
        filter["team"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(aid) = assignee {
        let resolved = resolve::resolve_user_identifier(client, aid).await?;
        filter["assignee"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(s) = status {
        filter["state"] = json!({ "name": { "eq": s } });
    }

    let variables = json!({
        "term": query,
        "first": limit,
        "filter": filter,
    });

    let data: IssueSearchData = client.execute(ISSUE_SEARCH_QUERY, Some(variables)).await?;
    let issues = data.search_issues.nodes;

    print_issues_table(&issues);
    Ok(())
}

pub async fn list(
    client: &LinearClient,
    team: Option<&str>,
    assignee: Option<&str>,
    status: Option<&str>,
    project: Option<&str>,
    priority: Option<i32>,
    limit: i32,
) -> Result<()> {
    let mut filter = json!({});
    if let Some(tid) = team {
        let resolved = resolve::resolve_team_identifier(client, tid).await?;
        filter["team"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(aid) = assignee {
        let resolved = resolve::resolve_user_identifier(client, aid).await?;
        filter["assignee"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(s) = status {
        filter["state"] = json!({ "name": { "eq": s } });
    }
    if let Some(pid) = project {
        let resolved = resolve::resolve_project_identifier(client, pid).await?;
        filter["project"] = json!({ "id": { "eq": resolved } });
    }
    if let Some(p) = priority {
        filter["priority"] = json!({ "eq": p });
    }

    let variables = json!({
        "first": limit,
        "filter": filter,
    });

    let data: IssuesData = client.execute(ISSUES_QUERY, Some(variables)).await?;
    let issues = data.issues.nodes;

    print_issues_table(&issues);
    Ok(())
}

pub async fn me(client: &LinearClient, status: Option<&str>, limit: i32) -> Result<()> {
    let viewer: ViewerData = client.execute(VIEWER_QUERY, None).await?;
    let user_id = viewer.viewer.id;

    let mut filter = json!({
        "assignee": { "id": { "eq": user_id } }
    });
    if let Some(s) = status {
        filter["state"] = json!({ "name": { "eq": s } });
    }

    let variables = json!({
        "first": limit,
        "filter": filter,
    });

    let data: IssuesData = client.execute(ISSUES_QUERY, Some(variables)).await?;
    let issues = data.issues.nodes;

    output::print_header(&format!(
        "My Issues ({})",
        viewer
            .viewer
            .display_name
            .as_deref()
            .unwrap_or(&viewer.viewer.name)
    ));
    print_issues_table(&issues);
    Ok(())
}

pub async fn state(
    client: &LinearClient,
    id: &str,
    new_state_name: Option<&str>,
    list_flag: bool,
) -> Result<()> {
    // First fetch the issue to get current state and team
    let issue_data: IssueData = client
        .execute(ISSUE_QUERY, Some(json!({ "id": id })))
        .await?;
    let issue = issue_data.issue;

    if list_flag {
        // List all available states grouped by type
        let team = issue
            .team
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Issue has no team"))?;

        let team_data: TeamData = client
            .execute(TEAM_STATES_QUERY, Some(json!({ "id": team.id })))
            .await?;

        let current_state_id = issue.state.as_ref().map(|s| s.id.as_str());

        output::print_header(&format!(
            "States for {} (team: {})",
            issue.identifier, team.name
        ));

        // Group by type
        let type_order = ["backlog", "unstarted", "started", "completed", "cancelled"];
        for state_type in &type_order {
            let states_of_type: Vec<&WorkflowState> = team_data
                .team
                .states
                .nodes
                .iter()
                .filter(|s| {
                    s.state_type
                        .as_deref()
                        .map(|t| t.to_lowercase() == *state_type)
                        .unwrap_or(false)
                })
                .collect();

            if !states_of_type.is_empty() {
                println!();
                output::print_field("Type", state_type);
                for s in &states_of_type {
                    let marker = if Some(s.id.as_str()) == current_state_id {
                        " ← current"
                    } else {
                        ""
                    };
                    println!("    {}{}", s.name, marker);
                }
            }
        }

        // Any states with unknown types
        let known_types: Vec<&str> = type_order.to_vec();
        let other: Vec<&WorkflowState> = team_data
            .team
            .states
            .nodes
            .iter()
            .filter(|s| {
                s.state_type
                    .as_deref()
                    .map(|t| !known_types.contains(&t.to_lowercase().as_str()))
                    .unwrap_or(true)
            })
            .collect();

        if !other.is_empty() {
            println!();
            output::print_field("Type", "other");
            for s in &other {
                let marker = if Some(s.id.as_str()) == current_state_id {
                    " ← current"
                } else {
                    ""
                };
                println!("    {}{}", s.name, marker);
            }
        }

        return Ok(());
    }

    match new_state_name {
        None => {
            // Just display current state
            let state_name = issue
                .state
                .as_ref()
                .map(|s| s.name.as_str())
                .unwrap_or("Unknown");
            output::print_header(&format!("{}{}", issue.identifier, issue.title));
            output::print_field("State", state_name);
        }
        Some(target_name) => {
            // Get team workflow states
            let team = issue
                .team
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("Issue has no team"))?;

            let team_data: TeamData = client
                .execute(TEAM_STATES_QUERY, Some(json!({ "id": team.id })))
                .await?;

            let target_lower = target_name.to_lowercase();
            let matching_state = team_data
                .team
                .states
                .nodes
                .iter()
                .find(|s| s.name.to_lowercase() == target_lower);

            let ws = matching_state.ok_or_else(|| {
                let available: Vec<&str> = team_data
                    .team
                    .states
                    .nodes
                    .iter()
                    .map(|s| s.name.as_str())
                    .collect();
                anyhow::anyhow!(
                    "State '{}' not found. Available states: {}",
                    target_name,
                    available.join(", ")
                )
            })?;

            let input = IssueUpdateInput {
                state_id: Some(ws.id.clone()),
                ..Default::default()
            };

            let data: IssueUpdateData = client
                .execute(
                    ISSUE_UPDATE_MUTATION,
                    Some(json!({ "id": issue.id, "input": input })),
                )
                .await?;

            if !data.issue_update.success {
                bail!("Failed to update issue state");
            }

            output::print_success(&format!(
                "{} state changed to '{}'",
                issue.identifier, ws.name
            ));
        }
    }

    Ok(())
}

pub async fn attachments(client: &LinearClient, id: &str) -> Result<()> {
    let data: IssueAttachmentsData = client
        .execute(ISSUE_ATTACHMENTS_QUERY, Some(json!({ "id": id })))
        .await?;

    let attachments = data.issue.attachments.nodes;
    output::print_header(&format!("Attachments ({})", attachments.len()));

    if attachments.is_empty() {
        println!("  No attachments.");
        return Ok(());
    }

    let headers = &["ID", "Title", "URL", "Created"];
    let rows: Vec<Vec<String>> = attachments
        .iter()
        .map(|a| {
            vec![
                truncate(&a.id, 8),
                a.title.clone().unwrap_or_default(),
                a.url.clone().unwrap_or_default(),
                a.created_at
                    .as_deref()
                    .map(output::format_date)
                    .unwrap_or_default(),
            ]
        })
        .collect();

    output::print_table(headers, &rows);
    Ok(())
}

fn print_issues_table(issues: &[Issue]) {
    output::print_header(&format!("Issues ({})", issues.len()));

    let headers = &["ID", "Title", "Status", "Assignee", "Team"];
    let rows: Vec<Vec<String>> = issues
        .iter()
        .map(|i| {
            vec![
                i.identifier.clone(),
                truncate(&i.title, 50),
                i.state.as_ref().map(|s| s.name.clone()).unwrap_or_default(),
                i.assignee
                    .as_ref()
                    .map(|a| a.name.clone())
                    .unwrap_or_default(),
                i.team.as_ref().map(|t| t.name.clone()).unwrap_or_default(),
            ]
        })
        .collect();

    output::print_table(headers, &rows);
}

fn truncate(s: &str, max: usize) -> String {
    if s.len() <= max {
        s.to_string()
    } else {
        format!("{}", &s[..max - 1])
    }
}