How can I commit changes to GitHub from within a R script?
Solution
The answer lie within Dirk Eddelbuettel's drat package function addrepo. It was also necessary to use git2r's config
function to insure that git recognizes R. git2r's functions probably provide a more robust solution for working with git from an R script in the future. In the meantime, here's how I fixed the problem.
Install git2r. Use git2r::config() to insure git recognizes R.
From Dirk's code I modified the
gitcommit()
function to utilizesprintf()
andsystem()
to execute a system command:
# Git commit.gitcommit <- function(msg = "commit from Rstudio", dir = getwd()){ cmd = sprintf("git commit -m\"%s\"",msg) system(cmd)}
Sprintf's output looks like this:
[1] "git commit -m\"commit from Rstudio\""
Example
#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()
Well, the pic looks wonky, but I think you get the point.
From what I have read in this Ask Ubuntu question, you should be using &&
, not &
, to separate multiple commands in the Git bash. Try doing that:
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)}
Note that your gitcommit
function will output something like this:
/v & cd /var/www/service/usercode/255741827 & git commit -am 'first commit'"
I don't know what purpose the substr(dir, 1, 2)
portion serves, but if my suggestion still doesn't work, then try removing it to leave just the cd
and git commit
commands.
I personally like the syntax and simplicity of the gert
package from rOpenSci. Specifically, to commit a repo you would do:
git_add("test.txt")git_commit("Adding a file", author = "jerry <jerry@gmail.com>")
Top push to remote:
git_push(remote = "origin", repo = ".")
And see all other useful functions with this simple syntax.