octorus 0.6.2

A TUI tool for GitHub PR review, designed for Helix editor users
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
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
//! Language injection support for tree-sitter.
//!
//! This module handles extracting and processing language injections
//! from tree-sitter queries (injections.scm).

use std::ops::Range;
use tree_sitter::{Language, Query, QueryCursor, StreamingIterator, Tree};

/// Represents a range of text that should be parsed with a different language.
#[derive(Debug, Clone)]
pub struct InjectionRange {
    /// Byte range in the source text
    pub range: Range<usize>,
    /// The language to use for this range
    pub language: String,
    /// The kind of the parent node containing this injection (e.g., "script_element", "style_element")
    pub parent_node_kind: Option<String>,
}

/// Extract injection ranges from a tree using an injection query.
///
/// Returns a list of ranges and their associated languages.
pub fn extract_injections(
    tree: &Tree,
    source: &[u8],
    language: &Language,
    injection_query: &str,
) -> Vec<InjectionRange> {
    let query = match Query::new(language, injection_query) {
        Ok(q) => q,
        Err(_) => return Vec::new(),
    };

    let mut cursor = QueryCursor::new();
    let mut injections = Vec::new();

    let mut matches = cursor.matches(&query, tree.root_node(), source);

    while let Some(match_) = matches.next() {
        let mut content_range: Option<Range<usize>> = None;
        let mut content_node: Option<tree_sitter::Node> = None;
        let mut lang: Option<String> = None;

        for capture in match_.captures {
            let capture_name = &query.capture_names()[capture.index as usize];

            if *capture_name == "injection.content" {
                content_range = Some(capture.node.byte_range());
                content_node = Some(capture.node);
            } else if *capture_name == "injection.language" {
                if let Ok(text) = capture.node.utf8_text(source) {
                    lang = Some(text.to_string());
                }
            }
        }

        if lang.is_none() {
            lang = get_injection_language_from_pattern(&query, match_.pattern_index);
        }

        let parent_node_kind = content_node.and_then(|node| {
            let mut current = node.parent();
            while let Some(parent) = current {
                let kind = parent.kind();
                if kind.ends_with("_element") || kind == "script" || kind == "style" {
                    return Some(kind.to_string());
                }
                current = parent.parent();
            }
            None
        });

        if let (Some(range), Some(language)) = (content_range, lang) {
            if !range.is_empty() {
                injections.push(InjectionRange {
                    range,
                    language,
                    parent_node_kind,
                });
            }
        }
    }

    // Deduplicate injections for the same range, preferring more specific languages
    // (e.g., TypeScript/TSX/JSX over JavaScript)
    deduplicate_injections(injections)
}

/// Deduplicate injections that cover the same range.
///
/// When multiple injections match the same byte range (e.g., a `<script lang="ts">` block
/// matching both the generic JavaScript rule and the TypeScript-specific rule), this function
/// keeps only the most specific language.
///
/// Language specificity order (most specific first):
/// - tsx, jsx (explicit JSX variants)
/// - typescript (explicit TS)
/// - All other languages are kept as-is
/// - javascript (least specific, used as fallback)
fn deduplicate_injections(mut injections: Vec<InjectionRange>) -> Vec<InjectionRange> {
    use std::collections::HashMap;

    let mut range_map: HashMap<(usize, usize), Vec<InjectionRange>> = HashMap::new();
    for inj in injections.drain(..) {
        let key = (inj.range.start, inj.range.end);
        range_map.entry(key).or_default().push(inj);
    }

    let mut result = Vec::new();
    for (_, mut group) in range_map {
        if group.len() == 1 {
            result.push(group.pop().unwrap());
        } else {
            group.sort_by_key(|inj| language_specificity(&inj.language));
            result.push(group.remove(0));
        }
    }

    result.sort_by_key(|inj| inj.range.start);
    result
}

/// Returns a specificity score for a language (lower is more specific).
fn language_specificity(lang: &str) -> u32 {
    match lang.to_lowercase().as_str() {
        // Most specific: explicit JSX/TSX variants
        "tsx" | "jsx" => 0,
        // TypeScript is more specific than JavaScript
        "ts" | "typescript" => 1,
        // JavaScript is the fallback
        "js" | "javascript" => 100,
        // Other languages get middle priority
        _ => 50,
    }
}

/// Try to extract the injection language from query pattern settings.
fn get_injection_language_from_pattern(query: &Query, pattern_index: usize) -> Option<String> {
    for setting in query.property_settings(pattern_index) {
        if setting.key.as_ref() == "injection.language" {
            if let Some(value) = &setting.value {
                return Some(value.to_string());
            }
        }
    }

    None
}

/// Map common language identifiers to our SupportedLanguage names.
pub fn normalize_language_name(name: &str) -> &str {
    match name.to_lowercase().as_str() {
        "ts" | "typescript" => "typescript",
        "tsx" => "tsx",
        "js" | "javascript" => "javascript",
        "jsx" => "jsx",
        "css" | "scss" | "postcss" | "less" | "stylus" => "css",
        "html" => "html",
        "json" => "json",
        "rust" | "rs" => "rust",
        "python" | "py" => "python",
        "go" | "golang" => "go",
        "lua" => "lua",
        "bash" | "sh" | "shell" => "bash",
        "php" => "php",
        "swift" => "swift",
        "haskell" | "hs" => "haskell",
        "moonbit" | "mbt" => "moonbit",
        "markdown_inline" | "markdown-inline" => "markdown_inline",
        _ => name,
    }
}

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

    #[test]
    fn test_normalize_language_name() {
        assert_eq!(normalize_language_name("ts"), "typescript");
        assert_eq!(normalize_language_name("typescript"), "typescript");
        assert_eq!(normalize_language_name("Typescript"), "typescript");
        assert_eq!(normalize_language_name("js"), "javascript");
        assert_eq!(normalize_language_name("css"), "css");
        assert_eq!(normalize_language_name("scss"), "css");
    }

    #[test]
    fn test_normalize_language_name_markdown_inline() {
        assert_eq!(
            normalize_language_name("markdown_inline"),
            "markdown_inline"
        );
        assert_eq!(
            normalize_language_name("markdown-inline"),
            "markdown_inline"
        );
    }

    #[test]
    fn test_extract_injections_markdown_inline() {
        // Parse a simple Markdown file
        let code = "# Heading\n\nSome **bold** text.\n";

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_md::LANGUAGE.into();
        parser.set_language(&language).unwrap();

        let tree = parser.parse(code, None).unwrap();
        let injection_query = tree_sitter_md::INJECTION_QUERY_BLOCK;

        let injections = extract_injections(&tree, code.as_bytes(), &language, injection_query);

        // Markdown block grammar injects markdown_inline for inline content
        let inline_injections: Vec<_> = injections
            .iter()
            .filter(|inj| normalize_language_name(&inj.language) == "markdown_inline")
            .collect();
        assert!(
            !inline_injections.is_empty(),
            "Markdown should have inline injections"
        );
    }

    #[test]
    fn test_extract_injections_markdown_code_fence() {
        // Parse Markdown with a code fence
        let code = "# Title\n\n```rust\nfn main() {}\n```\n";

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_md::LANGUAGE.into();
        parser.set_language(&language).unwrap();

        let tree = parser.parse(code, None).unwrap();
        let injection_query = tree_sitter_md::INJECTION_QUERY_BLOCK;

        let injections = extract_injections(&tree, code.as_bytes(), &language, injection_query);

        // Should have a "rust" injection for the code fence
        let rust_injections: Vec<_> = injections
            .iter()
            .filter(|inj| inj.language == "rust")
            .collect();
        assert!(
            !rust_injections.is_empty(),
            "Markdown code fence should produce a 'rust' injection"
        );
    }

    #[test]
    fn test_extract_injections_svelte_script() {
        // Parse a simple Svelte file with script content
        let code = r#"<script lang="ts">
    const x = 1;
</script>

<div>Hello</div>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_svelte_ng::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        // Use Svelte's injection query
        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_svelte_ng::INJECTIONS_QUERY,
        );

        // Should find at least one injection (the script content)
        assert!(
            !injections.is_empty(),
            "Should find injections in Svelte code"
        );

        // Find the TypeScript injection
        let ts_injection = injections
            .iter()
            .find(|i| i.language == "typescript" || i.language == "ts");
        assert!(
            ts_injection.is_some(),
            "Should find TypeScript injection, found: {:?}",
            injections
        );

        // Verify the range contains the script content
        if let Some(inj) = ts_injection {
            let content = &code[inj.range.clone()];
            assert!(
                content.contains("const x = 1"),
                "Injection should contain script content, got: {}",
                content
            );
        }
    }

    #[test]
    fn test_extract_injections_svelte_style() {
        let code = r#"<style>
    .foo { color: red; }
</style>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_svelte_ng::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_svelte_ng::INJECTIONS_QUERY,
        );

        // Should find CSS injection
        let css_injection = injections
            .iter()
            .find(|i| i.language == "css" || i.language == "scss");

        // Note: This might fail if the injection query uses a different language name
        // or if raw_text without lang attr defaults to something else
        if let Some(inj) = css_injection {
            let content = &code[inj.range.clone()];
            assert!(
                content.contains(".foo"),
                "Injection should contain style content"
            );
        }
    }

    #[test]
    fn test_extract_injections_empty_query() {
        let code = "<div>Hello</div>";

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_svelte_ng::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        // Empty query should return empty results
        let injections = extract_injections(&tree, code.as_bytes(), &language, "");
        assert!(injections.is_empty());
    }

    #[test]
    fn test_extract_injections_invalid_query() {
        let code = "<div>Hello</div>";

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_svelte_ng::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        // Invalid query should return empty results (not panic)
        let injections = extract_injections(&tree, code.as_bytes(), &language, "((invalid syntax");
        assert!(injections.is_empty());
    }

    #[test]
    fn test_extract_injections_vue_script() {
        let code = r#"<script lang="ts">
    const x = 1;
</script>

<template>
    <div>Hello</div>
</template>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // Should find TypeScript injection
        assert!(!injections.is_empty(), "Should find injections in Vue code");

        let ts_injection = injections
            .iter()
            .find(|i| i.language == "typescript" || i.language == "ts");
        assert!(
            ts_injection.is_some(),
            "Should find TypeScript injection, found: {:?}",
            injections
        );

        if let Some(inj) = ts_injection {
            let content = std::str::from_utf8(&code.as_bytes()[inj.range.clone()]).unwrap();
            assert!(
                content.contains("const x = 1"),
                "Injection should contain script content, got: {}",
                content
            );
        }
    }

    #[test]
    fn test_extract_injections_vue_style() {
        let code = r#"<style>
    .foo { color: red; }
</style>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // Should find CSS injection
        let css_injection = injections.iter().find(|i| i.language == "css");

        assert!(
            css_injection.is_some(),
            "Should find CSS injection, found: {:?}",
            injections
        );

        if let Some(inj) = css_injection {
            let content = std::str::from_utf8(&code.as_bytes()[inj.range.clone()]).unwrap();
            assert!(
                content.contains(".foo"),
                "Injection should contain style content, got: {}",
                content
            );
        }
    }

    #[test]
    fn test_extract_injections_vue_interpolation() {
        let code = r#"<template>
    <div>{{ message }}</div>
</template>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // Should find JavaScript injection for interpolation
        let js_injection = injections.iter().find(|i| i.language == "javascript");

        assert!(
            js_injection.is_some(),
            "Should find JavaScript injection for interpolation, found: {:?}",
            injections
        );

        if let Some(inj) = js_injection {
            let content = std::str::from_utf8(&code.as_bytes()[inj.range.clone()]).unwrap();
            assert!(
                content.contains("message"),
                "Injection should contain interpolation content, got: {}",
                content
            );
        }
    }

    #[test]
    fn test_deduplicate_injections_prefers_typescript_over_javascript() {
        // Vue <script lang="ts"> matches both the default JS rule and the TS-specific rule.
        // The deduplication logic should keep only TypeScript.
        let code = r#"<script lang="ts">
    const x: number = 1;
</script>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // Should find exactly one injection for the script content
        // (not both JavaScript and TypeScript)
        let script_injections: Vec<_> = injections
            .iter()
            .filter(|i| i.language == "typescript" || i.language == "javascript")
            .collect();

        assert_eq!(
            script_injections.len(),
            1,
            "Should have exactly one script injection after deduplication, got: {:?}",
            script_injections
        );

        assert_eq!(
            script_injections[0].language, "typescript",
            "Should prefer TypeScript over JavaScript"
        );
    }

    #[test]
    fn test_deduplicate_injections_prefers_tsx_over_typescript() {
        let code = r#"<script lang="tsx">
    const x = <div>Hello</div>;
</script>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // TSX should be preferred over both TypeScript and JavaScript
        let script_injections: Vec<_> = injections
            .iter()
            .filter(|i| {
                i.language == "tsx" || i.language == "typescript" || i.language == "javascript"
            })
            .collect();

        assert_eq!(
            script_injections.len(),
            1,
            "Should have exactly one script injection after deduplication, got: {:?}",
            script_injections
        );

        assert_eq!(
            script_injections[0].language, "tsx",
            "Should prefer TSX over TypeScript and JavaScript"
        );
    }

    #[test]
    fn test_language_specificity() {
        // More specific languages should have lower scores
        assert!(language_specificity("tsx") < language_specificity("typescript"));
        assert!(language_specificity("jsx") < language_specificity("typescript"));
        assert!(language_specificity("typescript") < language_specificity("javascript"));
        assert!(language_specificity("ts") < language_specificity("js"));
        // Other languages have middle priority
        assert!(language_specificity("css") < language_specificity("javascript"));
        assert!(language_specificity("css") > language_specificity("typescript"));
    }
}

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

    #[test]
    fn test_extract_injections_primed_vue_script() {
        // Simulate primed source: wrapping plain script content in <script lang="ts">
        let code = r#"<script lang="ts">
import { ref } from 'vue'
const count = ref(0)
</script>
"#;

        let mut parser = tree_sitter::Parser::new();
        let language: Language = tree_sitter_vue3::LANGUAGE.into();
        parser.set_language(&language).unwrap();
        let tree = parser.parse(code, None).unwrap();

        let injections = extract_injections(
            &tree,
            code.as_bytes(),
            &language,
            tree_sitter_vue3::INJECTIONS_QUERY,
        );

        // Should find TypeScript injection
        assert!(
            !injections.is_empty(),
            "Should find injections in primed Vue code"
        );

        let ts_injection = injections
            .iter()
            .find(|i| i.language == "typescript" || i.language == "ts");
        assert!(
            ts_injection.is_some(),
            "Should find TypeScript injection, found: {:?}",
            injections
        );

        let inj = ts_injection.unwrap();
        let content = std::str::from_utf8(&code.as_bytes()[inj.range.clone()]).unwrap();
        assert!(
            content.contains("import"),
            "Injection should contain import"
        );
        assert!(
            content.contains("const count"),
            "Injection should contain const"
        );
    }
}