linear-cli 0.3.22

A powerful CLI for Linear.app - manage issues, projects, cycles, and more from your 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
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use anyhow::Result;
use clap::Subcommand;
use colored::Colorize;
use serde_json::json;
use tabled::{Table, Tabled};

use crate::api::{resolve_team_id, LinearClient};
use crate::cache::{Cache, CacheType};
use crate::display_options;
use crate::output::{
    ensure_non_empty, filter_values, print_json, print_json_owned, sort_values, OutputOptions,
};
use crate::pagination::paginate_nodes;
use crate::text::truncate;
use crate::types::{Cycle, IssueRef, WorkflowState};

#[derive(Subcommand)]
pub enum CycleCommands {
    /// List cycles for a team
    #[command(alias = "ls")]
    List {
        /// Team ID or name
        #[arg(short, long)]
        team: String,
        /// Include completed cycles
        #[arg(short, long)]
        all: bool,
    },
    /// Get cycle details
    Get {
        /// Cycle ID
        id: String,
    },
    /// Show the current active cycle
    Current {
        /// Team ID or name
        #[arg(short, long)]
        team: String,
    },
    /// Create a new cycle
    Create {
        /// Team key, name, or ID
        #[arg(short, long)]
        team: String,
        /// Cycle name
        #[arg(short, long)]
        name: Option<String>,
        /// Cycle description
        #[arg(short, long)]
        description: Option<String>,
        /// Start date (ISO 8601, e.g. 2024-01-01)
        #[arg(long)]
        starts_at: Option<String>,
        /// End date (ISO 8601, e.g. 2024-01-14)
        #[arg(long)]
        ends_at: Option<String>,
    },
    /// Update an existing cycle
    Update {
        /// Cycle ID
        id: String,
        /// New name
        #[arg(short, long)]
        name: Option<String>,
        /// New description
        #[arg(short, long)]
        description: Option<String>,
        /// New start date
        #[arg(long)]
        starts_at: Option<String>,
        /// New end date
        #[arg(long)]
        ends_at: Option<String>,
        /// Preview without updating (dry run)
        #[arg(long)]
        dry_run: bool,
    },
    /// Delete a cycle
    Delete {
        /// Cycle ID
        id: String,
        /// Skip confirmation
        #[arg(long)]
        force: bool,
    },
    /// Mark a cycle as completed
    Complete {
        /// Cycle ID
        id: String,
    },
}

#[derive(Tabled)]
struct CycleRow {
    #[tabled(rename = "Name")]
    name: String,
    #[tabled(rename = "Number")]
    number: String,
    #[tabled(rename = "Status")]
    status: String,
    #[tabled(rename = "Start Date")]
    start_date: String,
    #[tabled(rename = "End Date")]
    end_date: String,
    #[tabled(rename = "Progress")]
    progress: String,
    #[tabled(rename = "ID")]
    id: String,
}

pub async fn handle(cmd: CycleCommands, output: &OutputOptions) -> Result<()> {
    match cmd {
        CycleCommands::List { team, all } => list_cycles(&team, all, output).await,
        CycleCommands::Get { id } => get_cycle(&id, output).await,
        CycleCommands::Current { team } => current_cycle(&team, output).await,
        CycleCommands::Create {
            team,
            name,
            description,
            starts_at,
            ends_at,
        } => create_cycle(&team, name, description, starts_at, ends_at, output).await,
        CycleCommands::Update {
            id,
            name,
            description,
            starts_at,
            ends_at,
            dry_run,
        } => {
            let dry_run = dry_run || output.dry_run;
            update_cycle(&id, name, description, starts_at, ends_at, dry_run, output).await
        }
        CycleCommands::Delete { id, force } => delete_cycle(&id, force).await,
        CycleCommands::Complete { id } => complete_cycle(&id, output).await,
    }
}

async fn list_cycles(team: &str, include_all: bool, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;

    // Resolve team key/name to UUID
    let team_id = resolve_team_id(&client, team, &output.cache).await?;

    // Look up team name from the teams cache (populated by resolve_team_id)
    let team_name = Cache::new()
        .ok()
        .and_then(|c| c.get(CacheType::Teams))
        .and_then(|teams| {
            teams.as_array().and_then(|arr| {
                arr.iter()
                    .find(|t| t["id"].as_str() == Some(&team_id))
                    .and_then(|t| t["name"].as_str().map(|s| s.to_string()))
            })
        })
        .unwrap_or_else(|| team.to_string());

    let cycles_query = r#"
        query($teamId: String!, $first: Int, $after: String, $last: Int, $before: String) {
            team(id: $teamId) {
                cycles(first: $first, after: $after, last: $last, before: $before) {
                    nodes {
                        id
                        name
                        number
                        startsAt
                        endsAt
                        completedAt
                        progress
                    }
                    pageInfo {
                        hasNextPage
                        endCursor
                        hasPreviousPage
                        startCursor
                    }
                }
            }
        }
    "#;

    let mut vars = serde_json::Map::new();
    vars.insert("teamId".to_string(), json!(team_id));
    let pagination = output.pagination.with_default_limit(50);
    let cycles = paginate_nodes(
        &client,
        cycles_query,
        vars,
        &["data", "team", "cycles", "nodes"],
        &["data", "team", "cycles", "pageInfo"],
        &pagination,
        50,
    )
    .await?;

    let cycles: Vec<_> = cycles
        .into_iter()
        .filter(|c| include_all || c["completedAt"].is_null())
        .collect();

    if output.is_json() || output.has_template() {
        print_json_owned(
            json!({
                "team": team_name,
                "cycles": cycles
            }),
            output,
        )?;
        return Ok(());
    }

    if cycles.is_empty() {
        println!("No cycles found for team '{}'.", team_name);
        return Ok(());
    }

    let mut filtered = cycles;
    filter_values(&mut filtered, &output.filters);

    if let Some(sort_key) = output.json.sort.as_deref() {
        sort_values(&mut filtered, sort_key, output.json.order);
    }

    let width = display_options().max_width(30);
    let rows: Vec<CycleRow> = filtered
        .iter()
        .filter_map(|v| serde_json::from_value::<Cycle>(v.clone()).ok())
        .map(|c| {
            let progress = c.progress.unwrap_or(0.0);

            let status = if c.completed_at.is_some() {
                "Completed".to_string()
            } else {
                "Active".to_string()
            };

            CycleRow {
                name: truncate(c.name.as_deref().unwrap_or("-"), width),
                number: c.number.map(|n| n.to_string()).unwrap_or("-".to_string()),
                status,
                start_date: c
                    .starts_at
                    .as_deref()
                    .map(|s| s.chars().take(10).collect())
                    .unwrap_or("-".to_string()),
                end_date: c
                    .ends_at
                    .as_deref()
                    .map(|s| s.chars().take(10).collect())
                    .unwrap_or("-".to_string()),
                progress: format!("{:.0}%", progress * 100.0),
                id: c.id,
            }
        })
        .collect();

    ensure_non_empty(&filtered, output)?;
    if rows.is_empty() {
        println!(
            "No active cycles found for team '{}'. Use --all to see completed cycles.",
            team_name
        );
        return Ok(());
    }

    println!("{}", format!("Cycles for team '{}'", team_name).bold());
    println!("{}", "-".repeat(40));

    let rows_len = rows.len();
    let table = Table::new(rows).to_string();
    println!("{}", table);
    println!("\n{} cycles shown", rows_len);

    Ok(())
}

async fn get_cycle(id: &str, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;

    let query = r#"
        query($id: String!) {
            cycle(id: $id) {
                id
                name
                number
                description
                startsAt
                endsAt
                completedAt
                progress
                scopeHistory
                completedScopeHistory
                team { name key }
                issues(first: 250) {
                    nodes {
                        id
                        identifier
                        title
                        state { name type }
                        assignee { name }
                        priority
                    }
                }
            }
        }
    "#;

    let result = client.query(query, Some(json!({ "id": id }))).await?;
    let raw = &result["data"]["cycle"];

    if raw.is_null() {
        anyhow::bail!("Cycle not found: {}", id);
    }

    if output.is_json() || output.has_template() {
        print_json(raw, output)?;
        return Ok(());
    }

    let cycle: Cycle = serde_json::from_value(raw.clone())
        .map_err(|e| anyhow::anyhow!("Failed to parse cycle: {}", e))?;

    let progress = cycle.progress.unwrap_or(0.0);
    let cycle_number = cycle.number.unwrap_or(0);
    let default_name = format!("Cycle {}", cycle_number);
    let cycle_name = cycle.name.as_deref().unwrap_or(&default_name);

    println!("{}", cycle_name.bold());
    println!("{}", "-".repeat(40));

    if let Some(team_name) = raw["team"]["name"].as_str() {
        let team_key = raw["team"]["key"].as_str().unwrap_or("");
        println!("Team: {} ({})", team_name, team_key);
    }

    println!("Number: {}", cycle_number);

    if let Some(desc) = &cycle.description {
        if !desc.is_empty() {
            println!("Description: {}", desc);
        }
    }

    println!(
        "Start: {}",
        cycle
            .starts_at
            .as_deref()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!(
        "End: {}",
        cycle
            .ends_at
            .as_deref()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!("Progress: {:.0}%", progress * 100.0);

    if cycle.completed_at.is_some() {
        println!("Status: {}", "Completed".green());
    } else {
        println!("Status: {}", "Active".yellow());
    }

    println!("ID: {}", cycle.id);

    // Show issues
    let issues = raw["issues"]["nodes"].as_array();
    if let Some(issues) = issues {
        if !issues.is_empty() {
            println!("\n{}", "Issues:".bold());
            for issue_val in issues {
                let identifier = issue_val["identifier"].as_str().unwrap_or("");
                let title = truncate(
                    issue_val["title"].as_str().unwrap_or(""),
                    display_options().max_width(50),
                );
                let state_name = issue_val["state"]["name"].as_str().unwrap_or("");
                let state_type = issue_val["state"]["type"].as_str().unwrap_or("");
                let assignee = issue_val["assignee"]["name"].as_str().unwrap_or("-");

                let state_colored = match state_type {
                    "completed" => state_name.green().to_string(),
                    "started" => state_name.yellow().to_string(),
                    "canceled" | "cancelled" => state_name.red().to_string(),
                    _ => state_name.dimmed().to_string(),
                };

                println!(
                    "  {} {} [{}] ({})",
                    identifier.cyan(),
                    title,
                    state_colored,
                    assignee
                );
            }
            println!("\n{} issues", issues.len());
        }
    }

    Ok(())
}

async fn current_cycle(team: &str, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;

    // Resolve team key/name to UUID
    let team_id = resolve_team_id(&client, team, &output.cache).await?;

    let query = r#"
        query($teamId: String!) {
            team(id: $teamId) {
                id
                name
                activeCycle {
                    id
                    name
                    number
                    startsAt
                    endsAt
                    progress
                    issues(first: 250) {
                        nodes {
                            id
                            identifier
                            title
                            state { name type }
                        }
                    }
                }
            }
        }
    "#;

    let result = client
        .query(query, Some(json!({ "teamId": team_id })))
        .await?;
    let team_data = &result["data"]["team"];

    if team_data.is_null() {
        anyhow::bail!("Team not found: {}", team);
    }

    if output.is_json() || output.has_template() {
        print_json(team_data, output)?;
        return Ok(());
    }

    let team_name = team_data["name"].as_str().unwrap_or("");
    let cycle_val = &team_data["activeCycle"];

    if cycle_val.is_null() {
        println!("No active cycle for team '{}'.", team_name);
        return Ok(());
    }

    let cycle: Cycle = serde_json::from_value(cycle_val.clone())
        .map_err(|e| anyhow::anyhow!("Failed to parse cycle data: {}", e))?;

    let progress = cycle.progress.unwrap_or(0.0);
    let cycle_number = cycle.number.unwrap_or(0);
    let default_name = format!("Cycle {}", cycle_number);
    let cycle_name = cycle.name.as_deref().unwrap_or(&default_name);

    println!("{}", format!("Current Cycle: {}", cycle_name).bold());
    println!("{}", "-".repeat(40));

    println!("Team: {}", team_name);
    println!("Cycle Number: {}", cycle_number);
    println!(
        "Start Date: {}",
        cycle
            .starts_at
            .as_deref()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!(
        "End Date: {}",
        cycle
            .ends_at
            .as_deref()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!("Progress: {:.0}%", progress * 100.0);
    println!("ID: {}", cycle.id);

    // Show issues in the cycle
    let issues = cycle_val["issues"]["nodes"].as_array();
    if let Some(issues) = issues {
        if !issues.is_empty() {
            println!("\n{}", "Issues in this cycle:".bold());
            for issue_val in issues {
                let issue_ref: Option<IssueRef> = serde_json::from_value(issue_val.clone()).ok();
                let state: Option<WorkflowState> =
                    serde_json::from_value(issue_val["state"].clone()).ok();

                let identifier = issue_ref
                    .as_ref()
                    .map(|i| i.identifier.as_str())
                    .unwrap_or("");
                let title = truncate(
                    issue_ref
                        .as_ref()
                        .and_then(|i| i.title.as_deref())
                        .unwrap_or(""),
                    display_options().max_width(50),
                );
                let state_name = state.as_ref().map(|s| s.name.as_str()).unwrap_or("");
                let state_type = state
                    .as_ref()
                    .and_then(|s| s.state_type.as_deref())
                    .unwrap_or("");

                let state_colored = match state_type {
                    "completed" => state_name.green().to_string(),
                    "started" => state_name.yellow().to_string(),
                    "canceled" | "cancelled" => state_name.red().to_string(),
                    _ => state_name.dimmed().to_string(),
                };

                println!("  {} {} [{}]", identifier.cyan(), title, state_colored);
            }
        }
    }

    Ok(())
}

async fn create_cycle(
    team: &str,
    name: Option<String>,
    description: Option<String>,
    starts_at: Option<String>,
    ends_at: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;
    let team_id = resolve_team_id(&client, team, &output.cache).await?;

    let mut input = json!({ "teamId": team_id });
    if let Some(n) = &name {
        input["name"] = json!(n);
    }
    if let Some(d) = &description {
        input["description"] = json!(d);
    }
    if let Some(s) = &starts_at {
        input["startsAt"] = json!(s);
    }
    if let Some(e) = &ends_at {
        input["endsAt"] = json!(e);
    }

    let mutation = r#"
        mutation($input: CycleCreateInput!) {
            cycleCreate(input: $input) {
                success
                cycle { id name number startsAt endsAt }
            }
        }
    "#;

    let result = client
        .mutate(mutation, Some(json!({ "input": input })))
        .await?;

    if result["data"]["cycleCreate"]["success"].as_bool() == Some(true) {
        let cycle = &result["data"]["cycleCreate"]["cycle"];
        if output.is_json() || output.has_template() {
            print_json(cycle, output)?;
            return Ok(());
        }
        let display_name = cycle["name"]
            .as_str()
            .filter(|s| !s.is_empty())
            .unwrap_or("cycle");
        println!("{} Created cycle: {}", "+".green(), display_name);
        println!("  ID: {}", cycle["id"].as_str().unwrap_or(""));
        if let Some(num) = cycle["number"].as_u64() {
            println!("  Number: {}", num);
        }
    } else {
        anyhow::bail!("Failed to create cycle");
    }

    Ok(())
}

async fn update_cycle(
    id: &str,
    name: Option<String>,
    description: Option<String>,
    starts_at: Option<String>,
    ends_at: Option<String>,
    dry_run: bool,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;

    let mut input = json!({});
    if let Some(n) = name {
        input["name"] = json!(n);
    }
    if let Some(d) = description {
        input["description"] = json!(d);
    }
    if let Some(s) = starts_at {
        input["startsAt"] = json!(s);
    }
    if let Some(e) = ends_at {
        input["endsAt"] = json!(e);
    }

    if input.as_object().map(|o| o.is_empty()).unwrap_or(true) {
        println!("No updates specified.");
        return Ok(());
    }

    if dry_run {
        if output.is_json() || output.has_template() {
            print_json_owned(
                json!({
                    "dry_run": true,
                    "would_update": { "id": id, "input": input }
                }),
                output,
            )?;
        } else {
            println!("{}", "[DRY RUN] Would update cycle:".yellow().bold());
            println!("  ID: {}", id);
        }
        return Ok(());
    }

    let mutation = r#"
        mutation($id: String!, $input: CycleUpdateInput!) {
            cycleUpdate(id: $id, input: $input) {
                success
                cycle { id name number }
            }
        }
    "#;

    let result = client
        .mutate(mutation, Some(json!({ "id": id, "input": input })))
        .await?;

    if result["data"]["cycleUpdate"]["success"].as_bool() == Some(true) {
        if output.is_json() || output.has_template() {
            print_json(&result["data"]["cycleUpdate"]["cycle"], output)?;
            return Ok(());
        }
        println!("{} Cycle updated", "+".green());
    } else {
        anyhow::bail!("Failed to update cycle");
    }

    Ok(())
}

async fn delete_cycle(id: &str, force: bool) -> Result<()> {
    if !force && !crate::is_yes() {
        anyhow::bail!(
            "Delete requires --force flag. Use: linear cycles delete {} --force",
            id
        );
    }

    let client = LinearClient::new()?;

    let mutation = r#"
        mutation($id: String!) {
            cycleDelete(id: $id) {
                success
            }
        }
    "#;

    let result = client.mutate(mutation, Some(json!({ "id": id }))).await?;

    let success = result["data"]["cycleDelete"]["success"]
        .as_bool()
        .unwrap_or(false);

    if success {
        println!("Cycle {} deleted.", id);
    } else {
        anyhow::bail!("Failed to delete cycle {}", id);
    }

    Ok(())
}

async fn complete_cycle(id: &str, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;

    let now = chrono::Utc::now().to_rfc3339();
    let input = json!({ "completedAt": now });

    let mutation = r#"
        mutation($id: String!, $input: CycleUpdateInput!) {
            cycleUpdate(id: $id, input: $input) {
                success
                cycle { id name number completedAt }
            }
        }
    "#;

    let result = client
        .mutate(mutation, Some(json!({ "id": id, "input": input })))
        .await?;

    if result["data"]["cycleUpdate"]["success"].as_bool() == Some(true) {
        let cycle = &result["data"]["cycleUpdate"]["cycle"];

        if output.is_json() || output.has_template() {
            print_json(cycle, output)?;
            return Ok(());
        }

        let display_name = cycle["name"]
            .as_str()
            .filter(|s| !s.is_empty())
            .unwrap_or("cycle");
        println!(
            "{} Cycle '{}' marked as completed",
            "+".green(),
            display_name
        );
    } else {
        anyhow::bail!("Failed to complete cycle");
    }

    Ok(())
}