By Bob Ziroll
Translation: Crazy geek
Original: www.freecodecamp.org/news/git-th…
Reproduced without permission
Git is an important tool in any developer’s toolbox.
Just the other day, for example, I solved a major problem that was already in production (it was all my fault) in about 20 minutes. Without Git, this can take a few days to fix.
So let’s take a moment to really understand Git’s most basic function: prepare and commit.
Note: This article does not contain anything related to GitHub, which is a third-party online Web service that allows you to back up code saved with Git in the cloud. Git is local, GitHub is a cloud-based application, and they are two very different things, albeit for the same purpose.
What is version control?
If you’re old enough to remember the world before Google Drive/Docs/Sheets, you might do something like this:
Working with group projects leads to multiple people trying to edit multiple copies of the original document, leading to a lot of duplication. If two people make edits at the same time, someone has to do everything manually and put the edits together.
There is no good way to control different versions of a project. It’s like the wild West. 🤠 + 😢
Git solves this problem 💡
Maybe you’ve added a new feature to your project that breaks something that worked well before, but don’t know where to find the bug or how to fix it. You have already closed the file in the editor, so you can no longer use Undo.
Git solves this problem 💡
Ok, but how does Git solve these problems?
Git’s core function is to create savepoints in files. I feel like these save points are like in a video game, and even if you screw up after that, you can always come back and try again without having to start over.
Git has many other awesome aspects, but the heart of what it’s all about is creating savepoints in your code that can be returned to later if needed.
How does Git work?
This core Git function (creating savepoints in your project) is divided into two phases:
- Add things (changed code and files) to the temporary area to commit (save) in the timeline, and
- Those things that are actually submitted.
Coercive contrast
These two phases, as if you were creating an old-fashioned photo album, one for printing photos and putting them into a real photo album. If you’re too young to have seen it, here it is:
First, you take a bunch of pictures with your camera. Taking photos doesn’t affect the album, because you can always choose photos to include in the album. You’ll get pictures that weren’t taken well and re-take them if necessary.
Next, you can choose which photo you want to save in the album. Imagine that you have printed them out and placed them next to blank pages in an album. You’re creating a kind of “temporary zone.” You haven’t pasted photos into pages in your album yet, but you’re ready to do so soon.
Finally, once you’re ready, paste your photos onto the page and glue them together. A good album contains some kind of description or caption of the events in the photos.
When you’re done, you can always go back to this page in the album and remember what was going on in your life (good or bad).
What does this have to do with Git?
Let’s relate this analogy to Git.
- Taking photos is like modifying project files (writing code, creating files, or deleting files).
- Selecting the desired photo in the album is like adding changes to the “temporary zone.”
- Pasting photos to the album page is like committing (saving) changes to the change timeline.
Let’s explain w one by one.
Taking photos is like editing a project file
Taking photos is like making changes to a project: writing new code, adding images, deleting old files, and so on. You are creating content that will eventually be saved in Git commits (” savepoints “). It’s still a work in progress, and you can write, rewrite, or delete anything you want whenever you want without having to save them “forever.”
The only thing Git is currently doing is seeing if anything has changed since the last time you committed (saved) your code. If you add a line of code and then delete it, Git will assume that nothing has changed. If you write 500 lines of code in dozens of files, Git knows exactly which lines have been added to which files and tracks the changes in its memory. It won’t make any commitments to the schedule of changes until you tell it, but it will keep a close eye on what you do.
Note: Keep in mind that we are now referring to a completely different process than saving changes to hard disk. Modern text editors can save your code every second or so, but that’s not what we’re talking about here. When I mention “save” with Git, I mean create a commit to save your changes to the timeline.
Selecting the desired photo in the album is like adding project changes to the “temporary zone”
In Git, this is the phase that occurs before a new creation in the code commits. This process is called “Add to staging area”. Adding to the staging area does not create a commit, it just prepares the commit.
After you add some files to the staging area, you may find that you still need to make some changes. No problem! Since Git hasn’t actually saved (committed) anything at this point, you can simply make the new changes you need and then add those changes to the temporary zone, even if they happen in the same file as the one you added earlier. It’s like taking some new photos that you decide to add to the album page and print.
Pasting photos into an album is like submitting code
This is the second (and final) stage for creating a savepoint (commit). There is one main requirement when creating a submission: you must include information. In the album, you can write captions or messages to provide future viewers with information about what the photos mean to you. In Git, you write a message that describes the changes you want to save to your code base.
If you write a bad commit, reviewing your code history won’t help anyone, including yourself. (What good is a “make some changes” message if you don’t know what those changes are? Imagine finding a page in an album that says “Here are some people……” Always use a good descriptive commit message to describe a feature or fix you added to the code base.
action
Examples are enough, now let’s get started!
The installation
First, you probably have Git installed. Open a terminal or command prompt and try running git –version. If it shows the version number, skip this step. If it says you don’t know what your Git means, you need to install it. Please follow the instructions below to install your operating system.
Create a Git repository
Git only knows how to keep track of projects that you have set up as Git repositories. In the above metaphor, if we don’t have an album in the first place, we can’t paste photos into an album.
When you are ready to start a new project, the first step you should take (after creating the project folder) is to run:
git init
Copy the code
This allows Git to immediately start tracking any changes you make to your project. Underneath it creates a new hidden.git folder, and everything in it needs to keep track of your changes. You almost never need to go into this folder unless you’re setting up something advanced.
Make changes to the project
For the following tutorial, I’ll keep it as simple as possible — a project folder, which is a Git repository with a single file called readme.md Markdown. You can imagine that every change I make to my README file represents some new feature or dozens or hundreds of lines of new code. 👌 🏻 😉
Basic commands
git status
I’d like to think of this as a sanity check to help me understand what Git is currently doing. (e.g., what changes it notices, is everything ok, etc.)
It tells me that I’m on the main branch (I’ll write another article about branches), that I haven’t committed before, and that I don’t have anything to commit now. Git doesn’t see any folders to save.
Now I’ll add the readme. md file and run git status again:
Git sees that I have added a new file to the project. Cool! Now that this awesome new project is underway, let’s create a savepoint.
git add
The git add command is a way to put things in a temporary area. Just like printing the photos we took and pasting them into our album page. But we need to tell Git that we want to add to the staging area. (Just typing git add will prompt you that you haven’t specified anything, so nothing will be added.) I’ll add the file name with Git:
git add README.md
git status
Copy the code
Using git status again, it shows a new file in the staging area, but it’s now green! This is an easy way to tell you that it has been added to a temporary area.
Basically git add readme. md tells Git “I want to include all the changes I’ve made since my last commit to readme. md that are included in the upcoming commit.”
However, adding files to the staging area one at a time can be cumbersome, especially if there are many tasks that require you to process many files. Instead of remembering and specifying every file you’re working on, you can use the “catch all” approach, which automatically adds every file you make changes to the staging area. My preferred method is:
git add -A
Copy the code
The -A flag adds all files with the change flag to the staging area.
Note: You’ll often see people using Git add. to add all changes to the staging area. While this works, it requires you to be in the project root to ensure that all changes are captured. (. Is short for current directory). Therefore, if you CD into a nested directory but make changes to files outside that directory and try to use git add., you will miss those changed files when you try to add them to the staging area. But no matter where you are on the terminal, Git Add-a works for the entire project.
git commit
Once you are ready to create a commit, use the git commit command. But remember how you added notes? If you simply run Git Commit and press Enter, a terminal based editor, such as Vi or Nano, will pop up to fill in the commit information.
You can also use the -m flag and then use string messages in quotes to keep your Git commit consistent with the message. Like this:
git commit -m "Added some really important information to the README"
Copy the code
Assuming everything else is in place before committing, you have now successfully committed your code using Git! Now you have a checkpoint from which you can always go back if there is a problem.
Let’s look at this process again in GIF form:
Note: GIfs use git add, but I think git add-a is more accurate. Also, use better submission information! Please forgive my mistake
git log
You can view the commit history by running git log. Using the arrow keys, you can scroll forward and backward in time to check submission dates, messages, and authors (submitters). Along with this comes a “commit hash,” which is essentially a unique ID for the commit that can be used to reference it later when needed.
Time travel
“So you keep talking about how Git allows me to jump back in time…… What can I do?”
git checkout
The term “checkout” refers to the process of switching from one commit to another. Remember the unique ID (” hash “) received for each submission? I can review my commit history, select one of the unique commit hashes, and then view it with the Git checkout command. If I want to see the submit a hash value of the a2 (complete them much longer than this – like 0 c9b8f7c23dea4cf0a0285f14211124b6d5891e9), you can run:
git checkout a2
Copy the code
All of a sudden, the timeline of my entire codebase shrinks, and everything looks exactly like it did after I committed. (This can be scary, as it looks like you may have lost all the updates since you submitted, but don’t worry! They’re still here!)
In GIF format:
Note that the third commit and the changes in it still fully exist. You can return to this commit with Git Checkout A3 or (more commonly) Git Checkout Master to restore all changes.
Now that you’re back, you’ll see messages from Git. Like:
Note: checking out 'a2'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by performing another checkout. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -b with the checkout command again. Example: git checkout -b <new-branch-name> HEAD is now at a2 Another MessageCopy the code
“Detached HEAD” sounds even scarier than it is now. 🤢
In this state, you no longer use the Master branch, which means that you can make experimental changes and even create new commits here, all without losing your code on the Master branch (commit hash A3 in the example above).
Again, I plan to override branches at another time, but that’s just to illustrate how powerful Git is when it comes to keeping multiple versions of code.
conclusion
You can learn a million things about Git, but if you don’t understand the core concepts, it will always seem a bit mysterious.
However, if you really want to learn and become familiar with Git, you’re better off experimenting.
That means you have to do more than just read the article. So create a new Git repository in an empty folder, start adding files, use Git status and Git log to see what it looks like, and consider downloading Sourcetree so you can visualize the state of your repository as you mess up your project.