rustik-diff 0.3.0

Pure diff viewer and Git diff pager for Rustik.
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
//! Built-in highlighting assets for diff viewers.
//!
//! This module bundles a default syntax theme and a small set of common
//! TextMate grammars, compiling them into a [`BuiltinHighlighter`] selected for
//! the files in a diff. It is gated behind the `builtins` feature so callers
//! that bring their own highlighting do not pay for the embedded assets.

use std::fs;
use std::path::{Path, PathBuf};

use rustik_highlight as syntax;

use crate::{BuiltinHighlighter, DiffDocument, DiffPalette};

/// Theme name used for built-in diff highlighting.
const THEME_NAME: &str = "rustik-catppuccin-mocha";
/// Built-in syntax theme JSON.
const THEME: &str = include_str!("themes/rustik-catppuccin-mocha.json");
/// Relative directory containing user-defined TextMate grammars.
const CUSTOM_SYNTAX_DIR: &str = "rustik/highlight/grammars";
/// Common syntax grammars loaded by the interactive pager.
const SYNTAXES: [SyntaxAsset; 20] = [
    SyntaxAsset {
        source: syntax::syntaxes::C,
        file_types: &["c", "h"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::CSS,
        file_types: &["css"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::ERB,
        file_types: &["erb", "rhtml", "html.erb"],
        dependencies: &[
            syntax::syntaxes::HTML,
            syntax::syntaxes::RUBY,
            syntax::syntaxes::CSS,
            syntax::syntaxes::JAVASCRIPT,
        ],
    },
    SyntaxAsset {
        source: syntax::syntaxes::FISH,
        file_types: &["fish"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::GO,
        file_types: &["go"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::HTML,
        file_types: &["html", "htm", "xhtml"],
        dependencies: &[syntax::syntaxes::CSS, syntax::syntaxes::JAVASCRIPT],
    },
    SyntaxAsset {
        source: syntax::syntaxes::JAVASCRIPT,
        file_types: &["js", "cjs", "mjs"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::LUA,
        file_types: &["lua"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::MAKE,
        file_types: &["makefile", "mk"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::MARKDOWN,
        file_types: &["md", "markdown", "mdown"],
        dependencies: &[
            syntax::syntaxes::YAML,
            syntax::syntaxes::HTML,
            syntax::syntaxes::CSS,
            syntax::syntaxes::JAVASCRIPT,
            syntax::syntaxes::LUA,
            syntax::syntaxes::TSX,
        ],
    },
    SyntaxAsset {
        source: syntax::syntaxes::PYTHON,
        file_types: &["py", "pyw"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::RUBY,
        file_types: &["rb", "rake", "gemspec"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::RUST,
        file_types: &["rs"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::SHELL,
        file_types: &["sh", "bash", "zsh"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::SQL,
        file_types: &["sql"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::TOML,
        file_types: &["toml"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::TYPESCRIPT,
        file_types: &["ts", "cts", "mts"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::TSX,
        file_types: &["tsx"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::XML,
        file_types: &["svg", "xml"],
        dependencies: &[],
    },
    SyntaxAsset {
        source: syntax::syntaxes::YAML,
        file_types: &["yaml", "yml"],
        dependencies: &[],
    },
];

/// Built-in highlight assets loaded for one diff document.
pub struct Builtins {
    /// Diff chrome palette derived from the built-in theme.
    pub palette: DiffPalette,
}

impl Builtins {
    /// Loads the built-in diff chrome assets.
    pub fn load() -> Result<Self, syntax::Error> {
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;

        Ok(Self {
            palette: (&raw_theme).into(),
        })
    }

    /// Loads a highlighter with grammars relevant to `document`.
    pub fn highlighter(document: &DiffDocument) -> Result<BuiltinHighlighter, syntax::Error> {
        Self::highlighter_for_paths(&Self::document_paths(document))
    }

    /// Loads a highlighter with grammars relevant to the given changed paths.
    pub(crate) fn highlighter_for_paths(
        paths: &[PathBuf],
    ) -> Result<BuiltinHighlighter, syntax::Error> {
        let raw_theme = THEME.parse::<syntax::RawTheme>()?;
        let mut registry = syntax::Registry::default();

        registry.add_theme(syntax::Theme::compile(&raw_theme));
        for syntax in SYNTAXES
            .iter()
            .filter(|syntax| paths.iter().any(|path| syntax.matches_path(path)))
        {
            registry.add_grammar(syntax.grammar()?);
        }
        for grammar in custom_grammars() {
            registry.add_grammar(grammar);
        }
        Ok(BuiltinHighlighter::new(registry, THEME_NAME))
    }

    /// Returns the old and new paths of every file in `document`.
    pub(crate) fn document_paths(document: &DiffDocument) -> Vec<PathBuf> {
        document
            .files
            .iter()
            .flat_map(|file| [&file.header.old_path, &file.header.new_path])
            .flatten()
            .cloned()
            .collect()
    }

    /// Loads grammars selected by a source file's head line.
    pub fn load_head_grammars(
        highlighter: &mut BuiltinHighlighter,
        head: &str,
    ) -> Result<(), syntax::Error> {
        if !head.starts_with("#!") {
            return Ok(());
        }
        for syntax in &SYNTAXES {
            if let Some(grammar) = syntax.head_grammar(head)? {
                highlighter.ensure_grammar(grammar);
            }
        }
        Ok(())
    }
}
/// Loads valid user-defined TextMate grammars from the configuration directory.
fn custom_grammars() -> Vec<syntax::Grammar> {
    let Some(directory) = config_dir().map(|directory| directory.join(CUSTOM_SYNTAX_DIR)) else {
        return Vec::new();
    };
    let Ok(entries) = fs::read_dir(directory) else {
        return Vec::new();
    };
    let paths = entries
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| {
            path.extension()
                .and_then(|extension| extension.to_str())
                .is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
        })
        .collect::<Vec<_>>();

    let raw = paths
        .iter()
        .filter_map(|path| fs::read_to_string(path).ok())
        .filter_map(|source| source.parse::<syntax::RawGrammar>().ok())
        .collect::<Vec<_>>();

    raw.iter()
        .filter_map(|grammar| syntax::Grammar::compile_with(grammar, &raw).ok())
        .collect()
}

/// Returns the user's configuration directory.
fn config_dir() -> Option<PathBuf> {
    std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .or_else(|| Some(PathBuf::from(std::env::var_os("HOME")?).join(".config")))
}

/// Built-in syntax source and path aliases.
struct SyntaxAsset {
    /// TextMate grammar JSON source.
    source: &'static str,
    /// File names and extensions recognized by the registry.
    file_types: &'static [&'static str],
    /// Raw grammars required by cross-grammar includes in this syntax.
    dependencies: &'static [&'static str],
}

impl SyntaxAsset {
    /// Returns whether this syntax matches a file path.
    fn matches_path(&self, path: &Path) -> bool {
        let file_name = path.file_name().and_then(|name| name.to_str());
        let extension = path.extension().and_then(|extension| extension.to_str());

        self.file_types.iter().any(|file_type| {
            file_name.is_some_and(|name| name.eq_ignore_ascii_case(file_type))
                || extension.is_some_and(|extension| extension.eq_ignore_ascii_case(file_type))
        })
    }

    /// Parses this grammar and attaches local path aliases.
    fn grammar(&self) -> Result<syntax::Grammar, syntax::Error> {
        let mut raw: syntax::RawGrammar = self.source.parse()?;
        self.compile(&mut raw)
    }

    /// Parses this grammar when its first-line pattern matches `head`.
    fn head_grammar(&self, head: &str) -> Result<Option<syntax::Grammar>, syntax::Error> {
        let mut raw: syntax::RawGrammar = self.source.parse()?;
        if raw.first_line_match.is_none() {
            return Ok(None);
        }
        let grammar = self.compile(&mut raw)?;
        Ok(grammar.matches_head(head).then_some(grammar))
    }

    /// Compiles `raw` with local path aliases and cross-grammar dependencies.
    fn compile(&self, raw: &mut syntax::RawGrammar) -> Result<syntax::Grammar, syntax::Error> {
        for file_type in self.file_types {
            if !raw
                .file_types
                .iter()
                .any(|existing| existing.eq_ignore_ascii_case(file_type))
            {
                raw.file_types.push((*file_type).to_owned());
            }
        }
        let dependencies = self
            .dependencies
            .iter()
            .map(|source| source.parse())
            .collect::<Result<Vec<syntax::RawGrammar>, syntax::Error>>()?;
        syntax::Grammar::compile_with(raw, &dependencies)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::{Decode as _, DiffSide, HighlightKey, HighlightKeyInput, HighlightRequest};
    use rustik_tui::Color;

    #[test]
    fn syntax_assets_match_common_source_paths() {
        for path in [
            "main.go",
            "app.js",
            "server.mjs",
            "Makefile",
            "rules.mk",
            "index.html.erb",
            "config.fish",
            "init.lua",
            "script.py",
            "task.rb",
            "build.sh",
            "Cargo.toml",
            "schema.sql",
            "component.tsx",
            "document.xml",
            "icon.svg",
            "page.xhtml",
            "config.yml",
        ] {
            assert!(
                SYNTAXES
                    .iter()
                    .any(|syntax| syntax.matches_path(path.as_ref())),
                "no built-in syntax matched {path}"
            );
        }
    }

    #[test]
    fn scripting_assets_match_shebangs() {
        for (head, source) in [
            ("#!/usr/bin/env ruby3.3", syntax::syntaxes::RUBY),
            ("#!/usr/bin/env python3.11", syntax::syntaxes::PYTHON),
            ("#!/bin/sh", syntax::syntaxes::SHELL),
            ("#!/usr/bin/env -S bash -e", syntax::syntaxes::SHELL),
            ("#!/usr/bin/env fish", syntax::syntaxes::FISH),
        ] {
            assert!(
                SYNTAXES.iter().any(|syntax| syntax.source == source
                    && syntax.head_grammar(head).unwrap().is_some()),
                "no built-in syntax matched {head}"
            );
        }
    }

    #[test]
    fn scripting_assets_highlight_extensionless_full_source_shebangs() {
        for (head, line, token) in [
            ("#!/usr/bin/env ruby", "if true", "if"),
            ("#!/usr/bin/env python3", "if True:", "if"),
            ("#!/bin/sh", "if true; then", "if"),
            ("#!/usr/bin/env fish", "if test -n \"$argv\"", "if"),
        ] {
            let result = highlight_extensionless_full_source(head, line);

            assert!(
                result
                    .line
                    .labels()
                    .iter()
                    .any(|label| label.content() == token
                        && label.paint.style.fg_color() != Color::Unset),
                "{:?}",
                result.line
            );
        }
    }

    fn highlight_extensionless_full_source(head: &str, line: &str) -> crate::HighlightResult {
        let patch = format!(
            "diff --git a/script b/script\n\
             index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100755\n\
             --- a/script\n\
             +++ b/script\n\
             @@ -10,1 +10,1 @@\n\
             -old\n\
             +{line}\n"
        );
        let document = DiffDocument::decode_str(&patch).unwrap();
        let file = &document.files[0];
        let source = crate::HighlightSource::new(format!("{head}\n\n\n\n\n\n\n\n\n{line}"), 1);
        let text = source.line(10).unwrap();
        let request = HighlightRequest {
            key: HighlightKey::new(HighlightKeyInput {
                file: file.id,
                side: DiffSide::New,
                source_line: 10,
                text,
                syntax: None,
                theme: "auto",
            }),
            hunk: file.hunks[0].id,
            row: file.hunks[0].lines[1].id,
            path: file.source_path(DiffSide::New),
            source,
        };
        let mut highlighter = Builtins::highlighter(&document).unwrap();

        Builtins::load_head_grammars(&mut highlighter, head).unwrap();
        highlighter.highlight(request)
    }

    #[test]
    fn added_sources_highlight_by_path() {
        for (path, line, token) in [
            ("init.lua", "local ok = true", "local"),
            ("config.fish", "if test -n \"$argv\"", "if"),
            (
                "component.tsx",
                "const view = <Button disabled />;",
                "Button",
            ),
            ("document.xml", "<item enabled=\"true\" />", "item"),
            ("icon.svg", "<circle cx=\"8\" cy=\"8\" r=\"4\" />", "circle"),
            ("page.xhtml", "<strong>hello</strong>", "strong"),
        ] {
            let result = highlight_path_source(path, line);

            assert!(
                result
                    .line
                    .labels()
                    .iter()
                    .any(|label| label.content() == token
                        && label.paint.style.fg_color() != Color::Unset),
                "{:?}",
                result.line
            );
        }
    }

    fn highlight_path_source(path: &str, line: &str) -> crate::HighlightResult {
        let patch = format!(
            "diff --git a/{path} b/{path}\n\
             index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644\n\
             --- a/{path}\n\
             +++ b/{path}\n\
             @@ -1,1 +1,1 @@\n\
             -old\n\
             +{line}\n"
        );
        let document = DiffDocument::decode_str(&patch).unwrap();
        let file = &document.files[0];
        let source = crate::HighlightSource::new(line.to_owned(), 1);
        let text = source.line(1).unwrap();
        let request = HighlightRequest {
            key: HighlightKey::new(HighlightKeyInput {
                file: file.id,
                side: DiffSide::New,
                source_line: 1,
                text,
                syntax: None,
                theme: "auto",
            }),
            hunk: file.hunks[0].id,
            row: file.hunks[0].lines[1].id,
            path: file.source_path(DiffSide::New),
            source,
        };
        let mut highlighter = Builtins::highlighter(&document).unwrap();

        highlighter.highlight(request)
    }
}