lincli 2026.4.16

Linear CLI — manage issues, projects, cycles, and more from the 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
pub mod cache;

use crate::error::LinearError;
use cache::Cache;
use reqwest::Client;
use std::env;
use std::path::PathBuf;
use std::time::Duration;

const API_URL: &str = "https://api.linear.app/graphql";
const MAX_RETRIES: u32 = 3;
const BACKOFF_BASE_MS: u64 = 1000;

pub struct LinearClient {
    http: Client,
    api_key: String,
    debug: bool,
    cache: Cache,
}

impl LinearClient {
    pub fn new(
        api_key: Option<String>,
        debug: bool,
        workspace: Option<&str>,
    ) -> Result<Self, LinearError> {
        let api_key = match api_key {
            Some(key) => key,
            None => Self::resolve_api_key(workspace)?,
        };

        let http = Client::builder()
            .timeout(Duration::from_secs(30))
            .https_only(true)
            .build()
            .map_err(LinearError::Request)?;

        Ok(Self {
            http,
            api_key,
            debug,
            cache: Cache::new(),
        })
    }

    fn resolve_api_key(workspace: Option<&str>) -> Result<String, LinearError> {
        // 1. Explicit --workspace flag takes priority over everything
        if workspace.is_some()
            && let Some(key) = crate::config::get_workspace_key(workspace)
        {
            return Ok(key);
        }

        // 2. Environment variable
        if let Ok(key) = env::var("LINEAR_API_KEY")
            && !key.is_empty()
        {
            return Ok(key);
        }

        // 3. Config file default workspace
        if let Some(key) = crate::config::get_workspace_key(None) {
            return Ok(key);
        }

        // 3. .env and .env.local files
        for filename in &[".env", ".env.local"] {
            for dir in Self::search_dirs() {
                let path = dir.join(filename);
                if let Ok(contents) = std::fs::read_to_string(&path) {
                    for line in contents.lines() {
                        let line = line.trim();
                        if let Some(val) = line.strip_prefix("LINEAR_API_KEY=") {
                            let val = val.trim().trim_matches('"').trim_matches('\'');
                            if !val.is_empty() {
                                return Ok(val.to_string());
                            }
                        }
                    }
                }
            }
        }

        Err(LinearError::NoApiKey)
    }

    fn search_dirs() -> Vec<PathBuf> {
        let mut dirs = Vec::new();
        if let Ok(cwd) = env::current_dir() {
            dirs.push(cwd);
        }
        dirs
    }

    /// Execute a raw GraphQL query string, returning the raw JSON Value.
    /// Used by all commands for now — typed cynic queries can be added later.
    pub async fn query_raw(
        &self,
        query: &str,
        variables: Option<serde_json::Value>,
    ) -> Result<serde_json::Value, LinearError> {
        if self.debug {
            eprintln!("--- GraphQL Query ---\n{query}");
            if let Some(ref vars) = variables {
                eprintln!(
                    "--- Variables ---\n{}",
                    serde_json::to_string_pretty(vars).unwrap_or_default()
                );
            }
        }

        let mut body = serde_json::json!({"query": query});
        if let Some(vars) = &variables {
            body["variables"] = vars.clone();
        }

        let mut last_err = None;

        for attempt in 0..=MAX_RETRIES {
            let response = self
                .http
                .post(API_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", &self.api_key)
                .json(&body)
                .send()
                .await
                .map_err(LinearError::Request)?;

            let status = response.status();

            if status == reqwest::StatusCode::TOO_MANY_REQUESTS && attempt < MAX_RETRIES {
                let wait = Duration::from_millis(BACKOFF_BASE_MS * 2u64.pow(attempt));
                tokio::time::sleep(wait).await;
                continue;
            }

            let response_text = response.text().await.map_err(LinearError::Request)?;

            if self.debug {
                eprintln!("--- Response ---\n{response_text}");
            }

            if !status.is_success() {
                // Try to extract GraphQL error message
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&response_text)
                    && let Some(errors) = parsed.get("errors").and_then(|e| e.as_array())
                {
                    let msgs: Vec<&str> = errors
                        .iter()
                        .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
                        .collect();
                    if !msgs.is_empty() {
                        return Err(LinearError::GraphQL(msgs.join("; ")));
                    }
                }
                let truncated = if response_text.len() > 200 {
                    format!("{}... (truncated)", &response_text[..200])
                } else {
                    response_text
                };
                last_err = Some(LinearError::Http {
                    status: status.as_u16(),
                    body: truncated,
                });
                continue;
            }

            let gql_response: serde_json::Value =
                serde_json::from_str(&response_text).map_err(LinearError::Json)?;

            if let Some(errors) = gql_response.get("errors").and_then(|e| e.as_array())
                && !errors.is_empty()
            {
                let msgs: Vec<&str> = errors
                    .iter()
                    .filter_map(|e| e.get("message").and_then(|m| m.as_str()))
                    .collect();
                return Err(LinearError::GraphQL(msgs.join("; ")));
            }

            return Ok(gql_response);
        }

        Err(last_err.unwrap_or(LinearError::GraphQL("Max retries exceeded".into())))
    }

    // --- Cache methods ---

    pub async fn get_teams(&self) -> Result<Vec<cache::CachedTeam>, LinearError> {
        if let Some(teams) = self.cache.teams.get() {
            return Ok(teams.clone());
        }
        let result = self
            .query_raw("query { teams { nodes { id name key } } }", None)
            .await?;
        let nodes = result
            .pointer("/data/teams/nodes")
            .ok_or_else(|| LinearError::GraphQL("No teams data".into()))?;
        let teams: Vec<cache::CachedTeam> = serde_json::from_value(nodes.clone())?;
        let _ = self.cache.teams.set(teams.clone());
        Ok(teams)
    }

    pub async fn get_team_id(&self, key_or_name: &str) -> Result<String, LinearError> {
        let teams = self.get_teams().await?;
        Ok(cache::find_team(&teams, key_or_name)?.id.clone())
    }

    pub async fn get_users(&self) -> Result<Vec<cache::CachedUser>, LinearError> {
        if let Some(users) = self.cache.users.get() {
            return Ok(users.clone());
        }
        let result = self
            .query_raw(
                "query { users(first: 250) { nodes { id name displayName email active } } }",
                None,
            )
            .await?;
        let nodes = result
            .pointer("/data/users/nodes")
            .ok_or_else(|| LinearError::GraphQL("No users data".into()))?;
        let users: Vec<cache::CachedUser> = serde_json::from_value(nodes.clone())?;
        let _ = self.cache.users.set(users.clone());
        Ok(users)
    }

    pub async fn get_user_id(&self, name: &str) -> Result<String, LinearError> {
        let users = self.get_users().await?;
        Ok(cache::find_user(&users, name)?.id.clone())
    }

    pub async fn get_project_id(&self, name: &str) -> Result<String, LinearError> {
        // 1. UUID passthrough — no API call needed
        if crate::util::looks_like_uuid(name) {
            return Ok(name.to_string());
        }

        // 2. Name match via cache
        let projects = if let Some(p) = self.cache.projects.get() {
            p.clone()
        } else {
            let result = self
                .query_raw("query { projects(first: 250) { nodes { id name } } }", None)
                .await?;
            let nodes = result
                .pointer("/data/projects/nodes")
                .ok_or_else(|| LinearError::GraphQL("No projects data".into()))?;
            let projects: Vec<cache::CachedProject> = serde_json::from_value(nodes.clone())?;
            let _ = self.cache.projects.set(projects.clone());
            projects
        };

        if let Ok(project) = cache::find_project(&projects, name) {
            return Ok(project.id.clone());
        }

        // 3. SlugId fallback — for URL slugs like "my-project-abc123"
        let slug_query = r#"
            query($slug: String!) {
                projects(filter: { slugId: { eq: $slug } }, first: 1) {
                    nodes { id name }
                }
            }
        "#;
        let slug_result = self
            .query_raw(slug_query, Some(serde_json::json!({ "slug": name })))
            .await?;
        if let Some(id) = slug_result
            .pointer("/data/projects/nodes")
            .and_then(|v| v.as_array())
            .and_then(|nodes| nodes.first())
            .and_then(|project| project.get("id"))
            .and_then(|v| v.as_str())
        {
            return Ok(id.to_string());
        }

        Err(LinearError::NotFound {
            entity: "Project",
            name: name.to_string(),
        })
    }

    pub async fn get_state_id(
        &self,
        team_key: &str,
        state_name: &str,
    ) -> Result<String, LinearError> {
        if !self.cache.states.contains_key(team_key) {
            let team_id = self.get_team_id(team_key).await?;
            let result = self.query_raw(
                r#"query($teamId: ID!) { workflowStates(filter: { team: { id: { eq: $teamId } } }) { nodes { id name type } } }"#,
                Some(serde_json::json!({"teamId": team_id})),
            ).await?;
            let nodes = result
                .pointer("/data/workflowStates/nodes")
                .ok_or_else(|| LinearError::GraphQL("No states data".into()))?;
            let states: Vec<cache::CachedState> = serde_json::from_value(nodes.clone())?;
            self.cache.states.insert(team_key.to_string(), states);
        }
        let entry = self.cache.states.get(team_key).unwrap();
        Ok(cache::find_state(entry.value(), state_name)?.id.clone())
    }

    pub async fn get_label_ids(
        &self,
        names: &[&str],
        team_key: Option<&str>,
    ) -> Result<Vec<String>, LinearError> {
        let cache_key = team_key.unwrap_or("__workspace__");
        if !self.cache.labels.contains_key(cache_key) {
            if let Some(tk) = team_key {
                let team_id = self.get_team_id(tk).await?;

                // Query team-scoped labels
                let team_query = r#"query($teamId: ID!) { issueLabels(filter: { team: { id: { eq: $teamId } } }) { nodes { id name } } }"#;
                let team_result = self
                    .query_raw(team_query, Some(serde_json::json!({"teamId": team_id})))
                    .await?;
                let team_nodes = team_result
                    .pointer("/data/issueLabels/nodes")
                    .ok_or_else(|| LinearError::GraphQL("No labels data".into()))?;
                let mut labels: Vec<cache::CachedLabel> =
                    serde_json::from_value(team_nodes.clone())?;

                // Also query workspace-level labels (no team)
                let ws_query = r#"query { issueLabels(filter: { team: { null: true } }) { nodes { id name } } }"#;
                let ws_result = self.query_raw(ws_query, None).await?;
                if let Some(ws_nodes) = ws_result.pointer("/data/issueLabels/nodes") {
                    let ws_labels: Vec<cache::CachedLabel> =
                        serde_json::from_value(ws_nodes.clone())?;
                    for wl in ws_labels {
                        if !labels.iter().any(|l| l.id == wl.id) {
                            labels.push(wl);
                        }
                    }
                }

                self.cache.labels.insert(cache_key.to_string(), labels);
            } else {
                let result = self
                    .query_raw("query { issueLabels { nodes { id name } } }", None)
                    .await?;
                let nodes = result
                    .pointer("/data/issueLabels/nodes")
                    .ok_or_else(|| LinearError::GraphQL("No labels data".into()))?;
                let labels: Vec<cache::CachedLabel> = serde_json::from_value(nodes.clone())?;
                self.cache.labels.insert(cache_key.to_string(), labels);
            }
        }
        let entry = self.cache.labels.get(cache_key).unwrap();
        cache::find_labels(entry.value(), names)
    }
}

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

    #[test]
    fn looks_like_uuid_passthrough() {
        // UUIDs should be detectable so get_project_id can skip the API call
        assert!(crate::util::looks_like_uuid(
            "550e8400-e29b-41d4-a716-446655440000"
        ));
        assert!(!crate::util::looks_like_uuid("my-project"));
        assert!(!crate::util::looks_like_uuid("My Project Name"));
    }

    #[test]
    fn test_resolve_api_key_from_env() {
        temp_env::with_var("LINEAR_API_KEY", Some("lin_api_test123"), || {
            let key = LinearClient::resolve_api_key(None).unwrap();
            assert_eq!(key, "lin_api_test123");
        });
    }

    fn has_local_env_file() -> bool {
        std::path::Path::new(".env").exists() || std::path::Path::new(".env.local").exists()
    }

    #[test]
    fn test_resolve_api_key_empty_env() {
        if has_local_env_file() {
            return; // .env/.env.local present — key will be found, test not applicable
        }
        temp_env::with_var("LINEAR_API_KEY", Some(""), || {
            let result = LinearClient::resolve_api_key(None);
            assert!(result.is_err());
        });
    }

    #[test]
    fn test_resolve_api_key_missing() {
        if has_local_env_file() {
            return; // .env/.env.local present — key will be found, test not applicable
        }
        temp_env::with_var_unset("LINEAR_API_KEY", || {
            let result = LinearClient::resolve_api_key(None);
            assert!(result.is_err());
            let err = result.unwrap_err().to_string();
            assert!(err.contains("LINEAR_API_KEY not found"));
        });
    }

    #[test]
    fn test_new_with_explicit_key() {
        let client = LinearClient::new(Some("lin_api_explicit".into()), false, None);
        assert!(client.is_ok());
    }
}