runner-run 0.18.0

Universal project task runner
Documentation
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
//! Position analysis for hover and completion.
//!
//! A small, TOML-aware (not TOML-complete) reading of the line under the cursor
//! plus the nearest `[section]` header above it. Enough to answer "what section
//! am I in, and am I on a key or a value?" — which drives both hover lookups and
//! completion candidate sets without a full document parse.

use lsp_types::{
    CompletionItem, CompletionItemKind, Documentation, Hover, HoverContents, MarkupContent,
    MarkupKind, Position,
};

use super::schema_index::SchemaIndex;
use super::text::LineIndex;
use crate::types::{PackageManager, TaskRunner, TaskSource};

/// What the cursor is sitting on within its line.
enum LineShape {
    /// A `[section]` header line; the string is the (possibly partial) path.
    Header(String),
    /// The key side of an assignment (or a bare word being typed as a key).
    Key,
    /// The value side, right of `=`; the string is the key on the left.
    Value(String),
    /// Blank / whitespace-only line.
    Empty,
}

/// The cursor's section context plus what it's on.
struct Cursor {
    /// Nearest `[section]` header above the cursor line.
    section: Option<String>,
    /// Shape of the cursor's own line.
    shape: LineShape,
}

/// Strip a `[section]` header line to its inner path. Tolerates a missing
/// closing bracket so a half-typed `[ta` still reads as a header.
fn header_path(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let inner = trimmed.strip_prefix('[')?;
    Some(inner.strip_suffix(']').unwrap_or(inner).trim().to_string())
}

/// Read the cursor context from the document text and position.
fn analyze(index: &LineIndex, text: &str, pos: Position) -> Cursor {
    let line_no = pos.line as usize;
    let line_text = text.lines().nth(line_no).unwrap_or("");

    let section = text.lines().take(line_no).filter_map(header_path).last();

    if header_path(line_text).is_some() && line_text.trim_start().starts_with('[') {
        let partial = line_text
            .trim()
            .trim_start_matches('[')
            .trim_end_matches(']')
            .trim()
            .to_string();
        return Cursor {
            section,
            shape: LineShape::Header(partial),
        };
    }

    let shape = line_text.find('=').map_or_else(
        || {
            if line_text.trim().is_empty() {
                LineShape::Empty
            } else {
                LineShape::Key
            }
        },
        |eq| {
            let line_start = index.offset(text, Position::new(pos.line, 0));
            let within = index.offset(text, pos).saturating_sub(line_start);
            if within > eq {
                LineShape::Value(line_text[..eq].trim().to_string())
            } else {
                LineShape::Key
            }
        },
    );

    Cursor { section, shape }
}

/// Build a hover response for the cursor, if it lands on something documented.
pub(super) fn hover(
    index: &LineIndex,
    schema: &SchemaIndex,
    text: &str,
    pos: Position,
) -> Option<Hover> {
    let cursor = analyze(index, text, pos);
    let (title, body) = match cursor.shape {
        LineShape::Header(path) => describe_section(schema, &path)?,
        LineShape::Key | LineShape::Value(_) => {
            let key = match &cursor.shape {
                LineShape::Value(key) => key.clone(),
                _ => current_key(text, pos)?,
            };
            describe_field(schema, cursor.section.as_deref()?, &key)?
        }
        LineShape::Empty => return None,
    };
    Some(Hover {
        contents: HoverContents::Markup(markdown(&title, &body)),
        range: None,
    })
}

/// The bare key token on the cursor's line (text before `=`, or the first word).
fn current_key(text: &str, pos: Position) -> Option<String> {
    let line = text.lines().nth(pos.line as usize)?;
    let lhs = line.split('=').next().unwrap_or(line).trim();
    let key = lhs.split_whitespace().next()?;
    (!key.is_empty()).then(|| key.to_string())
}

/// Hover/title for a `[section]` (or `[parent.child]` sub-table).
fn describe_section(schema: &SchemaIndex, path: &str) -> Option<(String, String)> {
    if let Some((parent, field)) = path.split_once('.') {
        let doc = schema.section(parent)?.fields.get(field)?;
        return Some((
            format!("[{path}]"),
            doc.description.clone().unwrap_or_default(),
        ));
    }
    let section = schema.section(path)?;
    Some((format!("[{path}]"), section.description.clone()?))
}

/// Hover/title for a `key` within `section`.
fn describe_field(schema: &SchemaIndex, section: &str, key: &str) -> Option<(String, String)> {
    if let Some((parent, sub)) = section.split_once('.') {
        // A sub-table entry (e.g. a pin under `[tasks.overrides]`): describe the
        // owning field, since individual entry keys are user-chosen task names.
        let doc = schema.section(parent)?.fields.get(sub)?;
        return Some((
            format!("[{section}].{key}"),
            doc.description.clone().unwrap_or_default(),
        ));
    }
    let doc = schema.section(section)?.fields.get(key)?;
    let mut body = doc.description.clone().unwrap_or_default();
    if doc.deprecated {
        body = format!("**Deprecated.**\n\n{body}");
    }
    Some((format!("[{section}].{key}"), body))
}

/// Completion candidates for the cursor.
pub(super) fn completion(
    index: &LineIndex,
    schema: &SchemaIndex,
    text: &str,
    pos: Position,
) -> Vec<CompletionItem> {
    let cursor = analyze(index, text, pos);
    match cursor.shape {
        LineShape::Header(_) => section_items(schema, false),
        LineShape::Value(key) => value_items(schema, cursor.section.as_deref(), &key),
        LineShape::Key => field_items(schema, cursor.section.as_deref()),
        LineShape::Empty => cursor.section.as_deref().map_or_else(
            || section_items(schema, true),
            |section| field_items(schema, Some(section)),
        ),
    }
}

/// Section-name completion. `bracketed` wraps the insert text in `[ ]` (for an
/// empty line); otherwise just the name (the `[` is already typed).
fn section_items(schema: &SchemaIndex, bracketed: bool) -> Vec<CompletionItem> {
    schema
        .header_paths()
        .into_iter()
        .map(|name| {
            let insert = if bracketed {
                format!("[{name}]")
            } else {
                name.clone()
            };
            let doc = describe_section(schema, &name)
                .map(|(_, body)| body)
                .filter(|body| !body.is_empty())
                .map(doc_markup);
            CompletionItem {
                label: name,
                kind: Some(CompletionItemKind::MODULE),
                insert_text: Some(insert),
                documentation: doc,
                ..CompletionItem::default()
            }
        })
        .collect()
}

/// Field-name completion for a section.
fn field_items(schema: &SchemaIndex, section: Option<&str>) -> Vec<CompletionItem> {
    let Some(doc) = section.and_then(|s| schema.section(s)) else {
        return Vec::new();
    };
    doc.fields
        .iter()
        .map(|(name, field)| CompletionItem {
            label: name.clone(),
            kind: Some(CompletionItemKind::FIELD),
            insert_text: Some(format!("{name} = ")),
            detail: field.deprecated.then(|| "deprecated".to_string()),
            documentation: field.description.clone().map(doc_markup),
            ..CompletionItem::default()
        })
        .collect()
}

/// Value completion for `section.key`: the schema's `enum`, or a code-driven set
/// for the fields the schema can't enumerate (label lists, booleans).
fn value_items(schema: &SchemaIndex, section: Option<&str>, key: &str) -> Vec<CompletionItem> {
    let section = section.unwrap_or("");
    if let Some(field) = schema.section(section).and_then(|s| s.fields.get(key))
        && !field.enum_values.is_empty()
    {
        return field
            .enum_values
            .iter()
            .map(|v| value_item(v, "value", true))
            .collect();
    }
    code_values(section, key)
        .into_iter()
        .map(|(value, detail)| value_item(&value, detail, detail != "bool"))
        .collect()
}

/// Code-driven value sets for fields the JSON Schema leaves open.
fn code_values(section: &str, key: &str) -> Vec<(String, &'static str)> {
    let label_vocab = || -> Vec<(String, &'static str)> {
        let mut out: Vec<(String, &'static str)> = Vec::new();
        let mut push = |value: String, detail: &'static str| {
            if !out.iter().any(|(v, _)| *v == value) {
                out.push((value, detail));
            }
        };
        for runner in TaskRunner::all() {
            push(runner.label().to_string(), "task runner");
        }
        for pm in PackageManager::all() {
            push(pm.label().to_string(), "package manager");
        }
        for source in TaskSource::all() {
            push(source.label().to_string(), "source");
        }
        out
    };

    match (section, key) {
        ("tasks", "prefer") | ("tasks.overrides", _) => label_vocab(),
        ("task_runner", "prefer") => TaskRunner::all()
            .iter()
            .map(|r| (r.label().to_string(), "task runner"))
            .collect(),
        ("install", "pms") => PackageManager::all()
            .iter()
            .map(|pm| (pm.label().to_string(), "package manager"))
            .collect(),
        ("chain", "keep_going" | "kill_on_fail")
        | ("github", "group_output" | "group_parallel")
        | ("parallel", "grouped") => {
            vec![("true".to_string(), "bool"), ("false".to_string(), "bool")]
        }
        _ => Vec::new(),
    }
}

/// A single value completion item. `quote` wraps `insert_text` in `"..."` for
/// string-typed values, so string fields (`pm.node`, `tasks.prefer`, …) insert
/// valid TOML rather than a bare, unquoted word; the label stays unquoted.
fn value_item(value: &str, detail: &str, quote: bool) -> CompletionItem {
    let insert_text = if quote {
        format!("\"{value}\"")
    } else {
        value.to_string()
    };
    CompletionItem {
        label: value.to_string(),
        kind: Some(CompletionItemKind::VALUE),
        detail: Some(detail.to_string()),
        insert_text: Some(insert_text),
        ..CompletionItem::default()
    }
}

/// A markdown hover block with a code-fenced title and a body.
fn markdown(title: &str, body: &str) -> MarkupContent {
    let value = if body.is_empty() {
        format!("```toml\n{title}\n```")
    } else {
        format!("```toml\n{title}\n```\n\n{body}")
    };
    MarkupContent {
        kind: MarkupKind::Markdown,
        value,
    }
}

/// Wrap a description string as completion-item markdown documentation.
const fn doc_markup(value: String) -> Documentation {
    Documentation::MarkupContent(MarkupContent {
        kind: MarkupKind::Markdown,
        value,
    })
}

#[cfg(test)]
mod tests {
    use lsp_types::Position;

    use super::super::schema_index::SchemaIndex;
    use super::super::text::LineIndex;
    use super::{completion, hover};

    fn labels(items: &[lsp_types::CompletionItem]) -> Vec<&str> {
        items.iter().map(|i| i.label.as_str()).collect()
    }

    #[test]
    fn hover_describes_a_section_header() {
        let schema = SchemaIndex::build();
        let text = "[tasks]\n";
        let result = hover(&LineIndex::new(text), &schema, text, Position::new(0, 2));
        assert!(result.is_some(), "expected hover on a [tasks] header");
    }

    #[test]
    fn completion_offers_section_names_after_bracket() {
        let schema = SchemaIndex::build();
        let text = "[\n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(0, 1));
        let names = labels(&items);
        assert!(names.contains(&"tasks"), "{names:?}");
        assert!(names.contains(&"pm"), "{names:?}");
    }

    #[test]
    fn completion_offers_field_names_in_a_section() {
        let schema = SchemaIndex::build();
        let text = "[tasks]\n\n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(1, 0));
        let names = labels(&items);
        assert!(names.contains(&"prefer"), "{names:?}");
        assert!(names.contains(&"overrides"), "{names:?}");
    }

    #[test]
    fn completion_offers_label_vocab_for_tasks_prefer() {
        let schema = SchemaIndex::build();
        let text = "[tasks]\nprefer = \n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(1, 9));
        let names = labels(&items);
        assert!(names.contains(&"turbo"), "{names:?}");
        assert!(names.contains(&"bun"), "{names:?}");
        assert!(names.contains(&"package.json"), "{names:?}");
    }

    #[test]
    fn completion_offers_schema_enum_for_pm_node() {
        let schema = SchemaIndex::build();
        let text = "[pm]\nnode = \n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(1, 7));
        let names = labels(&items);
        assert!(names.contains(&"bun"), "{names:?}");
        assert!(names.contains(&"pnpm"), "{names:?}");
    }

    #[test]
    fn completion_offers_nested_section_for_tasks_overrides() {
        let schema = SchemaIndex::build();
        let text = "[\n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(0, 1));
        let names = labels(&items);
        assert!(names.contains(&"tasks.overrides"), "{names:?}");
    }

    #[test]
    fn string_value_completions_insert_quoted_text() {
        let schema = SchemaIndex::build();
        let text = "[pm]\nnode = \n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(1, 7));
        let bun = items.iter().find(|i| i.label == "bun").expect("bun item");
        assert_eq!(bun.insert_text.as_deref(), Some("\"bun\""));
    }

    #[test]
    fn bool_value_completions_stay_unquoted() {
        let schema = SchemaIndex::build();
        let text = "[chain]\nkeep_going = \n";
        let items = completion(&LineIndex::new(text), &schema, text, Position::new(1, 13));
        let names = labels(&items);
        assert!(names.contains(&"true"), "{names:?}");
        let item = items.iter().find(|i| i.label == "true").expect("true item");
        assert_eq!(item.insert_text.as_deref(), Some("true"));
    }
}