diff: Highlight scripts by shebang

eb2ec2d2ddcf78766b45e6f9683d5ef08f6e4e0b
Load grammar first-line matchers for extensionless scripts when the full
source starts with a shebang. This lets Ruby, Python, and shell scripts
highlight even when the shebang is outside the displayed patch hunk.

Assisted-by: Codex:gpt-5.5
Alexis Sellier committed ago 1 parent 7fb23a9a
crates/diff/src/bin/rustik-diff/builtins.rs +89 -2
127 127
            .filter(|syntax| syntax.matches_document(document))
128 128
        {
129 129
            registry.add_grammar(syntax.grammar()?);
130 130
        }
131 131
132 -
        Ok(BuiltinHighlighter::new(registry, THEME_NAME))
132 +
        let mut highlighter = BuiltinHighlighter::new(registry, THEME_NAME);
133 +
        for file in &document.files {
134 +
            for hunk in &file.hunks {
135 +
                for side in [rustik_diff::DiffSide::Old, rustik_diff::DiffSide::New] {
136 +
                    let source = hunk.highlight_source(side);
137 +
                    if source.head == 1
138 +
                        && let Some(head) = source.text.lines().next()
139 +
                    {
140 +
                        Self::load_head_grammars(&mut highlighter, head)?;
141 +
                    }
142 +
                }
143 +
            }
144 +
        }
145 +
        Ok(highlighter)
146 +
    }
147 +
148 +
    /// Loads grammars selected by a source file's head line.
149 +
    pub(super) fn load_head_grammars(
150 +
        highlighter: &mut BuiltinHighlighter,
151 +
        head: &str,
152 +
    ) -> Result<(), syntax::Error> {
153 +
        if !head.starts_with("#!") {
154 +
            return Ok(());
155 +
        }
156 +
        for syntax in &SYNTAXES {
157 +
            if let Some(grammar) = syntax.head_grammar(head)? {
158 +
                highlighter.ensure_grammar(grammar);
159 +
            }
160 +
        }
161 +
        Ok(())
133 162
    }
134 163
}
135 164
136 165
/// Built-in syntax source and path aliases.
137 166
struct SyntaxAsset {
171 200
    }
172 201
173 202
    /// Parses this grammar and attaches local path aliases.
174 203
    fn grammar(&self) -> Result<syntax::Grammar, syntax::Error> {
175 204
        let mut raw: syntax::RawGrammar = self.source.parse()?;
205 +
        self.compile(&mut raw)
206 +
    }
207 +
208 +
    /// Parses this grammar when its first-line pattern matches `head`.
209 +
    fn head_grammar(&self, head: &str) -> Result<Option<syntax::Grammar>, syntax::Error> {
210 +
        let mut raw: syntax::RawGrammar = self.source.parse()?;
211 +
        if raw.first_line_match.is_none() {
212 +
            return Ok(None);
213 +
        }
214 +
        let grammar = self.compile(&mut raw)?;
215 +
        Ok(grammar.matches_head(head).then_some(grammar))
216 +
    }
176 217
218 +
    /// Compiles `raw` with local path aliases and cross-grammar dependencies.
219 +
    fn compile(&self, raw: &mut syntax::RawGrammar) -> Result<syntax::Grammar, syntax::Error> {
177 220
        for file_type in self.file_types {
178 221
            if !raw
179 222
                .file_types
180 223
                .iter()
181 224
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
186 229
        let dependencies = self
187 230
            .dependencies
188 231
            .iter()
189 232
            .map(|source| source.parse())
190 233
            .collect::<Result<Vec<syntax::RawGrammar>, syntax::Error>>()?;
191 -
        syntax::Grammar::compile_with(&raw, &dependencies)
234 +
        syntax::Grammar::compile_with(raw, &dependencies)
192 235
    }
193 236
}
194 237
195 238
#[cfg(test)]
196 239
mod tests {
197 240
    use super::*;
241 +
    use rustik_diff::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest};
242 +
    use rustik_tui::Color;
198 243
199 244
    #[test]
200 245
    fn syntax_assets_match_common_source_paths() {
201 246
        for path in [
202 247
            "main.go",
217 262
                    .any(|syntax| syntax.matches_path(path.as_ref())),
218 263
                "no built-in syntax matched {path}"
219 264
            );
220 265
        }
221 266
    }
267 +
268 +
    #[test]
269 +
    fn scripting_assets_match_shebangs() {
270 +
        for (head, source) in [
271 +
            ("#!/usr/bin/env ruby3.3", syntax::syntaxes::RUBY),
272 +
            ("#!/usr/bin/env python3.11", syntax::syntaxes::PYTHON),
273 +
            ("#!/bin/sh", syntax::syntaxes::SHELL),
274 +
            ("#!/usr/bin/env -S bash -e", syntax::syntaxes::SHELL),
275 +
        ] {
276 +
            assert!(
277 +
                SYNTAXES.iter().any(|syntax| syntax.source == source
278 +
                    && syntax.head_grammar(head).unwrap().is_some()),
279 +
                "no built-in syntax matched {head}"
280 +
            );
281 +
        }
282 +
    }
283 +
284 +
    #[test]
285 +
    fn scripting_assets_highlight_extensionless_full_source_shebangs() {
286 +
        for (head, line, token) in [
287 +
            ("#!/usr/bin/env ruby", "if true", "if"),
288 +
            ("#!/usr/bin/env python3", "if True:", "if"),
289 +
            ("#!/bin/sh", "if true; then", "if"),
290 +
        ] {
291 +
            let result = highlight_extensionless_full_source(head, line);
292 +
293 +
            assert!(
294 +
                result
295 +
                    .line
296 +
                    .labels()
297 +
                    .iter()
298 +
                    .any(|label| label.content() == token
299 +
                        && label.paint.style.fg_color() != Color::Unset),
300 +
                "{:?}",
301 +
                result.line
302 +
            );
303 +
        }
304 +
    }
305 +
306 +
    fn highlight_extensionless_full_source(head: &str, line: &str) -> rustik_diff::HighlightResult {
307 +
        let patch = format!(
308 +
            "
script\n\ +0 -0
crates/diff/src/bin/rustik-diff/session.rs +5 -0
262 262
                    continue;
263 263
                };
264 264
                let Some(source) = file.highlight_source(side) else {
265 265
                    continue;
266 266
                };
267 +
                if side == DiffSide::New
268 +
                    && let Some(head) = source.text.lines().next()
269 +
                {
270 +
                    let _ = Builtins::load_head_grammars(&mut self.highlighter, head);
271 +
                }
267 272
                self.full_sources.insert((file_id, side), source);
268 273
            }
269 274
        }
270 275
    }
271 276
crates/diff/src/highlight.rs +7 -0
242 242
            registry,
243 243
            default_theme: default_theme.into(),
244 244
        }
245 245
    }
246 246
247 +
    /// Adds `grammar` to this highlighter if a grammar with the same name is absent.
248 +
    pub fn ensure_grammar(&mut self, grammar: syntax::Grammar) {
249 +
        if self.registry.grammar_by_name(&grammar.name).is_err() {
250 +
            self.registry.add_grammar(grammar);
251 +
        }
252 +
    }
253 +
247 254
    /// Highlights one request.
248 255
    pub fn highlight(&mut self, request: HighlightRequest) -> HighlightResult {
249 256
        self.highlight_group(vec![request]).remove(0)
250 257
    }
251 258
a.css +0 -0
a.rs\n", +0 -0
crates/highlight/syntaxes/python.json +1 -0
1 1
{
2 2
  "displayName": "Python",
3 +
  "firstLineMatch": "^#!.*\\bpython[0-9.]*\\b",
3 4
  "name": "python",
4 5
  "patterns": [
5 6
    {
6 7
      "include": "#statement"
7 8
    },
crates/highlight/syntaxes/ruby.json +1 -0
1 1
{
2 2
  "displayName": "Ruby",
3 +
  "firstLineMatch": "^#!.*\\bruby[0-9.]*\\b",
3 4
  "name": "ruby",
4 5
  "patterns": [
5 6
    {
6 7
      "captures": {
7 8
        "1": {
crates/highlight/syntaxes/shellscript.json +1 -0
1 1
{
2 2
  "displayName": "Shell",
3 +
  "firstLineMatch": "^#!.*\\b(bash|zsh|sh)\\b",
3 4
  "name": "shellscript",
4 5
  "patterns": [
5 6
    {
6 7
      "include": "#initial_context"
7 8
    }
crates/highlight/tests/syntaxes.rs +11 -0
26 26
    ] {
27 27
        Grammar::from_str(source).unwrap();
28 28
    }
29 29
}
30 30
31 +
#[test]
32 +
fn scripting_syntaxes_match_shebangs() {
33 +
    let ruby = Grammar::from_str(syntaxes::RUBY).unwrap();
34 +
    let python = Grammar::from_str(syntaxes::PYTHON).unwrap();
35 +
    let shell = Grammar::from_str(syntaxes::SHELL).unwrap();
36 +
37 +
    assert!(ruby.matches_head("#!/usr/bin/env ruby3.3"));
38 +
    assert!(python.matches_head("#!/usr/bin/env python3.11"));
39 +
    assert!(shell.matches_head("#!/bin/sh"));
40 +
}
41 +
31 42
#[test]
32 43
fn erb_embeds_html_and_ruby_scopes() {
33 44
    let erb: rustik_highlight::RawGrammar = syntaxes::ERB.parse().unwrap();
34 45
    let html: rustik_highlight::RawGrammar = syntaxes::HTML.parse().unwrap();
35 46
    let ruby: rustik_highlight::RawGrammar = syntaxes::RUBY.parse().unwrap();