Skip to main content

Version Control with Git and GitHub

Friday, October 23: a history for your code

Friday, Oct 23, 12:10–1:00 PM, Asmundson 242: setup, step by step (slides). Which version of your script made Figure 3? What did you change since your committee meeting? Git keeps a record of every saved version of your code, so you can answer those questions and undo mistakes. We’ll set it up in RStudio, with no command line, and use it on your Problem Set 4 code. Bring your laptop.


Why git?

Five versions of the same script: analysis.R, analysis_v2.R, analysis_final.R, analysis_final_REAL.R, analysis_final_v3_USE_THIS.R

Git replaces the pile of files with one file and its whole history. Each save point is a commit, with a short note saying why you made it:

A timeline of four commits: read data, plot it, fit a line, logistic curve

git keeps that history on your computer. GitHub keeps a copy online; sending your commits there is called a push.

A laptop with an arrow up to a cloud

Note

The RStudio and GitHub pictures below are simplified drawings of what you’ll see, with the part you need boxed in red. Your screen will have more buttons, but the same labels.


Setup (about 15 minutes)

We’ll do these together in class. Missed it? Do them on your own, and if something doesn’t work, bring the output of step 7 to office hours.

Step 1. Install git

  • Mac: open the Terminal app (Applications → Utilities) and type:

    git --version

    If it prints a version number, you already have git. If a window pops up offering to install the command line developer tools, click Install and wait a few minutes.

  • Windows: download Git for Windows, run it, and accept every default.

Then quit RStudio completely and reopen it, so it finds git.

Trouble installing? See Troubleshooting below.

Step 2. Make a free GitHub account

Sign up at github.com/signup. Pick a username you’d be happy to put on a CV, and remember the email you used. Students can also apply for free extras through GitHub Education (optional).

Step 3. Install the usethis package

In the RStudio console. usethis does the fiddly git and GitHub setup for you.

install.packages("usethis")

Step 4. Tell git who you are

Your real name, and the email you used for GitHub. It prints nothing; that’s fine.

usethis::use_git_config with user.name and user.email boxed

usethis::use_git_config(user.name = "Your Name", user.email = "you@ucdavis.edu")

Step 5. Make a GitHub token

A token is a long password that lets RStudio act as you on GitHub.

usethis::create_github_token()

GitHub opens in your browser with the right boxes already ticked:

GitHub's new token page with the Expiration menu and the Generate token button boxed

  1. Change Expiration from 30 days to 90 days (or pick Custom for longer).
  2. Scroll down and click the green Generate token.
  3. Copy the token (it starts with ghp_). GitHub shows it only once, so keep the tab open until step 6.

Step 6. Give the token to RStudio

gitcreds::gitcreds_set()

When it asks for a password or token, paste it and press Enter. If it says you already have one, choose the option to replace it.

Step 7. Check it worked

usethis::git_sitrep()

git_sitrep output with name, email, discovered token and GitHub user boxed in green

Look for your name and email, <discovered> next to Personal access token, and your GitHub user. You can ignore warnings about token scopes, “No active usethis project” (normal until you make a project in Part 1), and a line saying Vaccinated: FALSE (it’s optional; running usethis::git_vaccinate() is harmless and just tells git to ignore R’s temporary files like .Rhistory). Errors here? Bring this output to class or office hours.

Errors? See Troubleshooting below.


Troubleshooting

If something doesn’t work, find your problem below. Click a tip to open it. Still stuck? Run usethis::git_sitrep() and bring the output to class or office hours.

If you see… Try
Mac: no git, no pop-up xcode-select --install in the Terminal (Mac tip below)
RStudio can’t find git Quit and reopen RStudio
Windows: still can’t find it Tools → Global Options → Git/SVN, set the git executable to C:/Program Files/Git/bin/git.exe
Token not found Run gitcreds::gitcreds_set() again with a fresh token
“The PAT discovered … has the wrong structure” What got saved isn’t a token (tip below)
could not find function "check_string" Package version clash between gh and rlang (tip below)
Something else usethis::git_sitrep() and bring the output

Type each command in the Terminal app (or RStudio’s Terminal tab, next to Console), not the R console. In the R console, git --version just gives an R error like “unexpected symbol”.

1. Ask for the installer directly.

xcode-select --install

A window should open offering to install the “command line developer tools”. Click Install and wait; it can take 5 to 15 minutes on campus wifi.

2. It says the tools are “already installed”, but git --version still fails? The install is half-broken (common after a macOS update). Reset it, then run step 1 again:

sudo xcode-select --reset
xcode-select --install

sudo asks for your laptop password. Nothing appears while you type it; just press Enter.

3. Still broken? Remove the old tools completely and reinstall:

sudo rm -rf /Library/Developer/CommandLineTools
xcode-select --install

4. Use Homebrew instead? If you already use Homebrew, brew install git works too.

5. Check. Run git --version again. A version number (e.g. git version 2.39.5) means it worked. Quit and reopen RStudio, then carry on with step 2 below.

Short on time in class? Do steps 2 to 7 now (none of them need git) and finish installing git at home.

  1. Quit RStudio completely (check it isn’t still running in the taskbar) and reopen it.
  2. Still nothing? In RStudio go to Tools → Global Options → Git/SVN, tick Enable version control interface, and set Git executable to C:/Program Files/Git/bin/git.exe (click Browse to find it). Restart RStudio.
  3. Keep your project folders outside OneDrive (for example C:/Users/yourname/pls206). OneDrive syncing can lock git’s files and cause odd errors.

What RStudio saved isn’t a valid token. A token starts with ghp_ (or github_pat_) and has nothing else around it: no spaces, no quote marks, no line break. The usual causes are pasting your GitHub password instead of the token, or copying extra characters with it.

GitHub shows a token only once, so make a fresh one:

  1. Run usethis::create_github_token(), click Generate token, and copy it with the copy icon next to the token (selecting the text by hand tends to grab extra spaces).
  2. Run gitcreds::gitcreds_set(). It says a credential already exists: choose Replace these credentials, paste the token (no quotes), and press Enter.
  3. Run usethis::git_sitrep() again. It should now say <discovered>.

Still wrong structure? An old token saved in your .Renviron file may be overriding the new one. Check:

Sys.getenv("GITHUB_PAT")

If that prints anything, run usethis::edit_r_environ(), delete the GITHUB_PAT=... line, save, restart R (Session → Restart R), and run usethis::git_sitrep() again.

A bug in the newest version of the gh package (1.6.1, which usethis uses to talk to GitHub): it needs a newer rlang package than it asks for. Nothing you did wrong. Part 1 below (projects, commits, history) doesn’t use gh, so you can carry on with that and come back to this.

1. Update rlang. Session → Restart R, then:

install.packages("rlang")

Say No if it asks to install from sources. Then Session → Restart R again and check:

packageVersion("rlang")   # needs to be 1.2.0 or newer
usethis::git_sitrep()

2. Still the same error, or rlang still shows 1.1.something? Go back to the previous version of gh, which works with older rlang (gh is plain R code, so this installs without any compilers):

install.packages("https://cran.r-project.org/src/contrib/Archive/gh/gh_1.5.0.tar.gz",
                 repos = NULL, type = "source")

Session → Restart R, then usethis::git_sitrep().

  • Always restart R before installing (Session → Restart R). Updating a package that’s already loaded can leave a half-updated mix, which shows up later as could not find function errors.
  • If it asks “Do you want to restart R prior to install?”, say Yes.
  • If it asks “Do you want to install from sources the package which needs compilation?”, say No.
  • After installing, Session → Restart R again.
  • Check what you actually have with packageVersion("usethis"), packageVersion("gh") and R.version.string. Very old R (before 4.3) is worth updating from cran.r-project.org first.

More help: Happy Git and GitHub for the useR.


Part 1 — Git on your own computer

Git tracks one folder, called a repository. In RStudio, that folder is an RStudio Project.

Make a project with git

File → New Project → New Directory → New Project. Name it (e.g. pls206-ps4) and tick “Create a git repository”:

New Project Wizard with the Create a git repository box ticked and boxed in red

Click Create Project. RStudio restarts inside the new project. (Already keep your work in an RStudio project? Run usethis::use_git() in it instead, and say yes when it asks to commit and restart.)

Put a script in the project

Git only tracks files inside the project folder.

  • Have a PS4 script already? Copy the .R file into the pls206-ps4 folder with Finder (Mac) or File Explorer (Windows).
  • Starting fresh? File → New File → R Script, paste this starter code, and save it as ps4.R (RStudio saves into the project folder by default):
# Problem Set 4: sunflower growth
d <- read.csv("https://greymonroe.github.io/PLS_206/data/sunflower_growth.csv")
giant <- subset(d, variety == "giant")
plot(mass_g ~ day, data = giant)

Either way, the script shows up in the Files tab:

RStudio Files tab showing .gitignore, pls206-ps4.Rproj and ps4.R, with ps4.R boxed

The Git tab

After RStudio restarts, there’s a Git tab in the top-right pane. It lists every file that changed since your last commit. Yellow ? means new, never committed.

RStudio Git tab listing .gitignore, pls206-ps4.Rproj and ps4.R as new files

Commit: tick, say why, click

Click Commit in the Git tab. In the window that opens:

  1. Tick the Staged box next to each file (the ? turns into a green A, for added).
  2. Write a message that says what you did and why.
  3. Click Commit.

Review Changes window: three files ticked, a commit message typed, the Commit button boxed

Change something: the diff

Edit your script and save. The file shows up again with a blue M (modified). Open Commit and the bottom half shows exactly what changed: red = removed, green = added. Tick, write why, Commit.

Review Changes window with a diff: the lm() line in red, the nls() lines in green

History

The clock icon (History) in the Git tab lists every commit, newest first. Click one to see what changed.

History window with three commits, their messages, author and date

Broke something? Go back

Delete a chunk of your script and save. In the Git tab, select the file, then More → Revert…. The file goes back to your last commit. Careful: changes since that commit are thrown away.

Git tab with the More menu open and Revert boxed

That’s the whole daily routine: edit → save → commit.

Part 2 — Back it up on GitHub

GitHub keeps a copy of your repository online, a bit like Dropbox but with the full history attached. It’s how you share code with your advisor, collaborate with co-authors, and publish code alongside a paper. Run this once, inside your project:

usethis::use_github(private = TRUE)

It creates a repository on your GitHub account, uploads your commits, and opens it in your browser. Leave out private = TRUE if you want it public.

After that, commit, then Push: the green up-arrow sends new commits to GitHub.

Git tab with the green Push button boxed

When your token expires

Tokens expire (90 days if you followed the steps above). GitHub emails you a few days before. After that, Push fails with an authentication or “invalid token” error. Nothing is lost: your code and history are still on your computer and on GitHub. To renew, run the same commands as at setup:

usethis::create_github_token()  # make a new token, copy it
gitcreds::gitcreds_set()        # paste it; when asked, choose to replace the old one
usethis::git_sitrep()           # check: the token should say <discovered>

If something goes wrong, usethis::git_sitrep() prints a report of what is and isn’t set up. Bring that output to class or office hours.


Habits worth keeping

  • Commit small and often, with a message that says why. Future-you is the main audience.
  • Don’t commit large data files or passwords. List them in the .gitignore file in your project folder, and git will leave them alone.
  • One project per analysis. One folder, one repository, one history.

Extra resources

  • Happy Git and GitHub for the useR — the guide for R users. Covers installation and the RStudio workflow in detail, and how to fix things when setup goes wrong.
  • Pro Git — the free, complete git book, for when you want to know what’s going on underneath.