linear-cli 0.3.5

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
use anyhow::Result;
use clap::Subcommand;
use colored::Colorize;
use serde_json::json;
use tabled::{Table, Tabled};

use crate::api::{resolve_project_id, resolve_team_id, LinearClient};
use crate::cache::{Cache, CacheType};
use crate::display_options;
use crate::input::read_ids_from_stdin;
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::Project;

#[derive(Subcommand)]
pub enum ProjectCommands {
    /// List all projects
    #[command(alias = "ls")]
    #[command(after_help = r#"EXAMPLES:
    linear projects list                       # List all projects
    linear p list --archived                   # Include archived projects
    linear p list --output json                # Output as JSON"#)]
    List {
        /// Show archived projects
        #[arg(short, long)]
        archived: bool,
    },
    /// Get project details
    #[command(after_help = r#"EXAMPLES:
    linear projects get PROJECT_ID             # View by ID
    linear p get "Q1 Roadmap"                  # View by name
    linear p get PROJECT_ID --output json      # Output as JSON
    linear p get ID1 ID2 ID3                   # Get multiple projects
    echo "PROJECT_ID" | linear p get -         # Read ID from stdin"#)]
    Get {
        /// Project ID(s) or name(s). Use "-" to read from stdin.
        ids: Vec<String>,
    },
    /// Create a new project
    #[command(after_help = r##"EXAMPLES:
    linear projects create "Q1 Roadmap" -t ENG # Create project
    linear p create "Feature" -t ENG -d "Desc" # With description
    linear p create "UI" -t ENG -c "#FF5733"   # With color"##)]
    Create {
        /// Project name
        name: String,
        /// Team name or ID
        #[arg(short, long)]
        team: String,
        /// Project description
        #[arg(short, long)]
        description: Option<String>,
        /// Project color (hex)
        #[arg(short, long)]
        color: Option<String>,
    },
    /// Update a project
    #[command(after_help = r#"EXAMPLES:
    linear projects update ID -n "New Name"    # Rename project
    linear p update ID -d "New description"    # Update description"#)]
    Update {
        /// Project ID
        id: String,
        /// New name
        #[arg(short, long)]
        name: Option<String>,
        /// New description
        #[arg(short, long)]
        description: Option<String>,
        /// New color (hex)
        #[arg(short, long)]
        color: Option<String>,
        /// New icon
        #[arg(short, long)]
        icon: Option<String>,
        /// Preview without updating (dry run)
        #[arg(long)]
        dry_run: bool,
    },
    /// Delete a project
    #[command(after_help = r#"EXAMPLES:
    linear projects delete PROJECT_ID          # Delete with confirmation
    linear p delete PROJECT_ID --force         # Delete without confirmation"#)]
    Delete {
        /// Project ID
        id: String,
        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
    /// Add labels to a project
    #[command(after_help = r#"EXAMPLES:
    linear projects add-labels ID LABEL_ID     # Add one label
    linear p add-labels ID L1 L2 L3            # Add multiple labels"#)]
    AddLabels {
        /// Project ID
        id: String,
        /// Label IDs to add
        #[arg(required = true)]
        labels: Vec<String>,
    },
}

#[derive(Tabled)]
struct ProjectRow {
    #[tabled(rename = "Name")]
    name: String,
    #[tabled(rename = "Status")]
    status: String,
    #[tabled(rename = "Labels")]
    labels: String,
    #[tabled(rename = "ID")]
    id: String,
}

pub async fn handle(cmd: ProjectCommands, output: &OutputOptions) -> Result<()> {
    match cmd {
        ProjectCommands::List { archived } => list_projects(archived, output).await,
        ProjectCommands::Get { ids } => {
            let final_ids = read_ids_from_stdin(ids);
            if final_ids.is_empty() {
                anyhow::bail!("No project IDs provided. Provide IDs or pipe them via stdin.");
            }
            get_projects(&final_ids, output).await
        }
        ProjectCommands::Create {
            name,
            team,
            description,
            color,
        } => create_project(&name, &team, description, color, output).await,
        ProjectCommands::Update {
            id,
            name,
            description,
            color,
            icon,
            dry_run,
        } => {
            let dry_run = dry_run || output.dry_run;
            update_project(&id, name, description, color, icon, dry_run, output).await
        }
        ProjectCommands::Delete { id, force } => delete_project(&id, force).await,
        ProjectCommands::AddLabels { id, labels } => add_labels(&id, labels, output).await,
    }
}

async fn list_projects(include_archived: bool, output: &OutputOptions) -> Result<()> {
    let can_use_cache = !output.cache.no_cache
        && !include_archived
        && output.pagination.after.is_none()
        && output.pagination.before.is_none()
        && !output.pagination.all
        && output.pagination.page_size.is_none()
        && output.pagination.limit.is_none();

    let cached: Vec<serde_json::Value> = if can_use_cache {
        let cache = Cache::with_ttl(output.cache.effective_ttl_seconds())?;
        cache
            .get(CacheType::Projects)
            .and_then(|data| data.as_array().cloned())
            .unwrap_or_default()
    } else {
        Vec::new()
    };

    let mut projects = if !cached.is_empty() {
        cached
    } else {
        let client = LinearClient::new()?;

        // Simplified query to reduce GraphQL complexity (was exceeding 10000 limit)
        let query = r#"
            query($includeArchived: Boolean, $first: Int, $after: String, $last: Int, $before: String) {
                projects(first: $first, after: $after, last: $last, before: $before, includeArchived: $includeArchived) {
                    nodes {
                        id
                        name
                        state
                        url
                        startDate
                        targetDate
                    }
                    pageInfo {
                        hasNextPage
                        endCursor
                        hasPreviousPage
                        startCursor
                    }
                }
            }
        "#;

        let mut vars = serde_json::Map::new();
        vars.insert("includeArchived".to_string(), json!(include_archived));

        let pagination = output.pagination.with_default_limit(50);
        let projects = paginate_nodes(
            &client,
            query,
            vars,
            &["data", "projects", "nodes"],
            &["data", "projects", "pageInfo"],
            &pagination,
            50,
        )
        .await?;

        if can_use_cache {
            let cache = Cache::with_ttl(output.cache.effective_ttl_seconds())?;
            let _ = cache.set(CacheType::Projects, serde_json::json!(projects.clone()));
        }

        projects
    };

    if output.is_json() || output.has_template() {
        print_json_owned(serde_json::json!(projects), output)?;
        return Ok(());
    }

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

    ensure_non_empty(&projects, output)?;
    if projects.is_empty() {
        println!("No projects found.");
        return Ok(());
    }

    let width = display_options().max_width(50);
    let rows: Vec<ProjectRow> = projects
        .iter()
        .filter_map(|v| serde_json::from_value::<Project>(v.clone()).ok())
        .map(|p| ProjectRow {
            name: truncate(&p.name, width),
            status: p.state.unwrap_or_else(|| "-".to_string()),
            labels: "-".to_string(),
            id: p.id,
        })
        .collect();

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

    Ok(())
}

async fn get_project(id: &str, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;
    let resolved_id = resolve_project_id(&client, id, &output.cache).await?;

    let query = r#"
        query($id: String!) {
            project(id: $id) {
                id
                name
                description
                icon
                color
                url
                status { name }
                labels { nodes { id name color parent { name } } }
            }
        }
    "#;

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

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

    // Handle JSON output
    if output.is_json() || output.has_template() {
        print_json(project, output)?;
        return Ok(());
    }

    let proj: Project = serde_json::from_value(project.clone())?;

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

    if let Some(desc) = &proj.description {
        if !desc.is_empty() {
            println!(
                "Description: {}",
                desc.chars().take(100).collect::<String>()
            );
        }
    }

    println!(
        "Status: {}",
        proj.status.as_ref().map(|s| s.name.as_str()).unwrap_or("-")
    );
    println!("Color: {}", proj.color.as_deref().unwrap_or("-"));
    println!("Icon: {}", proj.icon.as_deref().unwrap_or("-"));
    println!("URL: {}", proj.url.as_deref().unwrap_or("-"));
    println!("ID: {}", proj.id);

    if let Some(label_conn) = &proj.labels {
        if !label_conn.nodes.is_empty() {
            println!("\nLabels:");
            for label in &label_conn.nodes {
                let parent_name = label.parent.as_ref().map(|p| p.name.as_str()).unwrap_or("");
                if parent_name.is_empty() {
                    println!("  - {}", label.name);
                } else {
                    println!("  - {} > {}", parent_name.dimmed(), label.name);
                }
            }
        }
    }

    Ok(())
}

async fn get_projects(ids: &[String], output: &OutputOptions) -> Result<()> {
    if ids.len() == 1 {
        return get_project(&ids[0], output).await;
    }

    let client = LinearClient::new()?;

    use futures::stream::{self, StreamExt};
    let cache_opts = output.cache;
    let results: Vec<_> = stream::iter(ids.iter())
        .map(|id| {
            let client = client.clone();
            let id = id.clone();
            async move {
                let resolved = resolve_project_id(&client, &id, &cache_opts)
                    .await
                    .unwrap_or_else(|_| id.clone());
                let query = r#"
                    query($id: String!) {
                        project(id: $id) {
                            id
                            name
                            description
                            status { name }
                            url
                        }
                    }
                "#;
                let result = client.query(query, Some(json!({ "id": resolved }))).await;
                (id, result)
            }
        })
        .buffer_unordered(10)
        .collect()
        .await;

    if output.is_json() || output.has_template() {
        let projects: Vec<_> = results
            .iter()
            .filter_map(|(_, r)| {
                r.as_ref().ok().and_then(|data| {
                    let project = &data["data"]["project"];
                    if !project.is_null() {
                        Some(project.clone())
                    } else {
                        None
                    }
                })
            })
            .collect();
        print_json_owned(serde_json::json!(projects), output)?;
        return Ok(());
    }

    let width = display_options().max_width(50);
    for (id, result) in results {
        match result {
            Ok(data) => {
                let project = &data["data"]["project"];
                if project.is_null() {
                    eprintln!("{} Project not found: {}", "!".yellow(), id);
                } else if let Ok(proj) = serde_json::from_value::<Project>(project.clone()) {
                    let name = truncate(&proj.name, width);
                    let status = proj.status.as_ref().map(|s| s.name.as_str()).unwrap_or("-");
                    println!("{} [{}] {}", name.cyan(), status, id);
                } else {
                    eprintln!("{} Failed to parse project: {}", "!".yellow(), id);
                }
            }
            Err(e) => {
                eprintln!("{} Error fetching {}: {}", "!".red(), id, e);
            }
        }
    }

    Ok(())
}

async fn create_project(
    name: &str,
    team: &str,
    description: Option<String>,
    color: Option<String>,
    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 mut input = json!({
        "name": name,
        "teamIds": [team_id]
    });

    if let Some(desc) = description {
        input["description"] = json!(desc);
    }
    if let Some(c) = color {
        input["color"] = json!(c);
    }

    let mutation = r#"
        mutation($input: ProjectCreateInput!) {
            projectCreate(input: $input) {
                success
                project { id name url }
            }
        }
    "#;

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

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

        // Handle JSON output
        if output.is_json() || output.has_template() {
            print_json(project, output)?;
            return Ok(());
        }

        println!(
            "{} Created project: {}",
            "+".green(),
            project["name"].as_str().unwrap_or("")
        );
        println!("  ID: {}", project["id"].as_str().unwrap_or(""));
        println!("  URL: {}", project["url"].as_str().unwrap_or(""));

        // Invalidate projects cache after successful create
        let _ = Cache::new().and_then(|c| c.clear_type(CacheType::Projects));
    } else {
        anyhow::bail!("Failed to create project");
    }

    Ok(())
}

async fn update_project(
    id: &str,
    name: Option<String>,
    description: Option<String>,
    color: Option<String>,
    icon: 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(c) = color {
        input["color"] = json!(c);
    }
    if let Some(i) = icon {
        input["icon"] = json!(i);
    }

    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 project:".yellow().bold());
            println!("  ID: {}", id);
        }
        return Ok(());
    }

    let mutation = r#"
        mutation($id: String!, $input: ProjectUpdateInput!) {
            projectUpdate(id: $id, input: $input) {
                success
                project { id name }
            }
        }
    "#;

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

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

        // Handle JSON output
        if output.is_json() || output.has_template() {
            print_json(project, output)?;
            return Ok(());
        }

        println!("{} Project updated", "+".green());

        // Invalidate projects cache after successful update
        let _ = Cache::new().and_then(|c| c.clear_type(CacheType::Projects));
    } else {
        anyhow::bail!("Failed to update project");
    }

    Ok(())
}

async fn delete_project(id: &str, force: bool) -> Result<()> {
    if !force {
        println!("Are you sure you want to delete project {}?", id);
        println!("This action cannot be undone. Use --force to skip this prompt.");
        return Ok(());
    }

    let client = LinearClient::new()?;

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

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

    if result["data"]["projectDelete"]["success"].as_bool() == Some(true) {
        println!("{} Project deleted", "+".green());

        // Invalidate projects cache after successful delete
        let _ = Cache::new().and_then(|c| c.clear_type(CacheType::Projects));
    } else {
        anyhow::bail!("Failed to delete project");
    }

    Ok(())
}

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

    let mutation = r#"
        mutation($id: String!, $input: ProjectUpdateInput!) {
            projectUpdate(id: $id, input: $input) {
                success
                project {
                    name
                    labels { nodes { name } }
                }
            }
        }
    "#;

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

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

        // Handle JSON output
        if output.is_json() || output.has_template() {
            print_json(project, output)?;
            return Ok(());
        }

        let empty = vec![];
        let labels: Vec<&str> = project["labels"]["nodes"]
            .as_array()
            .unwrap_or(&empty)
            .iter()
            .filter_map(|l| l["name"].as_str())
            .collect();
        println!("{} Labels updated: {}", "+".green(), labels.join(", "));
    } else {
        anyhow::bail!("Failed to add labels");
    }

    Ok(())
}