Content from Automated Version Control


Last updated on 2024-03-05 | Edit this page

Estimated time: 25 minutes

Overview

Questions

  • What is version control and why should I use it?

Objectives

  • Understand the benefits of an automated version control system.
  • Understand the basics of how automated version control systems work.

Tracking changes


We’ll start by exploring how we are usually introduced to version control to keep track of what one person did and when. Even if you aren’t collaborating with other people, version control may have look like this situation:

One same files called Press release.doc with modifications in different files using the words FINAL, VERSION, REVISED, APPROVED. Source: Proper Discord.
Tracking changes for the Press release.doc file. Never use the word “final” in a filename.

Does it seem unnecessary to you to have multiple nearly identical versions of the same document? Possibly yes. But this Version control system opens the possibility of returning to a specific version in case you erased something that you think now is essential.

File names to track changes

Write down:

  • Is there any file naming convention that is familiar to you?

  • What was the version control system that you first used?

  • Share with us your favorite prefix or suffix!

We can use the comments or live participation as ice-breaker.

Some word processors let us deal with this a little better, such as Microsoft Word’s Track Changes, Google Docs’ version history, or LibreOffice’s Recording and Displaying Changes. Let’s illustrate how Google Docs works.

Tracking changes for the git-test file.
Tracking changes for the git-test file.

To use Google Docs version history click File > Version history > See version history. This highlights the new content added to the file in that version only.

The most recent version of the git-test file is called “third version”.
The most recent version of the git-test file is called “third version”.

We can move to any previous version tagged with two metadata values: the modification date and the name of the author.

We can view the “first version” of the file git-test. We can also restore it with the Restore this version button.
We can view the “first version” of the file git-test. We can also restore it with the Restore this version button.

Google Docs’ version history tool is an automatic Version control system for single Word/Doc files that works online.

The Turing Way project illustration by Scriberia. Used under a CC-BY 4.0 licence. DOI: https://zenodo.org/doi/10.5281/zenodo.3332807.
The Turing Way project illustration by Scriberia. Used under a CC-BY 4.0 licence. DOI: https://zenodo.org/doi/10.5281/zenodo.3332807.

Version control systems


Version control systems start with a base version of the document and then record changes you make each step of the way. You can think of it as a recording of your progress: you can rewind to start at the base document and play back each change you made, eventually arriving at your more recent version.

Changes Are Saved Sequentially

Once you think of changes as separate from the document itself, you can then think about “playing back” different sets of changes on the base document, ultimately resulting in different versions of that document.

A version control system is a tool that keeps track of these changes for us, effectively creating different versions of our files.

Checklist

Key characteristics of Version control systems are:

  1. Keep the entire history of a file and inspect a file throughout its lifetime.

  2. Tag a particular version so you can return to them easily.

Automated version control systems are nothing new. Tools like RCS, CVS, or Subversion have been around since the early 1980s and are used by many large companies. However, many of these are now considered legacy systems (i.e., outdated) due to various limitations in their capabilities. More modern systems, such as Git and Mercurial, are distributed, meaning that they do not need a centralized server to host the repository. These modern systems also include powerful merging tools that make it possible for multiple authors to work on the same files concurrently.

Paper Writing

  • Imagine you drafted an excellent paragraph for a paper you are writing, but later ruin it. How would you retrieve the excellent version of your conclusion? Is it even possible?

  • Imagine you have 5 co-authors. How would you manage the changes and comments they make to your paper? If you use LibreOffice Writer or Microsoft Word, what happens if you accept changes made using the Track Changes option? Do you have a history of those changes?

  • Recovering the excellent version is only possible if you created a copy of the old version of the paper. The danger of losing good versions often leads to the problematic workflow illustrated in this popular PhD Comics cartoon.

  • Collaborative writing with traditional word processors is cumbersome. Either every collaborator has to work on a document sequentially (slowing down the process of writing), or you have to send out a version to all collaborators and manually merge their comments into your document. The ‘track changes’ or ‘record changes’ option can highlight changes for you and simplifies merging, but as soon as you accept changes you will lose their history. You will then no longer know who suggested that change, why it was suggested, or when it was merged into the rest of the document. Even online word processors like Google Docs or Microsoft Office Online do not fully resolve these problems. Remember this for the collaboration episode!

Version control and R files


For code-like files like .R and .Rmd files, we can not use Google docs. The software and strategy to track changes in a project depends on the file type.

  • Google Docs’ version history tool is a Version control software optimized for single non-plain text files like Word/Doc files that works online.

  • Git is the Version control software optimized for plain text files that works offline. (Read: “What Not to Put Under Version Control” at G. Wilson et al. 2017)

Plain text files can be text, code, and data. Example for each of these are Markdown files (.md), R files (.R), and .csv or .tsv files, respectively.

Examples of non-plain and plain text files.
Examples of non-plain and plain text files.

data files

We can use Git to track changes of data files (like .csv and .tsv). However, if we consider data files as raw files, which should not change in time, then we may not be needed to use Git with them. We’ll take a look into this in the chapter on Ignoring things.

Also, if you consider your data file large with respect to your computer, you can opt to use:

Plain text files like Markdown files (.md) and R files (.R) are integrated in Rmarkdown files (.Rmd) to generate manuscripts, websites, and R packages. These three products are outputs of Open Science projects, that leads to Reproducible research and Sustainable software.

We can increase the reproducibility of our Open science projects with version control sytems like Git. Text and final results can be connected and executable by Data and code. From: “Ciencia reproducible: qué, por qué, cómo” https://www.revistaecosistemas.net/index.php/ecosistemas/article/view/1178
We can increase the reproducibility of our Open science projects with version control sytems like Git. Text and final results can be connected and executable by Data and code. From: “Ciencia reproducible: qué, por qué, cómo” https://www.revistaecosistemas.net/index.php/ecosistemas/article/view/1178
Concept map for automatic version control.
Concept map for automatic version control.

Exercise!

Tell us about your Open Science project and its file types!

  • Briefly share about one Open Science project in which they are involved or would like to start soon (e.g. thesis, current project, or work);
  • Identify the most relevant file types (.pdf, .jpge, .csv, .xlsx, .R, .docx, .Rmd) involved in it and classify them as non-plain or plain text files;
  • Discuss which ones can use a Version control software like Git?

This exercise can be solved in the shared document of the training.

Key Points

  • Version control record changes you make “step-by-step”.
  • Git is a Version control software optimized for plain text files, like .R and .Rmd files.

Content from Setting Up Git


Last updated on 2024-03-05 | Edit this page

Estimated time: 10 minutes

Overview

Questions

  • How do I set up Git?
  • What is a token?
  • What is a commit?
  • What is a repository?
  • What is a branch?

Objectives

  • Configure git the first time it is used on a computer.

The Git workflow


A version control system is a tool that keeps track of these changes for us, effectively creating different versions of our files. Each record of these changes is called a commit. Each keeps useful metadata about them. Instead of saving copies with different file names, we are making commits in the same file. Consecutive commits generate a linear history of changes.

Changes Are Saved Sequentially
Each record of changes is called a commit. From: https://speakerdeck.com/alicebartlett/git-for-humans

The complete history of commits for a particular project and their metadata make up a repository. Repositories can be kept in sync across different computers, facilitating collaboration among different people.

Before creating our first repository, we need to setup Git. So, let’s open Rstudio and introduce yourself to Git!

The Rstudio Console

In this episode, we are going to use the Rstudio Console.

Visual appearance of the Console.
Visual appearance of the Console.

Set up Git


When we use Git on a new computer for the first time, we need to configure a few things. Below are a few examples of configurations we will set as we get started with Git:

  • our name and email address,
  • and that we want to use these settings globally (i.e. for every project).

You can set your Git user name and email from within R using the usethis package.

Using the Rstudio Console, here is how Dracula sets up his new laptop:

R

# install if needed (do this exactly once):
# install.packages("usethis")

usethis::use_git_config(
  user.name = "Vlad Dracula",
  user.email = "vlad@tran.sylvan.ia",
  github.user = "vlad")

Substitute this chunk with your name and the email associated with your GitHub account.

Please use your own name and email address instead of Dracula’s. This user name and email will be associated with your subsequent Git activity, which means that any changes pushed to GitHub, BitBucket, GitLab or another Git host server after this lesson will include this information.

For this lesson, we will be interacting with GitHub and so the email address used should be the same as the one used when setting up your GitHub account. If you are concerned about privacy, please review GitHub’s instructions for keeping your email address private.

Keeping your email private

If you elect to use a private email address with GitHub, then use that same email address for the user.email value, e.g. username@users.noreply.github.com replacing username with your GitHub one.

Set up your GitHub token


To interact with GitHub we need to include credentials in the request. We are going to configure one type of credential called Personal Access Token (PAT). We need this to prove that we are a specific GitHub user, allowed to do whatever we’re asking to do. (Bryan, 2021)

First, let’s create your token.

Do this with usethis::create_github_token(). This function should redirect you to GitHub on your browser. Once there, check all the options in the figure below.

R

usethis::create_github_token()

Describe the token use case.

Look over the scopes; the recommended scopes to select are “repo”, “workflow”, and “user”. When using usethis::create_github_token() will pre-select all the recommended scopes for you!

Click “Generate token”.

Visual display with the recommended scopes selected. Optional scopes are “gist” and “delete_repo” to create a gist and delete repositories.
Visual display with the recommended scopes selected. Optional scopes are “gist” and “delete_repo” to create a gist and delete repositories.

Copy your token. Save it for the next step.

token options

Briefly:

  • "repo" will give you control of your private repositories online (YES! you can have private repos!).
  • "workflow" will allow you to run automated processes for your repository online (This is advanced! so let’s get back to this after the episode on GitHub).
  • "user" will allow you to update your user data (as in the first step here).

Second, let’s configure your token.

To complete the configuration of your token use gitcreds::gitcreds_set() (Bryan, 2021), then accept that you want to Replace these credentials. Write the corresponding number and press ENTER.

R

gitcreds::gitcreds_set()

OUTPUT

-> What would you like to do?

1: Abort update with error, and keep the existing credentials
2: Replace these credentials
3: See the password / token

Selection: 2

Paste your token to save it and complete this step.

Lastly, let’s confirm your setting.

Run:

R

usethis::git_sitrep()

In the ── Git global (user) section, the two first lines of the output should look like this:

OUTPUT

── Git global (user)
• Name: 'Vlad Dracula'
• Email: 'vlad@tran.sylvan.ia'

In the ── GitHub user section, the three first lines of the output should look like this:

OUTPUT

── GitHub user
• Default GitHub host: 'https://github.com'
• Personal access token for 'https://github.com': '<discovered>'
• GitHub user: 'vlad'

You should recognize your:

  • Name,
  • GitHub login, and
  • Token.

Set up a default branch name


As we mentioned before, the complete history of commits for a particular project and their metadata make up a repository. (We are going to create one in the next episode!)

A branch is a snapshot of a version of a repository. In that sense, a repository can have more than one branch. WHAT?!! How is that possible? We are going to see that in coming episodes!

Version history within a single branch.
Version history within a single branch.

Git (2.28+) allows configuration of the name of the branch created when you initialize any new repository. Dracula decides to use that feature to set it to main so it matches the cloud service he will eventually use.

Run the code chunk below:

R

usethis::git_default_branch_configure(name = "main")

To confirm this setting, run:

R

usethis::git_sitrep()

In the ── Git local (project) section, almost at the end of the message, the third line of the output should say Default branch: 'main':

── Git local (project)
• Name: 'Vlad Dracula'
• Email: 'vlad@tran.sylvan.ia'
• Default branch: 'main'

Source file changes are associated with a “branch.” For new learners in this lesson, it’s enough to know that branches exist, and this lesson uses one branch.
By default, Git will create a branch called master when you create a new repository with git init (as explained in the next Episode). This term evokes the racist practice of human slavery and the software development community has moved to adopt more inclusive language.

In 2020, most Git code hosting services transitioned to using main as the default branch. As an example, any new repository that is opened in GitHub and GitLab default to main. However, Git has not yet made the same change. As a result, local repositories must be manually configured have the same main branch name as most cloud services.

For versions of Git prior to 2.28, the change can be made on an individual repository level. The command for this is in the next episode. Note that if this value is unset in your local Git configuration, the init.defaultBranch value defaults to master.

Checklist

We need to run these commands only once! Git will use this settings for every project, in your user account, on this computer.

And if necessary, change your configuration using the same commands to update your email address. This can be done as many times as you want.

When using usethis::git_sitrep(), check if there is no ✖ ... line in the output with an error message.

Some common errors are solved here:

Callout

When using the Terminal, this step is known as git config with the --global option. In the next chapter we are going to interact with the Terminal!

Key Points

  • Use the usethis package to configure a user name, email address, and other preferences once per machine.
  • Use usethis::use_git_config() to configure Git in Rstudio.
  • Use usethis::git_sitrep() to verify your configuration.

Content from Creating a Repository


Last updated on 2024-03-04 | Edit this page

Estimated time: 25 minutes

Overview

Questions

  • Where does Git store information?

Objectives

  • Create a local Git repository.
  • Describe the purpose of the .git directory.

The Git jargon


Git is a topic that contains a lot of words to do version control.

Word cloud for Git from https://thoughtbot.com/blog/recommending-blog-posts

We will locate them using this workflow bellow as template. We will relate Version control actions that we can perform with specific git verb commands. These verbs will record your changes between Git spaces associated to your folder.

Workflow will show actions, git verb commands, and spaces.
Workflow will show actions, git verb commands, and spaces.

In this episode, we are going to learn how to initialize Git to create a Local Repository in our folder, also known as Working directory or Workspace.

Initialize a Local Repository in your Workspace with the git init command verb
Initialize a Local Repository in your Workspace with the git init command verb

Let’s start with a new R project in Rstudio.

PREREQUISITES

To start, you need to be out of any R project. In Rstudio, close you Project from File > Close Project. You can confirm this in the upper right corner Project: (None).

Create a local repository


Once Git is configured, we can start using it.

We will continue with the story of Wolfman and Dracula who are investigating a disease outbreak and build a situational report.

wolfman and dracula using computers for data analysis
Image by Bing, 2023, CC BY 4.0, created with Bing Image Creator powered by DALL·E 3

First, let’s create a new project folder for our work. Create a new project as you like. Here we are going to use functions from the usethis package.

If using RStudio desktop, the project is opened in a new session. Otherwise, the working directory and active project is changed:

R

usethis::create_project(path = "cases")

OUTPUT

✔ Creating 'cases/'
✔ Setting active project to 'C:/~/cases'
✔ Creating 'R/'
✔ Writing 'cases.Rproj'
✔ Adding '.Rproj.user' to '.gitignore'
✔ Opening 'C:/~/cases/' in new RStudio session
✔ Setting active project to '<no active project>'

Then we tell Git to make cases a repository -- a place where Git can store versions of our files:

R

usethis::use_git()

OUTPUT

✔ Setting active project to 'C:/~/cases'
✔ Initialising Git repo
✔ Adding '.Rhistory', '.Rdata', '.httr-oauth', '.DS_Store', '.quarto' to '.gitignore'
There are 2 uncommitted files:
* '.gitignore'
* 'cases.Rproj'
Is it ok to commit them?

Remember that each record of change can be commit. So, you can make these two files, .gitignore and cases.Rproj, part of it. Select that Yes, you agree!

OUTPUT

✔ Adding files
✔ Making a commit with message 'Initial commit'
• A restart of RStudio is required to activate the Git pane
Restart now?

Agree to restart your session to activate the Git pane in Rstudio:

The Git tab in the Environments pane shows the status of your repository.
The Git tab in the Environments pane shows the status of your repository.

The Git tab is in the Environments pane, usually in the upper right corner of the Rstudio IDE.

In this and next episodes you’ll learn the function of all those buttons on the top of the Git tab!

It is important to note that usethis::use_git() will create a repository that can include subdirectories and their files—there is no need to create separate repositories nested within the cases repository, whether subdirectories are present from the beginning or added later. Also, note that the creation of the cases directory and its initialization as a repository are completely separate processes.

This step is known as git init because it initialise your Git repository.

Checklist

Set up Git once per computer. Initialize Git once per project.
Set up Git once per computer. Initialize Git once per project.

Find the new files of a local repository


If we look at the Files tab in the Output pane to show the directory’s contents, it appears that nothing has changed.

But under the “cogwheel” button we get access to the “More file commands”. Click to the Show hidden files to show everything. We can see that Git has created a hidden directory within cases called .git:

Show hidden files in an Local repository.
Show hidden files in an Local repository.

The .git file gives the identity to the .git repository also known as the Local Repository “Local Repo”.

The .git folder is a hidden folder in a Local repository.
The .git folder is a hidden folder in a Local repository.

Git uses this special subdirectory to store all the information about the project, including the tracked files and sub-directories located within the project’s directory. If we ever delete the .git subdirectory, we will lose the project’s history.

From the Console to the Terminal

Now, we are going to use the Rstudio Terminal. The Terminal tab is next to the Console tab.

Click on the Terminal tab and a new terminal session will be created (if there isn’t one already).

Visual appearance of the Terminal.
Visual appearance of the Terminal.

Alternatively, in the Rstudio Terminal, with the ls -a command we can see the hidden directory called .git/:

BASH

$ ls -a

OUTPUT

./   .git/       .Rhistory     cases.Rproj
../  .gitignore  .Rproj.user/  R/

Important!

The .git directory is the Local Repository. This is the one of the Git spaces we talk about in the introduction of this episode!

Git stores all of its repository data (and your coming changes!) in the .git directory.

Initialize a Local Repository in your Workspace with the git init command verb
Initialize a Local Repository in your Workspace with the git init command verb

Check the status


To interact with Git, we can also use the Rstudio Terminal.

In the RStudio Terminal, we can check that everything is set up correctly by asking Git to tell us the git status of our project:

BASH

$ git status

OUTPUT

On branch main

nothing to commit, working tree clean

If you are using a different version of git, the exact wording of the output might be slightly different.

Checklist

Use the git init command to initialize a Local Repository in your Workspace. Use git status to check the status of the repository.
Use the git init command to initialize a Local Repository in your Workspace. Use git status to check the status of the repository.

The steps done with usethis can also be done with commands in the Terminal. For example, instead of usethis::use_git() in the Console you can use git init in the Terminal. However, we prefer using the first one given their explicit messages, interactivity, and warnings to prevent errors!

Git has a verb command similar to the help() function in R.

Always remember that if you forget the subcommands or options of a git command, you can access the relevant list of options typing git <command> -h or access the corresponding Git manual by typing git <command> --help, e.g.:

BASH

$ git config -h
$ git config --help

While viewing the manual, remember the : is a prompt waiting for commands and you can press Q to exit the manual.

More generally, you can get the list of available git commands and further resources of the Git manual typing:

BASH

$ git help

For complementary resources, refer to the Git Cheatsheets for Quick Reference inside this tutorial website.

Places to Create Git Repositories

Along with tracking information about cases (the project we have already created), Dracula would also like to track information about interventions. Despite Wolfman’s concerns, Dracula creates a interventions project inside his cases project and initialize Git. Dracula uses a sequence of commands in the Rstudio Console:

R

usethis::create_project(path = "interventions")
usethis::use_git()

Is the usethis::use_git() command, run inside the interventions subdirectory, required for tracking files stored in the interventions subdirectory?

No. Dracula does not need to make the interventions subdirectory a Git repository because the cases repository can track any files, sub-directories, and subdirectory files under the cases directory. Thus, in order to track all information about interventions, Dracula only needed to add the interventions subdirectory to the cases directory.

Additionally, Git repositories can interfere with each other if they are “nested”: the outer repository will try to version-control the inner repository. Therefore, it’s best to create each new Git repository in a separate directory. To be sure that there is no conflicting repository in the directory, check the output of git status from the Terminal. If it looks like the following, you are good to go to create a new repository as shown above:

BASH

$ git status

OUTPUT

fatal: Not a git repository (or any of the parent directories): .git

Actually, if you try to create a new project using usethis within the cases repository, you will get this message:

R

usethis::create_project(path = "interventions")

OUTPUT

New project 'interventions' is nested inside an existing project './', which is rarely a good idea.
If this is unexpected, the here package has a function, `here::dr_here()` that reveals why './' is regarded as a project.
Do you want to create anyway?

Using the R functions from the usethis package can be less error-prone!

Lastly, Dracula used a Bash commands in the Terminal to create a subdirectory.

$ mkdir interventions    # make a subdirectory cases/interventions

If you are interested to learn more about Bash commands, we invite you to read this tutorial on Bash commands!

Places to Create Git Repositories (continued)

Key Points

  • Use usethis::use_git() to initialize a repository.
  • Git stores all of its repository data in the .git directory.
  • Use git status in the Terminal to check the status of a repository.

Content from Tracking Changes


Last updated on 2024-03-12 | Edit this page

Estimated time: 45 minutes

Overview

Questions

  • How do I record changes in Git?
  • How do I check the status of my version control repository?
  • How do I record notes about what changes I made and why?

Objectives

  • Go through the modify-add-commit cycle for one or more files.
  • Explain where information is stored at each stage of that cycle.
  • Distinguish between descriptive and non-descriptive commit messages.

Let’s start to tell the story of your project while you are working on it!

The Console and the Terminal

In this episode, we are going to use both, the Console and the Terminal.

So look at the upper right corner of the code chunks in this episode:

  • R < > belongs to the Console.
  • BASH < > belongs to the Terminal.

Add changes


First, in the Rstudio Console, let’s make sure we’re still in the right R project. You should be in the cases directory.

R

usethis::proj_path()

OUTPUT

C:/~/cases

Let’s create a file called sitrep.Rmd that contains the situation report (Sitrep) describing the data in terms of person, time, and place.

We can do this from the Console. Run:

R

usethis::edit_file("sitrep.Rmd")
• Modify 'sitrep.Rmd'

This opens the file in the Source pane to edit it.

Type the text below into the sitrep.Rmd file:

OUTPUT

Comparison of attack rates in different age groups

Save the file.

Checklist

Remember always to Save the file. Only saved files are recognized by Git.

Now, in the Terminal, if we check the status of our project again, Git tells us that it’s noticed the new file:

BASH

$ git status

OUTPUT

On branch main

No commits yet

Untracked files:
   (use "git add <file>..." to include in what will be committed)

	sitrep.Rmd

nothing added to commit but untracked files present (use "git add" to track)

The “untracked files” message means that there’s a file in the directory that Git isn’t keeping track of. We can tell Git to track a file using git add:

BASH

$ git add sitrep.Rmd

and then check that the right thing happened:

BASH

$ git status

OUTPUT

On branch main

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

	new file:   sitrep.Rmd

Commit changes


Git now knows that it’s supposed to keep track of sitrep.Rmd, but it hasn’t recorded these changes as a commit yet. To get it to do that, in the Terminal, we need to run one more command:

BASH

$ git commit -m "Start Sitrep with attack rate analysis"

OUTPUT

[main (root-commit) f22b25e] Start Sitrep with attack rate analysis
 1 file changed, 1 insertion(+)
 create mode 100644 sitrep.Rmd

When we run git commit, Git takes everything we have told it to save by using git add and stores a copy permanently inside the special .git directory. This permanent copy is called a commit (or revision) and its short identifier is f22b25e. Your commit may have another identifier.

We use the -m flag (for “message”) to record a short, descriptive, and specific comment that will help us remember later on what we did and why. If we just run git commit without the -m option, Git will launch VIM (or whatever other editor we configured as core.editor) so that we can write a longer message.

Exiting Vim

Note that Vim is the default editor for many programs. If you haven’t used Vim before and wish to exit a session without saving your changes, press Esc then type :q! and hit Enter or or on Macs, Return. If you want to save your changes and quit, press Esc then type :wq and hit Enter or or on Macs, Return.

With Rstudio you don’t need to do change any editor. You can open all your files in the Source pane.

Also, to write commit messages you can use the Rstudio IDE. We invite you to read the supplemental episode.

However, if needed, Dracula can set his favorite text editor following this table:

Editor Configuration command
Atom $ git config --global core.editor "atom --wait"
nano $ git config --global core.editor "nano -w"
BBEdit (Mac, with command line tools) $ git config --global core.editor "bbedit -w"
Sublime Text (Mac) $ git config --global core.editor "/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl -n -w"
Sublime Text (Win, 32-bit install) $ git config --global core.editor "'c:/program files (x86)/sublime text 3/sublime_text.exe' -w"
Sublime Text (Win, 64-bit install) $ git config --global core.editor "'c:/program files/sublime text 3/sublime_text.exe' -w"
Notepad (Win) $ git config --global core.editor "c:/Windows/System32/notepad.exe"
Notepad++ (Win, 32-bit install) $ git config --global core.editor "'c:/program files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Notepad++ (Win, 64-bit install) $ git config --global core.editor "'c:/program files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Kate (Linux) $ git config --global core.editor "kate"
Gedit (Linux) $ git config --global core.editor "gedit --wait --new-window"
Scratch (Linux) $ git config --global core.editor "scratch-text-editor"
Emacs $ git config --global core.editor "emacs"
Vim $ git config --global core.editor "vim"
VS Code $ git config --global core.editor "code --wait"

It is possible to reconfigure the text editor for Git whenever you want to change it.

Good commit messages start with a brief (<50 characters) statement about the changes made in the commit. Generally, the message should complete the sentence “If applied, this commit will” . If you want to go into more detail, add a blank line between the summary line and your additional notes. Use this additional space to explain why you made changes and/or what their impact will be.

Good practice

A good commit:

  • Contains less than 50 characters in first line.

  • Start with an infinitive verb.

  • Recalls an specific action.

If we run git status now:

BASH

$ git status

OUTPUT

On branch main
nothing to commit, working tree clean

it tells us everything is up to date.

Show the history


If we want to know what we’ve done recently, in the Terminal, we can ask Git to show us the project’s history using git log:

BASH

$ git log

OUTPUT

commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 09:51:46 2013 -0400

    Start Sitrep with attack rate analysis

git log lists all commits made to a repository in reverse chronological order. The listing for each commit includes the commit’s full identifier (which starts with the same characters as the short identifier printed by the git commit command earlier), the commit’s author, when it was created, and the log message Git was given when the commit was created.

These commands are so similar!

The git status command displays the state of the working directory and the staging area. It lets you see which changes have been staged, which haven’t, and which files aren’t being tracked by Git. Status output does not show you any information regarding the committed project history (the local repository). For this, you need to use git log. (Atlassian, 2023)

Where Are My Changes?

If, in the Terminal, we run ls at this point, we will still see just one file called sitrep.Rmd. That’s because Git saves information about files’ history in the special .git directory mentioned earlier so that our filesystem doesn’t become cluttered (and so that we can’t accidentally edit or delete an old version).

Compare changes


Now suppose Dracula adds more information to the file. For this, let’s return to the sitrep.Rmd file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions

Save the file.

In the Terminal, when we run git status now, it tells us that a file it already knows about has been modified:

BASH

$ git status

OUTPUT

On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   sitrep.Rmd

no changes added to commit (use "git add" and/or "git commit -a")

The last line is the key phrase: “no changes added to commit”. We have changed this file, but we haven’t told Git we will want to save those changes (which we do with git add) nor have we saved them (which we do with git commit). So let’s do that now. It is good practice to always review our changes before saving them. In the Terminal, we do this using git diff. This shows us the differences between the current state of the file and the most recently saved version:

BASH

$ git diff

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index df0654a..315bf3a 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1 +1,2 @@
 Comparison of attack rates in different age groups
+This can identify priority groups for interventions

The output is cryptic because it is actually a series of commands for tools like editors and patch telling them how to reconstruct one file given the other. If we break it down into pieces:

  1. The first line tells us that Git is producing output similar to the Unix diff command comparing the old and new versions of the file.
  2. The second line tells exactly which versions of the file Git is comparing; df0654a and 315bf3a are unique computer-generated labels for those versions.
  3. The third and fourth lines once again show the name of the file being changed.
  4. The remaining lines are the most interesting, they show us the actual differences and the lines on which they occur. In particular, the + marker in the first column shows where we added a line.

Staging area


After reviewing our change, it’s time to commit it:

BASH

$ git commit -m "Add purpose of attack rate analysis"

OUTPUT

On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   sitrep.Rmd

no changes added to commit (use "git add" and/or "git commit -a")

Whoops: Git won’t commit because we didn’t use git add first. Let’s fix that:

BASH

$ git add sitrep.Rmd
$ git commit -m "Add purpose of attack rate analysis"

OUTPUT

[main 34961b1] Add purpose of attack rate analysis
 1 file changed, 1 insertion(+)

Git insists that we add files to the set we want to commit before actually committing anything. This allows us to commit our changes in stages and capture changes in logical portions rather than only large batches. For example, suppose we’re adding a few citations to relevant research to our thesis. We might want to commit those additions, and the corresponding bibliography entries, but not commit some of our work drafting the conclusion (which we haven’t finished yet).

To allow for this, Git has a special staging area where it keeps track of things that have been added to the current changeset but not yet committed.

The staging area is the middle ground between what you have done to your files (also known as the working directory) and what you had last committed (the HEAD commit). As the name implies, the staging area gives you space to prepare (stage) the changes that will be reflected on the next commit. (Coderefinery, 2023)

What is the use of the Staging area?

Read a testimony from StackOver Flow.

Staging Area

If you think of Git as taking snapshots of changes over the life of a project, git add specifies what will go in a snapshot (putting things in the staging area), and git commit then actually takes the snapshot, and makes a permanent record of it (as a commit). If you don’t have anything staged when you type git commit, Git will prompt you to use git commit -a or git commit --all, which is kind of like gathering everyone to take a group photo! However, it’s almost always better to explicitly add things to the staging area, because you might commit changes you forgot you made. (Going back to the group photo simile, you might get an extra with incomplete makeup walking on the stage for the picture because you used -a!) Try to stage things manually, or you might find yourself searching for “git undo commit” more than you would like!

The Git Staging Area

Checklist

Use git status to display the state of the working directory and the staging area. git add your changes before you git commit them to the Local repository. Use the git log to get the history of changes in it. Use git diff to compare these changes.
Use git status to display the state of the working directory and the staging area. git add your changes before you git commit them to the Local repository. Use the git log to get the history of changes in it. Use git diff to compare these changes.

Group Challenges


Choosing a Commit Message

Which of the following commit messages would be most appropriate for the last commit made to sitrep.Rmd?

  1. “Changes”
  2. “Added line ‘Maps illustrate the spread and impact of outbreak’ to sitrep.Rmd”
  3. “Discuss effects of Sitrep’ climate on the Mummy”

Answer 1 is not descriptive enough, and the purpose of the commit is unclear; and answer 2 is redundant to using “git diff” to see what changed in this commit; but answer 3 is good: short, descriptive, and imperative.

Committing Changes to Git

Which command(s) below would save the changes of myfile.txt to my local Git repository?

  1. BASH

      $ git commit -m "my recent changes"
  2. BASH

      $ git init myfile.txt
      $ git commit -m "my recent changes"
  3. BASH

      $ git add myfile.txt
      $ git commit -m "my recent changes"
  4. BASH

      $ git commit -m myfile.txt "my recent changes"
  1. Would only create a commit if files have already been staged.
  2. Would try to create a new repository.
  3. Is correct: first add the file to the staging area, then commit.
  4. Would try to commit a file “my recent changes” with the message myfile.txt.

Your turn!

Take 10 minutes to the following two sections:

  • Practice the workflow
  • Relevant callouts

If you want to keep practicing, move to the last one:

  • Individual Challenges

Practice the workflow


Let’s watch as our changes to a file move from our editor to the staging area and into long-term storage. First, in the Console, we’ll add another line to the file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak

Save the file.

In the Terminal, check the difference:

BASH

$ git diff

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index 315bf3a..b36abfd 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1,2 +1,3 @@
 Comparison of attack rates in different age groups
 This can identify priority groups for interventions
+Maps illustrate the spread and impact of outbreak

So far, so good: we’ve added one line to the end of the file (shown with a + in the first column). Now let’s put that change in the staging area and see what git diff reports:

BASH

$ git add sitrep.Rmd
$ git diff

There is no output: as far as Git can tell, there’s no difference between what it’s been asked to save permanently and what’s currently in the directory. However, if we do this:

BASH

$ git diff --staged

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index 315bf3a..b36abfd 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1,2 +1,3 @@
 Comparison of attack rates in different age groups
 This can identify priority groups for interventions
+Maps illustrate the spread and impact of outbreak

it shows us the difference between the last committed change and what’s in the staging area. Let’s save our changes:

BASH

$ git commit -m "Add geospatial visualization objective"

OUTPUT

[main 005937f] Add geospatial visualization objective
 1 file changed, 1 insertion(+)

check our status:

BASH

$ git status

OUTPUT

On branch main
nothing to commit, working tree clean

and look at the history of what we’ve done so far:

BASH

$ git log

OUTPUT

commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 10:14:07 2013 -0400

    Add geospatial visualization objective

commit 34961b159c27df3b475cfe4415d94a6d1fcd064d
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 10:07:21 2013 -0400

    Add purpose of attack rate analysis

commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 09:51:46 2013 -0400

    Start Sitrep with attack rate analysis

Relevant callouts


Word-based diffing

Sometimes, e.g. in the case of the text documents a line-wise diff is too coarse. That is where the --color-words option of git diff comes in very useful as it highlights the changed words using colors.

Paging the Log

When the output of git log is too long to fit in your screen, git uses a program to split it into pages of the size of your screen. When this “pager” is called, you will notice that the last line in your screen is a :, instead of your usual prompt.

  • To get out of the pager, press Q.
  • To move to the next page, press Spacebar.
  • To search for some_word in all pages, press / and type some_word. Navigate through matches pressing N.

Limit Log Size

To avoid having git log cover your entire terminal screen, you can limit the number of commits that Git lists by using -N, where N is the number of commits that you want to view. For example, if you only want information from the last commit you can use:

BASH

$ git log -1

OUTPUT

commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 10:14:07 2013 -0400

   Add geospatial visualization objective

You can also reduce the quantity of information using the --oneline option:

BASH

$ git log --oneline

OUTPUT

005937f (HEAD -> main) Add geospatial visualization objective
34961b1 Add purpose of attack rate analysis
f22b25e Start Sitrep with attack rate analysis

You can also combine the --oneline option with others. One useful combination adds --graph to display the commit history as a text-based graph and to indicate which commits are associated with the current HEAD, the current branch main, or other Git references:

BASH

$ git log --oneline --graph

OUTPUT

* 005937f (HEAD -> main) Add geospatial visualization objective
* 34961b1 Add purpose of attack rate analysis
* f22b25e Start Sitrep with attack rate analysis

Directories

Two important facts you should know about directories in Git.

Git track files, not empty directories

  1. Git does not track directories on their own, only files within them. Try it for yourself using the Terminal:

BASH

$ mkdir analyses
$ git status
$ git add analyses
$ git status

Note, our newly created empty directory analyses does not appear in the list of untracked files even if we explicitly add it (via git add) to our repository. This is the reason why you will sometimes see .gitkeep files in otherwise empty directories. Unlike .gitignore, these files are not special and their sole purpose is to populate a directory so that Git adds it to the repository. In fact, you can name such files anything you like.

  1. If you create a directory in your Git repository and populate it with files, you can add all files in the directory at once by:

BASH

git add <directory-with-files>

Try it for yourself:

BASH

$ touch analyses/attack-rate.R analyses/geospatial.R
$ git status
$ git add analyses
$ git status

Before moving on, we will commit these changes.

BASH

$ git commit -m "Add analysis scripts on attack rate and geospatial"

To recap, when we want to add changes to our repository, we first need to add the changed files to the staging area (git add) and then commit the staged changes to the repository (git commit):

The Git Commit Workflow

Individual Challenges


Committing Multiple Files

The staging area can hold changes from any number of files that you want to commit as a single snapshot.

  1. Add some text to sitrep.Rmd noting your decision to consider a data cleaning preliminary step.
  2. Create a new file clean.Rmd with your initial thoughts about Data as an step for you and your friends.
  3. Add changes from both files to the staging area, and commit those changes.

The output below from sitrep.Rmd reflects only content added during this exercise. Your output may vary.

First we make our changes to the sitrep.Rmd and clean.Rmd files:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Maybe I should start with a data cleaning step.

R

usethis::edit_file("clean.Rmd")

OUTPUT

Data is a messy file and I definitely should consider a data cleaning step.

Save both files.

Now you can add both files to the staging area. We can do that in one line:

BASH

$ git add sitrep.Rmd clean.Rmd

Or with multiple commands:

BASH

$ git add sitrep.Rmd
$ git add clean.Rmd

Now the files are ready to commit. You can check that using git status. If you are ready to commit use:

BASH

$ git commit -m "Write plans to start a data cleaning step"

OUTPUT

[main cc127c2]
 Write plans to start a data cleaning step
 2 files changed, 2 insertions(+)
 create mode 100644 clean.Rmd

bio Repository

  • Create a new Git repository on your computer called bio.
  • Write a three-line biography for yourself in a file called me.md, commit your changes
  • Modify one line, add a fourth line
  • Display the differences between its updated state and its original state.

If needed, create a project out of the cases folder:

R

usethis::create_project(path = "bio")

Initialise git:

R

usethis::use_git()

Create your biography file me.md using the Rstudio editor.

R

usethis::edit_file("me.md")

Save the file.

Once in place, in the Terminal add and commit it to the repository:

BASH

$ git add me.md
$ git commit -m "Add biography file" 

Modify the file as described (modify one line, add a fourth line). To display the differences between its updated state and its original state, use git diff:

BASH

$ git diff me.md

Key Points

  • git status shows the status of a repository.
  • Files can be stored in a project’s working directory (which users see), the staging area (where the next commit is being built up) and the local repository (where commits are permanently recorded).
  • git add puts files in the staging area.
  • git commit saves the staged content as a new commit in the local repository.
  • Write a commit message that accurately describes your changes.

Content from Ignoring Things


Last updated on 2024-03-05 | Edit this page

Estimated time: 5 minutes

Overview

Questions

  • How can I tell Git to ignore files I don’t want to track?

Objectives

  • Configure Git to ignore specific files.
  • Explain why ignoring files can be useful.

What not to put under Version Control?


In the section called “What Not to Put Under Version Control” from G. Wilson et al. 2017 on Good Enough Practices in Scientific Computing, authors emphasize, among other notes, in three points:

  • Version control systems are optimized for plain-text files;
  • Avoid raw data, since it should not change;
  • Avoid intermediate files or results that can be re-generated from raw data and software.

Ignore files


What if we have files that we do not want Git to track for us, like backup files created by our editor or intermediate files created during data analysis? For example, .csv files exported from the reader::write_csv() function or .png files from ggplot2::ggsave(). Let’s create a few dummy files in the Terminal:

BASH

$ mkdir figures
$ touch a.csv b.csv c.csv figures/a.png figures/b.png

and see what Git says:

BASH

$ git status

OUTPUT

On branch main
Untracked files:
  (use "git add <file>..." to include in what will be committed)

	a.csv
	b.csv
	c.csv
	figures/

nothing added to commit but untracked files present (use "git add" to track)

Putting these files under version control would be a waste of disk space. What’s worse, having them all listed could distract us from changes that actually matter, so let’s tell Git to ignore them.

We do this by creating a file in the root directory of our project called .gitignore. In the console, let’s use:

R

usethis::edit_file(".gitignore")

Write these patterns and save the file:

OUTPUT

*.csv
figures/

These patterns tell Git to ignore any file whose name ends in .csv and everything in the figures directory. (If any of these files were already being tracked, Git would continue to track them.)

Once we have created this file, the output of git status is much cleaner. In the terminal:

BASH

$ git status

OUTPUT

On branch main
Untracked files:
  (use "git add <file>..." to include in what will be committed)

	.gitignore

nothing added to commit but untracked files present (use "git add" to track)

The only thing Git notices now is the newly-created .gitignore file. You might think we wouldn’t want to track it, but everyone we’re sharing our repository with will probably want to ignore the same things that we’re ignoring. Let’s add and commit .gitignore:

BASH

$ git add .gitignore
$ git commit -m "Ignore data files and the figures folder"
$ git status

OUTPUT

On branch main
nothing to commit, working tree clean

As a bonus, using .gitignore helps us avoid accidentally adding files to the repository that we don’t want to track:

BASH

$ git add a.csv

OUTPUT

The following paths are ignored by one of your .gitignore files:
a.csv
Use -f if you really want to add them.

If we really want to override our ignore settings, we can use git add -f to force Git to add something. For example, git add -f a.csv. We can also always see the status of ignored files if we want:

BASH

$ git status --ignored

OUTPUT

On branch main
Ignored files:
 (use "git add -f <file>..." to include in what will be committed)

        a.csv
        b.csv
        c.csv
        figures/

nothing to commit, working tree clean

Good Practice

A good version control project:

  • Use it mostly for plain-text files

  • Avoid raw data.

  • Avoid intermediate files or results.

Your turn!

Take 5 minutes to the following two challenges:

  • Ignoring Nested Files
  • Including Specific Files

If you want to keep practicing, move to the last one:

  • Home challenges

Live challenges


Ignoring Nested Files

Given a directory structure that looks like:

BASH

outputs/paper
outputs/templates

How would you ignore only outputs/templates and not outputs/paper?

If you only want to ignore the contents of outputs/templates, you can change your .gitignore to ignore only the /templates/ subfolder by adding the following line to your .gitignore:

OUTPUT

outputs/templates/

This line will ensure only the contents of outputs/templates is ignored, and not the contents of outputs/paper.

As with most programming issues, there are a few alternative ways that one may ensure this ignore rule is followed. The “Ignoring Nested Files: Variation” exercise has a slightly different directory structure that presents an alternative solution. Further, the discussion page has more detail on ignore rules.

Including Specific Files

How would you ignore all .csv files in your root directory except for final.csv?

Find out what ! (the exclamation point operator) does for gitignore in the Git Reference documentation.

You would add the following two lines to your .gitignore:

OUTPUT

*.csv           # ignore all data files
!final.csv      # except final.csv

The exclamation point operator will include a previously excluded entry.

Note also that because you’ve previously committed .csv files in this lesson they will not be ignored with this new rule. Only future additions of .csv files added to the root directory will be ignored.

Home challenges


Ignoring Nested Files: Variation

Given a directory structure that looks similar to the earlier Nested Files exercise, but with a slightly different directory structure:

BASH

outputs/paper
outputs/templates
outputs/slides
outputs/tables

How would you ignore all of the contents in the outputs folder, but not outputs/paper?

Hint: think a bit about how you created an exception with the ! operator before.

If you want to ignore the contents of outputs/ but not those of outputs/paper/, you can change your .gitignore to ignore the contents of outputs folder, but create an exception for the contents of the outputs/paper subfolder. Your .gitignore would look like this:

OUTPUT

outputs/*               # ignore everything in outputs folder
!outputs/paper/          # do not ignore outputs/paper/ contents

Ignoring all data Files in a Directory

Assuming you have an empty .gitignore file, and given a directory structure that looks like:

BASH

data/household/position/gps/a.csv
data/household/position/gps/b.csv
data/household/position/gps/c.csv
data/household/position/gps/info.txt
data/survey

What’s the shortest .gitignore rule you could write to ignore all .csv files in data/household/position/gps? Do not ignore the info.txt.

Appending data/household/position/gps/*.csv will match every file in data/household/position/gps that ends with .csv. The file data/household/position/gps/info.txt will not be ignored.

Ignoring all CSV data Files in the repository

Let us assume you have many .csv files in different subdirectories of your repository. For example, you might have:

BASH

outputs/a.csv
data/household/b.csv
data/survey/c.csv
data/survey/area_1/d.csv

How do you ignore all the .csv files, without explicitly listing the names of the corresponding folders?

In the .gitignore file, write:

OUTPUT

**/*.csv

This will ignore all the .csv files, regardless of their position in the directory tree. You can still include some specific exception with the exclamation point operator.

The Order of Rules

Given a .gitignore file with the following contents:

BASH

*.csv
!*.csv

What will be the result?

The ! modifier will negate an entry from a previously defined ignore pattern. Because the !*.csv entry negates all of the previous .csv files in the .gitignore, none of them will be ignored, and all .csv files will be tracked.

Log Files

You wrote a script that creates many intermediate log-files of the form log_01, log_02, log_03, etc. You want to keep them but you do not want to track them through git.

  1. Write one .gitignore entry that excludes files of the form log_01, log_02, etc.

  2. Test your “ignore pattern” by creating some dummy files of the form log_01, etc.

  3. You find that the file log_01 is very important after all, add it to the tracked files without changing the .gitignore again.

  4. Discuss with your neighbor what other types of files could reside in your directory that you do not want to track and thus would exclude via .gitignore.

  1. append either log_* or log* as a new entry in your .gitignore
  2. track log_01 using git add -f log_01

Key Points

  • Avoid the version control of raw data, intermediate files and results that can be re-generated from raw data and software.
  • The .gitignore file tells Git what files to ignore.

Content from Remotes in GitHub


Last updated on 2024-03-12 | Edit this page

Estimated time: 45 minutes

Overview

Questions

  • How do I share my changes with others on the web?

Objectives

  • Explain what remote repositories are and why they are useful.
  • Push to or pull from a remote repository.

PREREQUISITES

When using usethis::git_sitrep(), check if there is no ✖ ... line in the output with an error message.

If you an error message like ✖ Token lacks ... or ✖ Can't retrieve registered email, follow the steps in episode 2 to solve it.

Version control really comes into its own when we begin to collaborate with other people. We already have most of the machinery we need to do this; the only thing missing is to copy changes from one repository to another.

Systems like Git allow us to move work between any two repositories. In practice, though, it’s easiest to use one copy as a central hub, and to keep it on the web rather than on someone’s laptop. Most programmers use hosting services like GitHub, Bitbucket or GitLab to hold those main copies; we’ll explore the pros and cons of this in a later episode.

Let’s start by sharing the changes we’ve made to our current project with the world. To this end we are going to create a remote repository that will be linked to our local repository.

How to connect from Local to GitHub?


From your local R project, after using usethis::use_git() to initialise your Local repository, then you can also use usethis to connect it with the Remote repository (a.k.a, “the remote”):

R

usethis::use_github()

OUTPUT

ℹ Defaulting to 'https' Git protocol
✔ Creating GitHub repository 'vlad/cases'
✔ Setting remote 'origin' to 'https://github.com/vlad/cases.git'
✔ Pushing 'main' branch to GitHub and setting 'origin/main' as upstream branch
✔ Opening URL 'https://github.com/vlad/cases'

This will open a new tab in your web browser with the URL path of your remote repository in GitHub.

You can use usethis::use_github() to create a remote repository, connect the local and the remote, and push your local changes to a remote.

R

usethis::git_sitrep()

The output in the last section called ── GitHub project should look like this:

OUTPUT

── GitHub project
• Type = 'ours'
• Host = 'https://github.com'
• Config supports a pull request = TRUE
• origin = 'vlad/cases' (can push)
• upstream = <not configured>
• Desc = 'origin' is both the source and primary repo.

The (can push) line of the output above is critical!

If you remember back to the earlier episode where we added and committed our earlier work on sitrep.Rmd, we had a diagram of the local repository which looked like this:

The Local Repository with Git Staging Area

Now that we have two repositories, we need a diagram like this:

Freshly-Made GitHub Repository

Note that our local repository still contains our earlier work on sitrep.Rmd, but the remote repository on GitHub appears empty as it doesn’t contain any files yet.

We’ll discuss remotes in more detail in the next episode, while talking about how they might be used for collaboration.

1. Create a remote repository

Log in to GitHub, then click on the icon in the top right corner to create a new repository called cases:

Creating a Repository on GitHub (Step 1)

Name your repository cases and then click “Create Repository”.

Note: Since this repository will be connected to a local repository, it needs to be empty. Leave “Initialize this repository with a README” unchecked, and keep “None” as options for both “Add .gitignore” and “Add a license.” See the “GitHub License and README files” exercise below for a full explanation of why the repository needs to be empty.

Creating a Repository on GitHub (Step 2)

As soon as the repository is created, GitHub displays a page with a URL and some information on how to configure your local repository:

Creating a Repository on GitHub (Step 3)

This effectively does the following on GitHub’s servers:

BASH

$ mkdir cases # creates a working directory 
$ cd cases    # go into cases directory
$ git init    # make the cases directory a Git repository

If you remember back to the earlier episode where we added and committed our earlier work on sitrep.Rmd, we had a diagram of the local repository which looked like this:

The Local Repository with Git Staging Area

Now that we have two repositories, we need a diagram like this:

Freshly-Made GitHub Repository

Note that our local repository still contains our earlier work on sitrep.Rmd, but the remote repository on GitHub appears empty as it doesn’t contain any files yet.

2. Connect local to remote repository

Now we connect the two repositories. We do this by making the GitHub repository a remote for the local repository. The home page of the repository on GitHub includes the URL string we need to identify it:

Where to Find Repository URL on GitHub

HTTPS vs. SSH

The current recommendation is HTTPS because it is the easiest to set up on the widest range of networks and platforms, and by users who are new to all this. HTTPS is less likely to be blocked by a firewall. (StackOverflow, 2012)

Copy that URL from the browser, go into the local cases repository, and run this command:

BASH

$ git remote add origin https://github.com/vlad/cases.git

Make sure to use the URL for your repository rather than Vlad’s: the only difference should be your username instead of vlad.

origin is a local name used to refer to the remote repository. It could be called anything, but origin is a convention that is often used by default in git and GitHub, so it’s helpful to stick with this unless there’s a reason not to.

We can check that the command has worked by running git remote -v:

BASH

$ git remote -v

OUTPUT

origin   git@github.com:vlad/cases.git (fetch)
origin   git@github.com:vlad/cases.git (push)

3. Push local changes to a remote

Now that authentication is setup, we can return to the remote. This command will push the changes from our local repository to the repository on GitHub:

BASH

$ git push origin main

Since Dracula set up a passphrase, it will prompt him for it. If you completed advanced settings for your authentication, it will not prompt for a passphrase.

OUTPUT

Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 8 threads.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (16/16), 1.45 KiB | 372.00 KiB/s, done.
Total 16 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), done.
To https://github.com/vlad/cases.git
 * [new branch]      main -> main

Push local changes to a remote


We can add new changes to the remote repository. Let’s make a change to sitrep.Rmd, adding yet another line.

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
Read shapefiles with the {sf} R package

Add and commit this change to the local repository:

BASH

git add sitrep.Rmd
git commit -m "Add package to read spatial data"

This command will push the changes from our local repository to the repository on GitHub:

BASH

$ git push origin main

Since Dracula set up a passphrase, it will prompt him for it. If you completed advanced settings for your authentication, it will not prompt for a passphrase.

OUTPUT

Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 8 threads.
Compressing objects: 100% (11/11), done.
Writing objects: 100% (16/16), 1.45 KiB | 372.00 KiB/s, done.
Total 16 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), done.
To https://github.com/vlad/cases.git
 * [new branch]      main -> main

If your operating system has a password manager configured, git push will try to use it when it needs your username and password. For example, this is the default behavior for Git Bash on Windows. If you want to type your username and password at the terminal instead of using a password manager, type:

BASH

$ unset SSH_ASKPASS

in the terminal, before you run git push. Despite the name, Git uses SSH_ASKPASS for all credential entry, so you may want to unset SSH_ASKPASS whether you are using Git via SSH or https.

You may also want to add unset SSH_ASKPASS at the end of your ~/.bashrc to make Git default to using the terminal for usernames and passwords.

Our local and remote repositories are now in this state:

GitHub Repository After First Push

You may see a -u option used with git push in some documentation. This option is synonymous with the --set-upstream-to option for the git branch command, and is used to associate the current branch with a remote branch so that the git pull command can be used without any arguments. To do this, simply use git push -u origin main once the remote has been set up.

Challenge

For the Outbreak response, along with tracking information about cases (the project we have already created), Dracula would also like to track information about interventions.

  1. Create new local repository for interventions and connect it with a remote repository.

  2. Create a read-data.R file.

  3. Add and commit that change to the local repository.

  4. Push that change to the remote repository.

First, if you are in Rstudio, close your R Project from File > Close Project.

In the Console, run:

R

# create a new R project in a new directory
usethis::create_project(path = "interventions")

# make the interventions directory a Git local repository
usethis::use_git()

# 1. create a GitHub remote repository
# 2. connect local with remote
# 3. push content to remote
usethis::use_github()

Create the file

R

usethis::edit_file("read-data.R")

In the Terminal, run:

BASH

$ git add read-data.R
$ git commit -m "Add read data file"
$ git push

Pull changes


We can pull changes from the remote repository to the local one as well:

BASH

$ git pull origin main

OUTPUT

From https://github.com/vlad/cases
 * branch            main     -> FETCH_HEAD
Already up-to-date.

Pulling has no effect in this case because the two repositories are already synchronized. If someone else had pushed some changes to the repository on GitHub, though, this command would download them to our local repository.

Group Challenges


Take 5 minutes to solve this challenge!

GitHub License and README files

In this episode we learned about creating a remote repository on GitHub, but when you initialized your GitHub repo, you didn’t add a README.md or a license file.

  1. Create a README file in the remote repository.

  2. Pull your changes from the remote to the local repository.

Click in the Add README option.

Copy and paste this minimal template of a README.md file:

# Situational Report

This is a report for a disease outbreak investigation by Outbreak Missions.

## Files

- sitrep.Rmd

## Authors

- Wolfman
- Dracula

To pull changes from remote to local, use this command:

BASH

$ git pull

If you are interested on how to write good READMEs, we invite you to review a dedicated episode in the Improve your code for Epidemic Analysis with R tutorial website!

Share your online repository!

This tutorial have a Discussions board also hosted in GitHub.

  1. Access to this Welcome entry

  2. Share with us a link to the case repository you just uploaded! (For example, this is the link to the repository of one of our participants https://github.com/avallecam/cases)

Checklist

Use git pull to download content from a remote repository to the workspace and update the local repository to match that content. Use git push to upload local repository content to a remote repository.
Use git pull to download content from a remote repository to the workspace and update the local repository to match that content. Use git push to upload local repository content to a remote repository.

Individual Challenges


GitHub GUI

Browse to your cases repository on GitHub. Underneath the Code button, find and click on the text that says “XX commits” (where “XX” is some number). Hover over, and click on, the three buttons to the right of each commit. What information can you gather/explore from these buttons? How would you get that same information in the shell?

The left-most button (with the picture of a clipboard) copies the full identifier of the commit to the clipboard. In the shell, git log will show you the full commit identifier for each commit.

When you click on the middle button, you’ll see all of the changes that were made in that particular commit. Green shaded lines indicate additions and red ones removals. In the shell we can do the same thing with git diff. In particular, git diff ID1..ID2 where ID1 and ID2 are commit identifiers (e.g. git diff a3bf1e5..041e637) will show the differences between those two commits.

The right-most button lets you view all of the files in the repository at the time of that commit. To do this in the shell, we’d need to checkout the repository at that particular time. We can do this with git checkout ID where ID is the identifier of the commit we want to look at. If we do this, we need to remember to put the repository back to the right state afterwards!

Uploading files directly in GitHub browser

Github also allows you to skip the command line and upload files directly to your repository without having to leave the browser. There are two options. First you can click the “Upload files” button in the toolbar at the top of the file tree. Or, you can drag and drop files from your desktop onto the file tree. You can read more about this on this GitHub page.

GitHub Timestamp

Create a remote repository on GitHub. Push the contents of your local repository to the remote. Make changes to your local repository and push these changes. Go to the repo you just created on GitHub and check the timestamps of the files. How does GitHub record times, and why?

GitHub displays timestamps in a human readable relative format (i.e. “22 hours ago” or “three weeks ago”). However, if you hover over the timestamp, you can see the exact time at which the last change to the file occurred.

Push vs. Commit

In this episode, we introduced the “git push” command. How is “git push” different from “git commit”?

When we push changes, we’re interacting with a remote repository to update it with the changes we’ve made locally (often this corresponds to sharing the changes we’ve made with others). Commit only updates your local repository.

Key Points

  • A local Git repository can be connected to one or more remote repositories.
  • Use usethis::use_github() to connect to a remote repository.
  • git push copies changes from a local repository to a remote repository.
  • git pull copies changes from a remote repository to a local repository.

Content from Collaborating


Last updated on 2024-03-05 | Edit this page

Estimated time: 25 minutes

Overview

Questions

  • How can I use version control to collaborate with other people?

Objectives

  • Clone a remote repository.
  • Collaborate by pushing to a common repository.
  • Describe the basic collaborative workflow.

Paper Writing


From the first episode!

Imagine you have 3 co-authors. How would you manage the changes and comments they make to your paper?

If you use Google Docs, you can have access to the history of changes, and also identify how made those changes.

For plain-text files, you can use GitHub to see the changes made per commit. In the left side or in color red are the deletions and in the right side or in color green the additions.

Additionally, in GitHub you can use the option Blame to read the authors of changes per line. In this way, you can also read any related comment regarding why an specific line was edited.

All of these is possible with a collaboration workflow between contributors using Git and GitHub!

Checklist

Key characteristics of Version control systems are:

  1. Keep the entire history of a file and inspect a file throughout its lifetime.

  2. Tag a particular version so you can return to them easily.

  1. Facilitates collaborations and makes contributions transparent.

Get a copy of remote


For the next step, get into pairs. One person will be the “Owner” and the other will be the “Collaborator”. The goal is that the Collaborator add changes into the Owner’s repository. We will switch roles at the end, so both persons will play Owner and Collaborator.

Practicing By Yourself

If you’re working through this lesson on your own, you can carry on by opening a second terminal window. This window will represent your partner, working on another computer. You won’t need to give anyone access on GitHub, because both ‘partners’ are you.

The Owner needs to give the Collaborator access. In your repository page on GitHub, click the “Settings” button on the right, select “Collaborators”, click “Add people”, and then enter your partner’s username.

screenshot of repository page with Settings then Collaborators selected, showing how to add Collaborators in a GitHub repository

To accept access to the Owner’s repo, the Collaborator needs to go to https://github.com/notifications or check for email notification. Once there she can accept access to the Owner’s repo.

Next, the Collaborator needs to download a copy of the Owner’s repository to her machine. This is called “cloning a repo”.

The Collaborator doesn’t want to overwrite her own version of cases.git, so needs to clone the Owner’s repository to a different location than her own repository with the same name.

Callout

First, if you are in Rstudio, close your R Project from File > Close Project.

To clone the Owner’s repo into Collaborator’s folder, in the Console, the Collaborator enters:

BASH

$ git clone https://github.com/vlad/cases.git vlad-cases

Replace ‘vlad’ with the Owner’s username.

Callout

If you choose to clone without the clone path (vlad-cases) specified at the end, you will clone inside your own cases folder!

ALSO: You only need to add the “clone path” when you have a local folder with the same name as the remote repository. This is not a common addition.

After Creating Clone of Repository
In the Outbreak response scenario, now Wolfman has a local copy of the remote repository. They are already set up to collaborate for one project!

Edit the clone


The Collaborator can now make a change in her clone of the Owner’s repository, exactly the same way as we’ve been doing before.

First, open the vlad-cases R project. If you are in Rstudio: File > New Project... and navigate to the directory location.

Now, let’s create a new file called dashboard.Rmd to complement our Situation report!

R

usethis::edit_file("dashboard.Rmd")

OUTPUT

Let's create a dashboard!

BASH

$ git add dashboard.Rmd
$ git commit -m "Add notes about Dashboard"

OUTPUT

 1 file changed, 1 insertion(+)
 create mode 100644 dashboard.Rmd

Then push the change to the Owner’s repository on GitHub:

BASH

$ git push origin main

OUTPUT

Enumerating objects: 4, done.
Counting objects: 4, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 306 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To https://github.com/vlad/cases.git
   9272da5..29aba7c  main -> main

Note that we didn’t have to create a remote called origin: Git uses this name by default when we clone a repository. (This is why origin was a sensible choice earlier when we were setting up remotes by hand.)

Take a look at the Owner’s repository on GitHub again, and you should be able to see the new commit made by the Collaborator. You may need to refresh your browser to see the new commit.

In this episode and the previous one, our local repository has had a single “remote”, called origin. A remote is a copy of the repository that is hosted somewhere else, that we can push to and pull from, and there’s no reason that you have to work with only one. For example, on some large projects you might have your own copy in your own GitHub account (you’d probably call this origin) and also the main “upstream” project repository (let’s call this upstream for the sake of examples). You would pull from upstream from time to time to get the latest updates that other people have committed.

Remember that the name you give to a remote only exists locally. It’s an alias that you choose - whether origin, or upstream, or fred - and not something intrinstic to the remote repository.

The git remote family of commands is used to set up and alter the remotes associated with a repository. Here are some of the most useful ones:

  • git remote -v lists all the remotes that are configured (we already used this in the last episode)
  • git remote add [name] [url] is used to add a new remote
  • git remote remove [name] removes a remote. Note that it doesn’t affect the remote repository at all - it just removes the link to it from the local repo.
  • git remote set-url [name] [newurl] changes the URL that is associated with the remote. This is useful if it has moved, e.g. to a different GitHub account, or from GitHub to a different hosting service. Or, if we made a typo when adding it!
  • git remote rename [oldname] [newname] changes the local alias by which a remote is known - its name. For example, one could use this to change upstream to fred.

Download contributor edits


To download the Collaborator’s changes from GitHub, in the Console, the Owner now enters:

BASH

$ git pull origin main

OUTPUT

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 3 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/vlad/cases
 * branch            main     -> FETCH_HEAD
   9272da5..29aba7c  main     -> origin/main
Updating 9272da5..29aba7c
Fast-forward
 dashboard.Rmd | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 dashboard.Rmd

Now the three repositories (Owner’s local, Collaborator’s local, and Owner’s on GitHub) are back in sync.

A Basic Collaborative Workflow

In practice, it is good to be sure that you have an updated version of the repository you are collaborating on, so you should git pull before making our changes. The basic collaborative workflow would be:

  • update your local repo with git pull origin main,
  • make your changes and stage them with git add,
  • commit your changes with git commit -m, and
  • upload the changes to GitHub with git push origin main

It is better to make many commits with smaller changes rather than of one commit with massive changes: small commits are easier to read and review.

Review Changes

The Owner pushed commits to the repository without giving any information to the Collaborator. How can the Collaborator find out what has changed with command line? And on GitHub?

On GitHub, the Collaborator can go to the repository and click on “commits” to view the most recent commits pushed to the repository.

Click on “commit”. Select one commit.
Click on “commit”. Select one commit.
Replace age with sex commit. The removed content within lines is in red. The added content within lines is in green.
Replace age with sex commit. The removed content within lines is in red. The added content within lines is in green.

On the command line, the Collaborator can use git fetch origin main to get the remote changes into the local repository, but without merging them. Then by running git diff main origin/main the Collaborator will see the changes output in the terminal.

Use git fetch to download the remote content but not update your local repo’s working state, leaving your current work intact. Use git pull to download the remote content for the active local branch and immediately merge it. this can potentially cause conflicts.
Use git fetch to download the remote content but not update your local repo’s working state, leaving your current work intact. Use git pull to download the remote content for the active local branch and immediately merge it. this can potentially cause conflicts.

Group challenge


Switch Roles and Repeat

Switch roles and repeat the whole process.

Individual challenges


Comment Changes in GitHub

The Collaborator has some questions about one line change made by the Owner and has some suggestions to propose.

With GitHub, it is possible to comment on the diff of a commit. Over the line of code to comment, a blue comment icon appears to open a comment window.

The Collaborator posts her comments and suggestions using the GitHub interface.

Version History, Backup, and Version Control

Some backup software can keep a history of the versions of your files. They also allows you to recover specific versions. How is this functionality different from version control? What are some of the benefits of using version control, Git and GitHub?

Create your GitHub profile!

Now your work will be visible online on GitHub. Your profile page introduce you to other contributors on GitHub:

To create this, go to the GitHub Home page, identify the section called Introduce yourself with a profile README. Click on Create:

Edit the lines in the template file. Then click on Commit changes...

To edit this in a local repository, clone it following the steps you learned!

Checklist

Use git clone to obtain a development copy of a remote repository. Like git init, cloning is generally a one-time operation. Use git pull to update the local repository to match the content in the remote repository.
Use git clone to obtain a development copy of a remote repository. Like git init, cloning is generally a one-time operation. Use git pull to update the local repository to match the content in the remote repository.

Key Points

  • git clone copies a remote repository to create a local repository with a remote called origin automatically set up.

Content from Conflicts


Last updated on 2024-03-12 | Edit this page

Estimated time: 15 minutes

Overview

Questions

  • What do I do when my changes conflict with someone else’s?

Objectives

  • Explain what conflicts are and when they can occur.
  • Resolve conflicts resulting from a merge.

A story of two collaborators


Two users can make independent sets of changes on the same document.

Different Versions Can be Saved

If multiple users make changes to different sections of the document you can incorporate two sets of changes into the same base document.

Multiple Versions Can be Merged

However, if multiple users make changes to the same sections of the document, this will generate a conflict.

The Conflicting Changes

As soon as people can work in parallel, they’ll likely step on each other’s toes. This will even happen with a single person: if we are working on a piece of software on both our laptop and a server in the lab, we could make different changes to each copy. Version control helps us manage these conflicts by giving us tools to resolve overlapping changes.

Before resolving conflicts, we’ll review two features that a good collaborator puts in practice: Create branches and make Atomic commits.

Group Challenge


A Typical Work Session

You sit down at your computer to work on a shared project that is tracked in a remote Git repository. During your work session, you take the following actions, but not in this order:

  • Make changes by appending the number 100 to a text file numbers.md
  • Update remote repository to match the local repository
  • Celebrate your success with some fancy beverage(s)
  • Update local repository to match the remote repository
  • Stage changes to be committed
  • Commit changes to the local repository

In what order should you perform these actions to minimize the chances of conflicts? Put the commands above in order in the action column of the table below. When you have the order right, see if you can write the corresponding commands in the command column. A few steps are populated to get you started.

order action . . . . . . command . . . . . . . . . .
1
2 echo 100 >> numbers.md
3
4
5
6 Celebrate! AFK
order action . . . . . . command . . . . . . . . . . . . . . . . . . .
1 Update local git pull origin main
2 Make changes echo 100 >> numbers.md
3 Stage changes git add numbers.md
4 Commit changes git commit -m "Add 100 to numbers.md"
5 Update remote git push origin main
6 Celebrate! AFK

Create a conflict


To see how we can resolve conflicts, we must first create one. The file sitrep.Rmd currently looks like this in both partners’ copies of our cases repository:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak

Let’s add a line to the collaborator’s copy only:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
This line added to Wolfman's copy

and then push the change to GitHub:

BASH

$ git add sitrep.Rmd
$ git commit -m "Add a line in our home copy"

OUTPUT

[main 5ae9631] Add a line in our home copy
 1 file changed, 1 insertion(+)

BASH

$ git push origin main

OUTPUT

Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 8 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 331 bytes | 331.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To https://github.com/vlad/cases.git
   29aba7c..dabb4c8  main -> main

Now let’s have the owner make a different change to their copy without updating from GitHub:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
We added a different line in the other copy

We can commit the change locally:

BASH

$ git add sitrep.Rmd
$ git commit -m "Add a line in my copy"

OUTPUT

[main 07ebc69] Add a line in my copy
 1 file changed, 1 insertion(+)

but Git won’t let us push it to GitHub:

BASH

$ git push origin main

OUTPUT

To https://github.com/vlad/cases.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'https://github.com/vlad/cases.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
The Conflicting Changes

Git rejects the push because it detects that the remote repository has new updates that have not been incorporated into the local branch. What we have to do is pull the changes from GitHub, merge them into the copy we’re currently working in, and then push that.

Resolve conflict


The owner need to solve this conflict to be able to push to the remote repository.

Let’s start by pulling:

BASH

$ git pull origin main

OUTPUT

remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (1/1), done.
remote: Total 3 (delta 2), reused 3 (delta 2), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/vlad/cases
 * branch            main     -> FETCH_HEAD
    29aba7c..dabb4c8  main     -> origin/main
Auto-merging sitrep.Rmd
CONFLICT (content): Merge conflict in sitrep.Rmd
Automatic merge failed; fix conflicts and then commit the result.

The git pull command updates the local repository to include those changes already included in the remote repository. After the changes from remote branch have been fetched, Git detects that changes made to the local copy overlap with those made to the remote repository, and therefore refuses to merge the two versions to stop us from trampling on our previous work. The conflict is marked in in the affected file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
<<<<<<< HEAD
We added a different line in the other copy
=======
This line added to Wolfman's copy
>>>>>>> dabb4c8c450e8475aee9b14b4383acc99f42af1d

Our change is preceded by <<<<<<< HEAD. Git has then inserted ======= as a separator between the conflicting changes and marked the end of the content downloaded from GitHub with >>>>>>>. (The string of letters and digits after that marker identifies the commit we’ve just downloaded.)

It is now up to us to edit this file to remove these markers and reconcile the changes. We can do anything we want: keep the change made in the local repository, keep the change made in the remote repository, write something new to replace both, or get rid of the change entirely. Let’s replace both so that the file looks like this:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
We removed the conflict on this line

To finish merging, we add sitrep.Rmd to the changes being made by the merge and then commit:

BASH

$ git add sitrep.Rmd
$ git status

OUTPUT

On branch main
All conflicts fixed but you are still merging.
  (use "git commit" to conclude merge)

Changes to be committed:

	modified:   sitrep.Rmd

BASH

$ git commit -m "Merge changes from GitHub"

OUTPUT

[main 2abf2b1] Merge changes from GitHub

Now we can push our changes to GitHub:

BASH

$ git push origin main

OUTPUT

Enumerating objects: 10, done.
Counting objects: 100% (10/10), done.
Delta compression using up to 8 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 645 bytes | 645.00 KiB/s, done.
Total 6 (delta 4), reused 0 (delta 0)
remote: Resolving deltas: 100% (4/4), completed with 2 local objects.
To https://github.com/vlad/cases.git
   dabb4c8..2abf2b1  main -> main

Pull before editing


Git keeps track of what we’ve merged with what, so we don’t have to fix things by hand again when the collaborator who made the first change pulls again:

BASH

$ git pull origin main

OUTPUT

remote: Enumerating objects: 10, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 6 (delta 4), reused 6 (delta 4), pack-reused 0
Unpacking objects: 100% (6/6), done.
From https://github.com/vlad/cases
 * branch            main     -> FETCH_HEAD
    dabb4c8..2abf2b1  main     -> origin/main
Updating dabb4c8..2abf2b1
Fast-forward
 sitrep.Rmd | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

We get the merged file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
We removed the conflict on this line

We don’t need to merge again because Git knows someone has already done that.

Git’s ability to resolve conflicts is very useful, but conflict resolution costs time and effort, and can introduce errors if conflicts are not resolved correctly. If you find yourself resolving a lot of conflicts in a project, consider these technical approaches to reducing them:

  • Pull from upstream more frequently, especially before starting new work
  • Use topic branches to segregate work, merging to main when complete
  • Make smaller more atomic commits
  • Push your work when it is done and encourage your team to do the same to reduce work in progress and, by extension, the chance of having conflicts
  • Where logically appropriate, break large files into smaller ones so that it is less likely that two authors will alter the same file simultaneously

Conflicts can also be minimized with project management strategies:

  • Clarify who is responsible for what areas with your collaborators
  • Discuss what order tasks should be carried out in with your collaborators so that tasks expected to change the same lines won’t be worked on simultaneously
  • If the conflicts are stylistic churn (e.g. tabs vs. spaces), establish a project convention that is governing and use code style tools (e.g. htmltidy, perltidy, rubocop, etc.) to enforce, if necessary

Solving Conflicts that You Create

Clone the repository created by your instructor. Add a new file to it, and modify an existing file (your instructor will tell you which one). When asked by your instructor, pull her changes from the repository to create a conflict, then resolve it.

Conflicts on Non-textual files

What does Git do when there is a conflict in an image or some other non-textual file that is stored in version control?

Let’s try it. Suppose Dracula takes a picture of the laboratory test and calls it lab.jpg.

If you do not have an image file of the lab available, you can create a dummy binary file like this:

BASH

$ head -c 1024 /dev/urandom > lab.jpg
$ ls -lh lab.jpg

OUTPUT

-rw-r--r-- 1 vlad 57095 1.0K Mar  8 20:24 lab.jpg

ls shows us that this created a 1-kilobyte file. It is full of random bytes read from the special file, /dev/urandom.

Now, suppose Dracula adds lab.jpg to his repository:

BASH

$ git add lab.jpg
$ git commit -m "Add picture of laboratory test"

OUTPUT

[main 8e4115c] Add picture of laboratory test
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 lab.jpg

Suppose that Wolfman has added a similar picture in the meantime. His is a picture of the laboratory site, but it is also called lab.jpg. When Dracula tries to push, he gets a familiar message:

BASH

$ git push origin main

OUTPUT

To https://github.com/vlad/cases.git
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'https://github.com/vlad/cases.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

We’ve learned that we must pull first and resolve any conflicts:

BASH

$ git pull origin main

When there is a conflict on an image or other binary file, git prints a message like this:

OUTPUT

$ git pull origin main
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From https://github.com/vlad/cases.git
 * branch            main     -> FETCH_HEAD
   6a67967..439dc8c  main     -> origin/main
warning: Cannot merge binary files: lab.jpg (HEAD vs. 439dc8c08869c342438f6dc4a2b615b05b93c76e)
Auto-merging lab.jpg
CONFLICT (add/add): Merge conflict in lab.jpg
Automatic merge failed; fix conflicts and then commit the result.

The conflict message here is mostly the same as it was for sitrep.Rmd, but there is one key additional line:

OUTPUT

warning: Cannot merge binary files: lab.jpg (HEAD vs. 439dc8c08869c342438f6dc4a2b615b05b93c76e)

Git cannot automatically insert conflict markers into an image as it does for text files. So, instead of editing the image file, we must check out the version we want to keep. Then we can add and commit this version.

On the key line above, Git has conveniently given us commit identifiers for the two versions of lab.jpg. Our version is HEAD, and Wolfman’s version is 439dc8c0.... If we want to use our version, we can use git checkout:

BASH

$ git checkout HEAD lab.jpg
$ git add lab.jpg
$ git commit -m "Use image of test instead of site"

OUTPUT

[main 21032c3] Use image of test instead of site

If instead we want to use Wolfman’s version, we can use git checkout with Wolfman’s commit identifier, 439dc8c0:

BASH

$ git checkout 439dc8c0 lab.jpg
$ git add lab.jpg
$ git commit -m "Use image of site instead of test"

OUTPUT

[main da21b34] Use image of site instead of test

We can also keep both images. The catch is that we cannot keep them under the same name. But, we can check out each version in succession and rename it, then add the renamed versions. First, check out each image and rename it:

BASH

$ git checkout HEAD lab.jpg
$ git mv lab.jpg lab-test.jpg
$ git checkout 439dc8c0 lab.jpg
$ mv lab.jpg lab-site.jpg

Then, remove the old lab.jpg and add the two new files:

BASH

$ git rm lab.jpg
$ git add lab-test.jpg
$ git add lab-site.jpg
$ git commit -m "Use two images: test and site"

OUTPUT

[main 94ae08c] Use two images: test and site
 2 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 lab-site.jpg
 rename lab.jpg => lab-test.jpg (100%)

Now both images of the lab are checked into the repository, and lab.jpg no longer exists.

Good practices

A good collaborator:

  • Pull from upstream frequently before new edits.
  • Use topic or feature branches to segregate work.
  • Make atomic commits.
  • Push your work when it is done to reduce work in progress.
  • Break large files when appropriate.
  • Read contributing guidelines from the project owner.

Create branches


Sometimes you want to experiment with your project without affecting the main version. You can do this by using branches. A branch is a local copy of the main project (also called the main branch) where you can make changes and test new ideas. The main branch stays safe and unchanged while you work on your branch (a.k.a., feature branch). When you are satisfied with the changes, you can merge them into the main branch. This means that the separate lines of development in your branch are combined with the main branch.

One feature branch and one main branch in Git.
One feature branch and one main branch in Git.

You can have more than one branch off of your main copy. If one of your branches ends up not working, you can either abandon it or delete it without impacting the main branch of your project.

Two feature branches and one main branch in Git.
Two feature branches and one main branch in Git.

To create a branch, first, verify that you are working on the main branch:

BASH

$ git status

OUTPUT

On branch main

The git branch command creates a branch of the name newbranch:

BASH

$ git branch newbranch

The git checkout command switch from the current branch (in this case, main) to the newbranch:

BASH

$ git checkout newbranch

OUTPUT

Switched to branch 'newbranch'

Now, you can confirm that we are in newbranch using git status:

BASH

$ git status

OUTPUT

On branch newbranch
nothing to commit, working tree clean

Now, let’s make an edit to the sitrep.Rmd file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
Use packages listed in the CRAN Task View: Epidemiology

Add and commit this change to the local repository:

BASH

$ git add sitrep.Rmd
$ git commit -m "Add edit in new branch"

OUTPUT

[newbranch 60d5ff9] Add edit in new branch
 1 file changed, 1 insertion(+)

Push commit to the remote repository. NOTE: instead of git push origin main, we replace main with the name of the new branch:

BASH

$ git push origin newbranch

OUTPUT

Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 339 bytes | 169.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
remote:
remote: Create a pull request for 'newbranch' on GitHub by visiting:
remote:      https://github.com/vlad/cases/pull/new/newbranch
remote:
To https://github.com/vlad/cases.git
 * [new branch]      newbranch -> newbranch

On GitHub, we get a notification to Create a Pull Request:

In your local repository, you can leave your work parked for a while on that branch. To return to main (or to any other branch), you can use the same command to switch between branches:

BASH

$ git checkout main

OUTPUT

Switched to branch 'main'
Your branch is up to date with 'origin/main'.

Atomic commits


A good commit is also an atomic commit, like in the commit of the last challenge:

BASH

$ git add lab-test.jpg
$ git add lab-site.jpg
$ git commit -m "Use two images: test and site"

Commits should be ‘atomic’, meaning that they should do one simple thing and they should do it completely. (The Turing Way Community). Atomic commits prioritize one unit of change instead of the quantity of changes.

Two related modified lines must be part of the same commit.
Two related modified lines must be part of the same commit.

In Rstudio, the Review changes window has a button called “Stage chunk”. This helps to make atomic commits, even if you change a lot of lines in a single edit. You can either select them to make isolated commits or to unite them to be part of the same commit.

Two unrelated edits must be part of two isolated commits.
Two unrelated edits must be part of two isolated commits.

Good practice

A good atomic commit:

  • Includes more than one file that involves one unit of change.

  • Isolate or includes multiple edited lines using the “Stage chunk” button in Rstudio.

  • Does not include all the files in one commit.

Key Points

  • Version control also allows many people to work in parallel.
  • Conflicts occur when two or more people change the same lines of the same file.
  • The version control system does not allow people to overwrite each other’s changes blindly, but highlights conflicts so that they can be resolved.
  • Feature branches help to segregate work and minimize conflicts.
  • Atomic commits prioritize one unit of change instead of the quantity of changes.

Content from Wrap-up


Last updated on 2024-03-12 | Edit this page

Estimated time: 5 minutes

Overview

Questions

  • Where is a full view of the concepts covered today?
  • Where can I ask for questions after this workshop?
  • Where can I write my feedback on this workshop?

Objectives

  • Show the final concept map of the workshop.
  • Share a self-assessment review checklist.
  • Remind our communication forum.
  • Share the feedback form of the workshop.

Praise yourself!


First of all:

R

# install.packages("praise")
praise::praise()

The goal


Checklist

Complete workflow with actions, git verb commands, and spaces.
Complete workflow with actions, git verb commands, and spaces.

Your next step!


Good job! We recommend you to read the supplemental episode on how to use Git with the Rstudio IDE. It can make some steps easier to interact with! For topics like resolving conflicts, we suggest to use Desktop software like VScode. (However, you may need to close RStudio when using VScode to avoid some git error messages!)

If you are looking for more practice, go for the individual challenges on each episode. We also recommend you to keep practicing how to Create branches and make Atomic commits.

Also! You’ve now fulfill the core prerequisites for the tutorial on Improve your code for Epidemic analysis with R!

With R, Git and GitHub you will now extend your skills with a Research compendium, a Reproducible environment, and informative READMEs!

Write an individual learning reflection


Before we wrap up, please take 5 minutes to think over everything we have covered so far.

  • On a piece of paper, write down something that captures what you want to remember about the day.
  • The Instructor will not look at this - it is just for you.

If you do not know where to start, consider the following list for a starting point:

  • Draw a concept map, connecting the material
  • Draw pictures or a comic depicting one of the day’s concepts
  • Write an outline of the topics we covered
  • Write a paragraph or “journal” entry about your experience of the workshop today
  • Write down one thing that struck you the most

This exercise should take about 5 minutes.

Our communication channel


Checklist

We remind you of our communication forum called GitHub Discussions. Here we will ask and solve our and your question on the topic!

You can fill your questions under the Q&A category… at any time in the future!

Your constructive feedback


This form is anonymous: https://forms.gle/HznDJM1c1U6Bgdmw7

If you did not fill out this form, please take 5 minutes to fill it. This form will be beneficial for further improvements to our workshop.

Complementary readings


Key Points

  • Read the tutorial on ‘Improve your code for Epidemic analysis with R’.
  • Use the GitHub Discussions as our communication forum after the workshop.
  • Use the feedback form to share your constructive comments.

Content from Supplemental: Using RStudio for Git


Last updated on 2024-03-05 | Edit this page

Estimated time: 10 minutes

Overview

Questions

  • How can I use Git with RStudio?

Objectives

  • Understand how to use Git from RStudio.

Version control can be very useful when developing data analysis scripts. For that reason, the popular development environment RStudio for the R programming language has built-in integration with Git. While some advanced Git features still require the command-line, RStudio has a nice interface for many common Git operations.

Testimonial

We also invite you to read this blog post about 10 Commands to Get Started with Git with screenshots of the Rstudio web-based interface.

Create project


RStudio allows us to create a project associated with a given directory to keep track of various related files. To be able to track the development of the project over time, to be able to revert to previous versions, and to collaborate with others, we version control the Rstudio project with Git. To get started using Git in RStudio, we create a new project:

RStudio screenshot showing the file menu dropdown with "New Project..." selected

This opens a dialog asking us how we want to create the project. We have some options here. Let’s say that we want to use RStudio with the planets repository that we already made. Since that repository lives in a directory on our computer, we choose the option “Existing Directory”:

RStudio screenshot showing New Project dialog window with "Create project from existing directory" selected

For a new directory, follow the steps in this section about “Versioning new work”.

To clone a remote repository from Rstudio, follow these steps:

Do You See a “Version Control” Option?

Although we’re not going to use it here, there should be a “version control” option on this menu. That is what you would click on if you wanted to create a project on your computer by cloning a repository from GitHub. If that option is not present, it probably means that RStudio doesn’t know where your Git executable is, and you won’t be able to progress further in this lesson until you tell RStudio where it is.

Find your Git Executable

First let’s make sure that Git is installed on your computer. Open your shell on Mac or Linux, or on Windows open the command prompt and then type:

  • which git (macOS, Linux)
  • where git (Windows)

If there is no version of Git on your computer, please follow the Git installation instructions in the setup of this lesson to install Git now. Next open your shell or command prompt and type which git (macOS, Linux), or where git (Windows). Copy the path to the git executable.

On one Windows computer which had GitHub Desktop installed on it, the path was: C:/Users/UserName/AppData/Local/GitHubDesktop/app-1.1.1/resources/app/git/cmd/git.exe

NOTE: The path on your computer will be somewhat different.

Tell RStudio where to find GitHub

In RStudio, go to the Tools menu > Global Options > Git/SVN and then browse to the Git executable you found in the command prompt or shell. Now restart RStudio. Note: Even if you have Git installed, you may need to accept the Xcode license if you are using macOS.

Next, RStudio will ask which existing directory we want to use. Click “Browse…” and navigate to the correct directory, then click “Create Project”:

Ta-da! We have created a new project in RStudio within the existing planets repository. Notice the vertical “Git” menu in the menu bar. RStudio has recognized that the current directory is a Git repository, and gives us a number of tools to use Git:

RStudio window after new project is created with large arrow pointing to vertical Git menu bar.

To edit the existing files in the repository, we can click on them in the “Files” panel on the lower right. Now let’s add some additional information about Pluto:

Once we have saved our edited files, we can use RStudio to commit the changes by clicking on “Commit…” in the Git menu:

RStudio screenshot showing the Git menu dropdown with "Commit..." selected

You can also use the buttons from the Git tab, usually in the upper right pane:

This will open a dialogue where we can select which files to commit (by checking the appropriate boxes in the “Staged” column), and enter a commit message (in the upper right panel). The icons in the “Status” column indicate the current status of each file. Clicking on a file shows information about changes in the lower panel (using output of git diff). Once everything is the way we want it, we click “Commit”:

The changes can be pushed by selecting “Push Branch” from the Git menu. There are also options to pull from the remote repository, and to view the commit history:

RStudio screenshot showing the git menu dropdown with "History" selected

Are the Push/Pull Commands Grayed Out?

Grayed out Push/Pull commands generally mean that RStudio doesn’t know the location of your remote repository (e.g. on GitHub). To fix this, open a terminal to the repository and enter the command: git push -u origin main. Then restart RStudio.

If we click on “History”, we can see a graphical version of what git log would tell us:

RStudio creates a number of files that it uses to keep track of a project. We often don’t want to track these, in which case we add them to our .gitignore file:

RStudio screenshot showing .gitignore open in the editor pane with the files .Rproj.user, .Rhistory, .RData, and *.Rproj added to the end

Tip: versioning disposable output

Generally you do not want to version control disposable output (or read-only data). You should modify the .gitignore file to tell Git to ignore these files and directories.

In the Rstudio: Review changes window, you can also open the .gitignore files from the Ignore button. You can use the Revert button to do a git checkout HEAD, i.e., to undo changes not yet on staging area by restoring the local repository (last commit).

Create a branch


In the Git tab, in the right hand side you will find the name of your current branch (e.g., main). Use the button in its left hand side to create a branch.

You can call it feature-branch:

You are able to switch between different branches using the menu displayed when you click in the branch name:

Git is a Version control software optimized for plain-text files. This can register non-linear changes.

Checklist

Key characteristics of Version control systems are:

  1. Keep the entire history of a file and inspect a file throughout its lifetime.

  2. Tag a particular version so you can return to them easily.

  3. Facilitates collaborations and makes contributions transparent.

  4. Experiment with code and feature without breaking the main project

The best way to merge branches is on GitHub. We recommend you to read about how to create a Pull Request, and how to merge a Pull Request

Challenge

  1. Create a new directory within your project called tests.
  2. Modify the .gitignore so that the tests directory is not version controlled.

This can be done in Rstudio:

R

usethis::use_directory("tests")

Then open up the .gitignore file from the right-hand panel of Rstudio and add tests/ to the list of files to ignore.

There are many more features in the RStudio Git menu, but these should be enough to get you started!

Key Points

  • Using RStudio’s Git integration allows you to version control a project over time.
  • Feature branches help you experiment with code without breaking the main project.

Content from Exploring History


Last updated on 2023-11-27 | Edit this page

Estimated time: 25 minutes

Overview

Questions

  • How can I identify old versions of files?
  • How do I review my changes?
  • How can I recover old versions of files?

Objectives

  • Explain what the HEAD of a repository is and how to use it.
  • Identify and use Git commit numbers.
  • Compare various versions of tracked files.
  • Restore old versions of files.

The HEAD


As we saw in the previous episode, we can refer to commits by their identifiers. You can refer to the most recent commit of the working directory by using the identifier HEAD.

We’ve been adding one line at a time to sitrep.Rmd, so it’s easy to track our progress by looking, so let’s do that using our HEADs. Before we start, let’s make a change to sitrep.Rmd, adding yet another line.

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak
Maps can aid in the identification of hotspots

Save the file.

Now, in the Terminal, let’s see what we get.

BASH

$ git diff HEAD sitrep.Rmd

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index b36abfd..0848c8d 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1,3 +1,4 @@
 Comparison of attack rates in different age groups
 This can identify priority groups for interventions
 Maps illustrate the spread and impact of outbreak
+Maps can aid in the identification of hotspots.

which is the same as what you would get if you leave out HEAD (try it). The real goodness in all this is when you can refer to previous commits. We do that by adding ~1 (where “~” is “tilde”, pronounced [til-duh]) to refer to the commit one before HEAD.

BASH

$ git diff HEAD~1 sitrep.Rmd

If we want to see the differences between older commits we can use git diff again, but with the notation HEAD~1, HEAD~2, and so on, to refer to them:

BASH

$ git diff HEAD~3 sitrep.Rmd

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index df0654a..b36abfd 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1 +1,4 @@
 Comparison of attack rates in different age groups
+This can identify priority groups for interventions
+Maps illustrate the spread and impact of outbreak
+Maps can aid in the identification of hotspots

Show changes in old commits


We could also use git show which shows us what changes we made at an older commit as well as the commit message, rather than the differences between a commit and our working directory that we see by using git diff.

BASH

$ git show HEAD~3 sitrep.Rmd

OUTPUT

commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
Author: Vlad Dracula <vlad@tran.sylvan.ia>
Date:   Thu Aug 22 09:51:46 2013 -0400

    Start Sitrep with attack rate analysis

diff --git a/sitrep.Rmd b/sitrep.Rmd
new file mode 100644
index 0000000..df0654a
--- /dev/null
+++ b/sitrep.Rmd
@@ -0,0 +1 @@
+Comparison of attack rates in different age groups

In this way, we can build up a chain of commits. The most recent end of the chain is referred to as HEAD; we can refer to previous commits using the ~ notation, so HEAD~1 means “the previous commit”, while HEAD~123 goes back 123 commits from where we are now.

Use commit unique ID


We can also refer to commits using those long strings of digits and letters that git log displays. These are unique IDs for the changes, and “unique” really does mean unique: every change to any set of files on any computer has a unique 40-character identifier. Our first commit was given the ID f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try this:

BASH

$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b sitrep.Rmd

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index df0654a..93a3e13 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1 +1,4 @@
 Comparison of attack rates in different age groups
+This can identify priority groups for interventions
+Maps illustrate the spread and impact of outbreak
+Maps can aid in the identification of hotspots

That’s the right answer, but typing out random 40-character strings is annoying, so Git lets us use just the first few characters (typically seven for normal size projects):

BASH

$ git diff f22b25e sitrep.Rmd

OUTPUT

diff --git a/sitrep.Rmd b/sitrep.Rmd
index df0654a..93a3e13 100644
--- a/sitrep.Rmd
+++ b/sitrep.Rmd
@@ -1 +1,4 @@
 Comparison of attack rates in different age groups
+This can identify priority groups for interventions
+Maps illustrate the spread and impact of outbreak
+Maps can aid in the identification of hotspots

Restore old versions


All right! So we can save changes to files and see what we’ve changed. Now, how can we restore older versions of things? Let’s suppose we change our mind about the last update to sitrep.Rmd (the one about the “hotspots”).

git status now tells us that the file has been changed, but those changes haven’t been staged:

BASH

$ git status

OUTPUT

On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   sitrep.Rmd

no changes added to commit (use "git add" and/or "git commit -a")

We can put things back the way they were by using git checkout:

BASH

$ git checkout HEAD sitrep.Rmd

Now, read the content in the file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups
This can identify priority groups for interventions
Maps illustrate the spread and impact of outbreak

As you might guess from its name, git checkout checks out (i.e., restores) an old version of a file. In this case, we’re telling Git that we want to recover the version of the file recorded in HEAD, which is the last saved commit. If we want to go back even further, we can use a commit identifier instead:

BASH

$ git checkout f22b25e sitrep.Rmd

Now, read the content in the file:

R

usethis::edit_file("sitrep.Rmd")

OUTPUT

Comparison of attack rates in different age groups

Ask the current status:

BASH

$ git status

OUTPUT

On branch main
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   sitrep.Rmd

Notice that the changes are currently in the staging area. Again, we can put things back the way they were by using git checkout:

BASH

$ git checkout HEAD sitrep.Rmd

Don’t Lose Your HEAD

Above we used

BASH

$ git checkout f22b25e sitrep.Rmd

to revert sitrep.Rmd to its state after the commit f22b25e. But be careful! The command checkout has other important functionalities and Git will misunderstand your intentions if you are not accurate with the typing. For example, if you forget sitrep.Rmd in the previous command.

BASH

$ git checkout f22b25e

ERROR

Note: checking out 'f22b25e'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

 git checkout -b <new-branch-name>

HEAD is now at f22b25e Start Sitrep with attack rate analysis

The “detached HEAD” is like “look, but don’t touch” here, so you shouldn’t make any changes in this state. After investigating your repo’s past state, reattach your HEAD with git checkout main.

It’s important to remember that we must use the commit number that identifies the state of the repository before the change we’re trying to undo. A common mistake is to use the number of the commit in which we made the change we’re trying to discard. In the example below, we want to retrieve the state from before the most recent commit (HEAD~1), which is commit f22b25e:

Git Checkout

So, to put it all together, here’s how Git works in cartoon form:

https://figshare.com/articles/How_Git_works_a_cartoon/1328266

Simplifying the Common Case

If you read the output of git status carefully, you’ll see that it includes this hint:

OUTPUT

(use "git checkout -- <file>..." to discard changes in working directory)

As it says, git checkout without a version identifier restores files to the state saved in HEAD. The double dash -- is needed to separate the names of the files being recovered from the command itself: without it, Git would try to use the name of the file as the commit identifier.

The fact that files can be reverted one by one tends to change the way people organize their work. If everything is in one large document, it’s hard (but not impossible) to undo changes to the introduction without also undoing changes made later to the conclusion. If the introduction and conclusion are stored in separate files, on the other hand, moving backward and forward in time becomes much easier.

Challenges


Recovering Older Versions of a File

Jennifer has made changes to the Python script that she has been working on for weeks, and the modifications she made this morning “broke” the script and it no longer runs. She has spent ~ 1hr trying to fix it, with no luck…

Luckily, she has been keeping track of her project’s versions using Git! Which commands below will let her recover the last committed version of her Python script called data_cruncher.py?

  1. $ git checkout HEAD

  2. $ git checkout HEAD data_cruncher.py

  3. $ git checkout HEAD~1 data_cruncher.py

  4. $ git checkout <unique ID of last commit> data_cruncher.py

  5. Both 2 and 4

The answer is (5)-Both 2 and 4.

The checkout command restores files from the repository, overwriting the files in your working directory. Answers 2 and 4 both restore the latest version in the repository of the file data_cruncher.py. Answer 2 uses HEAD to indicate the latest, whereas answer 4 uses the unique ID of the last commit, which is what HEAD means.

Answer 3 gets the version of data_cruncher.py from the commit before HEAD, which is NOT what we wanted.

Answer 1 can be dangerous! Without a filename, git checkout will restore all files in the current directory (and all directories below it) to their state at the commit specified. This command will restore data_cruncher.py to the latest commit version, but it will also restore any other files that are changed to that version, erasing any changes you may have made to those files! As discussed above, you are left in a detached HEAD state, and you don’t want to be there.

Reverting a Commit

Jennifer is collaborating with colleagues on her Python script. She realizes her last commit to the project’s repository contained an error, and wants to undo it. Jennifer wants to undo correctly so everyone in the project’s repository gets the correct change. The command git revert [erroneous commit ID] will create a new commit that reverses the erroneous commit.

The command git revert is different from git checkout [commit ID] because git checkout returns the files not yet committed within the local repository to a previous state, whereas git revert reverses changes committed to the local and project repositories.

Below are the right steps and explanations for Jennifer to use git revert, what is the missing command?

  1. ________ # Look at the git history of the project to find the commit ID

  2. Copy the ID (the first few characters of the ID, e.g. 0b1d055).

  3. git revert [commit ID]

  4. Type in the new commit message.

  5. Save and close

The command git log lists project history with commit IDs.

The command git show HEAD shows changes made at the latest commit, and lists the commit ID; however, Jennifer should double-check it is the correct commit, and no one else has committed changes to the repository.

These commands are so similar!

Commands like git checkout and git revert are useful but so similar that it’s very easy to mix them up!

With the concepts learned in this episode, we invite you to read this chapter on undoing commits and changes.

Understanding Workflow and History

What is the output of the last command in

BASH

$ cd cases
$ echo "Data is messy and full of typos" > clean.Rmd #this adds a line of text in clean.Rmd
$ git add clean.Rmd
$ echo "Data is too long to be suitable to print" >> clean.Rmd
$ git commit -m "Comment on Data as an unsuitable print"
$ git checkout HEAD clean.Rmd
$ cat clean.Rmd #this will print the contents of clean.Rmd to the screen
  1. OUTPUT

      Data is too long to be suitable to print
  2. OUTPUT

      Data is messy and full of typos
  3. OUTPUT

      Data is messy and full of typos
      Data is too long to be suitable to print
  4. OUTPUT

      Error because you have changed clean.Rmd without committing the changes

The answer is 2.

The command git add clean.Rmd places the current version of clean.Rmd into the staging area. The changes to the file from the second echo command are only applied to the working copy, not the version in the staging area.

So, when git commit -m "Comment on Data as an unsuitable print" is executed, the version of clean.Rmd committed to the repository is the one from the staging area and has only one line.

At this time, the working copy still has the second line (and git status will show that the file is modified). However, git checkout HEAD clean.Rmd replaces the working copy with the most recently committed version of clean.Rmd.

So, cat clean.Rmd will output

OUTPUT

Data is messy and full of typos.

Checking Understanding of git diff

Consider this command: git diff HEAD~9 sitrep.Rmd. What do you predict this command will do if you execute it? What happens when you do execute it? Why?

Try another command, git diff [ID] sitrep.Rmd, where [ID] is replaced with the unique identifier for your most recent commit. What do you think will happen, and what does happen?

Getting Rid of Staged Changes

git checkout can be used to restore a previous commit when unstaged changes have been made, but will it also work for changes that have been staged but not committed? Make a change to sitrep.Rmd, add that change using git add, then use git checkout to see if you can remove your change.

After adding a change, git checkout can not be used directly. Let’s look at the output of git status:

OUTPUT

On branch main
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   sitrep.Rmd

Note that if you don’t have the same output you may either have forgotten to change the file, or you have added it and committed it.

Using the command git checkout -- sitrep.Rmd now does not give an error, but it does not restore the file either. Git helpfully tells us that we need to use git reset first to unstage the file:

BASH

$ git reset HEAD sitrep.Rmd

OUTPUT

Unstaged changes after reset:
M	sitrep.Rmd

Now, git status gives us:

BASH

$ git status

OUTPUT

On branch main
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   sitrep.Rmd

no changes added to commit (use "git add" and/or "git commit -a")

This means we can now use git checkout to restore the file to the previous commit:

BASH

$ git checkout -- sitrep.Rmd
$ git status

OUTPUT

On branch main
nothing to commit, working tree clean

Explore and Summarize Histories

Exploring history is an important part of Git, and often it is a challenge to find the right commit ID, especially if the commit is from several months ago.

Imagine the cases project has more than 50 files. You would like to find a commit that modifies some specific text in sitrep.Rmd. When you type git log, a very long list appeared. How can you narrow down the search?

Recall that the git diff command allows us to explore one specific file, e.g., git diff sitrep.Rmd. We can apply a similar idea here.

BASH

$ git log sitrep.Rmd

Unfortunately some of these commit messages are very ambiguous, e.g., update files. How can you search through these files?

Both git diff and git log are very useful and they summarize a different part of the history for you. Is it possible to combine both? Let’s try the following:

BASH

$ git log --patch sitrep.Rmd

You should get a long list of output, and you should be able to see both commit messages and the difference between each commit.

Question: What does the following command do?

BASH

$ git log --patch HEAD~9 *.Rmd

Checklist

Use git diff to compare changes since last commit or between commits. Use git checkout to undo changes by restoring the staging area (committed changes) or the local repository (last commit)
Use git diff to compare changes since last commit or between commits. Use git checkout to undo changes by restoring the staging area (committed changes) or the local repository (last commit)

Key Points

  • git diff displays differences between commits.
  • git checkout recovers old versions of files.

Content from Open Science


Last updated on 2023-10-25 | Edit this page

Estimated time: 10 minutes

Overview

Questions

  • How can version control help me make my work more open?

Objectives

  • Explain how a version control system can be leveraged as an electronic lab notebook for computational work.

The opposite of “open” isn’t “closed”. The opposite of “open” is “broken”.

-– John Wilbanks

Free sharing of information might be the ideal in science, but the reality is often more complicated. Normal practice today looks something like this:

  • A scientist collects some data and stores it on a machine that is occasionally backed up by their department.
  • They then write or modify a few small programs (which also reside on the machine) to analyze that data.
  • Once they have some results, they write them up and submit a paper. The scientist might include their data – a growing number of journals require this – but they probably don’t include the code.
  • Time passes.
  • The journal sends the scientist reviews written anonymously by a handful of other people in their field. The scientist revises the paper to satisfy the reviewers, during which time they might also modify the scripts they wrote earlier, and resubmits.
  • More time passes.
  • The paper is eventually published. It might include a link to an online copy of the data, but the paper itself will be behind a paywall: only people who have personal or institutional access will be able to read it.

For a growing number of scientists, though, the process looks like this:

  • The data that the scientist collects is stored in an open access repository like figshare or Zenodo, possibly as soon as it’s collected, and given its own Digital Object Identifier (DOI). Or the data was already published and is stored in Dryad.
  • The scientist creates a new repository on GitHub to hold their work.
  • During analysis, they push changes to their scripts (and possibly some output files) to that repository. The scientist also uses the repository for their paper; that repository is then the hub for collaboration with colleagues.
  • When they are happy with the state of the paper, the scientist posts a version to arXiv or some other preprint server to invite feedback from peers.
  • Based on that feedback, they may post several revisions before finally submitting the paper to a journal.
  • The published paper includes links to the preprint and to the code and data repositories, which makes it much easier for other scientists to use their work as starting point for their own research.

This open model accelerates discovery: the more open work is, the more widely it is cited and re-used. However, people who want to work this way need to make some decisions about what exactly “open” means and how to do it. You can find more on the different aspects of Open Science in this book.

This is one of the (many) reasons we teach version control. When used diligently, it answers the “how” question by acting as a shareable electronic lab notebook for computational work:

  • The conceptual stages of your work are documented, including who did what and when. Every step is stamped with an identifier (the commit ID) that is for most intents and purposes unique.
  • You can tie documentation of rationale, ideas, and other intellectual work directly to the changes that spring from them.
  • You can refer to what you used in your research to obtain your computational results in a way that is unique and recoverable.
  • With a version control system such as Git, the entire history of the repository is easy to archive for perpetuity.

Making Code Citable

Anything that is hosted in a version control repository (data, code, papers, etc.) can be turned into a citable object. You’ll learn how to do this in the later episode on Citation.

How Reproducible Is My Work?

Ask one of your labmates to reproduce a result you recently obtained using only what they can find in your papers or on the web. Try to do the same for one of their results, then try to do it for a result from a lab you work with.

How to Find an Appropriate Data Repository?

Surf the internet for a couple of minutes and check out the data repositories mentioned above: Figshare, Zenodo, Dryad. Depending on your field of research, you might find community-recognized repositories that are well-known in your field. You might also find useful these data repositories recommended by Nature. Discuss with your neighbor which data repository you might want to approach for your current project and explain why.

How to Track Large Data or Image Files using Git?

Large data or image files such as .md5 or .psd file types can be tracked within a github repository using the Git Large File Storage open source extension tool. This tool automatically uploads large file contents to a remote server and replaces the file with a text pointer within the github repository.

Try downloading and installing the Git Large File Storage extension tool, then add tracking of a large file to your github repository. Ask a colleague to clone your repository and describe what they see when they access that large file.

Key Points

  • Open scientific work is more useful and more highly cited than closed.

Content from Licensing


Last updated on 2023-10-25 | Edit this page

Estimated time: 5 minutes

Overview

Questions

  • What licensing information should I include with my work?

Objectives

  • Explain why adding licensing information to a repository is important.
  • Choose a proper license.
  • Explain differences in licensing and social expectations.

When a repository with source code, a manuscript or other creative works becomes public, it should include a file LICENSE or LICENSE.txt in the base directory of the repository that clearly states under which license the content is being made available. This is because creative works are automatically eligible for intellectual property (and thus copyright) protection. Reusing creative works without a license is dangerous, because the copyright holders could sue you for copyright infringement.

A license solves this problem by granting rights to others (the licensees) that they would otherwise not have. What rights are being granted under which conditions differs, often only slightly, from one license to another. In practice, a few licenses are by far the most popular, and choosealicense.com will help you find a common license that suits your needs. Important considerations include:

  • Whether you want to address patent rights.
  • Whether you require people distributing derivative works to also distribute their source code.
  • Whether the content you are licensing is source code.
  • Whether you want to license the code at all.

Choosing a license that is in common use makes life easier for contributors and users, because they are more likely to already be familiar with the license and don’t have to wade through a bunch of jargon to decide if they’re ok with it. The Open Source Initiative and Free Software Foundation both maintain lists of licenses which are good choices.

This article provides an excellent overview of licensing and licensing options from the perspective of scientists who also write code.

At the end of the day what matters is that there is a clear statement as to what the license is. Also, the license is best chosen from the get-go, even if for a repository that is not public. Pushing off the decision only makes it more complicated later, because each time a new collaborator starts contributing, they, too, hold copyright and will thus need to be asked for approval once a license is chosen.

Can I Use Open License?

Find out whether you are allowed to apply an open license to your software. Can you do this unilaterally, or do you need permission from someone in your institution? If so, who?

What licenses have I already accepted?

Many of the software tools we use on a daily basis (including in this workshop) are released as open-source software. Pick a project on GitHub from the list below, or one of your own choosing. Find its license (usually in a file called LICENSE or COPYING) and talk about how it restricts your use of the software. Is it one of the licenses discussed in this session? How is it different?

  • Git, the source-code management tool
  • CPython, the standard implementation of the Python language
  • Jupyter, the project behind the web-based Python notebooks we’ll be using
  • EtherPad, a real-time collaborative editor

Key Points

  • The LICENSE, LICENSE.md, or LICENSE.txt file is often used in a repository to indicate how the contents of the repo may be used by others.
  • People who incorporate General Public License (GPL’d) software into their own software must make their software also open under the GPL license; most other open licenses do not require this.
  • The Creative Commons family of licenses allow people to mix and match requirements and restrictions on attribution, creation of derivative works, further sharing, and commercialization.
  • People who are not lawyers should not try to write licenses from scratch.

Content from Citation


Last updated on 2023-10-25 | Edit this page

Estimated time: 2 minutes

Overview

Questions

  • How can I make my work easier to cite?

Objectives

  • Make your work easy to cite

You may want to include a file called CITATION or CITATION.txt that describes how to reference your project; the one for Software Carpentry states:

To reference Software Carpentry in publications, please cite both of the following:

Greg Wilson: "Software Carpentry: Getting Scientists to Write Better
Code by Making Them More Productive".  Computing in Science &
Engineering, Nov-Dec 2006.

Greg Wilson: "Software Carpentry: Lessons Learned". arXiv:1307.5448,
July 2013.

@article{wilson-software-carpentry-2006,
    author =  {Greg Wilson},
    title =   {Software Carpentry: Getting Scientists to Write Better Code by Making Them More Productive},
    journal = {Computing in Science \& Engineering},
    month =   {November--December},
    year =    {2006},
}

@online{wilson-software-carpentry-2013,
  author      = {Greg Wilson},
  title       = {Software Carpentry: Lessons Learned},
  version     = {1},
  date        = {2013-07-20},
  eprinttype  = {arxiv},
  eprint      = {1307.5448}
}

More detailed advice, and other ways to make your code citable can be found at the Software Sustainability Institute blog and in:

Smith AM, Katz DS, Niemeyer KE, FORCE11 Software Citation Working Group. (2016) Software citation
principles. [PeerJ Computer Science 2:e86](https://peerj.com/articles/cs-86/)
https://doi.org/10.7717/peerj-cs.8

There is also an @software{... BibTeX entry type in case no “umbrella” citation like a paper or book exists for the project you want to make citable.

Key Points

  • Add a CITATION file to a repository to explain how you want your work cited.

Content from Hosting


Last updated on 2023-10-25 | Edit this page

Estimated time: 10 minutes

Overview

Questions

  • Where should I host my version control repositories?

Objectives

  • Explain different options for hosting scientific work.

The second big question for groups that want to open up their work is where to host their code and data. One option is for the lab, the department, or the university to provide a server, manage accounts and backups, and so on. The main benefit of this is that it clarifies who owns what, which is particularly important if any of the material is sensitive (i.e., relates to experiments involving human subjects or may be used in a patent application). The main drawbacks are the cost of providing the service and its longevity: a scientist who has spent ten years collecting data would like to be sure that data will still be available ten years from now, but that’s well beyond the lifespan of most of the grants that fund academic infrastructure.

Another option is to purchase a domain and pay an Internet service provider (ISP) to host it. This gives the individual or group more control, and sidesteps problems that can arise when moving from one institution to another, but requires more time and effort to set up than either the option above or the option below.

The third option is to use a public hosting service like GitHub, GitLab, or BitBucket. Each of these services provides a web interface that enables people to create, view, and edit their code repositories. These services also provide communication and project management tools including issue tracking, wiki pages, email notifications, and code reviews. These services benefit from economies of scale and network effects: it’s easier to run one large service well than to run many smaller services to the same standard. It’s also easier for people to collaborate. Using a popular service can help connect your project with communities already using the same service.

As an example, Software Carpentry is on GitHub where you can find the source for this page. Anyone with a GitHub account can suggest changes to this text.

GitHub repositories can also be assigned DOIs, by connecting its releases to Zenodo. For example, 10.5281/zenodo.7908089 is the DOI that has been “minted” for this introduction to Git.

Using large, well-established services can also help you quickly take advantage of powerful tools. One such tool, continuous integration (CI), can automatically run software builds and tests whenever code is committed or pull requests are submitted. Direct integration of CI with an online hosting service means this information is present in any pull request, and helps maintain code integrity and quality standards. While CI is still available in self-hosted situations, there is much less setup and maintenance involved with using an online service. Furthermore, such tools are often provided free of charge to open source projects, and are also available for private repositories for a fee.

Institutional Barriers

Sharing is the ideal for science, but many institutions place restrictions on sharing, for example to protect potentially patentable intellectual property. If you encounter such restrictions, it can be productive to inquire about the underlying motivations and either to request an exception for a specific project or domain, or to push more broadly for institutional reform to support more open science.

Can My Work Be Public?

Find out whether you are allowed to host your work openly in a public repository. Can you do this unilaterally, or do you need permission from someone in your institution? If so, who?

Where Can I Share My Work?

Does your institution have a repository or repositories that you can use to share your papers, data and software? How do institutional repositories differ from services like arXiV, figshare, GitHub or GitLab?

Key Points

  • Projects can be hosted on university servers, on personal domains, or on a public hosting service.
  • Rules regarding intellectual property and storage of sensitive information apply no matter where code and data are hosted.