summaryrefslogtreecommitdiffstats
path: root/src/handlers/blame.rs
blob: ed645c6d604cb27763073763361a5243c05c0eca (plain)
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
use chrono::{DateTime, FixedOffset};
use lazy_static::lazy_static;
use regex::Regex;
use std::borrow::Cow;

use crate::ansi::measure_text_width;
use crate::color;
use crate::config;
use crate::config::delta_unreachable;
use crate::delta::{self, State, StateMachine};
use crate::format::{self, Placeholder};
use crate::paint::BgShouldFill;
use crate::paint::StyleSectionSpecifier;
use crate::style::Style;
use crate::utils;

impl<'a> StateMachine<'a> {
    /// If this is a line of git blame output then render it accordingly. If
    /// this is the first blame line, then set the syntax-highlighter language
    /// according to delta.default-language.
    pub fn handle_blame_line(&mut self) -> std::io::Result<bool> {
        // TODO: It should be possible to eliminate some of the .clone()s and
        // .to_owned()s.
        let mut handled_line = false;
        self.painter.emit()?;
        let (previous_commit, mut repeat_blame_line, try_parse) = match &self.state {
            State::Blame(commit, repeat_blame_line) => {
                (Some(commit.as_str()), repeat_blame_line.clone(), true)
            }
            State::Unknown => (None, None, true),
            _ => (None, None, false),
        };
        if try_parse {
            if let Some(blame) =
                parse_git_blame_line(&self.line, &self.config.blame_timestamp_format)
            {
                let is_repeat = previous_commit == Some(blame.commit);
                let color = self.get_color(blame.commit, previous_commit, is_repeat);
                let mut style = Style::from_colors(None, color::parse_color(&color, true));
                // TODO: This will often be pointlessly updating a key with the
                // value it already has. It might be nicer to do this (and
                // compute the style) in get_color(), but as things stand the
                // borrow checker won't permit that.
                self.blame_commit_colors
                    .insert(blame.commit.to_owned(), color);

                style.is_syntax_highlighted = true;

                // Construct commit metadata, paint, and emit
                let format_data = format::parse_line_number_format(
                    &self.config.blame_format,
                    &*BLAME_PLACEHOLDER_REGEX,
                    false,
                );
                let blame_line = match (is_repeat, &repeat_blame_line) {
                    (false, _) => Cow::from(format_blame_metadata(
                        &format_data,
                        &blame,
                        false,
                        self.config,
                    )),
                    (true, None) => {
                        repeat_blame_line = Some(format_blame_metadata(
                            &format_data,
                            &blame,
                            true,
                            self.config,
                        ));
                        Cow::from(repeat_blame_line.as_ref().unwrap())
                    }
                    (true, Some(repeat_blame_line)) => Cow::from(repeat_blame_line),
                };
                write!(self.painter.writer, "{}", style.paint(blame_line))?;

                // Emit syntax-highlighted code
                if matches!(self.state, State::Unknown) {
                    if let Some(lang) = utils::process::git_blame_filename_extension()
                        .as_ref()
                        .or_else(|| self.config.default_language.as_ref())
                    {
                        self.painter.set_syntax(Some(lang));
                        self.painter.set_highlighter();
                    }
                }
                self.state = State::Blame(blame.commit.to_owned(), repeat_blame_line.to_owned());
                self.painter.syntax_highlight_and_paint_line(
                    &format!("{}\n", blame.code),
                    StyleSectionSpecifier::Style(style),
                    self.state.clone(),
                    BgShouldFill::default(),
                );
                handled_line = true
            }
        }
        Ok(handled_line)
    }

    fn get_color(
        &self,
        this_commit: &str,
        previous_commit: Option<&str>,
        is_repeat: bool,
    ) -> String {
        // Determine color for this line
        let previous_commit_color = match previous_commit {
            Some(previous_commit) => self.blame_commit_colors.get(previous_commit),
            None => None,
        };

        match (
            self.blame_commit_colors.get(this_commit),
            previous_commit_color,
            is_repeat,
        ) {
            (Some(commit_color), Some(previous_commit_color), true) => {
                debug_assert!(commit_color == previous_commit_color);
                // Repeated commit: assign same color
                commit_color.to_owned()
            }
            (None, Some(previous_commit_color), false) => {
                // The commit has no color: assign the next color that differs
                // from previous commit.
                self.get_next_color(Some(previous_commit_color))
            }
            (None, None, false) => {
                // The commit has no color, and there is no previous commit:
                // Just assign the next color. is_repeat is necessarily false.
                self.get_next_color(None)
            }
            (Some(commit_color), Some(previous_commit_color), false) => {
                if commit_color != previous_commit_color {
                    // Consecutive commits differ without a collision
                    commit_color.to_owned()
                } else {
                    // Consecutive commits differ; prevent color collision
                    self.get_next_color(Some(commit_color))
                }
            }
            (None, _, true) => {
                delta_unreachable("is_repeat cannot be true when commit has no color.")
            }
            (Some(_), None, _) => {
                delta_unreachable("There must be a previous commit if the commit has a color.")
            }
        }
    }

    fn get_next_color(&self, other_than_color: Option<&str>) -> String {
        let n_commits = self.blame_commit_colors.len();
        let n_colors = self.config.blame_palette.len();
        let color = self.config.blame_palette[n_commits % n_colors].clone();
        if Some(color.as_str()) != other_than_color {
            color
        } else {
            self.config.blame_palette[(n_commits + 1) % n_colors].clone()
        }
    }
}

#[derive(Debug)]
pub struct BlameLine<'a> {
    pub commit: &'a str,
    pub author: &'a str,
    pub time: DateTime<FixedOffset>,
    pub line_number: usize,
    pub code: &'a str,
}

// E.g.
//ea82f2d0 (Dan Davison       2021-08-22 18:20:19 -0700 120)             let mut handled_line = self.handle_commit_meta_header_line()?

lazy_static! {
    static ref BLAME_LINE_REGEX: Regex = Regex::new(
        r"(?x)
^
(
    \^?[0-9a-f]{4,40} # commit hash (^ is 'boundary commit' marker)
)
(?: .+)?           # optional file name (unused; present if file has been renamed; TODO: inefficient?)
[\ ]
\(                 # open (
(
    [^\ ].*[^\ ]   # author name
)
[\ ]+
(                  # timestamp
    [0-9]{4}-[0-9]{2}-[0-9]{2}\ [0-9]{2}:[0-9]{2}:[0-9]{2}\ [-+][0-9]{4}
)
[\ ]+
(
    [0-9]+        # line number
)
\)                # close )
(
    .*            # code, with leading space
)
$
"
    )
    .unwrap();
}

pub fn parse_git_blame_line<'a>(line: &'a str, timestamp_format: &str) -> Option<BlameLine<'a>> {
    let caps = BLAME_LINE_REGEX.captures(line)?;

    let commit = caps.get(1).unwrap().as