crates/diff/src/builtins.rs 13.4 KiB raw
1
//! Built-in highlighting assets for diff viewers.
2
//!
3
//! This module bundles a default syntax theme and a small set of common
4
//! TextMate grammars, compiling them into a [`BuiltinHighlighter`] selected for
5
//! the files in a diff. It is gated behind the `builtins` feature so callers
6
//! that bring their own highlighting do not pay for the embedded assets.
7
8
use std::fs;
9
use std::path::{Path, PathBuf};
10
11
use rustik_highlight as syntax;
12
13
use crate::{BuiltinHighlighter, DiffDocument, DiffPalette};
14
15
/// Theme name used for built-in diff highlighting.
16
const THEME_NAME: &str = "rustik-catppuccin-mocha";
17
/// Built-in syntax theme JSON.
18
const THEME: &str = include_str!("themes/rustik-catppuccin-mocha.json");
19
/// Relative directory containing user-defined TextMate grammars.
20
const CUSTOM_SYNTAX_DIR: &str = "rustik/highlight/grammars";
21
/// Common syntax grammars loaded by the interactive pager.
22
const SYNTAXES: [SyntaxAsset; 22] = [
23
    SyntaxAsset {
24
        source: syntax::syntaxes::C,
25
        file_types: &["c", "h"],
26
        dependencies: &[],
27
    },
28
    SyntaxAsset {
29
        source: syntax::syntaxes::CSS,
30
        file_types: &["css"],
31
        dependencies: &[],
32
    },
33
    SyntaxAsset {
34
        source: syntax::syntaxes::ERB,
35
        file_types: &["erb", "rhtml", "html.erb"],
36
        dependencies: &[
37
            syntax::syntaxes::HTML,
38
            syntax::syntaxes::RUBY,
39
            syntax::syntaxes::CSS,
40
            syntax::syntaxes::JAVASCRIPT,
41
        ],
42
    },
43
    SyntaxAsset {
44
        source: syntax::syntaxes::FISH,
45
        file_types: &["fish"],
46
        dependencies: &[],
47
    },
48
    SyntaxAsset {
49
        source: syntax::syntaxes::GO,
50
        file_types: &["go"],
51
        dependencies: &[],
52
    },
53
    SyntaxAsset {
54
        source: syntax::syntaxes::HTML,
55
        file_types: &["html", "htm", "xhtml"],
56
        dependencies: &[syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT],
57
    },
58
    SyntaxAsset {
59
        source: syntax::syntaxes::JAVASCRIPT,
60
        file_types: &["js", "cjs", "mjs"],
61
        dependencies: &[],
62
    },
63
    SyntaxAsset {
64
        source: syntax::syntaxes::LUA,
65
        file_types: &["lua"],
66
        dependencies: &[],
67
    },
68
    SyntaxAsset {
69
        source: syntax::syntaxes::MAKE,
70
        file_types: &["makefile", "mk"],
71
        dependencies: &[],
72
    },
73
    SyntaxAsset {
74
        source: syntax::syntaxes::MARKDOWN,
75
        file_types: &["md", "markdown", "mdown"],
76
        dependencies: &[
77
            syntax::syntaxes::YAML,
78
            syntax::syntaxes::HTML,
79
            syntax::syntaxes::CSS,
80
            syntax::syntaxes::JAVASCRIPT,
81
            syntax::syntaxes::LUA,
82
            syntax::syntaxes::TSX,
83
        ],
84
    },
85
    SyntaxAsset {
86
        source: syntax::syntaxes::PYTHON,
87
        file_types: &["py", "pyw"],
88
        dependencies: &[],
89
    },
90
    SyntaxAsset {
91
        source: syntax::syntaxes::RADIANCE,
92
        file_types: &["rad"],
93
        dependencies: &[],
94
    },
95
    SyntaxAsset {
96
        source: syntax::syntaxes::RIL,
97
        file_types: &["ril"],
98
        dependencies: &[],
99
    },
100
    SyntaxAsset {
101
        source: syntax::syntaxes::RUBY,
102
        file_types: &["rb", "rake", "gemspec"],
103
        dependencies: &[],
104
    },
105
    SyntaxAsset {
106
        source: syntax::syntaxes::RUST,
107
        file_types: &["rs"],
108
        dependencies: &[],
109
    },
110
    SyntaxAsset {
111
        source: syntax::syntaxes::SHELL,
112
        file_types: &["sh", "bash", "zsh"],
113
        dependencies: &[],
114
    },
115
    SyntaxAsset {
116
        source: syntax::syntaxes::SQL,
117
        file_types: &["sql"],
118
        dependencies: &[],
119
    },
120
    SyntaxAsset {
121
        source: syntax::syntaxes::TOML,
122
        file_types: &["toml"],
123
        dependencies: &[],
124
    },
125
    SyntaxAsset {
126
        source: syntax::syntaxes::TYPESCRIPT,
127
        file_types: &["ts", "cts", "mts"],
128
        dependencies: &[],
129
    },
130
    SyntaxAsset {
131
        source: syntax::syntaxes::TSX,
132
        file_types: &["tsx"],
133
        dependencies: &[],
134
    },
135
    SyntaxAsset {
136
        source: syntax::syntaxes::XML,
137
        file_types: &["svg", "xml"],
138
        dependencies: &[],
139
    },
140
    SyntaxAsset {
141
        source: syntax::syntaxes::YAML,
142
        file_types: &["yaml", "yml"],
143
        dependencies: &[],
144
    },
145
];
146
147
/// Built-in highlight assets loaded for one diff document.
148
pub struct Builtins {
149
    /// Diff chrome palette derived from the built-in theme.
150
    pub palette: DiffPalette,
151
}
152
153
impl Builtins {
154
    /// Loads the built-in diff chrome assets.
155
    pub fn load() -> Result<Self, syntax::Error> {
156
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
157
158
        Ok(Self {
159
            palette: (&raw_theme).into(),
160
        })
161
    }
162
163
    /// Loads a highlighter with grammars relevant to `document`.
164
    pub fn highlighter(document: &DiffDocument) -> Result<BuiltinHighlighter, syntax::Error> {
165
        Self::highlighter_for_paths(&Self::document_paths(document))
166
    }
167
168
    /// Loads a highlighter with grammars relevant to the given changed paths.
169
    pub(crate) fn highlighter_for_paths(
170
        paths: &[PathBuf],
171
    ) -> Result<BuiltinHighlighter, syntax::Error> {
172
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
173
        let mut registry = syntax::Registry::default();
174
175
        registry.add_theme(syntax::Theme::compile(&raw_theme));
176
        for syntax in SYNTAXES
177
            .iter()
178
            .filter(|syntax| paths.iter().any(|path| syntax.matches_path(path)))
179
        {
180
            registry.add_grammar(syntax.grammar()?);
181
        }
182
        for grammar in custom_grammars() {
183
            registry.add_grammar(grammar);
184
        }
185
        Ok(BuiltinHighlighter::new(registry, THEME_NAME))
186
    }
187
188
    /// Returns the old and new paths of every file in `document`.
189
    pub(crate) fn document_paths(document: &DiffDocument) -> Vec<PathBuf> {
190
        document
191
            .files
192
            .iter()
193
            .flat_map(|file| [&file.header.old_path, &file.header.new_path])
194
            .flatten()
195
            .cloned()
196
            .collect()
197
    }
198
199
    /// Loads grammars selected by a source file's head line.
200
    pub fn load_head_grammars(
201
        highlighter: &mut BuiltinHighlighter,
202
        head: &str,
203
    ) -> Result<(), syntax::Error> {
204
        if !head.starts_with("#!") {
205
            return Ok(());
206
        }
207
        for syntax in &SYNTAXES {
208
            if let Some(grammar) = syntax.head_grammar(head)? {
209
                highlighter.ensure_grammar(grammar);
210
            }
211
        }
212
        Ok(())
213
    }
214
}
215
216
/// Loads valid user-defined TextMate grammars from the configuration directory.
217
fn custom_grammars() -> Vec<syntax::Grammar> {
218
    let Some(directory) = config_dir().map(|directory| directory.join(CUSTOM_SYNTAX_DIR)) else {
219
        return Vec::new();
220
    };
221
    let Ok(entries) = fs::read_dir(directory) else {
222
        return Vec::new();
223
    };
224
    let paths = entries
225
        .flatten()
226
        .map(|entry| entry.path())
227
        .filter(|path| {
228
            path.extension()
229
                .and_then(|extension| extension.to_str())
230
                .is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
231
        })
232
        .collect::<Vec<_>>();
233
234
    let raw = paths
235
        .iter()
236
        .filter_map(|path| fs::read_to_string(path).ok())
237
        .filter_map(|source| source.parse::<syntax::RawGrammar>().ok())
238
        .collect::<Vec<_>>();
239
240
    raw.iter()
241
        .filter_map(|grammar| syntax::Grammar::compile_with(grammar, &raw).ok())
242
        .collect()
243
}
244
245
/// Returns the user's configuration directory.
246
fn config_dir() -> Option<PathBuf> {
247
    std::env::var_os("XDG_CONFIG_HOME")
248
        .map(PathBuf::from)
249
        .or_else(|| Some(PathBuf::from(std::env::var_os("HOME")?).join(".config")))
250
}
251
252
/// Built-in syntax source and path aliases.
253
struct SyntaxAsset {
254
    /// TextMate grammar JSON source.
255
    source: &'static str,
256
    /// File names and extensions recognized by the registry.
257
    file_types: &'static [&'static str],
258
    /// Raw grammars required by cross-grammar includes in this syntax.
259
    dependencies: &'static [&'static str],
260
}
261
262
impl SyntaxAsset {
263
    /// Returns whether this syntax matches a file path.
264
    fn matches_path(&self, path: &Path) -> bool {
265
        let file_name = path.file_name().and_then(|name| name.to_str());
266
        let extension = path.extension().and_then(|extension| extension.to_str());
267
268
        self.file_types.iter().any(|file_type| {
269
            file_name.is_some_and(|name| name.eq_ignore_ascii_case(file_type))
270
                || extension.is_some_and(|extension| extension.eq_ignore_ascii_case(file_type))
271
        })
272
    }
273
274
    /// Parses this grammar and attaches local path aliases.
275
    fn grammar(&self) -> Result<syntax::Grammar, syntax::Error> {
276
        let mut raw: syntax::RawGrammar = self.source.parse()?;
277
        self.compile(&mut raw)
278
    }
279
280
    /// Parses this grammar when its first-line pattern matches `head`.
281
    fn head_grammar(&self, head: &str) -> Result<Option<syntax::Grammar>, syntax::Error> {
282
        let mut raw: syntax::RawGrammar = self.source.parse()?;
283
        if raw.first_line_match.is_none() {
284
            return Ok(None);
285
        }
286
        let grammar = self.compile(&mut raw)?;
287
        Ok(grammar.matches_head(head).then_some(grammar))
288
    }
289
290
    /// Compiles `raw` with local path aliases and cross-grammar dependencies.
291
    fn compile(&self, raw: &mut syntax::RawGrammar) -> Result<syntax::Grammar, syntax::Error> {
292
        for file_type in self.file_types {
293
            if !raw
294
                .file_types
295
                .iter()
296
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
297
            {
298
                raw.file_types.push((*file_type).to_owned());
299
            }
300
        }
301
        let dependencies = self
302
            .dependencies
303
            .iter()
304
            .map(|source| source.parse())
305
            .collect::<Result<Vec<syntax::RawGrammar>, syntax::Error>>()?;
306
        syntax::Grammar::compile_with(raw, &dependencies)
307
    }
308
}
309
310
#[cfg(test)]
311
#[allow(clippy::unwrap_used)]
312
mod tests {
313
    use super::*;
314
    use crate::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest};
315
    use rustik_tui::Color;
316
317
    #[test]
318
    fn syntax_assets_match_common_source_paths() {
319
        for path in [
320
            "main.go",
321
            "app.js",
322
            "server.mjs",
323
            "Makefile",
324
            "rules.mk",
325
            "index.html.erb",
326
            "config.fish",
327
            "init.lua",
328
            "script.py",
329
            "main.rad",
330
            "main.ril",
331
            "task.rb",
332
            "build.sh",
333
            "Cargo.toml",
334
            "schema.sql",
335
            "component.tsx",
336
            "document.xml",
337
            "icon.svg",
338
            "page.xhtml",
339
            "config.yml",
340
        ] {
341
            assert!(
342
                SYNTAXES
343
                    .iter()
344
                    .any(|syntax| syntax.matches_path(path.as_ref())),
345
                "no built-in syntax matched {path}"
346
            );
347
        }
348
    }
349
350
    #[test]
351
    fn scripting_assets_match_shebangs() {
352
        for (head, source) in [
353
            ("#!/usr/bin/env ruby3.3", syntax::syntaxes::RUBY),
354
            ("#!/usr/bin/env python3.11", syntax::syntaxes::PYTHON),
355
            ("#!/bin/sh", syntax::syntaxes::SHELL),
356
            ("#!/usr/bin/env -S bash -e", syntax::syntaxes::SHELL),
357
            ("#!/usr/bin/env fish", syntax::syntaxes::FISH),
358
        ] {
359
            assert!(
360
                SYNTAXES.iter().any(|syntax| syntax.source == source
361
                    && syntax.head_grammar(head).unwrap().is_some()),
362
                "no built-in syntax matched {head}"
363
            );
364
        }
365
    }
366
367
    #[test]
368
    fn scripting_assets_highlight_extensionless_full_source_shebangs() {
369
        for (head, line, token) in [
370
            ("#!/usr/bin/env ruby", "if true", "if"),
371
            ("#!/usr/bin/env python3", "if True:", "if"),
372
            ("#!/bin/sh", "if true; then", "if"),
373
            ("#!/usr/bin/env fish", "if test -n \"$argv\"", "if"),
374
        ] {
375
            let result = highlight_extensionless_full_source(head, line);
376
377
            assert!(
378
                result
379
                    .line
380
                    .labels()
381
                    .iter()
382
                    .any(|label| label.content() == token
383
                        && label.paint.style.fg_color() != Color::Unset),
384
                "{:?}",
385
                result.line
386
            );
387
        }
388
    }
389
390
    fn highlight_extensionless_full_source(head: &str, line: &str) -> crate::HighlightResult {
391
        let patch = format!(
392
            "diff --git a/script b/script\n\
393
             index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100755\n\
394
             --- a/script\n\
395
             +++ b/script\n\
396
             @@ -10,1 +10,1 @@\n\
397
             -old\n\
398
             +{line}\n"
399
        );
400
        let document = DiffDocument::decode_str(&patch).unwrap();
401
        let file = &document.files[0];
402
        let source = crate::HighlightSource::new(format!("{head}\n\n\n\n\n\n\n\n\n{line}"), 1);
403
        let text = source.line(10).unwrap();
404
        let request = HighlightRequest {
405
            key: HighlightKey::new(HighlightKeyInput {
406
                file: file.id,
407
                side: DiffSide::New,
408
                source_line: 10,
409
                text,
410
                syntax: None,
411
                theme: "auto",
412
            }),
413
            hunk: file.hunks[0].id,
414
            row: file.hunks[0].lines[1].id,
415
            path: file.source_path(DiffSide::New),
416
            source,
417
        };
418
        let mut highlighter = Builtins::highlighter(&document).unwrap();
419
420
        Builtins::load_head_grammars(&mut highlighter, head).unwrap();
421
        highlighter.highlight(request)
422
    }
423
}