linear-cli 0.2.4

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
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, sort_values, OutputOptions};
use crate::pagination::paginate_nodes;
use crate::text::truncate;

#[derive(Subcommand)]
pub enum TimeCommands {
    /// Log time spent on an issue
    #[command(after_help = r#"EXAMPLES:
    linear time log LIN-123 2h                 # Log 2 hours
    linear time log LIN-123 30m                # Log 30 minutes
    linear time log LIN-123 1h30m              # Log 1.5 hours"#)]
    Log {
        /// Issue ID or identifier (e.g., "LIN-123")
        issue: String,
        /// Time spent (e.g., "2h", "30m", "1h30m")
        duration: String,
        /// Optional description of work done
        #[arg(short, long)]
        description: Option<String>,
    },
    /// List time entries
    #[command(after_help = r#"EXAMPLES:
    linear time list                           # List recent time entries
    linear time list -i LIN-123                # List for specific issue
    linear time list --output json             # Output as JSON"#)]
    List {
        /// Filter by issue ID or identifier
        #[arg(short, long)]
        issue: Option<String>,
    },
    /// Delete a time entry
    Delete {
        /// Time entry ID
        id: String,
        /// Skip confirmation prompt
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Tabled)]
struct TimeEntryRow {
    #[tabled(rename = "ID")]
    id: String,
    #[tabled(rename = "Issue")]
    issue: String,
    #[tabled(rename = "Duration")]
    duration: String,
    #[tabled(rename = "Date")]
    date: String,
    #[tabled(rename = "User")]
    user: String,
}

pub async fn handle(cmd: TimeCommands, output: &OutputOptions) -> Result<()> {
    match cmd {
        TimeCommands::Log {
            issue,
            duration,
            description,
        } => log_time(&issue, &duration, description).await,
        TimeCommands::List { issue } => list_time_entries(issue, output).await,
        TimeCommands::Delete { id, force } => delete_time_entry(&id, force).await,
    }
}

/// Parse duration string like "2h", "30m", "1h30m" into minutes
fn parse_duration(duration: &str) -> Result<i32> {
    let duration = duration.to_lowercase();
    let mut total_minutes = 0;
    let mut current_num = String::new();

    for c in duration.chars() {
        if c.is_ascii_digit() {
            current_num.push(c);
        } else if c == 'h' {
            let hours: i32 = current_num.parse().unwrap_or(0);
            total_minutes += hours * 60;
            current_num.clear();
        } else if c == 'm' {
            let minutes: i32 = current_num.parse().unwrap_or(0);
            total_minutes += minutes;
            current_num.clear();
        }
    }

    // If just a number, treat as minutes
    if !current_num.is_empty() {
        total_minutes += current_num.parse::<i32>().unwrap_or(0);
    }

    if total_minutes == 0 {
        anyhow::bail!("Invalid duration format. Use format like '2h', '30m', or '1h30m'");
    }

    Ok(total_minutes)
}

/// Format minutes into human-readable duration
fn format_duration(minutes: i32) -> String {
    let hours = minutes / 60;
    let mins = minutes % 60;
    if hours > 0 && mins > 0 {
        format!("{}h {}m", hours, mins)
    } else if hours > 0 {
        format!("{}h", hours)
    } else {
        format!("{}m", mins)
    }
}

async fn log_time(issue_id: &str, duration: &str, description: Option<String>) -> Result<()> {
    let minutes = parse_duration(duration)?;
    let client = LinearClient::new()?;

    // First, resolve the issue to get its UUID
    let query = r#"
        query($id: String!) {
            issue(id: $id) {
                id
                identifier
                title
            }
        }
    "#;

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

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

    let issue_uuid = issue["id"].as_str().unwrap_or("");
    let identifier = issue["identifier"].as_str().unwrap_or(issue_id);
    let title = issue["title"].as_str().unwrap_or("");

    // Create time entry using timeScheduleCreate mutation
    // Note: Linear's API uses timeScheduleCreate for logging time
    let mutation = r#"
        mutation CreateTimeEntry($issueId: String!, $duration: Int!, $description: String) {
            timeScheduleCreate(
                input: {
                    issueId: $issueId
                    duration: $duration
                    description: $description
                }
            ) {
                success
                timeSchedule {
                    id
                }
            }
        }
    "#;

    let variables = json!({
        "issueId": issue_uuid,
        "duration": minutes,
        "description": description
    });

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

    match result {
        Ok(data) => {
            if data["data"]["timeScheduleCreate"]["success"].as_bool() == Some(true) {
                println!(
                    "{} Logged {} on {} {}",
                    "+".green(),
                    format_duration(minutes).cyan(),
                    identifier.cyan(),
                    title.dimmed()
                );
            } else {
                // Time tracking might not be enabled or different API
                println!(
                    "{} Time tracking may not be available for your Linear workspace.",
                    "!".yellow()
                );
                println!(
                    "Attempted to log {} on {}",
                    format_duration(minutes),
                    identifier
                );
            }
        }
        Err(_) => {
            // Fallback message - Linear's time tracking API varies by plan
            println!(
                "{} Time tracking API not available. This feature requires Linear's time tracking add-on.",
                "!".yellow()
            );
        }
    }

    Ok(())
}

async fn list_time_entries(issue_filter: Option<String>, output: &OutputOptions) -> Result<()> {
    let client = LinearClient::new()?;

    // Query time schedules
    let query = if issue_filter.is_some() {
        r#"
            query($issueId: String!, $first: Int, $after: String, $last: Int, $before: String) {
                issue(id: $issueId) {
                    id
                    identifier
                    timeSchedules(first: $first, after: $after, last: $last, before: $before) {
                        nodes {
                            id
                            duration
                            createdAt
                            description
                            user { name }
                        }
                        pageInfo {
                            hasNextPage
                            endCursor
                            hasPreviousPage
                            startCursor
                        }
                    }
                }
            }
        "#
    } else {
        r#"
            query($first: Int, $after: String, $last: Int, $before: String) {
                timeSchedules(first: $first, after: $after, last: $last, before: $before) {
                    nodes {
                        id
                        duration
                        createdAt
                        description
                        issue { identifier }
                        user { name }
                    }
                    pageInfo {
                        hasNextPage
                        endCursor
                        hasPreviousPage
                        startCursor
                    }
                }
            }
        "#
    };

    let pagination = output.pagination.with_default_limit(20);
    let entries = if let Some(issue_id) = issue_filter {
        let mut vars = serde_json::Map::new();
        vars.insert("issueId".to_string(), json!(issue_id));
        paginate_nodes(
            &client,
            query,
            vars,
            &["data", "issue", "timeSchedules", "nodes"],
            &["data", "issue", "timeSchedules", "pageInfo"],
            &pagination,
            20,
        )
        .await
    } else {
        paginate_nodes(
            &client,
            query,
            serde_json::Map::new(),
            &["data", "timeSchedules", "nodes"],
            &["data", "timeSchedules", "pageInfo"],
            &pagination,
            20,
        )
        .await
    };

    match entries {
        Ok(mut entries) => {
            if output.is_json() || output.has_template() {
                print_json(&serde_json::Value::Array(entries.clone()), output)?;
                return Ok(());
            }

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

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

            let issue_width = display_options().max_width(20);
            let user_width = display_options().max_width(30);
            let rows: Vec<TimeEntryRow> = entries
                .iter()
                .map(|e| {
                    let duration_mins = e["duration"].as_i64().unwrap_or(0) as i32;
                    TimeEntryRow {
                        id: e["id"].as_str().unwrap_or("").chars().take(8).collect(),
                        issue: truncate(
                            e["issue"]["identifier"].as_str().unwrap_or("-"),
                            issue_width,
                        ),
                        duration: format_duration(duration_mins),
                        date: e["createdAt"]
                            .as_str()
                            .unwrap_or("")
                            .chars()
                            .take(10)
                            .collect(),
                        user: truncate(e["user"]["name"].as_str().unwrap_or("-"), user_width),
                    }
                })
                .collect();

            let table = Table::new(rows).to_string();
            println!("{}", table);
        }
        Err(_) => {
            println!(
                "{} Time tracking API not available. This feature requires Linear's time tracking add-on.",
                "!".yellow()
            );
        }
    }

    Ok(())
}

async fn delete_time_entry(id: &str, force: bool) -> Result<()> {
    if !force {
        let confirm = dialoguer::Confirm::new()
            .with_prompt(format!("Delete time entry {}?", id))
            .default(false)
            .interact()?;

        if !confirm {
            println!("Cancelled.");
            return Ok(());
        }
    }

    let client = LinearClient::new()?;

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

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

    if result["data"]["timeScheduleDelete"]["success"].as_bool() == Some(true) {
        println!("{} Time entry deleted", "+".green());
    } else {
        anyhow::bail!("Failed to delete time entry");
    }

    Ok(())
}

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

    #[test]
    fn test_parse_duration_hours() {
        assert_eq!(parse_duration("2h").unwrap(), 120);
    }

    #[test]
    fn test_parse_duration_minutes() {
        assert_eq!(parse_duration("30m").unwrap(), 30);
    }

    #[test]
    fn test_parse_duration_combined() {
        assert_eq!(parse_duration("1h30m").unwrap(), 90);
    }

    #[test]
    fn test_parse_duration_just_number() {
        assert_eq!(parse_duration("45").unwrap(), 45);
    }

    #[test]
    fn test_format_duration() {
        assert_eq!(format_duration(90), "1h 30m");
        assert_eq!(format_duration(60), "1h");
        assert_eq!(format_duration(45), "45m");
    }
}