Skip to content

Commit 379c351

Browse files
committed
Search upward if path not exist when cargo new
Signed-off-by: hi-rustin <[email protected]>
1 parent 8494149 commit 379c351

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/cargo/util/vcs.rs

+11-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,17 @@ use std::path::Path;
1010
// 2. We are in an HG repo.
1111
pub fn existing_vcs_repo(path: &Path, cwd: &Path) -> bool {
1212
fn in_git_repo(path: &Path, cwd: &Path) -> bool {
13-
if let Ok(repo) = GitRepo::discover(path, cwd) {
13+
// Try to find the first existing parent of the path.
14+
// Otherwise, we can't find the git repo when the path has non-existing parent directories.
15+
let mut first_exist_base_path = Some(path);
16+
while let Some(p) = first_exist_base_path {
17+
if p.exists() {
18+
break;
19+
}
20+
first_exist_base_path = p.parent();
21+
}
22+
23+
if let Ok(repo) = GitRepo::discover(first_exist_base_path.unwrap_or(path), cwd) {
1424
// Don't check if the working directory itself is ignored.
1525
if repo.workdir().map_or(false, |workdir| workdir == path) {
1626
true

tests/testsuite/new.rs

+37
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,43 @@ fn subpackage_git_with_gitignore() {
301301
.is_file());
302302
}
303303

304+
#[cargo_test]
305+
fn subpackage_no_git_with_git_in_ancestor() {
306+
cargo_process("new foo").run();
307+
308+
assert!(paths::root().join("foo/.git").is_dir());
309+
assert!(paths::root().join("foo/.gitignore").is_file());
310+
311+
cargo_process("new foo/non-existent/subcomponent").run();
312+
313+
assert!(!paths::root()
314+
.join("foo/non-existent/subcomponent/.git")
315+
.is_dir());
316+
assert!(!paths::root()
317+
.join("foo/non-existent/subcomponent/.gitignore")
318+
.is_file());
319+
}
320+
321+
#[cargo_test]
322+
fn subpackage_git_with_gitignore_in_ancestor() {
323+
cargo_process("new foo").run();
324+
325+
assert!(paths::root().join("foo/.git").is_dir());
326+
assert!(paths::root().join("foo/.gitignore").is_file());
327+
328+
let gitignore = paths::root().join("foo/.gitignore");
329+
fs::write(gitignore, b"non-existent").unwrap();
330+
331+
cargo_process("new foo/non-existent/subcomponent").run();
332+
333+
assert!(paths::root()
334+
.join("foo/non-existent/subcomponent/.git")
335+
.is_dir());
336+
assert!(paths::root()
337+
.join("foo/non-existent/subcomponent/.gitignore")
338+
.is_file());
339+
}
340+
304341
#[cargo_test]
305342
fn subpackage_git_with_vcs_arg() {
306343
cargo_process("new foo").run();

0 commit comments

Comments
 (0)