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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
use anyhow::{Context, Result};
use clap::{Subcommand, ValueHint};
use csv::Writer;
use serde_json::json;
use std::borrow::Cow;
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::api::LinearClient;
use crate::output::OutputOptions;
use crate::pagination::{paginate_nodes, stream_nodes, PaginationOptions};
use colored::Colorize;

#[cfg(unix)]
fn create_private_file(path: &Path) -> Result<std::fs::File> {
    use std::os::unix::fs::OpenOptionsExt;

    Ok(std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o600)
        .open(path)?)
}

#[cfg(not(unix))]
fn create_private_file(path: &Path) -> Result<std::fs::File> {
    Ok(std::fs::File::create(path)?)
}

fn atomic_temp_path(path: &Path) -> Result<PathBuf> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .context("Output path must include a file name")?;
    let unique = format!(
        ".{}.tmp-{}-{}",
        file_name,
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)?
            .as_nanos()
    );
    Ok(parent.join(unique))
}

struct AtomicPrivateFile {
    file: Option<std::fs::File>,
    temp_path: PathBuf,
    final_path: PathBuf,
    committed: bool,
}

impl AtomicPrivateFile {
    fn create(path: &Path) -> Result<Self> {
        let temp_path = atomic_temp_path(path)?;
        let file = create_private_file(&temp_path)?;
        Ok(Self {
            file: Some(file),
            temp_path,
            final_path: path.to_path_buf(),
            committed: false,
        })
    }

    fn commit(&mut self) -> Result<()> {
        if self.committed {
            return Ok(());
        }

        if let Some(mut file) = self.file.take() {
            file.flush()?;
            file.sync_all()?;
            drop(file);
        }

        std::fs::rename(&self.temp_path, &self.final_path)?;
        self.committed = true;
        Ok(())
    }

    #[cfg(test)]
    fn file_mut(&mut self) -> &mut std::fs::File {
        self.file.as_mut().expect("atomic file should be open")
    }
}

impl Write for AtomicPrivateFile {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.file
            .as_mut()
            .expect("atomic file should be open")
            .write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.file
            .as_mut()
            .expect("atomic file should be open")
            .flush()
    }
}

impl Drop for AtomicPrivateFile {
    fn drop(&mut self) {
        if !self.committed {
            let _ = self.file.take();
            let _ = std::fs::remove_file(&self.temp_path);
        }
    }
}

enum ExportDestination {
    Stdout(std::io::Stdout),
    Atomic(AtomicPrivateFile),
}

impl ExportDestination {
    fn commit(&mut self) -> Result<()> {
        if let Self::Atomic(file) = self {
            file.commit()?;
        }
        Ok(())
    }
}

impl Write for ExportDestination {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            Self::Stdout(stdout) => stdout.write(buf),
            Self::Atomic(file) => file.write(buf),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            Self::Stdout(stdout) => stdout.flush(),
            Self::Atomic(file) => file.flush(),
        }
    }
}

fn write_private_string(path: &str, contents: &str) -> Result<()> {
    let mut file = AtomicPrivateFile::create(Path::new(path))?;
    file.write_all(contents.as_bytes())?;
    file.commit()?;
    Ok(())
}

fn sanitize_csv_cell(value: &str) -> Cow<'_, str> {
    match value.chars().next() {
        Some('=' | '+' | '-' | '@' | '\t' | '\r') => Cow::Owned(format!("'{}", value)),
        _ => Cow::Borrowed(value),
    }
}

#[derive(Subcommand, Debug)]
pub enum ExportCommands {
    /// Export issues to CSV
    Csv {
        /// Team key to export
        #[arg(short, long)]
        team: Option<String>,
        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        file: Option<String>,
        /// Include completed issues
        #[arg(long)]
        include_completed: bool,
        /// Limit number of issues (default: 250, ignored with --all)
        #[arg(long)]
        limit: Option<usize>,
        /// Export all matching issues
        #[arg(long)]
        all: bool,
    },
    /// Export issues to Markdown
    Markdown {
        /// Team key to export
        #[arg(short, long)]
        team: Option<String>,
        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        file: Option<String>,
        /// Limit number of issues (default: 250, ignored with --all)
        #[arg(long)]
        limit: Option<usize>,
        /// Export all matching issues
        #[arg(long)]
        all: bool,
    },
    /// Export issues to JSON file
    Json {
        /// Team key to export
        #[arg(short, long)]
        team: Option<String>,
        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        file: Option<String>,
        /// Include completed issues
        #[arg(long)]
        include_completed: bool,
        /// Limit number of issues (default: 250, ignored with --all)
        #[arg(long)]
        limit: Option<usize>,
        /// Export all matching issues
        #[arg(long)]
        all: bool,
        /// Pretty-print JSON output
        #[arg(long)]
        pretty: bool,
    },
    /// Export projects to CSV
    ProjectsCsv {
        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath)]
        file: Option<String>,
        /// Include archived projects
        #[arg(long)]
        archived: bool,
    },
}

pub async fn handle(cmd: ExportCommands, _output: &OutputOptions) -> Result<()> {
    match cmd {
        ExportCommands::Csv {
            team,
            file,
            include_completed,
            limit,
            all,
        } => export_csv(team, file, include_completed, limit, all).await,
        ExportCommands::Markdown {
            team,
            file,
            limit,
            all,
        } => export_markdown(team, file, limit, all).await,
        ExportCommands::Json {
            team,
            file,
            include_completed,
            limit,
            all,
            pretty,
        } => export_json(team, file, include_completed, limit, all, pretty).await,
        ExportCommands::ProjectsCsv { file, archived } => export_projects_csv(file, archived).await,
    }
}

async fn export_csv(
    team: Option<String>,
    file: Option<String>,
    include_completed: bool,
    limit: Option<usize>,
    all: bool,
) -> Result<()> {
    let client = LinearClient::new()?;

    let query = r#"
        query($filter: IssueFilter, $first: Int, $after: String, $last: Int, $before: String) {
            issues(first: $first, after: $after, last: $last, before: $before, filter: $filter) {
                nodes {
                    identifier
                    title
                    description
                    priority
                    estimate
                    dueDate
                    createdAt
                    updatedAt
                    state { name type }
                    assignee { name email }
                    team { key name }
                    labels { nodes { name } }
                    project { name }
                    cycle { number name }
                }
                pageInfo {
                    hasNextPage
                    endCursor
                    hasPreviousPage
                    startCursor
                }
            }
        }
    "#;

    let mut filter = json!({});
    if let Some(ref t) = team {
        filter["team"] = json!({ "key": { "eq": t } });
    }
    if !include_completed {
        filter["state"] = json!({ "type": { "neq": "completed" } });
    }

    let mut vars = serde_json::Map::new();
    vars.insert("filter".to_string(), filter);

    let mut pagination = PaginationOptions {
        page_size: Some(250),
        ..Default::default()
    };
    if all {
        pagination.all = true;
    } else {
        pagination.limit = Some(limit.unwrap_or(250));
    }

    // Use RefCell to allow mutable access to the writer from the closure
    use std::cell::RefCell;
    use std::rc::Rc;

    let wtr: Rc<RefCell<Writer<ExportDestination>>> = if let Some(ref path) = file {
        Rc::new(RefCell::new(Writer::from_writer(
            ExportDestination::Atomic(AtomicPrivateFile::create(Path::new(path))?),
        )))
    } else {
        Rc::new(RefCell::new(Writer::from_writer(
            ExportDestination::Stdout(std::io::stdout()),
        )))
    };

    // Write CSV header
    wtr.borrow_mut().write_record([
        "Identifier",
        "Title",
        "Status",
        "Priority",
        "Estimate",
        "Due Date",
        "Assignee",
        "Team",
        "Project",
        "Cycle",
        "Labels",
        "Created",
        "Updated",
    ])?;

    // Stream pages and write rows as they arrive
    let wtr_clone = Rc::clone(&wtr);
    let total = stream_nodes(
        &client,
        query,
        vars,
        &["data", "issues", "nodes"],
        &["data", "issues", "pageInfo"],
        &pagination,
        250,
        |batch| {
            let wtr = Rc::clone(&wtr_clone);
            async move {
                let mut writer = wtr.borrow_mut();
                for issue in &batch {
                    let labels: Vec<&str> = issue["labels"]["nodes"]
                        .as_array()
                        .map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect())
                        .unwrap_or_default();

                    writer.write_record([
                        sanitize_csv_cell(issue["identifier"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(issue["title"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(issue["state"]["name"].as_str().unwrap_or("")).as_ref(),
                        &issue["priority"].as_i64().unwrap_or(0).to_string(),
                        &issue["estimate"].as_f64().unwrap_or(0.0).to_string(),
                        sanitize_csv_cell(issue["dueDate"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(issue["assignee"]["name"].as_str().unwrap_or(""))
                            .as_ref(),
                        sanitize_csv_cell(issue["team"]["key"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(issue["project"]["name"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(issue["cycle"]["name"].as_str().unwrap_or("")).as_ref(),
                        sanitize_csv_cell(&labels.join("; ")).as_ref(),
                        &issue["createdAt"]
                            .as_str()
                            .unwrap_or("")
                            .chars()
                            .take(10)
                            .collect::<String>(),
                        &issue["updatedAt"]
                            .as_str()
                            .unwrap_or("")
                            .chars()
                            .take(10)
                            .collect::<String>(),
                    ])?;
                }
                Ok(())
            }
        },
    )
    .await?;

    wtr.borrow_mut().flush()?;
    let writer = std::rc::Rc::try_unwrap(wtr)
        .map_err(|_| anyhow::anyhow!("Failed to recover CSV export writer"))?
        .into_inner();
    let mut destination = writer
        .into_inner()
        .map_err(|err| anyhow::anyhow!(err.into_error().to_string()))?;
    destination.commit()?;

    if let Some(ref path) = file {
        eprintln!("Exported {} issues to {}", total, path);
    }

    Ok(())
}

async fn export_markdown(
    team: Option<String>,
    file: Option<String>,
    limit: Option<usize>,
    all: bool,
) -> Result<()> {
    let client = LinearClient::new()?;

    let query = r#"
        query($filter: IssueFilter, $first: Int, $after: String, $last: Int, $before: String) {
            issues(first: $first, after: $after, last: $last, before: $before, filter: $filter) {
                nodes {
                    identifier
                    title
                    description
                    priority
                    state { name }
                    assignee { name }
                    team { key }
                    labels { nodes { name } }
                }
                pageInfo {
                    hasNextPage
                    endCursor
                    hasPreviousPage
                    startCursor
                }
            }
        }
    "#;

    let mut filter = json!({ "state": { "type": { "neq": "completed" } } });
    if let Some(ref t) = team {
        filter["team"] = json!({ "key": { "eq": t } });
    }

    let mut vars = serde_json::Map::new();
    vars.insert("filter".to_string(), filter);

    let mut pagination = PaginationOptions {
        page_size: Some(250),
        ..Default::default()
    };
    if all {
        pagination.all = true;
    } else {
        pagination.limit = Some(limit.unwrap_or(250));
    }

    let issues = paginate_nodes(
        &client,
        query,
        vars,
        &["data", "issues", "nodes"],
        &["data", "issues", "pageInfo"],
        &pagination,
        250,
    )
    .await?;

    let mut output = if let Some(ref path) = file {
        ExportDestination::Atomic(AtomicPrivateFile::create(Path::new(path))?)
    } else {
        ExportDestination::Stdout(std::io::stdout())
    };

    writeln!(output, "# Issues Export\n")?;
    writeln!(
        output,
        "Generated: {}\n",
        chrono::Utc::now().format("%Y-%m-%d %H:%M UTC")
    )?;

    // Group by status
    let mut by_status: std::collections::HashMap<String, Vec<&serde_json::Value>> =
        std::collections::HashMap::new();
    for issue in &issues {
        let status = issue["state"]["name"]
            .as_str()
            .unwrap_or("Unknown")
            .to_string();
        by_status.entry(status).or_default().push(issue);
    }

    for (status, status_issues) in by_status {
        writeln!(output, "## {}\n", status)?;
        for issue in status_issues {
            let labels: Vec<&str> = issue["labels"]["nodes"]
                .as_array()
                .map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect())
                .unwrap_or_default();
            let label_str = if labels.is_empty() {
                String::new()
            } else {
                format!(" `{}`", labels.join("` `"))
            };

            writeln!(
                output,
                "- **{}** {}{}",
                issue["identifier"].as_str().unwrap_or(""),
                issue["title"].as_str().unwrap_or(""),
                label_str
            )?;

            if let Some(assignee) = issue["assignee"]["name"].as_str() {
                writeln!(output, "  - Assignee: {}", assignee)?;
            }
        }
        writeln!(output)?;
    }

    output.commit()?;

    if let Some(ref path) = file {
        eprintln!("Exported {} issues to {}", issues.len(), path);
    }

    Ok(())
}

async fn export_json(
    team: Option<String>,
    file: Option<String>,
    include_completed: bool,
    limit: Option<usize>,
    all: bool,
    pretty: bool,
) -> Result<()> {
    let client = LinearClient::new()?;

    let query = r#"
        query($filter: IssueFilter, $first: Int, $after: String, $last: Int, $before: String) {
            issues(first: $first, after: $after, last: $last, before: $before, filter: $filter) {
                nodes {
                    identifier
                    title
                    description
                    priority
                    estimate
                    dueDate
                    createdAt
                    updatedAt
                    state { name type }
                    assignee { name email }
                    team { key name }
                    labels { nodes { name } }
                    project { name }
                    cycle { number name }
                }
                pageInfo {
                    hasNextPage
                    endCursor
                    hasPreviousPage
                    startCursor
                }
            }
        }
    "#;

    let mut filter = json!({});
    if let Some(ref t) = team {
        filter["team"] = json!({ "key": { "eq": t } });
    }
    if !include_completed {
        filter["state"] = json!({ "type": { "neq": "completed" } });
    }

    let mut vars = serde_json::Map::new();
    vars.insert("filter".to_string(), filter);

    let mut pagination = PaginationOptions {
        page_size: Some(250),
        ..Default::default()
    };
    if all {
        pagination.all = true;
    } else {
        pagination.limit = Some(limit.unwrap_or(250));
    }

    let issues = paginate_nodes(
        &client,
        query,
        vars,
        &["data", "issues", "nodes"],
        &["data", "issues", "pageInfo"],
        &pagination,
        250,
    )
    .await?;

    // Flatten issue objects for easier re-import
    let flattened: Vec<serde_json::Value> = issues
        .iter()
        .map(|issue| {
            let labels: Vec<&str> = issue["labels"]["nodes"]
                .as_array()
                .map(|a| a.iter().filter_map(|l| l["name"].as_str()).collect())
                .unwrap_or_default();

            json!({
                "identifier": issue["identifier"],
                "title": issue["title"],
                "description": issue["description"],
                "priority": issue["priority"],
                "estimate": issue["estimate"],
                "dueDate": issue["dueDate"],
                "status": issue["state"]["name"],
                "statusType": issue["state"]["type"],
                "assignee": issue["assignee"]["name"],
                "assigneeEmail": issue["assignee"]["email"],
                "team": issue["team"]["key"],
                "teamName": issue["team"]["name"],
                "project": issue["project"]["name"],
                "cycleNumber": issue["cycle"]["number"],
                "cycleName": issue["cycle"]["name"],
                "labels": labels,
                "createdAt": issue["createdAt"],
                "updatedAt": issue["updatedAt"],
            })
        })
        .collect();

    let json_output = if pretty {
        serde_json::to_string_pretty(&flattened)?
    } else {
        serde_json::to_string(&flattened)?
    };

    if let Some(ref path) = file {
        write_private_string(path, &json_output)?;
        eprintln!("Exported {} issues to {}", flattened.len(), path);
    } else {
        println!("{}", json_output);
    }

    Ok(())
}

async fn export_projects_csv(file: Option<String>, include_archived: bool) -> Result<()> {
    let client = LinearClient::new()?;

    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
                    description
                    state
                    priority
                    progress
                    startDate
                    targetDate
                    url
                    createdAt
                    updatedAt
                    lead { name email }
                    teams { nodes { key name } }
                    members { nodes { name } }
                }
                pageInfo {
                    hasNextPage
                    endCursor
                    hasPreviousPage
                    startCursor
                }
            }
        }
    "#;

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

    let pagination = PaginationOptions {
        page_size: Some(50),
        all: true,
        ..Default::default()
    };

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

    let mut wtr: Writer<ExportDestination> = if let Some(ref path) = file {
        Writer::from_writer(ExportDestination::Atomic(AtomicPrivateFile::create(
            Path::new(path),
        )?))
    } else {
        Writer::from_writer(ExportDestination::Stdout(std::io::stdout()))
    };

    wtr.write_record([
        "Name",
        "State",
        "Priority",
        "Progress",
        "Start Date",
        "Target Date",
        "Lead",
        "Teams",
        "Members",
        "Created",
        "Updated",
        "URL",
    ])?;

    for project in &projects {
        let teams: Vec<&str> = project["teams"]["nodes"]
            .as_array()
            .map(|a| a.iter().filter_map(|t| t["key"].as_str()).collect())
            .unwrap_or_default();

        let members: Vec<&str> = project["members"]["nodes"]
            .as_array()
            .map(|a| a.iter().filter_map(|m| m["name"].as_str()).collect())
            .unwrap_or_default();

        let progress = project["progress"]
            .as_f64()
            .map(|p| format!("{:.0}%", p * 100.0))
            .unwrap_or_default();

        wtr.write_record([
            sanitize_csv_cell(project["name"].as_str().unwrap_or("")).as_ref(),
            sanitize_csv_cell(project["state"].as_str().unwrap_or("")).as_ref(),
            &project["priority"].as_i64().unwrap_or(0).to_string(),
            sanitize_csv_cell(&progress).as_ref(),
            sanitize_csv_cell(project["startDate"].as_str().unwrap_or("")).as_ref(),
            sanitize_csv_cell(project["targetDate"].as_str().unwrap_or("")).as_ref(),
            sanitize_csv_cell(project["lead"]["name"].as_str().unwrap_or("")).as_ref(),
            sanitize_csv_cell(&teams.join("; ")).as_ref(),
            sanitize_csv_cell(&members.join("; ")).as_ref(),
            &project["createdAt"]
                .as_str()
                .unwrap_or("")
                .chars()
                .take(10)
                .collect::<String>(),
            &project["updatedAt"]
                .as_str()
                .unwrap_or("")
                .chars()
                .take(10)
                .collect::<String>(),
            sanitize_csv_cell(project["url"].as_str().unwrap_or("")).as_ref(),
        ])?;
    }

    wtr.flush()?;
    let mut destination = wtr
        .into_inner()
        .map_err(|err| anyhow::anyhow!(err.into_error().to_string()))?;
    destination.commit()?;

    if let Some(ref path) = file {
        eprintln!(
            "{}",
            format!("Exported {} projects to {}", projects.len(), path).green()
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn temp_path(label: &str) -> PathBuf {
        let unique = format!(
            "linear-cli-export-{}-{}-{}",
            label,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        std::env::temp_dir().join(unique)
    }

    #[test]
    fn test_atomic_private_file_commit_replaces_destination() {
        let path = temp_path("commit");
        std::fs::write(&path, "old").unwrap();

        let mut file = AtomicPrivateFile::create(&path).unwrap();
        file.file_mut().write_all(b"new").unwrap();
        file.commit().unwrap();

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
    }

    #[test]
    fn test_atomic_private_file_drop_preserves_existing_destination() {
        let path = temp_path("drop");
        std::fs::write(&path, "old").unwrap();

        let mut file = AtomicPrivateFile::create(&path).unwrap();
        file.file_mut().write_all(b"partial").unwrap();
        drop(file);

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "old");
    }
}