Skip to content

Commit e975b75

Browse files
committed
Implemented git-worktree
1 parent 28e3251 commit e975b75

File tree

7 files changed

+282
-0
lines changed

7 files changed

+282
-0
lines changed

Cargo.lock

+10
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

git-index/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ mod access {
2222
pub fn entries(&self) -> &[Entry] {
2323
&self.entries
2424
}
25+
26+
pub fn entries_mut(&mut self) -> &mut [Entry] {
27+
&mut self.entries
28+
}
2529
}
2630
}
2731

git-worktree/Cargo.toml

+10
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,13 @@ doctest = false
1313
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
1414

1515
[dependencies]
16+
git-index = { version = "^0.1.0", path = "../git-index" }
17+
quick-error = "2.0.1"
18+
git-hash = { version = "^0.9.0", path = "../git-hash" }
19+
git-object = { version = "^0.17.0", path = "../git-object" }
20+
21+
[dev-dependencies]
22+
git-odb = { path = "../git-odb" }
23+
walkdir = "2.3.2"
24+
git-testtools = { path = "../tests/tools" }
25+
tempfile = "3.2.0"

git-worktree/src/lib.rs

+125
Original file line numberDiff line numberDiff line change
@@ -1 +1,126 @@
11
#![forbid(unsafe_code, rust_2018_idioms)]
2+
//! Git Worktree
3+
4+
use git_hash::oid;
5+
use git_object::bstr::ByteSlice;
6+
use quick_error::quick_error;
7+
use std::convert::TryFrom;
8+
use std::fs;
9+
use std::fs::create_dir_all;
10+
use std::path::Path;
11+
use std::time::Duration;
12+
13+
#[cfg(unix)]
14+
use std::os::unix::fs::PermissionsExt;
15+
16+
quick_error! {
17+
#[derive(Debug)]
18+
pub enum Error {
19+
Utf8Error(err: git_object::bstr::Utf8Error) {
20+
from()
21+
display("Could not convert path to UTF8: {}", err)
22+
}
23+
TimeError(err: std::time::SystemTimeError) {
24+
from()
25+
display("Could not read file time in proper format: {}", err)
26+
}
27+
ToU32Error(err: std::num::TryFromIntError) {
28+
from()
29+
display("Could not convert seconds to u32: {}", err)
30+
}
31+
IoError(err: std::io::Error) {
32+
from()
33+
display("IO Error: {}", err)
34+
}
35+
}
36+
}
37+
38+
/// Copy index to `path`
39+
pub fn copy_index<P, Find>(state: &mut git_index::State, path: P, mut find: Find, opts: Options) -> Result<(), Error>
40+
where
41+
P: AsRef<Path>,
42+
Find: for<'a> FnMut(&oid, &'a mut Vec<u8>) -> Option<git_object::BlobRef<'a>>,
43+
{
44+
let path = path.as_ref();
45+
let mut buf = Vec::new();
46+
let mut entry_time = Vec::new(); // Entries whose timestamps have to be updated
47+
for (i, entry) in state.entries().iter().enumerate() {
48+
if entry.flags.contains(git_index::entry::Flags::SKIP_WORKTREE) {
49+
continue;
50+
}
51+
let dest = path.join(entry.path(state).to_path()?);
52+
create_dir_all(dest.parent().expect("path is empty"))?;
53+
match entry.mode {
54+
git_index::entry::Mode::FILE | git_index::entry::Mode::FILE_EXECUTABLE => {
55+
let obj = find(&entry.id, &mut buf).unwrap();
56+
std::fs::write(&dest, obj.data)?;
57+
if entry.mode == git_index::entry::Mode::FILE_EXECUTABLE {
58+
#[cfg(unix)]
59+
fs::set_permissions(&dest, fs::Permissions::from_mode(0o777)).unwrap();
60+
}
61+
let met = std::fs::symlink_metadata(&dest)?;
62+
// Set both fields to mtime if ctime is not present and vice-versa
63+
// If both fields are not present, will raise an Err
64+
let ctime = met
65+
.created()
66+
.map_or(Ok(Duration::from_secs(0)), |x| x.duration_since(std::time::UNIX_EPOCH));
67+
let mtime = met
68+
.modified()
69+
.map_or(Ok(Duration::from_secs(0)), |x| x.duration_since(std::time::UNIX_EPOCH));
70+
entry_time.push((ctime?, mtime?, i));
71+
}
72+
git_index::entry::Mode::SYMLINK => {
73+
let obj = find(&entry.id, &mut buf).unwrap();
74+
let linked_to = obj.data.to_path()?;
75+
if opts.symlinks {
76+
#[cfg(unix)]
77+
std::os::unix::fs::symlink(linked_to, &dest)?;
78+
#[cfg(windows)]
79+
if dest.exists() {
80+
if dest.is_file() {
81+
std::os::windows::fs::symlink_file(linked_to, &dest)?;
82+
} else {
83+
std::os::windows::fs::symlink_dir(linked_to, &dest)?;
84+
}
85+
}
86+
} else {
87+
std::fs::write(&dest, obj.data)?;
88+
}
89+
let met = std::fs::symlink_metadata(&dest)?;
90+
// Set both fields to mtime if ctime is not present and vice-versa
91+
// If both fields are not present, will raise an Err
92+
let ctime = met
93+
.created()
94+
.map_or(Ok(Duration::from_secs(0)), |x| x.duration_since(std::time::UNIX_EPOCH));
95+
let mtime = met
96+
.modified()
97+
.map_or(Ok(Duration::from_secs(0)), |x| x.duration_since(std::time::UNIX_EPOCH));
98+
entry_time.push((ctime?, mtime?, i));
99+
}
100+
git_index::entry::Mode::DIR => todo!(),
101+
git_index::entry::Mode::COMMIT => todo!(),
102+
_ => unreachable!(),
103+
}
104+
}
105+
let entries = state.entries_mut();
106+
for (ctime, mtime, i) in entry_time {
107+
let stat = &mut entries[i].stat;
108+
stat.mtime.secs = u32::try_from(mtime.as_secs())?;
109+
stat.mtime.nsecs = mtime.subsec_nanos();
110+
stat.ctime.secs = u32::try_from(ctime.as_secs())?;
111+
stat.ctime.nsecs = ctime.subsec_nanos();
112+
}
113+
Ok(())
114+
}
115+
116+
/// Options for [copy_index](crate::copy_index)
117+
pub struct Options {
118+
/// Enable/disable symlinks
119+
pub symlinks: bool,
120+
}
121+
122+
impl Default for Options {
123+
fn default() -> Self {
124+
Options { symlinks: true }
125+
}
126+
}

git-worktree/tests/copy_index/mod.rs

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
use crate::{dir_structure, fixture_path};
2+
use git_object::bstr::ByteSlice;
3+
use git_odb::FindExt;
4+
use git_worktree::{copy_index, Options};
5+
use std::fs;
6+
7+
#[cfg(unix)]
8+
use std::os::unix::prelude::MetadataExt;
9+
10+
type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;
11+
12+
#[test]
13+
fn test_copy_index() -> Result<()> {
14+
let path = fixture_path("make_repo");
15+
let path_git = path.join(".git");
16+
let mut file = git_index::File::at(path_git.join("index"), git_index::decode::Options::default())?;
17+
let output_dir = tempfile::tempdir()?;
18+
let output = output_dir.path();
19+
let odb_handle = git_odb::at(path_git.join("objects")).unwrap();
20+
21+
copy_index(
22+
&mut file,
23+
&output,
24+
move |oid, buf| {
25+
odb_handle
26+
.find(oid, buf)
27+
.ok()
28+
.map(|x| git_object::BlobRef::from_bytes(x.data).unwrap())
29+
},
30+
Options::default(),
31+
)?;
32+
33+
let repo_files = dir_structure(&path);
34+
let copy_files = dir_structure(output);
35+
36+
let srepo_files: Vec<_> = repo_files.iter().flat_map(|p| p.strip_prefix(&path)).collect();
37+
let scopy_files: Vec<_> = copy_files.iter().flat_map(|p| p.strip_prefix(output)).collect();
38+
assert!(srepo_files == scopy_files);
39+
40+
for (file1, file2) in repo_files.iter().zip(copy_files.iter()) {
41+
assert!(fs::read(file1)? == fs::read(file2)?);
42+
#[cfg(unix)]
43+
assert!(fs::symlink_metadata(file1)?.mode() & 0b111 << 6 == fs::symlink_metadata(file2)?.mode() & 0b111 << 6);
44+
}
45+
46+
Ok(())
47+
}
48+
49+
#[test]
50+
fn test_copy_index_without_symlinks() -> Result<()> {
51+
let path = fixture_path("make_repo");
52+
let path_git = path.join(".git");
53+
let mut file = git_index::File::at(path_git.join("index"), git_index::decode::Options::default())?;
54+
let output_dir = tempfile::tempdir()?;
55+
let output = output_dir.path();
56+
let odb_handle = git_odb::at(path_git.join("objects")).unwrap();
57+
58+
copy_index(
59+
&mut file,
60+
&output,
61+
move |oid, buf| {
62+
odb_handle
63+
.find(oid, buf)
64+
.ok()
65+
.map(|x| git_object::BlobRef::from_bytes(x.data).unwrap())
66+
},
67+
Options { symlinks: false },
68+
)?;
69+
70+
let repo_files = dir_structure(&path);
71+
let copy_files = dir_structure(output);
72+
73+
let srepo_files: Vec<_> = repo_files.iter().flat_map(|p| p.strip_prefix(&path)).collect();
74+
let scopy_files: Vec<_> = copy_files.iter().flat_map(|p| p.strip_prefix(output)).collect();
75+
assert!(srepo_files == scopy_files);
76+
77+
for (file1, file2) in repo_files.iter().zip(copy_files.iter()) {
78+
if file1.is_symlink() {
79+
assert!(!file2.is_symlink());
80+
assert!(fs::read(file2)?.to_path()? == fs::read_link(file1)?);
81+
} else {
82+
assert!(fs::read(file1)? == fs::read(file2)?);
83+
#[cfg(unix)]
84+
assert!(
85+
fs::symlink_metadata(file1)?.mode() & 0b111 << 6 == fs::symlink_metadata(file2)?.mode() & 0b111 << 6
86+
);
87+
}
88+
}
89+
90+
Ok(())
91+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#!/bin/bash
2+
set -eu -o pipefail
3+
4+
git init -q
5+
6+
touch a
7+
echo "Test Vals" > a
8+
touch b
9+
touch c
10+
touch executable.sh
11+
chmod +x executable.sh
12+
13+
mkdir d
14+
touch d/a
15+
echo "Subdir" > d/a
16+
ln -sf d/a sa
17+
18+
git add -A
19+
git commit -m "Commit"

git-worktree/tests/mod.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use std::path::{Path, PathBuf};
2+
use walkdir::WalkDir;
3+
4+
mod copy_index;
5+
6+
pub fn dir_structure<P: AsRef<Path>>(path: P) -> Vec<PathBuf> {
7+
let path = path.as_ref();
8+
let mut ps: Vec<_> = WalkDir::new(path)
9+
.into_iter()
10+
.filter_entry(|e| e.path() == path || !e.file_name().to_str().map(|s| s.starts_with('.')).unwrap_or(false))
11+
.flatten()
12+
.filter(|e| e.path().is_file())
13+
.map(|p| p.path().to_path_buf())
14+
.collect();
15+
ps.sort();
16+
ps
17+
}
18+
19+
pub fn fixture_path(name: &str) -> PathBuf {
20+
let dir =
21+
git_testtools::scripted_fixture_repo_read_only(Path::new(name).with_extension("sh")).expect("script works");
22+
dir
23+
}

0 commit comments

Comments
 (0)