git: extract add_remote() function, and map git2::Error there

I'm going to add check for remote named "git" there.
This commit is contained in:
Yuya Nishihara 2023-08-19 13:46:30 +09:00
parent 61172b1c1e
commit c5b6e9705d
3 changed files with 45 additions and 6 deletions

View file

@ -251,12 +251,7 @@ fn cmd_git_remote_add(
let workspace_command = command.workspace_helper(ui)?;
let repo = workspace_command.repo();
let git_repo = get_git_repo(repo.store())?;
if git_repo.find_remote(&args.remote).is_ok() {
return Err(user_error("Remote already exists"));
}
git_repo
.remote(&args.remote, &args.url)
.map_err(|err| user_error(err.to_string()))?;
git::add_remote(&git_repo, &args.remote, &args.url)?;
Ok(())
}

View file

@ -51,6 +51,35 @@ fn test_git_remotes() {
"###);
}
#[test]
fn test_git_remote_add() {
let test_env = TestEnvironment::default();
test_env.jj_cmd_success(test_env.env_root(), &["init", "--git", "repo"]);
let repo_path = test_env.env_root().join("repo");
test_env.jj_cmd_success(
&repo_path,
&["git", "remote", "add", "foo", "http://example.com/repo/foo"],
);
let stderr = test_env.jj_cmd_failure(
&repo_path,
&[
"git",
"remote",
"add",
"foo",
"http://example.com/repo/foo2",
],
);
insta::assert_snapshot!(stderr, @r###"
Error: Git remote named 'foo' already exists
"###);
let stdout = test_env.jj_cmd_success(&repo_path, &["git", "remote", "list"]);
insta::assert_snapshot!(stdout, @r###"
foo http://example.com/repo/foo
"###);
}
#[test]
fn test_git_remote_rename() {
let test_env = TestEnvironment::default();

View file

@ -575,6 +575,21 @@ fn is_remote_exists_err(err: &git2::Error) -> bool {
)
}
pub fn add_remote(
git_repo: &git2::Repository,
remote_name: &str,
url: &str,
) -> Result<(), GitRemoteManagementError> {
git_repo.remote(remote_name, url).map_err(|err| {
if is_remote_exists_err(&err) {
GitRemoteManagementError::RemoteAlreadyExists(remote_name.to_owned())
} else {
GitRemoteManagementError::InternalGitError(err)
}
})?;
Ok(())
}
pub fn remove_remote(
mut_repo: &mut MutableRepo,
git_repo: &git2::Repository,