Version Control with Git : Lesson 4 : Add Commits To A Repo

1. Intro

This is the lesson where we finally learn how to make commits of our very own.
We've laid the groundwork of learning the git init command to create a new repository,
the git clone command to copy an existing repository,
the git log command to review existing commits,
and the all important git status command to see the status of the repository.

So we have theses as the foundation we'll build on top of them in this lesson with git add,
git commit, and git diff.

With git add, you'l add files from the working directory to the staging index.

With git commit, you'll take files from the staging index and save them in the repository which is what actually makes a commit.

The git diff command is really cool and will seem pretty familiar actually since you've already seen its output before. git diff displays the difference two versions of a file.
Its output is exactly like the output of the git log dash p command we used in the previous lesson.

2. Git Add

Move To Correct Project

If you've been following along, you should have two different directories with Git projects on your computer:
  • new-git-project - an empty directory that you converted to a Git repository using git init
  • course-git-blog-project - an existing blog project you retrieved using git clone
To avoid any confusion with existing commits, we'll be making our commits to the new-git-project Git repository.
On the Terminal, make sure you cd into the new-git-project directory. If you don't have a new-git-project directory, create it now. Once you're inside the directory, run the git initcommand. If you've already run git init before it's ok – running git init multiple times doesn't cause any problems since it just re-initializes the Git directory.
Your Terminal should look like this:

Status Status Status

I've said it a number of times already, but the git status command will be extremely helpful in this lesson. You should have it as your goal to run the git status command both before and afterany other Git command.
Let's run it right now!

Git Status Output Review

This is the output:
On branch master

Initial commit

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

💡 Changes in Git v2.14 💡

Remember that in Git version 2.14, the git status command changed the wording from "Inital commit" to the much clearer "No commits yet". So the output would be:
On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)
Notice that last line – nothing to commit (create/copy files and use "git add" to track). See how it's recommending the git add command? that's super helpful! The git status output will give you advice or hints as to what you should do next.
Let's do what the feedback says and create some files.

Create An HTML File

First, create a file named index.html, and fill it with some starter code:

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Blog Project</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <link rel="stylesheet" href="css/app.css">
</head>
<body>

    <script src="js/app.js"></script>
</body>
</html>
Things to note, the code references a CSS file and a JavaScript file.
Now create the CSS and JavaScript files. You can leave both of these files empty. We'll add content to them in a bit.

Quick Git Status Check

We just made a number of changes to the repository by adding files and content. It's time to do a quick check-in with Git:
$ git status
Here's what my Terminal displays:

Big Picture Review

That's really cool, isn't it! We haven't done anything specific with Git just yet, but it's watching this directory (since it's a Git project), and it knows that we've created a couple of new files. What's also pretty neat about the output of the git status command is that it's telling us that the files are untracked by Git.
Let's do a quick review of what's going on and what we're about to do:
  • we have some new files that we want Git to start tracking
  • for Git to track a file, it needs to be committed to the repository
  • for a file to be committed, it needs to be in the Staging Index
  • the git add command is used to move files from the Working Directory to the Staging Index
  • there are currently three, untracked files in the Working Directory
    • index.html
    • app.css in the css directory
    • app.js in the js directory
So the first step to getting any files committed to the repository is to add them from the Working Directory to the Staging Index. We will be using the git add command to move all three of these files to the Staging Index.

Staging Files

Alrighty, it's go time! Run the following command on the Terminal which uses git add to add index.html to the Staging Index:
$ git add index.html
Note - we are only adding the index.html file. We'll add the CSS and JavaScript files in just a second.
Running the git add command produces no output (as long as there wasn't an error). So how do we have Git tell us what it did and has happened to the index.html file that was added? That's what git status does. You're probably sick of me stressing the importance of the git statuscommand, but it's an extremely helpful command, especially if you're new to version control and/or the command line.
Let's check out the status of the project:
$ git status
This is the output I get:

Changes To Be Committed

There's now a new section in the output of git status - the "Changes to be committed" area! This new "Changes to be committed" section displays files that are in the Staging Area! Right now it only displays the index.html file, so this file is the only item on the Staging Index. To continue this train of thought, if we made a commit right now, only the index.html file would be committed.
TIP: Did you also notice the helpful text that's located just beneath "Changes to be committed"? It says (use "git rm --cached ..." to unstage) This is a hint of what you should do if you accidentally ran git add and gave it the wrong file.
As a side note, git rm --cached is not like the shell's rm command. git rm --cachedwill not destroy any of your work; it just removes it from the Staging Index.
Also, this used the word "unstage". The act of moving a file from the Working Directory to the Staging Index is called "staging". If a file has been moved, then it has been "staged". Moving a file from the Staging Index back to the Working Directory will unstage the file. If you read documentation that says "stage the following files" that means you should use the git add command.

Stage Remaining Files

The index.html file has been staged. Let's stage the other two files. Now we could run the following:
$ git add css/app.css js/app.js
...but that's a lot of extra typing. We could use a special command line character to help:

The Period .

The period refers to the current directory and can be used as a shortcut to refer to all files and directories (including all nested files and directories!).
$ git add css/app.css js/app.js
# would become
$ git add .
The only thing to be careful of is that you might accidentally include more files than you meant to. Right now we want both css/app.css and js/app.js to be staged, so running this command is fine right now. But let's say you added some images to an img directory but didn't want to stage them just yet. Running git add . will stage them. If you do stage files that you didn't mean to, remember that git status will tell you the command to use to "unstage" files.

Stage The Remaining Files

Let's use the shortcut to stage the remaining files:
$ git add .
And then a quick git status:

Git Add Recap

The git add command is used to move files from the Working Directory to the Staging Index.
$ git add  
This command:
  • takes a space-separated list of file names
  • alternatively, the period . can be used in place of a list of files to tell Git to add the current directory (and all nested files)

3. Git Commit

One Last Git Status Check

If you haven't added any new files to the Working Directory or modified any of the existing files, nothing will have changed, but to make sure, let's run a quick git status again right before we make the commit just to make absolutely sure the project is how we left it.

Make A Commit

Ok, let's do it!
To make a commit in Git you use the git commit command, but don't run it just yet. Running this command will open the code editor that you configured way back in the first lesson. If you haven't run this command yet:
$ git config --global core.editor 
...go back to the Git configuration step and configure Git to use your chosen editor.
If you didn't do this step and you already ran git commit, then Git probably defaulted to using the "Vim" editor. Vim is a popular editor for people who have been using Unix or Linux systems forever, but it's not the friendliest for new users. It's definitely not in the scope of this course. Check out this forum post on how to get out of Vim and return to the regular command prompt.
If you did configure your editor, then go ahead and make a commit using the git commitcommand:
$ git commit
Remember, your editor should pop open and you should see something like this:

Terminal Hangs

If you switch back to the Terminal for a quick second, you'll see that the Terminal is chillin' out just waiting for you to finish with the code editor that popped up. You don't need to worry about this, though. Once we add the necessary content to the code editor and finally close the code editor window, the Terminal will unfreeze and return to normal.

Code Editor Commit Message Explanation

Ok, switch back to the code editor. Here's what's showing in my editor:
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
# On branch master
#
# Initial commit
#
# Changes to be committed:
#    new file:   css/app.css
#    new file:   index.html
#    new file:   js/app.js
#
The first paragraph is telling us exactly what we need to do - we need to supply a message for this commit. Also, any line that begins with the # character will be ignored. Farther down it says that this will be the initial commit. Lastly, it's giving us a list of the files that will be committed.
Since this is the very first commit of the repository, we'll use the commit message "Initial commit". The text "Initial commit" isn't special, but it's the de facto commit message for the very first commit. If you want to use something else, feel free!
Type out your commit message on the first line of the code editor:

Finish Committing

Now save the file and close the editor window (closing just the pane/tab isn't enough, you need to close the code editor window that the git commit command opened).
Awesome, now switch back to the Terminal and you should see something like the following:

First Commit, Congrats!

You just made your first commit - woohoo! 🙌🏼 How does it feel? Was it more towards the awe-inspiring side or the anticlimactic? Honestly, when I made my first commit, I was a bit like:
"Wait...is that it? You just add the files you want to have committed to the Staging Area, and then you run 'git commit'?"
...and the answer to my questions are "Yes" and "Yes". That's all there is to it. At first, version control seems like this overwhelming obstacle that one must overcome to become a true programmer/developer/designer/etc. But once you get a handle on the terminology (which I think is the most challenging part), then actually using version control isn't all that challenging.

Bypass The Editor With The -m Flag

TIP: If the commit message you're writing is short and you don't want to wait for your code editor to open up to type it out, you can pass your message directly on the command line with the -m flag:
$ git commit -m "Initial commit"
In the example above, the text "Initial commit" is used as the commit message. Be aware that you can't provide a description for the commit, only the message part.

2nd Commit - Add Changes

We've had a short breather, so let's make a second commit! Here, add this just inside the body tag in index.html:
<header>
    <h1>Expedition</h1>
</header>
Ok, now what do you do next? That's right, it's our good old friend git status!
TIP: If you run git status but don't see that index.html has changed, make sure to save the file. I modify a file and then forget to save it - all - the - time! I like to think that forgetting to save a file after editing it is the mark of a true professional.

Multipurpose Git Add

So we've modified our file. Git sees that it's been modified. So we're doing well so far. Now remember, to make a commit, the file or files we want committed need to be on the Staging Index. What command do we use to move files from the Working Directory to the Staging Index? You got it - git add!
Even though we used git add to add newly created files to the Staging Index, we use the same command to move modified files to the Staging Index.
Use the git add command to move the file over to the Staging Index, now. Verify that it's there with git status.

Second Commit

Now that we have a file with changes we can commit, let's make our second commit! Use the git commit command to make a commit. Use the commit message Add header to blog.
Now you might be asking yourself, "Why did Richard pick that as the commit message to use?" or "What makes a good commit message?". These are fantastic questions that we'll be looking at in the next concept!

What To Include In A Commit

I've been telling you what files to create, giving you the content to include, and telling you when you should make commits. But when you're on your own, how do you know what you should include in a commit and when/how often you should make commits?
The goal is that each commit has a single focus. Each commit should record a single-unit change. Now this can be a bit subjective (which is totally fine), but each commit should make a change to just one aspect of the project.
Now this isn't limiting the number of lines of code that are added/removed or the number of files that are added/removed/modified. Let's say you want to change your sidebar to add a new image. You'll probably:
  • add a new image to the project files
  • alter the HTML
  • add/modify CSS to incorporate the new image
A commit that records all of these changes would be totally fine!
Conversely, a commit shouldn't include unrelated changes - changes to the sidebar and rewording content in the footer. These two aren't related to each other and shouldn't be included in the same commit. Work on one change first, commit that, and then change the second one. That way, if it turns out that one change had a bug and you have to undo it, you don't have to undo the other change too.
The best way that I've found to think about what should be in a commit is to think, "What if all changes introduced in this commit were erased?". If a commit were erased, it should only remove one thing.
Don't worry, commits don't get randomly erased.
In a later lesson, we'll look at using Git to undo changes made in commits and how to manually, carefully remove the last commit that was made.

Git Commit Recap

The git commit command takes files from the Staging Index and saves them in the repository.
$ git commit
This command:
  • will open the code editor that is specified in your configuration
    • (check out the Git configuration step from the first lesson to configure your editor)
Inside the code editor:
  • a commit message must be supplied
  • lines that start with a # are comments and will not be recorded
  • save the file after adding a commit message
  • close the editor to make the commit
Then, use git log to review the commit you just made!

Further Research

4. Commit Messages

Good Commit Messages

Let's take a quick stroll down Stickler Lane and ask the question:
How do I write a good commit message? And why should I care?
These are fantastic questions! I can't stress enough how important it is to spend some time writing a good commit message.
Now, what makes a "good" commit message? That's a great question and has been written about a number of times. Here are some important things to think about when crafting a good commit message:
Do
  • do keep the message short (less than 60-ish characters)
  • do explain what the commit does (not how or why!)
Do not
  • do not explain why the changes are made (more on this below)
  • do not explain how the changes are made (that's what git log -p is for!)
  • do not use the word "and"
    • if you have to use "and", your commit message is probably doing too many changes - break the changes into separate commits
    • e.g. "make the background color pink and increase the size of the sidebar"
The best way that I've found to come up with a commit message is to finish this phrase, "This commit will...". However, you finish that phrase, use that as your commit message.
Above all, be consistent in how you write your commit messages!

Explain the Why

If you need to explain why a commit needs to be made, you can!
When you're writing the commit message, the first line is the message itself. After the message, leave a blank line, and then type out the body or explanation including details about why the commit is needed (e.g. URL links).
Here's what a commit message edit screen might look like:
This details section of a commit message is included in the git log. To see a commit message with a body, check out the Blog project repo and look at commit 8a11b3f.
Only the message (the first line) is included in git log --oneline, though!

Udacity's Commit Style Requirements

As I've mentioned, there are a number of ways to write commit messages. If you're working on a team, they might already have a predetermined way of writing commit messages. Here at Udacity, we have our own standard for commit messages. You can check it out on our Git Commit Message Style Guide.
If you haven't chosen a commit message style, feel free to use ours. But if you're working on an existing project, use their existing style; it's much more important to be consistent with your actual team than to be consistent with us!

Git Diff Up Next!

In the next section, we'll look at a new tool (with a familiar output!). This tool will tell us what changes we've made to files before the files have been committed!

5. Git Diff

Explain the Why

If you need to explain why a commit needs to be made, you can!
When you're writing the commit message, the first line is the message itself. After the message, leave a blank line, and then type out the body or explanation including details about why the commit is needed (e.g. URL links).
Here's what a commit message edit screen might look like:
This details section of a commit message is included in the git log. To see a commit message with a body, check out the Blog project repo and look at commit 8a11b3f.
Only the message (the first line) is included in git log --oneline, though!

Udacity's Commit Style Requirements

As I've mentioned, there are a number of ways to write commit messages. If you're working on a team, they might already have a predetermined way of writing commit messages. Here at Udacity, we have our own standard for commit messages. You can check it out on our Git Commit Message Style Guide.
If you haven't chosen a commit message style, feel free to use ours. But if you're working on an existing project, use their existing style; it's much more important to be consistent with your actual team than to be consistent with us!

Git Diff Up Next!

In the next section, we'll look at a new tool (with a familiar output!). This tool will tell us what changes we've made to files before the files have been committed!

6. Having Git Ignore Files

Why Should Files Be Ignored

Remember a couple sections back when we were learning about git add? Instead of adding the files one by one, there was a special character that we could use to indicate the current directory and all subdirectories. Do you remember what that character is?
That's right, the period (.)!

The Problem

Let's say you add a file like a Word document to the directory where your project is stored but don't want it added to the repository. (You can simulate adding a Word document by running touch project.docx) Git will see this new file, so if you run git status it'll show up in the list of files.
The potential problem with having this file in your project is that, because git add . adds all files, the Word document might get accidentally committed to the repository.

Git Ignore

If you want to keep a file in your project's directory structure but make sure it isn't accidentally committed to the project, you can use the specially named file, .gitignore (note the dot at the front, it's important!). Add this file to your project in the same directory that the hidden .gitdirectory is located. All you have to do is list the names of files that you want Git to ignore (not track) and it will ignore them.
Let's try it with the "project.docx" file. Add the following line inside the .gitignore file:
project.docx
Now run git status and check its output:
Git knows to look at the contents of a file with the name .gitignore. Since it saw "project.docx" in it, it ignored that file and doesn't show it in the output of git status.

Globbing Crash Course

Let's say that you add 50 images to your project, but want Git to ignore all of them. Does this mean you have to list each and every filename in the .gitignore file? Oh gosh no, that would be crazy! Instead, you can use a concept called globbing.
Globbing lets you use special characters to match patterns/characters. In the .gitignore file, you can use the following:
  • blank lines can be used for spacing
  • # - marks line as a comment
  • * - matches 0 or more characters
  • ? - matches 1 character
  • [abc] - matches a, b, or c
  • ** - matches nested directories - a/**/z matches
    • a/z
    • a/b/z
    • a/b/c/z
So if all of the 50 images are JPEG images in the "samples" folder, we could add the following line to .gitignore to have Git ignore all 50 images.
samples/*.jpg

Git Ignore Recap

To recap, the .gitignore file is used to tell Git about the files that Git should not track. This file should be placed in the same directory that the .git directory is in.

Further Research

7. Outro

We looked at using git add to stage content.
We used git commit to actually commit changes to the repository.
We also looked at what makes a good commit message.
Then we learned about how helpful git diff can be to help us recall changes that haven't been committed yet. And last, we just looked at the git ignore file what files it should not track.


0 개의 댓글:

댓글 쓰기