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

use crate::api::LinearClient;
use crate::display_options;
use crate::output::{
    ensure_non_empty, filter_values, print_json, print_json_owned, sort_values, OutputOptions,
};
use crate::text::truncate;

#[derive(Subcommand)]
pub enum AttachmentCommands {
    /// List attachments for an issue
    #[command(alias = "ls")]
    List {
        /// Issue ID or identifier (e.g., SCW-123)
        issue: String,
    },
    /// Get attachment details
    Get {
        /// Attachment ID
        id: String,
    },
    /// Create an attachment on an issue
    Create {
        /// Issue ID or identifier
        issue: String,
        /// Attachment title
        #[arg(short = 'T', long)]
        title: String,
        /// Attachment URL
        #[arg(short, long)]
        url: String,
        /// Subtitle/description
        #[arg(short, long)]
        subtitle: Option<String>,
        /// Icon URL
        #[arg(long)]
        icon_url: Option<String>,
    },
    /// Update an attachment
    Update {
        /// Attachment ID
        id: String,
        /// New title
        #[arg(short = 'T', long)]
        title: Option<String>,
        /// New URL
        #[arg(short, long)]
        url: Option<String>,
        /// New subtitle
        #[arg(short, long)]
        subtitle: Option<String>,
    },
    /// Delete an attachment
    #[command(alias = "rm")]
    Delete {
        /// Attachment ID
        id: String,
        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
    /// Link a URL to an issue
    #[command(alias = "link")]
    LinkUrl {
        /// Issue ID or identifier
        issue: String,
        /// URL to link
        url: String,
        /// Link title
        #[arg(short = 'T', long)]
        title: Option<String>,
    },
}

#[derive(Tabled)]
struct AttachmentRow {
    #[tabled(rename = "Title")]
    title: String,
    #[tabled(rename = "URL")]
    url: String,
    #[tabled(rename = "Source")]
    source: String,
    #[tabled(rename = "ID")]
    id: String,
}

pub async fn handle(cmd: AttachmentCommands, output: &OutputOptions) -> Result<()> {
    match cmd {
        AttachmentCommands::List { issue } => list_attachments(&issue, output).await,
        AttachmentCommands::Get { id } => get_attachment(&id, output).await,
        AttachmentCommands::Create {
            issue,
            title,
            url,
            subtitle,
            icon_url,
        } => create_attachment(&issue, &title, &url, subtitle, icon_url, output).await,
        AttachmentCommands::Update {
            id,
            title,
            url,
            subtitle,
        } => update_attachment(&id, title, url, subtitle, output).await,
        AttachmentCommands::Delete { id, force } => delete_attachment(&id, force).await,
        AttachmentCommands::LinkUrl { issue, url, title } => {
            link_url(&issue, &url, title, output).await
        }
    }
}

async fn resolve_issue_uuid(client: &LinearClient, issue: &str) -> Result<String> {
    let query = r#"
        query($id: String!) {
            issue(id: $id) {
                id
            }
        }
    "#;

    let result = client.query(query, Some(json!({ "id": issue }))).await?;
    let id = result["data"]["issue"]["id"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Issue not found: {}", issue))?;
    Ok(id.to_string())
}

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

    let query = r#"
        query($id: String!) {
            issue(id: $id) {
                identifier
                title
                attachments(first: 50) {
                    nodes {
                        id
                        title
                        subtitle
                        url
                        sourceType
                        createdAt
                    }
                }
            }
        }
    "#;

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

    if issue_data.is_null() {
        anyhow::bail!("Issue not found: {}", issue);
    }

    let mut attachments = issue_data["attachments"]["nodes"]
        .as_array()
        .cloned()
        .unwrap_or_default();

    if output.is_json() || output.has_template() {
        print_json_owned(
            json!({
                "issue": issue_data["identifier"],
                "title": issue_data["title"],
                "attachments": attachments
            }),
            output,
        )?;
        return Ok(());
    }

    let identifier = issue_data["identifier"].as_str().unwrap_or("");
    let title = issue_data["title"].as_str().unwrap_or("");

    println!("{} {}", identifier.bold(), title);
    println!("{}", "-".repeat(50));

    filter_values(&mut attachments, &output.filters);

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

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

    let width = display_options().max_width(40);
    let rows: Vec<AttachmentRow> = attachments
        .iter()
        .map(|v| AttachmentRow {
            title: truncate(v["title"].as_str().unwrap_or("-"), width),
            url: truncate(v["url"].as_str().unwrap_or("-"), width),
            source: v["sourceType"].as_str().unwrap_or("-").to_string(),
            id: v["id"].as_str().unwrap_or("").to_string(),
        })
        .collect();

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

    Ok(())
}

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

    let query = r#"
        query($id: String!) {
            attachment(id: $id) {
                id
                title
                subtitle
                url
                sourceType
                metadata
                createdAt
                updatedAt
                issue { identifier }
            }
        }
    "#;

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

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

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

    let title = raw["title"].as_str().unwrap_or("-");
    println!("{}", title.bold());
    println!("{}", "-".repeat(40));

    if let Some(issue_id) = raw["issue"]["identifier"].as_str() {
        println!("Issue: {}", issue_id);
    }
    if let Some(subtitle) = raw["subtitle"].as_str() {
        if !subtitle.is_empty() {
            println!("Subtitle: {}", subtitle);
        }
    }
    if let Some(url) = raw["url"].as_str() {
        println!("URL: {}", url);
    }
    if let Some(source) = raw["sourceType"].as_str() {
        println!("Source: {}", source);
    }
    println!(
        "Created: {}",
        raw["createdAt"]
            .as_str()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!(
        "Updated: {}",
        raw["updatedAt"]
            .as_str()
            .map(|s| s.get(..10).unwrap_or(s))
            .unwrap_or("-")
    );
    println!("ID: {}", id);

    Ok(())
}

async fn create_attachment(
    issue: &str,
    title: &str,
    url: &str,
    subtitle: Option<String>,
    icon_url: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;
    let issue_id = resolve_issue_uuid(&client, issue).await?;

    let mut input = json!({
        "issueId": issue_id,
        "title": title,
        "url": url
    });
    if let Some(s) = &subtitle {
        input["subtitle"] = json!(s);
    }
    if let Some(icon) = &icon_url {
        input["iconUrl"] = json!(icon);
    }

    let mutation = r#"
        mutation($input: AttachmentCreateInput!) {
            attachmentCreate(input: $input) {
                success
                attachment { id title url }
            }
        }
    "#;

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

    if result["data"]["attachmentCreate"]["success"].as_bool() == Some(true) {
        let attachment = &result["data"]["attachmentCreate"]["attachment"];
        if output.is_json() || output.has_template() {
            print_json(attachment, output)?;
            return Ok(());
        }
        println!(
            "{} Attachment created: {}",
            "+".green(),
            attachment["title"].as_str().unwrap_or("")
        );
        println!("  ID: {}", attachment["id"].as_str().unwrap_or(""));
        println!("  URL: {}", attachment["url"].as_str().unwrap_or(""));
    } else {
        anyhow::bail!("Failed to create attachment");
    }

    Ok(())
}

async fn update_attachment(
    id: &str,
    title: Option<String>,
    url: Option<String>,
    subtitle: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;

    let mut input = json!({});
    if let Some(t) = title {
        input["title"] = json!(t);
    }
    if let Some(u) = url {
        input["url"] = json!(u);
    }
    if let Some(s) = subtitle {
        input["subtitle"] = json!(s);
    }

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

    let mutation = r#"
        mutation($id: String!, $input: AttachmentUpdateInput!) {
            attachmentUpdate(id: $id, input: $input) {
                success
                attachment { id title url }
            }
        }
    "#;

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

    if result["data"]["attachmentUpdate"]["success"].as_bool() == Some(true) {
        let attachment = &result["data"]["attachmentUpdate"]["attachment"];
        if output.is_json() || output.has_template() {
            print_json(attachment, output)?;
            return Ok(());
        }
        println!("{} Attachment updated", "+".green());
        println!("  ID: {}", attachment["id"].as_str().unwrap_or(""));
    } else {
        anyhow::bail!("Failed to update attachment");
    }

    Ok(())
}

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

    let client = LinearClient::new()?;

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

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

    if result["data"]["attachmentDelete"]["success"]
        .as_bool()
        .unwrap_or(false)
    {
        println!("{} Attachment deleted", "+".green());
    } else {
        anyhow::bail!("Failed to delete attachment {}", id);
    }

    Ok(())
}

async fn link_url(
    issue: &str,
    url: &str,
    title: Option<String>,
    output: &OutputOptions,
) -> Result<()> {
    let client = LinearClient::new()?;
    let issue_id = resolve_issue_uuid(&client, issue).await?;

    let mut vars = json!({
        "issueId": issue_id,
        "url": url
    });
    if let Some(t) = &title {
        vars["title"] = json!(t);
    }

    let mutation = r#"
        mutation($issueId: String!, $url: String!, $title: String) {
            attachmentLinkURL(issueId: $issueId, url: $url, title: $title) {
                success
                attachment { id title url }
            }
        }
    "#;

    let result = client.mutate(mutation, Some(vars)).await?;

    if result["data"]["attachmentLinkURL"]["success"].as_bool() == Some(true) {
        let attachment = &result["data"]["attachmentLinkURL"]["attachment"];
        if output.is_json() || output.has_template() {
            print_json(attachment, output)?;
            return Ok(());
        }
        println!("{} URL linked to issue", "+".green());
        println!("  ID: {}", attachment["id"].as_str().unwrap_or(""));
        println!("  Title: {}", attachment["title"].as_str().unwrap_or("-"));
        println!("  URL: {}", attachment["url"].as_str().unwrap_or(""));
    } else {
        anyhow::bail!("Failed to link URL to issue");
    }

    Ok(())
}