Используйте R, чтобы перенаправить локальное репо на github в Windows

Я как-то спросил очень аналогичный вопрос и получил ответ, который работал из командной строки, но теперь я хочу использовать R для автоматизации процесса из Windows (Linux намного легче).

Вот что я пытаюсь сделать:

  • Создайте локальный каталог (или он уже существует)
  • Создайте новое github-репо в облаке с тем же именем, что и локальное (на основе этого ответа)
  • Добавить .git в локальное репо
  • Сделать начальную фиксацию
  • Установить связь между облачным репо и локальным репо
  • Нажмите фиксацию и файлы в локальном репо на github

Я верю на основе вывода, который я добираюсь до шага 5 до того, как я потерпите неудачу (как фиксация и файлы из локального каталог никогда не идет в github в облаке). Я знаю, что шаг 2 работает, потому что пустое репо создано здесь. Я не знаю, как проверить шаг 5. На последнем шаге shell(cmd6, intern = T) RGui и RStudio приводят к вечной спирали смерти. Возникает вопрос: Как я могу нажать фиксацию и локальное репо на облако.

Вот мой обновленный код (единственное, что зависит от пользователя, - это имя пользователя и пароль в третьем блоке кода):

## Create Directory
repo <- "foo5"
dir.create(repo)
project.dir <- file.path(getwd(), repo) 

## Throw a READ.ME in the directory
cat("This is a test", file=file.path(project.dir, "READ.ME"))

## Github info (this will change per user)
password <-"pass" 
github.user <- "trinker"  

## Get git location
test <- c(file.exists("C:/Program Files (x86)/Git/bin/git.exe"),
    file.exists("C:/Program Files/Git/bin/git.exe"))
gitpath <- c("C:/Program Files (x86)/Git/bin/git.exe",
  "C:/Program Files/Git/bin/git.exe")[test][1]

## download curl and set up github api
wincurl <- "http://curl.askapache.com/download/curl-7.32.0-win64-ssl-sspi.zip"
url <- wincurl
tmp <- tempfile( fileext = ".zip" )
download.file(url,tmp)
unzip(tmp, exdir = tempdir())       
shell(paste0(tempdir(), "/curl http://curl.haxx.se/ca/cacert.pem -o " , 
    tempdir() , "/curl-ca-bundle.crt"))
json <- paste0(" { \"name\":\"" , repo , "\" } ") #string we desire formatting
json <- shQuote(json , type = "cmd" )
cmd1 <- paste0( tempdir() ,"/curl -i -u \"" , github.user , ":" , password , 
    "\" https://api.github.com/user/repos -d " , json )

shell(cmd1, intern = T)

## Change working directory
wd <- getwd()
setwd(project.dir)

## set up the .git directory
cmd2 <- paste0(shQuote(gitpath), " init")
shell(cmd2, intern = T)

## add all the contents of the directory for tracking
cmd3 <- paste0(shQuote(gitpath), " add .")  
shell(cmd3, intern = T)       

cmdStat <- paste0(shQuote(gitpath), " status")  
shell(cmdStat, intern = T)

## Set email (may not be needed)
Trim <- function (x) gsub("^\\s+|\\s+$", "", x) #remove trailing/leading white 

x <- file.path(path.expand("~"), ".gitconfig")
if (file.exists(x)) {
    y <- readLines(x)
    email <- Trim(unlist(strsplit(y[grepl("email = ", y)], "email ="))[2])
} else {
    z <- file.path(Sys.getenv("HOME"), ".gitconfig")
    if (file.exists(z)) {
        email <- Trim(unlist(strsplit(y[grepl("email = ", y)], "email ="))[2])
    } else {
        warning(paste("Set `email` in", x))
    }
}
cmdEM <- paste0(shQuote(gitpath), sprintf(" config --global user.email %s", email))        
system(cmdEM, intern = T)

## Initial commit
cmd4 <- paste0(shQuote(gitpath), ' commit -m "Initial commit"')  
system(cmd4, intern = T) 

## establish connection between local and remote
cmd5 <- paste0(shQuote(gitpath), " remote add origin https://github.com/",
    github.user, "/", repo, ".git")  
shell(cmd5, intern = T) 

## push local to remote 
cmd6 <- paste0(shQuote(gitpath), " push -u origin master")  
shell(cmd6, intern = T) 

setwd(wd)

Я знаю, что script немного длиннее, но все это необходимо для воссоздания проблемы и репликации проблемы:

Примечание Я обновил вопрос в свете ответа Саймона, поскольку он был прав и приблизился к толчке. Содержание исходного вопроса можно найти здесь.

Ответы

Ответ 1

Если используется адрес https, убедитесь, что:

  • определена переменная среды %HOME%
  • a _netrc файл существует в нем с правильными учетными данными, чтобы вернуться к вашему репо

В этом файле shoud содержится:

machine github.com
login username
password xxxx
protocol https

Это работает, даже если у вас активирована недавняя двухфакторная аутентификация на GitHub.

Тогда ваш push не будет тайм-аут:

cmd6 <- paste0(shQuote(gitpath), " push -u origin master")  
shell(cmd6, intern = T) 

Это проще, чем настройка общедоступных/приватных ssh-ключей.


Как OP Tyler Rinker прокомментировал, установка %HOME% проиллюстрирована в моем другом ответе "Git - Как использовать файл .netrc для Windows для сохранения пользователя и пароля".
Обычно это делается git-cmd.bat:

if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH%
@if not exist "%HOME%" @set HOME=%USERPROFILE%

Но вы также можете сделать это вручную.

Ответ 2

Проблема состоит в простом смешивании протоколов ssh и https.

Обратите внимание, что URL-адреса должны быть:

#  https:
"https://github.com/<username>/<myrepo>.git"

#  ssh:
"[email protected]:<username>/<repo>.git"

У вас есть:

cmd5 <- paste0(shQuote(gitpath), " remote add origin https://github.com:",
github.user, "/", repo, ".git") 
cat( cmd5 )
"... remote add origin https://github.com:trinker/foo2.git"

Просто измените cmd5 на

# Note the forward slash at EOL in place of the colon
cmd5 <- paste0(shQuote(gitpath), " remote add origin https://github.com/",
github.user, "/", repo, ".git")
"... remote add origin https://github.com/trinker/foo2.git"

Также не помешало запустить это сразу после git add .:

cmdStat <- paste0(shQuote(gitpath), " status")  
shell(cmdStat, intern = T)