Content from Automated Version Control


Last updated on 2025-02-27 | Edit this page

Estimated time: 5 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.

Important!

Everyone should run ssh -T git@github.com to test their SSH access, unless they have a PAT setup.

We’ll start by exploring how version control can be used to keep track of what one person did and when. Even if you aren’t collaborating with other people, automated version control is much better than this situation:

Comic: a PhD student sends "FINAL.doc" to their supervisor, but after several increasingly intense and frustrating rounds of comments and revisions they end up with a file named "FINAL_rev.22.comments49.corrections.10.#@$%WHYDIDCOMETOGRADSCHOOL????.doc"
“notFinal.doc” by Jorge Cham, https://www.phdcomics.com

We’ve all been in this situation before: it seems unnecessary to have multiple nearly-identical versions of the same document. 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.

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.

A diagram demonstrating how a single document grows as the result of sequential changes

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. For example, two users can make independent sets of changes on the same document.

A diagram with one source document that has been modified in two different ways to produce two different versions of the document

Unless multiple users make changes to the same section of the document - a conflict - you can incorporate two sets of changes into the same base document.

A diagram that shows the merging of two different document versions into one document that contains all of the changes from both versions

A version control system is a tool that keeps track of these changes for us, effectively creating different versions of our files. It allows us to decide which changes will be made to the next version (each record of these changes is called a commit), and keeps useful metadata about them. 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.

In this lesson you will be using a version control system called Git alongside a cloud-based platform, GitHub. By the end of the lesson you will have:

  • Configured Git based on our recommended settings
  • Initialised a new repository with Git
  • Committed files to the repository which places them under version control
  • Developed a change using a feature branch
  • Explored the history of your repository
  • Reverted changes to files
  • Ignored files you do not want to version control
  • Created a backup of our repository on GitHub
  • Navigated around the GitHub interface
  • Merged your feature branch changes through GitHub

Terminology


This workshop may contain language that is new to you. The Glossary section outlines key Git & GitHub terminology for your reference.

Take this opportunity to show the learners where the glossary can be found. Explain the difference between Git & GitHub using the glossary! Or if there is time to spare, the first challenge on this page gets the learners to use the glossary to explain the difference to a partner or write it down in their own words.

Distributed Version Control

Git is an example of a distributed version control system. This means that each collaborator has a copy of the entire repository.

---
title: Distributed Version Control (e.g. Git)
---
flowchart TD
    accDescr {A flowchart showing a remote server on GitHub and three local repository copies on collaborators computers. This is a distributed version control system as everyone has a copy of the entire repository and its history.}
    subgraph "Remote Server (GitHub)"
        r1[(Origin Repository)]
    end
    subgraph "<div style="margin-top: 14em">Computer 3</div>"
        r2[(Repository)]
        id2[Working Copy]
    end
    subgraph "<div style="margin-top: 14em">Computer 2</div>"
        r3[(Repository)]
        id3[Working Copy]
    end
    subgraph "<div style="margin-top: 14em">Computer 1</div>"
        r4[(Repository)]
        id4[Working Copy]
    end
    r1 -->|pull| r2 -.->|push| r1
    r1 -->|pull| r3 -.->|push| r1
    r1 -->|pull| r4 -.->|push| r1
    r2 -->|checkout| id2 -.->|commit| r2
    r3 -->|checkout| id3 -.->|commit| r3
    r4 -->|checkout| id4 -.->|commit| r4

Centralised (FCM)

FCM and SVN are examples of centralised version control systems. Here there is only one repository on a central server.

---
title: Centralised Version Control (e.g. SVN)
---
flowchart TD
    accDescr {A flowchart showing a central remote server and three local working copies on collaborators computers.}
    subgraph "Remote Server"
        id1[(Central Repository)]
    end
    subgraph "<div style="margin-top: 5em">Computer 3</div>"
        id2[Working Copy]
    end
    subgraph "<div style="margin-top: 5em">Computer 2</div>"
        id3[Working Copy]
    end
    subgraph "<div style="margin-top: 5em">Computer 1</div>"
        id4[Working Copy]
    end
    id1 -->|checkout| id2 -.->|commit| id1
    id1 -->|checkout| id3 -.->|commit| id1
    id1 -->|checkout| id4 -.->|commit| id1

The Long History of Version Control Systems

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.

Migrating to Git from FCM

If you currently use FCM (a wrapper around Subversion, SVN) then look out for the following dropdowns. They contain the FCM equivalent for Git commands.

Running the git ... command is equivalent to:

BASH

fcm ...

Challenge

Use the Glossary to describe the difference between Git & GitHub in your own words.

Share your description with other learners if you are comfortable doing so.

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 the PhD Comics cartoon at the top of this page.

  • 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.

Key Points

  • Version control is like an unlimited ‘undo’.
  • Version control also allows many people to work in parallel.

Content from Setting Up Git


Last updated on 2025-04-15 | Edit this page

Estimated time: 5 minutes

Overview

Questions

  • How do I get set up to use Git?

Objectives

  • Configure git the first time it is used on a computer.
  • Understand the meaning of the --global configuration flag.

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,
  • what our preferred text editor is,
  • and that we want to use these settings globally (i.e. for every project).

Command Line Git Setup


On a command line, Git commands are written as git verb options, where verb is what we actually want to do and options is additional optional information which may be needed for the verb.

Authorship

To set up a new computer:

BASH

$ git config --global user.name "Joanne Simpson"
$ git config --global user.email "j.simpson@mo-weather.uk"

Please use your own name and email address. 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 GitHub’s no-reply email address for the user.email value. It looks like ID+username@users.noreply.github.com. You can look up your own address in your GitHub email settings. Check with your instructor whether your organisation has a policy on keeping emails private. At the Met Office it is up to you whether to keep your email address private.

Text Editor

To set your preferred text editor, find the correct configuration command from 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"
gVim $ git config --global core.editor "gvim -f"
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.

Nedit not available on Azure Spice

Nedit won’t be available on Azure SPICE VDI. Details are available in the Met Office Azure SPICE Documentation. The most similar editor in the table above is Gedit.

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 press Enter or or on Macs, Return. If you want to save your changes and quit, press Esc then type :wq and press Enter or or on Macs, Return.

Default Branch Name

Git (2.28+) allows configuration of the name of the branch created when you initialize any new repository. We want to set this to main so it matches the cloud service we will eventually use.

BASH

$ git config --global init.defaultBranch main

History of main

Source file changes are associated with a “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.

The five commands we just ran above only need to be run once: the flag --global tells Git to use the settings for every project, in your user account, on this computer.

Text Editor Git Setup


Let’s review those settings and test our core.editor right away:

BASH

$ git config --global --edit

Let’s close the file without making any additional changes. Since typos in the config file will cause issues, it’s safer to view the configuration with:

BASH

$ git config --list

And alter the configuration via the command line. You can re-run the commands above as many times as you want to change your configuration. The discussion page has details on more recommended settings.

Proxy

In some networks you need to use a proxy. If this is the case, you may also need to tell Git about the proxy:

BASH

$ git config --global http.proxy proxy-url
$ git config --global https.proxy proxy-url

To disable the proxy, use

BASH

$ git config --global --unset http.proxy
$ git config --global --unset https.proxy

Git Help and Manual

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

Key Points

  • Use git config with the --global option to configure a user name, email address, editor, and other preferences once per machine.

Content from Creating a Repository


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

Estimated time: 10 minutes

Overview

Questions

  • Where does Git store information?

Objectives

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

Now that Git is configured, we can start using it.

First, let’s create a new directory in the Desktop folder for our work and then change the current working directory to the newly created one:

BASH

$ cd ~/Desktop
$ mkdir weather
$ cd weather

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

BASH

$ git init

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

If we use ls to show the directory’s contents, it appears that nothing has changed:

BASH

$ ls

But if we add the -a flag to show everything, we can see that Git has created a hidden directory within weather called .git:

BASH

$ ls -a

OUTPUT

.	..	.git

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.

FCM, which wraps SVN, is a centralised version control system. There is one central repository stored on a server that we work from.

Git is an example of distributed version control. The .git directory contains the entire history of the repository. Each colleague working on the same repository will have a backup of the whole repository. We recommend reading the GitLab links in this callout for more benefits of Git and distributed version control systems over FCM/SVN.

We can now start using one of the most important git commands, which is particularly helpful to beginners. git status tells us the status of our project, and better, a list of changes in the project and options on what to do with those changes. We can use it as often as we want, whenever we want to understand what is going on.

BASH

$ git status

OUTPUT

On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)

git status is equivalent to:

BASH

$ fcm status

or

BASH

$ fcm info

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

Initial Commit


As soon as you initialise your repository you should make an initial commit. All repositories should have a README file which outlines the purpose of the repository and other useful information. For now we will create the file with just the repository name, Weather as the title:

BASH

$ echo "# Weather" > README.md
$ cat README.md

OUTPUT

# Weather

Now add and commit the README.md file using the git add and git commit commands:

BASH

$ git add README.md
$ git commit -m "Initial commit"

OUTPUT

[main (root-commit) 6f12a47] Initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 README.md

You’ve just added your first file to be version controlled with Git! This first commit is the special root-commit. It is the start of your version control history and like all commits has been given a unique alphanumeric hash (6f12a47). In the next few episodes you will explore tracking changes with git add and git commit in detail, and learn how to inspect your repositories history.

README Files

All repositories should have a README file. The README file describes what is in your repository. The makeareadme website is a great resource for README templates and inspiration.

The README.md file we added is a Markdown file. Markdown is a simple markup language and GitHub can render Markdown files natively. The GitHub documentation pages on Writing on GitHub have more info on writing in Markdown for GitHub.

Places to Create Git Repositories

Along with tracking information about weather (the project we have already created), you might also want to track information about clouds specifically. Imagine you create a clouds project inside your weather project with the following sequence of commands:

BASH

$ cd ~/Desktop    # return to Desktop directory
$ cd weather      # go into weather directory, which is already a Git repository
$ ls -a           # ensure the .git subdirectory is still present in the weather directory
$ mkdir clouds    # make a sub-directory weather/clouds
$ cd clouds       # go into clouds subdirectory
$ git init        # make the clouds subdirectory a Git repository
$ ls -a           # ensure the .git subdirectory is present indicating we have created a new Git repository

Is the git init command, run inside the clouds subdirectory, required for tracking files stored in the clouds subdirectory?

No. You do not need to make the clouds subdirectory a Git repository because the weather repository will track all files, sub-directories, and subdirectory files under the weather directory. Thus, in order to track all information about clouds, you only needed to add the clouds subdirectory to the weather 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. 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

Correcting git init Mistakes

A colleague explains to you how a nested repository is redundant and may cause confusion down the road. You would like to go back to a single Git repository. How can you undo the last git init in the clouds subdirectory?

Background

Removing files from a Git repository needs to be done with caution. But we have not learned yet how to tell Git to track a particular file; we will learn this in the next episode. Files that are not tracked by Git can easily be removed like any other “ordinary” files with

BASH

$ rm filename

Similarly a directory can be removed using rm -r dirname. If the files or folder being removed in this fashion are tracked by Git, then their removal becomes another change that we will need to track, as we will see in the next episode.

Solution

Git keeps all of its files in the .git directory. To recover from this little mistake, you can remove the .git folder in the clouds subdirectory by running the following command from inside the weather directory:

BASH

$ rm -rf clouds/.git

But be careful! Running this command in the wrong directory will remove the entire Git history of a project you might want to keep. In general, deleting files and directories using rm from the command line cannot be reversed. Therefore, always check your current directory using the command pwd.

Key Points

  • git init initializes a repository.
  • Git stores all of its repository data in the .git directory.

Content from Branches


Last updated on 2025-02-12 | Edit this page

Estimated time: 30 minutes

Overview

Questions

  • Understand how branches are created.
  • Learn the key commands to view and manipulate branches.

Objectives

  • What are branches?
  • How do I view the current branches?
  • How do I manipulate branches?

Branching is a feature available in most modern version control systems. Branching in other version control systems can be an expensive operation in both time and disk space. In Git, branches are a part of your everyday development process.

So far we have been working on the main branch and have made one commit, the root-commit. Committing the initial root-commit is the only time you should commit to main. When you want to add a new change or fix a bug, no matter how big or how small, you create a new branch for your changes. This makes it harder for unstable code to get merged into the main code base, and it gives you the chance to clean up your branch history before merging it into the main branch.

---
config:
  gitGraph:
    showCommitLabel: false
---
    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch with one commit branched off the root-commit. This branch is then merged back into main via a merge commit on GitHub.}
        commit id: '6f12a47'
        branch forecast
        commit id: '8136c6f Add in a seasonal forecasts file'
        checkout main
        merge forecast

If you completed the pre-workshop setup instructions for git autocomplete you should see the current branch, main, in your terminal prompt:

[~/Desktop/weather]:(main =)$

The git status command also shows us the current branch:

BASH

$ git status

OUTPUT

On branch main
nothing to commit, working tree clean

The phrase working tree clean means there are no changes in your working directory and the current state of your repository is identical to the last commit.

main == trunk

In an earlier episode we set our default branch to be called main. This is where our stable production code lives and is equivalent to trunk.

We could have also named this branch trunk in Git. We chose main as it is a more common default branch name for Git and matches the default on GitHub.

Creating Branches


Our current repository looks something like this:

---
config:
  gitGraph:
    showCommitLabel: false
---
    gitGraph
        accDescr {A Git graph showing one commit, the root-commit on the main branch.}
        commit id: '6f12a47'

To make any changes we should create a new branch. There are several ways to create a branch and switch to the new branch. While it’s good to be aware of all these different methods we recommend using git switch -c.

You should ensure the branch has a suitable unique name which will help you identify what the branch is for; even after several months of inactivity.

We are going to add a weather forecast to our repository so our branch will be named forecast:

The git switch command was added in Git version 2.23. To check your version run:

BASH

$ git --version
git version 2.47.0

If your version of Git is lower than 2.23 you should use the git checkout command to swap branches.

Running git status now should output:

BASH

$ git status

OUTPUT

On branch forecast
nothing to commit, working tree clean

Now we have created but not committed anything to this new branch so our repository looks like this:

---
config:
  gitGraph:
    showCommitLabel: false
---
    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch with no commits.}
        commit id: '6f12a47'
        branch forecast

If we run git branch we can see the branches that exist in our repository.

BASH

$ git branch

OUTPUT

* forecast
  main

The * indicates we are now on the forecast branch.

Unique Branch Names

To avoid creating a branch with the same name as a collaborators branch it is common to prefix the branch name with an Issue (ticket) number.

You might choose to include your initials or username in your branch although this is less common than an Issue number.

Separate words in branch names with - or _ depending on your teams working practices. The Git & GitHub Working Practices lesson, which you can take after this introductory lesson, will help you choose the working practices that are right for you and your team.

Switching Between Branches

How would you switch back to the main branch from the forecast branch?

BASH

$ git switch main

Typos when creating branches

Help! Luca made a typo when naming their branch, seesonal-forecast, how can they fix the branch name?

Hint: Look at the git documentation for the git branch command.

The -m flag used with git branch lets you rename a branch.

BASH

$ git branch -m <old-branch-name> <new-branch-name>

Branch start-points

The commands we used above created a branch from the HEAD of the main branch because we ran git switch from main. How would you create a branch that branched off at an earlier commit that isn’t HEAD?

Hint: Look at the git documentation for the git switch command.

The git switch command lets you define a <start-point> to branch from:

BASH

$ git switch -c <branch-name> <start-point>

<branch-name> is the name of the new branch. <start-point> can be a branch name, a commit-id, or a tag.

This functionality also applies to the git branch command:

BASH

git branch <branch-name> <start-point>

Deleting Branches


A colleague of yours gets really excited about using branches and creates a new one:

BASH

$ git switch -c shipping-forecast

OUTPUT

Switched to a new branch 'shipping-forecast'

They then check their branches:

BASH

$ git branch -vv

OUTPUT

  forecast          6f12a47 Initial commit
  main              6f12a47 Initial commit
* shipping-forecast 6f12a47 Initial commit

Your colleague decides to delete the branch since today’s shipping forecast isn’t ready. To delete a branch first switch to any other branch:

BASH

$ git switch forecast

and then delete the branch with git branch -d:

BASH

$ git branch -d shipping-forecast

OUTPUT

Deleted branch shipping-forecast (was 6f12a47).

Check your branch point

Always switch to the branch you want to branch from, usually main, or explicitly specify a branch point when creating new branches. This helps avoid accidentally branching of a branch which isn’t main if you didn’t mean to.

Imagine a colleague has added more files to their forecast branch and just created a tidal-forecast branch.

They run:

$ git branch -vv

OUTPUT

  forecast       8136c6f Add in a seasonal forecasts file
  main           6f12a47 Initial commit
* tidal-forecast 8136c6f Add in a seasonal forecasts file

Here the hash for the tidal-forecast branch is the same as the forecast branch so tidal-forecast is not branched off main. If they meant to branch off main they should delete this branch, and re-create it from the correct branch point.

Deleting a branch that is checked out

What happens if you:

  1. Create a new branch and switch to it
  2. Try to delete the new branch while it’s checked out

Git won’t let you delete a branch you are currently on! Try it for yourself:

BASH

$ git switch -c climate
$ git branch -D climate

OUTPUT

error: Cannot delete branch 'climate' checked out at '~/Documents/weather'

Note that even with the -D, force delete, flag the branch wasn’t deleted.

Key Points

  • git status shows you the branch you’re currently on.
  • git switch -c <branch-name> creates a new branch and switches you to it. Make sure you know what branch you are branching from before using git switch without a start-point!
  • git switch -c <branch-name> <start-point> lets you define the start-point to branch off, via another branch name, a commit ID, or a tag.
  • git switch <branch-name> switches you to another branch that already exists.
  • git branch -vv shows you all the branches in the repository.
  • git branch -m <old-branch-name> <new-branch-name> renames branches.
  • git branch -d <branch-name> deletes a branch. Use the -D flag instead of -d to force delete the branch.

Content from Tracking Changes


Last updated on 2025-01-20 | Edit this page

Estimated time: 20 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.

First let’s make sure we’re still on the right branch. You should be on the forecast branch:

BASH

$ git switch forecast

Let’s create a file called forecast.md that contains a basic weather forecast. We’ll use nano to edit the file; you can use whatever editor you like. In particular, this does not have to be the core.editor you set globally earlier. But remember, the steps to create create or edit a new file will depend on the editor you choose (it might not be nano). For a refresher on text editors, check out “Which Editor?” in The Unix Shell lesson.

BASH

$ nano forecast.md

Type the text below into the forecast.md file:

OUTPUT

# Forecast

## Today

Cloudy with a chance of pizza.

Save the file and exit your editor. Next, let’s verify that the file was properly created by running the list command (ls):

BASH

$ ls

OUTPUT

forecast.md README.md

forecast.md contains three lines, which we can see by running:

BASH

$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of pizza.

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 forecast
Untracked files:
   (use "git add <file>..." to include in what will be committed)

	forecast.md

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 forecast.md

and then check that the right thing happened:

BASH

$ git status

OUTPUT

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

	new file:   forecast.md

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

BASH

$ git commit -m "Create a md file with the forecast"

OUTPUT

[forecast f22b25e] Create a md file with the forecast
 1 file changed, 5 insertions(+)
 create mode 100644 forecast.md

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 nano (or whatever other editor we configured as core.editor) so that we can write a longer message.

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.

The whatthecommit site can be used to show example commit messages, good and bad, pulled from public repos on GitHub. You should note that there is no safe for work filter. Some of the commit messages may include inappropriate language.

Using git add .

Using git add . or the -a flag with git commit will add all your unstaged changes in your repository.

This might include things you didn’t mean to add. Always use git status to check your changes before adding them. We recommend you avoid using git add . and git commit -a.

Running git add followed by git commit is equivalent to:

BASH

$ fcm commit

Our repository now looks like this:

    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch, branching off the root-commit, with one commit.}
        commit id: 'Initial commit'
        branch forecast
        commit id: 'Create a md file with the forecast'

If we run git status now:

BASH

$ git status

OUTPUT

On branch forecast
nothing to commit, working tree clean

it tells us everything is up to date.

Where Are My Changes?

If we run ls at this point, we will still see just our two files, README.md and forecast.md. 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).

Now suppose you want to more information to the file. (Again, we’ll edit with nano and then cat the file to show its contents; you may use a different editor, and don’t need to cat.)

BASH

$ nano forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of pizza.

## Tomorrow

Morning rainbows followed by light showers.

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 forecast
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)

	modified:   forecast.md

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. 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/forecast.md b/forecast.md
index df0654a..315bf3a 100644
--- a/forecast.md
+++ b/forecast.md
@@ -3,3 +3,7 @@
 ## Today

 Cloudy with a chance of pizza.
+
+## Tomorrow
+
+Morning rainbows followed by light showers.

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.

git difftool

git-difftool lets you compare and edit files using your preferred diff tool.

BASH

$ git difftool -g

The -g flag launches the default gui diff tool. To change defaults:

BASH

git config --global diff.tool <tool>
git config --global diff.guitool <gui-tool>
git config --global difftool.prompt false
git config --global difftool.guiDefault auto

Where <tool> is a diffing tool such as Vim, <gui-tool> is your preferred graphical user interface diffing tool such as meld. The third line disables the Git prompt which asks you to confirm whether to launch the diff for every changed file. The last line automatically detects support for launching the gui based tool and launches <gui-tool> preferentially over <tool>. With this set to auto there is no need to add the -g flag when running git difftool.

To see a list of available tools run:

BASH

$ git difftool --tool-help

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

BASH

$ git commit -m "Add tomorrows forecast to forecast.md"

OUTPUT

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

	modified:   forecast.md

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 forecast.md
$ git commit -m "Add tomorrows forecast to forecast.md"

OUTPUT

[forecast 34961b1] Add tomorrows forecast to forecast.md
 1 file changed, 4 insertions(+)

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.

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!

A diagram showing how "git add" registers changes in the staging area, while "git commit" moves changes from the staging area to the repository

In FCM there is no concept of a staging area. FCM will commit all file modifications at once. This can lead to rather large commits. In Git remember to break down commits into small logical chunks.

BASH

$ git add <file>
$ git commit

is equivalent to:

BASH

$ fcm commit

Our repository now looks like this:

    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch, branching off the root-commit, with two commits.}
        commit id: 'Initial commit'
        branch forecast
        commit id: 'Create a md file with the forecast'
        commit id: 'Add tomorrows forecast to forecast.md'

Let’s watch as our changes to a file move from our editor to the staging area and into long-term storage. First, we’ll improve our forecast by changing ‘pizza’ to ‘Sun’:

BASH

$ nano forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of Sun.

## Tomorrow

Morning rainbows followed by light showers.

BASH

$ git diff

OUTPUT

diff --git a/forecast.md b/forecast.md
index 315bf3a..b36abfd 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,7 +2,7 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of Sun.

 ## Tomorrow

So far, so good: we’ve replaced one line (shown with a - in the first column) with a new line (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 forecast.md
$ 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/forecast.md b/forecast.md
index 315bf3a..b36abfd 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,7 +2,7 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of Sun.

 ## Tomorrow

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 "Modify the forecast to add a chance of Sun"

OUTPUT

[forecast 005937f] Modify the forecast to add a chance of Sun
 1 file changed, 1 insertion(+), 1 deletion(-)

check our status:

BASH

$ git status

OUTPUT

On branch forecast
nothing to commit, working tree clean

Our repository now looks like this:

    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch, branching off the root-commit, with three commits.}
        commit id: 'Initial commit'
        branch forecast
        commit id: 'Create a md file with the forecast'
        commit id: 'Add tomorrows forecast to forecast.md'
        commit id: 'Modify the forecast to add a chance of Sun'

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.

Directories

Two important facts you should know about directories in Git.

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

BASH

$ mkdir symbols
$ git status
$ git add symbols
$ git status

Note, our newly created empty directory symbols 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 symbols/pressure.md symbols/pollen.md
$ git status
$ git add symbols
$ git status

Before moving on, we will commit these changes.

BASH

$ git commit -m "Add some initial weather symbols"

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):

A diagram showing two documents being separately staged using git add, before being combined into one commit using git commit

Choosing a Commit Message

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

  1. “Changes”
  2. “Modify the forecast”
  3. “Modify the forecast to add a chance of Sun”

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.

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 forecast.md noting the expected temperature.
  2. Create a new file atlas.md with a list of common weather such as rain, sunshine, fog etc.
  3. Add changes from both files to the staging area, and commit those changes.

First we make our changes to the forecast.md and atlas.md files:

BASH

$ nano forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of sun.
Mild temperatures around 16 °C.

## Tomorrow

Morning rainbows followed by light showers.

BASH

$ nano atlas.md
$ cat atlas.md

OUTPUT

# Weather Atlas

- rain
- sunshine
- fog

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

BASH

$ git add forecast.md atlas.md

Or with multiple commands:

BASH

$ git add forecast.md
$ git add atlas.md

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 "Add in the temperature to the forecast and create the weather atlas file"

OUTPUT

[forecast cc127c2] Add in the temperature to the forecast and create the weather atlas file
 2 files changed, 6 insertions(+)
 create mode 100644 atlas.md

bio Repository

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

If needed, move out of the weather folder:

BASH

$ cd ..

Create a new folder called bio and ‘move’ into it:

BASH

$ mkdir bio
$ cd bio

Initialise the repository:

BASH

$ git init

Create your biography file me.txt using nano or another text editor. Once in place, add and commit it to the repository:

BASH

$ git add me.txt
$ 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.txt

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 Exploring History


Last updated on 2025-01-20 | Edit this page

Estimated time: 20 minutes

Overview

Questions

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

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.

Viewing a Repositories History


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

BASH

$ git log

OUTPUT

commit cdb7fa654c3f5aee731a655e57f2ba74d9c74582 (HEAD -> forecast)
Author: Joanne Simpson <j.simpson@mo-weather.uk>
Date:   Mon Nov 4 18:35:21 2024 +0000

    Add in the temperature to the forecast and create the weather atlas file

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. The output above only shows the latest commit in the log for brevity, you should see all your commits! Your log output may be different from what’s shown above depending on whether you completed the challenges in earlier episodes.

git log is equivalent to:

BASH

$ fcm log

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 cdb7fa654c3f5aee731a655e57f2ba74d9c74582 (HEAD -> forecast)
Author: Joanne Simpson <j.simpson@mo-weather.uk>
Date:   Mon Nov 4 18:35:21 2024 +0000

    Add in the temperature to the forecast and create the weather atlas file

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

BASH

$ git log --oneline

OUTPUT

cdb7fa6 (HEAD -> forecast) Add in the temperature to the forecast and create the weather atlas file
62a9457 Modify the forecast to add a chance of Sun
d3e4637 Add tomorrows forecast to forecast.md
590c40c Create a md file with the forecast

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][git-references]:

BASH

$ git log --oneline --graph

OUTPUT

* cdb7fa6 (HEAD -> forecast) Add in the temperature to the forecast and create the weather atlas file
* 62a9457 Modify the forecast to add a chance of Sun
* d3e4637 Add tomorrows forecast to forecast.md
* 590c40c Create a md file with the forecast

A common alias for git log

It is often useful to use the --decorate, --oneline, and --graph flags all at once. To avoid us having to write out the three flags each time we can set an alias:

BASH

$ git config --global alias.dog "log --decorate --oneline --graph"

This alias makes these two commands equivalent:

BASH

$ git dog
$ git log --decorate --oneline --graph

--decorate ensures commits with reference names1 are displayed when using older versions of Git.

git show

The git show command lets you view information for specific commits. By default git show will show information for the latest commit on the current branch.

BASH

$ git show

OUTPUT

commit cdb7fa654c3f5aee731a655e57f2ba74d9c74582 (HEAD -> forecast)
Author: Joanne Simpson <j.simpson@mo-weather.uk>
Date:   Mon Nov 4 18:35:21 2024 +0000

    Add in the temperature to the forecast and create the weather atlas file

diff --git a/atlas.md b/atlas.md
new file mode 100644
index 0000000..18fac28
--- /dev/null
+++ b/atlas.md
@@ -0,0 +1,5 @@
+# Weather Atlas
+
+- rain
+- sunshine
+- fog
:

Identifying Commits


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 reference name HEAD.

We’ve been adding small changes at a time to forecast.md, 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 forecast.md, adding yet another line with an ill-considered change.

BASH

$ nano forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of sun.
Mild temperatures around 16 °C.

## Tomorrow

Morning rainbows followed by light showers.
An ill-considered change.

Now, let’s see what we get.

BASH

$ git diff HEAD forecast.md

OUTPUT

diff --git a/forecast.md b/forecast.md
index b36abfd..0848c8d 100644
--- a/forecast.md
+++ b/forecast.md
@@ -8,3 +8,4 @@
 Mild temperatures around 16 °C.

 ## Tomorrow

 Morning rainbows followed by light showers.
+An ill-considered change.

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 forecast.md

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~2 forecast.md

OUTPUT

diff --git a/forecast.md b/forecast.md
index df0654a..b36abfd 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,8 +2,10 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of sun.
+Mild temperatures around 16 °C.

 ## Tomorrow

 Morning rainbows followed by light showers.
+An ill-considered change.

We can also use identifiers with git show.

BASH

$ git show HEAD~2 forecast.md

OUTPUT

Author: Joanne Simpson <j.simpson@mo-weather.uk>
Date:   Mon Nov 4 18:16:29 2024 +0000

    Add tomorrows forecast to forecast.md

diff --git a/forecast.md b/forecast.md
index d8bc6ce..5b5d97e 100644
--- a/forecast.md
+++ b/forecast.md
@@ -3,3 +3,7 @@
 ## Today

 Cloudy with a chance of pizza.
+
+## Tomorrow
+
+Morning rainbows followed by light showers.

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.

We can also refer to commits using those long strings of digits and letters that both git log and git show display. 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 on the forecast branch was given the ID f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try this:

BASH

$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b forecast.md

OUTPUT

diff --git a/forecast.md b/forecast.md
index df0654a..93a3e13 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,4 +2,10 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of sun.
+Mild temperatures around 16 °C.
+
+## Tomorrow
+
+Morning rainbows followed by light showers.
+An ill-considered change.

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 forecast.md

OUTPUT

diff --git a/forecast.md b/forecast.md
index df0654a..93a3e13 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,4 +2,10 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of sun.
+Mild temperatures around 16 °C.
+
+## Tomorrow
+
+Morning rainbows followed by light showers.
+An ill-considered change.

So far we have only been comparing a previous commit to the working copy. To get a difference between two specific commits use both their IDs:

BASH

$ git diff d3e4637 62a9457 forecast.md

OUTPUT

diff --git a/forecast.md b/forecast.md
index 4c96be7..541eee7 100644
--- a/forecast.md
+++ b/forecast.md
@@ -2,7 +2,7 @@

 ## Today

-Cloudy with a chance of pizza.
+Cloudy with a chance of Sun.

 ## Tomorrow
 

Understanding Workflow and History

What is the output of the last command in

BASH

$ cd weather
$ git switch -c add_CMIP_data
$ echo "Global Climate Data" > CMIP7.md
$ git add CMIP7.md
$ echo "Data from the 7th model intercomparison project" >> CMIP7.md
$ git commit -m "Adds in CMIP7 data file"
$ git restore CMIP7.md
$ cat CMIP7.md  # this will print the content of CMIP7.md on screen
  1. OUTPUT

      Data from the 7th model intercomparison project
  2. OUTPUT

      Global Climate Data
  3. OUTPUT

      Global Climate Data
      Data from the 7th model intercomparison project
  4. OUTPUT

      Error because you have changed CMIP7.md without committing the changes

The answer is 2.

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 "Adds in CMIP7 data file" is executed, the version of CMIP7.md committed to the repository is the one from the staging area and only has one line, Global Climate Data.

At this time, the working copy still has the second line (and git status will show that the file is modified). However, git restore CMIP7.md removes all unstaged modifications to the CMIP7.md file, so the second line is removed. So, cat CMIP7.md will output

OUTPUT

Global Climate Data

Checking Understanding of git diff

Consider this command: git diff HEAD~9 forecast.md. 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] forecast.md, where [ID] is replaced with the unique identifier for your most recent commit. What do you think will happen, and what does happen?

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 weather project has more than 50 files. You would like to find a commit that modifies some specific text in forecast.md. 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 forecast.md. We can apply a similar idea here.

BASH

$ git log forecast.md

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 forecast.md

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 *.md

Key Points

  • git log displays the repositories history.
  • git diff displays differences between commits.
  • HEAD references the last commit.
  • HEAD~1 references the commit before last.

  1. References in Git are user friendly links to specific commits. For instance HEAD is a reference to the latest commit on a branch. Programs with regular releases might add reference tags such as v1.0 to a specific commit to mark a new release. These references can be used instead of a commit identifier such as e48heu0.↩︎

Content from Reverting Changes


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

Estimated time: 25 minutes

Overview

Questions

  • How can I recover old versions of files?

Objectives

  • Restore old versions of files.
  • Undo commits.

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 forecast.md (the “ill-considered change”).

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

BASH

$ git status

OUTPUT

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

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 restore:

BASH

$ git restore forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of sun.
Mild temperatures around 16 °C.

## Tomorrow

Morning rainbows followed by light showers.

As you might guess from its name, git restore restores an old version of a file. By default, it recovers the version of the file recorded in HEAD, which is the last saved commit.

git restore is equivalent to:

BASH

$ fcm revert FILE

Restoring a file from further back


If we want to go back even further, we can use a commit identifier instead, using -s option:

BASH

$ git restore -s f22b25e forecast.md

BASH

$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of pizza.

BASH

$ git status

OUTPUT

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

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

Notice that the changes are not currently in the staging area, and have not been committed. If we wished, we can put things back the way they were at the last commit by using git restore to overwrite the working copy with the last committed version:

BASH

$ git restore forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of sun.
Mild temperatures around 16 °C.

## Tomorrow

Morning rainbows followed by light showers.

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. We use the . to mean all files:

A diagram showing how git restore can be used to restore the previous version of two files

The fact that files can be restored 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.

Reverting Changes


Generally it is best to spot and revert mistakes before the commit stage. The table below summarises how to revert a change depending on where in the commit process you are:

To revert files you have … git command
modified $ git restore <files>
staged $ git restore --staged <files>
committed $ git revert <commit>

We have already practised restoring modified files. Now let’s practise restoring staged changes. Go ahead and make a similar change like you did earlier to your forecast.md:

BASH

$ nano forecast.md
$ cat forecast.md

OUTPUT

# Forecast

## Today

Cloudy with a chance of sun.
Mild temperatures around 16 °C.

## Tomorrow

Morning rainbows followed by light showers.
Another ill-considered change.

Add the changes:

BASH

$ git add forecast.md

Now git status shows:

BASH

$ git status

OUTPUT

On branch forecast
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
	modified:   forecast.md

And we can use the hint to unstage our changes:

BASH

$ git restore --staged forecast.md

Our modifications to the forecast.md file have been unstaged and are now back in the working copy. We can restore these modifications fully with:

BASH

$ git restore forecast.md

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 restore

  2. $ git restore data_cruncher.py

  3. $ git restore -s HEAD~1 data_cruncher.py

  4. $ git restore -s <unique ID of last commit> data_cruncher.py

  5. Both 2 and 4

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

The restore 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 results in an error. You need to specify a file to restore. If you want to restore all files you should use git restore .

Reverting a Commit

Ahmed is collaborating with colleagues on a Python script. He realizes his last commit to the project’s repository contained an error, and wants to undo it. Ahmed wants to undo it 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 restore -s [commit ID] .. git restore restores files within the local repository to a previous state, whereas git revert restores the files to a previous state and adds then commits these changes to the local repository. So git revert here is the same as git restore -s [commit ID]
followed by git commit -am Reverts: [commit].

git revert undoes a whole commit whereas git restore -s can be used restore individual files.

Below are the right steps and explanations for Ahmed 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, Ahmed should double-check it is the correct commit, and no one else has committed changes to the repository.

Key Points

  • git restore recovers old versions of files.
  • git reset undoes staged changes.
  • git revert reverses a commit.

Content from Ignoring Things


Last updated on 2024-12-19 | 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 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? Let’s create a few dummy files:

BASH

$ mkdir data
$ touch a.png b.png c.png data/a.csv data/b.nc

and see what Git says:

BASH

$ git status

OUTPUT

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

	a.png
	b.png
	c.png
	data/

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:

BASH

$ nano .gitignore
$ cat .gitignore

OUTPUT

*.png
data/

These patterns tell Git to ignore any file whose name ends in .png and everything in the data 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:

BASH

$ git status

OUTPUT

On branch forecast
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 png files and the data folder"
$ git status

OUTPUT

On branch forecast
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.png

OUTPUT

The following paths are ignored by one of your .gitignore files:
a.png
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 forecast
Ignored files:
 (use "git add -f <file>..." to include in what will be committed)

        a.png
        b.png
        c.png
        data/

nothing to commit, working tree clean

Ignoring Nested Files

Given a directory structure that looks like:

BASH

data/csv
data/plots

How would you ignore only data/plots and not data/csv?

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

OUTPUT

data/plots/

This line will ensure only the contents of data/plots is ignored, and not the contents of data/csv.

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 .png files in your root directory except for final.png? Hint: Find out what ! (the exclamation point operator) does

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

OUTPUT

*.png           # ignore all png files
!final.png      # except final.png

The exclamation point operator will include a previously excluded entry.

Note if you’ve previously committed .png files they will not be ignored with this new rule. Only future additions of .png files added to the root directory will be ignored.

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

data/csv
data/images
data/plots
data/analysis

How would you ignore all of the contents in the data folder, but not data/csv?

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

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

OUTPUT

data/*               # ignore everything in data folder
!data/csv/          # do not ignore data/csv/ 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/csv/global/temperature/a.dat
data/csv/global/temperature/b.dat
data/csv/global/temperature/c.dat
data/csv/global/temperature/info.txt
data/plots

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

Appending data/csv/global/temperature/*.dat will match every file in data/csv/global/temperature that ends with .dat. The file data/csv/global/temperature/info.txt will not be ignored.

Ignoring all 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

results/a.csv
data/experiment_1/b.csv
data/experiment_2/c.csv
data/experiment_2/variation_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

  • The .gitignore file tells Git what files to ignore.

Content from Break


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

Estimated time: 0 minutes

This marks the end of the Git section. Take a break and remember to fill out your minute card feedback.

Summary


You’ve now used Git to create a repository and made some commits on a feature branch. Your repository will look something like this:

---
config:
  gitGraph:
    showCommitLabel: false
---
    gitGraph
        accDescr {A Git graph showing the root-commit on the main branch and a new forecast branch with five commits.}
        commit id: 'Initial commit'
        branch forecast
        commit id: 'Create a md file with the forecast'
        commit id: 'Add tomorrows forecast to forecast.md'
        commit id: 'Modify the forecast to add a chance of Sun'
        commit id: 'Add in the temperature to the forecast and create the weather atlas file'
        commit id: 'Ignore png files and the data folder'

Your repo may have a different number of commits on the forecast branch depending on which challenge exercises you have completed. You can find short summaries of all the new commands you’ve learnt on the Key Points page.

Content from Remotes in GitHub


Last updated on 2025-02-25 | 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.

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 now share 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.

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 weather:

The first step in creating a repository on GitHub: clicking the "create new" button

Name your repository “weather” 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.

The second step in creating a repository on GitHub: filling out the new repository form to provide the repository name, and specify that neither a readme nor a license should be created

Here we have chosen to make our repository public. The visibility of your repository depends on which option you choose:

  • Private: only you
  • Internal (organisations only): read permissions to anyone in the organisation
  • Public: read permissions to anyone

Some organisations will restrict the creation of public repositories so you may find their default is internal. If your project deals with sensitive material then create a private repository.

As soon as the repository is created, GitHub displays a page with a URL and some information on how to configure your local repository. Ignore the suggested commands for now as we will run these later.

The summary page displayed by GitHub after a new repository has been created. It contains instructions for configuring the new GitHub repository as a Git remote

This effectively does the following on GitHub’s servers:

BASH

$ mkdir weather
$ cd weather
$ git init

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

A diagram showing how "git add" registers changes in the staging area, while "git commit" moves changes from the staging area to the repository

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

A diagram illustrating how the GitHub "weather" repository is also a Git repository like our local repository, but that it is currently empty

Note that our local repository still contains our earlier work on forecast.md, 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:

A screenshot showing that clicking on "SSH" will make GitHub provide the SSH URL for a repository instead of the HTTPS URL

Click on the ‘SSH’ link to change the protocol from HTTPS to SSH.

HTTPS vs. SSH

We use SSH here because, while it requires some additional configuration, it is a security protocol widely used by many applications. The steps below describe SSH at a minimum level for GitHub.

If you use a Personal Access Token (PAT) to connect to GitHub you should select ‘HTTPS’ not ‘SSH’.

We recommend you move to using SSH Keys instead of a PAT. The setup instructions show you how to set up an SSH key.

If you choose to continue using your PAT, in the rest of the material any SSH links such as:

BASH

git@github.com:mo-eormerod/weather.git

should be converted to the HTTPS form like this:

BASH

https://github.com/mo-eormerod/weather.git

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

BASH

$ git remote add origin git@github.com:mo-eormerod/weather.git

Make sure to use the URL for your repository: the only difference should be your username instead of mo-eormerod.

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:mo-eormerod/weather.git (fetch)
origin   git@github.com:mo-eormerod/weather.git (push)

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

3. Push local changes to a remote


Now that authentication is setup, we can return to the local repository. Ensure you are on the main branch:

BASH

$ git switch main

This command will push our main branch on our local repository to the repository on GitHub:

BASH

$ git push

OUTPUT

fatal: The current branch main has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin main

Git is telling us it doesn’t know what branch we want to push our local main branch to on GitHub. We can tell Git this by setting the upstream origin branch to also be named main.

If you entered a passphrase when creating an shh key you will be prompted for it.

OUTPUT

Enumerating objects: 16, done.
Counting objects: 100% (16/16), done.
Delta compression using up to 4 threads
Compressing objects: 100% (13/13), done.
Writing objects: 100% (16/16), 1.69 KiB | 216.00 KiB/s, done.
Total 16 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), done.
To github.com:mo-eormerod/weather.git
 * [new branch]      main -> main
branch 'main' set up to track 'origin/main'.

Automatically set the upstream branch

You can get git to automatically set the upstream branch. This avoids having to run git push with the --set-upstream flag the first time you push from a new branch.

Change your git config using:

BASH

$ git config --global push.autoSetupRemote true

Proxy

If the network you are connected to uses a proxy, there is a chance that your last command failed with “Could not resolve hostname” as the error message. To solve this issue, you need to tell Git about the proxy:

BASH

$ git config --global http.proxy http://user:password@proxy.url
$ git config --global https.proxy https://user:password@proxy.url

When you connect to another network that doesn’t use a proxy, you will need to tell Git to disable the proxy using:

BASH

$ git config --global --unset http.proxy
$ git config --global --unset https.proxy

Password Managers

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:

A diagram showing how "git push origin" will push changes from the local repository to the remote, making the remote repository an exact copy of the local repository.

The ‘-u’ Flag

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 push command can be used without any arguments. To do this, simply use git push -u origin main once the remote has been set up.

Here, we are telling Git to push the branch to the origin (GitHub) repositories main branch.

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

BASH

$ git pull

OUTPUT

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.

GitHub GUI

Browse to your weather repository on GitHub. Under the Code tab, 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.

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. If you had, what do you think would have happened when you tried to link your local and remote repositories?

In this case, we’d see a merge conflict due to unrelated histories. When GitHub creates a README.md file, it performs a commit in the remote repository. When you try to pull the remote repository to your local repository, Git detects that they have histories that do not share a common origin and refuses to merge.

BASH

$ git pull origin main

OUTPUT

warning: no common commits
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/mo-eormerod/weather
 * branch            main     -> FETCH_HEAD
 * [new branch]      main     -> origin/main
fatal: refusing to merge unrelated histories

You can force git to merge the two repositories with the option --allow-unrelated-histories. Be careful when you use this option and carefully examine the contents of local and remote repositories before merging.

BASH

$ git pull --allow-unrelated-histories origin main

OUTPUT

From https://github.com/mo-eormerod/weather
 * branch            main     -> FETCH_HEAD
Merge made by the 'recursive' strategy.
README.md | 1 +
1 file changed, 1 insertion(+)
create mode 100644 README.md

Key Points

  • A local Git repository can be connected to one or more remote repositories.
  • Use the SSH protocol to connect to remote repositories.
  • 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 Exploring GitHub


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

Estimated time: 20 minutes

Overview

Questions

  • How do I search a repository?

Objectives

  • Navigate around the GitHub interface.

GitHub has a lot of features so we’ll take some time to learn how to navigate the interface. Your instructor will guide you through navigating each section.

The GitHub home page showing repositories on the left, and news in the centre.

This is the GitHub homepage. On the left you can quickly navigate to a repository or use the green New button to create a new repository. If you are in an organisation that requires single sign on to see organisational repositories you will be prompted with a large green button at the top of this page to sign in.

To access your settings click on your round profile icon in the top right hand corner and select the Settings option.

1 Exploring the interface for a repository

The following image shows an example repository. In fact it is the repository containing the material for this lesson. Link to the git-novice repository.

A screenshot of the GitHub repository for the git-novice lesson.

Let’s break it down into parts:

The GitHub nav at the top of a repository.

When you navigate to a repository the top nav will display the organisation the repository belongs to, swcarpentry, and the name of the repository, git-novice, in the top left. In the top right you have access to GitHubs powerful search, buttons to open Issues and Pull requests (which will be explained later), and the notifications and profile icon on the far right.

The GitHub navigation tabs for a repository.

This next section displays tabs to navigate around your repository and various buttons which allow you to watch for changes to a repository and star a project. Starring a repo makes it easier to find from your homepage and helps repository owners gauge usage of their code.

A screenshot of the lower section of the repository interface.

This section displays the code contained on the default branch, in this case main. It also displays useful stats about the repository on the right. The green <> Code button lets you check out a local copy of the repository.

Key Points

  • Quickly navigate to a repository in your browser using the url pattern: https://github.com/<username or organisation>/<repo name>

Content from Exploring History on GitHub


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

Estimated time: 10 minutes

Overview

Questions

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

Objectives

  • Recognise and use Git commit unique identifers (SHAs).
  • Compare various versions of tracked files.

Viewing the History of a Repository on GitHub


In an earlier episode, we used git log on the command line in our local repository to show the commits to our branch.

We can also see the commits to our branch on GitHub. But first we need to push our local branch to GitHub.

Make sure you are on the forecast branch:

BASH

$ git switch forecast

Now we can push our local branch to GitHub:

BASH

$ git push

Navigate to your weather GitHub repo:

A screenshot of the main branch of weather repository on GitHub.

Select the forecast branch from the branch drop down box labelled main:

A screenshot of the main branch of weather repository on GitHub, showing the branch drop down box.

Click on Commits:

A screenshot of the forecast branch of weather repository on GitHub, showing how to navigate to the commits.

This commits page shows all the commits on your branch:

A screenshot of the commit on the forecast branch of the weather repository on GitHub.

The Git commit unique identifiers (SHAs) here on GitHub match with those shown after running git log on the command line in your local branch.

Viewing Differences Between Commits


In an earlier episode, we used git diff on the command line in our local repository to show the differences between two commits on our branch.

We can also see these differences on GitHub.

In a new tab, navigate to your weather GitHub repo then add compare to the end of the URL. The URL should follow https://github.com/<your-user-name>/weather/compare:

A screenshot of the compare page for the weather repository on GitHub.

Select one of the Git commit SHAs from the Commits page and add it to the first drop down box labelled base: main.

Then select a second Git commit SHA from the Commits page and add it to the second drop down box labelled compare: main.

The resulting page will show the differences between the two Git commit SHAs:

A screenshot showing the differences between two Git commit SHAs from the weather repository on GitHub.`

Key Points

  • The Commits page displays the history for the specified branch.
  • Adding compare to the end of the repository URL displays differences between commits.

Content from Pull Requests


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

Estimated time: 45 minutes

Overview

Questions

  • What are pull requests for?
  • How can I make a pull request?

Objectives

  • Make a pull request and describe what they are useful for

Pull requests are a great way to collaborate with others using GitHub. Instead of making changes directly to a repository you can suggest changes to a repository using a pull request.

Pull requests are where your changes go through the vital steps of code and science review. Some of these code and science checks can be completely automated using pull requests (PRs). This helps speed up the review process and reduce the chance of human error when checking new code.

Creating a Pull Request


In the previous episodes we developed our changes on the forecast branch. Let’s use a PR to merge these changes back into the main branch.

Navigate to your weather GitHub repo. You should see a notification appear with the text forecast had recent pushes.

A screenshot of the weather repo showing the notification prompting us to Compare & pull request for the forecast branch.

Click on the green Compare & pull request button.

A screenshot of the weather repo showing the creation of a pull request for the forecast branch changes.

This page lets us create a new pull request from the forecast branch. The title has been autofilled with the message of the last commit. You can see all the commits on the branch at the bottom of this page.

Make sure the title and description are clear. Then press the green Create pull request button.

Draft Pull Requests

If your changes are not ready for review yet you can mark the pull request as a draft:

A screenshot showing the dropdown to swap from a normal pull request to a creating a draft pull request.

Draft pull requests can’t be merged and code reviewers aren’t automatically assigned.

A screenshot showing an open pull request on the weather repo.

Notice we’ve now moved to the Pull Requests tab. This is PR #1 and underneath the title we see:

wants to merge 4 commits into main from forecast

If you need to change the title or the branch you’re merging into, in this case main, click on the edit button to the far right of the title.

The PR has four tabs below the title section:

  • Conversation is where code and science reviews occur
  • Commits shows all the commits we want to merge
  • Checks shows the output from any automated code and science checks
  • Files Changed shows a diff (difference) between the branch with your changes, forecast, and the target branch, main.

At this point you should use the diff in the Files changed tab to check your changes.

Rulesets


GitHub Rulesets control how people can interact with your repository.

When we opened our first PR we were prompted to Require approval from specific reviewers before merging. Click on the Add rule button.

This page lets us create a rule preventing anyone from committing directly into the main branch. All repositories should have some form of protection using these rulesets. To add a rule to protect the main branch:

  1. Enter the Ruleset Name main
  2. Change the Enforcement status to Active
  3. Scroll down to Target branches. Click Add target and select Default branch (which in our weather repo is main).
  4. Scroll down to Rules. Tick the Require a pull request before merging option.
  5. At the bottom of the page click the green Create button.

Now even if you commit to main locally you will not be able to push those changes to GitHub. To add changes you MUST open a PR and go through code and science review.

A screenshot showing the creation of a rule to protect the main branch in the repository settings, rulesets page.

Private Personal Repos

Rulesets cannot be created on private repos in your personal space unless you have a paid GitHub plan.

Merging a Pull Request


Navigate back to your PR. To merge the PR click on the dropdown, and select Squash and merge. Squashing before merging will combine all the commits on your branch and ‘squash’ them into a single new commit on the target branch, in this case main. This helps keep the commit history of the main branch tidy and linear1.

A screenshot showing the dropdown to swap from a normal merge to a squash merge.

Once you’ve selected the squash option click on the green Squash and merge button. Edit the commit title so that the PR number is at the start of the message. For instance:

OUTPUT

Add in a forecast file (#1)

Would be changed to:

OUTPUT

#1 Add in a forecast file

This makes it easier to navigate to the PR for a change when you’re on the GitHub repositories code view. Change the description if necessary. Then click on Confirm squash and merge.

A screenshot showing a closed pull request on the weather repository.

The PR is now successfully merged into the main branch. We can safely delete the forecast branch from the GitHub repo. Click on the Delete branch button.

Updating your Local Repo


The new forecast.md file is currently only on the main branch in GitHub. We should pull the changes down to our local copy. Switch to the main branch:

BASH

$ git switch main

Pull down the changes from GitHub:

BASH

$ git pull

BASH

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 1), reused 2 (delta 1), pack-reused 0 (from 0)
Unpacking objects: 100% (3/3), 1.01 KiB | 173.00 KiB/s, done.
From github.com:mo-eormerod/weather
   41c775b..49c845c  main       -> origin/main
Updating 41c775b..49c845c
Fast-forward
 .gitignore  | 2 ++
 forecast.md | 9 +++++++++
 2 files changed, 11 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 forecast.md

git pull and GitHub’s Pull Requests are not the same. GitHub Pull Requests are where we performed code and science review, then merged our feature branch changes into the main branch. git pull is fetching changes to the remote branch on GitHub and merging them into your local copy.

You may need to tell Git what to do

If you see the below in your output, Git is asking what it should do.

OUTPUT

hint: You have divergent branches and need to specify how to reconcile them.
hint: You can do so by running one of the following commands sometime before
hint: your next pull:
hint:
hint:   git config pull.rebase false  # merge (the default strategy)
hint:   git config pull.rebase true   # rebase
hint:   git config pull.ff only       # fast-forward only
hint:
hint: You can replace "git config" with "git config --global" to set a default
hint: preference for all repositories. You can also pass --rebase, --no-rebase,
hint: or --ff-only on the command line to override the configured default per
hint: invocation.

In newer versions of Git it gives you the option of specifying different behaviours when a pull would merge divergent branches. The Git & GitHub Working Practices training will help you decide which option is best for your teams repositories. For now we will use the fast-forward only strategy. To use this strategy run the following command to select it as the default thing Git should do.

BASH

$ git config pull.ff only

Then attempt the pull again.

BASH

$ git pull

How do I know there are Changes to Pull?

git pull actually runs two commands:

BASH

$ git fetch
$ git merge

The git fetch command fetches any changes on the GitHub remote. Then git merge merges those changes into your local branch.

If you’re not sure if there are changes to pull; or you’re not sure you want to merge the changes right away run git fetch and examine the output before running git pull.

Example git fetch output showing changes on the remote main branch being fetched:

OUTPUT

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 1), reused 2 (delta 1), pack-reused 0 (from 0)
Unpacking objects: 100% (3/3), 1010 bytes | 144.00 KiB/s, done.
From github.com:mo-ormerod/weather
   49c845c..e4bdab8  main       -> origin/main

Cleaning up your Local Branches

We deleted our forecast dev branch from GitHub but we still have a local copy. Let’s tidy up by deleting it. To see all our branches including remote GitHub branches run:

BASH

$ git branch -avv

OUTPUT

  forecast                13e0329 [origin/forecast] Ignore png files and the data folder
* main                    d1da035 [origin/main] #1 Add in a forecast file
  remotes/origin/forecast 13e0329 Ignore png files and the data folder
  remotes/origin/main     d1da035 #1 Add in a forecast file

The first two branches are our local branches, the last two are the GitHub remotes. To remove references to remote branches that have been deleted on GitHub run:

BASH

$ git remote prune origin
Pruning origin
URL: git@github.com:mo-eormerod/weather.git
 * [pruned] origin/forecast

Running git branch -avv again now shows:

  forecast            13e0329 [origin/forecast: gone] Ignore png files and the data folder
* main                d1da035 [origin/main] #1 Add in a forecast file
  remotes/origin/main d1da035 #1 Add in a forecast file

You can see the remote reference for the forecast branch has been removed. The second line with the local forecast branch now has gone in the brackets referencing the remote branch.

To delete our local branch run:

BASH

$ git branch -D forecast

Running git branch -avv again now shows:

OUTPUT

* main                d1da035 [origin/main] #1 Add in a forecast file
  remotes/origin/main d1da035 #1 Add in a forecast file

You’ve now successfully merged and tidied up after your first pull request. Remember when making changes create a new branch and open a PR, NEVER commit to the main branch.

Automatically Prune Deleted Remote Branches

If you set the following Git configuration:

BASH

$ git config --global fetch.prune true

Git will automatically prune the links to remote branches that were deleted on GitHub when you run git fetch or git pull.

Adding in a seasonal-forecast.md file

Try adding in a seasonal forecast using the following steps:

  1. Create a new branch with an appropriate name and switch to it
  2. Create the seasonal-forecast.md file
  3. Add and commit the new file
  4. Push the changes to GitHub
  5. Open a PR on GitHub
  6. Merge the PR, delete the branch on GitHub
  7. Pull down the changes to your local copy
  8. Tidy up your branches
  1. Create a new branch with an appropriate name and switch to it

BASH

$ git switch -c add-seasonal-forecast

OUTPUT

Switched to a new branch 'add-seasonal-forecast'
  1. Create the seasonal-forecast.md file

BASH

$ nano seasonal-forecast.md
$ cat seasonal-forecast.md

OUTPUT

# Seasonal Forecast

- Winter is wet
- Summer is hot
  1. Add and commit the new file

BASH

$ git add seasonal-forecast.md
$ git commit -m "Add in a seasonal-forecast.md file"

OUTPUT

[add-seasonal-forecast aeaf804] Add in a seasonal-forecast.md file
 1 file changed, 4 insertions(+)
 create mode 100644 seasonal-forecast.md
  1. Push the changes to GitHub

BASH

$ git push

OUTPUT

Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 326 bytes | 163.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
remote:
remote: Create a pull request for 'add-seasonal-forecast' on GitHub by visiting:
remote:      https://github.com/mo-ormerod/weather/pull/new/add-seasonal-forecast
remote:
To github.com:mo-ormerod/weather.git
 * [new branch]      add-seasonal-forecast -> add-seasonal-forecast
branch 'add-seasonal-forecast' set up to track 'origin/add-seasonal-forecast'.
  1. Open a PR as shown in this very episode!
  2. Merge the PR, delete the branch on GitHub
  3. Pull down the changes to your local copy

Switch to main:

BASH

$ git switch main

If you want to check if there are changes to pull:

BASH

$ git fetch

OUTPUT

remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 1), reused 2 (delta 1), pack-reused 0 (from 0)
Unpacking objects: 100% (3/3), 1010 bytes | 144.00 KiB/s, done.
From github.com:mo-ormerod/weather
   49c845c..e4bdab8  main       -> origin/main

Then merge the changes:

BASH

$ git pull

OUTPUT

Updating 49c845c..e4bdab8
Fast-forward
 seasonal-forecast.md | 4 +++
 1 file changed, 4 insertions(+)
 create mode 100644 seasonal-forecast.md
  1. Tidy up your branches

BASH

$ git remote prune origin

OUTPUT

Pruning origin
URL: git@github.com:mo-ormerod/weather.git
 * [pruned] origin/add-seasonal-forecast

BASH

$ git branch -D add-seasonal-forecast

OUTPUT

Deleted branch add-seasonal-forecast (was aeaf804).

Key Points

  • A pull request (PR) is where your changes go through code and science review.
  • PRs can contain automated checks to help speed up the review process and avoid human error.
  • The PR will automatically create an easy to read diff (difference) of the changes for the review (in the Files changed tab).
  • Squashing and merging takes all the commits in your PR and ‘squashes’ them into a single new commit on the target branch.
  • git fetch fetches changes to the GitHub remote.
  • git pull pulls and merges changes to the GitHub remote into your local copy.
  • git branch -avv displays all your local branches including references to any remote branches.
  • git remote prune origin removes references to remote branches that have been deleted on GitHub.

Content from Configuring GitHub


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

Estimated time: 15 minutes

Overview

Questions

  • How do I edit my GitHub profile?
  • How do I change my notification preferences?
  • How do I change my organisation membership visibility, and team memberships?

Objectives

  • Configure your GitHub profile and settings.

In this section we will look at configuring some optional GitHub settings on both a GitHub wide and repository level.

Profile Settings


You access your profile settings by navigating to: https://github.com/settings/profile

Working down the page:

  1. Set your preferred name. This helps collaborators find you on GitHub.
  2. Set a public email, this also helps collaborators find your profile. To keep your email address private click on email settings, then tick the Keep my email addresses private checkbox.
  3. Set your pronouns.
  4. If you have a professional website you can add a link to the URL section.
  5. If you have an ORCID you can link your GitHub profile to your ID.
  6. If you would like to display your organisational affiliation add @<organisation-name> to the Company section.

You can also set a profile picture on this page. Click on the green Update profile button when you have finished making changes.

A screenshot of a users GitHub profile.

You can also make profile changes directly from your profile by clicking on the Edit profile button.

Configuring Notifications


To configure general notification settings navigate to: https://github.com/settings/notifications

Here you can choose a default email for notifications, and set up Custom routing. Custom routing allows you to specify different emails for each organisation you are a member of.

In the Subscriptions section you can decide whether to receive notifications via GitHub, email, or both.

Repository Notifications

You can customise notifications on a repository level. Since you created the weather repository you are automatically watching All Activity. Click on the Unwatch dropdown to change your notification settings.

A screenshot of the GitHub weather repo with the Unwatch dropdown expanded.

The same dropdown will display Watch on repositories that do not belong to you.

Organisation Membership


If you are a member of an organisation you can make your membership of the organisation public or private by navigating to: https://github.com/orgs/<organisation-name>/people

Search for your name and click on the right hand dropdown to change your organisation visibility.

A screenshot of the GitHub organisation People settings for an organisation showing how to change your organisation visibility.

The default visibility setting will depend on your organisation. If you set the visibility to public your membership will appear on your profile, https://github.com/<your-username>/, near the bottom left of the screen.

Teams Membership


One across from the People settings are the Teams settings: https://github.com/orgs/<organisation-name>/teams. You can leave, request to join, or if you are an admin add members to your GitHub team here. Teams let you manage access to repositories for a group of people all at once. Some organisations restrict the creation of GitHub teams to central admins.

Key Points

Content from End


Last updated on 2025-01-07 | Edit this page

Estimated time: 0 minutes

This marks the end of the GitHub section and the workshop. Please remember to fill out your post-workshop feedback. This feedback is vital for us to keep improving the lesson for other learners.

Where to next?


The Git & GitHub Working Practices lesson teaches you how to work collaboratively with others using Git and GitHub. It explores more complex workflows and topics, building on from this lesson.

There are also a number of optional episodes after this page which focus on open science and code which you can read in your own time.

You can revisit this training anytime. Useful page links:

You can keep your weather repositories around to practice with for as long as you like and when you are ready to delete them use the instructions at the end of this page.

Summary


You’ve now created a repository both locally on your computer and remotely on GitHub. You’ve developed changes on a feature branch, reviewed the changes on GitHub and merged them into main. The diagram below outlines the workflow you used during the course:

A sequence diagram showing the workflow we used during the lesson.

A summary page outlining the steps we’ve taken to create a new repository locally and connect it to a GitHub remote can be found in the extra Quick Start Repository Guide.

Deleting a Repository


Make sure you are certain you want to delete the repository. If you delete both the local and GitHub repositories you won’t be able to recover your files!

Deleting a Local Repository

BASH

$ cd ~/Desktop
$ rm -rf weather

Deleting a GitHub Repository

  1. Navigate to https://github.com/<your-username>/weather/settings
  2. Scroll down to the last setting in the Danger Zone
  3. Click on Delete this repository

You will be asked to confirm twice that you understand the effects of deleting the repository. You will also be asked to type out <your-username>/weather to confirm the deletion and you may have to confirm the deletion using MFA or your passkey.

Content from Open Science


Last updated on 2024-12-19 | 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.

Check your Organisation’s Policy

Your organisation most likely has policies governing their intellectual property. The guidelines below are general. You should consult your organisational policy on publishing and open source before making any decisions.

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 2024-12-03 | 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.

Check your Organisation’s Policy

Your organisation most likely has policies governing their intellectual property. The guidelines below are general. You should consult your organisational policy on licensing and open source before making any decisions.

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 the derived software also open under the GPL license if they decide to share it; 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 2024-12-03 | 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:

Greg Wilson: "Software Carpentry: Lessons Learned". F1000Research,
2016, 3:62 (doi: 10.12688/f1000research.3-62.v2).

@online{wilson-software-carpentry-2016,
  author      = {Greg Wilson},
  title       = {Software Carpentry: Lessons Learned},
  version     = {2},
  date        = {2016-01-28},
  url         = {http://f1000research.com/articles/3-62/v2},
  doi         = {10.12688/f1000research.3-62.v2}
}

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 2024-12-03 | 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.

After choosing a license, another 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.

Content from Using Git from RStudio


Last updated on 2024-12-19 | 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.

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 weather 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

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”:

RStudio window showing the "Create Project From Existing Directory" dialog. In the dialog, the project working directory has been set to "~/Desktop/weather"

Ta-da! We have created a new project in RStudio within the existing weather 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 Hummus:

RStudio window demonstrating the use of the editor panel to modify the "pluto.txt" file

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 the "Commit..." option selected

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”:

RStudio screenshow showing the "Review Changes" dialog. The top left panel shows the list of files that can be included or excluded from the commit. The top right panel is for writing a commit message. The bottom panel shows information about the currently selected file in the top left panel.

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 the "History" option 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 screenshot showing the "Review Changes" dialog after pressing the "History" button. The top panel lists the commits in the repository, similar to git log. The bottom panel shows the changes included in the commit that has been selected in the top panel.

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.

Challenge

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

This can be done in Rstudio:

R

dir.create("./graphs")

Then open up the .gitignore file from the right-hand panel of Rstudio and add graphs/ 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.