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
use std::{
    fs::read_link,
    io::Write,
    ops::Range,
    os::unix::prelude::OsStrExt,
    path::{Component, PathBuf},
    str,
};

use anyhow::Result;
use is_executable::IsExecutable;
use tree_sitter::{Node, Tree, TreeCursor};

use crate::{parse_command, Context};

pub fn patch(ctx: &mut Context, tree: Tree, out: &mut impl Write) -> Result<()> {
    walk(ctx, &mut tree.walk())?;

    let mut last = 0;
    for (range, path) in &ctx.patches {
        out.write_all(&ctx.src[last .. range.start])?;
        let path = path.as_os_str().as_bytes();
        if let Ok(path) = str::from_utf8(path) {
            write!(out, "{}", shell_escape::escape(path.into()))?;
        } else {
            out.write_all(b"'")?;
            out.write_all(path)?;
            out.write_all(b"'")?;
        }
        last = range.end;
    }
    out.write_all(&ctx.src[last ..])?;

    Ok(())
}

fn walk(ctx: &mut Context, cur: &mut TreeCursor) -> Result<()> {
    if cur.node().kind() == "command_name" && cur.goto_first_child() {
        patch_node(ctx, cur.node());
        cur.goto_parent();
    }

    if cur.goto_first_child() {
        walk(ctx, cur)?;
        cur.goto_parent();
    }

    if cur.goto_next_sibling() {
        walk(ctx, cur)?;
    }

    Ok(())
}

fn patch_node(ctx: &mut Context, node: Node) {
    let (no_builtins, commands) = parse_command(ctx, &node);
    for (range, name) in commands {
        let path = PathBuf::from(name);
        if path.starts_with(&ctx.store_dir) {
            continue;
        }

        let mut c = path.components();
        let name = match c.next() {
            Some(Component::RootDir) => {
                if let Some(Component::Normal(name)) = c.last() {
                    name
                } else {
                    continue;
                }
            }
            Some(Component::Normal(name))
                if c.next().is_none() && (no_builtins || !ctx.builtins.contains(&name.into())) =>
            {
                name
            }
            _ => continue,
        };

        let Some(idx) = get_patch_index(&ctx.patches, &range) else {
            continue;
        };

        let Some(mut path) = ctx.paths.iter().find_map(|path| {
            let path = path.join(name);
            path.is_executable().then_some(path)
        }) else {
            continue;
        };

        while let Ok(resolved) = read_link(&path) {
            if resolved.file_name() == Some(name) {
                path = resolved;
            } else {
                break;
            }
        }

        if path.starts_with(&ctx.store_dir) {
            add_patch(&mut ctx.patches, idx, range, path);
        }
    }
}

pub(crate) fn get_patch_index(
    patches: &[(Range<usize>, PathBuf)],
    range: &Range<usize>,
) -> Option<(usize, bool)> {
    let mut idx = patches.len();
    let mut replace = false;

    for (i, (other, _)) in patches.iter().enumerate() {
        if range == other {
            return None;
        } else if range.start < other.start {
            if range.end <= other.end {
                idx = i;
            } else {
                panic!("{range:?} and {other:?} overlaps");
            }
        } else if range.start < other.end {
            if range.end <= other.end {
                idx = i;
                replace = true;
            } else {
                panic!("{range:?} and {other:?} overlaps");
            }
        } else {
            break;
        }
    }

    Some((idx, replace))
}

pub(crate) fn add_patch(
    patches: &mut Vec<(Range<usize>, PathBuf)>,
    (idx, replace): (usize, bool),
    range: Range<usize>,
    path: PathBuf,
) {
    if replace {
        patches[idx] = (range, path);
    } else {
        patches.insert(idx, (range, path));
    }
}