如何在R脚本中将更改提交到GitHub?

twb*_*b10 5 git shell r github rstudio

我正在尝试从R脚本中自动化一些基本的git操作。我在Windows OS上使用Rstudio。例如,如果您希望在脚本完成一些自动化任务后更新GitHub,这可能会有所帮助。

我编写了一些简单的函数,这些函数利用R shell()函数和Window的&管道运算符将命令链发送到OS终端:

# Git status.
gitstatus <- function(dir = getwd()){
  cmd_list <- list(
    cmd1 = tolower(substr(dir,1,2)),
    cmd2 = paste("cd",dir),
    cmd3 = "git status"
  )
  cmd <- paste(unlist(cmd_list),collapse = " & ")
  shell(cmd)
}

# Git add.
gitadd <- function(dir = getwd()){
  cmd_list <- list(
    cmd1 = tolower(substr(dir,1,2)),
    cmd2 = paste("cd",dir),
    cmd3 = "git add --all"
  )
  cmd <- paste(unlist(cmd_list),collapse = " & ")
  shell(cmd)
}

# Git commit.
gitcommit <- function(msg = "commit from Rstudio", dir = getwd()){
  cmd_list <- list(
    cmd1 = tolower(substr(dir,1,2)),
    cmd2 = paste("cd",dir),
    cmd3 = paste0("git commit -am ","'",msg,"'")
  )
  cmd <- paste(unlist(cmd_list),collapse = " & ")
  shell(cmd)
}

# Git push.
gitpush <- function(dir = getwd()){
  cmd_list <- list(
    cmd1 = tolower(substr(dir,1,2)),
    cmd2 = paste("cd",dir),
    cmd3 = "git push"
  )
  cmd <- paste(unlist(cmd_list),collapse = " & ")
  shell(cmd)
}
Run Code Online (Sandbox Code Playgroud)

我的gitstatusgitaddgitpush功能正常工作。该gitcommit功能不起作用。它生成以下错误:

致命的:-a路径没有意义。
警告消息:
在shell(cmd)中:'d:&cd D:/ Documents / R / my_path&git commit -am'commit from Rstudio'执行失败,错误代码128

gitpush功能之所以有效,是因为如果您在Rstudio中切换到终端或git,则可以提交更改,然后成功调用gitpush

有关如何解决此问题的任何想法?

...

注意:我已经安装了Git bash,并且可以从Windows命令终端和Rstudio成功使用git。我还尝试了一种替代策略,该策略是让R编写一个临时.bat文件,然后执行该临时文件,但是该策略也挂在提交步骤上。

twb*_*b10 3

解决方案

答案就在 Dirk Eddelbuettel 的 drat包函数addrepo中。还需要使用git2r 的 config函数来确保 git 识别 R。git2r 的函数可能为将来从 R 脚本使用 git 提供更强大的解决方案。与此同时,以下是我解决问题的方法。

  • 安装 git2r。使用 git2r::config() 确保 git 识别 R。

  • 从德克的代码中,我修改了该gitcommit()函数以利用sprintf()system()执行系统命令:

# Git commit.
gitcommit <- function(msg = "commit from Rstudio", dir = getwd()){
  cmd = sprintf("git commit -m\"%s\"",msg)
  system(cmd)
}
Run Code Online (Sandbox Code Playgroud)

Sprintf 的输出如下所示:

[1] "git commit -m\"commit from Rstudio\""
Run Code Online (Sandbox Code Playgroud)

例子

#install.packages("git2r")
library(git2r)

# Insure you have navigated to a directory with a git repo.
dir <- "mypath"
setwd(dir)

# Configure git.
git2r::config(user.name = "myusername",user.email = "myemail")

# Check git status.
gitstatus()

# Download a file.
url <- "https://i.kym-cdn.com/entries/icons/original/000/002/232/bullet_cat.jpg"
destfile <- "bullet_cat.jpg"
download.file(url,destfile)

# Add and commit changes. 
gitadd()
gitcommit()

# Push changes to github.
gitpush()

Run Code Online (Sandbox Code Playgroud)

好吧,这张照片看起来很奇怪,但我想你明白了。