Git. Quick Start to Basic Operations with Explanations

This explains the practical part of using Git - installing it and registering it on the GitHub.com server.

GitHub.com is a service that offers storage of your code and data using a version control system Git... GitHub provides a free plan for storing 300MB of data in clear text. This means that any Internet user can download your data. On GitHub, you can host repositories that are closed to others, paying $ 7 per month. On a free GitHub account, by default, no one can change your data (they can only read). However, you can specify which GitHub users are writeable.

This article explains in detail how to set up Git on Windows and Linux.

Installing Git on Linux

To Linux users, I think it makes no sense to explain how to install Git - on each system it is done differently. On a Debian system (which I have), to install Git, you can use the command:

apt-get install git

Installing Git on Windows

Go to official page Git http://git-scm.com, click on Download for Windows... In the window that opens, click on Full installer for official Git... We launch the resulting exe-shnik.

During the installation process, the following question will be asked:

I recommend choosing "Run Git from the Windows Command Prompt". All other options can be left by default. After installing Git, you need to reboot or log out and log back in for the changes to the system PATH to apply.

If we get version information, then Git is installed and working. If we get information that the git program was not found, we figure out what we did wrong.

Configuring SSH Keys

Before registering on GitHub, you must first generate an SSH encryption key. This key is required to quickly establish a connection to GitHub without entering a password. Without such a key, GitHub simply won't work.

Attention!

At the time of key generation, you will be prompted for a password. This is the password for accessing the private key, which is only stored on your machine and nowhere else. This password is set for maximum security, although you can do without it. You need to know that by setting a password for the private key, you will need to enter this password every time you connect to the GitHub server. Thus, when setting a password, all the convenience of using encryption keys disappears.

For MyTetra users: the command line interface used to invoke git during synchronization cannot work on character input. Therefore, if you set a password, synchronization will not work.

Configuring SSH Keys on Linux

V operating system Linux, you first need to look into the ~ / .ssh directory. If there are files id_rsa and id_rsa.pub, then these are SSH keys. If there is no such directory or such files, then the keys need to be generated. We give the command:

Instead of [email protected] you need to enter your email. In the process of generating a key, you will be asked where to put the files, in response, simply press Enter. When prompted for a password, just press Enter. After generation, the files id_rsa and id_rsa.pub should appear in the ~ / .ssh directory, they will be useful to us in the future.

Configuring SSH Keys on Windows

On Windows, an SSH key generator is included with Git. To generate keys, you need to run the file C: \ Program Files \ Git \ Git bash.vbs... It can be run as a regular exe-shnik. The git Console opens. In it, you need to give the command:

ssh-keygen -t rsa -C " [email protected]"

Be careful, this console enables copy-paste, it's easier to enter the command manually. Specify your email as an email mailbox... On request " Enter file in which to save the key"just press Enter. When prompted for the password" Enter passphrase "and" Enter same passphrase again "just press Enter. During the key generation process, the console will display approximately the following information:

Generating public / private rsa key pair.
Enter file in which to save the key (/ c / Documents and Settings / username / .ssh / id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in / c / Documents and Settings / username / .ssh / id_rsa.
Your public key has been saved in / c / Documents and Settings / username / .ssh / id_rsa.pub.
The key fingerprint is:
51: db: 73: e9: 31: 9f: 51: a6: 7a: c5: 3d: da: 9c: 35: 8f: 95 [email protected]

After executing this program, in the directory C: \ Documents and Settings \ username \ .ssh there will be files id_rsa and id_rsa.pub, they will be useful to us in the future.

Sign up on GitHub.com

Now everything is ready for registration. Go to the start page of GitHub.com. The interface is a little confused, so I will give a couple of screenshots of where to click what. The design and layout can be changed at any time, so I describe the logic of actions in this moment.

In the top menu we find the item " Pricing and Signup"and click on it:

The selection page will open tariff plan... Choosing a free account " Create a free account":

Installing SSH Key on GitHub

Immediately after registration, you must register your public encryption key (SSH public key) in the GutHub system. To add a key, you need to in the right upper corner press " Account Settings":

In the window that opens, click on the menu item " SSH Public Keys", and press" Add Another Public Key". Two fields will appear - the name of the key ( Title) and the contents of the key ( Key).

In field Title you can write the name of the computer on which the public key was generated. You can write in Russian.

In field Key you need to insert the contents of the id_rsa.pub file. Remember which directory they are in? Go to this directory, open the id_rsa.pub file with any text editor (with the .pub extension, do not mix it up). Select all text, copy, and paste on the GitHub page into the field Key.

After adding the key, the computer can connect to GitHub through the git program, and no errors should occur.

Creating a repository on GitHub

Now it's time to create your first GitHub repository. The repository can be viewed simply as a directory in which the files and subdirectories to be synchronized will be located. You need to create a repository in the GitHub web interface, and you can fill it with files and work with it using the git program on your computer.

To create a repository, in the upper right corner, click " Dashboard". In the window that opens, you will see the item" Create A Repository":

So, we don't need this item! This item does not open a dialog for creating a repository, but a help page. Instead of clicking on this item, look for an unremarkable link below on the page " Create A Repository". It will open the dialog for adding a new repository.

In the dialog for adding a new repository, you need to fill in at least the project name field " Project Name". It is better not to use the Cyrillic alphabet in the name of the project, since the name of the project is in fact the name of the directory. To avoid problems, it is better that the name of the project contains only the Latin alphabet. After clicking the button" Create Repository", the repository will be created.

The working link to the repository in the GitHub system is formed as follows. If you registered as username and your repository is called reponame, you can use the following links to access this repository:

In Git syntax:

[email protected]: username / reponame.git

In the Https syntax:

https: // [email protected]/username/reponame.git

Working with a repository on GitHub through the Git program

From now on, the dancing around the GitHub web interface can be considered complete. Further, you can work only using the git program.

First, you need to do a little tweak to the git program: tell the local git system a username and email. This is done with the following commands, which can be executed from any directory:

git config --global user.name "YourFullName"
git config --global user.email [email protected]

where instead of YourFullName you need to write your name, and instead of [email protected]- your email. These values ​​are used to login to GitHub. Therefore, in place of YourFullName, you need to indicate your username on GitHub, and in place [email protected] you need to specify the email that you entered when generating encryption keys.

After these settings, you can upload your files to the repository. We go to the directory with our project, and give the commands:

git commit -a -m "first commit"

git remote add origin [email protected]: username / reponame.git

git push -u origin master

After these commands, copies of the files of the directory in which these commands were executed are formed on the GitHub server. Then you can already make commits, uploading changes to the GitHub server, reading changes from the server. But that's a completely different story.

It's natural for people to resist change. If you didn't encounter Git when you started working with version control systems, you probably feel more comfortable with Subversion (SVN).

Often people say that Git is too complicated for newbies. However, I will allow myself to disagree with this.

In this tutorial, I'll show you how to use Git in your projects. Let's say you are building a project from scratch and want to manage it with Git. By going through the list of basic commands, you will get an idea of ​​how to host your code in the cloud using GitHub.

In this article, we'll talk about the basics of Git - how to initialize your projects, how to manage new and existing files, and how to store your code in the cloud.

We won't touch on the relatively complex parts of Git, such as branching, as this tutorial is intended for beginners.

Installing Git

The official Git site has detailed information about installing it on Linux, Mac and Windows. In our case, we will use Ubuntu 13.04 for demonstration purposes, where we will install Git using apt-get:

sudo apt-get install git

Initial setup

Let's create a directory within which we will work. Alternatively, you can use Git to manage one of your existing projects; in this case, you will not need to create a demo directory as shown below:

mkdir my_git_project cd my_git_project

The first step is to initialize Git in the directory. This can be done using the init command, which creates a .git directory containing all the Git-related information for your project.

git config --global user.name "Shaumik" git config --global user.email " [email protected]"git config --global color.ui" auto "

It is important to note that if you do not include your name and address Email then the default values ​​will be used. In our case, the default values ​​would be the username donny and the email address. [email protected].

In addition, we set for the color user interface auto, which makes the output of Git commands color-coded.

The -global prefix in front of the commands is to avoid entering these configuration commands the next time we run a Git project on our system.

Preparing files for commit

The next step is to create files in the directory. You can use for example text editor Vim. Note that if you are going to add Git to an existing directory, you do not need to complete this step:

Check repository status

Now that we have a few files in our repository, let's see how Git handles them. In order to check the current status of the repository, you need to use the git status command:

Adding Files to Git for Tracking

We currently have no files to track with Git. We need to add files specifically to Git in order to tell Git what to track.

Add files using the add command:

By checking the state of the repository again, we can see that one file has been added:

To add multiple files, the following command entry can be used (note that we have added another file for demonstration purposes):

git add myfile2 myfile3

You can use git add recursively, but be careful with this command. There are certain files (such as compiled files) that are usually stored outside of the Git repository.

If you use the add command recursively, it will add any such files if they exist in your repository.

Deleting files

But running a simple git rm command will remove the file not only from Git, but also from your local filesystem! To

Git has stopped tracking the file, but the file itself is still on your local system, run the following command:

git rm --cached

Commit changes

Once you've placed your files, you can commit them to Git. Imagine a commit is a capture of a specific point that you can come back to to access your repository at this point.

You can bind a message to each commit, which is appended with the -m prefix:

git commit -m "My first commit"

Feed your commits with helpful messages because it will help you determine what you changed in that commit.

Avoid too general messages like " Bugs fixed". If you have a task tracker, you can add messages as “ Fixed bug # 234».

It is good practice to use the branch name or function name as a prefix to the commit message. For example, " Asset Management: Added function to generate PDF asset files"Is a meaningful message.

Git identifies commits by adding a long hexadecimal number to each commit. As a rule, you do not need to copy the entire line, the first 5-6 characters are enough to define your commit.

Please note that in the screenshot, our first commit is identified by code 8dd76fc.

Further commits

Now let's change a few files after our first commit. After changing them, we will see that as a result of executing the git status command, Git detected changes in the files that it tracks:

You can check the changes to tracked files made in the last commit with the git diff command. If you want to see the changes in a specific file, use the git diff command :

You need to add these files again in order to implement the changes to the tracked files for the next commit. You can add all tracked files by running the command:

You can avoid using this command by using the -a prefix for the git commit command, which will add all changes to the tracked files.

This process, however, is very dangerous as it can harm the project. For example, let's say you opened a file and changed it by mistake.

If you selectively place files, you will notice changes in each file. But if you add the -a prefix to your commit, all files will be committed and you won't be able to identify possible errors.

Once you've placed your files, you can start committing. I mentioned that every commit can have a message associated with it, which we enter with the -m prefix.

However, it is possible to enter the message on multiple lines using the git commit command, which opens an interactive write form:

Project management

To view the history of your project, you can run the following command:

This will show the entire history of the project, which is a list of all commits and information on them. The commit information includes the hash of the commit, author, time, and commit message. There are various git log options that you can explore once you have a grasp of branch in Git.

To view detailed information about a specific commit and the files that have changed, run the following command:

git show

where this is hexadecimal number associated with the commit. Since this tutorial is intended for beginners, we will not cover how to go back to the state of a specific commit or how to manage branches.

Placing code in the cloud

Now that you've learned how to manage code on your system, it's time to put your code in the cloud.

Github is a very well-known platform for storing, distributing and managing source code for open source projects. This service is used by many developers around the world, including large companies such as Microsoft, RedHat and many others, as well as hundreds of developers of many popular projects.

The platform provides not only code review and distribution capabilities, but also version history, collaborative development tools, tools for providing documentation, release releases, and feedback. And the best part is that you can host both public and private projects on Gihub. In this article, we'll look at how to use Github to host your project. So to speak, github is for beginners.

So, let's say you have your own project and you want to publish its code on Github in the public domain so that other users can view it and participate in development. The first thing you need to do is create an account.

1. Create an account

To create a new account on the site, open home page GitHub and right away you can enter data for a new account... You need to provide a username, email and password:

When you have finished entering, press the button. "Sign Up Free":

In the next step, you need to select the type of repository. Public repositories are free, but if you want to create a private repository where the code is only available to you, you will have to pay $ 7 per month.

The account is ready and you will be redirected to the page where you can create your first project. But before you can do this, you need to confirm your Email address. To do this, open your mailbox and follow the link in the letter from Github.

No github configuration is needed, just a few clicks are enough.

2. Creating a repository

On the page that opens, this is the main page for authorized users, click the button "Start a project":

You can immediately initialize the repository by creating a Readme file by checking the box "Initialize this repository with a README" at the bottom of the page. You can also choose a license:

When you're done, choose "Create project", a new project will be created with a README file containing a description and a license file.


3. Adding branches

Github branches allow you to work with multiple versions of a project at the same time. By default, when you create a repository, a master branch is created, this is the main working branch. Additional branches can be created, for example, to test software before it is published to the master branch. Thus, it is possible to simultaneously develop a product and provide users with a stable version. You can also create separate branches for the version of the program for different systems.

The current branch is indicated in the upper left corner after the word "Branch". To create a new branch, simply expand this list and start typing its name:

The site itself will offer you to create a new branch, select "Create branch".

Immediately after creation, you will be working on the branch you just created.

4. Modifying files and commits

Any changes to files on Github are done using commits. The commit is done by introducing the fixes themselves and describing those fixes. This is necessary so that you know what and when you changed, and also makes it easy to track the work of the team. The word commit can be translated as "commit". That is, we can make changes to several files and then commit them. Let's modify the README file for example. To do this, find the button with a brush in the right side of the panel and click on it:

A text editor will open where you can enter the corrections you want:

After you have done everything you need, you need to fill in the field "Commit" at the bottom of the page. Briefly describe what was changed and then click "Commit changes":

These changes will be made to the current branch of the project, since we are currently working with testing, then the changes will be sent there.

5. Making Pull Requests

GitHub for beginners can seem overwhelming because of these features, but it's very handy when you figure it out. A Pull Request or Pull Request is a feature whereby any developer can ask another, such as the repository creator, to review their code and add it to the main project or branch. The merge query tool uses the diff compare tool, so you can see all the changes, they will be underlined in a different color. The Pull Request can be created immediately after the commit is created. Let's send a Pull Request from our testing branch to the main branch. First open the tab "Pull Request".

Click here "Create Pull Request":

In this window you can view all the changes, now we see that the line has been added:

6. Review and approve merge requests

Now, on the same Pull Requests tab, we see the newly created pull request and we just have to accept it by clicking "Merge Pull Request":

But if this request came from another person, you should check what he changed there and whether it is necessary, to do this, just click on the description of the request and you will see the already familiar window for viewing changes:

The code will then be imported into the main branch and the testing branch can be safely removed.

7. Bug reports

Conveniently, it is possible to use GitHub not only for development and code management, but also for user feedback. In the tab "Issue" users can post about problems they encounter while using your product. Open the tab "Issues", and press the button "New issue":

8. Releases

The last thing we will look at today is the releases. When the product has reached a certain stage, you can release a release so that users and you can be sure that everything is stable there and no one broke anything with an incorrect Pull Request in Master. First you need to go to the main page of the project, then to the tab "Releases":

On this page, you need to specify the version in the field "Tag Version" followed by the release name and a short description. If you have compiled archives with binaries, then they also need to be attached here. Then press "Create Release":

After creating the release, the following page will be created:

conclusions

In this article, we looked at how to use GitHub to host and manage your project. The whole system is in English, so basic knowledge of the language is very desirable, but even without them, working with github will not be very difficult. Hope this information was helpful to you. If you are interested in how to work with Git from command line, see the article for beginners.

A detailed introduction to working with Git

What is Git and why do I need it?

Git is a distributed version control system that allows you to save all changes made to files stored in a repository. Changes are stored as snapshots, called commits, that can be posted on many servers. Think of it as a standard cloud for backups on steroids - you can not only restore the code in case of a failure, but also roll back the code to any of the previous saved states. You can also easily interact with other developers - again, just as several people can work on the same file in Google Docs, so developers can simultaneously work on the same repository and save their changes.

In view of all its advantages, Git is an indispensable tool for anyone who is or is going to do development. In this article, we'll go over the most useful Git commands and when to use them. It will also help you brush up on your knowledge if you are already familiar with Git.

How to work with Git

There are many commands available in Git, so it's helpful to break them down by topic / reason of use. We'll first look at working with Git on a local machine, since most of the operations take place there, and then we'll move on to the multiuser format.

You can work with Git both through the command line and through graphical interface like GitHub Desktop. While the command line may be intimidating to novice developers, it is better to learn it anyway, as it provides more options than many interface tools.

Typically, Git commands take the form of git<команда> <аргументы>where the argument can be a file path. Commands can also have options, which are denoted as -<опция>or -<однобуквенная опция>... They allow you to customize the actions of the command in more detail. In this article, the commands will be presented in a general way, so everything that is in<>, you will need to replace with your own values.

If you don't know how to use the command, you can open the manual with git help<команда>and if you just need a reminder use git<команда>-h or git<команда>--help (--help and -h are equivalent).

Preparing Git

Installing Git

Windows users can download it from here.

On macOS (OS X), Git comes as part of the Xcode command line tools, so you'll need to install them. To check for Git, open a terminal and type git --version to check the version.

If you are on Linux, use the command sudo apt install git-all (Debian based distributions) or sudo dnf install git-all (RPM based).

Configuring the configuration file

The first thing to do after installing Git is to set up your username and email, as they are used for identification and are stored in all the snapshots you take. These settings, along with all others, are stored in the configuration file.

You can either edit the.gitconfig file directly with a text editor, or use the git config --global --edit command, and you can also edit individual fields using the git config --global command<поле> <значение>- we are interested in the user.name and user.email fields.

You can also configure your text editor to write commit messages using the core.editor field. Initially, the system default editor is used, such as vi for Linux / Mac. The commit.template field allows you to specify the template to be used on each commit.

There are many other fields, but one of the most useful is alias, which binds the command to an alias. For example git config --global alias.st "status -s" allows you to use git st instead of git status -s

The git config --list command will list all the fields and their values ​​from the config file.

Create a git repository

To initialize a new git repository, you can use the git init command or, if you want to copy an existing one, git clone<адрес репозитория> .

Git commit history

Git stores data as a collection of lightweight snapshots known as commits. They store the state of the filesystem at a specific point in time, as well as a pointer to the previous commit (s). Each commit contains a unique checksum - the identifier that Git uses to refer to the commit. To keep track of history, Git keeps a HEAD pointer that points to the first commit (we follow the chain of commits in reverse order to get to the previous commits).

We can refer to a commit either through its checksum or its position relative to HEAD, for example HEAD ~ 4 refers to a commit that is 4 commits before HEAD.

Git file system

Git keeps track of files in three main sections:

  • working directory (file system of your computer);
  • staging area (staging area, stores the content of the next commit);
  • HEAD (last commit in the repository).

All the basic commands for working with files boil down to understanding how Git manages these three sections. There is a common misconception that the staging area only stores changes. Better to think of these three sections as separate file systems, each of which contains its own copies of the files.

Viewing changes in file systems

The git status command displays all files that differ between the three sections. Files have 4 states:

  1. Untracked - Located in the working directory, but there are no versions in HEAD or staging area (Git is unaware of the file).
  2. Modified - there is a newer version in the working directory than in the HEAD or staging area (the changes are not in the next commit).
  3. Staged - there is a newer version in the working directory and staged files area compared to the one stored in HEAD (ready to commit).
  4. No changes - one version of the file in all sections, i.e. the last commit contains the current version.

Note A file can be both "modified" and "prepared" if the version in the working directory is newer than the staging area, which in turn is newer than the version in HEAD.

We can use the -s option to git status to get more compact output (line per file). If the file is not being tracked, will the ?? ; if it has been changed, then its name will be red, and if prepared, it will be green.

To see the changes themselves, and not the changed files, you can use the following commands:

  • git diff - comparison of the working directory with the area of ​​prepared files;
  • git diff --staged - compare staged file area with HEAD.

If you use the argument<файл/папка>then diff will show changes only for the specified files / folders, for example git diff src /.

Updating file systems

Git add command<файл/папка>updates the staged files area with the versions of files / folders from the working directory.

The git commit command updates HEAD with a new commit, which takes snapshots of files in the staging area.

Git reset command action<коммит>consists of three potential steps:

  1. Move HEAD pointer to<коммит>(for example, when you roll back a commit, the working directory and staging area will have newer versions of the files than HEAD). Also the HEAD branch pointer will be moved to this commit.
  2. Update the staging area with the contents of the commit. In this case, only the working directory will contain newest versions files.
  3. Update the working directory with the contents of the staging area. You need to be careful with this, as the file changes will eventually be destroyed.

By default, the git reset command only performs steps 1 and 2, however its behavior can be changed using the --soft (only 1 step) and --hard (all steps) options.

If you pass the path to the file / folder, then the command will be executed only for them, for example git reset --soft HEAD ~ 1 src /.

Git checkout HEAD command<файл>produces the same result as git reset --hard HEAD<файл>- overwrites the version of the file in the prepared files area and in the working directory with the version from HEAD, that is, undo changes after the last commit.

On the other hand, git checkout<файл>(already without HEAD) overwrites the version of the file in the working directory with the version in the staging area, that is, undoes the changes since the last prepared version.

Finally git rm<файл>cancels tracking of the file and removes it from the working directory, the --cached option will save the file.

Ignoring files

Often times, we don't want Git to keep track of all the files in the repository, because these might include:

  • files with sensitive information like passwords;
  • large binaries;
  • assembly files that are generated after each compilation;
  • OS / IDE specific files like .DS_Store for macOS or .iml for IntelliJ IDEA- we need the repository to depend on the system as little as possible.

The .gitignore file is used to ignore. To mark files we want to ignore, we can use search patterns (think of them as simplified regular expressions):

  • / ___ - avoids recursiveness - matches files only in the current directory;
  • __ / - matches all files in the specified directory;
  • * ___ - matches all files with the specified end;
  • ! - ignoring files matching the specified template;
  • [__] - matches any character specified in square brackets;
  • ? - matches any character;
  • / ** / - matches nested directories, for example a / ** / d matches a / d, a / b / d, a / b / c / d, etc.

We can even use search patterns when specifying a file / folder in other commands. For example git add src / *. Css will add all the .css files in the src folder.

Commits

Since commits are the backbone of the version history, it doesn't hurt to learn a little more about them.

The git commit command will open a text editor to enter the commit message. It also accepts several common arguments:

  • -m allows you to write a message along with the command without opening the editor. For example git commit -m "Fixed a bug";
  • -a moves all tracked files to the staging area and includes them in the commit (lets you skip git add before committing);
  • --amend replaces the last commit with the new changed commit, which is useful if you typed the message of the last commit incorrectly or forgot to include some files in it.

A few tips to listen to:

  • Commit often: You won't be able to roll back your changes if there is nothing to roll back to.
  • One change, one commit: Don't put all unrelated changes in one commit, separate them to make it easier to rollback.
  • Message format: the header must be imperative, less than 50 characters in length, and must logically complement the phrase this commit will ___ (this commit will fix bugs - this commit will fix bugs). The message should explain why the commit was made, and the commit itself shows what has changed. details how to write commit messages.
  • (Optional) Don't commit minor changes: in a large repository, many small commits can clog up history. It is considered good practice to make such commits during development, and when adding to a large repository, combine them into one commit.

Viewing changes in history

You can use the git log command to view the history of previous commits in reverse chronological order. Different options can be passed to it:

  • -p shows changes in each commit;
  • --stat shows abbreviated statistics for commits, such as changed files and the number of added / removed lines in each of them;
  • -n shows n last commits;
  • --since = ___ and --until = ___ allows you to filter commits by time period, for example --since = "2019-01-01" will show commits since January 1, 2019;
  • --pretty allows you to specify the format of the logs (for example, --pretty = oneline), you can also use --pretty = format for more customization, for example --pretty = format: "% h% s";
  • --grep and -S filter commits with messages / code changes that contain the specified string, for example, git log -S function_name allows you to see the addition / removal of a function;
  • --no-merges skips merge commits;
  • branch1..branch2 lets you see which commits from branch 2 are not in branch 1 (useful when merging branches). For example, git log master..test will show which commits from the test branch are not in master (we'll talk about branches a little later).
  • --left-right branch1 ... branch2 shows commits that are in either branch 1 or branch 2, but not both; sign< обозначает коммиты из ветка1 , а >- from branch2. Please note: three points are used, not two;
  • -L takes a start, end: file, or: function: file argument and shows the history of changes to the passed lineset or function in the file.

Another useful command is git blame<файл>, which for each line of the file shows the author and the checksum of the last commit that changed that line. -L<начало>, <конец>allows you to restrict this command to the specified lines. This can be used, for example, to find out which commit caused a particular bug (so that you can rollback it).

Finally, there is the git grep command, which searches all files in the commit history (not just the working directory like grep) for a given regexp. The -n option displays the corresponding line number in the file for each match, and the --count option shows the number of matches for each file.

Note Do not confuse git grep with git log --grep! The former looks for files among the commits, and the latter looks at the log messages.

Remote servers

So far, we've only discussed using Git on a local machine. However, we can keep the commit history of remote repositories, which can be tracked and updated (think of them as remote cloud backups of our commit history).

The git remote -v command lists the remote repositories we are tracking and the names we have assigned to them.

When using the git clone command we not only download ourselves a copy of the repository, but also implicitly track remote server which is on the specified address and which is named origin.

Most used commands:

  • git remote add<имя> - adds a remote repository with the given name;
  • git remote remove<имя>- deletes a remote repository with the given name;
  • git remote rename<старое имя> <новое имя>- renames the remote repository;
  • git remote set-url<имя> - assigns a new address to the repository named;
  • git remote show<имя>- shows information about the repository.

The following commands work with remote branches:

  • git fetch<имя> <ветка>- gets data from a branch of a given repository, but does not merge changes;
  • git pull<имя> <ветка>- merges data from a branch of a given repository;
  • git push<имя> <ветка>- Submits changes to the branch of the given repository. If the local branch is already tracking the remote one, then you can simply use git push or git pull.

Thus, several people can request changes from the server, make changes in local copies and then push them to a remote server, which allows interacting with each other within the same repository.

Branching

It's all good and great if each developer works on a project at a different time. The diagrams shown above only showed situations where the original repository or local copy was modified, not the work of multiple people.

This leads us to key feature Git - branching, opportunities to work on different versions project. This means that instead of one list with ordered commits, the history will diverge at certain points (which makes it look like a tree). Each branch in Git contains a lightweight HEAD pointer to the last commit on that branch, allowing you to create many branches at no extra cost. Tip: Name the branch according to the functionality you develop in it. The default branch is named master.

So, we have a common pointer HEAD and HEAD for each branch. Thus, switching between branches only involves moving HEAD in the HEAD of the corresponding branch.

Standard commands:

  • git branch<имя ветки>- creates a new branch with HEAD pointing to HEAD... If you don't pass an argument<имя ветки>, then the command will display a list of all local branches;
  • git checkout<имя ветки>- switches to this branch. You can pass the -b option to create a new branch before switching;
  • git branch -d<имя ветки>- deletes a branch.

Both our local repository and the remote one can have many branches, so when you track a remote repository, the remote branch is actually being tracked (git clone links your master branch to the origin / master branch of the remote repository).

Linking to a remote branch:

  • git branch -u<имя удалённого репозитория>/<удалённая ветка>- binds the current branch to the specified remote branch;
  • git checkout --track<имя удалённого репозитория>/<удалённая ветка>- analogue of the previous command;
  • git checkout -b<ветка> <имя удалённого репозитория>/<удалённая ветка>- creates a new local branch and starts tracking the remote one;
  • git branch --vv - shows local and tracked remote branches;
  • git checkout<удалённая ветка>- creates a local branch with the same name as the remote one and starts tracking it.

In general, git checkout is about changing the location that the HEAD of the branch points to, which is similar to how git reset moves the total HEAD.

Hide and seek

There is one subtlety - when switching branches, Git requires that the working state be clean, that is, all changes in the tracked files must be committed.

Approx. transl. This is not entirely true. Under some circumstances, Git can automatically push an uncommitted change to another branch.

However, sometimes you have unfinished changes that cannot be committed. In such a situation, they can be saved and hidden using the git stash command. To revert changes use git stash apply.

You might want to erase any changes you made instead. In this case, use the git clean command. The -d option will also remove untracked files. Tip: add the -n option to see what happens when you run git clean without using it directly.

Combining branches

After we've discussed what branches are and how to switch between them, it's time to talk about how you can merge them after development. The branch into which we want to merge the changes will be called the main branch, and the branch from which we will merge them will be called the topic branch. There are two ways to make changes from one branch to another: merge and move.

Merge

It involves creating a new commit that is based on the common ancestor commit of the two branches and points to both HEADs as previous commits. To merge, we go to master and use the git merge command<тематическая ветка> .

If both branches change the same part of the file, then a merge conflict occurs - a situation in which Git does not know which version of the file to save, so you need to resolve the conflict yourself. To see conflicting files use git status.

After opening such files, you will see similar conflict resolution markers:

<<<<<<< HEAD:index.html Everything above the ==== is the version in master. ======= Everything below the ==== is the version in the test branch. >>>>>>> test: index.html

Replace everything in this block with the version you want to keep and prepare the file. Once all conflicts have been resolved, you can use git commit to complete the merge.

Moving

Rather than merging the two branches with a merge commit, a move replays the commits of the topic branch as a set of new commits on the base branch, resulting in a cleaner commit history.

The git rebase command is used to move.<основная ветка> <тематическая ветка>that reproduces the changes to the topic thread on the main one; The HEAD of the topic branch points to the last replayed commit.

Moving vs. merger

After merging, the log with history can look quite messy. Moving, on the other hand, allows you to rewrite history in a normal, consistent way.

So why do you need merge when you can use movement all the time? Unfortunately, moving is not a cure for confusing logs, since the moved commits are actually different from the original ones, although they have the same author, message and changes.

Let's imagine the scenario:

  • On your branch, you create multiple commits and merge them into the master branch.
  • Someone else decides to work it out based on your commits.
  • You decide to move your commits and push them to the server.
  • When someone tries to merge their work based on your original commits, they end up with two parallel branches with the same author, posts and changes, but different commits.

So here's a tip:

Only push changes on your private local branch - don't push commits that someone else depends on.

Rollback commits - revert and reset

A similar debate about which is best to use arises when you want to rollback a commit. Git revert command<коммит>creates a new commit that undo changes but preserves history, while git reset<коммит>moves the HEAD pointer, providing a cleaner history (as if this commit never happened). It is important to note that this also means that you can no longer revert back to these changes, for example, if you still decide that undoing the commit was unnecessary. Cleaner doesn't mean better!

Let's summarize

At this point, you have almost everything you need to get started with Git. Below are some (optional) advanced tips for more control over commits and history. In addition, below we will briefly touch on GitHub - one of the most famous platforms for working with Git, which you may find useful.

Github

GitHub is a platform that hosts Git repositories on its multiple servers. As a GitHub user, you can keep your remote repositories on their servers, as well as contribute to other open-source repositories. GitHub augments the use of Git with some new features.

For example, you can fork a remote repository, that is, create your own copy of the repository in the GitHub server. This is useful in cases where you do not have permission to create a branch in the original repository. When you use git clone, your local repository will track the remote fork as origin and the original repository as upstream.

After that, you may need to merge the topic branch of your remote repository into the master branch of the original. To do this, you can create a new Pull Request, where GitHub checks for conflicts before letting you merge. There are often other pre-merge checks, such as reviewing and approving code, or even running tests. In the request, you can discuss the code, and any commits that you submit to the remote topic branch will be automatically added to the request, even if it was created before those commits.

Advanced Usage: Interactive Preparation

You can conveniently control the staging area (for example, when committing multiple small commits instead of one big one) using an interactive console that you can run git add -i. 8 commands are available in it:

  • status - shows for each file a short description of what is (not) prepared;
  • update - prepares tracked files;
  • revert - remove one or more files from the prepared area;
  • add untracked - prepares an untracked file;
  • patch - prepares only part of the file (useful when, for example, you have changed several functions, but want to split the changes into several commits). After selecting a file, you will be shown its fragments and presented with possible commands: Stage this hunk? ... Can I enter? to see what each team is doing;
  • diff - shows a list of prepared files and allows you to see the changes for each of them;
  • quit - exits the interactive console;
  • help - shows a short description of each command.

The * next to the file means that the command will change its status (prepared / unprepared depending on whether it is updating or rolling back). If you press Enter without typing anything in any of the command sub-menus, then all files will go into an (un) prepared state.

Please note that creating patches (preparing only part of the file) is available not only in the interactive console, but also through the git add -p command.

Advanced Usage: Changing History

For more control over the commit history of a local branch, you can use the command git rebase -i HEAD ~ n which will open an interactive console for moving the set of the last n commits, listed in order from oldest to newest (that is, in the order in which they will be moved). This way you can "edit history", but remember that the original commits cannot be changed, only moved.

You can change the order of the commits by changing the order in which they are listed.

Change commit message / split commits

The edit command is used to specify the commit you want to change. Then, when Git does the move, it will stop at that commit. After that, you can use git commit --amend to change the message or prepare forgotten files. If you want to split a commit, after stopping, type git reset HEAD ^ (as a result, HEAD will be moved back one commit and all files changed in this commit will go to the unprepared status). You can then commit the files in separate commits in the usual way.

When finished editing, enter git rebase --continue.

Overwriting multiple commits

Sometimes you may need to overwrite multiple commits - in such cases, you can use git filter-branch. For example, to delete an accidentally committed file, you can type git filter-branch --tree-filter "git rm -f<имя файла>"HEAD. Note, however, that this moves the entire story.

Merging multiple commits

While working on new function in the project, you can gradually commit even the smallest changes in the topic thread. However, because of this, the history is littered with such small commits that it can be contrary to the rules of the project. This can be fixed by merging multiple commits into one big one. To do this, first use the pick command to select the first commit, and then squash for the subsequent ones. Git will apply all the changes in one commit and ask you to edit the shared commit message.

Moving a single commit

Apart from merging / moving all commits in a topic branch, you may only be interested in a specific commit. Let's say you have a local drafts branch where you are working on several potential articles but only want to publish one of them. The git cherry-pick command can be used for this. To get specific commits we want to choose from, we can use git log<основная ветка>..<тематическая> .

Note that this creates a new commit that only repeats the diff of the selected commit (that is, the difference between this commit and the previous one), but not its state.

Conclusion

So we've covered the basic concepts of Git. You can use this article as a quick reference, or you can read the book "Pro Git", which is much longer (~ 450 pages) and covers Git in more depth.

Want to dig deeper into Git, but don't have enough (or, conversely, a lot) of one big book? Then you should take a look at ours.

Resistance to change is a basic human trait. If there was no Git when you started with version control systems, it is very likely that you started with Subversion. Often people say that Git is too complicated for beginners. Nevertheless, I will allow myself to disagree with you.

In this article, I'll show you how you can use Git to work with your projects. Let's assume that you are building a project from scratch and want to use Git as your version control system. After getting familiar with the basic commands, we will take a look at how you can upload your code to GitHub.

This article will cover the basics - how to initialize a project, how to manage new and existing files, and how to store your code in the cloud. We'll skip some of the tricky stuff like branching as this article is geared towards beginners.

Installing Git

On the official site, Git is available for various systems - Linux, Mac, Windows. In our case, we will be using Ubuntu 13.04, and we will install Git using apt-get.

Sudo apt-get install git

Initial configuration

Let's create a directory in which we will work. You can also use Git to work with an existing project, in which case you will not create a demo directory as described below.

Mkdir my_git_project cd my_git_project

The first step is to initialize the Git repository in the project directory. This can be done with the init command, which creates a .git directory with all the information about your project.

Git config --global user.name "Shaumik" git config --global user.email " [email protected]"git config --global color.ui" auto "

It is worth noting that if you do not specify your address and name, then the default values ​​will be used instead. In our case, the default values ​​are donny and [email protected]

We also set the interface color to auto so that the output of the Git commands will be colored. We add the --global prefix to these commands so that these values ​​are used throughout the system, and there is no need to set them for each individual project.

Preparing files for commit

In the next step, we will create some files. You can use any text editor for this. Note that if you are initializing Git in an existing project, you do not need to do this step.

Checking the status of the repository

Now that you have files in your project, let's see how Git handles them. To check the current status of the repository, use the git status command

Adding files to Git

At this point, Git is not tracking any of our files. You need to specifically add files to Git for this to happen. To do this, we will use the add command.

Git add my_file

After checking the status of the repository, we see that one of the files has already been added to it.

To add multiple files, use the following (note that we added the first file earlier, so we only add the remaining two).

Git add myfile2 myfile3

It is possible to use git add recursively, but be careful with this command. There are some files (for example, compiled programs) that should not be added to version control. If you use git add recursively, such files will also go to the repository.

Delete files

Let's say you accidentally added a file to the repository that you shouldn't have gotten there. Or you want to remove a file from the version control system. In general, the git rm command will not only remove the file from the repository, but also physically remove it from disk. To make Git stop tracking the file, but keep it on disk, use the following command:

Git rm --cached [filename]

Commit the changes

Once you've added all the required files, you can commit (commit) them to Git. Imagine that a commit is a snapshot of the state of the project at a certain stage, to which you can return at any point in time, and see the state of the project at that moment. A message is associated with each commit, which is specified by the argument after the -m prefix

Git commit -m "My first commit"

Include a message that will contain useful information, as they help you understand what exactly was changed within the framework of this commit. Avoid general messages like "Rules bugs". If you have a bug tracker, you can indicate a message like “Fixed bug # 123”. It is good practice to include the name of the branch or enhancement in the post. For example, “Asset management - added the ability to generate PDF based on the asset” - a clear and easy-to-understand message.

Git defines a commit with a long hexadecimal number. Usually, there is no need to copy the entire line, the first 5-6 characters are enough to identify a specific commit. The screenshot shows that our commit is identified by the number 8dd76fc.

Further commits

Let's change a few files after we commit them. After we changed them, git status will report that we have changed files.

You can see what has changed in these files since the last commit using the git diff command. If you want to see the changes for a specific file, you can use git diff<файл> .

It is necessary to index the changes and commit them. All changed project files can be added to the commit with the following command:

You can avoid using this command by adding the -a option to git commit. This command will index all modified files and commit them. But this approach can be quite dangerous, because by mistake you can commit what you don't want. For example, let's say you opened a file and accidentally changed it. When indexing changed files, you will be notified of the changes in each file. But if you commit all changed files without looking for help. git commit -a, then all files will be committed, including those you didn't want to commit.

Once you've indexed the files, you can start committing. As mentioned earlier, you can point a message to a commit using the -m switch. But you can also specify multi-line comments using the git commit command, which opens a console editor for entering a comment.

Project management

To view the history of a project, you can use the following command:

It will display the complete history of the project in the form of a list of commits and information about them. The commit information contains the hash of the commit, the author, the time, and the message of the commit. There are many kinds of git log commands that you will need to become familiar with if you are using branching in Git. To view the details of a specific commit, and the files that have changed, run the following command:

Git show<хеш_коммита>

where<хеш_коммита>- the hexadecimal number associated with the commit. Because this manual intended for newbies, we won't cover how to get the state back at the time of a particular commit, or how to manage branches.