gpt4 book ai didi

r - 如何从 R 脚本中将更改提交到 GitHub?

转载 作者:太空狗 更新时间:2023-10-29 13:25:01 29 4
gpt4 key购买 nike

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

我编写了一些简单的函数,它们利用 R 的 shell() 函数和 Window 的 & 管道运算符向操作系统终端发送命令链:

# 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)
}

我的 gitstatusgitaddgitpush 功能正常。 gitcommit 函数不起作用。它会产生以下错误:

fatal: Paths with -a does not make sense.
Warning message:
In shell(cmd) : 'd: & cd D:/Documents/R/my_path & git commit -am 'commit from Rstudio'' execution failed with error code 128

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

关于如何解决这个问题有什么想法吗?

...

注意:我安装了 Git bash,我可以从 Windows 命令终端和 Rstudio 成功使用 git。我还尝试了另一种策略,即让 R 编写一个临时 .bat 文件,然后执行它,但这种策略也会在提交步骤中挂起。

最佳答案

解决方案

答案在 Dirk Eddelbuettel'sdrat 封装函数addrepo .也有必要使用 git2r's config 函数以确保 git 识别 R。git2r 的函数可能会为将来从 R 脚本中使用 git 提供更强大的解决方案。与此同时,以下是我解决问题的方法。

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

  • 根据 Dirk 的代码,我修改了 gitcommit() 函数以利用 sprintf()system() 来执行系统命令:

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

Sprintf 的输出如下所示:

[1] "git commit -m\"commit from Rstudio\""

例子

#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()

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

关于r - 如何从 R 脚本中将更改提交到 GitHub?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432420/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com