git-pincer 0.1.3

A simple and efficient terminal Git conflict resolution CLI tool.
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
//! 三栏正文渲染:圆角边框面板、色带、词级强调、选中指示、行号、折叠横线与滚动条。

use crate::i18n::{tr, tr_f};
use std::ops::Range;

use ratatui::Frame;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
};

use crate::app::{FileMerge, SideState};

use super::highlight::{FileHighlight, PaneSyntax};
use super::rows::{Cell, ChangeType, Row};
use super::theme::Theme;

/// 三栏之一。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Pane {
    /// 本地(左栏, ours)
    Local,
    /// 合并结果(中栏)
    Result,
    /// 远端(右栏, theirs)
    Remote,
}

/// 一栏内的空间预算:窄终端时逐级裁剪次要元素(先丢行号,再丢 gutter)。
struct CellBudget {
    /// 是否显示左侧 gutter 列(操作符号 + 空格)
    gutter: bool,
    /// 行号列宽;0 表示不显示行号
    no_width: usize,
}

/// 依据栏内宽与最大行号计算空间预算。
fn cell_budget(inner: u16, max_no: usize) -> CellBudget {
    let no_width = max_no.to_string().len().max(3);
    if inner >= 24 {
        CellBudget {
            gutter: true,
            no_width,
        }
    } else if inner >= 14 {
        CellBudget {
            gutter: true,
            no_width: 0,
        }
    } else {
        CellBudget {
            gutter: false,
            no_width: 0,
        }
    }
}

/// gutter 操作符号(IDEA 风格):
/// `»` / `«` 待取用(箭头指向结果栏)、`✓` 已取用、`✗` 已忽略。
/// 结果栏不放符号(紧贴边框的色块会被误读为边框变色),
/// 当前块由提亮色带 + 亮行号标识。
fn gutter_symbol(row: &Row, pane: Pane, theme: &Theme) -> Span<'static> {
    let sym = |state: Option<SideState>, arrow: &'static str| match state {
        // 覆写(e 编辑)后块已解决,不再提示待取用
        Some(SideState::Pending) if !row.resolved => {
            Span::styled(arrow, Style::new().fg(theme.accent(row.change)))
        }
        Some(SideState::Applied) => Span::styled("", Style::new().fg(theme.green)),
        Some(SideState::Ignored) => Span::styled("", Style::new().fg(theme.fg_dim)),
        _ => Span::raw(" "),
    };
    match pane {
        Pane::Local => sym(row.ours_state, "»"),
        Pane::Remote => sym(row.theirs_state, "«"),
        Pane::Result => Span::raw(" "),
    }
}

/// 栏头标题(嵌入边框):固定栏名 + 分支标签。
fn pane_title(pane: Pane, merge: &FileMerge) -> String {
    match pane {
        Pane::Local => merge
            .ours_label
            .as_deref()
            .map_or(" LOCAL (ours) ".to_owned(), |l| format!(" LOCAL · {l} ")),
        Pane::Result => " RESULT ".to_owned(),
        Pane::Remote => merge
            .theirs_label
            .as_deref()
            .map_or(" REMOTE (theirs) ".to_owned(), |l| {
                format!(" REMOTE · {l} ")
            }),
    }
}

/// 折叠行:左右栏画纯横线,中栏在横线中嵌入行数标签(窄栏逐级降级)。
/// 横线与面板边框同色,保证全部线条元素色调一致。
fn fold_line(n: usize, pane: Pane, inner: u16, theme: &Theme) -> Line<'static> {
    let style = Style::new().fg(theme.border);
    if pane != Pane::Result {
        return Line::styled("".repeat(inner as usize), style);
    }
    // 中栏标签按可用宽度降级:完整文案 → 精简 → 纯横线
    let text = if inner >= 30 {
        tr_f("ui.fold", &[("n", &n.to_string())])
    } else if inner >= 12 {
        format!("─ ⋯ {n} ⋯ ─")
    } else {
        "".repeat(inner as usize)
    };
    Line::styled(text, style).alignment(Alignment::Center)
}

/// 三层样式合成:按 fg(语法高亮)与 emphasis(词级强调)的区间端点分段,
/// 每段 fg 取语法色、命中 emphasis 处 bg 换更亮的强调色;色带 bg 由行样式提供。
fn compose_spans(
    text: &str,
    fg_spans: &[(Color, Range<usize>)],
    emphasis: &[Range<usize>],
    emph_bg: Color,
) -> Vec<Span<'static>> {
    let mut bounds = vec![0, text.len()];
    for r in fg_spans.iter().map(|(_, r)| r).chain(emphasis) {
        bounds.push(r.start.min(text.len()));
        bounds.push(r.end.min(text.len()));
    }
    bounds.sort_unstable();
    bounds.dedup();
    let mut spans = Vec::with_capacity(bounds.len());
    for win in bounds.windows(2) {
        let (a, b) = (win[0], win[1]);
        let mut style = Style::new();
        if let Some((color, _)) = fg_spans.iter().find(|(_, r)| r.start <= a && b <= r.end) {
            style = style.fg(*color);
        }
        if emphasis.iter().any(|r| r.start <= a && b <= r.end) {
            style = style.bg(emph_bg);
        }
        spans.push(Span::styled(text[a..b].to_owned(), style));
    }
    spans
}

/// 一行的两个着色层:(词级强调区间, 语法高亮段)。
type LineLayers<'a> = (&'a [Range<usize>], &'a [(Color, Range<usize>)]);

/// 组装一栏中的一行(gutter 符号 + 行号 + 内容 / 占位 / 空白);
/// `current` 为该行是否属于光标所在块(渲染时现算,行列表可跨帧缓存),
/// `(emphasis, fg_spans)` 为词级强调与语法高亮两个着色层。
fn cell_line(
    row: &Row,
    current: bool,
    cell: &Cell,
    pane: Pane,
    budget: &CellBudget,
    theme: &Theme,
    (emphasis, fg_spans): LineLayers<'_>,
) -> Line<'static> {
    let mut style = Style::new();
    // 色带只画在发生改动的栏 + 结果栏(IDEA 式),随块解决消失;当前块同色相提亮
    let banded = match pane {
        Pane::Local => row.ours_state.is_some(),
        Pane::Remote => row.theirs_state.is_some(),
        Pane::Result => true,
    };
    if banded
        && !row.resolved
        && let Some(bg) = theme.band_bg(row.change, current)
    {
        style = style.bg(bg);
    }
    let mut spans = Vec::with_capacity(4);
    if budget.gutter {
        spans.push(gutter_symbol(row, pane, theme));
        spans.push(Span::raw(" "));
    }
    let (no, text) = match cell {
        Cell::Line { no, text, .. } => (*no, text),
        Cell::Empty => return Line::from(spans).style(style),
        Cell::Placeholder => {
            spans.push(Span::styled(
                tr("ui.pending"),
                Style::new().fg(theme.placeholder_fg),
            ));
            return Line::from(spans).style(style);
        }
    };
    if budget.no_width > 0 {
        let no_style = if current {
            Style::new().fg(theme.fg_bright)
        } else {
            Style::new().fg(theme.fg_dim)
        };
        spans.push(Span::styled(
            format!("{no:>w$} ", w = budget.no_width),
            no_style,
        ));
    }
    if emphasis.is_empty() && fg_spans.is_empty() {
        spans.push(Span::raw(text.clone()));
    } else {
        spans.extend(compose_spans(
            text,
            fg_spans,
            emphasis,
            theme.emph_bg(row.change, current),
        ));
    }
    Line::from(spans).style(style)
}

/// 取某栏某行的语法高亮段;无语法定义或行号越界时为空。
fn pane_fg(pane: Option<&PaneSyntax>, no: usize) -> &[(Color, Range<usize>)] {
    pane.and_then(|p| p.lines.get(no.wrapping_sub(1)))
        .map_or(&[], Vec::as_slice)
}

/// 三列正文;根据光标调整滚动位置并写回,跨帧保持视口稳定。
///
/// 渲染行由 [`RowCache`](super::rows::RowCache) 提供(纯导航按键零重建),
/// 光标所在块在此处用 `row.chunk` 现比;`scroll_request` 为待结算的
/// 手动滚动量(半页为单位),消费后视口脱离光标跟随。
pub(crate) fn draw_columns(
    frame: &mut Frame,
    area: Rect,
    merge: &mut FileMerge,
    theme: &Theme,
    highlight: &FileHighlight,
    (rows, chunk_starts, max_no): (&[Row], &[usize], usize),
    scroll_request: &mut isize,
) {
    // 上下边框各占一行
    let height = (area.height as usize).saturating_sub(2);
    let max_scroll = rows.len().saturating_sub(height);

    // 结算手动滚动:半页步长按当前视口高度换算,滚动后脱离跟随
    if *scroll_request != 0 {
        let step = (height / 2).max(1) as isize;
        merge.scroll = merge
            .scroll
            .saturating_add_signed(*scroll_request * step)
            .min(max_scroll);
        merge.follow = false;
        *scroll_request = 0;
    }

    // 跟随模式下:光标块在视口内则不动;跳出视口时把块首行定位到约 1/3 处,
    // 让上方留出上下文、下方能看到块的内容
    let target = chunk_starts.get(merge.cursor).copied().unwrap_or(0);
    let mut scroll = merge.scroll.min(max_scroll);
    if merge.follow && height > 0 && (target < scroll || target >= scroll + height) {
        scroll = target.saturating_sub(height / 3).min(max_scroll);
    }
    merge.scroll = scroll;

    let visible = &rows[scroll.min(rows.len())..rows.len().min(scroll + height)];

    let cols = split_columns(area);
    let panes = [
        (Pane::Local, cols[0]),
        (Pane::Result, cols[1]),
        (Pane::Remote, cols[2]),
    ];
    for (pane, col) in panes {
        let block = Block::bordered()
            .border_type(BorderType::Rounded)
            .border_style(Style::new().fg(theme.border))
            .title(Span::styled(
                pane_title(pane, merge),
                Style::new()
                    .fg(theme.fg_bright)
                    .add_modifier(Modifier::BOLD),
            ));
        let inner = block.inner(col);
        let budget = cell_budget(inner.width, max_no);
        let lines: Vec<Line<'static>> = visible
            .iter()
            .map(|row| {
                let cell = match pane {
                    Pane::Local => &row.ours,
                    Pane::Result => &row.result,
                    Pane::Remote => &row.theirs,
                };
                // 词级强调只作用于未解决块的左右两栏(结果栏展示的是已选内容)
                let emphasis: &[Range<usize>] = match (row.resolved, pane, cell) {
                    (false, Pane::Local, Cell::Line { offset, .. }) => highlight
                        .emphasis
                        .get(row.chunk)
                        .and_then(|e| e.ours.get(*offset))
                        .map_or(&[], Vec::as_slice),
                    (false, Pane::Remote, Cell::Line { offset, .. }) => highlight
                        .emphasis
                        .get(row.chunk)
                        .and_then(|e| e.theirs.get(*offset))
                        .map_or(&[], Vec::as_slice),
                    _ => &[],
                };
                // 语法高亮寻址:左右栏按栏内绝对行号,结果栏按 (块, 块内偏移)
                let fg_spans: &[(Color, Range<usize>)] = match (pane, cell) {
                    (Pane::Local, Cell::Line { no, .. }) => pane_fg(highlight.ours.as_ref(), *no),
                    (Pane::Result, Cell::Line { offset, .. }) => highlight
                        .result
                        .as_ref()
                        .map_or(&[], |r| r.spans(row.chunk, *offset)),
                    (Pane::Remote, Cell::Line { no, .. }) => {
                        pane_fg(highlight.theirs.as_ref(), *no)
                    }
                    _ => &[],
                };
                // 光标所在块(折叠行只出现在稳定块上,恒非当前)
                let current = row.chunk == merge.cursor && row.change != ChangeType::None;
                match row.fold {
                    Some(n) => fold_line(n, pane, inner.width, theme),
                    None => cell_line(
                        row,
                        current,
                        cell,
                        pane,
                        &budget,
                        theme,
                        (emphasis, fg_spans),
                    ),
                }
            })
            .collect();
        frame.render_widget(block, col);
        frame.render_widget(Paragraph::new(lines), inner);
    }
    // 三栏同步滚动,滚动条只画一条,置于窗口最右缘,避免栏间边框被滑块「点亮」
    draw_scrollbar(frame, cols[2], max_scroll, scroll, theme);
}

/// 在栏右边框上覆画滚动条(避开圆角);内容未溢出时不显示。
fn draw_scrollbar(frame: &mut Frame, col: Rect, max_scroll: usize, scroll: usize, theme: &Theme) {
    if max_scroll == 0 || col.height <= 2 || col.width < 2 {
        return;
    }
    let track = Rect {
        x: col.x + col.width - 1,
        y: col.y + 1,
        width: 1,
        height: col.height - 2,
    };
    let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
        .begin_symbol(None)
        .end_symbol(None)
        .track_symbol(Some(""))
        .track_style(Style::new().fg(theme.border))
        .thumb_symbol("")
        .thumb_style(Style::new().fg(theme.scrollbar_thumb));
    let mut state = ScrollbarState::new(max_scroll).position(scroll);
    frame.render_stateful_widget(scrollbar, track, &mut state);
}

/// 将区域水平三等分。
fn split_columns(area: Rect) -> [Rect; 3] {
    Layout::horizontal([
        Constraint::Ratio(1, 3),
        Constraint::Ratio(1, 3),
        Constraint::Ratio(1, 3),
    ])
    .areas(area)
}

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

    /// 三层区间交叠时分段与样式合成正确
    #[test]
    fn compose_spans_merges_overlapping_layers() {
        let fg = [(Color::Red, 0..4)];
        let emphasis = std::slice::from_ref(&(2..6));
        let spans = compose_spans("abcdef", &fg, emphasis, Color::Blue);
        // 分段:[0,2) 仅 fg | [2,4) fg + emph bg | [4,6) 仅 emph bg
        assert_eq!(spans.len(), 3);
        assert_eq!(spans[0].content, "ab");
        assert_eq!(
            (spans[0].style.fg, spans[0].style.bg),
            (Some(Color::Red), None)
        );
        assert_eq!(spans[1].content, "cd");
        assert_eq!(
            (spans[1].style.fg, spans[1].style.bg),
            (Some(Color::Red), Some(Color::Blue))
        );
        assert_eq!(spans[2].content, "ef");
        assert_eq!(
            (spans[2].style.fg, spans[2].style.bg),
            (None, Some(Color::Blue))
        );
    }

    /// 区间端点越界时被安全钳制,不会切出非法切片
    #[test]
    fn compose_spans_clamps_out_of_range() {
        let spans = compose_spans("ab", &[], std::slice::from_ref(&(1..99)), Color::Blue);
        assert_eq!(spans.len(), 2);
        assert_eq!(spans[1].content, "b");
        assert_eq!(spans[1].style.bg, Some(Color::Blue));
    }
}