When working with Git repositories in R, automating commits and pushes can save time and ensure changes are consistently tracked. The function update_git_hub() simplifies the Git workflow by automating the process of configuring user identity, staging changes, committing, and pushing to GitHub.
The update_git_hub() function performs the following tasks:
Configures Git user identity (name and email).
Initializes a Git repository if it does not already exist.
Stages all changes in the working directory.
Displays the current Git status.
Commits changes with a user-provided message.
Ensures the branch is set to main.
Pushes the committed changes to the remote repository.
Below is the R function:
update_git_hub <- function(comment = "first commit", user_name = "Your Name", user_email = "your_email@example.com") {
# Set Git user identity
system(glue::glue('git config --global user.name "{user_name}"'))
system(glue::glue('git config --global user.email "{user_email}"'))
# Initialize Git repository if not already initialized
if (!file.exists(".git")) {
system("git init")
}
# Add all changes to staging
system("git add .")
# Show status of the repository
system("git status")
# Commit changes with a message
system(glue::glue('git commit -m "{comment}"'))
# Ensure the branch is set to main
system("git branch -M main")
# Push changes to the main branch
system("git push origin main --force")
}
How to Use the Function
Load the Required Library:
Ensure that the glue package is installed and loaded before using the function:
install.packages("glue")
library(glue)
Run the Function:
Call the function with custom parameters:
update_git_hub(comment = "Updated analysis scripts", user_name = "John Kamau", user_email = "john.kamau@example.com")
After executing the function, the following will happen:
If Git is not initialized, it will be set up in the current directory.
All changes will be staged and committed with the provided comment.
The main branch will be ensured and the changes will be pushed forcefully to the remote repository.
The terminal will display the status of the repository.
This function assumes that the repository is already linked to a remote origin.
Using --force in git push will overwrite changes on the remote branch, so use it carefully.
Ensure your SSH or HTTPS authentication is properly configured to push changes successfully.
This function is a powerful way to streamline GitHub updates directly from R, making version control seamless within your workflow. 🚀