summaryrefslogtreecommitdiffstats
path: root/asyncgit/src/sync/hunks.rs
blob: fd77d7727a7940634104858cc8c590ea4c644c30 (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
use super::{
    diff::{get_diff_raw, HunkHeader},
    utils::repo,
};
use crate::{
    error::{Error, Result},
    hash,
};
use git2::{ApplyLocation, ApplyOptions, Diff};
use scopetime::scope_time;

///
pub fn stage_hunk(
    repo_path: &str,
    file_path: &str,
    hunk_hash: u64,
) -> Result<()> {
    scope_time!("stage_hunk");

    let repo = repo(repo_path)?;

    let diff = get_diff_raw(&repo, file_path, false, false, None)?;

    let mut opt = ApplyOptions::new();
    opt.hunk_callback(|hunk| {
        hunk.map_or(false, |hunk| {
            let header = HunkHeader::from(hunk);
            hash(&header) == hunk_hash
        })
    });

    repo.apply(&diff, ApplyLocation::Index, Some(&mut opt))?;

    Ok(())
}

/// this will fail for an all untracked file
pub fn reset_hunk(
    repo_path: &str,
    file_path: &str,
    hunk_hash: u64,
) -> Result<()> {
    scope_time!("reset_hunk");

    let repo = repo(repo_path)?;

    let diff = get_diff_raw(&repo, file_path, false, false, None)?;

    let hunk_index = find_hunk_index(&diff, hunk_hash);
    if let Some(hunk_index) = hunk_index {
        let mut hunk_idx = 0;
        let mut opt = ApplyOptions::new();
        opt.hunk_callback(|_hunk| {
            let res = hunk_idx == hunk_index;
            hunk_idx += 1;
            res
        });

        let diff = get_diff_raw(&repo, file_path, false, true, None)?;

        repo.apply(&diff, ApplyLocation::WorkDir, Some(&mut opt))?;

        Ok(())
    } else {
        Err(Error::Generic("hunk not found".to_string()))
    }
}

fn find_hunk_index(diff: &Diff, hunk_hash: u64) -> Option<usize> {
    let mut result = None;

    let mut hunk_count = 0;

    let foreach_result = diff.foreach(
        &mut |_, _| true,
        None,
        Some(&mut |_, hunk| {
            let header = HunkHeader::from(hunk);
            if hash(&header) == hunk_hash {
                result = Some(hunk_count);
            }
            hunk_count += 1;
            true
        }),
        None,
    );

    if foreach_result.is_ok() {
        result
    } else {
        None
    }
}

///
pub fn unstage_hunk(
    repo_path: &str,
    file_path: &str,
    hunk_hash: u64,
) -> Result<bool> {
    scope_time!("revert_hunk");

    let repo = repo(repo_path)?;

    let diff = get_diff_raw(&repo, file_path, true, false, None)?;
    let diff_count_positive = diff.deltas().len();

    let hunk_index = find_hunk_index(&diff, hunk_hash);
    let hunk_index = hunk_index.map_or_else(
        || Err(Error::Generic("hunk not found".to_string())),
        Ok,
    )?;

    let diff = get_diff_raw(&repo, file_path, true, true, None)?;

    if diff.deltas().len() != diff_count_positive {
        return Err(Error::Generic(format!(
            "hunk error: {}!={}",
            diff.deltas().len(),
            diff_count_positive
        )));
    }

    let mut count = 0;
    {
        let mut hunk_idx = 0;
        let mut opt = ApplyOptions::new();
        opt.hunk_callback(|_hunk| {
            let res = if hunk_idx == hunk_index {
                count += 1;
                true
            } else {
                false
            };

            hunk_idx += 1;

            res
        });

        repo.apply(&diff, ApplyLocation::Index, Some(&mut opt))?;
    }

    Ok(count == 1)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        error::Result,
        sync::{diff::get_diff, tests::repo_init_empty},
    };
    use std::{
        fs::{self, File},
        io::Write,
        path::Path,
    };

    #[test]
    fn reset_untracked_file_which_will_not_find_hunk() -> Result<()> {
        let file_path = Path::new("foo/foo.txt");
        let (_td, repo) = repo_init_empty()?;
        let root = repo.path().parent().unwrap();
        let repo_path = root.as_os_str().to_str().unwrap();

        let sub_path = root.join("foo/");

        fs::create_dir_all(&sub_path)?;
        File::create(&root.join(file_path))?.write_all(b"test")?;

        let diff = get_diff(
            sub_path.to_str().unwrap(),
            file_path.to_str().unwrap(),
            false,
        )?;

        assert!(reset_hunk(
            repo_path,
            file_path.to_str().unwrap(),
            diff.hunks[0].header_hash,
        )
        .is_err());

        Ok(())
    }
}