Skip to content

fix(forge): init a git repo at root during init unless explicitely stated #9695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/cli/src/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,10 @@ impl<'a> Git<'a> {
self.cmd().args(["rev-parse", "--is-inside-work-tree"]).status().map(|s| s.success())
}

pub fn is_repo_root(self) -> Result<bool> {
self.cmd().args(["rev-parse", "--show-cdup"]).exec().map(|out| out.stdout.is_empty())
}

pub fn is_clean(self) -> Result<bool> {
self.cmd().args(["status", "--porcelain"]).exec().map(|out| out.stdout.is_empty())
}
Expand Down
22 changes: 17 additions & 5 deletions crates/forge/bin/cmd/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,18 @@ pub struct InitArgs {
#[arg(long, conflicts_with = "template")]
pub vscode: bool,

/// Use the parent git repository instead of initializing a new one.
/// Only valid if the target is in a git repository.
#[arg(long, conflicts_with = "template")]
pub use_parent_git: bool,

#[command(flatten)]
pub install: DependencyInstallOpts,
}

impl InitArgs {
pub fn run(self) -> Result<()> {
let Self { root, template, branch, install, offline, force, vscode } = self;
let Self { root, template, branch, install, offline, force, vscode, use_parent_git } = self;
let DependencyInstallOpts { shallow, no_git, no_commit } = install;

// create the root dir if it does not exist
Expand Down Expand Up @@ -138,7 +143,7 @@ impl InitArgs {

// set up the repo
if !no_git {
init_git_repo(git, no_commit)?;
init_git_repo(git, no_commit, use_parent_git)?;
}

// install forge-std
Expand All @@ -163,15 +168,22 @@ impl InitArgs {
}
}

/// Initialises `root` as a git repository, if it isn't one already.
/// Initialises `root` as a git repository, if it isn't one already, unless 'use_parent_git' is
/// true.
///
/// Creates `.gitignore` and `.github/workflows/test.yml`, if they don't exist already.
///
/// Commits everything in `root` if `no_commit` is false.
fn init_git_repo(git: Git<'_>, no_commit: bool) -> Result<()> {
/// Commits everything if `no_commit` is false.
fn init_git_repo(git: Git<'_>, no_commit: bool, use_parent_git: bool) -> Result<()> {
// git init
// if not in a git repo, initialize one
if !git.is_in_repo()? {
git.init()?;
} else {
// if target is not the repo root init a new one unless `use_parent_git` is true
if !git.is_repo_root()? && !use_parent_git {
git.init()?;
}
}

// .gitignore
Expand Down
47 changes: 47 additions & 0 deletions crates/forge/tests/cli/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,53 @@ Warning: Target directory is not empty, but `--force` was specified
assert_eq!(gitignore, "not foundry .gitignore");
});

// `forge init --use-parent-git` works on already initialized git repository
forgetest!(can_init_using_parent_repo, |prj, cmd| {
let root = prj.root();

// initialize new git repo
let status = Command::new("git")
.arg("init")
.current_dir(root)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("could not run git init");
assert!(status.success());
assert!(root.join(".git").exists());

prj.create_file("README.md", "non-empty dir");
prj.create_file(".gitignore", "not foundry .gitignore");

let folder = "foundry-folder";
cmd.arg("init").arg(folder).arg("--force").arg("--use-parent-git").assert_success().stdout_eq(
str![[r#"
Initializing [..]...
Installing forge-std in [..] (url: Some("https://github.com/foundry-rs/forge-std"), tag: None)
Installed forge-std[..]
Initialized forge project

"#]],
);

assert!(root.join(folder).join("lib/forge-std").exists());

// not overwritten
let gitignore = root.join(".gitignore");
let gitignore = fs::read_to_string(gitignore).unwrap();
assert_eq!(gitignore, "not foundry .gitignore");

// submodules are registered at root
let gitmodules = root.join(".gitmodules");
let gitmodules = fs::read_to_string(gitmodules).unwrap();
assert!(gitmodules.contains(
"
path = foundry-folder/lib/forge-std
url = https://github.com/foundry-rs/forge-std
"
));
});

Comment on lines +540 to +550
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@0xvv

I'm not sure how this fixes #3962 since the top-level .gitmodules file is still being modified even though you've created a subfolder in which the project resides, i.e., the foundry folder.

The core issue here concerns how git submodules work and how .gitmodules must always be at the git root. Not sure if this is feasible since it would break git submodule command that keeps the .gitmodules file updated and always assumes it's at the root-level.

See: https://git-scm.com/docs/gitsubmodules and https://git-scm.com/docs/gitmodules.

Maybe I'm missing something.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@0xvv did you get the chance to take a look at this? ^^

Copy link
Contributor Author

@0xvv 0xvv Apr 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yash-atreya I think I don't understand your point.
I changed the default behavior to not modify the parent .gitmodules, which is the behavior in other comparable tools and fixes #3962. The .gitmodules thus resides at the root of the newly created forge repo with the new dependencies as expected even if already contained in a git repository. The newly created forge repo can then become a module of the parent git repo.

And I added the option to use an existing parent repo and .gitmodules if we are already in a git repository. Again the modules are declared at the root of the repository that contains the forge, it's just n levels above the forge folder. This is the existing behavior which I think we should move away from as a more modular approach seems better suited to me here but I left it as an option for flexibility and legacy behavior support.

I don't think this would prevent anything regarding submodules management because either way you would be at the root of the git repository.

Let me know if I'm missing anything

// Checks that remappings.txt and .vscode/settings.json is generated
forgetest!(can_init_vscode, |prj, cmd| {
prj.wipe();
Expand Down