diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000000..e69de29bb2 diff --git a/01-basics.html b/01-basics.html new file mode 100644 index 0000000000..6a3e7493ca --- /dev/null +++ b/01-basics.html @@ -0,0 +1,614 @@ + +Version Control with Git: Automated Version Control +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Automated Version Control

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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

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.

+
+
+ +
+
+

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.

+
+
+
+
+
+ +
+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/02-setup.html b/02-setup.html new file mode 100644 index 0000000000..03153ebad0 --- /dev/null +++ b/02-setup.html @@ -0,0 +1,757 @@ + +Version Control with Git: Setting Up Git +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Setting Up Git

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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

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. So here is +how Alfredo sets up his new laptop:

+
+

BASH +

+
$ git config --global user.name "Alfredo Linguini"
+$ git config --global user.email "a.linguini@ratatouille.fr"
+
+

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

+

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

+
+
+ +
+
+

Keeping your email private

+
+

If you elect to use a private email address with GitHub, then use +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.

+
+
+
+
+
+ +
+
+

Line Endings

+
+

As with other keys, when you hit Enter or or +on Macs, Return on your keyboard, your computer encodes this +input as a character. Different operating systems use different +character(s) to represent the end of a line. (You may also hear these +referred to as newlines or line breaks.) Because Git uses these +characters to compare files, it may cause unexpected issues when editing +a file on different machines. Though it is beyond the scope of this +lesson, you can read more about this issue in +the Pro Git book.

+

You can change the way Git recognizes and encodes line endings using +the core.autocrlf command to git config. The +following settings are recommended:

+

On macOS and Linux:

+
+

BASH +

+
$ git config --global core.autocrlf input
+
+

And on Windows:

+
+

BASH +

+
$ git config --global core.autocrlf true
+
+
+
+
+

Alfredo also has to set his favorite text editor, following this +table:

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

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

+
+
+ +
+
+

Exiting Vim

+
+

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

+
+
+
+

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

+
+

BASH +

+
$ git config --global init.defaultBranch main
+
+
+
+ +
+
+

Default Git branch naming

+
+

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

+

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

+

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

+
+
+
+

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.

+

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. Remember, +since typos in the config file will cause issues, it’s safer to view the +configuration with:

+
+

BASH +

+
$ git config --list
+
+

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

+
+
+ +
+
+

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

+
+

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

+
+

BASH +

+
$ git config -h
+$ git config --help
+
+

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

+

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

+
+

BASH +

+
$ git help
+
+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Use git config with the --global option to +configure a user name, email address, editor, and other preferences once +per machine.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/03-create.html b/03-create.html new file mode 100644 index 0000000000..51c3e482af --- /dev/null +++ b/03-create.html @@ -0,0 +1,710 @@ + +Version Control with Git: Creating a Repository +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Creating a Repository

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

+
  • Where does Git store information?
  • +
+
+
+
+
+
+

Objectives

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

Once Git is configured, we can start using it.

+

We will help Alfredo with his new project, create a repository with +all his recipes.

+

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 recipes
+$ cd recipes
+
+

Then we tell Git to make recipes 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 +recipes repository, whether subdirectories are present from +the beginning or added later. Also, note that the creation of the +recipes 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 recipes +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.

+

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

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

+
+
+ +
+
+

Places to Create Git Repositories

+
+

Along with tracking information about recipes (the project we have +already created), Alfredo would also like to track information about +desserts specifically. Alfredo creates a desserts project +inside his recipes project with the following sequence of +commands:

+
+

BASH +

+
$ cd ~/Desktop    # return to Desktop directory
+$ cd recipes      # go into recipes directory, which is already a Git repository
+$ ls -a           # ensure the .git subdirectory is still present in the recipes directory
+$ mkdir desserts # make a sub-directory recipes/desserts
+$ cd desserts    # go into desserts subdirectory
+$ git init        # make the desserts 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 +desserts subdirectory, required for tracking files stored +in the desserts subdirectory?

+
+
+
+
+
+ +
+
+

No. Alfredo does not need to make the desserts +subdirectory a Git repository because the recipes +repository will track all files, sub-directories, and subdirectory files +under the recipes directory. Thus, in order to track all +information about desserts, Alfredo only needed to add the +desserts subdirectory to the recipes +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

+
+

Jimmy explains to Alfredo how a nested repository is redundant and +may cause confusion down the road. Alfredo would like to go back to a +single git repository. How can Alfredo undo his last +git init in the desserts 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, Alfredo can remove the +.git folder in the desserts subdirectory by running the +following command from inside the recipes directory:

+
+

BASH +

+
$ rm -rf desserts/.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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/04-changes.html b/04-changes.html new file mode 100644 index 0000000000..393ca71045 --- /dev/null +++ b/04-changes.html @@ -0,0 +1,1377 @@ + +Version Control with Git: Tracking Changes +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Tracking Changes

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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 in the right directory. You should +be in the recipes directory.

+
+

BASH +

+
$ cd ~/Desktop/recipes
+
+

Let’s create a file called guacamole.md that contains +the basic structure to have a recipe. 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 guacamole.md
+
+

Type the text below into the guacamole.md file:

+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

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 +

+
guacamole.md
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

If we check the status of our project again, Git tells us that it’s +noticed the new file:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Untracked files:
+   (use "git add <file>..." to include in what will be committed)
+
+	guacamole.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 guacamole.md
+
+

and then check that the right thing happened:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Changes to be committed:
+  (use "git rm --cached <file>..." to unstage)
+
+	new file:   guacamole.md
+
+
+

Git now knows that it’s supposed to keep track of +guacamole.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 template for recipe"
+
+
+

OUTPUT +

+
[main (root-commit) f22b25e] Create a template for recipe
+ 1 file changed, 1 insertion(+)
+ create mode 100644 guacamole.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.

+

If we run git status now:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

it tells us everything is up to date. 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 f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+

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.

+
+
+ +
+
+

Where Are My Changes?

+
+

If we run ls at this point, we will still see just one +file called guacamole.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 Alfredo adds 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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lemon
+* salt
+## Instructions
+
+

When we run git status now, it tells us that a file it +already knows about has been modified:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git restore <file>..." to discard changes in working directory)
+
+	modified:   guacamole.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/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lemon
++* salt
+ ## Instructions
+
+

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. +
  3. The second line tells exactly which versions of the file Git is +comparing; df0654a and 315bf3a are unique +computer-generated labels for those versions.
  4. +
  5. The third and fourth lines once again show the name of the file +being changed.
  6. +
  7. 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.
  8. +

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

+
+

BASH +

+
$ git commit -m "Add basic guacamole's ingredients"
+$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ git commit -m "Add basic guacamole's ingredients"
+
+
+

OUTPUT +

+
[main 34961b1] Add basic guacamole's ingredient
+ 1 file changed, 3 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

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 recipe +by changing ‘lemon’ to ‘lime’:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole.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/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole to the traditional recipe"
+
+
+

OUTPUT +

+
[main 005937f] Modify guacamole to the traditional recipe
+ 1 file changed, 1 insertion(+)
+
+

check our status:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git log
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+    Modify guacamole to the traditional recipe
+
+commit 34961b159c27df3b475cfe4415d94a6d1fcd064d
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Add basic guacamole's ingredients
+
+commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+
+
+ +
+
+

Word-based diffing

+
+

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

+
+
+
+
+
+ +
+
+

Paging the Log

+
+

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

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

Limit Log Size

+
+

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

+
+

BASH +

+
$ git log -1
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+   Modify guacamole to the traditional recipe
+
+

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

+
+

BASH +

+
$ git log --oneline
+
+
+

OUTPUT +

+
005937f (HEAD -> main) Modify guacamole to the traditional recipe
+34961b1 Add basic guacamole's ingredients
+f22b25e Create a template for recipe
+
+

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

+
+

BASH +

+
$ git log --oneline --graph
+
+
+

OUTPUT +

+
* 005937f (HEAD -> main) Modify guacamole to the traditional recipe
+* 34961b1 Add basic guacamole's ingredients
+* f22b25e Create a template for recipe
+
+
+
+
+
+
+ +
+
+

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:
  2. +
+

BASH +

+
$ mkdir cakes
+$ git status
+$ git add cakes
+$ git status
+
+

Note, our newly created empty directory cakes 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:
  2. +
+

BASH +

+
git add <directory-with-files>
+
+

Try it for yourself:

+
+

BASH +

+
$ touch cakes/brownie cakes/lemon_drizzle
+$ git status
+$ git add cakes
+$ git status
+
+

Before moving on, we will commit these changes.

+
+

BASH +

+
$ git commit -m "Add some initial cakes"
+
+
+
+
+

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 guacamole.md?

+
  1. “Changes”
  2. +
  3. “Changed lemon for lime”
  4. +
  5. “Guacamole modified to the traditional recipe”
  6. +
+
+
+
+
+ +
+
+

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. +
  3. +

    BASH +

    +
       $ git init myfile.txt
    +   $ git commit -m "my recent changes"
    +
  4. +
  5. +

    BASH +

    +
       $ git add myfile.txt
    +   $ git commit -m "my recent changes"
    +
  6. +
  7. +

    BASH +

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

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 guacamole.md noting the rough price of +the ingredients.
  2. +
  3. Create a new file groceries.md with a list of products +and their prices for different markets.
  4. +
  5. Add changes from both files to the staging area, and commit those +changes.
  6. +
+
+
+
+
+ +
+
+

First we make our changes to the guacamole.md and +groceries.md files:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado (1.35)
+* lime (0.64)
+* salt (2)
+
+
+

BASH +

+
$ nano groceries.md
+$ cat groceries.md
+
+
+

OUTPUT +

+
# Market A
+* avocado: 1.35 per unit.
+* lime: 0.64 per unit
+* salt: 2 per kg
+
+

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

+
+

BASH +

+
$ git add guacamole.md groceries.md
+
+

Or with multiple commands:

+
+

BASH +

+
$ git add guacamole.md
+$ git add groceries.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 "Write prices for ingredients and their source"
+
+
+

OUTPUT +

+
[main cc127c2]
+ Write prices for ingredients and their source
+ 2 files changed, 7 insertions(+)
+ create mode 100644 groceries.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 recipes folder:

+
+

BASH +

+
$ cd ..
+
+

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

+
+

BASH +

+
$ mkdir bio
+$ cd bio
+
+

Initialise git:

+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/05-history.html b/05-history.html new file mode 100644 index 0000000000..aebcfd2d08 --- /dev/null +++ b/05-history.html @@ -0,0 +1,1103 @@ + +Version Control with Git: Exploring History +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Exploring History

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

We’ve been adding small changes at a time to +guacamole.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 guacamole.md, adding yet another +line.

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+An ill-considered change
+
+

Now, let’s see what we get.

+
+

BASH +

+
$ git diff HEAD guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index b36abfd..0848c8d 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -4,3 +4,4 @@
+ * lime
+ * salt
+ ## Instructions
++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 guacamole.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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
+
+

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

+
+

BASH +

+
$ git show HEAD~2 guacamole.md
+
+
+

OUTPUT +

+
commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Create a template for recipe
+
+diff --git a/guacamole.md b/guacamole.md
+new file mode 100644
+index 0000000..df0654a
+--- /dev/null
++++ b/guacamole.md
+@@ -0,0 +1,3 @@
++# Guacamole
++## Ingredients
++## Instructions
+
+

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 was given the ID +f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try +this:

+
+

BASH +

+
$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++An ill-considered change
+
+

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 guacamole.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 main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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. If +we want to go back even further, we can use a commit identifier instead, +using -s option:

+
+

BASH +

+
$ git restore -s f22b25e guacamole.md
+
+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

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

+
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

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

+
+
+ +
+
+

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. +
  3. $ git restore data_cruncher.py

  4. +
  5. $ git restore -s HEAD~1 data_cruncher.py

  6. +
  7. $ git restore -s <unique ID of last commit> data_cruncher.py

  8. +
  9. Both 2 and 4

  10. +
+
+
+
+
+ +
+
+

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

+
+

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

+

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

+

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

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

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

  4. +
  5. git revert [commit ID]

  6. +
  7. Type in the new commit message.

  8. +
  9. Save and close.

  10. +
+
+
+
+
+ +
+
+

The command git log lists project history with commit +IDs.

+

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

+
+
+
+
+
+
+ +
+
+

Understanding Workflow and History

+
+

What is the output of the last command in

+
+

BASH +

+
$ cd recipes
+$ echo "I like tomatoes, therefore I like ketchup" > ketchup.md
+$ git add ketchup.md
+$ echo "ketchup enhances pasta dishes" >> ketchup.md
+$ git commit -m "My opinions about the red sauce"
+$ git restore ketchup.md
+$ cat ketchup.md # this will print the content of ketchup.md on screen
+
+
  1. +

    OUTPUT +

    +
      ketchup enhances pasta dishes
    +
  2. +
  3. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +
  4. +
  5. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +  ketchup enhances pasta dishes
    +
  6. +
  7. +

    OUTPUT +

    +
      Error because you have changed ketchup.md without committing the changes
    +
  8. +
+
+
+
+
+ +
+
+

The answer is 2.

+

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

+

So, when git commit -m "My opinions about the red sauce" +is executed, the version of ketchup.md committed to the +repository is the one from the staging area and has only one line.

+

At this time, the working copy still has the second line (and

+

git status will show that the file is modified). +However, git restore ketchup.md replaces the working copy +with the most recently committed version of ketchup.md. So, +cat ketchup.md will output

+
+

OUTPUT +

+
I like tomatoes, therefore I like ketchup
+
+
+
+
+
+
+
+ +
+
+

Checking Understanding of +git diff +

+
+

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

+
+
+
+
+
+ +
+
+

Getting Rid of Staged Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

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

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

+

Using the command git restore guacamole.md now does not +give an error, but it does not restore the file either. Git helpfully +tells us that we need to use git restore --staged first to +unstage the file:

+
+

BASH +

+
$ git restore --staged guacamole.md
+
+

Now, git status gives us:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git git restore <file>..." to discard changes in working directory)
+        modified:   guacamole.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

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

+
+

BASH +

+
$ git restore guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+
+
+
+
+
+
+ +
+
+

Explore and Summarize Histories

+
+

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

+

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

+
+

BASH +

+
$ git log guacamole.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 guacamole.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 diff displays differences between commits.
  • +
  • +git restore recovers old versions of files.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/06-ignore.html b/06-ignore.html new file mode 100644 index 0000000000..ab2908bade --- /dev/null +++ b/06-ignore.html @@ -0,0 +1,924 @@ + +Version Control with Git: Ignoring Things +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Ignoring Things

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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 receipts
+$ touch a.png b.png c.png receipts/a.jpg receipts/b.jpg
+
+

and see what Git says:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	a.png
+	b.png
+	c.png
+	receipts/
+
+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
+receipts/
+
+

These patterns tell Git to ignore any file whose name ends in +.png and everything in the receipts 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 main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	.gitignore
+
+nothing added to commit but untracked files present (use "git add" to track)
+
+

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

+
+

BASH +

+
$ git add .gitignore
+$ git commit -m "Ignore png files and the receipts folder."
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git add a.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 main
+Ignored files:
+ (use "git add -f <file>..." to include in what will be committed)
+
+        a.png
+        b.png
+        c.png
+        receipts/
+
+nothing to commit, working tree clean
+
+
+
+ +
+
+

Ignoring Nested Files

+
+

Given a directory structure that looks like:

+
+

BASH +

+
receipts/data
+receipts/plots
+
+

How would you ignore only receipts/plots and not +receipts/data?

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/plots/
+
+

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

+

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 also that because you’ve previously committed .png +files in this lesson 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 +

+
receipts/data
+receipts/images
+receipts/plots
+receipts/analysis
+
+

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

+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/*               # ignore everything in receipts folder
+!receipts/data/          # do not ignore receipts/data/ contents
+
+
+
+
+
+
+
+ +
+
+

Ignoring all data Files in a Directory

+
+

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

+
+

BASH +

+
receipts/data/market_position/gps/a.dat
+receipts/data/market_position/gps/b.dat
+receipts/data/market_position/gps/c.dat
+receipts/data/market_position/gps/info.txt
+receipts/plots
+
+

What’s the shortest .gitignore rule you could write to +ignore all .dat files in +result/data/market_position/gps? Do not ignore the +info.txt.

+
+
+
+
+
+ +
+
+

Appending receipts/data/market_position/gps/*.dat will +match every file in receipts/data/market_position/gps that +ends with .dat. The file +receipts/data/market_position/gps/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. +
  3. Test your “ignore pattern” by creating some dummy files of the +form log_01, etc.

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

  6. +
  7. 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.

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

Key Points

+
+
  • The .gitignore file tells Git what files to +ignore.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/07-github.html b/07-github.html new file mode 100644 index 0000000000..be7999f2f6 --- /dev/null +++ b/07-github.html @@ -0,0 +1,1126 @@ + +Version Control with Git: Remotes in GitHub +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Remotes in GitHub

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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 start by sharing the changes we’ve made to our current project +with the world. To this end we are going to create a remote +repository that will be linked to our local repository.

+

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 +recipes:

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

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

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

+
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 recipes
+$ cd recipes
+$ git init
+
+

If you remember back to the earlier episode where we added and committed our +earlier work on guacamole.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 "recipes" 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 +guacamole.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.

+
+
+
+
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

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

+
+

BASH +

+
$ git remote add origin git@github.com:alflin/recipes.git
+
+

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

+

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:alflin/recipes.git (fetch)
+origin   git@github.com:alflin/recipes.git (push)
+
+

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

+

3. SSH Background and Setup

+

Before Alfredo can connect to a remote repository, he needs to set up +a way for his computer to authenticate with GitHub so it knows it’s him +trying to connect to his remote repository.

+

We are going to set up the method that is commonly used by many +different services to authenticate access on the command line. This +method is called Secure Shell Protocol (SSH). SSH is a cryptographic +network protocol that allows secure communication between computers +using an otherwise insecure network.

+

SSH uses what is called a key pair. This is two keys that work +together to validate access. One key is publicly known and called the +public key, and the other key called the private key is kept private. +Very descriptive names.

+

You can think of the public key as a padlock, and only you have the +key (the private key) to open it. You use the public key where you want +a secure method of communication, such as your GitHub account. You give +this padlock, or public key, to GitHub and say “lock the communications +to my account with this so that only computers that have my private key +can unlock communications and send git commands as my GitHub +account.”

+

What we will do now is the minimum required to set up the SSH keys +and add the public key to a GitHub account.

+
+
+ +
+
+

Advanced SSH

+
+

A supplemental episode in this lesson discusses SSH and key pairs in +more depth and detail.

+
+
+
+

The first thing we are going to do is check if this has already been +done on the computer you’re on. Because generally speaking, this setup +only needs to happen once and then you can forget about it.

+
+
+ +
+
+

Keeping your keys secure

+
+

You shouldn’t really forget about your SSH keys, since they keep your +account secure. It’s good practice to audit your secure shell keys every +so often. Especially if you are using multiple computers to access your +account.

+
+
+
+

We will run the list command to check what key pairs already exist on +your computer.

+
+

BASH +

+
ls -al ~/.ssh
+
+

Your output is going to look a little different depending on whether +or not SSH has ever been set up on the computer you are using.

+

Alfredo has not set up SSH on his computer, so his output is

+
+

OUTPUT +

+
ls: cannot access '/c/Users/Alfredo/.ssh': No such file or directory
+
+

If SSH has been set up on the computer you’re using, the public and +private key pairs will be listed. The file names are either +id_ed25519/id_ed25519.pub or +id_rsa/id_rsa.pub depending on how the key +pairs were set up. Since they don’t exist on Alfredo’s computer, he uses +this command to create them.

+
+

3.1 Create an SSH key pair

+

To create an SSH key pair Alfredo uses this command, where the +-t option specifies which type of algorithm to use and +-C attaches a comment to the key (here, Alfredo’s +email):

+
+

BASH +

+
$ ssh-keygen -t ed25519 -C "a.linguini@ratatouille.fr"
+
+

If you are using a legacy system that doesn’t support the Ed25519 +algorithm, use: +$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

+
+

OUTPUT +

+
Generating public/private ed25519 key pair.
+Enter file in which to save the key (/c/Users/Alfredo/.ssh/id_ed25519):
+
+

We want to use the default file, so just press Enter.

+
+

OUTPUT +

+
Created directory '/c/Users/Alfredo/.ssh'.
+Enter passphrase (empty for no passphrase):
+
+

Now, it is prompting Alfredo for a passphrase. Since he is using his +kitchen’s laptop that other people sometimes have access to, he wants to +create a passphrase. Be sure to use something memorable or save your +passphrase somewhere, as there is no “reset my password” option. Note +that, when typing a passphrase on a terminal, there won’t be any visual +feedback of your typing. This is normal: your passphrase will be +recorded even if you see nothing changing on your screen.

+
+

OUTPUT +

+
Enter same passphrase again:
+
+

After entering the same passphrase a second time, we receive the +confirmation

+
+

OUTPUT +

+
Your identification has been saved in /c/Users/Alfredo/.ssh/id_ed25519
+Your public key has been saved in /c/Users/Alfredo/.ssh/id_ed25519.pub
+The key fingerprint is:
+SHA256:SMSPIStNyA00KPxuYu94KpZgRAYjgt9g4BA4kFy3g1o a.linguini@ratatouille.fr
+The key's randomart image is:
++--[ED25519 256]--+
+|^B== o.          |
+|%*=.*.+          |
+|+=.E =.+         |
+| .=.+.o..        |
+|....  . S        |
+|.+ o             |
+|+ =              |
+|.o.o             |
+|oo+.             |
++----[SHA256]-----+
+
+

The “identification” is actually the private key. You should never +share it. The public key is appropriately named. The “key fingerprint” +is a shorter version of a public key.

+

Now that we have generated the SSH keys, we will find the SSH files +when we check.

+
+

BASH +

+
ls -al ~/.ssh
+
+
+

OUTPUT +

+
drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ./
+drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ../
+-rw-r--r-- 1 Alfredo   197121 419 Jul 16 14:48 id_ed25519
+-rw-r--r-- 1 Alfredo   197121 106 Jul 16 14:48 id_ed25519.pub
+
+
+
+

3.2 Copy the public key to GitHub

+

Now we have a SSH key pair and we can run this command to check if +GitHub can read our authentication.

+
+

BASH +

+
ssh -T git@github.com
+
+
+

OUTPUT +

+
The authenticity of host 'github.com (192.30.255.112)' can't be established.
+RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
+This key is not known by any other names
+Are you sure you want to continue connecting (yes/no/[fingerprint])? y
+Please type 'yes', 'no' or the fingerprint: yes
+Warning: Permanently added 'github.com' (RSA) to the list of known hosts.
+git@github.com: Permission denied (publickey).
+
+

Right, we forgot that we need to give GitHub our public key!

+

First, we need to copy the public key. Be sure to include the +.pub at the end, otherwise you’re looking at the private +key.

+
+

BASH +

+
cat ~/.ssh/id_ed25519.pub
+
+
+

OUTPUT +

+
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDmRA3d51X0uu9wXek559gfn6UFNF69yZjChyBIU2qKI a.linguini@ratatouille.fr
+
+

Now, going to GitHub.com, click on your profile icon in the top right +corner to get the drop-down menu. Click “Settings”, then on the settings +page, click “SSH and GPG keys”, on the left side “Access” menu. Click +the “New SSH key” button on the right side. Now, you can add the title +(Alfredo uses the title “Alfredo’s Kitchen Laptop” so he can remember +where the original key pair files are located), paste your SSH key into +the field, and click the “Add SSH key” to complete the setup.

+

Now that we’ve set that up, let’s check our authentication again from +the command line.

+
+

BASH +

+
$ ssh -T git@github.com
+
+
+

OUTPUT +

+
Hi Alfredo! You've successfully authenticated, but GitHub does not provide shell access.
+
+

Good! This output confirms that the SSH key works as intended. We are +now ready to push our work to the remote repository.

+
+

4. Push local changes to a remote

+

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

+
+

BASH +

+
$ git push origin main
+
+

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

+
+

OUTPUT +

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

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

+
+
+
+

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

+
From https://github.com/alflin/recipes
+ * branch            main     -> FETCH_HEAD
+Already up-to-date.
+
+

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

+
+
+ +
+
+

GitHub GUI

+
+

Browse to your recipes 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/alflin/recipes
+ * 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/alflin/recipes
+ * 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.
  • +
+
+
+
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/08-collab.html b/08-collab.html new file mode 100644 index 0000000000..fb26ea935c --- /dev/null +++ b/08-collab.html @@ -0,0 +1,785 @@ + +Version Control with Git: Collaborating +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Collaborating

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+
+
+ +
+
+

Practicing By Yourself

+
+

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

+
+
+
+

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

+
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

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

+

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

+

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

+

To clone the Owner’s repo into her Desktop folder, the +Collaborator enters:

+
+

BASH +

+
$ git clone git@github.com:alflin/recipes.git ~/Desktop/alflin-recipes
+
+

Replace ‘alflin’ with the Owner’s username.

+

If you choose to clone without the clone path +(~/Desktop/alflin-recipes) specified at the end, you will +clone inside your own recipes folder! Make sure to navigate to the +Desktop folder first.

+
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

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

+
+

BASH +

+
$ cd ~/Desktop/alflin-recipes
+$ nano hummus.md
+$ cat hummus.md
+
+
+

OUTPUT +

+
# Hummus
+## Ingredients
+* chickpeas
+* lemon
+* olive oil
+* salt
+
+
+

BASH +

+
$ git add hummus.md
+$ git commit -m "Add ingredients for hummus"
+
+
+

OUTPUT +

+
 1 file changed, 6 insertion(+)
+ create mode 100644 hummus.md
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+

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

+
+
+ +
+
+

Some more about remotes

+
+

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

+

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

+

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

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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

+
+
+ +
+
+

A Basic Collaborative Workflow

+
+

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

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

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

+
+
+
+
+
+ +
+
+

Switch Roles and Repeat

+
+

Switch roles and repeat the whole process.

+
+
+
+
+
+ +
+
+

Review Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+

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

+
+
+
+
+
+
+ +
+
+

Comment Changes in GitHub

+
+

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

+

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

+

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

+
+
+
+
+
+ +
+
+

Version History, Backup, and Version Control

+
+

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

+
+
+
+
+
+ +
+
+

Key Points

+
+
  • +git clone copies a remote repository to create a local +repository with a remote called origin automatically set +up.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/09-conflict.html b/09-conflict.html new file mode 100644 index 0000000000..7c274828ac --- /dev/null +++ b/09-conflict.html @@ -0,0 +1,1158 @@ + +Version Control with Git: Conflicts +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Conflicts

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* put one avocado into a bowl.
+
+

and then push the change to GitHub:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "First step on the instructions"
+
+
+

OUTPUT +

+
[main 5ae9631] First step on the instructions
+ 1 file changed, 1 insertion(+)
+
+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados
+
+

We can commit the change locally:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "Add first step"
+
+
+

OUTPUT +

+
[main 07ebc69] Add first step
+ 1 file changed, 1 insertion(+)
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

+
To https://github.com/alflin/recipes.git
+ ! [rejected]        main -> main (fetch first)
+error: failed to push some refs to 'https://github.com/alflin/recipes.git'
+hint: Updates were rejected because the remote contains work that you do
+hint: not have locally. This is usually caused by another repository pushing
+hint: to the same ref. You may want to first integrate the remote changes
+hint: (e.g., 'git pull ...') before pushing again.
+hint: See the 'Note about fast-forwards' in 'git push --help' for details.
+
+
A diagram showing a conflict that might occur when two sets of independent changes are merged

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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. In our +case we want ‘the default strategy’. To use this strategy run the +following command to select it as the default thing git should do.

+
+

BASH +

+
$ git config pull.rebase false
+
+

Then attempt the pull again.

+
+

BASH +

+
$ git pull origin main
+
+
+
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+<<<<<<< HEAD
+* peel the avocados
+=======
+* put one avocado into a bowl.
+>>>>>>> dabb4c8c450e8475aee9b14b4383acc99f42af1d
+
+

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

To finish merging, we add guacamole.md to the changes +being made by the merge and then commit:

+
+

BASH +

+
$ git add guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+All conflicts fixed but you are still merging.
+  (use "git commit" to conclude merge)
+
+Changes to be committed:
+
+	modified:   guacamole.md
+
+
+
+

BASH +

+
$ git commit -m "Merge changes from GitHub"
+
+
+

OUTPUT +

+
[main 2abf2b1] Merge changes from GitHub
+
+

Now we can push our changes to GitHub:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

We get the merged file:

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

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

+

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

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

Conflicts can also be minimized with project management +strategies:

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

Solving Conflicts that You Create

+
+

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

+
+
+
+
+
+ +
+
+

Conflicts on Non-textual files

+
+

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

+
+
+
+
+
+ +
+
+

Let’s try it. Suppose Alfredo takes a picture of its guacamole and +calls it guacamole.jpg.

+

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

+
+

BASH +

+
$ head --bytes 1024 /dev/urandom > guacamole.jpg
+$ ls -lh guacamole.jpg
+
+
+

OUTPUT +

+
-rw-r--r-- 1 alflin 57095 1.0K Mar  8 20:24 guacamole.jpg
+
+

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

+

Now, suppose Alfredo adds guacamole.jpg to his +repository:

+
+

BASH +

+
$ git add guacamole.jpg
+$ git commit -m "Add picture of guacamole"
+
+
+

OUTPUT +

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

Suppose that Jimmy has added a similar picture in the meantime. His +is a picture of a guacamole with nachos, but it is also called +guacamole.jpg. When Alfredo tries to push, he gets a +familiar message:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+

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

+
+

OUTPUT +

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

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

+
+

OUTPUT +

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

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

+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of just guacamole instead of with nachos"
+
+
+

OUTPUT +

+
[main 21032c3] Use image of just guacamole instead of with nachos
+
+

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

+
+

BASH +

+
$ git checkout 439dc8c0 guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of guacamole with nachos instead of just guacamole"
+
+
+

OUTPUT +

+
[main da21b34] Use image of guacamole with nachos instead of just guacamole
+
+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git mv guacamole.jpg guacamole-only.jpg
+$ git checkout 439dc8c0 guacamole.jpg
+$ mv guacamole.jpg guacamole-nachos.jpg
+
+

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

+
+

BASH +

+
$ git rm guacamole.jpg
+$ git add guacamole-only.jpg
+$ git add guacamole-nachos.jpg
+$ git commit -m "Use two images: just guacamole and with nachos"
+
+
+

OUTPUT +

+
[main 94ae08c] Use two images: just guacamole and with nachos
+ 2 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 guacamole-nachos.jpg
+ rename guacamole.jpg => guacamole-only.jpg (100%)
+
+

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

+
+
+
+
+
+
+ +
+
+

A Typical Work Session

+
+

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

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

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

+ + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . . . . . .command . . . . . . . . . .
1
2echo 100 >> numbers.txt
3
4
5
6Celebrate!
+
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . .command . . . . . . . . . . . . . . . . . . .
1Update localgit pull origin main
2Make changesecho 100 >> numbers.txt
3Stage changesgit add numbers.txt
4Commit changesgit commit -m "Add 100 to numbers.txt"
5Update remotegit push origin main
6Celebrate!
+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/10-open.html b/10-open.html new file mode 100644 index 0000000000..9e692ca2c2 --- /dev/null +++ b/10-open.html @@ -0,0 +1,642 @@ + +Version Control with Git: Open Science +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Open Science

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

-– John Wilbanks

+
+

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

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

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

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

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

+

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

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

Making Code Citable

+
+

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

+
+
+
+
+
+ +
+
+

How Reproducible Is My Work?

+
+

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

+
+
+
+
+
+ +
+
+

How to Find an Appropriate Data Repository?

+
+

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

+
+
+
+
+
+ +
+
+

How to Track Large Data or Image Files using Git?

+
+

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

+

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

+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Open scientific work is more useful and more highly cited than +closed.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/11-licensing.html b/11-licensing.html new file mode 100644 index 0000000000..fb51bd8e76 --- /dev/null +++ b/11-licensing.html @@ -0,0 +1,602 @@ + +Version Control with Git: Licensing +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Licensing

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

+
  • What licensing information should I include with my work?
  • +
+
+
+
+
+
+

Objectives

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

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

+

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

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

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

+

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

+

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

+
+
+ +
+
+

Can I Use Open License?

+
+

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

+
+
+
+
+
+ +
+
+

What licenses have I already accepted?

+
+

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

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

Key Points

+
+
  • The LICENSE, LICENSE.md, or +LICENSE.txt file is often used in a repository to indicate +how the contents of the repo may be used by others.
  • +
  • People who incorporate General Public License (GPL’d) software into +their own software must make 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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/12-citation.html b/12-citation.html new file mode 100644 index 0000000000..92041f2e2a --- /dev/null +++ b/12-citation.html @@ -0,0 +1,540 @@ + +Version Control with Git: Citation +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Citation

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/13-hosting.html b/13-hosting.html new file mode 100644 index 0000000000..0b0adbcf73 --- /dev/null +++ b/13-hosting.html @@ -0,0 +1,600 @@ + +Version Control with Git: Hosting +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Hosting

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/14-supplemental-rstudio.html b/14-supplemental-rstudio.html new file mode 100644 index 0000000000..7ca9017277 --- /dev/null +++ b/14-supplemental-rstudio.html @@ -0,0 +1,665 @@ + +Version Control with Git: Supplemental: Using Git from RStudio +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Supplemental: Using Git from RStudio

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +
+

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 +recipes 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/recipes"

Ta-da! We have created a new project in RStudio within the existing +recipes 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. +
  3. Modify the .gitignore so that the graphs +directory is not version controlled.
  4. +
+
+
+
+
+ +
+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/404.html b/404.html new file mode 100644 index 0000000000..3cd0fcf4c7 --- /dev/null +++ b/404.html @@ -0,0 +1,478 @@ + +Version Control with Git: Page not found +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Page not found

+ +

Our apologies!

+

We cannot seem to find the page you are looking for. Here are some +tips that may help:

+
  1. try going back to the previous +page or
  2. +
  3. navigate to any other page using the navigation bar on the +left.
  4. +
  5. if the URL ends with /index.html, try removing +that.
  6. +
  7. head over to the home page of this +lesson +
  8. +

If you came here from a link in this lesson, please contact the +lesson maintainers using the links at the foot of this page.

+
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/CODE_OF_CONDUCT.html b/CODE_OF_CONDUCT.html new file mode 100644 index 0000000000..3ff8244af6 --- /dev/null +++ b/CODE_OF_CONDUCT.html @@ -0,0 +1,482 @@ + +Version Control with Git: Contributor Code of Conduct +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Contributor Code of Conduct

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +

As contributors and maintainers of this project, we pledge to follow +the The +Carpentries Code of Conduct.

+

Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our reporting +guidelines.

+ + + +
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/LICENSE.html b/LICENSE.html new file mode 100644 index 0000000000..361cc10852 --- /dev/null +++ b/LICENSE.html @@ -0,0 +1,530 @@ + +Version Control with Git: Licenses +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Licenses

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +

Instructional Material

+

All Carpentries (Software Carpentry, Data Carpentry, and Library +Carpentry) instructional material is made available under the Creative Commons +Attribution license. The following is a human-readable summary of +(and not a substitute for) the full legal +text of the CC BY 4.0 license.

+

You are free:

+
  • to Share—copy and redistribute the material in any +medium or format
  • +
  • to Adapt—remix, transform, and build upon the +material
  • +

for any purpose, even commercially.

+

The licensor cannot revoke these freedoms as long as you follow the +license terms.

+

Under the following terms:

+
  • Attribution—You must give appropriate credit +(mentioning that your work is derived from work that is Copyright (c) +The Carpentries and, where practical, linking to https://carpentries.org/), provide a link to the +license, and indicate if changes were made. You may do so in any +reasonable manner, but not in any way that suggests the licensor +endorses you or your use.

  • +
  • No additional restrictions—You may not apply +legal terms or technological measures that legally restrict others from +doing anything the license permits. With the understanding +that:

  • +

Notices:

+
  • You do not have to comply with the license for elements of the +material in the public domain or where your use is permitted by an +applicable exception or limitation.
  • +
  • No warranties are given. The license may not give you all of the +permissions necessary for your intended use. For example, other rights +such as publicity, privacy, or moral rights may limit how you use the +material.
  • +

Software

+

Except where otherwise noted, the example programs and other software +provided by The Carpentries are made available under the OSI-approved MIT +license.

+

Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +“Software”), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions:

+

The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software.

+

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+

Trademark

+

“The Carpentries”, “Software Carpentry”, “Data Carpentry”, and +“Library Carpentry” and their respective logos are registered trademarks +of Community Initiatives.

+
+
+ + +
+
+
+ +
Back To Top +
+
+ + diff --git a/aio.html b/aio.html new file mode 100644 index 0000000000..22b9d9b181 --- /dev/null +++ b/aio.html @@ -0,0 +1,5748 @@ + + + + + +Version Control with Git: All in One View + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Content from Automated Version Control

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

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

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.

+
+
+ +
+
+

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.

+
+
+
+
+
+ +
+
+

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 2024-11-01 | + + Edit this page

+
+ +
+
+

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

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. So here is +how Alfredo sets up his new laptop:

+
+

BASH +

+
$ git config --global user.name "Alfredo Linguini"
+$ git config --global user.email "a.linguini@ratatouille.fr"
+
+

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

+

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

+
+
+ +
+
+

Keeping your email private

+
+

If you elect to use a private email address with GitHub, then use +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.

+
+
+
+
+
+ +
+
+

Line Endings

+
+

As with other keys, when you hit Enter or or +on Macs, Return on your keyboard, your computer encodes this +input as a character. Different operating systems use different +character(s) to represent the end of a line. (You may also hear these +referred to as newlines or line breaks.) Because Git uses these +characters to compare files, it may cause unexpected issues when editing +a file on different machines. Though it is beyond the scope of this +lesson, you can read more about this issue in +the Pro Git book.

+

You can change the way Git recognizes and encodes line endings using +the core.autocrlf command to git config. The +following settings are recommended:

+

On macOS and Linux:

+
+

BASH +

+
$ git config --global core.autocrlf input
+
+

And on Windows:

+
+

BASH +

+
$ git config --global core.autocrlf true
+
+
+
+
+

Alfredo also has to set his favorite text editor, following this +table:

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

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

+
+
+ +
+
+

Exiting Vim

+
+

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

+
+
+
+

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

+
+

BASH +

+
$ git config --global init.defaultBranch main
+
+
+
+ +
+
+

Default Git branch naming

+
+

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

+

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

+

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

+
+
+
+

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.

+

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. Remember, +since typos in the config file will cause issues, it’s safer to view the +configuration with:

+
+

BASH +

+
$ git config --list
+
+

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

+
+
+ +
+
+

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

+
+

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

+
+

BASH +

+
$ git config -h
+$ git config --help
+
+

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

+

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

+
+

BASH +

+
$ git help
+
+
+
+
+
+
+ +
+
+

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-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

+
    +
  • Where does Git store information?
  • +
+
+
+
+
+
+
+

Objectives

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

Once Git is configured, we can start using it.

+

We will help Alfredo with his new project, create a repository with +all his recipes.

+

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 recipes
+$ cd recipes
+
+

Then we tell Git to make recipes 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 +recipes repository, whether subdirectories are present from +the beginning or added later. Also, note that the creation of the +recipes 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 recipes +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.

+

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

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

+
+
+ +
+
+

Places to Create Git Repositories

+
+

Along with tracking information about recipes (the project we have +already created), Alfredo would also like to track information about +desserts specifically. Alfredo creates a desserts project +inside his recipes project with the following sequence of +commands:

+
+

BASH +

+
$ cd ~/Desktop    # return to Desktop directory
+$ cd recipes      # go into recipes directory, which is already a Git repository
+$ ls -a           # ensure the .git subdirectory is still present in the recipes directory
+$ mkdir desserts # make a sub-directory recipes/desserts
+$ cd desserts    # go into desserts subdirectory
+$ git init        # make the desserts 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 +desserts subdirectory, required for tracking files stored +in the desserts subdirectory?

+
+
+
+
+
+ +
+
+

No. Alfredo does not need to make the desserts +subdirectory a Git repository because the recipes +repository will track all files, sub-directories, and subdirectory files +under the recipes directory. Thus, in order to track all +information about desserts, Alfredo only needed to add the +desserts subdirectory to the recipes +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

+
+

Jimmy explains to Alfredo how a nested repository is redundant and +may cause confusion down the road. Alfredo would like to go back to a +single git repository. How can Alfredo undo his last +git init in the desserts 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, Alfredo can remove the +.git folder in the desserts subdirectory by running the +following command from inside the recipes directory:

+
+

BASH +

+
$ rm -rf desserts/.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 Tracking Changes

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

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 in the right directory. You should +be in the recipes directory.

+
+

BASH +

+
$ cd ~/Desktop/recipes
+
+

Let’s create a file called guacamole.md that contains +the basic structure to have a recipe. 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 guacamole.md
+
+

Type the text below into the guacamole.md file:

+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

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 +

+
guacamole.md
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

If we check the status of our project again, Git tells us that it’s +noticed the new file:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Untracked files:
+   (use "git add <file>..." to include in what will be committed)
+
+	guacamole.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 guacamole.md
+
+

and then check that the right thing happened:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Changes to be committed:
+  (use "git rm --cached <file>..." to unstage)
+
+	new file:   guacamole.md
+
+
+

Git now knows that it’s supposed to keep track of +guacamole.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 template for recipe"
+
+
+

OUTPUT +

+
[main (root-commit) f22b25e] Create a template for recipe
+ 1 file changed, 1 insertion(+)
+ create mode 100644 guacamole.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.

+

If we run git status now:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

it tells us everything is up to date. 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 f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+

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.

+
+
+ +
+
+

Where Are My Changes?

+
+

If we run ls at this point, we will still see just one +file called guacamole.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 Alfredo adds 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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lemon
+* salt
+## Instructions
+
+

When we run git status now, it tells us that a file it +already knows about has been modified:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git restore <file>..." to discard changes in working directory)
+
+	modified:   guacamole.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/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lemon
++* salt
+ ## Instructions
+
+

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. +
  3. The second line tells exactly which versions of the file Git is +comparing; df0654a and 315bf3a are unique +computer-generated labels for those versions.
  4. +
  5. The third and fourth lines once again show the name of the file +being changed.
  6. +
  7. 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.
  8. +
+

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

+
+

BASH +

+
$ git commit -m "Add basic guacamole's ingredients"
+$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ git commit -m "Add basic guacamole's ingredients"
+
+
+

OUTPUT +

+
[main 34961b1] Add basic guacamole's ingredient
+ 1 file changed, 3 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

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 recipe +by changing ‘lemon’ to ‘lime’:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole.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/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole to the traditional recipe"
+
+
+

OUTPUT +

+
[main 005937f] Modify guacamole to the traditional recipe
+ 1 file changed, 1 insertion(+)
+
+

check our status:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git log
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+    Modify guacamole to the traditional recipe
+
+commit 34961b159c27df3b475cfe4415d94a6d1fcd064d
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Add basic guacamole's ingredients
+
+commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+
+
+ +
+
+

Word-based diffing

+
+

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

+
+
+
+
+
+ +
+
+

Paging the Log

+
+

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

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

Limit Log Size

+
+

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

+
+

BASH +

+
$ git log -1
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+   Modify guacamole to the traditional recipe
+
+

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

+
+

BASH +

+
$ git log --oneline
+
+
+

OUTPUT +

+
005937f (HEAD -> main) Modify guacamole to the traditional recipe
+34961b1 Add basic guacamole's ingredients
+f22b25e Create a template for recipe
+
+

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

+
+

BASH +

+
$ git log --oneline --graph
+
+
+

OUTPUT +

+
* 005937f (HEAD -> main) Modify guacamole to the traditional recipe
+* 34961b1 Add basic guacamole's ingredients
+* f22b25e Create a template for recipe
+
+
+
+
+
+
+ +
+
+

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:
  2. +
+
+

BASH +

+
$ mkdir cakes
+$ git status
+$ git add cakes
+$ git status
+
+

Note, our newly created empty directory cakes 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:
  2. +
+
+

BASH +

+
git add <directory-with-files>
+
+

Try it for yourself:

+
+

BASH +

+
$ touch cakes/brownie cakes/lemon_drizzle
+$ git status
+$ git add cakes
+$ git status
+
+

Before moving on, we will commit these changes.

+
+

BASH +

+
$ git commit -m "Add some initial cakes"
+
+
+
+
+

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 guacamole.md?

+
    +
  1. “Changes”
  2. +
  3. “Changed lemon for lime”
  4. +
  5. “Guacamole modified to the traditional recipe”
  6. +
+
+
+
+
+
+ +
+
+

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. +
  3. +

    BASH +

    +
       $ git init myfile.txt
    +   $ git commit -m "my recent changes"
    +
  4. +
  5. +

    BASH +

    +
       $ git add myfile.txt
    +   $ git commit -m "my recent changes"
    +
  6. +
  7. +

    BASH +

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

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 guacamole.md noting the rough price of +the ingredients.
  2. +
  3. Create a new file groceries.md with a list of products +and their prices for different markets.
  4. +
  5. Add changes from both files to the staging area, and commit those +changes.
  6. +
+
+
+
+
+
+ +
+
+

First we make our changes to the guacamole.md and +groceries.md files:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado (1.35)
+* lime (0.64)
+* salt (2)
+
+
+

BASH +

+
$ nano groceries.md
+$ cat groceries.md
+
+
+

OUTPUT +

+
# Market A
+* avocado: 1.35 per unit.
+* lime: 0.64 per unit
+* salt: 2 per kg
+
+

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

+
+

BASH +

+
$ git add guacamole.md groceries.md
+
+

Or with multiple commands:

+
+

BASH +

+
$ git add guacamole.md
+$ git add groceries.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 "Write prices for ingredients and their source"
+
+
+

OUTPUT +

+
[main cc127c2]
+ Write prices for ingredients and their source
+ 2 files changed, 7 insertions(+)
+ create mode 100644 groceries.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 recipes folder:

+
+

BASH +

+
$ cd ..
+
+

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

+
+

BASH +

+
$ mkdir bio
+$ cd bio
+
+

Initialise git:

+
+

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 2024-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

We’ve been adding small changes at a time to +guacamole.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 guacamole.md, adding yet another +line.

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+An ill-considered change
+
+

Now, let’s see what we get.

+
+

BASH +

+
$ git diff HEAD guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index b36abfd..0848c8d 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -4,3 +4,4 @@
+ * lime
+ * salt
+ ## Instructions
++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 guacamole.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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
+
+

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

+
+

BASH +

+
$ git show HEAD~2 guacamole.md
+
+
+

OUTPUT +

+
commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Create a template for recipe
+
+diff --git a/guacamole.md b/guacamole.md
+new file mode 100644
+index 0000000..df0654a
+--- /dev/null
++++ b/guacamole.md
+@@ -0,0 +1,3 @@
++# Guacamole
++## Ingredients
++## Instructions
+
+

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 was given the ID +f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try +this:

+
+

BASH +

+
$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++An ill-considered change
+
+

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 guacamole.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 main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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. If +we want to go back even further, we can use a commit identifier instead, +using -s option:

+
+

BASH +

+
$ git restore -s f22b25e guacamole.md
+
+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

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

+
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

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

+
+
+ +
+
+

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. +
  3. $ git restore data_cruncher.py

  4. +
  5. $ git restore -s HEAD~1 data_cruncher.py

  6. +
  7. $ git restore -s <unique ID of last commit> data_cruncher.py

  8. +
  9. Both 2 and 4

  10. +
+
+
+
+
+
+ +
+
+

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

+
+

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

+

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

+

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

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

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

  4. +
  5. git revert [commit ID]

  6. +
  7. Type in the new commit message.

  8. +
  9. Save and close.

  10. +
+
+
+
+
+
+ +
+
+

The command git log lists project history with commit +IDs.

+

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

+
+
+
+
+
+
+ +
+
+

Understanding Workflow and History

+
+

What is the output of the last command in

+
+

BASH +

+
$ cd recipes
+$ echo "I like tomatoes, therefore I like ketchup" > ketchup.md
+$ git add ketchup.md
+$ echo "ketchup enhances pasta dishes" >> ketchup.md
+$ git commit -m "My opinions about the red sauce"
+$ git restore ketchup.md
+$ cat ketchup.md # this will print the content of ketchup.md on screen
+
+
    +
  1. +

    OUTPUT +

    +
      ketchup enhances pasta dishes
    +
  2. +
  3. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +
  4. +
  5. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +  ketchup enhances pasta dishes
    +
  6. +
  7. +

    OUTPUT +

    +
      Error because you have changed ketchup.md without committing the changes
    +
  8. +
+
+
+
+
+
+ +
+
+

The answer is 2.

+

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

+

So, when git commit -m "My opinions about the red sauce" +is executed, the version of ketchup.md committed to the +repository is the one from the staging area and has only one line.

+

At this time, the working copy still has the second line (and

+

git status will show that the file is modified). +However, git restore ketchup.md replaces the working copy +with the most recently committed version of ketchup.md. So, +cat ketchup.md will output

+
+

OUTPUT +

+
I like tomatoes, therefore I like ketchup
+
+
+
+
+
+
+
+ +
+
+

Checking Understanding of +git diff +

+
+

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

+
+
+
+
+
+ +
+
+

Getting Rid of Staged Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

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

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

+

Using the command git restore guacamole.md now does not +give an error, but it does not restore the file either. Git helpfully +tells us that we need to use git restore --staged first to +unstage the file:

+
+

BASH +

+
$ git restore --staged guacamole.md
+
+

Now, git status gives us:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git git restore <file>..." to discard changes in working directory)
+        modified:   guacamole.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

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

+
+

BASH +

+
$ git restore guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+
+
+
+
+
+
+ +
+
+

Explore and Summarize Histories

+
+

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

+

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

+
+

BASH +

+
$ git log guacamole.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 guacamole.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 diff displays differences between commits.
  • +
  • +git restore recovers old versions of files.
  • +
+
+
+

Content from Ignoring Things

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

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 receipts
+$ touch a.png b.png c.png receipts/a.jpg receipts/b.jpg
+
+

and see what Git says:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	a.png
+	b.png
+	c.png
+	receipts/
+
+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
+receipts/
+
+

These patterns tell Git to ignore any file whose name ends in +.png and everything in the receipts 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 main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	.gitignore
+
+nothing added to commit but untracked files present (use "git add" to track)
+
+

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

+
+

BASH +

+
$ git add .gitignore
+$ git commit -m "Ignore png files and the receipts folder."
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git add a.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 main
+Ignored files:
+ (use "git add -f <file>..." to include in what will be committed)
+
+        a.png
+        b.png
+        c.png
+        receipts/
+
+nothing to commit, working tree clean
+
+
+
+ +
+
+

Ignoring Nested Files

+
+

Given a directory structure that looks like:

+
+

BASH +

+
receipts/data
+receipts/plots
+
+

How would you ignore only receipts/plots and not +receipts/data?

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/plots/
+
+

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

+

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 also that because you’ve previously committed .png +files in this lesson 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 +

+
receipts/data
+receipts/images
+receipts/plots
+receipts/analysis
+
+

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

+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/*               # ignore everything in receipts folder
+!receipts/data/          # do not ignore receipts/data/ contents
+
+
+
+
+
+
+
+ +
+
+

Ignoring all data Files in a Directory

+
+

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

+
+

BASH +

+
receipts/data/market_position/gps/a.dat
+receipts/data/market_position/gps/b.dat
+receipts/data/market_position/gps/c.dat
+receipts/data/market_position/gps/info.txt
+receipts/plots
+
+

What’s the shortest .gitignore rule you could write to +ignore all .dat files in +result/data/market_position/gps? Do not ignore the +info.txt.

+
+
+
+
+
+ +
+
+

Appending receipts/data/market_position/gps/*.dat will +match every file in receipts/data/market_position/gps that +ends with .dat. The file +receipts/data/market_position/gps/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. +
  3. Test your “ignore pattern” by creating some dummy files of the +form log_01, etc.

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

  6. +
  7. 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.

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

Key Points

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

Content from Remotes in GitHub

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

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 start by sharing the changes we’ve made to our current project +with the world. To this end we are going to create a remote +repository that will be linked to our local repository.

+

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 +recipes:

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

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

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

+
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 recipes
+$ cd recipes
+$ git init
+
+

If you remember back to the earlier episode where we added and committed our +earlier work on guacamole.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 "recipes" 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 +guacamole.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.

+
+
+
+
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

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

+
+

BASH +

+
$ git remote add origin git@github.com:alflin/recipes.git
+
+

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

+

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:alflin/recipes.git (fetch)
+origin   git@github.com:alflin/recipes.git (push)
+
+

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

+

3. SSH Background and Setup +

+
+

Before Alfredo can connect to a remote repository, he needs to set up +a way for his computer to authenticate with GitHub so it knows it’s him +trying to connect to his remote repository.

+

We are going to set up the method that is commonly used by many +different services to authenticate access on the command line. This +method is called Secure Shell Protocol (SSH). SSH is a cryptographic +network protocol that allows secure communication between computers +using an otherwise insecure network.

+

SSH uses what is called a key pair. This is two keys that work +together to validate access. One key is publicly known and called the +public key, and the other key called the private key is kept private. +Very descriptive names.

+

You can think of the public key as a padlock, and only you have the +key (the private key) to open it. You use the public key where you want +a secure method of communication, such as your GitHub account. You give +this padlock, or public key, to GitHub and say “lock the communications +to my account with this so that only computers that have my private key +can unlock communications and send git commands as my GitHub +account.”

+

What we will do now is the minimum required to set up the SSH keys +and add the public key to a GitHub account.

+
+
+ +
+
+

Advanced SSH

+
+

A supplemental episode in this lesson discusses SSH and key pairs in +more depth and detail.

+
+
+
+

The first thing we are going to do is check if this has already been +done on the computer you’re on. Because generally speaking, this setup +only needs to happen once and then you can forget about it.

+
+
+ +
+
+

Keeping your keys secure

+
+

You shouldn’t really forget about your SSH keys, since they keep your +account secure. It’s good practice to audit your secure shell keys every +so often. Especially if you are using multiple computers to access your +account.

+
+
+
+

We will run the list command to check what key pairs already exist on +your computer.

+
+

BASH +

+
ls -al ~/.ssh
+
+

Your output is going to look a little different depending on whether +or not SSH has ever been set up on the computer you are using.

+

Alfredo has not set up SSH on his computer, so his output is

+
+

OUTPUT +

+
ls: cannot access '/c/Users/Alfredo/.ssh': No such file or directory
+
+

If SSH has been set up on the computer you’re using, the public and +private key pairs will be listed. The file names are either +id_ed25519/id_ed25519.pub or +id_rsa/id_rsa.pub depending on how the key +pairs were set up. Since they don’t exist on Alfredo’s computer, he uses +this command to create them.

+
+

3.1 Create an SSH key pair +

+

To create an SSH key pair Alfredo uses this command, where the +-t option specifies which type of algorithm to use and +-C attaches a comment to the key (here, Alfredo’s +email):

+
+

BASH +

+
$ ssh-keygen -t ed25519 -C "a.linguini@ratatouille.fr"
+
+

If you are using a legacy system that doesn’t support the Ed25519 +algorithm, use: +$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

+
+

OUTPUT +

+
Generating public/private ed25519 key pair.
+Enter file in which to save the key (/c/Users/Alfredo/.ssh/id_ed25519):
+
+

We want to use the default file, so just press Enter.

+
+

OUTPUT +

+
Created directory '/c/Users/Alfredo/.ssh'.
+Enter passphrase (empty for no passphrase):
+
+

Now, it is prompting Alfredo for a passphrase. Since he is using his +kitchen’s laptop that other people sometimes have access to, he wants to +create a passphrase. Be sure to use something memorable or save your +passphrase somewhere, as there is no “reset my password” option. Note +that, when typing a passphrase on a terminal, there won’t be any visual +feedback of your typing. This is normal: your passphrase will be +recorded even if you see nothing changing on your screen.

+
+

OUTPUT +

+
Enter same passphrase again:
+
+

After entering the same passphrase a second time, we receive the +confirmation

+
+

OUTPUT +

+
Your identification has been saved in /c/Users/Alfredo/.ssh/id_ed25519
+Your public key has been saved in /c/Users/Alfredo/.ssh/id_ed25519.pub
+The key fingerprint is:
+SHA256:SMSPIStNyA00KPxuYu94KpZgRAYjgt9g4BA4kFy3g1o a.linguini@ratatouille.fr
+The key's randomart image is:
++--[ED25519 256]--+
+|^B== o.          |
+|%*=.*.+          |
+|+=.E =.+         |
+| .=.+.o..        |
+|....  . S        |
+|.+ o             |
+|+ =              |
+|.o.o             |
+|oo+.             |
++----[SHA256]-----+
+
+

The “identification” is actually the private key. You should never +share it. The public key is appropriately named. The “key fingerprint” +is a shorter version of a public key.

+

Now that we have generated the SSH keys, we will find the SSH files +when we check.

+
+

BASH +

+
ls -al ~/.ssh
+
+
+

OUTPUT +

+
drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ./
+drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ../
+-rw-r--r-- 1 Alfredo   197121 419 Jul 16 14:48 id_ed25519
+-rw-r--r-- 1 Alfredo   197121 106 Jul 16 14:48 id_ed25519.pub
+
+
+
+

3.2 Copy the public key to GitHub +

+

Now we have a SSH key pair and we can run this command to check if +GitHub can read our authentication.

+
+

BASH +

+
ssh -T git@github.com
+
+
+

OUTPUT +

+
The authenticity of host 'github.com (192.30.255.112)' can't be established.
+RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
+This key is not known by any other names
+Are you sure you want to continue connecting (yes/no/[fingerprint])? y
+Please type 'yes', 'no' or the fingerprint: yes
+Warning: Permanently added 'github.com' (RSA) to the list of known hosts.
+git@github.com: Permission denied (publickey).
+
+

Right, we forgot that we need to give GitHub our public key!

+

First, we need to copy the public key. Be sure to include the +.pub at the end, otherwise you’re looking at the private +key.

+
+

BASH +

+
cat ~/.ssh/id_ed25519.pub
+
+
+

OUTPUT +

+
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDmRA3d51X0uu9wXek559gfn6UFNF69yZjChyBIU2qKI a.linguini@ratatouille.fr
+
+

Now, going to GitHub.com, click on your profile icon in the top right +corner to get the drop-down menu. Click “Settings”, then on the settings +page, click “SSH and GPG keys”, on the left side “Access” menu. Click +the “New SSH key” button on the right side. Now, you can add the title +(Alfredo uses the title “Alfredo’s Kitchen Laptop” so he can remember +where the original key pair files are located), paste your SSH key into +the field, and click the “Add SSH key” to complete the setup.

+

Now that we’ve set that up, let’s check our authentication again from +the command line.

+
+

BASH +

+
$ ssh -T git@github.com
+
+
+

OUTPUT +

+
Hi Alfredo! You've successfully authenticated, but GitHub does not provide shell access.
+
+

Good! This output confirms that the SSH key works as intended. We are +now ready to push our work to the remote repository.

+
+

4. Push local changes to a remote +

+
+

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

+
+

BASH +

+
$ git push origin main
+
+

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

+
+

OUTPUT +

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

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

+
+
+
+

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

+
From https://github.com/alflin/recipes
+ * branch            main     -> FETCH_HEAD
+Already up-to-date.
+
+

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

+
+
+ +
+
+

GitHub GUI

+
+

Browse to your recipes 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/alflin/recipes
+ * 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/alflin/recipes
+ * 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 Collaborating

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+
+
+ +
+
+

Practicing By Yourself

+
+

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

+
+
+
+

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

+
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

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

+

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

+

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

+

To clone the Owner’s repo into her Desktop folder, the +Collaborator enters:

+
+

BASH +

+
$ git clone git@github.com:alflin/recipes.git ~/Desktop/alflin-recipes
+
+

Replace ‘alflin’ with the Owner’s username.

+

If you choose to clone without the clone path +(~/Desktop/alflin-recipes) specified at the end, you will +clone inside your own recipes folder! Make sure to navigate to the +Desktop folder first.

+
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

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

+
+

BASH +

+
$ cd ~/Desktop/alflin-recipes
+$ nano hummus.md
+$ cat hummus.md
+
+
+

OUTPUT +

+
# Hummus
+## Ingredients
+* chickpeas
+* lemon
+* olive oil
+* salt
+
+
+

BASH +

+
$ git add hummus.md
+$ git commit -m "Add ingredients for hummus"
+
+
+

OUTPUT +

+
 1 file changed, 6 insertion(+)
+ create mode 100644 hummus.md
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+

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

+
+
+ +
+
+

Some more about remotes

+
+

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

+

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

+

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

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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

+
+
+ +
+
+

A Basic Collaborative Workflow

+
+

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

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

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

+
+
+
+
+
+ +
+
+

Switch Roles and Repeat

+
+

Switch roles and repeat the whole process.

+
+
+
+
+
+ +
+
+

Review Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+

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

+
+
+
+
+
+
+ +
+
+

Comment Changes in GitHub

+
+

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

+

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

+

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

+
+
+
+
+
+ +
+
+

Version History, Backup, and Version Control

+
+

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

+
+
+
+
+
+ +
+
+

Key Points

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

Content from Conflicts

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* put one avocado into a bowl.
+
+

and then push the change to GitHub:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "First step on the instructions"
+
+
+

OUTPUT +

+
[main 5ae9631] First step on the instructions
+ 1 file changed, 1 insertion(+)
+
+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados
+
+

We can commit the change locally:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "Add first step"
+
+
+

OUTPUT +

+
[main 07ebc69] Add first step
+ 1 file changed, 1 insertion(+)
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

+
To https://github.com/alflin/recipes.git
+ ! [rejected]        main -> main (fetch first)
+error: failed to push some refs to 'https://github.com/alflin/recipes.git'
+hint: Updates were rejected because the remote contains work that you do
+hint: not have locally. This is usually caused by another repository pushing
+hint: to the same ref. You may want to first integrate the remote changes
+hint: (e.g., 'git pull ...') before pushing again.
+hint: See the 'Note about fast-forwards' in 'git push --help' for details.
+
+
A diagram showing a conflict that might occur when two sets of independent changes are merged

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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. In our +case we want ‘the default strategy’. To use this strategy run the +following command to select it as the default thing git should do.

+
+

BASH +

+
$ git config pull.rebase false
+
+

Then attempt the pull again.

+
+

BASH +

+
$ git pull origin main
+
+
+
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+<<<<<<< HEAD
+* peel the avocados
+=======
+* put one avocado into a bowl.
+>>>>>>> dabb4c8c450e8475aee9b14b4383acc99f42af1d
+
+

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

To finish merging, we add guacamole.md to the changes +being made by the merge and then commit:

+
+

BASH +

+
$ git add guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+All conflicts fixed but you are still merging.
+  (use "git commit" to conclude merge)
+
+Changes to be committed:
+
+	modified:   guacamole.md
+
+
+
+

BASH +

+
$ git commit -m "Merge changes from GitHub"
+
+
+

OUTPUT +

+
[main 2abf2b1] Merge changes from GitHub
+
+

Now we can push our changes to GitHub:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

We get the merged file:

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

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

+

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

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

Conflicts can also be minimized with project management +strategies:

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

Solving Conflicts that You Create

+
+

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

+
+
+
+
+
+ +
+
+

Conflicts on Non-textual files

+
+

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

+
+
+
+
+
+ +
+
+

Let’s try it. Suppose Alfredo takes a picture of its guacamole and +calls it guacamole.jpg.

+

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

+
+

BASH +

+
$ head --bytes 1024 /dev/urandom > guacamole.jpg
+$ ls -lh guacamole.jpg
+
+
+

OUTPUT +

+
-rw-r--r-- 1 alflin 57095 1.0K Mar  8 20:24 guacamole.jpg
+
+

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

+

Now, suppose Alfredo adds guacamole.jpg to his +repository:

+
+

BASH +

+
$ git add guacamole.jpg
+$ git commit -m "Add picture of guacamole"
+
+
+

OUTPUT +

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

Suppose that Jimmy has added a similar picture in the meantime. His +is a picture of a guacamole with nachos, but it is also called +guacamole.jpg. When Alfredo tries to push, he gets a +familiar message:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+

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

+
+

OUTPUT +

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

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

+
+

OUTPUT +

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

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

+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of just guacamole instead of with nachos"
+
+
+

OUTPUT +

+
[main 21032c3] Use image of just guacamole instead of with nachos
+
+

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

+
+

BASH +

+
$ git checkout 439dc8c0 guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of guacamole with nachos instead of just guacamole"
+
+
+

OUTPUT +

+
[main da21b34] Use image of guacamole with nachos instead of just guacamole
+
+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git mv guacamole.jpg guacamole-only.jpg
+$ git checkout 439dc8c0 guacamole.jpg
+$ mv guacamole.jpg guacamole-nachos.jpg
+
+

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

+
+

BASH +

+
$ git rm guacamole.jpg
+$ git add guacamole-only.jpg
+$ git add guacamole-nachos.jpg
+$ git commit -m "Use two images: just guacamole and with nachos"
+
+
+

OUTPUT +

+
[main 94ae08c] Use two images: just guacamole and with nachos
+ 2 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 guacamole-nachos.jpg
+ rename guacamole.jpg => guacamole-only.jpg (100%)
+
+

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

+
+
+
+
+
+
+ +
+
+

A Typical Work Session

+
+

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

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

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

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . . . . . .command . . . . . . . . . .
1
2echo 100 >> numbers.txt
3
4
5
6Celebrate!
+
+
+
+
+
+ +
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . .command . . . . . . . . . . . . . . . . . . .
1Update localgit pull origin main
2Make changesecho 100 >> numbers.txt
3Stage changesgit add numbers.txt
4Commit changesgit commit -m "Add 100 to numbers.txt"
5Update remotegit push origin main
6Celebrate!
+
+
+
+
+
+
+ +
+
+

Key Points

+
+
    +
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +
+
+
+

Content from Open Science

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

-– John Wilbanks

+
+

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

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

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

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

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

+

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

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

Making Code Citable

+
+

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

+
+
+
+
+
+ +
+
+

How Reproducible Is My Work?

+
+

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

+
+
+
+
+
+ +
+
+

How to Find an Appropriate Data Repository?

+
+

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

+
+
+
+
+
+ +
+
+

How to Track Large Data or Image Files using Git?

+
+

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

+

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

+
+
+
+
+
+ +
+
+

Key Points

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

Content from Licensing

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

Overview

+
+
+
+
+

Questions

+
    +
  • What licensing information should I include with my work?
  • +
+
+
+
+
+
+
+

Objectives

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

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

+

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

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

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

+

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

+

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

+
+
+ +
+
+

Can I Use Open License?

+
+

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

+
+
+
+
+
+ +
+
+

What licenses have I already accepted?

+
+

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

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

Key Points

+
+
    +
  • The LICENSE, LICENSE.md, or +LICENSE.txt file is often used in a repository to indicate +how the contents of the repo may be used by others.
  • +
  • People who incorporate General Public License (GPL’d) software into +their own software must make 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-11-01 | + + Edit this page

+
+ +
+
+

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-11-01 | + + Edit this page

+
+ +
+
+

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 Supplemental: Using Git from RStudio

+
+

Last updated on 2024-11-01 | + + Edit this page

+
+ +
+
+

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 +recipes 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/recipes"

Ta-da! We have created a new project in RStudio within the existing +recipes 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. +
  3. Modify the .gitignore so that the graphs +directory is not version controlled.
  4. +
+
+
+
+
+
+ +
+
+

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.
  • +
+
+
+
+
+
+
+ + +
+ + +
+
+ +
Back To Top +
+
+ + + + diff --git a/android-chrome-192x192.png b/android-chrome-192x192.png new file mode 100644 index 0000000000..ed3c210abf Binary files /dev/null and b/android-chrome-192x192.png differ diff --git a/android-chrome-512x512.png b/android-chrome-512x512.png new file mode 100644 index 0000000000..c88d96c1cb Binary files /dev/null and b/android-chrome-512x512.png differ diff --git a/apple-touch-icon.png b/apple-touch-icon.png new file mode 100644 index 0000000000..8044feefd6 Binary files /dev/null and b/apple-touch-icon.png differ diff --git a/assets/fonts/Mulish-Bold.ttf b/assets/fonts/Mulish-Bold.ttf new file mode 100644 index 0000000000..1f522d4769 Binary files /dev/null and b/assets/fonts/Mulish-Bold.ttf differ diff --git a/assets/fonts/Mulish-Bold.woff b/assets/fonts/Mulish-Bold.woff new file mode 100644 index 0000000000..711448ea9b Binary files /dev/null and b/assets/fonts/Mulish-Bold.woff differ diff --git a/assets/fonts/Mulish-ExtraBold.ttf b/assets/fonts/Mulish-ExtraBold.ttf new file mode 100644 index 0000000000..62850fff3b Binary files /dev/null and b/assets/fonts/Mulish-ExtraBold.ttf differ diff --git a/assets/fonts/mulish-v5-latin-regular.eot b/assets/fonts/mulish-v5-latin-regular.eot new file mode 100644 index 0000000000..423bcb17a6 Binary files /dev/null and b/assets/fonts/mulish-v5-latin-regular.eot differ diff --git a/assets/fonts/mulish-v5-latin-regular.svg b/assets/fonts/mulish-v5-latin-regular.svg new file mode 100644 index 0000000000..70341f98b4 --- /dev/null +++ b/assets/fonts/mulish-v5-latin-regular.svg @@ -0,0 +1,305 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/fonts/mulish-v5-latin-regular.ttf b/assets/fonts/mulish-v5-latin-regular.ttf new file mode 100644 index 0000000000..541bb406e0 Binary files /dev/null and b/assets/fonts/mulish-v5-latin-regular.ttf differ diff --git a/assets/fonts/mulish-v5-latin-regular.woff b/assets/fonts/mulish-v5-latin-regular.woff new file mode 100644 index 0000000000..700ec13f5a Binary files /dev/null and b/assets/fonts/mulish-v5-latin-regular.woff differ diff --git a/assets/fonts/mulish-v5-latin-regular.woff2 b/assets/fonts/mulish-v5-latin-regular.woff2 new file mode 100644 index 0000000000..b244298bf6 Binary files /dev/null and b/assets/fonts/mulish-v5-latin-regular.woff2 differ diff --git a/assets/fonts/mulish-variablefont_wght.woff b/assets/fonts/mulish-variablefont_wght.woff new file mode 100644 index 0000000000..fc425383ae Binary files /dev/null and b/assets/fonts/mulish-variablefont_wght.woff differ diff --git a/assets/fonts/mulish-variablefont_wght.woff2 b/assets/fonts/mulish-variablefont_wght.woff2 new file mode 100644 index 0000000000..8a233c6f9f Binary files /dev/null and b/assets/fonts/mulish-variablefont_wght.woff2 differ diff --git a/assets/images/carpentries-logo-sm.svg b/assets/images/carpentries-logo-sm.svg new file mode 100644 index 0000000000..da70d40ee6 --- /dev/null +++ b/assets/images/carpentries-logo-sm.svg @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/assets/images/carpentries-logo.svg b/assets/images/carpentries-logo.svg new file mode 100644 index 0000000000..6cbe665005 --- /dev/null +++ b/assets/images/carpentries-logo.svg @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/assets/images/data-logo-sm.svg b/assets/images/data-logo-sm.svg new file mode 100644 index 0000000000..6d4019ed59 --- /dev/null +++ b/assets/images/data-logo-sm.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/images/data-logo.svg b/assets/images/data-logo.svg new file mode 100644 index 0000000000..c5949528e1 --- /dev/null +++ b/assets/images/data-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/images/dropdown-arrow.svg b/assets/images/dropdown-arrow.svg new file mode 100644 index 0000000000..a12b04b343 --- /dev/null +++ b/assets/images/dropdown-arrow.svg @@ -0,0 +1,12 @@ + + + + +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Discussion

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +
+ +
+ + + +

Frequently Asked Questions

+

People often have questions about Git beyond the scope of the core +material. Students who have completed the rest of the lessons might find +value in looking through the following topics.

+

Note that since this material isn’t essential for basic Git usage, it +won’t be covered by the instructor.

+

More Advanced Git Configuration

+

In Setting Up Git, we used +git config --global to set some default options for Git. It +turns out that these configuration options get stored in your home +directory in a plain text file called .gitconfig.

+
+

BASH +

+
$ cat ~/.gitconfig
+
+
+

OUTPUT +

+
[user]
+	name = Alfredo Linguini
+	email = a.linguini@ratatouille.fr
+[color]
+	ui = true
+[core]
+	editor = nano
+
+

This file can be opened in your preferred text editor. (Note that it +is recommended to continue using the git config command, as +this helps avoid introducing syntax errors.)

+

Eventually, you will want to start customizing Git’s behaviour. This +can be done by adding more entries to your .gitconfig. The +available options are described in the manual:

+
+

BASH +

+
$ git config --help
+
+

In particular, you might find it useful to add aliases. These are +like shortcuts for longer Git commands. For example, if you get sick of +typing git checkout all the time, you could run the +command:

+
+

BASH +

+
$ git config --global alias.co checkout
+
+

Now if we return to the example from Exploring History where we ran:

+
+

BASH +

+
$ git checkout f22b25e guacamole.md
+
+

we could now instead type:

+
+

BASH +

+
$ git co f22b25e guacamole.md
+
+

Styling Git’s Log

+

A good target for customization is output from the log. The default +log is quite verbose but gives no graphical hints such as information +about which commits were done locally and which were pulled from +remotes.

+

You can use git log --help and +git config --help to look for different ways to change the +log output. Try the following commands and see what effect they +have:

+
+

BASH +

+
$ git config --global alias.lg "log --graph"
+$ git config --global log.abbrevCommit true
+$ git config --global format.pretty oneline
+$ git lg
+
+

If you don’t like the effects, you can undo them with:

+
+

BASH +

+
$ git config --global --unset alias.lg
+$ git config --global --unset log.abbrevCommit
+$ git config --global --unset format.pretty
+
+
+
+ +
+
+

Undoing Git Configuration Changes

+
+

You can use the --unset flag to delete unwanted options +from .gitconfig. Another way to roll back changes is to +store your .gitconfig using Git.

+

For hints on what you might want to configure, go to GitHub and +search for “gitconfig”. You will find hundreds of repositories in which +people have stored their own Git configuration files. Sort them by the +number of stars and have a look at the top few. If you find some you +like, please check that they’re covered by an open source license before +you clone them.

+
+
+
+

Non-text Files

+

Recall when we discussed Conflicts +there was a challenge that asked, “What does Git do when there is a +conflict in an image or some other non-textual file that is stored in +version control?”

+

We will now revisit this in more detail.

+

Many people want to version control non-text files, such as images, +PDFs and Microsoft Office or LibreOffice documents. It is true that Git +can handle these filetypes (which fall under the banner of “binary” file +types). However, just because it can be done doesn’t mean it +should be done.

+

Much of Git’s magic comes from being able to do line-by-line +comparisons (“diffs”) between files. This is generally easy for +programming source code and marked up text. For non-text files, a diff +can usually only detect that the files have changed but can’t say how or +where.

+

This has various impacts on Git’s performance and will make it +difficult to compare different versions of your project.

+

For a basic example to show the difference it makes, we’re going to +go see what would have happened if Alfredo had tried using outputs from +a word processor instead of plain text.

+

Create a new directory and go into it:

+
+

BASH +

+
$ mkdir recipes-nontext
+$ cd recipes-nontext
+
+

Use a program such as Microsoft Word or LibreOffice Writer to create +a new document. Enter the same text that we began with before:

+
+

OUTPUT +

+
# Ingredients
+# Instructions
+
+

Save the document into the recipes-nontext directory +with the name of guacamole.doc. Back in the terminal, run +the usual commands for setting up a new Git repository:

+
+

BASH +

+
$ git init
+$ git add guacamole.doc
+$ git commit -m "Create a template for recipe"
+
+

Then make the same changes to guacamole.doc that we (or +Alfredo) previously made to guacamole.md.

+
+

OUTPUT +

+
# Ingredients
+- avocado
+- lemon
+- salt
+# Instructions
+
+

Save and close the word processor. Now see what Git thinks of your +changes:

+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.doc b/guacamole.doc
+index 53a66fd..6e988e9 100644
+Binary files a/guacamole.doc and b/guacamole.doc differ
+
+

Compare this to the earlier git diff obtained when using +text files:

+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,2 +1,5 @@
+ # Ingredients
++- avocado
++- lemon
++- salt
+ # Instructions
+
+

Notice how plain text files give a much more informative diff. You +can see exactly which lines changed and what the changes were.

+

An uninformative git diff is not the only consequence of +using Git on binary files. However, most of the other problems boil down +to whether or not a good diff is possible.

+

This isn’t to say you should never use Git on binary files. +A rule of thumb is that it’s OK if the binary file won’t change very +often, and if it does change, you don’t care about merging in small +differences between versions.

+

We’ve already seen how a word processed report will fail this test. +An example that passes the test is a logo for your organization or +project. Even though a logo will be stored in a binary format such as +jpg or png, you can expect it will remain +fairly static through the lifetime of your repository. On the rare +occasion that branding does change, you will probably just want to +replace the logo completely rather than merge little differences in.

+

Removing a File

+

Adding and modifying files are not the only actions one might take +when working on a project. It might be required to remove a file from +the repository.

+

Create a new file for the invisible ink:

+
+

BASH +

+
$ echo "This is where we keep the secret sauce" > invisible.md
+
+

Now add to the repository like you have learned earlier:

+
+

BASH +

+
$ git add invisible.md
+$ git commit -m 'Add secret sauce'
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working directory clean
+
+

Invisible ink is not a real food. That was a silly idea. Let us +remove it from the disk and let Git know about it:

+
+

BASH +

+
$ git rm invisible.md
+$ git status
+
+
+

OUTPUT +

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

The change has been staged. Now commit the removal, and remove the +file from the repository itself. Note that the file will be removed in +the new commit. The previous commit will still have the file, if you +were to retrieve that specific commit.

+
+

BASH +

+
$ git commit -m 'Remove info on Invisible ink.  It is not an edible sauce!'
+
+

Removing a File with Unix

+

Sometimes we might forget to remove the file through Git. If you +removed the file with Unix rm instead of using +git rm, no worries, Git is smart enough to notice the +missing file. Let us recreate the file and commit it again.

+
+

BASH +

+
$ echo "This is another way to make invisible ink" > secret.md
+$ git add secret.md
+$ git commit -m 'Add invisible ink again'
+
+

Now we remove the file with Unix rm:

+
+

BASH +

+
$ rm secret.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+   (use "git add/rm <file>..." to update what will be committed)
+   (use "git checkout -- <file>..." to discard changes in working directory)
+
+    deleted:    secret.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

See how Git has noticed that the file secret.md has been +removed from the disk. The next step is to “stage” the removal of the +file from the repository. This is done with the command +git rm just as before.

+
+

BASH +

+
$ git rm secret.md
+$ git status
+
+
+

OUTPUT +

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

The change that was made in Unix has now been staged and needs to be +committed.

+
+

BASH +

+
$ git commit -m 'Remove info on invisible ink, again!'
+
+

Renaming a File

+

Another common change when working on a project is to rename a +file.

+

Create a file for the whitesauce recipe:

+
+

BASH +

+
$ echo "Very fun recipe to do" > whitesauce.md
+
+

Add it to the repository:

+
+

BASH +

+
$ git add whitesauce.md
+$ git commit -m 'Add white sauce recipe'
+
+

We all know that white sauce has a more sophisticated name.

+

Rename the file whitesauce.md to +bechamel.md with Git:

+
+

BASH +

+
$ git mv whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes to be committed:
+  (use "git reset HEAD <file>..." to unstage)
+
+	renamed:    whitesauce.md ->  bechamel.md
+
+

The final step is commit our change to the repository:

+
+

BASH +

+
$ git commit -m 'Use the French name for the whitesauce'
+
+

Renaming a File with Unix

+

If you forgot to use Git and you used Unix mv instead of +git mv, you will have a touch more work to do but Git will +be able to deal with it. Let’s try again renaming the file, this time +with Unix mv. First, we need to recreate the +krypton.txt file:

+
+

BASH +

+
$ echo "Very fun recipe to do" > whitesauce.md
+$ git add whitesauce.md
+$ git commit -m 'Add white sauce recipe'
+
+

Let us rename the file and see what Git can figured out by +itself:

+
+

BASH +

+
$ mv whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add/rm <file>..." to update what will be committed)
+  (use "git checkout -- <file>..." to discard changes in working directory)
+
+        deleted:    whitesauce.md
+
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+    bechamel.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

Git has noticed that the file whitesauce.md has +disappeared from the file system and a new file bechamel.md +has showed up.

+

Add those changes to the staging area:

+
+

BASH +

+
$ git add whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes to be committed:
+  (use "git reset HEAD <file>..." to unstage)
+
+    renamed:    whitesauce.md -> bechamel.md
+
+
+

Notice how Git has now figured out that the +whitesauce.md has not disappeared - it has simply been +renamed.

+

The final step, as before, is to commit our change to the +repository:

+
+

BASH +

+
$ git commit -m 'Use the French name for the whitesauce'
+
+

Further .gitignore concepts

+

For additional documentation on .gitignore, please reference the official git +documentation.

+

In the ignore exercise, learners were presented with two variations +of ignoring nested files. Depending on the organization of your +repository, one may suit your needs over another. Keep in mind that the +way that Git travels along directory paths can be confusing.

+

Sometimes the ** pattern comes in handy, too, which +matches multiple directory levels. E.g. **/results/plots/* +would make git ignore the results/plots directory in any +root directory.

+
+
+ +
+
+

Ignoring Nested Files: Challenge Problem

+
+

Given a directory structure that looks like:

+
+

BASH +

+
results/data
+results/plots
+results/run001.log
+results/run002.log
+
+

And a .gitignore that looks like:

+
+

OUTPUT +

+
*.csv
+
+

How would you track all of the contents of +results/data/, including *.csv files, but +ignore the rest of results/?

+
+
+
+
+
+ +
+
+

To do this, your .gitignore would look like this:

+
+

OUTPUT +

+
*.csv                 # ignore the .csv files
+results/*             # ignore the files in the results directory
+!results/data/        # do not ignore the files in results/data
+!results/data/*       # do not ignore the .csv files in reults/data
+
+
+
+
+
+
+
+ + +
+
+ + + diff --git a/docsearch.css b/docsearch.css new file mode 100644 index 0000000000..e5f1fe1dfa --- /dev/null +++ b/docsearch.css @@ -0,0 +1,148 @@ +/* Docsearch -------------------------------------------------------------- */ +/* + Source: https://github.com/algolia/docsearch/ + License: MIT +*/ + +.algolia-autocomplete { + display: block; + -webkit-box-flex: 1; + -ms-flex: 1; + flex: 1 +} + +.algolia-autocomplete .ds-dropdown-menu { + width: 100%; + min-width: none; + max-width: none; + padding: .75rem 0; + background-color: #fff; + background-clip: padding-box; + border: 1px solid rgba(0, 0, 0, .1); + box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .175); +} + +@media (min-width:768px) { + .algolia-autocomplete .ds-dropdown-menu { + width: 175% + } +} + +.algolia-autocomplete .ds-dropdown-menu::before { + display: none +} + +.algolia-autocomplete .ds-dropdown-menu [class^=ds-dataset-] { + padding: 0; + background-color: rgb(255,255,255); + border: 0; + max-height: 80vh; +} + +.algolia-autocomplete .ds-dropdown-menu .ds-suggestions { + margin-top: 0 +} + +.algolia-autocomplete .algolia-docsearch-suggestion { + padding: 0; + overflow: visible +} + +.algolia-autocomplete .algolia-docsearch-suggestion--category-header { + padding: .125rem 1rem; + margin-top: 0; + font-size: 1.3em; + font-weight: 500; + color: #00008B; + border-bottom: 0 +} + +.algolia-autocomplete .algolia-docsearch-suggestion--wrapper { + float: none; + padding-top: 0 +} + +.algolia-autocomplete .algolia-docsearch-suggestion--subcategory-column { + float: none; + width: auto; + padding: 0; + text-align: left +} + +.algolia-autocomplete .algolia-docsearch-suggestion--content { + float: none; + width: auto; + padding: 0 +} + +.algolia-autocomplete .algolia-docsearch-suggestion--content::before { + display: none +} + +.algolia-autocomplete .ds-suggestion:not(:first-child) .algolia-docsearch-suggestion--category-header { + padding-top: .75rem; + margin-top: .75rem; + border-top: 1px solid rgba(0, 0, 0, .1) +} + +.algolia-autocomplete .ds-suggestion .algolia-docsearch-suggestion--subcategory-column { + display: block; + padding: .1rem 1rem; + margin-bottom: 0.1; + font-size: 1.0em; + font-weight: 400 + /* display: none */ +} + +.algolia-autocomplete .algolia-docsearch-suggestion--title { + display: block; + padding: .25rem 1rem; + margin-bottom: 0; + font-size: 0.9em; + font-weight: 400 +} + +.algolia-autocomplete .algolia-docsearch-suggestion--text { + padding: 0 1rem .5rem; + margin-top: -.25rem; + font-size: 0.8em; + font-weight: 400; + line-height: 1.25 +} + +.algolia-autocomplete .algolia-docsearch-footer { + width: 110px; + height: 20px; + z-index: 3; + margin-top: 10.66667px; + float: right; + font-size: 0; + line-height: 0; +} + +.algolia-autocomplete .algolia-docsearch-footer--logo { + background-image: url("data:image/svg+xml;utf8,"); + background-repeat: no-repeat; + background-position: 50%; + background-size: 100%; + overflow: hidden; + text-indent: -9000px; + width: 100%; + height: 100%; + display: block; + transform: translate(-8px); +} + +.algolia-autocomplete .algolia-docsearch-suggestion--highlight { + color: #FF8C00; + background: rgba(232, 189, 54, 0.1) +} + + +.algolia-autocomplete .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight { + box-shadow: inset 0 -2px 0 0 rgba(105, 105, 105, .5) +} + +.algolia-autocomplete .ds-suggestion.ds-cursor .algolia-docsearch-suggestion--content { + background-color: rgba(192, 192, 192, .15) +} diff --git a/docsearch.js b/docsearch.js new file mode 100644 index 0000000000..b35504cd3a --- /dev/null +++ b/docsearch.js @@ -0,0 +1,85 @@ +$(function() { + + // register a handler to move the focus to the search bar + // upon pressing shift + "/" (i.e. "?") + $(document).on('keydown', function(e) { + if (e.shiftKey && e.keyCode == 191) { + e.preventDefault(); + $("#search-input").focus(); + } + }); + + $(document).ready(function() { + // do keyword highlighting + /* modified from https://jsfiddle.net/julmot/bL6bb5oo/ */ + var mark = function() { + + var referrer = document.URL ; + var paramKey = "q" ; + + if (referrer.indexOf("?") !== -1) { + var qs = referrer.substr(referrer.indexOf('?') + 1); + var qs_noanchor = qs.split('#')[0]; + var qsa = qs_noanchor.split('&'); + var keyword = ""; + + for (var i = 0; i < qsa.length; i++) { + var currentParam = qsa[i].split('='); + + if (currentParam.length !== 2) { + continue; + } + + if (currentParam[0] == paramKey) { + keyword = decodeURIComponent(currentParam[1].replace(/\+/g, "%20")); + } + } + + if (keyword !== "") { + $(".contents").unmark({ + done: function() { + $(".contents").mark(keyword); + } + }); + } + } + }; + + mark(); + }); +}); + +/* Search term highlighting ------------------------------*/ + +function matchedWords(hit) { + var words = []; + + var hierarchy = hit._highlightResult.hierarchy; + // loop to fetch from lvl0, lvl1, etc. + for (var idx in hierarchy) { + words = words.concat(hierarchy[idx].matchedWords); + } + + var content = hit._highlightResult.content; + if (content) { + words = words.concat(content.matchedWords); + } + + // return unique words + var words_uniq = [...new Set(words)]; + return words_uniq; +} + +function updateHitURL(hit) { + + var words = matchedWords(hit); + var url = ""; + + if (hit.anchor) { + url = hit.url_without_anchor + '?q=' + escape(words.join(" ")) + '#' + hit.anchor; + } else { + url = hit.url + '?q=' + escape(words.join(" ")); + } + + return url; +} diff --git a/favicon-16x16.png b/favicon-16x16.png new file mode 100644 index 0000000000..d44f8acb47 Binary files /dev/null and b/favicon-16x16.png differ diff --git a/favicon-32x32.png b/favicon-32x32.png new file mode 100644 index 0000000000..63441d4c30 Binary files /dev/null and b/favicon-32x32.png differ diff --git a/favicons/cp/apple-touch-icon-114x114.png b/favicons/cp/apple-touch-icon-114x114.png new file mode 100644 index 0000000000..a60b75810e Binary files /dev/null and b/favicons/cp/apple-touch-icon-114x114.png differ diff --git a/favicons/cp/apple-touch-icon-120x120.png b/favicons/cp/apple-touch-icon-120x120.png new file mode 100644 index 0000000000..8f20a8f12b Binary files /dev/null and b/favicons/cp/apple-touch-icon-120x120.png differ diff --git a/favicons/cp/apple-touch-icon-144x144.png b/favicons/cp/apple-touch-icon-144x144.png new file mode 100644 index 0000000000..4be151b14c Binary files /dev/null and b/favicons/cp/apple-touch-icon-144x144.png differ diff --git a/favicons/cp/apple-touch-icon-152x152.png b/favicons/cp/apple-touch-icon-152x152.png new file mode 100644 index 0000000000..7d1d94395d Binary files /dev/null and b/favicons/cp/apple-touch-icon-152x152.png differ diff --git a/favicons/cp/apple-touch-icon-57x57.png b/favicons/cp/apple-touch-icon-57x57.png new file mode 100644 index 0000000000..92309cef29 Binary files /dev/null and b/favicons/cp/apple-touch-icon-57x57.png differ diff --git a/favicons/cp/apple-touch-icon-60x60.png b/favicons/cp/apple-touch-icon-60x60.png new file mode 100644 index 0000000000..de8148e58f Binary files /dev/null and b/favicons/cp/apple-touch-icon-60x60.png differ diff --git a/favicons/cp/apple-touch-icon-72x72.png b/favicons/cp/apple-touch-icon-72x72.png new file mode 100644 index 0000000000..81d7e3d830 Binary files /dev/null and b/favicons/cp/apple-touch-icon-72x72.png differ diff --git a/favicons/cp/apple-touch-icon-76x76.png b/favicons/cp/apple-touch-icon-76x76.png new file mode 100644 index 0000000000..15bca5c779 Binary files /dev/null and b/favicons/cp/apple-touch-icon-76x76.png differ diff --git a/favicons/cp/favicon-128.png b/favicons/cp/favicon-128.png new file mode 100644 index 0000000000..e612cdc15e Binary files /dev/null and b/favicons/cp/favicon-128.png differ diff --git a/favicons/cp/favicon-16x16.png b/favicons/cp/favicon-16x16.png new file mode 100644 index 0000000000..65b3311122 Binary files /dev/null and b/favicons/cp/favicon-16x16.png differ diff --git a/favicons/cp/favicon-196x196.png b/favicons/cp/favicon-196x196.png new file mode 100644 index 0000000000..0da938b273 Binary files /dev/null and b/favicons/cp/favicon-196x196.png differ diff --git a/favicons/cp/favicon-32x32.png b/favicons/cp/favicon-32x32.png new file mode 100644 index 0000000000..0c1442e391 Binary files /dev/null and b/favicons/cp/favicon-32x32.png differ diff --git a/favicons/cp/favicon-96x96.png b/favicons/cp/favicon-96x96.png new file mode 100644 index 0000000000..bed74ec8d3 Binary files /dev/null and b/favicons/cp/favicon-96x96.png differ diff --git a/favicons/cp/favicon.ico b/favicons/cp/favicon.ico new file mode 100644 index 0000000000..4f2f2f11f4 Binary files /dev/null and b/favicons/cp/favicon.ico differ diff --git a/favicons/cp/mstile-144x144.png b/favicons/cp/mstile-144x144.png new file mode 100644 index 0000000000..4be151b14c Binary files /dev/null and b/favicons/cp/mstile-144x144.png differ diff --git a/favicons/cp/mstile-150x150.png b/favicons/cp/mstile-150x150.png new file mode 100644 index 0000000000..bf7ad5e79f Binary files /dev/null and b/favicons/cp/mstile-150x150.png differ diff --git a/favicons/cp/mstile-310x150.png b/favicons/cp/mstile-310x150.png new file mode 100644 index 0000000000..6ac8048435 Binary files /dev/null and b/favicons/cp/mstile-310x150.png differ diff --git a/favicons/cp/mstile-310x310.png b/favicons/cp/mstile-310x310.png new file mode 100644 index 0000000000..b778147505 Binary files /dev/null and b/favicons/cp/mstile-310x310.png differ diff --git a/favicons/cp/mstile-70x70.png b/favicons/cp/mstile-70x70.png new file mode 100644 index 0000000000..e612cdc15e Binary files /dev/null and b/favicons/cp/mstile-70x70.png differ diff --git a/favicons/dc/apple-touch-icon-114x114.png b/favicons/dc/apple-touch-icon-114x114.png new file mode 100644 index 0000000000..edafbda139 Binary files /dev/null and b/favicons/dc/apple-touch-icon-114x114.png differ diff --git a/favicons/dc/apple-touch-icon-120x120.png b/favicons/dc/apple-touch-icon-120x120.png new file mode 100644 index 0000000000..ee145ec5cd Binary files /dev/null and b/favicons/dc/apple-touch-icon-120x120.png differ diff --git a/favicons/dc/apple-touch-icon-144x144.png b/favicons/dc/apple-touch-icon-144x144.png new file mode 100644 index 0000000000..bf50701441 Binary files /dev/null and b/favicons/dc/apple-touch-icon-144x144.png differ diff --git a/favicons/dc/apple-touch-icon-152x152.png b/favicons/dc/apple-touch-icon-152x152.png new file mode 100644 index 0000000000..bd596c8168 Binary files /dev/null and b/favicons/dc/apple-touch-icon-152x152.png differ diff --git a/favicons/dc/apple-touch-icon-57x57.png b/favicons/dc/apple-touch-icon-57x57.png new file mode 100644 index 0000000000..61c1527350 Binary files /dev/null and b/favicons/dc/apple-touch-icon-57x57.png differ diff --git a/favicons/dc/apple-touch-icon-60x60.png b/favicons/dc/apple-touch-icon-60x60.png new file mode 100644 index 0000000000..9daad36337 Binary files /dev/null and b/favicons/dc/apple-touch-icon-60x60.png differ diff --git a/favicons/dc/apple-touch-icon-72x72.png b/favicons/dc/apple-touch-icon-72x72.png new file mode 100644 index 0000000000..2069520fc8 Binary files /dev/null and b/favicons/dc/apple-touch-icon-72x72.png differ diff --git a/favicons/dc/apple-touch-icon-76x76.png b/favicons/dc/apple-touch-icon-76x76.png new file mode 100644 index 0000000000..3db01ca7d1 Binary files /dev/null and b/favicons/dc/apple-touch-icon-76x76.png differ diff --git a/favicons/dc/favicon-128.png b/favicons/dc/favicon-128.png new file mode 100644 index 0000000000..9e3de2a494 Binary files /dev/null and b/favicons/dc/favicon-128.png differ diff --git a/favicons/dc/favicon-16x16.png b/favicons/dc/favicon-16x16.png new file mode 100644 index 0000000000..4c9f9b8c57 Binary files /dev/null and b/favicons/dc/favicon-16x16.png differ diff --git a/favicons/dc/favicon-196x196.png b/favicons/dc/favicon-196x196.png new file mode 100644 index 0000000000..588afc2130 Binary files /dev/null and b/favicons/dc/favicon-196x196.png differ diff --git a/favicons/dc/favicon-32x32.png b/favicons/dc/favicon-32x32.png new file mode 100644 index 0000000000..9c2ecbfbe2 Binary files /dev/null and b/favicons/dc/favicon-32x32.png differ diff --git a/favicons/dc/favicon-96x96.png b/favicons/dc/favicon-96x96.png new file mode 100644 index 0000000000..ff13fc06e1 Binary files /dev/null and b/favicons/dc/favicon-96x96.png differ diff --git a/favicons/dc/favicon.ico b/favicons/dc/favicon.ico new file mode 100644 index 0000000000..e4715f3294 Binary files /dev/null and b/favicons/dc/favicon.ico differ diff --git a/favicons/dc/mstile-144x144.png b/favicons/dc/mstile-144x144.png new file mode 100644 index 0000000000..bf50701441 Binary files /dev/null and b/favicons/dc/mstile-144x144.png differ diff --git a/favicons/dc/mstile-150x150.png b/favicons/dc/mstile-150x150.png new file mode 100644 index 0000000000..c5844cca37 Binary files /dev/null and b/favicons/dc/mstile-150x150.png differ diff --git a/favicons/dc/mstile-310x150.png b/favicons/dc/mstile-310x150.png new file mode 100644 index 0000000000..786813af88 Binary files /dev/null and b/favicons/dc/mstile-310x150.png differ diff --git a/favicons/dc/mstile-310x310.png b/favicons/dc/mstile-310x310.png new file mode 100644 index 0000000000..9580653c6d Binary files /dev/null and b/favicons/dc/mstile-310x310.png differ diff --git a/favicons/dc/mstile-70x70.png b/favicons/dc/mstile-70x70.png new file mode 100644 index 0000000000..9e3de2a494 Binary files /dev/null and b/favicons/dc/mstile-70x70.png differ diff --git a/favicons/lc/apple-touch-icon-114x114.png b/favicons/lc/apple-touch-icon-114x114.png new file mode 100644 index 0000000000..6c83127cad Binary files /dev/null and b/favicons/lc/apple-touch-icon-114x114.png differ diff --git a/favicons/lc/apple-touch-icon-120x120.png b/favicons/lc/apple-touch-icon-120x120.png new file mode 100644 index 0000000000..8334648f14 Binary files /dev/null and b/favicons/lc/apple-touch-icon-120x120.png differ diff --git a/favicons/lc/apple-touch-icon-144x144.png b/favicons/lc/apple-touch-icon-144x144.png new file mode 100644 index 0000000000..5f32151edb Binary files /dev/null and b/favicons/lc/apple-touch-icon-144x144.png differ diff --git a/favicons/lc/apple-touch-icon-152x152.png b/favicons/lc/apple-touch-icon-152x152.png new file mode 100644 index 0000000000..4e5c177ce5 Binary files /dev/null and b/favicons/lc/apple-touch-icon-152x152.png differ diff --git a/favicons/lc/apple-touch-icon-57x57.png b/favicons/lc/apple-touch-icon-57x57.png new file mode 100644 index 0000000000..61f9c9c74c Binary files /dev/null and b/favicons/lc/apple-touch-icon-57x57.png differ diff --git a/favicons/lc/apple-touch-icon-60x60.png b/favicons/lc/apple-touch-icon-60x60.png new file mode 100644 index 0000000000..ccb5ada1c8 Binary files /dev/null and b/favicons/lc/apple-touch-icon-60x60.png differ diff --git a/favicons/lc/apple-touch-icon-72x72.png b/favicons/lc/apple-touch-icon-72x72.png new file mode 100644 index 0000000000..517d459afc Binary files /dev/null and b/favicons/lc/apple-touch-icon-72x72.png differ diff --git a/favicons/lc/apple-touch-icon-76x76.png b/favicons/lc/apple-touch-icon-76x76.png new file mode 100644 index 0000000000..17454b311d Binary files /dev/null and b/favicons/lc/apple-touch-icon-76x76.png differ diff --git a/favicons/lc/favicon-128.png b/favicons/lc/favicon-128.png new file mode 100644 index 0000000000..9d781c9017 Binary files /dev/null and b/favicons/lc/favicon-128.png differ diff --git a/favicons/lc/favicon-16x16.png b/favicons/lc/favicon-16x16.png new file mode 100644 index 0000000000..3c20abcc09 Binary files /dev/null and b/favicons/lc/favicon-16x16.png differ diff --git a/favicons/lc/favicon-196x196.png b/favicons/lc/favicon-196x196.png new file mode 100644 index 0000000000..46baaf8f90 Binary files /dev/null and b/favicons/lc/favicon-196x196.png differ diff --git a/favicons/lc/favicon-32x32.png b/favicons/lc/favicon-32x32.png new file mode 100644 index 0000000000..ed6701ea12 Binary files /dev/null and b/favicons/lc/favicon-32x32.png differ diff --git a/favicons/lc/favicon-96x96.png b/favicons/lc/favicon-96x96.png new file mode 100644 index 0000000000..bc468c73a3 Binary files /dev/null and b/favicons/lc/favicon-96x96.png differ diff --git a/favicons/lc/favicon.ico b/favicons/lc/favicon.ico new file mode 100644 index 0000000000..5c14e80916 Binary files /dev/null and b/favicons/lc/favicon.ico differ diff --git a/favicons/lc/mstile-144x144.png b/favicons/lc/mstile-144x144.png new file mode 100644 index 0000000000..5f32151edb Binary files /dev/null and b/favicons/lc/mstile-144x144.png differ diff --git a/favicons/lc/mstile-150x150.png b/favicons/lc/mstile-150x150.png new file mode 100644 index 0000000000..924953a845 Binary files /dev/null and b/favicons/lc/mstile-150x150.png differ diff --git a/favicons/lc/mstile-310x150.png b/favicons/lc/mstile-310x150.png new file mode 100644 index 0000000000..e4dcda444d Binary files /dev/null and b/favicons/lc/mstile-310x150.png differ diff --git a/favicons/lc/mstile-310x310.png b/favicons/lc/mstile-310x310.png new file mode 100644 index 0000000000..a12c87632b Binary files /dev/null and b/favicons/lc/mstile-310x310.png differ diff --git a/favicons/lc/mstile-70x70.png b/favicons/lc/mstile-70x70.png new file mode 100644 index 0000000000..9d781c9017 Binary files /dev/null and b/favicons/lc/mstile-70x70.png differ diff --git a/favicons/swc/apple-touch-icon-114x114.png b/favicons/swc/apple-touch-icon-114x114.png new file mode 100644 index 0000000000..e5125f8c4b Binary files /dev/null and b/favicons/swc/apple-touch-icon-114x114.png differ diff --git a/favicons/swc/apple-touch-icon-120x120.png b/favicons/swc/apple-touch-icon-120x120.png new file mode 100644 index 0000000000..0f97a0aecc Binary files /dev/null and b/favicons/swc/apple-touch-icon-120x120.png differ diff --git a/favicons/swc/apple-touch-icon-144x144.png b/favicons/swc/apple-touch-icon-144x144.png new file mode 100644 index 0000000000..7441446cc3 Binary files /dev/null and b/favicons/swc/apple-touch-icon-144x144.png differ diff --git a/favicons/swc/apple-touch-icon-152x152.png b/favicons/swc/apple-touch-icon-152x152.png new file mode 100644 index 0000000000..45cc338e5d Binary files /dev/null and b/favicons/swc/apple-touch-icon-152x152.png differ diff --git a/favicons/swc/apple-touch-icon-57x57.png b/favicons/swc/apple-touch-icon-57x57.png new file mode 100644 index 0000000000..e180a4a320 Binary files /dev/null and b/favicons/swc/apple-touch-icon-57x57.png differ diff --git a/favicons/swc/apple-touch-icon-60x60.png b/favicons/swc/apple-touch-icon-60x60.png new file mode 100644 index 0000000000..c96fd6ce7a Binary files /dev/null and b/favicons/swc/apple-touch-icon-60x60.png differ diff --git a/favicons/swc/apple-touch-icon-72x72.png b/favicons/swc/apple-touch-icon-72x72.png new file mode 100644 index 0000000000..aae014aa78 Binary files /dev/null and b/favicons/swc/apple-touch-icon-72x72.png differ diff --git a/favicons/swc/apple-touch-icon-76x76.png b/favicons/swc/apple-touch-icon-76x76.png new file mode 100644 index 0000000000..2167f94a7e Binary files /dev/null and b/favicons/swc/apple-touch-icon-76x76.png differ diff --git a/favicons/swc/favicon-128.png b/favicons/swc/favicon-128.png new file mode 100644 index 0000000000..f61df620c0 Binary files /dev/null and b/favicons/swc/favicon-128.png differ diff --git a/favicons/swc/favicon-16x16.png b/favicons/swc/favicon-16x16.png new file mode 100644 index 0000000000..2d20a40612 Binary files /dev/null and b/favicons/swc/favicon-16x16.png differ diff --git a/favicons/swc/favicon-196x196.png b/favicons/swc/favicon-196x196.png new file mode 100644 index 0000000000..2a20d3a6fe Binary files /dev/null and b/favicons/swc/favicon-196x196.png differ diff --git a/favicons/swc/favicon-32x32.png b/favicons/swc/favicon-32x32.png new file mode 100644 index 0000000000..f622b73a19 Binary files /dev/null and b/favicons/swc/favicon-32x32.png differ diff --git a/favicons/swc/favicon-96x96.png b/favicons/swc/favicon-96x96.png new file mode 100644 index 0000000000..5e57f66a56 Binary files /dev/null and b/favicons/swc/favicon-96x96.png differ diff --git a/favicons/swc/favicon.ico b/favicons/swc/favicon.ico new file mode 100644 index 0000000000..f771790f29 Binary files /dev/null and b/favicons/swc/favicon.ico differ diff --git a/favicons/swc/mstile-144x144.png b/favicons/swc/mstile-144x144.png new file mode 100644 index 0000000000..7441446cc3 Binary files /dev/null and b/favicons/swc/mstile-144x144.png differ diff --git a/favicons/swc/mstile-150x150.png b/favicons/swc/mstile-150x150.png new file mode 100644 index 0000000000..d1594bcb89 Binary files /dev/null and b/favicons/swc/mstile-150x150.png differ diff --git a/favicons/swc/mstile-310x150.png b/favicons/swc/mstile-310x150.png new file mode 100644 index 0000000000..f7d58b2b9f Binary files /dev/null and b/favicons/swc/mstile-310x150.png differ diff --git a/favicons/swc/mstile-310x310.png b/favicons/swc/mstile-310x310.png new file mode 100644 index 0000000000..b632b421c5 Binary files /dev/null and b/favicons/swc/mstile-310x310.png differ diff --git a/favicons/swc/mstile-70x70.png b/favicons/swc/mstile-70x70.png new file mode 100644 index 0000000000..f61df620c0 Binary files /dev/null and b/favicons/swc/mstile-70x70.png differ diff --git a/fig/RStudio_screenshot_afterclone.png b/fig/RStudio_screenshot_afterclone.png new file mode 100644 index 0000000000..268c188c42 Binary files /dev/null and b/fig/RStudio_screenshot_afterclone.png differ diff --git a/fig/RStudio_screenshot_commit.png b/fig/RStudio_screenshot_commit.png new file mode 100644 index 0000000000..66aeeab724 Binary files /dev/null and b/fig/RStudio_screenshot_commit.png differ diff --git a/fig/RStudio_screenshot_editfiles.png b/fig/RStudio_screenshot_editfiles.png new file mode 100644 index 0000000000..251aed4bdf Binary files /dev/null and b/fig/RStudio_screenshot_editfiles.png differ diff --git a/fig/RStudio_screenshot_existingdirectory.png b/fig/RStudio_screenshot_existingdirectory.png new file mode 100644 index 0000000000..27658eee10 Binary files /dev/null and b/fig/RStudio_screenshot_existingdirectory.png differ diff --git a/fig/RStudio_screenshot_gitignore.png b/fig/RStudio_screenshot_gitignore.png new file mode 100644 index 0000000000..225e101784 Binary files /dev/null and b/fig/RStudio_screenshot_gitignore.png differ diff --git a/fig/RStudio_screenshot_history.png b/fig/RStudio_screenshot_history.png new file mode 100644 index 0000000000..52600748e4 Binary files /dev/null and b/fig/RStudio_screenshot_history.png differ diff --git a/fig/RStudio_screenshot_navigateexisting.png b/fig/RStudio_screenshot_navigateexisting.png new file mode 100644 index 0000000000..ef8fcf8c1b Binary files /dev/null and b/fig/RStudio_screenshot_navigateexisting.png differ diff --git a/fig/RStudio_screenshot_newproject.png b/fig/RStudio_screenshot_newproject.png new file mode 100644 index 0000000000..a4f7f79f45 Binary files /dev/null and b/fig/RStudio_screenshot_newproject.png differ diff --git a/fig/RStudio_screenshot_review.png b/fig/RStudio_screenshot_review.png new file mode 100644 index 0000000000..3854b8623a Binary files /dev/null and b/fig/RStudio_screenshot_review.png differ diff --git a/fig/RStudio_screenshot_viewhistory.png b/fig/RStudio_screenshot_viewhistory.png new file mode 100644 index 0000000000..4917409351 Binary files /dev/null and b/fig/RStudio_screenshot_viewhistory.png differ diff --git a/fig/conflict.svg b/fig/conflict.svg new file mode 100644 index 0000000000..ce24496a2c --- /dev/null +++ b/fig/conflict.svg @@ -0,0 +1,309 @@ + + + +image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fig/git-committing.svg b/fig/git-committing.svg new file mode 100644 index 0000000000..71b9dcae0c --- /dev/null +++ b/fig/git-committing.svg @@ -0,0 +1,436 @@ + + + +image/svg+xml.git +FILE1.txt +FILE2.txt +git commit +staging area +repository +git add FILE2.txt +git add FILE1.txt + \ No newline at end of file diff --git a/fig/git-freshly-made-github-repo.svg b/fig/git-freshly-made-github-repo.svg new file mode 100644 index 0000000000..aa497cf0d0 --- /dev/null +++ b/fig/git-freshly-made-github-repo.svg @@ -0,0 +1,315 @@ + + + +image/svg+xml.git +https://github.com/alflin/recipes.git +.git +~/alflin/recipes +git add +git commit +staging area +repository + \ No newline at end of file diff --git a/fig/git-restore.svg b/fig/git-restore.svg new file mode 100644 index 0000000000..615ca07b29 --- /dev/null +++ b/fig/git-restore.svg @@ -0,0 +1,111 @@ + + + + + + + + .git + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + FILE1.txt + + + + + + + + + + + + + + FILE2.txt + + + HEAD + + HEAD~1 + + HEAD~2 + + 892134f + + f22b25e + + 3a54f76 + + + + + + + + + git restore -s HEAD~1 .or git restore -s f22b25e . + + + repository + + diff --git a/fig/git-staging-area.svg b/fig/git-staging-area.svg new file mode 100644 index 0000000000..c74c2987ee --- /dev/null +++ b/fig/git-staging-area.svg @@ -0,0 +1,93 @@ + + + + + + + + .git + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + git add + + + + + + git commit + + staging area + + repository + + diff --git a/fig/git_staging.svg b/fig/git_staging.svg new file mode 100644 index 0000000000..3db5b3b5ac --- /dev/null +++ b/fig/git_staging.svg @@ -0,0 +1,675 @@ + + + +image/svg+xmla2129cb + +892134f + +59e230a + +3a54f76 + +43fe423 + + + + branch + +main + +staging area + +git add file2.txt + +git add file1.txt + +HEADHEAD~1HEAD~2 + +git commit + +git restore file1.txt + + + diff --git a/fig/github-add-collaborators.png b/fig/github-add-collaborators.png new file mode 100644 index 0000000000..4dede75108 Binary files /dev/null and b/fig/github-add-collaborators.png differ diff --git a/fig/github-change-repo-string.png b/fig/github-change-repo-string.png new file mode 100644 index 0000000000..7ffe1bfda6 Binary files /dev/null and b/fig/github-change-repo-string.png differ diff --git a/fig/github-collaboration.svg b/fig/github-collaboration.svg new file mode 100644 index 0000000000..8e72a64390 --- /dev/null +++ b/fig/github-collaboration.svg @@ -0,0 +1,767 @@ + + + +image/svg+xml +.gitorigin https://github.com/alflin/recipes.git +~/alflin/recipes +git add +git commit +staging area +repository +.git +https://github.com/alflin/recipes.git +repository +git clone +.gitorigin https://github.com/alflin/recipes.git +~/jimmy/recipes +git add +git commit +staging area +repository + \ No newline at end of file diff --git a/fig/github-create-repo-01.png b/fig/github-create-repo-01.png new file mode 100644 index 0000000000..6dc6bf2195 Binary files /dev/null and b/fig/github-create-repo-01.png differ diff --git a/fig/github-create-repo-02.png b/fig/github-create-repo-02.png new file mode 100644 index 0000000000..5981881cda Binary files /dev/null and b/fig/github-create-repo-02.png differ diff --git a/fig/github-create-repo-03.png b/fig/github-create-repo-03.png new file mode 100644 index 0000000000..ebce87d5e6 Binary files /dev/null and b/fig/github-create-repo-03.png differ diff --git a/fig/github-find-repo-string.png b/fig/github-find-repo-string.png new file mode 100644 index 0000000000..97d339bd72 Binary files /dev/null and b/fig/github-find-repo-string.png differ diff --git a/fig/github-repo-after-first-push.svg b/fig/github-repo-after-first-push.svg new file mode 100644 index 0000000000..e829035f83 --- /dev/null +++ b/fig/github-repo-after-first-push.svg @@ -0,0 +1,483 @@ + + + +image/svg+xml +.gitorigin https://github.com/alflin/recipes.git +~/alflin/recipes +git add +git commit +staging area +repository +.git +https://github.com/alflin/recipes.git +repository +git push origin + \ No newline at end of file diff --git a/fig/merge.svg b/fig/merge.svg new file mode 100644 index 0000000000..bc1378cbab --- /dev/null +++ b/fig/merge.svg @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/fig/motivatingexample.png b/fig/motivatingexample.png new file mode 100644 index 0000000000..e9320a90ee Binary files /dev/null and b/fig/motivatingexample.png differ diff --git a/fig/phd101212s.png b/fig/phd101212s.png new file mode 100644 index 0000000000..c47c428bde Binary files /dev/null and b/fig/phd101212s.png differ diff --git a/fig/play-changes.svg b/fig/play-changes.svg new file mode 100644 index 0000000000..d1a22e79bf --- /dev/null +++ b/fig/play-changes.svg @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/fig/versions.svg b/fig/versions.svg new file mode 100644 index 0000000000..96e8cab171 --- /dev/null +++ b/fig/versions.svg @@ -0,0 +1,247 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/images.html b/images.html new file mode 100644 index 0000000000..7f56c6fb35 --- /dev/null +++ b/images.html @@ -0,0 +1,635 @@ + + + + + +Version Control with Git: All Images + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Automated Version Control

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

Setting Up Git

+

Creating a Repository

+

Tracking Changes

+
+

Figure 1

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

+

Figure 2

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

Exploring History

+
+

Figure 1

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

+

Figure 2

+ +
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

Ignoring Things

+

Remotes in GitHub

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

+

Figure 5

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

+

Figure 6

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

+

Figure 7

+ +
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

+

Figure 8

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

Collaborating

+
+

Figure 1

+ +
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

+

Figure 2

+ +
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

Conflicts

+
+

Figure 1

+ +
A diagram showing a conflict that might occur when two sets of independent changes are merged

Open Science

+

Licensing

+

Citation

+

Hosting

+

Supplemental: Using Git from RStudio

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

+

Figure 5

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

+

Figure 6

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

+

Figure 7

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

+

Figure 8

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

+

Figure 9

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

+

Figure 10

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

+
+
+
+ + +
+ + +
+ + + + + diff --git a/index.html b/index.html new file mode 100644 index 0000000000..a9993dacb7 --- /dev/null +++ b/index.html @@ -0,0 +1,561 @@ + +Version Control with Git: Summary and Setup +
+ Version Control with Git +
+ +
+
+ + + + + +
+

Summary and Setup

+ + +

Jimmy and Alfredo have been hired by Ratatouille restaurant (a +special restaurant from Euphoric State University) to investigate if it +is possible to make the best recipes archive ever. They want to be able +to work on indexing the prices at the same time, but they have run into +problems doing this in the past. If they take turns, each one will spend +a lot of time waiting for the other to finish, but if they work on their +own copies and email changes back and forth things will be lost, +overwritten, or duplicated.

+

A colleague suggests using version control to manage +their work. Version control is better than mailing files back and +forth:

+
  • Nothing that is committed to version control is ever lost, unless +you work really, really hard at losing it. Since all old versions of +files are saved, it’s always possible to go back in time to see exactly +who wrote what on a particular day, or what version of a program was +used to generate a particular set of results.

  • +
  • As we have this record of who made what changes when, we know who +to ask if we have questions later on, and, if needed, revert to a +previous version, much like the “undo” feature in an editor.

  • +
  • When several people collaborate in the same project, it’s +possible to accidentally overlook or overwrite someone’s changes. The +version control system automatically notifies users whenever there’s a +conflict between one person’s work and another’s.

  • +

Teams are not the only ones to benefit from version control: lone +researchers can benefit immensely. Keeping a record of what was changed, +when, and why is extremely useful for all researchers if they ever need +to come back to the project later on (e.g., a year later, when memory +has faded).

+

Version control is the lab notebook of the digital world: it’s what +professionals use to keep track of what they’ve done and to collaborate +with other people. Every large software development project relies on +it, and most programmers use it for their small jobs as well. And it +isn’t just for software: books, papers, small data sets, and anything +that changes over time or needs to be shared can and should be stored in +a version control system.

+
+
+ +
+
+

Prerequisites

+
+

In this lesson we use Git from the Unix Shell. Some previous +experience with the shell is expected, but isn’t mandatory.

+
+
+
+ + +

Installing Git

+

Since several Carpentries lessons rely on Git, please see this +section of the workshop template for instructions on installing Git +for various operating systems.

+

Creating a GitHub Account

+

You will need an account for GitHub +to follow episodes 7 & 8 in this lesson.

+
  1. Go to https://github.com and follow the “Sign up” link at the +top-right of the window.
  2. +
  3. Follow the instructions to create an account.
  4. +
  5. Verify your email address with GitHub.
  6. +
  7. Configure multifactor authentication (see below).
  8. +
+

Multi-factor Authentication

+

In 2023, GitHub introduced a requirement for all accounts to have multi-factor +authentication (2FA) configured for extra security. Several options +exist for setting up 2FA, which are summarised here:

+
  1. If you already use an authenticator app, like Google +Authenticator or Duo +Mobile on your smartphone for example, add +GitHub to that app.
  2. +
  3. If you have access to a smartphone but do not already use an +authenticator app, install one and add +GitHub to the app.
  4. +
  5. If you do not have access to a smartphone or do not want to install +an authenticator app, you have two options: +
    1. +set +up 2FA via text message (list +of countries where authentication by SMS is supported), or
    2. +
    3. +use +a hardware security key like YubiKey +or the Google +Titan key.
    4. +
  6. +

The GitHub documentation provides more +details about configuring 2FA.

+
+

Preparing Your Working Directory

+

We’ll do our work in the Desktop folder so make sure you +change your working directory to it with:

+
+

BASH +

+
$ cd
+$ cd Desktop
+
+
+ + +
+
+ + + diff --git a/instructor-notes.html b/instructor-notes.html new file mode 100644 index 0000000000..db33b8c687 --- /dev/null +++ b/instructor-notes.html @@ -0,0 +1,899 @@ + + + + + +Version Control with Git: Instructor Notes + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+

Instructor Notes

+ + +

Using a software tool to handle the versions of your project files +lets you focus on the more interesting/innovative aspects of your +project.

+
    +
  • Version control’s advantages +
      +
    • It’s easy to set up
    • +
    • Every copy of a Git repository is a full backup of a project and its +history
    • +
    • A few easy-to-remember commands are all you need for most day-to-day +version control tasks
    • +
    • The GitHub hosting service +provides a web-based collaboration service
    • +
    +
  • +
  • Two main concepts +
      +
    • +commit: a recorded set of changes in your project’s +files
    • +
    • +repository: the history of all your project’s commits
    • +
    +
  • +
  • Why use GitHub? +
      +
    • No need for a server: easy to set up
    • +
    • GitHub’s strong community: your colleagues are probably already +there
    • +
    +
  • +
+

Overall +

+
+

Version control might be the most important topic we teach, but Git +is definitely the most complicated tool. However, GitHub presently +dominates the open software repository landscape, so the time and effort +required to teach fundamental Git is justified and worthwhile.

+

Because of this complexity, we don’t teach novice learners about many +interesting topics, such as branching, hashes, and commit objects.

+

Instead we try to convince them that version control is useful for +researchers working in teams or not, because it is

+
    +
  • a better way to “undo” changes,
  • +
  • a better way to collaborate than mailing files back and forth, +and
  • +
  • a better way to share your code and other scientific work with the +world.
  • +

Teaching Notes +

+
+
    +
  • You can “split” your shell so that recent commands remain in view +using this +script.

  • +
  • Make sure the network is working before starting this +lesson.

  • +
  • Drawings are particularly useful in this lesson: if you have a +whiteboard, use +it!

  • +
  • Version control is usually not the first subject in a workshop, +so get learners to create a GitHub account after the session before. +Remind learners that the username and email they use for GitHub (and +setup during Git configuration) will be viewable to the public by +default. However, there are many reasons why a learner may not want +their personal information viewable, and GitHub has resources +for keeping an email address private.

  • +
  • If some learners are using Windows, there will inevitably be +issues merging files with different line endings. (Even if everyone’s on +some flavor of Unix, different editors may or may not add a newline to +the last line of a file.) Take a moment to explain these issues, since +learners will almost certainly trip over them again. If learners are +running into line ending problems, GitHub has a page +that helps with troubleshooting. Specifically, the section +on refreshing a repository may be helpful if learners need to change +the core.autocrlf setting after already having made one or +more commits.

  • +
  • We don’t use a Git GUI in these notes because we haven’t found +one that installs easily and runs reliably on the three major operating +systems, and because we want learners to understand what commands are +being run. That said, instructors should demo a GUI on their desktop at +some point during this lesson and point learners at this page.

  • +
  • Instructors should show learners graphical diff/merge tools like +DiffMerge.

  • +
  • When appropriate, explain that we teach Git rather than CVS, +Subversion, or Mercurial primarily because of GitHub’s growing +popularity: CVS and Subversion are now seen as legacy systems, and +Mercurial isn’t nearly as widely used in the sciences right +now.

  • +
  • +

    Further resources:

    + +
  • +

+Automated Version Control +

+
+
    +
  • Ask, “Who uses ‘undo’ in their editor?” All say “Me”. ‘Undo’ is +the simplest form of version control.

  • +
  • Give learners a five-minute overview of what version control does +for them before diving into the watch-and-do practicals. Most of them +will have tried to co-author papers by emailing files back and forth, or +will have biked into the office only to realize that the USB key with +last night’s work is still on the kitchen table. Instructors can also +make jokes about directories with names like “final version”, “final +version revised”, “final version with reviewer three’s corrections”, +“really final version”, and, “come on this really has to be the last +version” to motivate version control as a better way to collaborate and +as a better way to back work up.

  • +

+Setting Up Git +

+
+
    +
  • +

    We suggest instructors and students use nano as the +text editor for this lessons because

    +
      +
    • it runs in all three major operating systems,
    • +
    • it runs inside the shell (switching windows can be confusing to +students), and
    • +
    • it has shortcut help at the bottom of the window.
    • +
    +

    Please point out to students during setup that they can and should +use another text editor if they’re already familiar with it.

    +
  • +
  • When setting up Git, be very clear what learners have to enter: +it is common for them to edit the instructor’s details (e.g. email). +Check at the end using git config --list.

  • +
  • When setting up the default branch name, if learners have a Git +version older than 2.28, the default branch name can be changed for the +lesson using git branch -M main if there are currently +commits in the repository, or git checkout -b main if there +are no commits/the repository is completely empty.

  • +

+Creating a Repository +

+
+
    +
  • When you do git status, Mac users may see a +.DS_Store file showing as untracked. This a file that Mac +OS creates in each directory.

  • +
  • +

    The challenge “Places to create repositories” tries to reinforce +the idea that the .git folder contains the whole Git repo +and deleting this folder undoes a git init. It also gives +the learner the way to fix the common mistake of putting unwanted +folders (like Desktop) under version control.

    +

    Instead of removing the .git folder directly, you can +choose to move it first to a safer directory and remove it from +there:

    +
    +

    BASH +

    +
    $ mv .git temp_git
    +$ rm -rf  temp_git
    +
    +

    The challenge suggests that it is a bad idea to create a Git repo +inside another repo. For more discussion on this topic, please see this +issue.

    +
  • +

+Tracking Changes +

+
+
    +
  • It’s important that learners do a full commit cycle by themselves +(make changes, git diff, git add, and +git commit). The “bio repository” challenge +does that.

  • +
  • This is a good moment to show a diff with a graphical diff tool. +If you skip it because you’re short on time, show it once in +GitHub.

  • +
  • One thing may cause confusion is recovering old versions. If, +instead of doing $ git checkout f22b25e guacamole.md, +someone does $ git checkout f22b25e, they wind up in the +“detached HEAD” state and confusion abounds. It’s then possible to keep +on committing, but things like git push origin main a bit +later will not give easily comprehensible results. It also makes it look +like commits can be lost. To “re-attach” HEAD, use +git checkout main.

  • +
  • This is a good moment to show a log within a Git GUI. If you skip +it because you’re short on time, show it once in GitHub.

  • +

+Ignoring Things +

+
+

Just remember that you can use wildcards and regular expressions to +ignore a particular set of files in .gitignore.

+

+Remotes in GitHub +

+
+
    +
  • Make it clear that Git and GitHub are not the same thing: Git is +an open source version control tool, GitHub is a company that hosts Git +repositories in the web and provides a web interface to interact with +repos they host.

  • +
  • It is very useful to draw a diagram showing the different +repositories involved.

  • +
  • When pushing to a remote, the output from Git can vary slightly +depending on what leaners execute. The lesson displays the output from +git if a learner executes git push origin main. However, +some learners might use syntax suggested by GitHub for pushing to a +remote with an existing repository, which is +git push -u origin main. Learners using syntax from GitHub, +git push -u origin main, will have slightly different +output, including the line +Branch main set up to track remote branch main from origin by rebasing.

  • +

+Collaborating +

+
+
    +
  • Decide in advance whether all the learners will work in one +shared repository, or whether they will work in pairs (or other small +groups) in separate repositories. The former is easier to set up; the +latter runs more smoothly.

  • +
  • Role playing between two instructors can be effective when +teaching the collaboration and conflict sections of the lesson. One +instructor can play the role of the repository owner, while the second +instructor can play the role of the collaborator. If it is possible, try +to use two projectors so that the computer screens of both instructors +can be seen. This makes for a very clear illustration to the students as +to who does what.

  • +
  • It is also effective to pair up students during this lesson and +assign one member of the pair to take the role of the owner and the +other the role of the collaborator. In this setup, challenges can +include asking the collaborator to make a change, commit it, and push +the change to the remote repository so that the owner can then retrieve +it, and vice-versa. The role playing between the instructors can get a +bit “dramatic” in the conflicts part of the lesson if the instructors +want to inject some humor into the room.

  • +
  • If you don’t have two projectors, have two instructors at the +front of the room. Each instructor does their piece of the collaboration +demonstration on their own computer and then passes the projector cord +back and forth with the other instructor when it’s time for them to do +the other part of the collaborative workflow. It takes less than 10 +seconds for each switchover, so it doesn’t interrupt the flow of the +lesson. And of course it helps to give each of the instructors a +different-colored hat, or put different-colored sticky notes on their +foreheads.

  • +
  • +

    If you’re the only instructor, the best way to create is clone +the two repos in your Desktop, but under different names, e.g., pretend +one is your computer at work:

    +
    +

    BASH +

    +
    $ git clone https://github.com/alflin/recipes.git recipes-at-work
    +
    +
  • +
  • +

    It’s very common that learners mistype the remote alias or the +remote URL when adding a remote, so they cannot push. You +can diagnose this with git remote -v and checking carefully +for typos.

    +
      +
    • To fix a wrong alias, you can do +git remote rename <old> <new>.
    • +
    • To fix a wrong URL, you can do +git remote set-url <alias> <newurl>.
    • +
    +
  • +
  • Before cloning the repo, be sure that nobody is inside another +repo. The best way to achieve this is moving to the Desktop +before cloning: cd && cd Desktop.

  • +
  • +

    If both repos are in the Desktop, have them to clone +their collaborator repo under a given directory using a second +argument:

    +
    +

    BASH +

    +
    $ git clone https://github.com/alflin/recipes.git alflin-recipes
    +
    +
  • +
  • The most common mistake is that learners push before +pulling. If they pull afterward, they may get +a conflict.

  • +
  • Conflicts, sometimes weird, will start to arise. Stay tight: +conflicts are next.

  • +
  • Learners may have slightly different output from +git push and git pull depending on the version +of git, and if upstream (-u) is used.

  • +

+Conflicts +

+
+
    +
  • Expect the learners to make mistakes. Expect yourself to +make mistakes. This happens because it is late in the lesson and +everyone is tired.

  • +
  • +

    If you’re the only instructor, the best way to create a conflict +is:

    +
      +
    • Clone your repo in a different directory, pretending is your +computer at work: +git clone https://github.com/alflin/recipes.git recipes-at-work.
    • +
    • At the office, you make a change, commit and push.
    • +
    • At your laptop repo, you (forget to pull and) make a change, commit +and try to push.
    • +
    • +git pull now and show the conflict.
    • +
    +
  • +
  • Learners usually forget to git add the file after +fixing the conflict and just (try to) commit. You can diagnose this with +git status.

  • +
  • +

    Remember that you can discard one of the two parents of the +merge:

    +
      +
    • discard the remote file, +git checkout --ours conflicted_file.txt +
    • +
    • discard the local file, +git checkout --theirs conflicted_file.txt +
    • +
    +

    You still have to git add and git commit +after this. This is particularly useful when working with binary +files.

    +
  • +
  • Keep in mind that depending on the Git version used, the outputs +for git push and git pull can vary +slightly.

  • +

+Open Science +

+

+Licensing +

+
+

We teach about licensing because questions about who owns what, or +can use what, arise naturally once we start talking about using public +services like GitHub to store files. Also, the discussion gives learners +a chance to catch their breath after what is often a frustrating couple +of hours.

+

The Creative Commons family of licenses is recommended for many types +of works (including software documentation and images used in software) +but not software itself. Creative Commons recommends +a software-specific license instead.

+

+Citation +

+

+Hosting +

+
+

A common concern for learners is having their work publicly available +on GitHub. While we encourage open science, sometimes private repos are +the only choice. It’s always interesting to mention the options to have +web-hosted private repositories.

+
+
+
+
+ + +
+ + +
+ + + + + diff --git a/instructor/01-basics.html b/instructor/01-basics.html new file mode 100644 index 0000000000..4cb4b927b0 --- /dev/null +++ b/instructor/01-basics.html @@ -0,0 +1,616 @@ + +Version Control with Git: Automated Version Control +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Automated Version Control

+

Last updated on 2024-11-01 | + + 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.
  • +
+
+
+
+
+

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.

+
+
+ +
+
+

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.

+
+
+
+
+
+ +
+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/02-setup.html b/instructor/02-setup.html new file mode 100644 index 0000000000..2ef9063bf8 --- /dev/null +++ b/instructor/02-setup.html @@ -0,0 +1,759 @@ + +Version Control with Git: Setting Up Git +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Setting Up Git

+

Last updated on 2024-11-01 | + + 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).
  • +

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. So here is +how Alfredo sets up his new laptop:

+
+

BASH +

+
$ git config --global user.name "Alfredo Linguini"
+$ git config --global user.email "a.linguini@ratatouille.fr"
+
+

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

+

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

+
+
+ +
+
+

Keeping your email private

+
+

If you elect to use a private email address with GitHub, then use +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.

+
+
+
+
+
+ +
+
+

Line Endings

+
+

As with other keys, when you hit Enter or or +on Macs, Return on your keyboard, your computer encodes this +input as a character. Different operating systems use different +character(s) to represent the end of a line. (You may also hear these +referred to as newlines or line breaks.) Because Git uses these +characters to compare files, it may cause unexpected issues when editing +a file on different machines. Though it is beyond the scope of this +lesson, you can read more about this issue in +the Pro Git book.

+

You can change the way Git recognizes and encodes line endings using +the core.autocrlf command to git config. The +following settings are recommended:

+

On macOS and Linux:

+
+

BASH +

+
$ git config --global core.autocrlf input
+
+

And on Windows:

+
+

BASH +

+
$ git config --global core.autocrlf true
+
+
+
+
+

Alfredo also has to set his favorite text editor, following this +table:

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

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

+
+
+ +
+
+

Exiting Vim

+
+

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

+
+
+
+

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

+
+

BASH +

+
$ git config --global init.defaultBranch main
+
+
+
+ +
+
+

Default Git branch naming

+
+

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

+

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

+

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

+
+
+
+

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.

+

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. Remember, +since typos in the config file will cause issues, it’s safer to view the +configuration with:

+
+

BASH +

+
$ git config --list
+
+

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

+
+
+ +
+
+

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

+
+

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

+
+

BASH +

+
$ git config -h
+$ git config --help
+
+

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

+

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

+
+

BASH +

+
$ git help
+
+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Use git config with the --global option to +configure a user name, email address, editor, and other preferences once +per machine.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/03-create.html b/instructor/03-create.html new file mode 100644 index 0000000000..21eb51023f --- /dev/null +++ b/instructor/03-create.html @@ -0,0 +1,712 @@ + +Version Control with Git: Creating a Repository +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Creating a Repository

+

Last updated on 2024-11-01 | + + 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.
  • +
+
+
+
+
+

Once Git is configured, we can start using it.

+

We will help Alfredo with his new project, create a repository with +all his recipes.

+

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 recipes
+$ cd recipes
+
+

Then we tell Git to make recipes 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 +recipes repository, whether subdirectories are present from +the beginning or added later. Also, note that the creation of the +recipes 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 recipes +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.

+

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

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

+
+
+ +
+
+

Places to Create Git Repositories

+
+

Along with tracking information about recipes (the project we have +already created), Alfredo would also like to track information about +desserts specifically. Alfredo creates a desserts project +inside his recipes project with the following sequence of +commands:

+
+

BASH +

+
$ cd ~/Desktop    # return to Desktop directory
+$ cd recipes      # go into recipes directory, which is already a Git repository
+$ ls -a           # ensure the .git subdirectory is still present in the recipes directory
+$ mkdir desserts # make a sub-directory recipes/desserts
+$ cd desserts    # go into desserts subdirectory
+$ git init        # make the desserts 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 +desserts subdirectory, required for tracking files stored +in the desserts subdirectory?

+
+
+
+
+
+ +
+
+

No. Alfredo does not need to make the desserts +subdirectory a Git repository because the recipes +repository will track all files, sub-directories, and subdirectory files +under the recipes directory. Thus, in order to track all +information about desserts, Alfredo only needed to add the +desserts subdirectory to the recipes +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

+
+

Jimmy explains to Alfredo how a nested repository is redundant and +may cause confusion down the road. Alfredo would like to go back to a +single git repository. How can Alfredo undo his last +git init in the desserts 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, Alfredo can remove the +.git folder in the desserts subdirectory by running the +following command from inside the recipes directory:

+
+

BASH +

+
$ rm -rf desserts/.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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/04-changes.html b/instructor/04-changes.html new file mode 100644 index 0000000000..9daa5ee5dc --- /dev/null +++ b/instructor/04-changes.html @@ -0,0 +1,1379 @@ + +Version Control with Git: Tracking Changes +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Tracking Changes

+

Last updated on 2024-11-01 | + + 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 in the right directory. You should +be in the recipes directory.

+
+

BASH +

+
$ cd ~/Desktop/recipes
+
+

Let’s create a file called guacamole.md that contains +the basic structure to have a recipe. 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 guacamole.md
+
+

Type the text below into the guacamole.md file:

+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

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 +

+
guacamole.md
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

If we check the status of our project again, Git tells us that it’s +noticed the new file:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Untracked files:
+   (use "git add <file>..." to include in what will be committed)
+
+	guacamole.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 guacamole.md
+
+

and then check that the right thing happened:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Changes to be committed:
+  (use "git rm --cached <file>..." to unstage)
+
+	new file:   guacamole.md
+
+
+

Git now knows that it’s supposed to keep track of +guacamole.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 template for recipe"
+
+
+

OUTPUT +

+
[main (root-commit) f22b25e] Create a template for recipe
+ 1 file changed, 1 insertion(+)
+ create mode 100644 guacamole.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.

+

If we run git status now:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

it tells us everything is up to date. 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 f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+

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.

+
+
+ +
+
+

Where Are My Changes?

+
+

If we run ls at this point, we will still see just one +file called guacamole.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 Alfredo adds 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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lemon
+* salt
+## Instructions
+
+

When we run git status now, it tells us that a file it +already knows about has been modified:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git restore <file>..." to discard changes in working directory)
+
+	modified:   guacamole.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/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lemon
++* salt
+ ## Instructions
+
+

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. +
  3. The second line tells exactly which versions of the file Git is +comparing; df0654a and 315bf3a are unique +computer-generated labels for those versions.
  4. +
  5. The third and fourth lines once again show the name of the file +being changed.
  6. +
  7. 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.
  8. +

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

+
+

BASH +

+
$ git commit -m "Add basic guacamole's ingredients"
+$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ git commit -m "Add basic guacamole's ingredients"
+
+
+

OUTPUT +

+
[main 34961b1] Add basic guacamole's ingredient
+ 1 file changed, 3 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

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 recipe +by changing ‘lemon’ to ‘lime’:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole.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/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole to the traditional recipe"
+
+
+

OUTPUT +

+
[main 005937f] Modify guacamole to the traditional recipe
+ 1 file changed, 1 insertion(+)
+
+

check our status:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git log
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+    Modify guacamole to the traditional recipe
+
+commit 34961b159c27df3b475cfe4415d94a6d1fcd064d
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Add basic guacamole's ingredients
+
+commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+
+
+ +
+
+

Word-based diffing

+
+

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

+
+
+
+
+
+ +
+
+

Paging the Log

+
+

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

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

Limit Log Size

+
+

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

+
+

BASH +

+
$ git log -1
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+   Modify guacamole to the traditional recipe
+
+

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

+
+

BASH +

+
$ git log --oneline
+
+
+

OUTPUT +

+
005937f (HEAD -> main) Modify guacamole to the traditional recipe
+34961b1 Add basic guacamole's ingredients
+f22b25e Create a template for recipe
+
+

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

+
+

BASH +

+
$ git log --oneline --graph
+
+
+

OUTPUT +

+
* 005937f (HEAD -> main) Modify guacamole to the traditional recipe
+* 34961b1 Add basic guacamole's ingredients
+* f22b25e Create a template for recipe
+
+
+
+
+
+
+ +
+
+

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:
  2. +
+

BASH +

+
$ mkdir cakes
+$ git status
+$ git add cakes
+$ git status
+
+

Note, our newly created empty directory cakes 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:
  2. +
+

BASH +

+
git add <directory-with-files>
+
+

Try it for yourself:

+
+

BASH +

+
$ touch cakes/brownie cakes/lemon_drizzle
+$ git status
+$ git add cakes
+$ git status
+
+

Before moving on, we will commit these changes.

+
+

BASH +

+
$ git commit -m "Add some initial cakes"
+
+
+
+
+

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 guacamole.md?

+
  1. “Changes”
  2. +
  3. “Changed lemon for lime”
  4. +
  5. “Guacamole modified to the traditional recipe”
  6. +
+
+
+
+
+ +
+
+

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. +
  3. +

    BASH +

    +
       $ git init myfile.txt
    +   $ git commit -m "my recent changes"
    +
  4. +
  5. +

    BASH +

    +
       $ git add myfile.txt
    +   $ git commit -m "my recent changes"
    +
  6. +
  7. +

    BASH +

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

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 guacamole.md noting the rough price of +the ingredients.
  2. +
  3. Create a new file groceries.md with a list of products +and their prices for different markets.
  4. +
  5. Add changes from both files to the staging area, and commit those +changes.
  6. +
+
+
+
+
+ +
+
+

First we make our changes to the guacamole.md and +groceries.md files:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado (1.35)
+* lime (0.64)
+* salt (2)
+
+
+

BASH +

+
$ nano groceries.md
+$ cat groceries.md
+
+
+

OUTPUT +

+
# Market A
+* avocado: 1.35 per unit.
+* lime: 0.64 per unit
+* salt: 2 per kg
+
+

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

+
+

BASH +

+
$ git add guacamole.md groceries.md
+
+

Or with multiple commands:

+
+

BASH +

+
$ git add guacamole.md
+$ git add groceries.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 "Write prices for ingredients and their source"
+
+
+

OUTPUT +

+
[main cc127c2]
+ Write prices for ingredients and their source
+ 2 files changed, 7 insertions(+)
+ create mode 100644 groceries.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 recipes folder:

+
+

BASH +

+
$ cd ..
+
+

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

+
+

BASH +

+
$ mkdir bio
+$ cd bio
+
+

Initialise git:

+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/05-history.html b/instructor/05-history.html new file mode 100644 index 0000000000..46f9a7c812 --- /dev/null +++ b/instructor/05-history.html @@ -0,0 +1,1105 @@ + +Version Control with Git: Exploring History +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Exploring History

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +

Estimated time: 25 minutes

+ +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

We’ve been adding small changes at a time to +guacamole.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 guacamole.md, adding yet another +line.

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+An ill-considered change
+
+

Now, let’s see what we get.

+
+

BASH +

+
$ git diff HEAD guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index b36abfd..0848c8d 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -4,3 +4,4 @@
+ * lime
+ * salt
+ ## Instructions
++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 guacamole.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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
+
+

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

+
+

BASH +

+
$ git show HEAD~2 guacamole.md
+
+
+

OUTPUT +

+
commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Create a template for recipe
+
+diff --git a/guacamole.md b/guacamole.md
+new file mode 100644
+index 0000000..df0654a
+--- /dev/null
++++ b/guacamole.md
+@@ -0,0 +1,3 @@
++# Guacamole
++## Ingredients
++## Instructions
+
+

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 was given the ID +f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try +this:

+
+

BASH +

+
$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++An ill-considered change
+
+

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 guacamole.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 main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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. If +we want to go back even further, we can use a commit identifier instead, +using -s option:

+
+

BASH +

+
$ git restore -s f22b25e guacamole.md
+
+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

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

+
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

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

+
+
+ +
+
+

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. +
  3. $ git restore data_cruncher.py

  4. +
  5. $ git restore -s HEAD~1 data_cruncher.py

  6. +
  7. $ git restore -s <unique ID of last commit> data_cruncher.py

  8. +
  9. Both 2 and 4

  10. +
+
+
+
+
+ +
+
+

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

+
+

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

+

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

+

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

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

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

  4. +
  5. git revert [commit ID]

  6. +
  7. Type in the new commit message.

  8. +
  9. Save and close.

  10. +
+
+
+
+
+ +
+
+

The command git log lists project history with commit +IDs.

+

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

+
+
+
+
+
+
+ +
+
+

Understanding Workflow and History

+
+

What is the output of the last command in

+
+

BASH +

+
$ cd recipes
+$ echo "I like tomatoes, therefore I like ketchup" > ketchup.md
+$ git add ketchup.md
+$ echo "ketchup enhances pasta dishes" >> ketchup.md
+$ git commit -m "My opinions about the red sauce"
+$ git restore ketchup.md
+$ cat ketchup.md # this will print the content of ketchup.md on screen
+
+
  1. +

    OUTPUT +

    +
      ketchup enhances pasta dishes
    +
  2. +
  3. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +
  4. +
  5. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +  ketchup enhances pasta dishes
    +
  6. +
  7. +

    OUTPUT +

    +
      Error because you have changed ketchup.md without committing the changes
    +
  8. +
+
+
+
+
+ +
+
+

The answer is 2.

+

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

+

So, when git commit -m "My opinions about the red sauce" +is executed, the version of ketchup.md committed to the +repository is the one from the staging area and has only one line.

+

At this time, the working copy still has the second line (and

+

git status will show that the file is modified). +However, git restore ketchup.md replaces the working copy +with the most recently committed version of ketchup.md. So, +cat ketchup.md will output

+
+

OUTPUT +

+
I like tomatoes, therefore I like ketchup
+
+
+
+
+
+
+
+ +
+
+

Checking Understanding of +git diff +

+
+

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

+
+
+
+
+
+ +
+
+

Getting Rid of Staged Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

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

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

+

Using the command git restore guacamole.md now does not +give an error, but it does not restore the file either. Git helpfully +tells us that we need to use git restore --staged first to +unstage the file:

+
+

BASH +

+
$ git restore --staged guacamole.md
+
+

Now, git status gives us:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git git restore <file>..." to discard changes in working directory)
+        modified:   guacamole.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

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

+
+

BASH +

+
$ git restore guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+
+
+
+
+
+
+ +
+
+

Explore and Summarize Histories

+
+

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

+

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

+
+

BASH +

+
$ git log guacamole.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 guacamole.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 diff displays differences between commits.
  • +
  • +git restore recovers old versions of files.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/06-ignore.html b/instructor/06-ignore.html new file mode 100644 index 0000000000..583b520f1d --- /dev/null +++ b/instructor/06-ignore.html @@ -0,0 +1,926 @@ + +Version Control with Git: Ignoring Things +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Ignoring Things

+

Last updated on 2024-11-01 | + + 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 receipts
+$ touch a.png b.png c.png receipts/a.jpg receipts/b.jpg
+
+

and see what Git says:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	a.png
+	b.png
+	c.png
+	receipts/
+
+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
+receipts/
+
+

These patterns tell Git to ignore any file whose name ends in +.png and everything in the receipts 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 main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	.gitignore
+
+nothing added to commit but untracked files present (use "git add" to track)
+
+

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

+
+

BASH +

+
$ git add .gitignore
+$ git commit -m "Ignore png files and the receipts folder."
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git add a.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 main
+Ignored files:
+ (use "git add -f <file>..." to include in what will be committed)
+
+        a.png
+        b.png
+        c.png
+        receipts/
+
+nothing to commit, working tree clean
+
+
+
+ +
+
+

Ignoring Nested Files

+
+

Given a directory structure that looks like:

+
+

BASH +

+
receipts/data
+receipts/plots
+
+

How would you ignore only receipts/plots and not +receipts/data?

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/plots/
+
+

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

+

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 also that because you’ve previously committed .png +files in this lesson 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 +

+
receipts/data
+receipts/images
+receipts/plots
+receipts/analysis
+
+

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

+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/*               # ignore everything in receipts folder
+!receipts/data/          # do not ignore receipts/data/ contents
+
+
+
+
+
+
+
+ +
+
+

Ignoring all data Files in a Directory

+
+

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

+
+

BASH +

+
receipts/data/market_position/gps/a.dat
+receipts/data/market_position/gps/b.dat
+receipts/data/market_position/gps/c.dat
+receipts/data/market_position/gps/info.txt
+receipts/plots
+
+

What’s the shortest .gitignore rule you could write to +ignore all .dat files in +result/data/market_position/gps? Do not ignore the +info.txt.

+
+
+
+
+
+ +
+
+

Appending receipts/data/market_position/gps/*.dat will +match every file in receipts/data/market_position/gps that +ends with .dat. The file +receipts/data/market_position/gps/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. +
  3. Test your “ignore pattern” by creating some dummy files of the +form log_01, etc.

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

  6. +
  7. 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.

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

Key Points

+
+
  • The .gitignore file tells Git what files to +ignore.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/07-github.html b/instructor/07-github.html new file mode 100644 index 0000000000..af3a550c6c --- /dev/null +++ b/instructor/07-github.html @@ -0,0 +1,1128 @@ + +Version Control with Git: Remotes in GitHub +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Remotes in GitHub

+

Last updated on 2024-11-01 | + + 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 start by sharing the changes we’ve made to our current project +with the world. To this end we are going to create a remote +repository that will be linked to our local repository.

+

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 +recipes:

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

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

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

+
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 recipes
+$ cd recipes
+$ git init
+
+

If you remember back to the earlier episode where we added and committed our +earlier work on guacamole.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 "recipes" 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 +guacamole.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.

+
+
+
+
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

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

+
+

BASH +

+
$ git remote add origin git@github.com:alflin/recipes.git
+
+

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

+

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:alflin/recipes.git (fetch)
+origin   git@github.com:alflin/recipes.git (push)
+
+

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

+

3. SSH Background and Setup

+

Before Alfredo can connect to a remote repository, he needs to set up +a way for his computer to authenticate with GitHub so it knows it’s him +trying to connect to his remote repository.

+

We are going to set up the method that is commonly used by many +different services to authenticate access on the command line. This +method is called Secure Shell Protocol (SSH). SSH is a cryptographic +network protocol that allows secure communication between computers +using an otherwise insecure network.

+

SSH uses what is called a key pair. This is two keys that work +together to validate access. One key is publicly known and called the +public key, and the other key called the private key is kept private. +Very descriptive names.

+

You can think of the public key as a padlock, and only you have the +key (the private key) to open it. You use the public key where you want +a secure method of communication, such as your GitHub account. You give +this padlock, or public key, to GitHub and say “lock the communications +to my account with this so that only computers that have my private key +can unlock communications and send git commands as my GitHub +account.”

+

What we will do now is the minimum required to set up the SSH keys +and add the public key to a GitHub account.

+
+
+ +
+
+

Advanced SSH

+
+

A supplemental episode in this lesson discusses SSH and key pairs in +more depth and detail.

+
+
+
+

The first thing we are going to do is check if this has already been +done on the computer you’re on. Because generally speaking, this setup +only needs to happen once and then you can forget about it.

+
+
+ +
+
+

Keeping your keys secure

+
+

You shouldn’t really forget about your SSH keys, since they keep your +account secure. It’s good practice to audit your secure shell keys every +so often. Especially if you are using multiple computers to access your +account.

+
+
+
+

We will run the list command to check what key pairs already exist on +your computer.

+
+

BASH +

+
ls -al ~/.ssh
+
+

Your output is going to look a little different depending on whether +or not SSH has ever been set up on the computer you are using.

+

Alfredo has not set up SSH on his computer, so his output is

+
+

OUTPUT +

+
ls: cannot access '/c/Users/Alfredo/.ssh': No such file or directory
+
+

If SSH has been set up on the computer you’re using, the public and +private key pairs will be listed. The file names are either +id_ed25519/id_ed25519.pub or +id_rsa/id_rsa.pub depending on how the key +pairs were set up. Since they don’t exist on Alfredo’s computer, he uses +this command to create them.

+
+

3.1 Create an SSH key pair

+

To create an SSH key pair Alfredo uses this command, where the +-t option specifies which type of algorithm to use and +-C attaches a comment to the key (here, Alfredo’s +email):

+
+

BASH +

+
$ ssh-keygen -t ed25519 -C "a.linguini@ratatouille.fr"
+
+

If you are using a legacy system that doesn’t support the Ed25519 +algorithm, use: +$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

+
+

OUTPUT +

+
Generating public/private ed25519 key pair.
+Enter file in which to save the key (/c/Users/Alfredo/.ssh/id_ed25519):
+
+

We want to use the default file, so just press Enter.

+
+

OUTPUT +

+
Created directory '/c/Users/Alfredo/.ssh'.
+Enter passphrase (empty for no passphrase):
+
+

Now, it is prompting Alfredo for a passphrase. Since he is using his +kitchen’s laptop that other people sometimes have access to, he wants to +create a passphrase. Be sure to use something memorable or save your +passphrase somewhere, as there is no “reset my password” option. Note +that, when typing a passphrase on a terminal, there won’t be any visual +feedback of your typing. This is normal: your passphrase will be +recorded even if you see nothing changing on your screen.

+
+

OUTPUT +

+
Enter same passphrase again:
+
+

After entering the same passphrase a second time, we receive the +confirmation

+
+

OUTPUT +

+
Your identification has been saved in /c/Users/Alfredo/.ssh/id_ed25519
+Your public key has been saved in /c/Users/Alfredo/.ssh/id_ed25519.pub
+The key fingerprint is:
+SHA256:SMSPIStNyA00KPxuYu94KpZgRAYjgt9g4BA4kFy3g1o a.linguini@ratatouille.fr
+The key's randomart image is:
++--[ED25519 256]--+
+|^B== o.          |
+|%*=.*.+          |
+|+=.E =.+         |
+| .=.+.o..        |
+|....  . S        |
+|.+ o             |
+|+ =              |
+|.o.o             |
+|oo+.             |
++----[SHA256]-----+
+
+

The “identification” is actually the private key. You should never +share it. The public key is appropriately named. The “key fingerprint” +is a shorter version of a public key.

+

Now that we have generated the SSH keys, we will find the SSH files +when we check.

+
+

BASH +

+
ls -al ~/.ssh
+
+
+

OUTPUT +

+
drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ./
+drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ../
+-rw-r--r-- 1 Alfredo   197121 419 Jul 16 14:48 id_ed25519
+-rw-r--r-- 1 Alfredo   197121 106 Jul 16 14:48 id_ed25519.pub
+
+
+
+

3.2 Copy the public key to GitHub

+

Now we have a SSH key pair and we can run this command to check if +GitHub can read our authentication.

+
+

BASH +

+
ssh -T git@github.com
+
+
+

OUTPUT +

+
The authenticity of host 'github.com (192.30.255.112)' can't be established.
+RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
+This key is not known by any other names
+Are you sure you want to continue connecting (yes/no/[fingerprint])? y
+Please type 'yes', 'no' or the fingerprint: yes
+Warning: Permanently added 'github.com' (RSA) to the list of known hosts.
+git@github.com: Permission denied (publickey).
+
+

Right, we forgot that we need to give GitHub our public key!

+

First, we need to copy the public key. Be sure to include the +.pub at the end, otherwise you’re looking at the private +key.

+
+

BASH +

+
cat ~/.ssh/id_ed25519.pub
+
+
+

OUTPUT +

+
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDmRA3d51X0uu9wXek559gfn6UFNF69yZjChyBIU2qKI a.linguini@ratatouille.fr
+
+

Now, going to GitHub.com, click on your profile icon in the top right +corner to get the drop-down menu. Click “Settings”, then on the settings +page, click “SSH and GPG keys”, on the left side “Access” menu. Click +the “New SSH key” button on the right side. Now, you can add the title +(Alfredo uses the title “Alfredo’s Kitchen Laptop” so he can remember +where the original key pair files are located), paste your SSH key into +the field, and click the “Add SSH key” to complete the setup.

+

Now that we’ve set that up, let’s check our authentication again from +the command line.

+
+

BASH +

+
$ ssh -T git@github.com
+
+
+

OUTPUT +

+
Hi Alfredo! You've successfully authenticated, but GitHub does not provide shell access.
+
+

Good! This output confirms that the SSH key works as intended. We are +now ready to push our work to the remote repository.

+
+

4. Push local changes to a remote

+

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

+
+

BASH +

+
$ git push origin main
+
+

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

+
+

OUTPUT +

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

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

+
+
+
+

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

+
From https://github.com/alflin/recipes
+ * branch            main     -> FETCH_HEAD
+Already up-to-date.
+
+

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

+
+
+ +
+
+

GitHub GUI

+
+

Browse to your recipes 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/alflin/recipes
+ * 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/alflin/recipes
+ * 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.
  • +
+
+
+
+
+ + +
+
+ + + diff --git a/instructor/08-collab.html b/instructor/08-collab.html new file mode 100644 index 0000000000..0de5cdb10e --- /dev/null +++ b/instructor/08-collab.html @@ -0,0 +1,787 @@ + +Version Control with Git: Collaborating +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Collaborating

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +

Estimated time: 25 minutes

+ +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+
+
+ +
+
+

Practicing By Yourself

+
+

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

+
+
+
+

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

+
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

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

+

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

+

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

+

To clone the Owner’s repo into her Desktop folder, the +Collaborator enters:

+
+

BASH +

+
$ git clone git@github.com:alflin/recipes.git ~/Desktop/alflin-recipes
+
+

Replace ‘alflin’ with the Owner’s username.

+

If you choose to clone without the clone path +(~/Desktop/alflin-recipes) specified at the end, you will +clone inside your own recipes folder! Make sure to navigate to the +Desktop folder first.

+
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

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

+
+

BASH +

+
$ cd ~/Desktop/alflin-recipes
+$ nano hummus.md
+$ cat hummus.md
+
+
+

OUTPUT +

+
# Hummus
+## Ingredients
+* chickpeas
+* lemon
+* olive oil
+* salt
+
+
+

BASH +

+
$ git add hummus.md
+$ git commit -m "Add ingredients for hummus"
+
+
+

OUTPUT +

+
 1 file changed, 6 insertion(+)
+ create mode 100644 hummus.md
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+

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

+
+
+ +
+
+

Some more about remotes

+
+

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

+

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

+

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

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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

+
+
+ +
+
+

A Basic Collaborative Workflow

+
+

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

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

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

+
+
+
+
+
+ +
+
+

Switch Roles and Repeat

+
+

Switch roles and repeat the whole process.

+
+
+
+
+
+ +
+
+

Review Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+

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

+
+
+
+
+
+
+ +
+
+

Comment Changes in GitHub

+
+

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

+

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

+

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

+
+
+
+
+
+ +
+
+

Version History, Backup, and Version Control

+
+

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

+
+
+
+
+
+ +
+
+

Key Points

+
+
  • +git clone copies a remote repository to create a local +repository with a remote called origin automatically set +up.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/09-conflict.html b/instructor/09-conflict.html new file mode 100644 index 0000000000..d8cc0bb429 --- /dev/null +++ b/instructor/09-conflict.html @@ -0,0 +1,1160 @@ + +Version Control with Git: Conflicts +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Conflicts

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +

Estimated time: 15 minutes

+ +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* put one avocado into a bowl.
+
+

and then push the change to GitHub:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "First step on the instructions"
+
+
+

OUTPUT +

+
[main 5ae9631] First step on the instructions
+ 1 file changed, 1 insertion(+)
+
+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados
+
+

We can commit the change locally:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "Add first step"
+
+
+

OUTPUT +

+
[main 07ebc69] Add first step
+ 1 file changed, 1 insertion(+)
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

+
To https://github.com/alflin/recipes.git
+ ! [rejected]        main -> main (fetch first)
+error: failed to push some refs to 'https://github.com/alflin/recipes.git'
+hint: Updates were rejected because the remote contains work that you do
+hint: not have locally. This is usually caused by another repository pushing
+hint: to the same ref. You may want to first integrate the remote changes
+hint: (e.g., 'git pull ...') before pushing again.
+hint: See the 'Note about fast-forwards' in 'git push --help' for details.
+
+
A diagram showing a conflict that might occur when two sets of independent changes are merged

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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. In our +case we want ‘the default strategy’. To use this strategy run the +following command to select it as the default thing git should do.

+
+

BASH +

+
$ git config pull.rebase false
+
+

Then attempt the pull again.

+
+

BASH +

+
$ git pull origin main
+
+
+
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+<<<<<<< HEAD
+* peel the avocados
+=======
+* put one avocado into a bowl.
+>>>>>>> dabb4c8c450e8475aee9b14b4383acc99f42af1d
+
+

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

To finish merging, we add guacamole.md to the changes +being made by the merge and then commit:

+
+

BASH +

+
$ git add guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+All conflicts fixed but you are still merging.
+  (use "git commit" to conclude merge)
+
+Changes to be committed:
+
+	modified:   guacamole.md
+
+
+
+

BASH +

+
$ git commit -m "Merge changes from GitHub"
+
+
+

OUTPUT +

+
[main 2abf2b1] Merge changes from GitHub
+
+

Now we can push our changes to GitHub:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

We get the merged file:

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

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

+

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

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

Conflicts can also be minimized with project management +strategies:

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

Solving Conflicts that You Create

+
+

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

+
+
+
+
+
+ +
+
+

Conflicts on Non-textual files

+
+

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

+
+
+
+
+
+ +
+
+

Let’s try it. Suppose Alfredo takes a picture of its guacamole and +calls it guacamole.jpg.

+

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

+
+

BASH +

+
$ head --bytes 1024 /dev/urandom > guacamole.jpg
+$ ls -lh guacamole.jpg
+
+
+

OUTPUT +

+
-rw-r--r-- 1 alflin 57095 1.0K Mar  8 20:24 guacamole.jpg
+
+

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

+

Now, suppose Alfredo adds guacamole.jpg to his +repository:

+
+

BASH +

+
$ git add guacamole.jpg
+$ git commit -m "Add picture of guacamole"
+
+
+

OUTPUT +

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

Suppose that Jimmy has added a similar picture in the meantime. His +is a picture of a guacamole with nachos, but it is also called +guacamole.jpg. When Alfredo tries to push, he gets a +familiar message:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+

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

+
+

OUTPUT +

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

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

+
+

OUTPUT +

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

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

+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of just guacamole instead of with nachos"
+
+
+

OUTPUT +

+
[main 21032c3] Use image of just guacamole instead of with nachos
+
+

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

+
+

BASH +

+
$ git checkout 439dc8c0 guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of guacamole with nachos instead of just guacamole"
+
+
+

OUTPUT +

+
[main da21b34] Use image of guacamole with nachos instead of just guacamole
+
+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git mv guacamole.jpg guacamole-only.jpg
+$ git checkout 439dc8c0 guacamole.jpg
+$ mv guacamole.jpg guacamole-nachos.jpg
+
+

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

+
+

BASH +

+
$ git rm guacamole.jpg
+$ git add guacamole-only.jpg
+$ git add guacamole-nachos.jpg
+$ git commit -m "Use two images: just guacamole and with nachos"
+
+
+

OUTPUT +

+
[main 94ae08c] Use two images: just guacamole and with nachos
+ 2 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 guacamole-nachos.jpg
+ rename guacamole.jpg => guacamole-only.jpg (100%)
+
+

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

+
+
+
+
+
+
+ +
+
+

A Typical Work Session

+
+

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

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

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

+ + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . . . . . .command . . . . . . . . . .
1
2echo 100 >> numbers.txt
3
4
5
6Celebrate!
+
+
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . .command . . . . . . . . . . . . . . . . . . .
1Update localgit pull origin main
2Make changesecho 100 >> numbers.txt
3Stage changesgit add numbers.txt
4Commit changesgit commit -m "Add 100 to numbers.txt"
5Update remotegit push origin main
6Celebrate!
+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/10-open.html b/instructor/10-open.html new file mode 100644 index 0000000000..a119e9abc1 --- /dev/null +++ b/instructor/10-open.html @@ -0,0 +1,644 @@ + +Version Control with Git: Open Science +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Open Science

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +

Estimated time: 10 minutes

+ +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

-– John Wilbanks

+
+

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

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

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

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

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

+

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

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

Making Code Citable

+
+

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

+
+
+
+
+
+ +
+
+

How Reproducible Is My Work?

+
+

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

+
+
+
+
+
+ +
+
+

How to Find an Appropriate Data Repository?

+
+

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

+
+
+
+
+
+ +
+
+

How to Track Large Data or Image Files using Git?

+
+

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

+

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

+
+
+
+
+
+ +
+
+

Key Points

+
+
  • Open scientific work is more useful and more highly cited than +closed.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/11-licensing.html b/instructor/11-licensing.html new file mode 100644 index 0000000000..821ef23efb --- /dev/null +++ b/instructor/11-licensing.html @@ -0,0 +1,604 @@ + +Version Control with Git: Licensing +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Licensing

+

Last updated on 2024-11-01 | + + Edit this page

+ + + +

Estimated time: 5 minutes

+ +
+ +
+ + + +
+

Overview

+
+
+
+
+

Questions

+
  • What licensing information should I include with my work?
  • +
+
+
+
+
+
+

Objectives

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

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

+

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

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

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

+

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

+

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

+
+
+ +
+
+

Can I Use Open License?

+
+

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

+
+
+
+
+
+ +
+
+

What licenses have I already accepted?

+
+

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

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

Key Points

+
+
  • The LICENSE, LICENSE.md, or +LICENSE.txt file is often used in a repository to indicate +how the contents of the repo may be used by others.
  • +
  • People who incorporate General Public License (GPL’d) software into +their own software must make 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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/12-citation.html b/instructor/12-citation.html new file mode 100644 index 0000000000..bc02d148ca --- /dev/null +++ b/instructor/12-citation.html @@ -0,0 +1,542 @@ + +Version Control with Git: Citation +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Citation

+

Last updated on 2024-11-01 | + + 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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/13-hosting.html b/instructor/13-hosting.html new file mode 100644 index 0000000000..77dc7719e0 --- /dev/null +++ b/instructor/13-hosting.html @@ -0,0 +1,602 @@ + +Version Control with Git: Hosting +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Hosting

+

Last updated on 2024-11-01 | + + 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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/14-supplemental-rstudio.html b/instructor/14-supplemental-rstudio.html new file mode 100644 index 0000000000..48a81f0953 --- /dev/null +++ b/instructor/14-supplemental-rstudio.html @@ -0,0 +1,667 @@ + +Version Control with Git: Supplemental: Using Git from RStudio +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Supplemental: Using Git from RStudio

+

Last updated on 2024-11-01 | + + 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 +recipes 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/recipes"

Ta-da! We have created a new project in RStudio within the existing +recipes 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. +
  3. Modify the .gitignore so that the graphs +directory is not version controlled.
  4. +
+
+
+
+
+ +
+
+

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.
  • +
+
+
+ + + +
+
+ + +
+
+ + + diff --git a/instructor/404.html b/instructor/404.html new file mode 100644 index 0000000000..61aac939c8 --- /dev/null +++ b/instructor/404.html @@ -0,0 +1,478 @@ + +Version Control with Git: Page not found +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Page not found

+ +

Our apologies!

+

We cannot seem to find the page you are looking for. Here are some +tips that may help:

+
  1. try going back to the previous +page or
  2. +
  3. navigate to any other page using the navigation bar on the +left.
  4. +
  5. if the URL ends with /index.html, try removing +that.
  6. +
  7. head over to the home page of this +lesson +
  8. +

If you came here from a link in this lesson, please contact the +lesson maintainers using the links at the foot of this page.

+
+
+ + +
+
+ + + diff --git a/instructor/CODE_OF_CONDUCT.html b/instructor/CODE_OF_CONDUCT.html new file mode 100644 index 0000000000..a06e857fdd --- /dev/null +++ b/instructor/CODE_OF_CONDUCT.html @@ -0,0 +1,484 @@ + +Version Control with Git: Contributor Code of Conduct +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Contributor Code of Conduct

+

Last updated on 2024-11-01 | + + Edit this page

+ + + + + +
+ +
+ + + +

As contributors and maintainers of this project, we pledge to follow +the The +Carpentries Code of Conduct.

+

Instances of abusive, harassing, or otherwise unacceptable behavior +may be reported by following our reporting +guidelines.

+ + + +
+
+ + +
+
+ + + diff --git a/instructor/LICENSE.html b/instructor/LICENSE.html new file mode 100644 index 0000000000..f2a611c6f7 --- /dev/null +++ b/instructor/LICENSE.html @@ -0,0 +1,532 @@ + +Version Control with Git: Licenses +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Licenses

+

Last updated on 2024-11-01 | + + Edit this page

+ + + + + +
+ +
+ + + +

Instructional Material

+

All Carpentries (Software Carpentry, Data Carpentry, and Library +Carpentry) instructional material is made available under the Creative Commons +Attribution license. The following is a human-readable summary of +(and not a substitute for) the full legal +text of the CC BY 4.0 license.

+

You are free:

+
  • to Share—copy and redistribute the material in any +medium or format
  • +
  • to Adapt—remix, transform, and build upon the +material
  • +

for any purpose, even commercially.

+

The licensor cannot revoke these freedoms as long as you follow the +license terms.

+

Under the following terms:

+
  • Attribution—You must give appropriate credit +(mentioning that your work is derived from work that is Copyright (c) +The Carpentries and, where practical, linking to https://carpentries.org/), provide a link to the +license, and indicate if changes were made. You may do so in any +reasonable manner, but not in any way that suggests the licensor +endorses you or your use.

  • +
  • No additional restrictions—You may not apply +legal terms or technological measures that legally restrict others from +doing anything the license permits. With the understanding +that:

  • +

Notices:

+
  • You do not have to comply with the license for elements of the +material in the public domain or where your use is permitted by an +applicable exception or limitation.
  • +
  • No warranties are given. The license may not give you all of the +permissions necessary for your intended use. For example, other rights +such as publicity, privacy, or moral rights may limit how you use the +material.
  • +

Software

+

Except where otherwise noted, the example programs and other software +provided by The Carpentries are made available under the OSI-approved MIT +license.

+

Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +“Software”), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions:

+

The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software.

+

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+

Trademark

+

“The Carpentries”, “Software Carpentry”, “Data Carpentry”, and +“Library Carpentry” and their respective logos are registered trademarks +of Community Initiatives.

+
+
+ + +
+
+ + + diff --git a/instructor/aio.html b/instructor/aio.html new file mode 100644 index 0000000000..3e444103c8 --- /dev/null +++ b/instructor/aio.html @@ -0,0 +1,5764 @@ + + + + + +Version Control with Git: All in One View + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Content from Automated Version Control

+
+

Last updated on 2024-11-01 | + + 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.
  • +
+
+
+
+
+
+

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.

+
+
+ +
+
+

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.

+
+
+
+
+
+ +
+
+

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 2024-11-01 | + + 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).
  • +
+

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. So here is +how Alfredo sets up his new laptop:

+
+

BASH +

+
$ git config --global user.name "Alfredo Linguini"
+$ git config --global user.email "a.linguini@ratatouille.fr"
+
+

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

+

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

+
+
+ +
+
+

Keeping your email private

+
+

If you elect to use a private email address with GitHub, then use +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.

+
+
+
+
+
+ +
+
+

Line Endings

+
+

As with other keys, when you hit Enter or or +on Macs, Return on your keyboard, your computer encodes this +input as a character. Different operating systems use different +character(s) to represent the end of a line. (You may also hear these +referred to as newlines or line breaks.) Because Git uses these +characters to compare files, it may cause unexpected issues when editing +a file on different machines. Though it is beyond the scope of this +lesson, you can read more about this issue in +the Pro Git book.

+

You can change the way Git recognizes and encodes line endings using +the core.autocrlf command to git config. The +following settings are recommended:

+

On macOS and Linux:

+
+

BASH +

+
$ git config --global core.autocrlf input
+
+

And on Windows:

+
+

BASH +

+
$ git config --global core.autocrlf true
+
+
+
+
+

Alfredo also has to set his favorite text editor, following this +table:

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

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

+
+
+ +
+
+

Exiting Vim

+
+

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

+
+
+
+

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

+
+

BASH +

+
$ git config --global init.defaultBranch main
+
+
+
+ +
+
+

Default Git branch naming

+
+

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

+

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

+

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

+
+
+
+

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.

+

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. Remember, +since typos in the config file will cause issues, it’s safer to view the +configuration with:

+
+

BASH +

+
$ git config --list
+
+

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

+
+
+ +
+
+

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

+
+

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

+
+

BASH +

+
$ git config -h
+$ git config --help
+
+

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

+

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

+
+

BASH +

+
$ git help
+
+
+
+
+
+
+ +
+
+

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-11-01 | + + 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.
  • +
+
+
+
+
+
+

Once Git is configured, we can start using it.

+

We will help Alfredo with his new project, create a repository with +all his recipes.

+

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 recipes
+$ cd recipes
+
+

Then we tell Git to make recipes 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 +recipes repository, whether subdirectories are present from +the beginning or added later. Also, note that the creation of the +recipes 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 recipes +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.

+

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

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

+
+
+ +
+
+

Places to Create Git Repositories

+
+

Along with tracking information about recipes (the project we have +already created), Alfredo would also like to track information about +desserts specifically. Alfredo creates a desserts project +inside his recipes project with the following sequence of +commands:

+
+

BASH +

+
$ cd ~/Desktop    # return to Desktop directory
+$ cd recipes      # go into recipes directory, which is already a Git repository
+$ ls -a           # ensure the .git subdirectory is still present in the recipes directory
+$ mkdir desserts # make a sub-directory recipes/desserts
+$ cd desserts    # go into desserts subdirectory
+$ git init        # make the desserts 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 +desserts subdirectory, required for tracking files stored +in the desserts subdirectory?

+
+
+
+
+
+ +
+
+

No. Alfredo does not need to make the desserts +subdirectory a Git repository because the recipes +repository will track all files, sub-directories, and subdirectory files +under the recipes directory. Thus, in order to track all +information about desserts, Alfredo only needed to add the +desserts subdirectory to the recipes +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

+
+

Jimmy explains to Alfredo how a nested repository is redundant and +may cause confusion down the road. Alfredo would like to go back to a +single git repository. How can Alfredo undo his last +git init in the desserts 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, Alfredo can remove the +.git folder in the desserts subdirectory by running the +following command from inside the recipes directory:

+
+

BASH +

+
$ rm -rf desserts/.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 Tracking Changes

+
+

Last updated on 2024-11-01 | + + 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 in the right directory. You should +be in the recipes directory.

+
+

BASH +

+
$ cd ~/Desktop/recipes
+
+

Let’s create a file called guacamole.md that contains +the basic structure to have a recipe. 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 guacamole.md
+
+

Type the text below into the guacamole.md file:

+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

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 +

+
guacamole.md
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+

If we check the status of our project again, Git tells us that it’s +noticed the new file:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Untracked files:
+   (use "git add <file>..." to include in what will be committed)
+
+	guacamole.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 guacamole.md
+
+

and then check that the right thing happened:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+
+No commits yet
+
+Changes to be committed:
+  (use "git rm --cached <file>..." to unstage)
+
+	new file:   guacamole.md
+
+
+

Git now knows that it’s supposed to keep track of +guacamole.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 template for recipe"
+
+
+

OUTPUT +

+
[main (root-commit) f22b25e] Create a template for recipe
+ 1 file changed, 1 insertion(+)
+ create mode 100644 guacamole.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.

+

If we run git status now:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

it tells us everything is up to date. 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 f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+

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.

+
+
+ +
+
+

Where Are My Changes?

+
+

If we run ls at this point, we will still see just one +file called guacamole.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 Alfredo adds 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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lemon
+* salt
+## Instructions
+
+

When we run git status now, it tells us that a file it +already knows about has been modified:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git restore <file>..." to discard changes in working directory)
+
+	modified:   guacamole.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/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lemon
++* salt
+ ## Instructions
+
+

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. +
  3. The second line tells exactly which versions of the file Git is +comparing; df0654a and 315bf3a are unique +computer-generated labels for those versions.
  4. +
  5. The third and fourth lines once again show the name of the file +being changed.
  6. +
  7. 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.
  8. +
+

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

+
+

BASH +

+
$ git commit -m "Add basic guacamole's ingredients"
+$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ git commit -m "Add basic guacamole's ingredients"
+
+
+

OUTPUT +

+
[main 34961b1] Add basic guacamole's ingredient
+ 1 file changed, 3 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

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 recipe +by changing ‘lemon’ to ‘lime’:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole.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/guacamole.md b/guacamole.md
+index 315bf3a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,6 +1,6 @@
+ # Guacamole
+ ## Ingredients
+ * avocado
+-* lemon
++* lime
+ * salt
+ ## Instructions
+
+

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 guacamole to the traditional recipe"
+
+
+

OUTPUT +

+
[main 005937f] Modify guacamole to the traditional recipe
+ 1 file changed, 1 insertion(+)
+
+

check our status:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git log
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+    Modify guacamole to the traditional recipe
+
+commit 34961b159c27df3b475cfe4415d94a6d1fcd064d
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Add basic guacamole's ingredients
+
+commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 09:51:46 2013 -0400
+
+    Create a template for recipe
+
+
+
+ +
+
+

Word-based diffing

+
+

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

+
+
+
+
+
+ +
+
+

Paging the Log

+
+

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

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

Limit Log Size

+
+

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

+
+

BASH +

+
$ git log -1
+
+
+

OUTPUT +

+
commit 005937fbe2a98fb83f0ade869025dc2636b4dad5 (HEAD -> main)
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:14:07 2013 -0400
+
+   Modify guacamole to the traditional recipe
+
+

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

+
+

BASH +

+
$ git log --oneline
+
+
+

OUTPUT +

+
005937f (HEAD -> main) Modify guacamole to the traditional recipe
+34961b1 Add basic guacamole's ingredients
+f22b25e Create a template for recipe
+
+

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

+
+

BASH +

+
$ git log --oneline --graph
+
+
+

OUTPUT +

+
* 005937f (HEAD -> main) Modify guacamole to the traditional recipe
+* 34961b1 Add basic guacamole's ingredients
+* f22b25e Create a template for recipe
+
+
+
+
+
+
+ +
+
+

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:
  2. +
+
+

BASH +

+
$ mkdir cakes
+$ git status
+$ git add cakes
+$ git status
+
+

Note, our newly created empty directory cakes 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:
  2. +
+
+

BASH +

+
git add <directory-with-files>
+
+

Try it for yourself:

+
+

BASH +

+
$ touch cakes/brownie cakes/lemon_drizzle
+$ git status
+$ git add cakes
+$ git status
+
+

Before moving on, we will commit these changes.

+
+

BASH +

+
$ git commit -m "Add some initial cakes"
+
+
+
+
+

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 guacamole.md?

+
    +
  1. “Changes”
  2. +
  3. “Changed lemon for lime”
  4. +
  5. “Guacamole modified to the traditional recipe”
  6. +
+
+
+
+
+
+ +
+
+

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. +
  3. +

    BASH +

    +
       $ git init myfile.txt
    +   $ git commit -m "my recent changes"
    +
  4. +
  5. +

    BASH +

    +
       $ git add myfile.txt
    +   $ git commit -m "my recent changes"
    +
  6. +
  7. +

    BASH +

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

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 guacamole.md noting the rough price of +the ingredients.
  2. +
  3. Create a new file groceries.md with a list of products +and their prices for different markets.
  4. +
  5. Add changes from both files to the staging area, and commit those +changes.
  6. +
+
+
+
+
+
+ +
+
+

First we make our changes to the guacamole.md and +groceries.md files:

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado (1.35)
+* lime (0.64)
+* salt (2)
+
+
+

BASH +

+
$ nano groceries.md
+$ cat groceries.md
+
+
+

OUTPUT +

+
# Market A
+* avocado: 1.35 per unit.
+* lime: 0.64 per unit
+* salt: 2 per kg
+
+

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

+
+

BASH +

+
$ git add guacamole.md groceries.md
+
+

Or with multiple commands:

+
+

BASH +

+
$ git add guacamole.md
+$ git add groceries.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 "Write prices for ingredients and their source"
+
+
+

OUTPUT +

+
[main cc127c2]
+ Write prices for ingredients and their source
+ 2 files changed, 7 insertions(+)
+ create mode 100644 groceries.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 recipes folder:

+
+

BASH +

+
$ cd ..
+
+

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

+
+

BASH +

+
$ mkdir bio
+$ cd bio
+
+

Initialise git:

+
+

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 2024-11-01 | + + Edit this page

+

Estimated time: 25 minutes

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

We’ve been adding small changes at a time to +guacamole.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 guacamole.md, adding yet another +line.

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+An ill-considered change
+
+

Now, let’s see what we get.

+
+

BASH +

+
$ git diff HEAD guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index b36abfd..0848c8d 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -4,3 +4,4 @@
+ * lime
+ * salt
+ ## Instructions
++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 guacamole.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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..b36abfd 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,6 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
+
+

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

+
+

BASH +

+
$ git show HEAD~2 guacamole.md
+
+
+

OUTPUT +

+
commit f22b25e3233b4645dabd0d81e651fe074bd8e73b
+Author: Alfredo Linguini <a.linguini@ratatouille.fr>
+Date:   Thu Aug 22 10:07:21 2013 -0400
+
+    Create a template for recipe
+
+diff --git a/guacamole.md b/guacamole.md
+new file mode 100644
+index 0000000..df0654a
+--- /dev/null
++++ b/guacamole.md
+@@ -0,0 +1,3 @@
++# Guacamole
++## Ingredients
++## Instructions
+
+

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 was given the ID +f22b25e3233b4645dabd0d81e651fe074bd8e73b, so let’s try +this:

+
+

BASH +

+
$ git diff f22b25e3233b4645dabd0d81e651fe074bd8e73b guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++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 guacamole.md
+
+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..93a3e13 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,3 +1,7 @@
+ # Guacamole
+ ## Ingredients
++* avocado
++* lime
++* salt
+ ## Instructions
++An ill-considered change
+
+

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 guacamole.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 main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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. If +we want to go back even further, we can use a commit identifier instead, +using -s option:

+
+

BASH +

+
$ git restore -s f22b25e guacamole.md
+
+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+## Instructions
+
+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+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:   guacamole.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 guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

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

+
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

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

+
+
+ +
+
+

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. +
  3. $ git restore data_cruncher.py

  4. +
  5. $ git restore -s HEAD~1 data_cruncher.py

  6. +
  7. $ git restore -s <unique ID of last commit> data_cruncher.py

  8. +
  9. Both 2 and 4

  10. +
+
+
+
+
+
+ +
+
+

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

+
+

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

+

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

+

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

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

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

  4. +
  5. git revert [commit ID]

  6. +
  7. Type in the new commit message.

  8. +
  9. Save and close.

  10. +
+
+
+
+
+
+ +
+
+

The command git log lists project history with commit +IDs.

+

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

+
+
+
+
+
+
+ +
+
+

Understanding Workflow and History

+
+

What is the output of the last command in

+
+

BASH +

+
$ cd recipes
+$ echo "I like tomatoes, therefore I like ketchup" > ketchup.md
+$ git add ketchup.md
+$ echo "ketchup enhances pasta dishes" >> ketchup.md
+$ git commit -m "My opinions about the red sauce"
+$ git restore ketchup.md
+$ cat ketchup.md # this will print the content of ketchup.md on screen
+
+
    +
  1. +

    OUTPUT +

    +
      ketchup enhances pasta dishes
    +
  2. +
  3. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +
  4. +
  5. +

    OUTPUT +

    +
      I like tomatoes, therefore I like ketchup
    +  ketchup enhances pasta dishes
    +
  6. +
  7. +

    OUTPUT +

    +
      Error because you have changed ketchup.md without committing the changes
    +
  8. +
+
+
+
+
+
+ +
+
+

The answer is 2.

+

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

+

So, when git commit -m "My opinions about the red sauce" +is executed, the version of ketchup.md committed to the +repository is the one from the staging area and has only one line.

+

At this time, the working copy still has the second line (and

+

git status will show that the file is modified). +However, git restore ketchup.md replaces the working copy +with the most recently committed version of ketchup.md. So, +cat ketchup.md will output

+
+

OUTPUT +

+
I like tomatoes, therefore I like ketchup
+
+
+
+
+
+
+
+ +
+
+

Checking Understanding of +git diff +

+
+

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

+
+
+
+
+
+ +
+
+

Getting Rid of Staged Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

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

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

+

Using the command git restore guacamole.md now does not +give an error, but it does not restore the file either. Git helpfully +tells us that we need to use git restore --staged first to +unstage the file:

+
+

BASH +

+
$ git restore --staged guacamole.md
+
+

Now, git status gives us:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add <file>..." to update what will be committed)
+  (use "git git restore <file>..." to discard changes in working directory)
+        modified:   guacamole.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

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

+
+

BASH +

+
$ git restore guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+
+
+
+
+
+
+ +
+
+

Explore and Summarize Histories

+
+

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

+

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

+
+

BASH +

+
$ git log guacamole.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 guacamole.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 diff displays differences between commits.
  • +
  • +git restore recovers old versions of files.
  • +
+
+
+

Content from Ignoring Things

+
+

Last updated on 2024-11-01 | + + 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 receipts
+$ touch a.png b.png c.png receipts/a.jpg receipts/b.jpg
+
+

and see what Git says:

+
+

BASH +

+
$ git status
+
+
+

OUTPUT +

+
On branch main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	a.png
+	b.png
+	c.png
+	receipts/
+
+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
+receipts/
+
+

These patterns tell Git to ignore any file whose name ends in +.png and everything in the receipts 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 main
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+	.gitignore
+
+nothing added to commit but untracked files present (use "git add" to track)
+
+

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

+
+

BASH +

+
$ git add .gitignore
+$ git commit -m "Ignore png files and the receipts folder."
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working tree clean
+
+

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

+
+

BASH +

+
$ git add a.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 main
+Ignored files:
+ (use "git add -f <file>..." to include in what will be committed)
+
+        a.png
+        b.png
+        c.png
+        receipts/
+
+nothing to commit, working tree clean
+
+
+
+ +
+
+

Ignoring Nested Files

+
+

Given a directory structure that looks like:

+
+

BASH +

+
receipts/data
+receipts/plots
+
+

How would you ignore only receipts/plots and not +receipts/data?

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/plots/
+
+

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

+

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 also that because you’ve previously committed .png +files in this lesson 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 +

+
receipts/data
+receipts/images
+receipts/plots
+receipts/analysis
+
+

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

+

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

+
+
+
+
+
+ +
+
+

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

+
+

OUTPUT +

+
receipts/*               # ignore everything in receipts folder
+!receipts/data/          # do not ignore receipts/data/ contents
+
+
+
+
+
+
+
+ +
+
+

Ignoring all data Files in a Directory

+
+

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

+
+

BASH +

+
receipts/data/market_position/gps/a.dat
+receipts/data/market_position/gps/b.dat
+receipts/data/market_position/gps/c.dat
+receipts/data/market_position/gps/info.txt
+receipts/plots
+
+

What’s the shortest .gitignore rule you could write to +ignore all .dat files in +result/data/market_position/gps? Do not ignore the +info.txt.

+
+
+
+
+
+ +
+
+

Appending receipts/data/market_position/gps/*.dat will +match every file in receipts/data/market_position/gps that +ends with .dat. The file +receipts/data/market_position/gps/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. +
  3. Test your “ignore pattern” by creating some dummy files of the +form log_01, etc.

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

  6. +
  7. 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.

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

Key Points

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

Content from Remotes in GitHub

+
+

Last updated on 2024-11-01 | + + 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 start by sharing the changes we’ve made to our current project +with the world. To this end we are going to create a remote +repository that will be linked to our local repository.

+

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 +recipes:

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

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

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

+
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 recipes
+$ cd recipes
+$ git init
+
+

If you remember back to the earlier episode where we added and committed our +earlier work on guacamole.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 "recipes" 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 +guacamole.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.

+
+
+
+
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

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

+
+

BASH +

+
$ git remote add origin git@github.com:alflin/recipes.git
+
+

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

+

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:alflin/recipes.git (fetch)
+origin   git@github.com:alflin/recipes.git (push)
+
+

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

+

3. SSH Background and Setup +

+
+

Before Alfredo can connect to a remote repository, he needs to set up +a way for his computer to authenticate with GitHub so it knows it’s him +trying to connect to his remote repository.

+

We are going to set up the method that is commonly used by many +different services to authenticate access on the command line. This +method is called Secure Shell Protocol (SSH). SSH is a cryptographic +network protocol that allows secure communication between computers +using an otherwise insecure network.

+

SSH uses what is called a key pair. This is two keys that work +together to validate access. One key is publicly known and called the +public key, and the other key called the private key is kept private. +Very descriptive names.

+

You can think of the public key as a padlock, and only you have the +key (the private key) to open it. You use the public key where you want +a secure method of communication, such as your GitHub account. You give +this padlock, or public key, to GitHub and say “lock the communications +to my account with this so that only computers that have my private key +can unlock communications and send git commands as my GitHub +account.”

+

What we will do now is the minimum required to set up the SSH keys +and add the public key to a GitHub account.

+
+
+ +
+
+

Advanced SSH

+
+

A supplemental episode in this lesson discusses SSH and key pairs in +more depth and detail.

+
+
+
+

The first thing we are going to do is check if this has already been +done on the computer you’re on. Because generally speaking, this setup +only needs to happen once and then you can forget about it.

+
+
+ +
+
+

Keeping your keys secure

+
+

You shouldn’t really forget about your SSH keys, since they keep your +account secure. It’s good practice to audit your secure shell keys every +so often. Especially if you are using multiple computers to access your +account.

+
+
+
+

We will run the list command to check what key pairs already exist on +your computer.

+
+

BASH +

+
ls -al ~/.ssh
+
+

Your output is going to look a little different depending on whether +or not SSH has ever been set up on the computer you are using.

+

Alfredo has not set up SSH on his computer, so his output is

+
+

OUTPUT +

+
ls: cannot access '/c/Users/Alfredo/.ssh': No such file or directory
+
+

If SSH has been set up on the computer you’re using, the public and +private key pairs will be listed. The file names are either +id_ed25519/id_ed25519.pub or +id_rsa/id_rsa.pub depending on how the key +pairs were set up. Since they don’t exist on Alfredo’s computer, he uses +this command to create them.

+
+

3.1 Create an SSH key pair +

+

To create an SSH key pair Alfredo uses this command, where the +-t option specifies which type of algorithm to use and +-C attaches a comment to the key (here, Alfredo’s +email):

+
+

BASH +

+
$ ssh-keygen -t ed25519 -C "a.linguini@ratatouille.fr"
+
+

If you are using a legacy system that doesn’t support the Ed25519 +algorithm, use: +$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

+
+

OUTPUT +

+
Generating public/private ed25519 key pair.
+Enter file in which to save the key (/c/Users/Alfredo/.ssh/id_ed25519):
+
+

We want to use the default file, so just press Enter.

+
+

OUTPUT +

+
Created directory '/c/Users/Alfredo/.ssh'.
+Enter passphrase (empty for no passphrase):
+
+

Now, it is prompting Alfredo for a passphrase. Since he is using his +kitchen’s laptop that other people sometimes have access to, he wants to +create a passphrase. Be sure to use something memorable or save your +passphrase somewhere, as there is no “reset my password” option. Note +that, when typing a passphrase on a terminal, there won’t be any visual +feedback of your typing. This is normal: your passphrase will be +recorded even if you see nothing changing on your screen.

+
+

OUTPUT +

+
Enter same passphrase again:
+
+

After entering the same passphrase a second time, we receive the +confirmation

+
+

OUTPUT +

+
Your identification has been saved in /c/Users/Alfredo/.ssh/id_ed25519
+Your public key has been saved in /c/Users/Alfredo/.ssh/id_ed25519.pub
+The key fingerprint is:
+SHA256:SMSPIStNyA00KPxuYu94KpZgRAYjgt9g4BA4kFy3g1o a.linguini@ratatouille.fr
+The key's randomart image is:
++--[ED25519 256]--+
+|^B== o.          |
+|%*=.*.+          |
+|+=.E =.+         |
+| .=.+.o..        |
+|....  . S        |
+|.+ o             |
+|+ =              |
+|.o.o             |
+|oo+.             |
++----[SHA256]-----+
+
+

The “identification” is actually the private key. You should never +share it. The public key is appropriately named. The “key fingerprint” +is a shorter version of a public key.

+

Now that we have generated the SSH keys, we will find the SSH files +when we check.

+
+

BASH +

+
ls -al ~/.ssh
+
+
+

OUTPUT +

+
drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ./
+drwxr-xr-x 1 Alfredo   197121   0 Jul 16 14:48 ../
+-rw-r--r-- 1 Alfredo   197121 419 Jul 16 14:48 id_ed25519
+-rw-r--r-- 1 Alfredo   197121 106 Jul 16 14:48 id_ed25519.pub
+
+
+
+

3.2 Copy the public key to GitHub +

+

Now we have a SSH key pair and we can run this command to check if +GitHub can read our authentication.

+
+

BASH +

+
ssh -T git@github.com
+
+
+

OUTPUT +

+
The authenticity of host 'github.com (192.30.255.112)' can't be established.
+RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
+This key is not known by any other names
+Are you sure you want to continue connecting (yes/no/[fingerprint])? y
+Please type 'yes', 'no' or the fingerprint: yes
+Warning: Permanently added 'github.com' (RSA) to the list of known hosts.
+git@github.com: Permission denied (publickey).
+
+

Right, we forgot that we need to give GitHub our public key!

+

First, we need to copy the public key. Be sure to include the +.pub at the end, otherwise you’re looking at the private +key.

+
+

BASH +

+
cat ~/.ssh/id_ed25519.pub
+
+
+

OUTPUT +

+
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDmRA3d51X0uu9wXek559gfn6UFNF69yZjChyBIU2qKI a.linguini@ratatouille.fr
+
+

Now, going to GitHub.com, click on your profile icon in the top right +corner to get the drop-down menu. Click “Settings”, then on the settings +page, click “SSH and GPG keys”, on the left side “Access” menu. Click +the “New SSH key” button on the right side. Now, you can add the title +(Alfredo uses the title “Alfredo’s Kitchen Laptop” so he can remember +where the original key pair files are located), paste your SSH key into +the field, and click the “Add SSH key” to complete the setup.

+

Now that we’ve set that up, let’s check our authentication again from +the command line.

+
+

BASH +

+
$ ssh -T git@github.com
+
+
+

OUTPUT +

+
Hi Alfredo! You've successfully authenticated, but GitHub does not provide shell access.
+
+

Good! This output confirms that the SSH key works as intended. We are +now ready to push our work to the remote repository.

+
+

4. Push local changes to a remote +

+
+

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

+
+

BASH +

+
$ git push origin main
+
+

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

+
+

OUTPUT +

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

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

+
+
+
+

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

+
From https://github.com/alflin/recipes
+ * branch            main     -> FETCH_HEAD
+Already up-to-date.
+
+

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

+
+
+ +
+
+

GitHub GUI

+
+

Browse to your recipes 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/alflin/recipes
+ * 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/alflin/recipes
+ * 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 Collaborating

+
+

Last updated on 2024-11-01 | + + Edit this page

+

Estimated time: 25 minutes

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+
+
+ +
+
+

Practicing By Yourself

+
+

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

+
+
+
+

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

+
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

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

+

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

+

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

+

To clone the Owner’s repo into her Desktop folder, the +Collaborator enters:

+
+

BASH +

+
$ git clone git@github.com:alflin/recipes.git ~/Desktop/alflin-recipes
+
+

Replace ‘alflin’ with the Owner’s username.

+

If you choose to clone without the clone path +(~/Desktop/alflin-recipes) specified at the end, you will +clone inside your own recipes folder! Make sure to navigate to the +Desktop folder first.

+
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

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

+
+

BASH +

+
$ cd ~/Desktop/alflin-recipes
+$ nano hummus.md
+$ cat hummus.md
+
+
+

OUTPUT +

+
# Hummus
+## Ingredients
+* chickpeas
+* lemon
+* olive oil
+* salt
+
+
+

BASH +

+
$ git add hummus.md
+$ git commit -m "Add ingredients for hummus"
+
+
+

OUTPUT +

+
 1 file changed, 6 insertion(+)
+ create mode 100644 hummus.md
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+

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

+
+
+ +
+
+

Some more about remotes

+
+

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

+

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

+

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

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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

+
+
+ +
+
+

A Basic Collaborative Workflow

+
+

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

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

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

+
+
+
+
+
+ +
+
+

Switch Roles and Repeat

+
+

Switch roles and repeat the whole process.

+
+
+
+
+
+ +
+
+

Review Changes

+
+

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

+
+
+
+
+
+ +
+
+

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

+

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

+
+
+
+
+
+
+ +
+
+

Comment Changes in GitHub

+
+

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

+

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

+

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

+
+
+
+
+
+ +
+
+

Version History, Backup, and Version Control

+
+

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

+
+
+
+
+
+ +
+
+

Key Points

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

Content from Conflicts

+
+

Last updated on 2024-11-01 | + + Edit this page

+

Estimated time: 15 minutes

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+
+

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* put one avocado into a bowl.
+
+

and then push the change to GitHub:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "First step on the instructions"
+
+
+

OUTPUT +

+
[main 5ae9631] First step on the instructions
+ 1 file changed, 1 insertion(+)
+
+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ nano guacamole.md
+$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados
+
+

We can commit the change locally:

+
+

BASH +

+
$ git add guacamole.md
+$ git commit -m "Add first step"
+
+
+

OUTPUT +

+
[main 07ebc69] Add first step
+ 1 file changed, 1 insertion(+)
+
+

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

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

+
To https://github.com/alflin/recipes.git
+ ! [rejected]        main -> main (fetch first)
+error: failed to push some refs to 'https://github.com/alflin/recipes.git'
+hint: Updates were rejected because the remote contains work that you do
+hint: not have locally. This is usually caused by another repository pushing
+hint: to the same ref. You may want to first integrate the remote changes
+hint: (e.g., 'git pull ...') before pushing again.
+hint: See the 'Note about fast-forwards' in 'git push --help' for details.
+
+
A diagram showing a conflict that might occur when two sets of independent changes are merged

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

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. In our +case we want ‘the default strategy’. To use this strategy run the +following command to select it as the default thing git should do.

+
+

BASH +

+
$ git config pull.rebase false
+
+

Then attempt the pull again.

+
+

BASH +

+
$ git pull origin main
+
+
+
+
+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+<<<<<<< HEAD
+* peel the avocados
+=======
+* put one avocado into a bowl.
+>>>>>>> dabb4c8c450e8475aee9b14b4383acc99f42af1d
+
+

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

+

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

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

To finish merging, we add guacamole.md to the changes +being made by the merge and then commit:

+
+

BASH +

+
$ git add guacamole.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+All conflicts fixed but you are still merging.
+  (use "git commit" to conclude merge)
+
+Changes to be committed:
+
+	modified:   guacamole.md
+
+
+
+

BASH +

+
$ git commit -m "Merge changes from GitHub"
+
+
+

OUTPUT +

+
[main 2abf2b1] Merge changes from GitHub
+
+

Now we can push our changes to GitHub:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+
+

OUTPUT +

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

We get the merged file:

+
+

BASH +

+
$ cat guacamole.md
+
+
+

OUTPUT +

+
# Guacamole
+## Ingredients
+* avocado
+* lime
+* salt
+## Instructions
+* peel the avocados and put them into a bowl.
+
+

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

+

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

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

Conflicts can also be minimized with project management +strategies:

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

Solving Conflicts that You Create

+
+

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

+
+
+
+
+
+ +
+
+

Conflicts on Non-textual files

+
+

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

+
+
+
+
+
+ +
+
+

Let’s try it. Suppose Alfredo takes a picture of its guacamole and +calls it guacamole.jpg.

+

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

+
+

BASH +

+
$ head --bytes 1024 /dev/urandom > guacamole.jpg
+$ ls -lh guacamole.jpg
+
+
+

OUTPUT +

+
-rw-r--r-- 1 alflin 57095 1.0K Mar  8 20:24 guacamole.jpg
+
+

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

+

Now, suppose Alfredo adds guacamole.jpg to his +repository:

+
+

BASH +

+
$ git add guacamole.jpg
+$ git commit -m "Add picture of guacamole"
+
+
+

OUTPUT +

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

Suppose that Jimmy has added a similar picture in the meantime. His +is a picture of a guacamole with nachos, but it is also called +guacamole.jpg. When Alfredo tries to push, he gets a +familiar message:

+
+

BASH +

+
$ git push origin main
+
+
+

OUTPUT +

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

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

+
+

BASH +

+
$ git pull origin main
+
+

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

+
+

OUTPUT +

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

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

+
+

OUTPUT +

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

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

+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of just guacamole instead of with nachos"
+
+
+

OUTPUT +

+
[main 21032c3] Use image of just guacamole instead of with nachos
+
+

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

+
+

BASH +

+
$ git checkout 439dc8c0 guacamole.jpg
+$ git add guacamole.jpg
+$ git commit -m "Use image of guacamole with nachos instead of just guacamole"
+
+
+

OUTPUT +

+
[main da21b34] Use image of guacamole with nachos instead of just guacamole
+
+

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

+
+

BASH +

+
$ git checkout HEAD guacamole.jpg
+$ git mv guacamole.jpg guacamole-only.jpg
+$ git checkout 439dc8c0 guacamole.jpg
+$ mv guacamole.jpg guacamole-nachos.jpg
+
+

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

+
+

BASH +

+
$ git rm guacamole.jpg
+$ git add guacamole-only.jpg
+$ git add guacamole-nachos.jpg
+$ git commit -m "Use two images: just guacamole and with nachos"
+
+
+

OUTPUT +

+
[main 94ae08c] Use two images: just guacamole and with nachos
+ 2 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 guacamole-nachos.jpg
+ rename guacamole.jpg => guacamole-only.jpg (100%)
+
+

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

+
+
+
+
+
+
+ +
+
+

A Typical Work Session

+
+

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

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

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

+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . . . . . .command . . . . . . . . . .
1
2echo 100 >> numbers.txt
3
4
5
6Celebrate!
+
+
+
+
+
+ +
+
+ +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
orderaction . . . . . .command . . . . . . . . . . . . . . . . . . .
1Update localgit pull origin main
2Make changesecho 100 >> numbers.txt
3Stage changesgit add numbers.txt
4Commit changesgit commit -m "Add 100 to numbers.txt"
5Update remotegit push origin main
6Celebrate!
+
+
+
+
+
+
+ +
+
+

Key Points

+
+
    +
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +
+
+
+

Content from Open Science

+
+

Last updated on 2024-11-01 | + + Edit this page

+

Estimated time: 10 minutes

+
+ +
+
+

Overview

+
+
+
+
+

Questions

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

Objectives

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

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

+

-– John Wilbanks

+
+

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

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

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

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

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

+

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

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

Making Code Citable

+
+

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

+
+
+
+
+
+ +
+
+

How Reproducible Is My Work?

+
+

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

+
+
+
+
+
+ +
+
+

How to Find an Appropriate Data Repository?

+
+

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

+
+
+
+
+
+ +
+
+

How to Track Large Data or Image Files using Git?

+
+

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

+

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

+
+
+
+
+
+ +
+
+

Key Points

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

Content from Licensing

+
+

Last updated on 2024-11-01 | + + Edit this page

+

Estimated time: 5 minutes

+
+ +
+
+

Overview

+
+
+
+
+

Questions

+
    +
  • What licensing information should I include with my work?
  • +
+
+
+
+
+
+
+

Objectives

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

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

+

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

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

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

+

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

+

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

+
+
+ +
+
+

Can I Use Open License?

+
+

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

+
+
+
+
+
+ +
+
+

What licenses have I already accepted?

+
+

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

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

Key Points

+
+
    +
  • The LICENSE, LICENSE.md, or +LICENSE.txt file is often used in a repository to indicate +how the contents of the repo may be used by others.
  • +
  • People who incorporate General Public License (GPL’d) software into +their own software must make 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-11-01 | + + 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-11-01 | + + 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 Supplemental: Using Git from RStudio

+
+

Last updated on 2024-11-01 | + + 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 +recipes 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/recipes"

Ta-da! We have created a new project in RStudio within the existing +recipes 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. +
  3. Modify the .gitignore so that the graphs +directory is not version controlled.
  4. +
+
+
+
+
+
+ +
+
+

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.
  • +
+
+
+
+
+
+
+ + +
+ + +
+ + + + + diff --git a/instructor/discuss.html b/instructor/discuss.html new file mode 100644 index 0000000000..5da18917dc --- /dev/null +++ b/instructor/discuss.html @@ -0,0 +1,957 @@ + +Version Control with Git: Discussion +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Discussion

+

Last updated on 2024-11-01 | + + Edit this page

+ + + + + +
+ +
+ + + +

Frequently Asked Questions

+

People often have questions about Git beyond the scope of the core +material. Students who have completed the rest of the lessons might find +value in looking through the following topics.

+

Note that since this material isn’t essential for basic Git usage, it +won’t be covered by the instructor.

+

More Advanced Git Configuration

+

In Setting Up Git, we used +git config --global to set some default options for Git. It +turns out that these configuration options get stored in your home +directory in a plain text file called .gitconfig.

+
+

BASH +

+
$ cat ~/.gitconfig
+
+
+

OUTPUT +

+
[user]
+	name = Alfredo Linguini
+	email = a.linguini@ratatouille.fr
+[color]
+	ui = true
+[core]
+	editor = nano
+
+

This file can be opened in your preferred text editor. (Note that it +is recommended to continue using the git config command, as +this helps avoid introducing syntax errors.)

+

Eventually, you will want to start customizing Git’s behaviour. This +can be done by adding more entries to your .gitconfig. The +available options are described in the manual:

+
+

BASH +

+
$ git config --help
+
+

In particular, you might find it useful to add aliases. These are +like shortcuts for longer Git commands. For example, if you get sick of +typing git checkout all the time, you could run the +command:

+
+

BASH +

+
$ git config --global alias.co checkout
+
+

Now if we return to the example from Exploring History where we ran:

+
+

BASH +

+
$ git checkout f22b25e guacamole.md
+
+

we could now instead type:

+
+

BASH +

+
$ git co f22b25e guacamole.md
+
+

Styling Git’s Log

+

A good target for customization is output from the log. The default +log is quite verbose but gives no graphical hints such as information +about which commits were done locally and which were pulled from +remotes.

+

You can use git log --help and +git config --help to look for different ways to change the +log output. Try the following commands and see what effect they +have:

+
+

BASH +

+
$ git config --global alias.lg "log --graph"
+$ git config --global log.abbrevCommit true
+$ git config --global format.pretty oneline
+$ git lg
+
+

If you don’t like the effects, you can undo them with:

+
+

BASH +

+
$ git config --global --unset alias.lg
+$ git config --global --unset log.abbrevCommit
+$ git config --global --unset format.pretty
+
+
+
+ +
+
+

Undoing Git Configuration Changes

+
+

You can use the --unset flag to delete unwanted options +from .gitconfig. Another way to roll back changes is to +store your .gitconfig using Git.

+

For hints on what you might want to configure, go to GitHub and +search for “gitconfig”. You will find hundreds of repositories in which +people have stored their own Git configuration files. Sort them by the +number of stars and have a look at the top few. If you find some you +like, please check that they’re covered by an open source license before +you clone them.

+
+
+
+

Non-text Files

+

Recall when we discussed Conflicts +there was a challenge that asked, “What does Git do when there is a +conflict in an image or some other non-textual file that is stored in +version control?”

+

We will now revisit this in more detail.

+

Many people want to version control non-text files, such as images, +PDFs and Microsoft Office or LibreOffice documents. It is true that Git +can handle these filetypes (which fall under the banner of “binary” file +types). However, just because it can be done doesn’t mean it +should be done.

+

Much of Git’s magic comes from being able to do line-by-line +comparisons (“diffs”) between files. This is generally easy for +programming source code and marked up text. For non-text files, a diff +can usually only detect that the files have changed but can’t say how or +where.

+

This has various impacts on Git’s performance and will make it +difficult to compare different versions of your project.

+

For a basic example to show the difference it makes, we’re going to +go see what would have happened if Alfredo had tried using outputs from +a word processor instead of plain text.

+

Create a new directory and go into it:

+
+

BASH +

+
$ mkdir recipes-nontext
+$ cd recipes-nontext
+
+

Use a program such as Microsoft Word or LibreOffice Writer to create +a new document. Enter the same text that we began with before:

+
+

OUTPUT +

+
# Ingredients
+# Instructions
+
+

Save the document into the recipes-nontext directory +with the name of guacamole.doc. Back in the terminal, run +the usual commands for setting up a new Git repository:

+
+

BASH +

+
$ git init
+$ git add guacamole.doc
+$ git commit -m "Create a template for recipe"
+
+

Then make the same changes to guacamole.doc that we (or +Alfredo) previously made to guacamole.md.

+
+

OUTPUT +

+
# Ingredients
+- avocado
+- lemon
+- salt
+# Instructions
+
+

Save and close the word processor. Now see what Git thinks of your +changes:

+
+

BASH +

+
$ git diff
+
+
+

OUTPUT +

+
diff --git a/guacamole.doc b/guacamole.doc
+index 53a66fd..6e988e9 100644
+Binary files a/guacamole.doc and b/guacamole.doc differ
+
+

Compare this to the earlier git diff obtained when using +text files:

+
+

OUTPUT +

+
diff --git a/guacamole.md b/guacamole.md
+index df0654a..315bf3a 100644
+--- a/guacamole.md
++++ b/guacamole.md
+@@ -1,2 +1,5 @@
+ # Ingredients
++- avocado
++- lemon
++- salt
+ # Instructions
+
+

Notice how plain text files give a much more informative diff. You +can see exactly which lines changed and what the changes were.

+

An uninformative git diff is not the only consequence of +using Git on binary files. However, most of the other problems boil down +to whether or not a good diff is possible.

+

This isn’t to say you should never use Git on binary files. +A rule of thumb is that it’s OK if the binary file won’t change very +often, and if it does change, you don’t care about merging in small +differences between versions.

+

We’ve already seen how a word processed report will fail this test. +An example that passes the test is a logo for your organization or +project. Even though a logo will be stored in a binary format such as +jpg or png, you can expect it will remain +fairly static through the lifetime of your repository. On the rare +occasion that branding does change, you will probably just want to +replace the logo completely rather than merge little differences in.

+

Removing a File

+

Adding and modifying files are not the only actions one might take +when working on a project. It might be required to remove a file from +the repository.

+

Create a new file for the invisible ink:

+
+

BASH +

+
$ echo "This is where we keep the secret sauce" > invisible.md
+
+

Now add to the repository like you have learned earlier:

+
+

BASH +

+
$ git add invisible.md
+$ git commit -m 'Add secret sauce'
+$ git status
+
+
+

OUTPUT +

+
On branch main
+nothing to commit, working directory clean
+
+

Invisible ink is not a real food. That was a silly idea. Let us +remove it from the disk and let Git know about it:

+
+

BASH +

+
$ git rm invisible.md
+$ git status
+
+
+

OUTPUT +

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

The change has been staged. Now commit the removal, and remove the +file from the repository itself. Note that the file will be removed in +the new commit. The previous commit will still have the file, if you +were to retrieve that specific commit.

+
+

BASH +

+
$ git commit -m 'Remove info on Invisible ink.  It is not an edible sauce!'
+
+

Removing a File with Unix

+

Sometimes we might forget to remove the file through Git. If you +removed the file with Unix rm instead of using +git rm, no worries, Git is smart enough to notice the +missing file. Let us recreate the file and commit it again.

+
+

BASH +

+
$ echo "This is another way to make invisible ink" > secret.md
+$ git add secret.md
+$ git commit -m 'Add invisible ink again'
+
+

Now we remove the file with Unix rm:

+
+

BASH +

+
$ rm secret.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+   (use "git add/rm <file>..." to update what will be committed)
+   (use "git checkout -- <file>..." to discard changes in working directory)
+
+    deleted:    secret.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

See how Git has noticed that the file secret.md has been +removed from the disk. The next step is to “stage” the removal of the +file from the repository. This is done with the command +git rm just as before.

+
+

BASH +

+
$ git rm secret.md
+$ git status
+
+
+

OUTPUT +

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

The change that was made in Unix has now been staged and needs to be +committed.

+
+

BASH +

+
$ git commit -m 'Remove info on invisible ink, again!'
+
+

Renaming a File

+

Another common change when working on a project is to rename a +file.

+

Create a file for the whitesauce recipe:

+
+

BASH +

+
$ echo "Very fun recipe to do" > whitesauce.md
+
+

Add it to the repository:

+
+

BASH +

+
$ git add whitesauce.md
+$ git commit -m 'Add white sauce recipe'
+
+

We all know that white sauce has a more sophisticated name.

+

Rename the file whitesauce.md to +bechamel.md with Git:

+
+

BASH +

+
$ git mv whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes to be committed:
+  (use "git reset HEAD <file>..." to unstage)
+
+	renamed:    whitesauce.md ->  bechamel.md
+
+

The final step is commit our change to the repository:

+
+

BASH +

+
$ git commit -m 'Use the French name for the whitesauce'
+
+

Renaming a File with Unix

+

If you forgot to use Git and you used Unix mv instead of +git mv, you will have a touch more work to do but Git will +be able to deal with it. Let’s try again renaming the file, this time +with Unix mv. First, we need to recreate the +krypton.txt file:

+
+

BASH +

+
$ echo "Very fun recipe to do" > whitesauce.md
+$ git add whitesauce.md
+$ git commit -m 'Add white sauce recipe'
+
+

Let us rename the file and see what Git can figured out by +itself:

+
+

BASH +

+
$ mv whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes not staged for commit:
+  (use "git add/rm <file>..." to update what will be committed)
+  (use "git checkout -- <file>..." to discard changes in working directory)
+
+        deleted:    whitesauce.md
+
+Untracked files:
+  (use "git add <file>..." to include in what will be committed)
+
+    bechamel.md
+
+no changes added to commit (use "git add" and/or "git commit -a")
+
+

Git has noticed that the file whitesauce.md has +disappeared from the file system and a new file bechamel.md +has showed up.

+

Add those changes to the staging area:

+
+

BASH +

+
$ git add whitesauce.md bechamel.md
+$ git status
+
+
+

OUTPUT +

+
On branch main
+Changes to be committed:
+  (use "git reset HEAD <file>..." to unstage)
+
+    renamed:    whitesauce.md -> bechamel.md
+
+
+

Notice how Git has now figured out that the +whitesauce.md has not disappeared - it has simply been +renamed.

+

The final step, as before, is to commit our change to the +repository:

+
+

BASH +

+
$ git commit -m 'Use the French name for the whitesauce'
+
+

Further .gitignore concepts

+

For additional documentation on .gitignore, please reference the official git +documentation.

+

In the ignore exercise, learners were presented with two variations +of ignoring nested files. Depending on the organization of your +repository, one may suit your needs over another. Keep in mind that the +way that Git travels along directory paths can be confusing.

+

Sometimes the ** pattern comes in handy, too, which +matches multiple directory levels. E.g. **/results/plots/* +would make git ignore the results/plots directory in any +root directory.

+
+
+ +
+
+

Ignoring Nested Files: Challenge Problem

+
+

Given a directory structure that looks like:

+
+

BASH +

+
results/data
+results/plots
+results/run001.log
+results/run002.log
+
+

And a .gitignore that looks like:

+
+

OUTPUT +

+
*.csv
+
+

How would you track all of the contents of +results/data/, including *.csv files, but +ignore the rest of results/?

+
+
+
+
+
+ +
+
+

To do this, your .gitignore would look like this:

+
+

OUTPUT +

+
*.csv                 # ignore the .csv files
+results/*             # ignore the files in the results directory
+!results/data/        # do not ignore the files in results/data
+!results/data/*       # do not ignore the .csv files in reults/data
+
+
+
+
+
+
+
+ + +
+
+ + + diff --git a/instructor/images.html b/instructor/images.html new file mode 100644 index 0000000000..49a94fc51b --- /dev/null +++ b/instructor/images.html @@ -0,0 +1,637 @@ + + + + + +Version Control with Git: All Images + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Automated Version Control

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

Setting Up Git

+

Creating a Repository

+

Tracking Changes

+
+

Figure 1

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

+

Figure 2

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

Exploring History

+
+

Figure 1

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

+

Figure 2

+ +
A diagram showing the entire git workflow: local changes are staged using git add, applied to the local repository using git commit, and can be restored from the repository using git checkout +

Ignoring Things

+

Remotes in GitHub

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

+

Figure 5

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

+

Figure 6

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

+

Figure 7

+ +
Clicking the "Copy to Clipboard" button on GitHub to obtain the repository's URL

+

Figure 8

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

Collaborating

+
+

Figure 1

+ +
A screenshot of the GitHub Collaborators settings page, which is accessed by clicking "Settings" then "Collaborators"

+

Figure 2

+ +
A diagram showing that "git clone" can create a copy of a remote GitHub repository, allowing a second person to create their own local repository that they can make changes to.

Conflicts

+
+

Figure 1

+ +
A diagram showing a conflict that might occur when two sets of independent changes are merged

Open Science

+

Licensing

+

Citation

+

Hosting

+

Supplemental: Using Git from RStudio

+
+

Figure 1

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

+

Figure 2

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

+

Figure 3

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

+

Figure 4

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

+

Figure 5

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

+

Figure 6

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

+

Figure 7

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

+

Figure 8

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

+

Figure 9

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

+

Figure 10

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

+
+
+
+ + +
+ + +
+ + + + + diff --git a/instructor/index.html b/instructor/index.html new file mode 100644 index 0000000000..51132b269f --- /dev/null +++ b/instructor/index.html @@ -0,0 +1,694 @@ + +Version Control with Git: Summary and Schedule +
+ Version Control with Git +
+ +
+
+ + + + + +
+

Summary and Schedule

+ + +

Jimmy and Alfredo have been hired by Ratatouille restaurant (a +special restaurant from Euphoric State University) to investigate if it +is possible to make the best recipes archive ever. They want to be able +to work on indexing the prices at the same time, but they have run into +problems doing this in the past. If they take turns, each one will spend +a lot of time waiting for the other to finish, but if they work on their +own copies and email changes back and forth things will be lost, +overwritten, or duplicated.

+

A colleague suggests using version control to manage +their work. Version control is better than mailing files back and +forth:

+
  • Nothing that is committed to version control is ever lost, unless +you work really, really hard at losing it. Since all old versions of +files are saved, it’s always possible to go back in time to see exactly +who wrote what on a particular day, or what version of a program was +used to generate a particular set of results.

  • +
  • As we have this record of who made what changes when, we know who +to ask if we have questions later on, and, if needed, revert to a +previous version, much like the “undo” feature in an editor.

  • +
  • When several people collaborate in the same project, it’s +possible to accidentally overlook or overwrite someone’s changes. The +version control system automatically notifies users whenever there’s a +conflict between one person’s work and another’s.

  • +

Teams are not the only ones to benefit from version control: lone +researchers can benefit immensely. Keeping a record of what was changed, +when, and why is extremely useful for all researchers if they ever need +to come back to the project later on (e.g., a year later, when memory +has faded).

+

Version control is the lab notebook of the digital world: it’s what +professionals use to keep track of what they’ve done and to collaborate +with other people. Every large software development project relies on +it, and most programmers use it for their small jobs as well. And it +isn’t just for software: books, papers, small data sets, and anything +that changes over time or needs to be shared can and should be stored in +a version control system.

+
+
+ +
+
+

Prerequisites

+
+

In this lesson we use Git from the Unix Shell. Some previous +experience with the shell is expected, but isn’t mandatory.

+
+
+
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

+ The actual schedule may vary slightly depending on the topics and exercises chosen by the instructor. +

+

Installing Git

+

Since several Carpentries lessons rely on Git, please see this +section of the workshop template for instructions on installing Git +for various operating systems.

+

Creating a GitHub Account

+

You will need an account for GitHub +to follow episodes 7 & 8 in this lesson.

+
  1. Go to https://github.com and follow the “Sign up” link at the +top-right of the window.
  2. +
  3. Follow the instructions to create an account.
  4. +
  5. Verify your email address with GitHub.
  6. +
  7. Configure multifactor authentication (see below).
  8. +
+

Multi-factor Authentication

+

In 2023, GitHub introduced a requirement for all accounts to have multi-factor +authentication (2FA) configured for extra security. Several options +exist for setting up 2FA, which are summarised here:

+
  1. If you already use an authenticator app, like Google +Authenticator or Duo +Mobile on your smartphone for example, add +GitHub to that app.
  2. +
  3. If you have access to a smartphone but do not already use an +authenticator app, install one and add +GitHub to the app.
  4. +
  5. If you do not have access to a smartphone or do not want to install +an authenticator app, you have two options: +
    1. +set +up 2FA via text message (list +of countries where authentication by SMS is supported), or
    2. +
    3. +use +a hardware security key like YubiKey +or the Google +Titan key.
    4. +
  6. +

The GitHub documentation provides more +details about configuring 2FA.

+
+

Preparing Your Working Directory

+

We’ll do our work in the Desktop folder so make sure you +change your working directory to it with:

+
+

BASH +

+
$ cd
+$ cd Desktop
+
+
+ + +
+
+ + + diff --git a/instructor/instructor-notes.html b/instructor/instructor-notes.html new file mode 100644 index 0000000000..91057f87a4 --- /dev/null +++ b/instructor/instructor-notes.html @@ -0,0 +1,915 @@ + + + + + +Version Control with Git: Instructor Notes + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+

Instructor Notes

+ + +

Using a software tool to handle the versions of your project files +lets you focus on the more interesting/innovative aspects of your +project.

+
    +
  • Version control’s advantages +
      +
    • It’s easy to set up
    • +
    • Every copy of a Git repository is a full backup of a project and its +history
    • +
    • A few easy-to-remember commands are all you need for most day-to-day +version control tasks
    • +
    • The GitHub hosting service +provides a web-based collaboration service
    • +
    +
  • +
  • Two main concepts +
      +
    • +commit: a recorded set of changes in your project’s +files
    • +
    • +repository: the history of all your project’s commits
    • +
    +
  • +
  • Why use GitHub? +
      +
    • No need for a server: easy to set up
    • +
    • GitHub’s strong community: your colleagues are probably already +there
    • +
    +
  • +
+

Overall +

+
+

Version control might be the most important topic we teach, but Git +is definitely the most complicated tool. However, GitHub presently +dominates the open software repository landscape, so the time and effort +required to teach fundamental Git is justified and worthwhile.

+

Because of this complexity, we don’t teach novice learners about many +interesting topics, such as branching, hashes, and commit objects.

+

Instead we try to convince them that version control is useful for +researchers working in teams or not, because it is

+
    +
  • a better way to “undo” changes,
  • +
  • a better way to collaborate than mailing files back and forth, +and
  • +
  • a better way to share your code and other scientific work with the +world.
  • +

Teaching Notes +

+
+
    +
  • You can “split” your shell so that recent commands remain in view +using this +script.

  • +
  • Make sure the network is working before starting this +lesson.

  • +
  • Drawings are particularly useful in this lesson: if you have a +whiteboard, use +it!

  • +
  • Version control is usually not the first subject in a workshop, +so get learners to create a GitHub account after the session before. +Remind learners that the username and email they use for GitHub (and +setup during Git configuration) will be viewable to the public by +default. However, there are many reasons why a learner may not want +their personal information viewable, and GitHub has resources +for keeping an email address private.

  • +
  • If some learners are using Windows, there will inevitably be +issues merging files with different line endings. (Even if everyone’s on +some flavor of Unix, different editors may or may not add a newline to +the last line of a file.) Take a moment to explain these issues, since +learners will almost certainly trip over them again. If learners are +running into line ending problems, GitHub has a page +that helps with troubleshooting. Specifically, the section +on refreshing a repository may be helpful if learners need to change +the core.autocrlf setting after already having made one or +more commits.

  • +
  • We don’t use a Git GUI in these notes because we haven’t found +one that installs easily and runs reliably on the three major operating +systems, and because we want learners to understand what commands are +being run. That said, instructors should demo a GUI on their desktop at +some point during this lesson and point learners at this page.

  • +
  • Instructors should show learners graphical diff/merge tools like +DiffMerge.

  • +
  • When appropriate, explain that we teach Git rather than CVS, +Subversion, or Mercurial primarily because of GitHub’s growing +popularity: CVS and Subversion are now seen as legacy systems, and +Mercurial isn’t nearly as widely used in the sciences right +now.

  • +
  • +

    Further resources:

    + +
  • +

+Automated Version Control +

+
+
    +
  • Ask, “Who uses ‘undo’ in their editor?” All say “Me”. ‘Undo’ is +the simplest form of version control.

  • +
  • Give learners a five-minute overview of what version control does +for them before diving into the watch-and-do practicals. Most of them +will have tried to co-author papers by emailing files back and forth, or +will have biked into the office only to realize that the USB key with +last night’s work is still on the kitchen table. Instructors can also +make jokes about directories with names like “final version”, “final +version revised”, “final version with reviewer three’s corrections”, +“really final version”, and, “come on this really has to be the last +version” to motivate version control as a better way to collaborate and +as a better way to back work up.

  • +

+Setting Up Git +

+
+
    +
  • +

    We suggest instructors and students use nano as the +text editor for this lessons because

    +
      +
    • it runs in all three major operating systems,
    • +
    • it runs inside the shell (switching windows can be confusing to +students), and
    • +
    • it has shortcut help at the bottom of the window.
    • +
    +

    Please point out to students during setup that they can and should +use another text editor if they’re already familiar with it.

    +
  • +
  • When setting up Git, be very clear what learners have to enter: +it is common for them to edit the instructor’s details (e.g. email). +Check at the end using git config --list.

  • +
  • When setting up the default branch name, if learners have a Git +version older than 2.28, the default branch name can be changed for the +lesson using git branch -M main if there are currently +commits in the repository, or git checkout -b main if there +are no commits/the repository is completely empty.

  • +

+Creating a Repository +

+
+
    +
  • When you do git status, Mac users may see a +.DS_Store file showing as untracked. This a file that Mac +OS creates in each directory.

  • +
  • +

    The challenge “Places to create repositories” tries to reinforce +the idea that the .git folder contains the whole Git repo +and deleting this folder undoes a git init. It also gives +the learner the way to fix the common mistake of putting unwanted +folders (like Desktop) under version control.

    +

    Instead of removing the .git folder directly, you can +choose to move it first to a safer directory and remove it from +there:

    +
    +

    BASH +

    +
    $ mv .git temp_git
    +$ rm -rf  temp_git
    +
    +

    The challenge suggests that it is a bad idea to create a Git repo +inside another repo. For more discussion on this topic, please see this +issue.

    +
  • +

+Tracking Changes +

+
+
    +
  • It’s important that learners do a full commit cycle by themselves +(make changes, git diff, git add, and +git commit). The “bio repository” challenge +does that.

  • +
  • This is a good moment to show a diff with a graphical diff tool. +If you skip it because you’re short on time, show it once in +GitHub.

  • +
  • One thing may cause confusion is recovering old versions. If, +instead of doing $ git checkout f22b25e guacamole.md, +someone does $ git checkout f22b25e, they wind up in the +“detached HEAD” state and confusion abounds. It’s then possible to keep +on committing, but things like git push origin main a bit +later will not give easily comprehensible results. It also makes it look +like commits can be lost. To “re-attach” HEAD, use +git checkout main.

  • +
  • This is a good moment to show a log within a Git GUI. If you skip +it because you’re short on time, show it once in GitHub.

  • +

+Ignoring Things +

+
+

Just remember that you can use wildcards and regular expressions to +ignore a particular set of files in .gitignore.

+

+Remotes in GitHub +

+
+
    +
  • Make it clear that Git and GitHub are not the same thing: Git is +an open source version control tool, GitHub is a company that hosts Git +repositories in the web and provides a web interface to interact with +repos they host.

  • +
  • It is very useful to draw a diagram showing the different +repositories involved.

  • +
  • When pushing to a remote, the output from Git can vary slightly +depending on what leaners execute. The lesson displays the output from +git if a learner executes git push origin main. However, +some learners might use syntax suggested by GitHub for pushing to a +remote with an existing repository, which is +git push -u origin main. Learners using syntax from GitHub, +git push -u origin main, will have slightly different +output, including the line +Branch main set up to track remote branch main from origin by rebasing.

  • +

+Collaborating +

+
+
    +
  • Decide in advance whether all the learners will work in one +shared repository, or whether they will work in pairs (or other small +groups) in separate repositories. The former is easier to set up; the +latter runs more smoothly.

  • +
  • Role playing between two instructors can be effective when +teaching the collaboration and conflict sections of the lesson. One +instructor can play the role of the repository owner, while the second +instructor can play the role of the collaborator. If it is possible, try +to use two projectors so that the computer screens of both instructors +can be seen. This makes for a very clear illustration to the students as +to who does what.

  • +
  • It is also effective to pair up students during this lesson and +assign one member of the pair to take the role of the owner and the +other the role of the collaborator. In this setup, challenges can +include asking the collaborator to make a change, commit it, and push +the change to the remote repository so that the owner can then retrieve +it, and vice-versa. The role playing between the instructors can get a +bit “dramatic” in the conflicts part of the lesson if the instructors +want to inject some humor into the room.

  • +
  • If you don’t have two projectors, have two instructors at the +front of the room. Each instructor does their piece of the collaboration +demonstration on their own computer and then passes the projector cord +back and forth with the other instructor when it’s time for them to do +the other part of the collaborative workflow. It takes less than 10 +seconds for each switchover, so it doesn’t interrupt the flow of the +lesson. And of course it helps to give each of the instructors a +different-colored hat, or put different-colored sticky notes on their +foreheads.

  • +
  • +

    If you’re the only instructor, the best way to create is clone +the two repos in your Desktop, but under different names, e.g., pretend +one is your computer at work:

    +
    +

    BASH +

    +
    $ git clone https://github.com/alflin/recipes.git recipes-at-work
    +
    +
  • +
  • +

    It’s very common that learners mistype the remote alias or the +remote URL when adding a remote, so they cannot push. You +can diagnose this with git remote -v and checking carefully +for typos.

    +
      +
    • To fix a wrong alias, you can do +git remote rename <old> <new>.
    • +
    • To fix a wrong URL, you can do +git remote set-url <alias> <newurl>.
    • +
    +
  • +
  • Before cloning the repo, be sure that nobody is inside another +repo. The best way to achieve this is moving to the Desktop +before cloning: cd && cd Desktop.

  • +
  • +

    If both repos are in the Desktop, have them to clone +their collaborator repo under a given directory using a second +argument:

    +
    +

    BASH +

    +
    $ git clone https://github.com/alflin/recipes.git alflin-recipes
    +
    +
  • +
  • The most common mistake is that learners push before +pulling. If they pull afterward, they may get +a conflict.

  • +
  • Conflicts, sometimes weird, will start to arise. Stay tight: +conflicts are next.

  • +
  • Learners may have slightly different output from +git push and git pull depending on the version +of git, and if upstream (-u) is used.

  • +

+Conflicts +

+
+
    +
  • Expect the learners to make mistakes. Expect yourself to +make mistakes. This happens because it is late in the lesson and +everyone is tired.

  • +
  • +

    If you’re the only instructor, the best way to create a conflict +is:

    +
      +
    • Clone your repo in a different directory, pretending is your +computer at work: +git clone https://github.com/alflin/recipes.git recipes-at-work.
    • +
    • At the office, you make a change, commit and push.
    • +
    • At your laptop repo, you (forget to pull and) make a change, commit +and try to push.
    • +
    • +git pull now and show the conflict.
    • +
    +
  • +
  • Learners usually forget to git add the file after +fixing the conflict and just (try to) commit. You can diagnose this with +git status.

  • +
  • +

    Remember that you can discard one of the two parents of the +merge:

    +
      +
    • discard the remote file, +git checkout --ours conflicted_file.txt +
    • +
    • discard the local file, +git checkout --theirs conflicted_file.txt +
    • +
    +

    You still have to git add and git commit +after this. This is particularly useful when working with binary +files.

    +
  • +
  • Keep in mind that depending on the Git version used, the outputs +for git push and git pull can vary +slightly.

  • +

+Open Science +

+

+Licensing +

+
+

We teach about licensing because questions about who owns what, or +can use what, arise naturally once we start talking about using public +services like GitHub to store files. Also, the discussion gives learners +a chance to catch their breath after what is often a frustrating couple +of hours.

+

The Creative Commons family of licenses is recommended for many types +of works (including software documentation and images used in software) +but not software itself. Creative Commons recommends +a software-specific license instead.

+

+Citation +

+

+Hosting +

+
+

A common concern for learners is having their work publicly available +on GitHub. While we encourage open science, sometimes private repos are +the only choice. It’s always interesting to mention the options to have +web-hosted private repositories.

+

Automated Version Control

+

Setting Up Git

+

Creating a Repository

+

Tracking Changes

+

Exploring History

+

Ignoring Things

+

Remotes in GitHub

+

Collaborating

+

Conflicts

+

Open Science

+

Licensing

+

Citation

+

Hosting

+

Supplemental: Using Git from RStudio

+
+
+
+
+ + +
+ + +
+ + + + + diff --git a/instructor/key-points.html b/instructor/key-points.html new file mode 100644 index 0000000000..a881e101f4 --- /dev/null +++ b/instructor/key-points.html @@ -0,0 +1,641 @@ + + + + + +Version Control with Git: Key Points + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Automated Version Control

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

Setting Up Git

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

Creating a Repository

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

Tracking Changes

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

Exploring History

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

Ignoring Things

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

Remotes in GitHub

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

Collaborating

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

Conflicts

+
+
    +
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +

Open Science

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

Licensing

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

Citation

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

Hosting

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

Supplemental: Using Git from RStudio

+
+
    +
  • Using RStudio’s Git integration allows you to version control a +project over time.
  • +
+
+
+
+ + +
+ + +
+ + + + + diff --git a/instructor/profiles.html b/instructor/profiles.html new file mode 100644 index 0000000000..7a2a230958 --- /dev/null +++ b/instructor/profiles.html @@ -0,0 +1,434 @@ + +Version Control with Git: Learner Profiles +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Learner Profiles

+ +

This is a placeholder file. Please add content here.

+ +
+
+ + +
+
+ + + diff --git a/instructor/reference.html b/instructor/reference.html new file mode 100644 index 0000000000..e99f7d6b94 --- /dev/null +++ b/instructor/reference.html @@ -0,0 +1,575 @@ + +Version Control with Git: Git Cheatsheets for Quick Reference +
+ Version Control with Git +
+ +
+
+ + + + + +
+
+

Git Cheatsheets for Quick Reference

+

Last updated on 2024-11-01 | + + Edit this page

+ + + + + +
+ +
+ + + +

Git Cheatsheets for Quick Reference

+
  • Printable Git cheatsheets in several languages are available here (English +version). More material is available from the GitHub training website.
  • +
  • An interactive +one-page visualisation about the relationships between workspace, +staging area, local repository, upstream repository, and the commands +associated with each (with explanations).
  • +
  • Both resources are also available in other languages (e.g. Spanish, +French, and more).
  • +
  • Happy Git and GitHub for the +useR” is an accessible, free online book by Jenny Bryan on how to +setup and use Git and GitHub with specific references on the integration +of Git with RStudio and working with Git in R.
  • +
  • +Open +Scientific Code using Git and GitHub - A collection of explanations +and short practical exercises to help researchers learn more about +version control and open source software.
  • +

Glossary

+
changeset
+
+A group of changes to one or more files that are or will be added to a +single commit in a version control repository. +
+
commit
+
+To record the current state of a set of files (a changeset) in a version +control repository. As a noun, the result +of committing, i.e. a recorded changeset in a repository. If a commit +contains changes to multiple files, all of the changes are recorded +together. +
+
conflict
+
+A change made by one user of a version +control system that is incompatible with changes made by other +users. Helping users resolve conflicts is one of +version control’s major tasks. +
+
HTTP
+
+The Hypertext Transfer Protocol used for sharing +web pages and other data on the World Wide Web. +
+
merge
+
+(a repository): To reconcile two sets of changes to a repository. +
+
protocol
+
+A set of rules that define how one computer communicates with another. +Common protocols on the Internet include HTTP and SSH. +
+
remote
+
+(of a repository) A version control repository +connected to another, in such way that both can be kept in sync +exchanging commits. +
+
repository
+
+A storage area where a version control +system stores the full history of commits of a +project and information about who changed what, when. +
+
resolve
+
+To eliminate the conflicts between two or more +incompatible changes to a file or set of files being managed by a version control system. +
+
revision
+
+A synonym for commit. +
+
SHA-1
+
+SHA-1 hashes is what +Git uses to compute identifiers, including for commits. To compute +these, Git uses not only the actual change of a commit, but also its +metadata (such as date, author, message), including the identifiers of +all commits of preceding changes. This makes Git commit IDs virtually +unique. I.e., the likelihood that two commits made independently, even +of the same change, receive the same ID is exceedingly small. +
+
SSH
+
+The Secure Shell protocol used for secure +communication between computers. +
+
timestamp
+
+A record of when a particular event occurred. +
+
version control
+
+A tool for managing changes to a set of files. Each set of changes +creates a new commit of the files; the version +control system allows users to recover old commits reliably, and helps +manage conflicting changes made by different users. +
+
+
+ + +
+
+ + + diff --git a/key-points.html b/key-points.html new file mode 100644 index 0000000000..bc0ba87681 --- /dev/null +++ b/key-points.html @@ -0,0 +1,639 @@ + + + + + +Version Control with Git: Key Points + + + + + + + + + + + + +
+ Version Control with Git +
+ +
+
+ + + + + + +
+
+ + +

Automated Version Control

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

Setting Up Git

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

Creating a Repository

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

Tracking Changes

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

Exploring History

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

Ignoring Things

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

Remotes in GitHub

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

Collaborating

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

Conflicts

+
+
    +
  • Conflicts occur when two or more people change the same lines of the +same file.
  • +
  • The version control system does not allow people to overwrite each +other’s changes blindly, but highlights conflicts so that they can be +resolved.
  • +

Open Science

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

Licensing

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

Citation

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

Hosting

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

Supplemental: Using Git from RStudio

+
+
    +
  • Using RStudio’s Git integration allows you to version control a +project over time.
  • +
+
+
+
+ + +
+ + +
+ + + + + diff --git a/link.svg b/link.svg new file mode 100644 index 0000000000..88ad82769b --- /dev/null +++ b/link.svg @@ -0,0 +1,12 @@ + + + + + + diff --git a/md5sum.txt b/md5sum.txt new file mode 100644 index 0000000000..13303e1a0e --- /dev/null +++ b/md5sum.txt @@ -0,0 +1,24 @@ +"file" "checksum" "built" "date" +"CODE_OF_CONDUCT.md" "c93c83c630db2fe2462240bf72552548" "site/built/CODE_OF_CONDUCT.md" "2024-11-01" +"LICENSE.md" "b24ebbb41b14ca25cf6b8216dda83e5f" "site/built/LICENSE.md" "2024-11-01" +"config.yaml" "69e678021a92f74f922e53d180d05f47" "site/built/config.yaml" "2024-11-01" +"index.md" "a37c98b62b9cd48ff67c51cea5240a1f" "site/built/index.md" "2024-11-01" +"episodes/01-basics.md" "78184e84f5bf3b0dd88de3918e927591" "site/built/01-basics.md" "2024-11-01" +"episodes/02-setup.md" "ff206706b9e5521d474bd7b8e8ccc832" "site/built/02-setup.md" "2024-11-01" +"episodes/03-create.md" "c1198fc3106059d83fd8078d57fbbfef" "site/built/03-create.md" "2024-11-01" +"episodes/04-changes.md" "722631c230dc97143a267bff3739f768" "site/built/04-changes.md" "2024-11-01" +"episodes/05-history.md" "c535c544c5d01637f78f2cc6031196cb" "site/built/05-history.md" "2024-11-01" +"episodes/06-ignore.md" "3a56f9255434111624a69a81713d00e4" "site/built/06-ignore.md" "2024-11-01" +"episodes/07-github.md" "cc33245b998145b54cfbfc1a647a523d" "site/built/07-github.md" "2024-11-01" +"episodes/08-collab.md" "26c15a5971a7caef2daf17c84e72d3c9" "site/built/08-collab.md" "2024-11-01" +"episodes/09-conflict.md" "1a602107bd9804f23d94c403da504d8e" "site/built/09-conflict.md" "2024-11-01" +"episodes/10-open.md" "6504a09be66b6c32dc3bc929da9ae50e" "site/built/10-open.md" "2024-11-01" +"episodes/11-licensing.md" "928f7fe569e838941cdd45cd34657573" "site/built/11-licensing.md" "2024-11-01" +"episodes/12-citation.md" "c74aa1d0c8f60e69bdb7827560f2ac53" "site/built/12-citation.md" "2024-11-01" +"episodes/13-hosting.md" "c390f6e5ab0017576241ff881a26604c" "site/built/13-hosting.md" "2024-11-01" +"episodes/14-supplemental-rstudio.md" "fb775c44625313a1b5adc7b012b3766e" "site/built/14-supplemental-rstudio.md" "2024-11-01" +"instructors/instructor-notes.md" "688d07f9e69038f83982baab441c82dd" "site/built/instructor-notes.md" "2024-11-01" +"learners/discuss.md" "a84433e59f99f287b2e426f42ed41d94" "site/built/discuss.md" "2024-11-01" +"learners/reference.md" "d976a57639fa49361d9c8431850cde6a" "site/built/reference.md" "2024-11-01" +"learners/setup.md" "19ccf15a75716fe39f1116abf68a380d" "site/built/setup.md" "2024-11-01" +"profiles/learner-profiles.md" "60b93493cf1da06dfd63255d73854461" "site/built/learner-profiles.md" "2024-11-01" diff --git a/mstile-150x150.png b/mstile-150x150.png new file mode 100644 index 0000000000..8136f75e7a Binary files /dev/null and b/mstile-150x150.png differ diff --git a/pkgdown.css b/pkgdown.css new file mode 100644 index 0000000000..80ea5b838a --- /dev/null +++ b/pkgdown.css @@ -0,0 +1,384 @@ +/* Sticky footer */ + +/** + * Basic idea: https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ + * Details: https://github.com/philipwalton/solved-by-flexbox/blob/master/assets/css/components/site.css + * + * .Site -> body > .container + * .Site-content -> body > .container .row + * .footer -> footer + * + * Key idea seems to be to ensure that .container and __all its parents__ + * have height set to 100% + * + */ + +html, body { + height: 100%; +} + +body { + position: relative; +} + +body > .container { + display: flex; + height: 100%; + flex-direction: column; +} + +body > .container .row { + flex: 1 0 auto; +} + +footer { + margin-top: 45px; + padding: 35px 0 36px; + border-top: 1px solid #e5e5e5; + color: #666; + display: flex; + flex-shrink: 0; +} +footer p { + margin-bottom: 0; +} +footer div { + flex: 1; +} +footer .pkgdown { + text-align: right; +} +footer p { + margin-bottom: 0; +} + +img.icon { + float: right; +} + +/* Ensure in-page images don't run outside their container */ +.contents img { + max-width: 100%; + height: auto; +} + +/* Fix bug in bootstrap (only seen in firefox) */ +summary { + display: list-item; +} + +/* Typographic tweaking ---------------------------------*/ + +.contents .page-header { + margin-top: calc(-60px + 1em); +} + +dd { + margin-left: 3em; +} + +/* Section anchors ---------------------------------*/ + +a.anchor { + display: none; + margin-left: 5px; + width: 20px; + height: 20px; + + background-image: url(./link.svg); + background-repeat: no-repeat; + background-size: 20px 20px; + background-position: center center; +} + +h1:hover .anchor, +h2:hover .anchor, +h3:hover .anchor, +h4:hover .anchor, +h5:hover .anchor, +h6:hover .anchor { + display: inline-block; +} + +/* Fixes for fixed navbar --------------------------*/ + +.contents h1, .contents h2, .contents h3, .contents h4 { + padding-top: 60px; + margin-top: -40px; +} + +/* Navbar submenu --------------------------*/ + +.dropdown-submenu { + position: relative; +} + +.dropdown-submenu>.dropdown-menu { + top: 0; + left: 100%; + margin-top: -6px; + margin-left: -1px; + border-radius: 0 6px 6px 6px; +} + +.dropdown-submenu:hover>.dropdown-menu { + display: block; +} + +.dropdown-submenu>a:after { + display: block; + content: " "; + float: right; + width: 0; + height: 0; + border-color: transparent; + border-style: solid; + border-width: 5px 0 5px 5px; + border-left-color: #cccccc; + margin-top: 5px; + margin-right: -10px; +} + +.dropdown-submenu:hover>a:after { + border-left-color: #ffffff; +} + +.dropdown-submenu.pull-left { + float: none; +} + +.dropdown-submenu.pull-left>.dropdown-menu { + left: -100%; + margin-left: 10px; + border-radius: 6px 0 6px 6px; +} + +/* Sidebar --------------------------*/ + +#pkgdown-sidebar { + margin-top: 30px; + position: -webkit-sticky; + position: sticky; + top: 70px; +} + +#pkgdown-sidebar h2 { + font-size: 1.5em; + margin-top: 1em; +} + +#pkgdown-sidebar h2:first-child { + margin-top: 0; +} + +#pkgdown-sidebar .list-unstyled li { + margin-bottom: 0.5em; +} + +/* bootstrap-toc tweaks ------------------------------------------------------*/ + +/* All levels of nav */ + +nav[data-toggle='toc'] .nav > li > a { + padding: 4px 20px 4px 6px; + font-size: 1.5rem; + font-weight: 400; + color: inherit; +} + +nav[data-toggle='toc'] .nav > li > a:hover, +nav[data-toggle='toc'] .nav > li > a:focus { + padding-left: 5px; + color: inherit; + border-left: 1px solid #878787; +} + +nav[data-toggle='toc'] .nav > .active > a, +nav[data-toggle='toc'] .nav > .active:hover > a, +nav[data-toggle='toc'] .nav > .active:focus > a { + padding-left: 5px; + font-size: 1.5rem; + font-weight: 400; + color: inherit; + border-left: 2px solid #878787; +} + +/* Nav: second level (shown on .active) */ + +nav[data-toggle='toc'] .nav .nav { + display: none; /* Hide by default, but at >768px, show it */ + padding-bottom: 10px; +} + +nav[data-toggle='toc'] .nav .nav > li > a { + padding-left: 16px; + font-size: 1.35rem; +} + +nav[data-toggle='toc'] .nav .nav > li > a:hover, +nav[data-toggle='toc'] .nav .nav > li > a:focus { + padding-left: 15px; +} + +nav[data-toggle='toc'] .nav .nav > .active > a, +nav[data-toggle='toc'] .nav .nav > .active:hover > a, +nav[data-toggle='toc'] .nav .nav > .active:focus > a { + padding-left: 15px; + font-weight: 500; + font-size: 1.35rem; +} + +/* orcid ------------------------------------------------------------------- */ + +.orcid { + font-size: 16px; + color: #A6CE39; + /* margins are required by official ORCID trademark and display guidelines */ + margin-left:4px; + margin-right:4px; + vertical-align: middle; +} + +/* Reference index & topics ----------------------------------------------- */ + +.ref-index th {font-weight: normal;} + +.ref-index td {vertical-align: top; min-width: 100px} +.ref-index .icon {width: 40px;} +.ref-index .alias {width: 40%;} +.ref-index-icons .alias {width: calc(40% - 40px);} +.ref-index .title {width: 60%;} + +.ref-arguments th {text-align: right; padding-right: 10px;} +.ref-arguments th, .ref-arguments td {vertical-align: top; min-width: 100px} +.ref-arguments .name {width: 20%;} +.ref-arguments .desc {width: 80%;} + +/* Nice scrolling for wide elements --------------------------------------- */ + +table { + display: block; + overflow: auto; +} + +/* Syntax highlighting ---------------------------------------------------- */ + +pre, code, pre code { + background-color: #f8f8f8; + color: #333; +} +pre, pre code { + white-space: pre-wrap; + word-break: break-all; + overflow-wrap: break-word; +} + +pre { + border: 1px solid #eee; +} + +pre .img, pre .r-plt { + margin: 5px 0; +} + +pre .img img, pre .r-plt img { + background-color: #fff; +} + +code a, pre a { + color: #375f84; +} + +a.sourceLine:hover { + text-decoration: none; +} + +.fl {color: #1514b5;} +.fu {color: #000000;} /* function */ +.ch,.st {color: #036a07;} /* string */ +.kw {color: #264D66;} /* keyword */ +.co {color: #888888;} /* comment */ + +.error {font-weight: bolder;} +.warning {font-weight: bolder;} + +/* Clipboard --------------------------*/ + +.hasCopyButton { + position: relative; +} + +.btn-copy-ex { + position: absolute; + right: 0; + top: 0; + visibility: hidden; +} + +.hasCopyButton:hover button.btn-copy-ex { + visibility: visible; +} + +/* headroom.js ------------------------ */ + +.headroom { + will-change: transform; + transition: transform 200ms linear; +} +.headroom--pinned { + transform: translateY(0%); +} +.headroom--unpinned { + transform: translateY(-100%); +} + +/* mark.js ----------------------------*/ + +mark { + background-color: rgba(255, 255, 51, 0.5); + border-bottom: 2px solid rgba(255, 153, 51, 0.3); + padding: 1px; +} + +/* vertical spacing after htmlwidgets */ +.html-widget { + margin-bottom: 10px; +} + +/* fontawesome ------------------------ */ + +.fab { + font-family: "Font Awesome 5 Brands" !important; +} + +/* don't display links in code chunks when printing */ +/* source: https://stackoverflow.com/a/10781533 */ +@media print { + code a:link:after, code a:visited:after { + content: ""; + } +} + +/* Section anchors --------------------------------- + Added in pandoc 2.11: https://github.com/jgm/pandoc-templates/commit/9904bf71 +*/ + +div.csl-bib-body { } +div.csl-entry { + clear: both; +} +.hanging-indent div.csl-entry { + margin-left:2em; + text-indent:-2em; +} +div.csl-left-margin { + min-width:2em; + float:left; +} +div.csl-right-inline { + margin-left:2em; + padding-left:1em; +} +div.csl-indent { + margin-left: 2em; +} diff --git a/pkgdown.js b/pkgdown.js new file mode 100644 index 0000000000..6f0eee40bc --- /dev/null +++ b/pkgdown.js @@ -0,0 +1,108 @@ +/* http://gregfranko.com/blog/jquery-best-practices/ */ +(function($) { + $(function() { + + $('.navbar-fixed-top').headroom(); + + $('body').css('padding-top', $('.navbar').height() + 10); + $(window).resize(function(){ + $('body').css('padding-top', $('.navbar').height() + 10); + }); + + $('[data-toggle="tooltip"]').tooltip(); + + var cur_path = paths(location.pathname); + var links = $("#navbar ul li a"); + var max_length = -1; + var pos = -1; + for (var i = 0; i < links.length; i++) { + if (links[i].getAttribute("href") === "#") + continue; + // Ignore external links + if (links[i].host !== location.host) + continue; + + var nav_path = paths(links[i].pathname); + + var length = prefix_length(nav_path, cur_path); + if (length > max_length) { + max_length = length; + pos = i; + } + } + + // Add class to parent
  • , and enclosing
  • if in dropdown + if (pos >= 0) { + var menu_anchor = $(links[pos]); + menu_anchor.parent().addClass("active"); + menu_anchor.closest("li.dropdown").addClass("active"); + } + }); + + function paths(pathname) { + var pieces = pathname.split("/"); + pieces.shift(); // always starts with / + + var end = pieces[pieces.length - 1]; + if (end === "index.html" || end === "") + pieces.pop(); + return(pieces); + } + + // Returns -1 if not found + function prefix_length(needle, haystack) { + if (needle.length > haystack.length) + return(-1); + + // Special case for length-0 haystack, since for loop won't run + if (haystack.length === 0) { + return(needle.length === 0 ? 0 : -1); + } + + for (var i = 0; i < haystack.length; i++) { + if (needle[i] != haystack[i]) + return(i); + } + + return(haystack.length); + } + + /* Clipboard --------------------------*/ + + function changeTooltipMessage(element, msg) { + var tooltipOriginalTitle=element.getAttribute('data-original-title'); + element.setAttribute('data-original-title', msg); + $(element).tooltip('show'); + element.setAttribute('data-original-title', tooltipOriginalTitle); + } + + if(ClipboardJS.isSupported()) { + $(document).ready(function() { + var copyButton = ""; + + $("div.sourceCode").addClass("hasCopyButton"); + + // Insert copy buttons: + $(copyButton).prependTo(".hasCopyButton"); + + // Initialize tooltips: + $('.btn-copy-ex').tooltip({container: 'body'}); + + // Initialize clipboard: + var clipboardBtnCopies = new ClipboardJS('[data-clipboard-copy]', { + text: function(trigger) { + return trigger.parentNode.textContent.replace(/\n#>[^\n]*/g, ""); + } + }); + + clipboardBtnCopies.on('success', function(e) { + changeTooltipMessage(e.trigger, 'Copied!'); + e.clearSelection(); + }); + + clipboardBtnCopies.on('error', function() { + changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); + }); + }); + } +})(window.jQuery || window.$) diff --git a/pkgdown.yml b/pkgdown.yml new file mode 100644 index 0000000000..8c133262f3 --- /dev/null +++ b/pkgdown.yml @@ -0,0 +1,5 @@ +pandoc: 3.1.11 +pkgdown: 2.1.1 +pkgdown_sha: ~ +articles: {} +last_built: 2024-11-01T09:47Z diff --git a/profiles.html b/profiles.html new file mode 100644 index 0000000000..2b837438cd --- /dev/null +++ b/profiles.html @@ -0,0 +1,434 @@ + +Version Control with Git: Learner Profiles +
    + Version Control with Git +
    + +
    +
    + + + + + +
    +
    +

    Learner Profiles

    + +

    This is a placeholder file. Please add content here.

    + +
    +
    + + +
    +
    + + + diff --git a/reference.html b/reference.html new file mode 100644 index 0000000000..704ec58895 --- /dev/null +++ b/reference.html @@ -0,0 +1,573 @@ + +Version Control with Git: Git Cheatsheets for Quick Reference +
    + Version Control with Git +
    + +
    +
    + + + + + +
    +
    +

    Git Cheatsheets for Quick Reference

    +

    Last updated on 2024-11-01 | + + Edit this page

    + + + +
    + +
    + + + +

    Git Cheatsheets for Quick Reference

    +
    • Printable Git cheatsheets in several languages are available here (English +version). More material is available from the GitHub training website.
    • +
    • An interactive +one-page visualisation about the relationships between workspace, +staging area, local repository, upstream repository, and the commands +associated with each (with explanations).
    • +
    • Both resources are also available in other languages (e.g. Spanish, +French, and more).
    • +
    • Happy Git and GitHub for the +useR” is an accessible, free online book by Jenny Bryan on how to +setup and use Git and GitHub with specific references on the integration +of Git with RStudio and working with Git in R.
    • +
    • +Open +Scientific Code using Git and GitHub - A collection of explanations +and short practical exercises to help researchers learn more about +version control and open source software.
    • +

    Glossary

    +
    changeset
    +
    +A group of changes to one or more files that are or will be added to a +single commit in a version control repository. +
    +
    commit
    +
    +To record the current state of a set of files (a changeset) in a version +control repository. As a noun, the result +of committing, i.e. a recorded changeset in a repository. If a commit +contains changes to multiple files, all of the changes are recorded +together. +
    +
    conflict
    +
    +A change made by one user of a version +control system that is incompatible with changes made by other +users. Helping users resolve conflicts is one of +version control’s major tasks. +
    +
    HTTP
    +
    +The Hypertext Transfer Protocol used for sharing +web pages and other data on the World Wide Web. +
    +
    merge
    +
    +(a repository): To reconcile two sets of changes to a repository. +
    +
    protocol
    +
    +A set of rules that define how one computer communicates with another. +Common protocols on the Internet include HTTP and SSH. +
    +
    remote
    +
    +(of a repository) A version control repository +connected to another, in such way that both can be kept in sync +exchanging commits. +
    +
    repository
    +
    +A storage area where a version control +system stores the full history of commits of a +project and information about who changed what, when. +
    +
    resolve
    +
    +To eliminate the conflicts between two or more +incompatible changes to a file or set of files being managed by a version control system. +
    +
    revision
    +
    +A synonym for commit. +
    +
    SHA-1
    +
    +SHA-1 hashes is what +Git uses to compute identifiers, including for commits. To compute +these, Git uses not only the actual change of a commit, but also its +metadata (such as date, author, message), including the identifiers of +all commits of preceding changes. This makes Git commit IDs virtually +unique. I.e., the likelihood that two commits made independently, even +of the same change, receive the same ID is exceedingly small. +
    +
    SSH
    +
    +The Secure Shell protocol used for secure +communication between computers. +
    +
    timestamp
    +
    +A record of when a particular event occurred. +
    +
    version control
    +
    +A tool for managing changes to a set of files. Each set of changes +creates a new commit of the files; the version +control system allows users to recover old commits reliably, and helps +manage conflicting changes made by different users. +
    +
    +
    + + +
    +
    + + + diff --git a/safari-pinned-tab.svg b/safari-pinned-tab.svg new file mode 100644 index 0000000000..8a74e60c8d --- /dev/null +++ b/safari-pinned-tab.svg @@ -0,0 +1,68 @@ + + + + +Created by potrace 1.14, written by Peter Selinger 2001-2017 + + + + + + + + diff --git a/site.webmanifest b/site.webmanifest new file mode 100644 index 0000000000..f2302ffdd3 --- /dev/null +++ b/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "The Carpentries", + "short_name": "The Carpentries", + "icons": [ + { + "src": "/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000000..ee7562092e --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,129 @@ + + + + https://swcarpentry.github.io/git-novice/01-basics.html + + + https://swcarpentry.github.io/git-novice/02-setup.html + + + https://swcarpentry.github.io/git-novice/03-create.html + + + https://swcarpentry.github.io/git-novice/04-changes.html + + + https://swcarpentry.github.io/git-novice/05-history.html + + + https://swcarpentry.github.io/git-novice/06-ignore.html + + + https://swcarpentry.github.io/git-novice/07-github.html + + + https://swcarpentry.github.io/git-novice/08-collab.html + + + https://swcarpentry.github.io/git-novice/09-conflict.html + + + https://swcarpentry.github.io/git-novice/10-open.html + + + https://swcarpentry.github.io/git-novice/11-licensing.html + + + https://swcarpentry.github.io/git-novice/12-citation.html + + + https://swcarpentry.github.io/git-novice/13-hosting.html + + + https://swcarpentry.github.io/git-novice/14-supplemental-rstudio.html + + + https://swcarpentry.github.io/git-novice/404.html + + + https://swcarpentry.github.io/git-novice/CODE_OF_CONDUCT.html + + + https://swcarpentry.github.io/git-novice/LICENSE.html + + + https://swcarpentry.github.io/git-novice/discuss.html + + + https://swcarpentry.github.io/git-novice/index.html + + + https://swcarpentry.github.io/git-novice/instructor/01-basics.html + + + https://swcarpentry.github.io/git-novice/instructor/02-setup.html + + + https://swcarpentry.github.io/git-novice/instructor/03-create.html + + + https://swcarpentry.github.io/git-novice/instructor/04-changes.html + + + https://swcarpentry.github.io/git-novice/instructor/05-history.html + + + https://swcarpentry.github.io/git-novice/instructor/06-ignore.html + + + https://swcarpentry.github.io/git-novice/instructor/07-github.html + + + https://swcarpentry.github.io/git-novice/instructor/08-collab.html + + + https://swcarpentry.github.io/git-novice/instructor/09-conflict.html + + + https://swcarpentry.github.io/git-novice/instructor/10-open.html + + + https://swcarpentry.github.io/git-novice/instructor/11-licensing.html + + + https://swcarpentry.github.io/git-novice/instructor/12-citation.html + + + https://swcarpentry.github.io/git-novice/instructor/13-hosting.html + + + https://swcarpentry.github.io/git-novice/instructor/14-supplemental-rstudio.html + + + https://swcarpentry.github.io/git-novice/instructor/404.html + + + https://swcarpentry.github.io/git-novice/instructor/CODE_OF_CONDUCT.html + + + https://swcarpentry.github.io/git-novice/instructor/LICENSE.html + + + https://swcarpentry.github.io/git-novice/instructor/discuss.html + + + https://swcarpentry.github.io/git-novice/instructor/index.html + + + https://swcarpentry.github.io/git-novice/instructor/profiles.html + + + https://swcarpentry.github.io/git-novice/instructor/reference.html + + + https://swcarpentry.github.io/git-novice/profiles.html + + + https://swcarpentry.github.io/git-novice/reference.html + +