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
// Copyright 2020 Andreas Kurth
//
// SPDX-License-Identifier: (Apache-2.0 OR MIT)

//! Git API

use crate::error::{Error, Result};
use crate::util::trim_newline;
use derivative::Derivative;
use log::trace;
use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Display, Formatter};
use std::path::{Path, PathBuf};
use std::process::Command;

/// A Git object identifier.
pub type Oid = String; // TODO: better Oid?

/// A Git repository.
#[derive(Derivative)]
#[derivative(PartialEq, Hash, Eq, Debug)]
pub struct Repo {
    pub path: PathBuf,
    #[derivative(PartialEq = "ignore", Hash = "ignore", Debug = "ignore")]
    ancestry_cache: RefCell<HashMap<(Oid, Oid), bool>>,
}

/// A Git object.
#[derive(PartialEq, Hash, Eq, Debug, Clone)]
pub struct Object<'a> {
    pub oid: Oid,
    pub repo: &'a Repo,
}

fn path_str(path: &Path) -> &str {
    path.to_str()
        .expect(&format!("could not convert path {:?} to string", path))
}

impl Repo {
    /// Creates a Repo object for a path.
    pub fn new(path: PathBuf) -> Repo {
        Repo {
            path,
            ancestry_cache: RefCell::new(HashMap::new()),
        }
    }

    /// Creates a Git command on this repository.
    pub fn cmd(&self, cmd: &str) -> Command {
        let mut tmp = Command::new("git");
        tmp.current_dir(&self.path);
        tmp.arg(cmd);
        tmp
    }

    /// Returns the standard output of a Git command on this repository if the command succeeds.
    /// Returns `None` if the command completes with non-zero exit code.
    pub fn cmd_output(&self, params: &[&str]) -> Option<String> {
        if params.len() == 0 {
            unreachable!("`cmd_output' invoked without parameters!");
        }
        let mut cmd = self.cmd(params[0]);
        for p in &params[1..] {
            cmd.arg(p);
        }
        let cmd_str = format!("git {}", params.join(" "));
        trace!("{}", cmd_str);
        let output = cmd
            .output()
            .expect(&format!("could not get output of `{}'!", cmd_str));
        trace!("{:?}", output);
        if output.status.success() {
            Some(trim_newline(String::from_utf8(output.stdout).expect(
                &format!("output of `{}' contains non-UTF8 characters!", cmd_str),
            )))
        } else {
            None
        }
    }

    /// Returns the last commit modifying `path`.  Returns `None` if there is no such commit.
    pub fn last_commit_on_path(&self, path: &Path) -> Option<Object> {
        self.cmd_output(&["log", "-n", "1", "--pretty=format:%H", "--", path_str(path)])
            .and_then(|s| {
                if s.is_empty() {
                    None
                } else {
                    Some(Object::new(s, self))
                }
            })
    }

    /// Returns the first of a set of objects according to a given ordering.  Returns an error if
    /// the set is empty or any two of the objects are incomparable.
    fn first_ordered_object<'a>(
        &'a self,
        objects: &'a HashSet<Object<'a>>,
        ord: Ordering,
    ) -> Result<&'a Object> {
        if objects.len() == 0 {
            return Error::result("no objects given");
        }
        if objects.len() == 1 {
            return Ok(objects.iter().next().unwrap());
        }
        let mut iter = objects.iter();
        objects
            .iter()
            .try_fold(iter.next().unwrap(), |youngest, obj| {
                match obj.partial_cmp(&youngest) {
                    Some(o) => {
                        if o == ord {
                            Ok(obj)
                        } else {
                            Ok(youngest)
                        }
                    }
                    None => Error::result(format!("{:?} and {:?} are incomparable", youngest, obj)),
                }
            })
    }

    /// Returns the youngest (= furthest from root) of a set of objects.  Returns an error if the
    /// set is empty or any two of the objects are incomparable.
    pub fn youngest_object<'a>(&'a self, objects: &'a HashSet<Object<'a>>) -> Result<&'a Object> {
        self.first_ordered_object(objects, Ordering::Less)
    }

    /// Returns the oldest (= closest to root) of a set of objects.  Returns an error if the set is
    /// empty or any of two of the objects are incomparable.
    pub fn oldest_object<'a>(&'a self, objects: &'a HashSet<Object<'a>>) -> Result<&'a Object> {
        self.first_ordered_object(objects, Ordering::Greater)
    }

    /// Determine the oldest common descendant of a set of objects on the current branch.  Returns
    /// an error if any two of the objects do not have a common descendant.
    pub fn oldest_common_descendant_on_current_branch<'a>(
        &'a self,
        objects: &'a HashSet<Object<'a>>,
    ) -> Result<Object<'a>> {
        if objects.len() == 0 {
            return Error::result("no objects given");
        }
        let youngest_object = self.youngest_object(&objects);
        if youngest_object.is_ok() {
            return youngest_object.map(|obj| obj.clone());
        }
        let mut descendants = objects.iter().map(|obj| {
            obj.descendants_on_current_branch()
                .iter()
                .map(|obj| Object::new(obj.oid.clone(), &self))
                .collect::<HashSet<_>>()
        });
        let intersection: HashSet<Object> = descendants
            .next()
            .map(|set| descendants.fold(set, |set1, set2| &set1 & &set2))
            .unwrap_or_default();
        let oldest_descendant = self.oldest_object(&intersection);
        oldest_descendant.map(|obj| Object::new(obj.oid.clone(), &self))
    }

    fn object_is_ancestor_of(&self, ancestor: &Object, other: &Object) -> bool {
        let key = (ancestor.oid.clone(), other.oid.clone());
        if let Some(entry) = self.ancestry_cache.borrow().get(&key) {
            return *entry;
        }
        let output = self.cmd_output(&[
            "rev-list",
            "--ancestry-path",
            &format!("{}..{}", ancestor.oid, other.oid),
        ]);
        let entry = match output {
            None => false,
            Some(s) => s.len() > 0,
        };
        self.ancestry_cache.borrow_mut().insert(key, entry);
        entry
    }
}

impl<'a> Display for Object<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.oid)
    }
}

impl<'a> PartialOrd for Object<'a> {
    fn partial_cmp(&self, other: &Object) -> Option<Ordering> {
        if self == other {
            return Some(Ordering::Equal);
        } else if self.is_descendant_of(other) {
            return Some(Ordering::Less);
        } else if self.is_ancestor_of(other) {
            return Some(Ordering::Greater);
        } else {
            return None; // incomparable
        }
    }
}

impl<'a> Object<'a> {
    pub fn new(oid: Oid, repo: &'a Repo) -> Object<'a> {
        Object {
            oid: oid,
            repo: repo,
        }
    }

    pub fn is_ancestor_of(&self, obj: &Object) -> bool {
        if self.repo != obj.repo {
            return false;
        }
        self.repo.object_is_ancestor_of(&self, obj)
    }

    pub fn is_descendant_of(&self, obj: &Object) -> bool {
        obj.is_ancestor_of(self)
    }

    pub fn path_is_same_as(&self, ancestor: &Object, path: &Path) -> bool {
        if self.repo != ancestor.repo {
            return false;
        }
        // TODO: need to relativize path?
        let output = self.repo.cmd_output(&[
            "diff",
            "--quiet",
            &format!("{}..{}", ancestor.oid, self.oid),
            "--",
            path_str(path),
        ]);
        output.is_some()
    }

    /// Get descendants of this commit on the current branch, in chronological order.
    fn descendants_on_current_branch(&self) -> Vec<Object<'a>> {
        match self.repo.cmd_output(&[
            "rev-list",
            "--ancestry-path",
            "--reverse",
            &format!("{}..", self.oid),
        ]) {
            Some(s) => s
                .lines()
                .map(|line| Object::new(line.to_string(), self.repo))
                .collect(),
            None => vec![],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::{Error, Result};
    use crate::test_util::{create_file, write_file};
    use maplit::hashset;
    use tempdir::TempDir;

    /// Test helper methods for a Git repository.
    impl Repo {
        fn cmd_assert(&self, params: &[&str]) {
            assert!(
                self.cmd_output(params).is_some(),
                format!("git {}", params.join(" "))
            );
        }
        fn last_commit(&self) -> Option<Object> {
            self.past_commit(0)
        }
        fn past_commit(&self, n_commits_ago: usize) -> Option<Object> {
            self.cmd_output(&["rev-parse", &format!("HEAD~{}", n_commits_ago)])
                .and_then(|oup| oup.lines().next().map(|l| l.to_string()))
                .map(|head_commit| Object::new(head_commit.to_string(), &self))
        }
    }

    fn setup() -> Result<(Repo, TempDir)> {
        let tmp = TempDir::new("memora-test-git")
            .map_err(|cause| Error::chain("Could not create temporary directory:", cause))?;
        let repo = Repo::new(tmp.path().to_path_buf());
        repo.cmd_assert(&["init"]);
        repo.cmd_assert(&["config", "--local", "user.name", "Test"]);
        repo.cmd_assert(&["config", "--local", "user.email", "test@localhost"]);
        Ok((repo, tmp))
    }

    fn setup_with_file(rel_path: &str) -> Result<(Repo, TempDir, std::fs::File)> {
        let (repo, tmp_dir) = setup()?;
        let fp = tmp_dir.path().join(rel_path);
        let file = create_file(fp)?;
        Ok((repo, tmp_dir, file))
    }

    fn rand_string(rng: &mut dyn rand::RngCore, n_chars: usize) -> String {
        use rand::distributions::Alphanumeric;
        use rand::Rng;
        rng.sample_iter(Alphanumeric).take(n_chars).collect()
    }

    fn rand_commits_on_file(repo: &Repo, rel_path: &str, n_commits: usize) -> Result<()> {
        let mut rng = rand::thread_rng();
        let mut file = create_file(repo.path.join(rel_path))?;
        for _i in 0..n_commits {
            write_file(&mut file, &rand_string(&mut rng, 10))?;
            repo.cmd_assert(&["add", rel_path]);
            repo.cmd_assert(&["commit", "-m", &rand_string(&mut rng, 10)]);
        }
        Ok(())
    }

    fn setup_with_commits_on_file(rel_path: &str, n_commits: usize) -> Result<(Repo, TempDir)> {
        let (repo, tmp_dir, _file) = setup_with_file(rel_path)?;
        rand_commits_on_file(&repo, rel_path, n_commits)?;
        Ok((repo, tmp_dir))
    }

    fn create_two_incomparable_commits<'a>(
        repo: &'a Repo,
        path: &str,
    ) -> Result<(Object<'a>, Object<'a>)> {
        repo.cmd_assert(&["checkout", "-b", "some_branch"]);
        rand_commits_on_file(&repo, path, 1)?;
        let some_commit = repo.last_commit().unwrap();
        repo.cmd_assert(&["checkout", "master"]);
        repo.cmd_assert(&["checkout", "-b", "another_branch"]);
        rand_commits_on_file(&repo, path, 1)?;
        let another_commit = repo.last_commit().unwrap();
        Ok((some_commit, another_commit))
    }

    #[test]
    fn last_commit_on_existing_path_with_single_commit() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 1)?;
        let act = repo.last_commit_on_path(Path::new("some_file"));
        assert_eq!(act, repo.last_commit());
        Ok(())
    }

    #[test]
    fn last_commit_on_existing_path_with_no_commit() -> Result<()> {
        let (repo, _tmp_dir, _file) = setup_with_file("some_file")?;
        let act = repo.last_commit_on_path(Path::new("some_file"));
        assert_eq!(act, None);
        Ok(())
    }

    #[test]
    fn last_commit_on_existing_path_with_two_commits() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 2)?;
        let act = repo.last_commit_on_path(Path::new("some_file"));
        assert_eq!(act, repo.last_commit());
        Ok(())
    }

    #[test]
    fn last_commit_on_nonexistent_path() -> Result<()> {
        let (repo, _tmp_dir, _file) = setup_with_file("some_file")?;
        let act = repo.last_commit_on_path(Path::new("some_other_file"));
        assert_eq!(act, None);
        Ok(())
    }

    #[test]
    fn youngest_object_no_commit() -> Result<()> {
        let (repo, _tmp_dir, _file) = setup_with_file("some_file")?;
        assert!(repo.youngest_object(&hashset! {}).is_err());
        Ok(())
    }

    #[test]
    fn youngest_object_single_commit() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 5)?;
        let obj = repo.last_commit().unwrap();
        assert_eq!(repo.youngest_object(&hashset! {obj.clone()}).unwrap(), &obj);
        Ok(())
    }

    #[test]
    fn youngest_object_two_identical_commits() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 7)?;
        let obj = repo.last_commit().unwrap();
        assert_eq!(
            repo.youngest_object(&hashset! {obj.clone(), obj.clone()})
                .unwrap(),
            &obj
        );
        Ok(())
    }

    #[test]
    fn youngest_object_two_different_commits() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 7)?;
        let younger = repo.last_commit().unwrap();
        let older = repo.past_commit(4).unwrap();
        assert_eq!(
            repo.youngest_object(&hashset! {older.clone(), younger.clone()})
                .unwrap(),
            &younger
        );
        assert_eq!(
            repo.youngest_object(&hashset! {younger.clone(), older.clone()})
                .unwrap(),
            &younger
        );
        Ok(())
    }

    #[test]
    fn youngest_object_two_incomparable_commits() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 7)?;
        let (some_commit, another_commit) = create_two_incomparable_commits(&repo, "some_file")?;
        assert!(repo
            .youngest_object(&hashset! {some_commit.clone(), another_commit.clone()})
            .is_err());
        Ok(())
    }

    #[test]
    fn partial_cmp_different_objects() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 5)?;
        let younger = repo.past_commit(1).unwrap();
        let older = repo.past_commit(4).unwrap();
        assert_eq!(younger.partial_cmp(&older), Some(Ordering::Less));
        assert_eq!(older.partial_cmp(&younger), Some(Ordering::Greater));
        Ok(())
    }

    #[test]
    fn partial_cmp_identical_objects() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 5)?;
        let younger = repo.past_commit(1).unwrap();
        assert_eq!(younger.partial_cmp(&younger), Some(Ordering::Equal));
        Ok(())
    }

    #[test]
    fn partial_cmp_incomparable_objects() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 1)?;
        let (some_commit, another_commit) = create_two_incomparable_commits(&repo, "some_file")?;
        assert_eq!(some_commit.partial_cmp(&another_commit), None);
        Ok(())
    }

    #[test]
    fn descendants_on_current_branch() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 5)?;
        let ancestor = repo.past_commit(3).unwrap();
        let descendants = {
            let mut vec = Vec::new();
            for i in (0..3).rev() {
                vec.push(repo.past_commit(i).unwrap());
            }
            vec
        };
        assert_eq!(ancestor.descendants_on_current_branch(), descendants);
        Ok(())
    }

    #[test]
    fn oldest_common_descendant_on_current_branch_with_merge() -> Result<()> {
        let (repo, _tmp_dir) = setup_with_commits_on_file("some_file", 1)?;
        repo.cmd_assert(&["checkout", "-b", "some_branch"]);
        rand_commits_on_file(&repo, "some_file", 2)?;
        let branch_commit = repo.past_commit(1).unwrap();
        repo.cmd_assert(&["checkout", "master"]);
        rand_commits_on_file(&repo, "another_file", 20)?;
        let master_commit = repo.past_commit(10).unwrap();
        repo.cmd_assert(&["merge", "--no-edit", "some_branch"]);
        let merge_commit = repo.last_commit().unwrap();
        rand_commits_on_file(&repo, "some_file", 1)?;
        assert_eq!(
            repo.oldest_common_descendant_on_current_branch(&hashset! {branch_commit.clone(),
            master_commit.clone()})
                .unwrap(),
            merge_commit
        );
        Ok(())
    }
}