statusline/block/
git.rs

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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
use crate::{file, Environment, Icon, IconMode, Pretty, SimpleBlock, Style};
use anyhow::{anyhow, bail, Context, Result};
use memmapix::Mmap;
use rustix::process;
use std::{
    borrow::Cow,
    fs::{self, File},
    io::{BufRead, BufReader, Error, ErrorKind},
    iter, mem,
    ops::Deref,
    os::unix::process::CommandExt,
    path::{Path, PathBuf},
    process::Command,
};

/*
thanks to
    the git source code which is very fucking clear and understandable
    as well as to purplesyringa's immense help and kind emotional support

thanks to
    https://git-scm.com/docs/git-status
    https://github.com/romkatv/powerlevel10k
 feature[:master] v1^2 *3 ~4 +5 !6 ?7
    (feature) Current LOCAL branch   -> # branch.head <name>
    (master) Remote branch IF DIFFERENT and not null   -> # branch.upstream <origin>/<name>
    1 commit behind, 2 commits ahead   -> # branch.ab +<ahead> -<behind>
    3 stashes   -> # stash <count>
    4 unmerged   -> XX
    5 staged   -> X.
    6 dirty   -> .X
    7 untracked   -> ?
*/

fn parse_ref_by_name<T: AsRef<str>>(name: T, root: PathBuf) -> Head {
    if let Some(name) = name.as_ref().trim().strip_prefix("refs/heads/") {
        Head {
            kind: HeadKind::Branch(name.to_owned()),
            root,
        }
    } else {
        Head {
            kind: HeadKind::Unknown,
            root,
        }
    }
}

fn lcp<T: AsRef<str>>(a: T, b: T) -> usize {
    iter::zip(a.as_ref().chars(), b.as_ref().chars())
        .position(|(a, b)| a != b)
        .unwrap_or(0) // if equal then LCP should be zero
}

fn lcp_bytes(a: &[u8], b: &[u8]) -> usize {
    let pos = iter::zip(a.iter(), b.iter()).position(|(a, b)| a != b);
    match pos {
        None => 0,
        Some(i) => i * 2 + ((a[i] >> 4) == (b[i] >> 4)) as usize,
    }
}

fn load_objects(root: &Path, fanout: &str) -> Result<Vec<String>> {
    Ok(fs::read_dir(root.join("objects").join(fanout))?
        .map(|res| res.map(|e| String::from(e.file_name().to_string_lossy())))
        .collect::<Result<Vec<_>, _>>()?)
}

fn objects_dir_len(root: &Path, id: &str) -> Result<usize> {
    let (fanout, rest) = id.split_at(2);

    // Find len from ".git/objects/xx/..."
    let best_lcp = load_objects(root, fanout)?
        .iter()
        .map(|val| lcp(val.as_str(), rest))
        .max();
    Ok(match best_lcp {
        None => 2,
        Some(val) => 3 + val,
    })
}

fn packed_objects_len(root: &Path, commit: &str) -> Result<usize> {
    let commit = fahtsex::parse_oid_str(commit).ok_or(Error::from(ErrorKind::InvalidData))?;

    let mut res = 0;
    for entry in fs::read_dir(root.join("objects/pack"))? {
        let path = entry?.path();
        // eprintln!("entry {path:?}");
        let Some(ext) = path.extension() else {
            continue;
        };
        if ext != "idx" {
            continue;
        }

        // File should at least contain magic, version and a fanout table, which is 102 ints
        let file = File::open(path).context("open packed objects")?;
        let map = unsafe { Mmap::map(&file).context("map packed objects")? };
        let map = map.deref();
        if map.len() < 0x408 {
            continue;
        }
        // eprintln!("mmaped");

        // Git packed objects index file format is easy -- Yuki
        // Statements dreamed up by the utterly deranged -- purplesyringa
        // See https://github.com/purplesyringa/gitcenter -> main/dist/js/git.md
        //
        // Actually, I don't think this file format is easy. It's easy to make a great lot of bugs
        // in code dealing with this file format. Why did I return here? Because of one fucking
        // small optimization which thought that every i32 is in correct byte order -- the statement
        // which is wrong, but left unnoticed for a long time. -- Yuki, some months later
        //
        // I'd like to never return here again.

        let map_size = map.len() / 4;
        let integers: &[[u8; 4]] = unsafe { mem::transmute(&map[..4 * map_size]) };

        // Magic int is 0xFF744F63 ('\377tOc') which probably should be read as "table of contents"
        // Only version 2 is supported
        let magic_version = &map[..8]; // it's okay promise me
        if magic_version != [0xff, 0x74, 0x4f, 0x63, 0x00, 0x00, 0x00, 0x02] {
            continue;
        }

        // [0x0008 -- 0x0408] is fanout table as [u32, 256], but in fucking network byte order
        // where `table[i]` is count of objects with `fanout <= i`
        // object range is from `table[i-1]` to `table[i] - 1` including both borders
        let fanout_table: &[[u8; 4]] = &integers[2..0x102];
        let fanout = *commit.first().unwrap() as usize;
        let begin = if fanout == 0 {
            0
        } else {
            u32::from_be_bytes(fanout_table[fanout - 1])
        } as usize;
        let end = u32::from_be_bytes(fanout_table[fanout]) as usize;

        // eprintln!("left and right are {begin:x?} and {end:x?}");

        // begin and end are sha1 *indexes* and not positions of their beginning
        if begin == end {
            continue;
        }

        // If only little endian was the network byte order...
        let commit_position = |idx: usize| 0x102 + 5 * idx;
        if map_size < commit_position(u32::from_be_bytes(*fanout_table.last().unwrap()) as usize) {
            continue;
        }

        // holy hell, second memory transmute
        let hashes: &[[u8; 20]] =
            unsafe { mem::transmute(&integers[commit_position(begin)..commit_position(end)]) };

        let index = hashes.partition_point(|hash| hash < &commit);
        // eprintln!("got index {index}");
        if index > 0 {
            res = res.max(lcp_bytes(&hashes[index - 1], &commit));
        }
        if index < end - begin {
            res = res.max(lcp_bytes(
                &hashes[index + (hashes[index] == commit) as usize],
                &commit,
            ));
        }
    }
    // eprintln!("packed: {res:?}");
    // eprintln!("");
    Ok(1 + res)
}

fn abbrev_commit(root: &Path, id: &str) -> usize {
    let mut abbrev_len = 4;
    if let Ok(x) = objects_dir_len(root, id) {
        abbrev_len = abbrev_len.max(x);
    }
    if let Ok(x) = packed_objects_len(root, id) {
        abbrev_len = abbrev_len.max(x);
    }
    abbrev_len
}

#[derive(Debug)]
enum HeadKind {
    Branch(String),
    NonexistentBranch(String),
    Commit(String),
    Unknown,
}

#[derive(Debug)]
struct Head {
    root: PathBuf,
    kind: HeadKind,
}

impl Icon for HeadKind {
    fn icon(&self, mode: &IconMode) -> &'static str {
        use IconMode::*;
        match self {
            Self::Branch(_) => match mode {
                Text => "on",
                Icons | MinimalIcons => "󰘬",
            },
            Self::NonexistentBranch(_) => match mode {
                Text => "to",
                Icons | MinimalIcons => "󰽤",
            },
            Self::Commit(_) => match mode {
                Text => "at",
                Icons | MinimalIcons => "",
            },
            Self::Unknown => "<unknown>",
        }
    }
}

impl Pretty for Head {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        Some(match &self.kind {
            branch @ HeadKind::Branch(name) | branch @ HeadKind::NonexistentBranch(name) => {
                format!("{} {}", branch.icon(mode), name)
            }
            oid @ HeadKind::Commit(id) => {
                format!(
                    "{} {}",
                    oid.icon(mode),
                    &id[..abbrev_commit(&self.root, id)]
                )
                // TODO show tag?
            }
            other => other.icon(mode).to_string(),
        })
    }
}

impl Head {
    // Please WHY
    fn git_value(&self) -> Cow<str> {
        match &self.kind {
            HeadKind::Branch(name) | HeadKind::NonexistentBranch(name) => {
                Cow::from(format!("refs/heads/{name}"))
            }
            HeadKind::Commit(id) => Cow::from(id),
            HeadKind::Unknown => Cow::from("<head>"),
        }
    }

    // WHY WHY WHY send help
    fn fix_nonexistent(mut self) -> Self {
        let git_value = self.git_value();
        let git_value = git_value.as_ref();
        let root = &self.root;
        self.kind = match self.kind {
            HeadKind::Branch(name)
                if fs::exists(root.join(git_value)).ok() != Some(true)
                    && fs::File::open(root.join("packed-refs"))
                        .ok()
                        .map(BufReader::new)
                        .map(BufReader::lines)
                        .map(|lines| lines.map_while(Result::ok))
                        .and_then(|mut lines| lines.find(|line| line.contains(git_value)))
                        .is_none() =>
            {
                HeadKind::NonexistentBranch(name)
            }

            _ => self.kind,
        };
        self
    }
}

// TODO: add some info to bisect...
enum State {
    Merging { head: String },
    Rebasing { done: usize, todo: usize },
    CherryPicking { head: String },
    Reverting { head: String },
    Bisecting,
}

impl State {
    fn from_env(root: &Path) -> Option<State> {
        let revert_head = root.join("REVERT_HEAD");
        let cherry_pick_head = root.join("CHERRY_PICK_HEAD");
        let merge_head = root.join("MERGE_HEAD");
        let rebase_merge = root.join("rebase-merge");

        let abbrev_head = |head: &Path| {
            fs::read_to_string(head).map(|mut id| {
                id.truncate(abbrev_commit(root, &id));
                id
            })
        };

        Some(if file::exists(&root.join("BISECT_LOG")) {
            State::Bisecting
        } else if let Ok(head) = abbrev_head(&revert_head) {
            State::Reverting { head }
        } else if let Ok(head) = abbrev_head(&cherry_pick_head) {
            State::CherryPicking { head }
        } else if file::exists(&rebase_merge) {
            let todo = match File::open(rebase_merge.join("git-rebase-todo")) {
                Ok(file) => BufReader::new(file)
                    .lines()
                    .map_while(Result::ok)
                    .filter(|line| !line.starts_with('#'))
                    .count(),
                Err(_) => 0,
            };
            let done = match File::open(rebase_merge.join("done")) {
                Ok(file) => BufReader::new(file).lines().count(),
                Err(_) => 0,
            };
            State::Rebasing { todo, done }
        } else if let Ok(head) = abbrev_head(&merge_head) {
            State::Merging { head }
        } else {
            None?
        })
    }
}

impl Icon for State {
    fn icon(&self, mode: &IconMode) -> &'static str {
        use IconMode::*;
        match self {
            Self::Bisecting => match mode {
                Text => "bisecting",
                Icons | MinimalIcons => "󰩫 ", //TODO
            },
            Self::Reverting { .. } => match mode {
                Text => "reverting",
                Icons | MinimalIcons => "",
            },
            Self::CherryPicking { .. } => match mode {
                Text => "cherry-picking",
                Icons | MinimalIcons => "",
            },
            Self::Merging { .. } => match mode {
                Text => "merging",
                Icons | MinimalIcons => "󰃸",
            },
            Self::Rebasing { .. } => match mode {
                Text => "rebasing",
                Icons | MinimalIcons => "󰝖",
            },
        }
    }
}

impl Pretty for State {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        let icon = self.icon(mode);
        Some(match self {
            State::Bisecting => icon.to_string(),
            State::Reverting { head } => format!("{icon} {}", head),
            State::CherryPicking { head } => {
                format!("{icon} {}", head)
            }
            State::Merging { head } => format!("{icon} {}", head),
            State::Rebasing { done, todo } => {
                format!("{icon} {}/{}", done, done + todo)
            }
        })
    }
}

fn get_remote(head: &Head) -> Option<(String, String)> {
    let HeadKind::Branch(br) = &head.kind else {
        return None;
    };

    let root = &head.root;
    let section = format!("[branch \"{br}\"]");
    let mut remote_name = None;
    let mut remote_branch = None;
    for line in BufReader::new(fs::File::open(root.join("config")).ok()?)
        .lines()
        .map_while(Result::ok)
        .skip_while(|x| x != &section)
        .skip(1)
        .take_while(|x| x.starts_with('\t'))
    {
        if let Some(x) = line.strip_prefix("\tremote = ") {
            remote_name = Some(x.to_string());
        } else if let Some(x) = line.strip_prefix("\tmerge = refs/heads/") {
            remote_branch = Some(x.to_string());
        }
    }
    remote_name.zip(remote_branch)
}

fn get_ahead_behind(
    tree: &Path,
    head: &HeadKind,
    remote: &Option<(String, String)>,
) -> Result<(usize, usize)> {
    let (HeadKind::Branch(head), Some((name, branch))) = (head, remote) else {
        bail!("Head is not a branch or remote is missing");
    };

    // I assume this is fast
    Ok(Command::new("git")
        .arg("-C")
        .arg(tree)
        .arg("rev-list")
        .arg("--count")
        .arg("--left-right")
        .arg(format!("{head}...{name}/{branch}"))
        .output()?
        .stdout
        .trim_ascii_end()
        .split(|&c| c == b'\t')
        .map(|x| Result::<usize>::Ok(std::str::from_utf8(x)?.parse::<usize>()?))
        .filter_map(Result::ok)
        .next_chunk::<2>()
        .map_err(|_| anyhow!("Invalid rev-list output"))?
        .into())
}

pub struct GitRepo {
    head: Head,
    remote: Option<(String, String)>,
    stashes: usize,
    state: Option<State>,
    behind: usize,
    ahead: usize,
}

pub type Repo = Result<GitRepo>;

pub struct GitTree {
    tree: PathBuf,
    unmerged: usize,
    staged: usize,
    dirty: usize,
    untracked: usize,
}

pub type Tree = Option<GitTree>;

impl From<&Environment> for Tree {
    fn from(env: &Environment) -> Tree {
        let tree = env.git_tree.as_ref()?.clone();
        Some(GitTree {
            tree,
            unmerged: 0,
            staged: 0,
            dirty: 0,
            untracked: 0,
        })
    }
}
impl From<&Environment> for Repo {
    fn from(env: &Environment) -> Repo {
        let tree = env.git_tree.as_ref().context("No git tree found")?.clone();
        let dotgit = tree.join(".git");
        let root = if dotgit.is_file() {
            tree.join(
                fs::read_to_string(&dotgit)?
                    .strip_prefix("gitdir: ")
                    .ok_or(Error::from(ErrorKind::InvalidData))?
                    .trim_end_matches(['\r', '\n']),
            )
        } else {
            dotgit
        };

        let stash_path = root.join("logs/refs/stash");
        // eprintln!("try find stashes in {stash_path:?}");
        let stashes = fs::File::open(stash_path)
            .map(|file| BufReader::new(file).lines().count())
            .unwrap_or(0);

        let state = State::from_env(&root);

        // eprintln!("ok tree {tree:?} | {root:?}");
        let head_path = root.join("HEAD");

        let head = if head_path.is_symlink() {
            parse_ref_by_name(
                fs::read_link(head_path)?
                    .to_str()
                    .ok_or(Error::from(ErrorKind::InvalidFilename))?,
                root,
            )
        } else {
            let head = fs::read_to_string(head_path)?;
            if let Some(rest) = head.strip_prefix("ref:") {
                parse_ref_by_name(rest, root)
            } else {
                Head {
                    kind: HeadKind::Commit(
                        head.split_whitespace()
                            .next()
                            .unwrap_or_default()
                            .to_owned(),
                    ),
                    root,
                }
            }
        };
        let head = head.fix_nonexistent();

        let remote = get_remote(&head);

        let (ahead, behind) = get_ahead_behind(&tree, &head.kind, &remote).unwrap_or((0, 0));

        Ok(GitRepo {
            head,
            remote,
            stashes,
            state,
            behind,
            ahead,
        })
    }
}

impl SimpleBlock for Repo {
    fn extend(self: Box<Self>) -> Box<dyn Pretty> {
        self
    }
}

impl SimpleBlock for Tree {
    fn extend(self: Box<Self>) -> Box<dyn Pretty> {
        let self_ref = match *self {
            Some(x) => x,
            _ => return self,
        };

        let parent_pid = process::getpid();
        let out = unsafe {
            Command::new("git")
                .arg("-C")
                .arg(&self_ref.tree)
                .arg("status")
                .arg("--porcelain=2")
                .pre_exec(move || -> std::io::Result<()> {
                    process::set_parent_process_death_signal(Some(process::Signal::Term))?;
                    if Some(parent_pid) != process::getppid() {
                        return Err(std::io::Error::other("Parent already dead"));
                    }
                    Ok(())
                })
                .output()
                .ok()
        };
        let Some(out) = out else {
            return Box::new(self_ref);
        };
        let lines = out.stdout.split(|&c| c == b'\n').peekable();

        let mut unmerged = 0;
        let mut staged = 0;
        let mut dirty = 0;
        let mut untracked = 0;

        for line in lines {
            let words: Vec<_> = line.split(|&c| c == b' ').take(2).collect();
            if words.len() != 2 {
                continue;
            }
            let (id, pat) = (words[0], words[1]);
            match (id, pat) {
                (b"?", _) => {
                    untracked += 1;
                }
                (b"u", _) => {
                    unmerged += 1;
                }
                (_, pat) if pat.len() == 2 => {
                    if pat[0] != b'.' {
                        staged += 1;
                    }
                    if pat[1] != b'.' {
                        dirty += 1;
                    }
                }
                _ => {}
            }
        }

        Box::new(GitTree {
            tree: self_ref.tree,
            unmerged,
            staged,
            dirty,
            untracked,
        })
    }
}

impl Pretty for Repo {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        self.as_ref().ok()?.pretty(mode)
    }
}

impl Pretty for GitRepo {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        let mut res = vec![];

        if let Some(state) = &self.state {
            res.push(format!("{}|", state.pretty(mode).unwrap_or_default()));
        }

        let head = self.head.pretty(mode).unwrap_or_default();
        res.push(head);

        match (&self.head.kind, &self.remote) {
            (HeadKind::Branch(head), Some((_, remote))) if head != remote => {
                res.push(format!(":{}", remote));
            }
            _ => (),
        };

        for (icon, val) in [
            (GitIcon::Stashes, self.stashes),
            (GitIcon::Behind, self.behind),
            (GitIcon::Ahead, self.ahead),
        ] {
            if val != 0 {
                res.push(format!(" {}{}", icon.icon(mode), val));
            }
        }

        Some(
            res.join("")
                .boxed()
                .visible()
                .colorize_with(self.head.git_value().as_ref()) //.pink()
                .bold()
                .with_reset()
                .invisible()
                .to_string(),
        )
    }
}

impl Pretty for Tree {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        self.as_ref()?.pretty(mode)
    }
}

impl Pretty for GitTree {
    fn pretty(&self, mode: &IconMode) -> Option<String> {
        let vec = [
            (GitIcon::Conflict, self.unmerged),
            (GitIcon::Staged, self.staged),
            (GitIcon::Dirty, self.dirty),
            (GitIcon::Untracked, self.untracked),
        ]
        .into_iter()
        .filter(|(_, val)| val != &0)
        .map(|(s, val)| format!("{}{}", s.icon(mode), val))
        .collect::<Vec<_>>();

        if vec.is_empty() {
            None
        } else {
            Some(
                vec.join(" ")
                    .boxed()
                    .visible()
                    .pink()
                    .with_reset()
                    .invisible()
                    .to_string(),
            )
        }
    }
}

enum GitIcon {
    /// Git info: "ahead" the remote
    Ahead,
    /// Git info: "behind" the remote
    Behind,
    /// Git info: stashes
    Stashes,
    /// Git tree: merge conflicts
    Conflict,
    /// Git tree: staged
    Staged,
    /// Git tree: dirty
    Dirty,
    /// Git tree: untracked
    Untracked,
}

impl Icon for GitIcon {
    fn icon(&self, mode: &IconMode) -> &'static str {
        use IconMode::*;
        match &self {
            Self::Ahead => match mode {
                Text => "^",
                Icons | MinimalIcons => " ",
            },
            Self::Behind => match mode {
                Text => "v",
                Icons | MinimalIcons => " ",
            },
            Self::Stashes => match mode {
                Text => "*",
                Icons | MinimalIcons => " ",
            },
            Self::Conflict => match mode {
                Text => "=",
                Icons => "󰞇 ",
                MinimalIcons => " ",
            },
            Self::Staged => match mode {
                Text => "+",
                Icons | MinimalIcons => " ",
            },
            Self::Dirty => match mode {
                Text => "!",
                Icons | MinimalIcons => " ",
            },
            Self::Untracked => match mode {
                Text => "?",
                Icons => " ",
                MinimalIcons => " ",
            },
        }
    }
}