diff --git a/R/git_tools.R b/R/git_tools.R index 9422cf7..b7ef0af 100644 --- a/R/git_tools.R +++ b/R/git_tools.R @@ -184,15 +184,25 @@ install_external_deps <- function(repo_dir, internal_pkg_deps, ...) { # function to get the remote name (e.g. origin) which matches # the url given in the staged.deps yaml file get_remote_name <- function(git_repo, repo_url) { + + # remove the https:// and .git from repo_url + repo_url <- gsub("^.+://|.git$", "", repo_url, perl = TRUE) + + remotes <- git2r::remotes(git_repo) + for (remote in remotes) { + target_url <- git2r::remote_url(git_repo, remote = remote) - #sometimes git2r remote_url includes .git in remote_url sometimes does not - if (repo_url == target_url || repo_url == paste0(target_url, ".git")) { + target_url <- gsub("^(https://|git@ssh.|git@)|\\.git$", "", target_url) + target_url <- gsub(":", "/", target_url, fixed = TRUE) + + if (repo_url == target_url) { return(remote) } } - stop("Cannot determine remote") + # by default return origin + return("origin") } diff --git a/tests/testthat/test-git_tools_mocking.R b/tests/testthat/test-git_tools_mocking.R index d08dc9f..daa6e53 100644 --- a/tests/testthat/test-git_tools_mocking.R +++ b/tests/testthat/test-git_tools_mocking.R @@ -18,7 +18,6 @@ test_that("checkout_repo with mocking works", { # delete other local branches local_branches <- git2r::branches(repo_dir, flags = "local") lapply(local_branches[names(local_branches) != "main"], git2r::branch_delete) - git2r::remote_set_url(repo_dir, name = "origin", url = url) git2r::repository(local_path) }) @@ -27,6 +26,8 @@ test_that("checkout_repo with mocking works", { invisible(NULL) }) + mockery::stub(checkout_repo, 'get_remote_name', function(...) "origin") + with_tmp_cachedir({ repo_dir <- file.path(tempfile(), "stageddeps.food") @@ -76,3 +77,28 @@ test_that("check_only_remote_branches works", { regexp = "remote_name", fixed = TRUE ) }) + + +test_that("get_remote_name provides remote name of repo",{ + + mockery::stub(get_remote_name, 'git2r::remote_url', function(git_repo, remote){ + switch(remote, + A = "git@ssh.github.com:x/y.git", + B = "git@github.com:w/v.git", + C = "https://github.com/k/l/m", + D = "https://github.com/a/b.git", + origin = "https://github.com/xxx/c.git" + ) + }) + + + mockery::stub(get_remote_name, 'git2r::remotes', function(git_repo) c("origin", "A", "B", "C", "D")) + expect_equal(get_remote_name(".", "https://github.com/x/y.git"), "A") + expect_equal(get_remote_name(".", "https://github.com/w/v.git"), "B") + expect_equal(get_remote_name(".", "https://github.com/k/l/m.git"), "C") + expect_equal(get_remote_name(".", "https://github.com/a/b.git"), "D") + expect_equal(get_remote_name(".", "https://other.git"), "origin") + + +}) +