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

use crate::api::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::Label;

#[derive(Subcommand)]
pub enum LabelCommands {
    /// List labels
    #[command(alias = "ls")]
    #[command(after_help = r#"EXAMPLES:
    linear labels list                         # List project labels
    linear l list --type issue                 # List issue labels
    linear l list --output json                # Output as JSON"#)]
    List {
        /// Label type: issue or project
        #[arg(short, long, default_value = "project")]
        r#type: String,
    },
    /// Create a new label
    #[command(after_help = r##"EXAMPLES:
    linear labels create "Feature"             # Create project label
    linear l create "Bug" --type issue         # Create issue label
    linear l create "UI" -c "#FF5733"          # With custom color
    linear l create "Sub" -p PARENT_ID         # As child of parent"##)]
    Create {
        /// Label name
        name: String,
        /// Label type: issue or project
        #[arg(short, long, default_value = "project")]
        r#type: String,
        /// Label color (hex)
        #[arg(short, long, default_value = "#6B7280")]
        color: String,
        /// Parent label ID (for grouped labels)
        #[arg(short, long)]
        parent: Option<String>,
    },
    /// Delete a label
    #[command(after_help = r#"EXAMPLES:
    linear labels delete LABEL_ID              # Delete with confirmation
    linear l delete LABEL_ID --force           # Delete without confirmation
    linear l delete LABEL_ID --type issue      # Delete issue label"#)]
    Delete {
        /// Label ID
        id: String,
        /// Label type: issue or project
        #[arg(short, long, default_value = "project")]
        r#type: String,
        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
    /// Update a label's name or color
    Update {
        /// Label ID
        id: String,
        /// Label type: issue or project
        #[arg(short, long, default_value = "project")]
        r#type: String,
        /// New label name
        #[arg(short, long)]
        name: Option<String>,
        /// New color (hex, e.g. "#FF5733")
        #[arg(short, long)]
        color: Option<String>,
    },
}

#[derive(Tabled)]
struct LabelRow {
    #[tabled(rename = "Name")]
    name: String,
    #[tabled(rename = "Group")]
    group: String,
    #[tabled(rename = "Color")]
    color: String,
    #[tabled(rename = "ID")]
    id: String,
}

fn validate_label_type(label_type: &str) -> Result<()> {
    match label_type {
        "project" | "issue" => Ok(()),
        other => anyhow::bail!(
            "Invalid label type '{}'. Must be 'project' or 'issue'.",
            other
        ),
    }
}

pub async fn handle(cmd: LabelCommands, output: &OutputOptions) -> Result<()> {
    match cmd {
        LabelCommands::List { r#type } => {
            validate_label_type(&r#type)?;
            list_labels(&r#type, output).await
        }
        LabelCommands::Create {
            name,
            r#type,
            color,
            parent,
        } => {
            validate_label_type(&r#type)?;
            create_label(&name, &r#type, &color, parent, output).await
        }
        LabelCommands::Delete { id, r#type, force } => {
            validate_label_type(&r#type)?;
            delete_label(&id, &r#type, force).await
        }
        LabelCommands::Update {
            id,
            r#type,
            name,
            color,
        } => {
            validate_label_type(&r#type)?;
            update_label(&id, &r#type, name, color, output).await
        }
    }
}

async fn list_labels(label_type: &str, output: &OutputOptions) -> Result<()> {
    let can_use_cache = !output.cache.no_cache
        && 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<Value> = if can_use_cache {
        let cache = Cache::with_ttl(output.cache.effective_ttl_seconds())?;
        cache
            .get_keyed(CacheType::Labels, label_type)
            .and_then(|data| data.as_array().cloned())
            .unwrap_or_default()
    } else {
        Vec::new()
    };

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

        let query = if label_type == "project" {
            r#"
                query($first: Int, $after: String, $last: Int, $before: String) {
                    projectLabels(first: $first, after: $after, last: $last, before: $before) {
                        nodes {
                            id
                            name
                            color
                            parent { name }
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                            hasPreviousPage
                            startCursor
                        }
                    }
                }
            "#
        } else {
            r#"
                query($first: Int, $after: String, $last: Int, $before: String) {
                    issueLabels(first: $first, after: $after, last: $last, before: $before) {
                        nodes {
                            id
                            name
                            color
                            parent { name }
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                            hasPreviousPage
                            startCursor
                        }
                    }
                }
            "#
        };

        let key = if label_type == "project" {
            "projectLabels"
        } else {
            "issueLabels"
        };

        let pagination = output.pagination.with_default_limit(100);
        let labels = paginate_nodes(
            &client,
            query,
            serde_json::Map::new(),
            &["data", key, "nodes"],
            &["data", key, "pageInfo"],
            &pagination,
            100,
        )
        .await?;

        if can_use_cache {
            let cache = Cache::with_ttl(output.cache.effective_ttl_seconds())?;
            let _ = cache.set_keyed(
                CacheType::Labels,
                label_type,
                serde_json::json!(labels.clone()),
            );
        }

        labels
    };

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

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

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

    let width = display_options().max_width(30);
    let rows: Vec<LabelRow> = labels
        .iter()
        .filter_map(|v| serde_json::from_value::<Label>(v.clone()).ok())
        .map(|l| LabelRow {
            name: truncate(&l.name, width),
            group: truncate(
                l.parent.as_ref().map(|p| p.name.as_str()).unwrap_or("-"),
                width,
            ),
            color: l.color.unwrap_or_default(),
            id: l.id,
        })
        .collect();

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

    Ok(())
}

async fn create_label(
    name: &str,
    label_type: &str,
    color: &str,
    parent: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;

    let mut input = json!({
        "name": name,
        "color": color
    });

    if let Some(p) = parent {
        input["parentId"] = json!(p);
    }

    let mutation = if label_type == "project" {
        r#"
            mutation($input: ProjectLabelCreateInput!) {
                projectLabelCreate(input: $input) {
                    success
                    projectLabel { id name color }
                }
            }
        "#
    } else {
        r#"
            mutation($input: IssueLabelCreateInput!) {
                issueLabelCreate(input: $input) {
                    success
                    issueLabel { id name color }
                }
            }
        "#
    };

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

    let key = if label_type == "project" {
        "projectLabelCreate"
    } else {
        "issueLabelCreate"
    };
    let label_key = if label_type == "project" {
        "projectLabel"
    } else {
        "issueLabel"
    };

    if result["data"][key]["success"].as_bool() == Some(true) {
        let label = &result["data"][key][label_key];

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

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

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

    Ok(())
}

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

    let client = LinearClient::new()?;

    let mutation = if label_type == "project" {
        r#"
            mutation($id: String!) {
                projectLabelDelete(id: $id) {
                    success
                }
            }
        "#
    } else {
        r#"
            mutation($id: String!) {
                issueLabelDelete(id: $id) {
                    success
                }
            }
        "#
    };

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

    let key = if label_type == "project" {
        "projectLabelDelete"
    } else {
        "issueLabelDelete"
    };

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

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

    Ok(())
}

async fn update_label(
    id: &str,
    label_type: &str,
    name: Option<String>,
    color: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    if name.is_none() && color.is_none() {
        println!("No updates specified. Use --name or --color.");
        return Ok(());
    }

    let client = LinearClient::new()?;

    let mut input = json!({});
    if let Some(n) = &name {
        input["name"] = json!(n);
    }
    if let Some(c) = &color {
        input["color"] = json!(c);
    }

    let mutation = if label_type == "project" {
        r#"
            mutation($id: String!, $input: ProjectLabelUpdateInput!) {
                projectLabelUpdate(id: $id, input: $input) {
                    success
                    projectLabel { id name color }
                }
            }
        "#
    } else {
        r#"
            mutation($id: String!, $input: IssueLabelUpdateInput!) {
                issueLabelUpdate(id: $id, input: $input) {
                    success
                    issueLabel { id name color }
                }
            }
        "#
    };

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

    let key = if label_type == "project" {
        "projectLabelUpdate"
    } else {
        "issueLabelUpdate"
    };
    let label_key = if label_type == "project" {
        "projectLabel"
    } else {
        "issueLabel"
    };

    if result["data"][key]["success"].as_bool() == Some(true) {
        let label = &result["data"][key][label_key];

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

        println!(
            "{} Updated {} label: {}",
            "+".green(),
            label_type,
            label["name"].as_str().unwrap_or("")
        );

        let _ = Cache::new().and_then(|c| c.clear_type(CacheType::Labels));
    } else {
        anyhow::bail!("Failed to update label");
    }

    Ok(())
}