Работа с git gui в windows

Git has its native environment within the terminal. All the new features are updated first at the command line and only there is the full power of Git. But plain text isn t the simplest choice for all tasks sometimes some users are much more comfortable with a point and click interface a

Git has its native environment within the terminal. All the new features are updated first at the command line, and only there is the full power of Git. But plain text isn’t the simplest choice for all tasks; sometimes some users are much more comfortable with a point-and-click interface, a visual representation is what they need.

Note: There’s nothing these graphical clients can do that the command-line client can’t; the command-line is still where you’ll have the most power and control when working with your repositories.

Working with GUI

Git GUI is Tcl/Tk based graphical user interface to Git. It focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.

The first thing we need to do is install Git on Windows; you can do so with the following steps:
Step 1: Download and install the latest version of Git for Windows.
Step 2: Use the default options for each step in the installation.
Step 3: Remove Git Bash Desktop Icon.
Step 4: Go to Start > All Programs > Git > Git GUI and make a Desktop Shortcut.

Getting started with Git GUI

Step 1: Create Remote Repository
Now, we need a Git repository, and we’ll create a new remote repository on Github.

Step 2: Create a Local Repository
For creating a local repository: in our Git GUI, click on “Create New Repository”.
Select the location you wish to store your repository in. It is important to note that the selected repository location
MUST NOT
exist.

In order for this new repository to be initialized, you must first create a file, any file, in your local repo.Then, you must Commit and Push to the remote Git repository location.

Step 3: Clone a Remote Repository to a Local Repository
In order to clone a repository, click on the “Clone Existing Repository” link in the Git GUI window. An existing repository is one that is already initialized and/or has commits pushed to it.

Note: In the Source Location field, fill in the Git remote repository location. The target directory works as same in the case of creating a local repository. Git will attempt to create it, and it will fail if it already exists.

Working with the GUI Client

The Git GUI makes it easier to perform Git-related tasks, such as staging changes, commits, and pushes.

Staged Changes

When we move files to a Git directory, you will see all the files in the “Unstaged Changes” window. This basically means that new files have been added, removed, updated, etc. When we click the “Stage Changed” button, it will attempt to add all the new files to the Git index.

Git Equivalent Command:
git add file_name
git status

Commits

After we’ve staged your changes, we need to commit them to your local repository. Type a Commit Message that makes sense to the changes that were made. When we are done, press the Commit button.

Git Equivalent Command:
git commit -m "message"

Pushing

After we have committed all the codes in the local repository, we need to push these changes to our remote repository on GitHub. Without pushing the changes, others would not be able to access the code.

Before we can proceed to push, we need set up a location to push to. Most folks refer to this location as “origin”. In Git, “origin” is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository’s URL – and thereby makes referencing much easier.

Git Equivalent Command:
git push -u origin master

This way GUI makes it a lot easier to work with GIT for the users that do not prefer the command line.

Git has its native environment within the terminal. All the new features are updated first at the command line, and only there is the full power of Git. But plain text isn’t the simplest choice for all tasks; sometimes some users are much more comfortable with a point-and-click interface, a visual representation is what they need.

Note: There’s nothing these graphical clients can do that the command-line client can’t; the command-line is still where you’ll have the most power and control when working with your repositories.

Working with GUI

Git GUI is Tcl/Tk based graphical user interface to Git. It focuses on allowing users to make changes to their repository by making new commits, amending existing ones, creating branches, performing local merges, and fetching/pushing to remote repositories.

The first thing we need to do is install Git on Windows; you can do so with the following steps:
Step 1: Download and install the latest version of Git for Windows.
Step 2: Use the default options for each step in the installation.
Step 3: Remove Git Bash Desktop Icon.
Step 4: Go to Start > All Programs > Git > Git GUI and make a Desktop Shortcut.

Getting started with Git GUI

Step 1: Create Remote Repository
Now, we need a Git repository, and we’ll create a new remote repository on Github.

Step 2: Create a Local Repository
For creating a local repository: in our Git GUI, click on “Create New Repository”.
Select the location you wish to store your repository in. It is important to note that the selected repository location
MUST NOT
exist.

In order for this new repository to be initialized, you must first create a file, any file, in your local repo.Then, you must Commit and Push to the remote Git repository location.

Step 3: Clone a Remote Repository to a Local Repository
In order to clone a repository, click on the “Clone Existing Repository” link in the Git GUI window. An existing repository is one that is already initialized and/or has commits pushed to it.

Note: In the Source Location field, fill in the Git remote repository location. The target directory works as same in the case of creating a local repository. Git will attempt to create it, and it will fail if it already exists.

Working with the GUI Client

The Git GUI makes it easier to perform Git-related tasks, such as staging changes, commits, and pushes.

Staged Changes

When we move files to a Git directory, you will see all the files in the “Unstaged Changes” window. This basically means that new files have been added, removed, updated, etc. When we click the “Stage Changed” button, it will attempt to add all the new files to the Git index.

Git Equivalent Command:
git add file_name
git status

Commits

After we’ve staged your changes, we need to commit them to your local repository. Type a Commit Message that makes sense to the changes that were made. When we are done, press the Commit button.

Git Equivalent Command:
git commit -m "message"

Pushing

After we have committed all the codes in the local repository, we need to push these changes to our remote repository on GitHub. Without pushing the changes, others would not be able to access the code.

Before we can proceed to push, we need set up a location to push to. Most folks refer to this location as “origin”. In Git, “origin” is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository’s URL – and thereby makes referencing much easier.

Git Equivalent Command:
git push -u origin master

This way GUI makes it a lot easier to work with GIT for the users that do not prefer the command line.

Git GUI — A graphical user interface for Git

Git GUI allows you to use the Git source control management
tools via a GUI. This includes staging, committing,
adding, pushing, etc. It can also be used as a blame viewer, a tree browser,
and a citool (make exactly one commit before exiting and returning to shell).
More details about Git GUI can be found in its manual page by either running
man git-gui, or by visiting the online manual
page.

Git GUI was initially written by Shawn O. Pearce, and is distributed with the
standard Git installation.

Building and installing

You need to have the following dependencies installed before you begin:

  • Git
  • Tcl
  • Tk
  • wish
  • Gitk (needed for browsing history)
  • msgfmt

Most of Git GUI is written in Tcl, so there is no compilation involved. Still,
some things do need to be done (mostly some substitutions), so you do need to
«build» it.

You can build Git GUI using:

And then install it using:

You probably need to have root/admin permissions to install.

Contributing

The project is currently maintained by Pratyush Yadav over at
https://github.com/prati0100/git-gui. Even though the project is hosted at
GitHub, the development does not happen over GitHub Issues and Pull Requests.
Instead, an email based workflow is used. The Git mailing list
git@vger.kernel.org is where the patches are
discussed and reviewed.

More information about the Git mailing list and instructions to subscribe can
be found here.

Sending your changes

Since the development happens over email, you need to send in your commits in
text format. Commits can be converted to emails via the two tools provided by
Git: git-send-email and git-format-patch.

You can use git-format-patch to generate patches in mbox format from your
commits that can then be sent via email. Let’s say you are working on a branch
called ‘foo’ that was created on top of ‘master’. You can run:

git format-patch -o output_dir master..foo

to convert all the extra commits in ‘foo’ into a set of patches saved in the
folder output_dir.

If you are sending multiple patches, it is recommended to include a cover
letter. A cover letter is an email explaining in brief what the series is
supposed to do. A cover letter template can be generated by passing
--cover-letter to git-format-patch.

After you send your patches, you might get a review suggesting some changes.
Make those changes, and re-send your patch(es) in reply to the first patch of
your initial version. Also please mention the version of the patch. This can be
done by passing -v X to git-format-patch, where ‘X’ is the version number
of the patch(es).

Using git-send-email

You can use git-send-email to send patches generated via git-format-patch.
While you can directly send patches via git-send-email, it is recommended
that you first use git-format-patch to generate the emails, audit them, and
then send them via git-send-email.

A pretty good guide to configuring and using git-send-email can be found
here

Using your email client

If your email client supports sending mbox format emails, you can use
git-format-patch to get an mbox file for each commit, and then send them. If
there is more than one patch in the series, then all patches after the first
patch (or the cover letter) need to be sent as replies to the first.
git-send-email does this by default.

Using GitGitGadget

Since some people prefer a GitHub pull request based workflow, they can use
GitGitGadget to send in patches. The tool
was originally written for sending patches to the Git project, but it now also
supports sending patches for git-gui.

Instructions for using GitGitGadget to send git-gui patches, courtesy of
Johannes Schindelin:

If you don’t already have a fork of the git/git
repo, you need to make one. Then clone your fork:

git clone https://github.com/<your-username>/git

Then add GitGitGadget as a remote:

git remote add gitgitgadget https://github.com/gitgitgadget/git

Then fetch the git-gui branch:

git fetch gitgitgadget git-gui/master

Then create a new branch based on git-gui/master:

git checkout -b <your-branch-name> git-gui/master

Make whatever commits you need to, push them to your fork, and then head over
to https://github.com/gitgitgadget/git/pulls and open a Pull Request targeting
git-gui/master.

GitGitGadget will welcome you with a (hopefully) helpful message.

Signing off

You need to sign off your commits before sending them to the list. You can do
that by passing the -s option to git-commit. You can also use the «Sign
Off» option in Git GUI.

A sign-off is a simple ‘Signed-off-by: A U Thor <author@example.com>’ line at
the end of the commit message, after your explanation of the commit.

A sign-off means that you are legally allowed to send the code, and it serves
as a certificate of origin. More information can be found at
developercertificate.org.

Responding to review comments

It is quite likely your patches will get review comments. Those comments are
sent on the Git mailing list as replies to your patch, and you will usually be
Cc’ed in those replies.

You are expected to respond by either explaining your code further to convince
the reviewer what you are doing is correct, or acknowledge the comments and
re-send the patches with those comments addressed.

Some tips for those not familiar with communication on a mailing list:

  • Use only plain text emails. No HTML at all.
  • Wrap lines at around 75 characters.
  • Do not send attachments. If you do need to send some files, consider using a
    hosting service, and paste the link in your email.
  • Do not top post.
  • Always «reply all». Keep all correspondents and the list in Cc. If you reply
    directly to a reviewer, and not Cc the list, other people would not be able
    to chime in.

1. Git (произн. «гит») — распределённая система управления версиями
файлов. Проект был создан Линусом Торвальдсом для управления разработкой ядра
Linux.

Git использовался для таких больших проектов, как ядро Linux, Android, Drupal,
Wine, Chromium, PHP, NASM и некоторые дистрибутивы Linux.

2. Создание репозитория при помощи Git Gui.

2.1. Для того чтобы создать новый репозиторий, запускаем Git Gui и выбираем
пункт «Создать новый репозиторий»:

Выбор пункта “Создать новый репозиторий”
Выбор пункта “Создать новый репозиторий”

2.2. Далее выбираем каталог с проектом:

Выбор каталога с проектом
Выбор каталога с проектом

2.3. И нажимаем кнопку «Создать»:

Создание репозитория
Создание репозитория

2.4. Откроется окно работы с проектом: 

Работа с проектом в Git Gui
Работа с проектом в Git Gui

2.5. В каталоге проекта создастся подкаталог .git

Подкаталог .git в каталоге проекта
Подкаталог .git в каталоге проекта

 

2.6. Теперь при запуске Git Gui можно будет выбирать существующий репозиторий,
только что созданный нами: 

Выбор существующего репозитория в Git Gui
Выбор существующего репозитория в Git Gui

 
3. Полезные ссылки:

—  Книга про Git
—  Git, шпаргалка

 Посты по теме :

  • Debian.Утилиты для жестких дисков (hdd). 1 часть
  • VirtualBox и Debian. Настройка общих папок
  • Debian. Start, stop, restart сервера Apache2

I recently started to use GIT as source code management system, and because i’m not made for commands written in console-like windows, i was looking for a guide on how to install and use the GIT Gui for Windows.

I found this guide written by nathanj here and i think it’s one of the easiest tutorials that i found on the web. You can find it here or on nathanj site.

An Illustrated Guide to Git on Windows

Table of Contents

  1. About
  2. Downloading PuTTY
  3. Installing Git
  4. Creating a Repository
  5. Committing
  6. Branching
  7. Merging
  8. Viewing History
  9. Pushing to a Remote Server
  10. Pulling from a Remote Server
  11. Conclusion

About

Note: This guide was written in early 2009. Some parts of it may be out of date. Good luck!

Using the instructions in this document, you can quickly and easily install git on Windows. In this guide, I will create a repository, make several commits, create a branch, merge a branch, search the commit history, push to a remote server, and pull from a remote server. The majority of this will be done using GUI tools.

Although this guide is targeted for use on Windows, the git gui tool works the same on all platforms. Because of this, git users on other platforms may find useful information here as well.

Downloading PuTTY

Although you can use the SSH program that comes with git, I prefer to use the PuTTY Agent to keep track of my SSH keys. If
you don’t already have them, download putty.exe, plink.exe, pageant.exe, and puttygen.exe from the PuTTY
web site.

Later in this guide, we will use these programs for securely pushing our changes to a remote server.

Installing Git

First, download msysgit.
This download is a single executable which installs the entire git system. While going through the installer, you will want to check the options to add Windows Explorer integration when you right click on a folder.

Because we will be using PuTTY as our SSH client, choose Use PLink and fill in the path to the downloaded plink.exe executable.

Continue clicking Next until the installation is complete.

Creating a Repository

To create a repository, first create the folder you want the project to live under. Next, right click on the folder and choose Git GUI Here. Because there is no git repository in this folder yet, you will be presented with the git gui startup dialog.

Choosing Create New Repository brings us to the next dialog.

Fill in the path to your new directory and click Create. You will then be presented with the main interface of git gui, which
is what will be shown from now on when you right click on your folder and click Git GUI Here.

Now that the repository has been set up, you will need to tell git who you are so that commit messages will have the correct author. To do this, choose Edit ? Options.

In the options dialog, there are two versions of each preference. On the left side of the dialog are options that you want for this repository only, while the right side contains the global options which apply to all repositories. The defaults for these options are sensible so just fill in the user name and email for now. If you have a favorite font, you may want to set it now as well.

Committing

Now that the repository has been created, it is time to create something to commit. For this example, I created a file called main.c with the following content:

#include 

int main(int argc, char **argv)
{
	printf("Hello world!n");
	return 0;
}

Clicking the Rescan button in the git gui will cause it to search out new, modified, and deleted files in the directory. In the next screenshot, git gui has found our new file (amazing, I know).

To add the file for committing, click the icon to the left of the filename. The file will be moved from the Unstaged Changes pane to the Staged Changes pane. Now we can add a commit message and commit the change with the Commit button.

Saying hello to the world is all well and good, but I would like my program to be more personal. Let’s have it say hello to the user. Here’s my code for that:

#include 
#include 

int main(int argc, char **argv)
{
	char name[255];

	printf("Enter your name: ");
	fgets(name, 255, stdin);
	printf("length = %dn", strlen(name)); /* debug line */
	name[strlen(name)-1] = ''; /* remove the newline at the end */

	printf("Hello %s!n", name);
	return 0;
}

I had some trouble figuring out why a newline was printed after the user’s name, so I added a debugging line to help me track it down. I would like to commit this patch without the debug line, but I want to keep the line in my working copy to continue debugging. With git gui, this is no problem. First, click Rescan to scan for the modified file. Next, click the icon to the left of the filename to stage all modifications for commit. Then, right click on the debug line and chose Unstage Line From Commit.

Now, the debug line has been unstaged, while the rest of the changes have been staged. From here, it is just a matter of filling in the commit message and clicking Commit.

Branching

Now let’s say that we want to start adding new features for our next big version of the program. But, we also want to keep a stable, maintenance version of the program to fix bugs on. To do this, we will create a branch for our new development. To create a new branch in git gui, choose Branch ? Create. The big feature that I would like to add is to ask the user for their last name, so I am calling this branch lastname. The default options in the Create Branch dialog are all fine, so just enter the name and click Create.

Now that I am on the lastname branch, I can make my new modifications:

#include 
#include 

int main(int argc, char **argv)
{
	char first[255], last[255];

	printf("Enter your first name: ");
	fgets(first, 255, stdin);
	first[strlen(first)-1] = ''; /* remove the newline at the end */

	printf("Now enter your last name: ");
	gets(last); /* buffer overflow? what's that? */

	printf("Hello %s %s!n", first, last);
 	return 0;
}

And then I can commit the change. Note here that I am committing using a different name. This is to show off something later. Normally you would always use the same name when committing.

Meanwhile, a user informs us that not displaying a comma when directly addressing someone is a serious bug. In order to make
this bug fix on our stable branch, we must first switch back to it. This is done using Branch ? Checkout.

Now we can fix our major bug.

If we choose Repository ? Visualize All Branch History, we can see how our history is shaping up.

Merging

After days of work, we decide that our lastname branch is stable enough to be merged into the master branch. To perform the merge, use Merge ? Local Merge.

Because the two different commits made two different
modifications to the same line, a conflict occurs.

This conflict can be resolved using any text editor. After resolving the conflict, stage the changes by clicking the file icon and then commit the merge by clicking the Commit button.

Viewing History

The main.c file is starting to get a bit big, so I decided to move the user prompting portion of the code into its own function. While I was at it, I decided to move the function into a separate file. The repository now contains the files main.c, askname.c, and askname.h.

/* main.c */
#include 

#include "askname.h"

int main(int argc, char **argv)
{
	char first[255], last[255];

	askname(first, last);

	printf("Hello, %s %s!n", first, last);
 	return 0;
}

/* askname.c */
#include 
#include 

void askname(char *first, char *last)
{
	printf("Enter your first name: ");
	fgets(first, 255, stdin);
	first[strlen(first)-1] = ''; /* remove the newline at the end */

	printf("Now enter your last name: ");
	gets(last); /* buffer overflow? what's that? */
}

/* askname.h */
void askname(char *first, char *last);

The history of the repository can be viewed and searched by choosing Repository ? Visualize All Branch History.
In the next screenshot, I am trying to find which commit added the last variable by searching for all commits which added or removed the word last. Commits which match the search are bolded, making it quick and easy to spot the desired commit.

A few days later, someone looks through our code and sees that the gets function could cause a buffer overflow. Being the type to point fingers, this person decides to run a git blame to see who last modified this line of code. The problem is that Bob is the one who committed the line, but I was the one who last touched it when I moved the line into a different file. Obviously, I am not to blame (of course). Is git smart enough to figure this out? Yes, it is.

To run a blame, select Repository ? Browse master’s Files. From the tree that pops up, double click on the file with the line in question which in this case is askname.c.
Hovering the mouse over the line in question shows a tooltip message that tells us all we need to know.

Here we can see that the line was last modified by Bob in commit f6c0, and then I moved it to its new location in commit b312.

Pushing to a Remote Server

Before pushing to a remote server, you must first create a SSH public and private key pair. By using SSH, you will be able to securely authenticate to the server that you are who you say you are. Creating the key pair is a simple process. Begin by running the puttygen.exe program downloaded earlier. Next, click the Generate button to generate the keys. After processing for a few seconds, click the Save private key button to save your new private key. Copy the public key to the clipboard in preparation for the next step. I would recommend not clicking the Save public key button because the saved file is in a non-standard
format; trying to use it with other software might be problematic.

Now that the keys are generated, the remote servers need to know about it. If you would like to use github to host your code, just
go to your account page and paste in the public key.

Now github has our public key, but we do not yet have github’s. To remedy this, launch putty.exe, connect to github.com, and click Yes to accept github’s public key. You can safely close the login window that opens up after accepting the key.

We need our private key to be loaded up to use with our public key, so launch pageant.exe. This program will create an icon in your system tray. Double clicking on the icon will open up a window into which the private key can be added. Once the private key is added, the agent will sit in the background and provide authentication when needed.

Now that our client and server can authenticate each other, it is time to push! Remote ? Push will open up the push dialog. Typing in the commit address for the project and clicking Push will send the changes on their way.

Of course, typing in the remote url would become quite annoying if we had to do it with every push. Instead, git allows us to alias the long urls using remotes. Git gui currently does not have a way to add a remote, so the command line must be used. Right click on the repository folder and choose Git Bash Here.
In the prompt, enter the following command:

git remote add github git@github.com:nathanj/example.git

Note: After adding a remote, close and reopen git gui for it to recognize the new remote.

Now the remote github is aliased to the url git@github.com:nathanj/example.git. When viewing the push dialog in git gui, a convenient drop down list of remotes is shown.

Pulling from a Remote Server

Because our code is so useful, dozens of people have downloaded and now use our program. One person in particular, Fred, has decided to fork our project and add his own commits.
Now that he’s added his code, he would like us to pull those commits from him into our repository. To do this, first create another remote.

git remote add fred ssh://fred@192.168.2.67/home/fred/example

Now we can fetch Fred’s changes using Remote ? Fetch
from ? fred
.

After the fetch, Fred’s commits have now been added to our local repository under the remotes/fred/master branch. We can use gitk to visualize the changes that Fred has made.

If we like all of Fred’s changes, we could do a normal merge as before. In this case though, I like one of his commits but not the other. To only merge one of his commits, right click on the commit and choose Cherry-pick this commit. The commit will then be merged into the current branch.

We can now push a final time to send Fred’s patch to our
github tree for everyone to see and use.

Conclusion

In this guide, I have shown how to do many common tasks in git using GUI tools. I hope that this guide has shown that it is not only possible but easy to use git on Windows without having to use the Windows shell for most operations.

Getting started with Git can be a daunting task, especially if you are not at home in the command line. Fortunately, Git is a mature and widely used tool so there is a lot of reference and “How do I…?” material available. One aspect less commonly covered is using Git with some of the numerous Git GUIs available. This article will get you up and running with a basic understanding of Git concepts and how to manage your Git workflow with Git Gui, TortoiseGit, and Visual Studio Code.

Why use a GUI?

Git is a powerful, robust tool that runs on the command line by default. Using a GUI offers a more discoverable interface and some people prefer the aesthetics of GUIs over the CLI. For developers focused on writing code and using Git to collaborate with their team or contribute to OSS projects a GUI can be a pleasant tool that will comfortably handle the necessary tasks. Once you learn Git concepts you don’t necessarily need to memorize the specific steps to accomplish tasks – GUIs make it easier to discover (or rediscover!) how to accomplish a task when you know what your task is.

Branch history in Git Gui

Git concepts

If you aren’t already familiar with software version control this short article is a good introduction.

The Git commit tree

Git stores changes in a series of commits. Every commit is identified by a unique hash. One thing that can be confusing to newcomers is that the arrows in Git tree diagrams point backwards. While the chronological flow for commits A then B then C looks like:

A → B → C

The commits are stored with parent references, not child references. A has no knowledge of B or C; B records that A is its parent and C records that B is its parent. This gives us a commit tree like:

A ← B ← C

File concepts in Git

  • Working Tree: all of the files in the file system in your project folder. Git may ignore some files depending on the configuration in the .gitignore file.
  • Staging Area: the “commit” command only commits files that have been added to staging. File diffs can be viewed between working tree content and staged content.
  • Repository: the Git repository contains all commits and other Git data.

You add files to the working tree simply by adding them to your file system. Git’s “add” command, or Git Gui’s “Stage to Commit” action adds changes to the staging area. Git’s “commit” command adds changes to the repository.

Getting started

The first step is to create a Git repository. We’ll start with TortoiseGit for this task since its context menu is integrated into Windows Explorer.

Tip: The Tortoise VCS clients have quite a lineage going back to TortoiseSVN and even TortoiseCVS. If you have used those you’ll be right at home with TortoiseGit.

Create a new folder to start an empty project. Open the folder’s context menu and click “Git Create repository here”. This will add a “.git” folder to store Git’s data. At this point the repository is empty, the staging area is empty, all your project is in the working tree only and Git is not tracking anything. You can open Git Gui by clicking “Git GUI Here” in the folder’s context menu.

  • Top-left shows unstaged changes (which at this point is all files)
  • Bottom-left shows staged changes (empty)
  • Top-right shows the diff for the selected file
  • Bottom-right is where you can enter a commit message

Now add a plain text file to your project folder and click the “Rescan” button in Git Gui. The file will show up in the top-left pane. The “Stage Changed” button will add all changed files to the staging area.

Tip: You can add individual files from the menu: Commit → Stage to commit.

Click “Stage Changed” to add your new file to the staging area and you will see it move from the top-left pane to the bottom-left pane. Now edit the file and save changes, then rescan again. The file now shows up in both the unstaged and staged panes. Clicking the file in the staged pane will show a diff on the right of the file contents when you staged it. Clicking the file in the unstaged pane will show the additional changes you made after staging it.

Tip: This can be useful for incrementally tracking changes while you code – even if you are not ready to make a commit, you can stage your changes and then do experimental code changes. You can see a diff of your changes so you know exactly what you changed and you can even back out your unstaged changes (Commit → Revert changes) while preserving your staged changes.

Let’s go ahead and make our first commit – rescan and click “Stage Changed”. Now enter a commit message in the lower right pane and click “Commit”. At this point the panes on the left are empty indicating that the working tree and the repository are in sync. If you delete all files (but not the “.git” folder!) in your working tree you can still restore them from the Git repository (which is stored in the”.git” folder).

If you make a commit and realize you want to make another small change and want to include that in the commit you can check the “Amend Last Commit” checkbox above the commit message. Be cautious with this feature as it rewrites history. Git history is the record of what was changed in each commit and what parent each commit has. Git is very good at enabling multiple developers to collaborate on a project and synchronize changes, but when you rewrite history this can affect other people and complicate things. If you have not shared your commit with anyone you can safely amend commits. Once you share a commit with others (e.g. by pushing to GitHub) then rewriting history (amend, rebase) will affect them as well.

Sharing your work

There are various ways of sharing Git repositories, some of the most popular are GitHub and GitLab. To share your repository on GitHub you will need a GitHub account and you need to create a new empty repository on GitHub. To connect your local repository with GitHub you will configure a new remote. In Git Gui this is done from the menu: Remote → Add. The location is the URL with “.git” appended to it. For example the Dojo repository is at https://github.com/dojo/framework and its Git location is https://github.com/dojo/framework.git. The name is arbitrary, but it is a common practice to name the primary remote “origin”. You can add more remotes, for example the primary remote would be under your organization and each developer might create “forks” (GitHub copies) of the project in their GitHub account. You would need a remote for “origin”, another remote for your own fork, and if you want to work with branches from other developers you would need a remote for them.

Tip: Git Gui makes it easy to add remotes, but if you want to manage them in more detail you can do so in TortoiseGit: choose “Git Sync” from the context menu and click the “Manage” button to the right of “Remote URL” at the top.

With a remote configured you can now upload your Git repository to GitHub with Git’s “push” command. In Git Gui the “Push” button is just below the “Commit” button. TortoiseGit gives you a little more control over how you push with its dialog in “Git Sync”. After successfully pushing your repository to GitHub you will be able to browse your files on GitHub.

Cloning and pulling from GitHub

We’ve just covered creating a local repository and pushing it to GitHub. What if you want to copy a repository from GitHub locally? Open the context menu of the folder that will be the project’s parent and click “Git Clone”. In the URL field enter the Git URL (e.g. https://github.com/dojo/framework.git). Everything else can be left as-is, but you can rename the folder if you want (by default the dojo/framework repo would be cloned into the “framework” folder, but you can change the name).

With a GitHub repository created, a local repository created, and the GitHub repository configured as a remote you can synchronize the two using the Pull and Push buttons in TortoiseGit’s “Git Sync” window. Pull will download changes from GitHub to your local repository; push will upload changes to GitHub.

Play well with others

Adding new features to a project is commonly done within a branch. A branch is a named group of commits. A Git repository starts with a single branch, typically named “master” or “main”. Branches can be temporary, where a feature is developed in a branch and eventually integrated into the main branch, or they can be long-lived to maintain multiple versions of a project. Let’s create a feature branch from “master” in Git Gui:

  1. Click Branch → Create
  2. Give your branch a name
  3. For “Starting Revision” accept the default of “Local branch: master”
  4. Click “Create”

That’s it! You are now on a new branch. Any commits you make will be in the branch, not in “master”. Git Gui displays the name of the current branch just below the menu bar. You can now make some commits and push your branch to GitHub using TortoiseGit: choose “Git Sync” from the context menu, then click the Push button. Work can continue in parallel on the main branch and feature branches, and when a feature branch is complete and ready to be integrated you create a pull request in GitHub.

Rebasing a feature branch

Often when you are working on a feature branch work from other developers will be completed and merged into the main branch. Ideally work is broken up and scheduled in a way that minimizes conflicts, but they are inevitable.

One common workflow when integrating feature branches is to create a merge commit. A merge commit says “I added all these commits from this branch to master”, and potentially includes extra changes to resolve any conflicts. A merge workflow may be useful if you want your Git history to record who made what commits when, in what branch, and when they were merged. However, this type of history can be large and confusing. Many projects instead benefit from a history that records “this feature was added at this time by this person”.

Tip: A clean history makes finding out which commit broke (or fixed!) something with “git bisect” easier.

The recommended workflow to achieve a simple linear history is to use squash and rebase. Squashing a PR squashes all the PR’s commits into a single commit that is added to master directly (no extra merge commit). Rebasing is a method of resolving conflicts within a branch by rewriting the branch’s history. For a branch with commits C, D, and E, rebasing would change the commits (and assign new hashes) – this is why we say it “rewrites history”. The actual history is you created commits C, D, and E. When you rebase you change the history to record that you created commits C’, D’, and E’. The rebase commits will be identical if there are no conflicts, but will have a new parent. If there are conflicts you will have to resolve them during the rebase.

When should I rebase?

  • If master has been updated with new code that you want to use in your branch
  • If your PR has conflicts and cannot be merged

How to rebase

  1. Edit a file in your project to have 3 lines of text, save & commit to master
  2. Create a branch, edit line 3, save & commit
  3. Check out master, edit line 1, save & commit
  4. Check out your branch and look in the file – the most recent change to line 1 in master will not be present
  5. In Git Gui click Repository → Visualize <branch>’s History
    • This shows the commit history, click on a commit to see the SHA1 hash – note down the hash for your last commit
  6. Choose “Rebase” from TortoiseGit’s context menu
    • Top left will show your branch
    • In the top right set “Upstream” to “master”
    • Click “Start Rebase” and “Done”
  7. Look at the branch history again – the commit to master has been inserted into the branch’s history, and your latest commit in the branch has a new hash
  8. History has been rewritten!

The TortoiseGit rebase dialog

This was a simple rebase with no conflicts, let’s go through the process again with a conflict. You can continue with the same branch:

  1. Check out master, set line 1 to be “the first line of text”, save & commit
  2. Check out your branch, edit line 1 to be “the first line of (branch edit) text”, save & commit
  3. Check out master, set line 1 to be “the (master edit) first line of text”, save & commit
  4. Now when you rebase your branch on master the process halts indicating there is a conflict. VS Code provides a good UI for resolving conflicts, so open the project in VS Code and click the “Source Control” icon on the left.
  5. The left pane shows your files in two categories:
    1. Merge Changes: files with conflicts that cannot be automatically resolved (you need to fix these)
    2. Changes: files with no conflicts that can automatically be rebased (you don’t need to do anything)
  6. Open your file. VS Code will highlight conflicting lines, showing both versions of the line. “Current Change” is the value in the commit you are rebasing on (master). “Incoming Change” is the value in the commit in your branch. If one or the other is correct you can simply click “Accept Current/Incoming Change” in VS Code. If you need to manually edit the value you can click “Accept Both Changes” and edit the file as needed. When the conflict is resolved save the file and click the “Stage Changes” (➕) icon next to the file name.
  7. Back in TortoiseGit’s rebase dialog you can click “Resolved” in the file’s context menu and click “Commit” to finish rebasing.

Resolving a conflict in VS Code

As PRs are merged and the main branch is updated you may have to rebase your feature branch repeatedly to receive updates while continuing to work in your branch. If the updates to main do not affect your code there’s no need to rebase and incorporate them. When you create a PR on GitHub as long as there are no conflicts a squash merge will automatically squash and rebase all the commits in your PR into a single commit maintaining a linear history on master.

One challenge with rebasing is that the rebase process is performed for every commit in your branch. If you have a lot of commits, and a lot of noise in your change history (let’s do this, no that, hmmm, something else) then rebasing can be a bit of a waste of time resolving conflicts in commits that aren’t even relevant to the current state of the code. In this case you may benefit from squashing your whole branch to a single commit in a new branch. Then you move development to the new branch and when you rebase you are only dealing with a single commit.

Tip: Selective staging

Git Gui makes selective staging of individual lines very easy. Suppose you edited a file, made some changes and are ready to commit. But you have some debug statements, or unrelated feature changes in the file that you don’t want to commit. Looking at the diff in Git Gui you can select individual lines and click “Stage Line for Commit” – be sure to do this in pairs, as the diffing is done by line, not by word. When anything in a line is changed the diff records:

  • Line x was removed (displays old content in red with a minus sign at the beginning)
  • Line x was inserted (displays new content in green with a plus sign at the beginning)

So to stage a change to a single word in a line you have to stage both the removal and the insertion, which are displayed as two separate lines in the diff. If you only want to stage a few lines you can easily select them from the diff and stage them. Conversely, if you have a lot of changes and only want to exclude a few lines you can stage the whole file, then in the staged diff click “Unstage Line From Commit” for the relevant lines.

Git back to work

You now have a good foundation of Git principles and basic to intermediate tasks in some common Git GUIs to be able to get back to focusing on writing code while maintaining good collaboration practices. Some further items to learn about are cherry picking commits, squashing branches, and Git’s “bisect” command.

GIT FOR WINDOWS TUTORIAL

In this article we will focus on one area of Git version control software that is usually overlooked and not covered in most basic tutorials out there – how to use it for your own private and local files version tracking.

Git logo

Git Logo

WHAT IS GIT ?

Git is a revision control software — an essential tool that can help you track all the changes in your projects and your source code management. In the old days before version control software was widespread and easily available, programmers used to create and keep zipped/archived file versions of their projects: project_version_1.0.zip, project_version_1.1.zip, project_version_2.0.zip and so on.

While this practice is still around and actually not part of the history as some may believe, VCS/SCM/RCS (all synonyms!) can help you focus more on your work, instead on keeping the track with all the versions and changes.

What’s more, revision control software has many “smart” features such as automatic detection of renamed files/directories, calculating similarity between old and new created ones, automatic synchronization of changes between different users (users A and B can work on the same project at the same time), easy comparison between different files and entire project versions, and so on.

Git is the most popular one today, but you should know that there are many others, with different architectures and features, and their own set of advantages and disadvantages. For a list of available VCS tools take a look at this list here.

WHAT IS GIT FOR WINDOWS ?

First of all, there are many GUI (graphical user interface) so-called Git clients for Windows — take a look at this list here. However, in this tutorial we will focus on the simplest, free and very easy to use Git for Windows found here:

updated url: https://gitforwindows.org/
(old url: http://msysgit.github.io)

Naturally, this entire project is hosted on GitHub, a “cloud” version of the Git itself here: https://github.com/msysgit

And finally, in case you wish to read about differences between msysGit and Git For Windows naming conventions and all the confusion that arises between them – go here

In a nutshell, using layman’s terms, Git for Windows is a version control built in executable form (.exe) which you can download and install on your Windows OS machine (XP, Vista, 7, 8, 10…). It comes with 2 versions:

  • Git Bash (this is a terminal or command line version of Git for Windows)
  • Git GUI (this is what we are talking about and will use today in this tutorial — this is a zero CLIno command lines Git tutorial for newbies!

HOW TO DOWNLOAD GIT FOR WINDOWS ?

At msysgit.github.io gitforwindows.org there is a pretty straight forward download page, however, you may get confused about the msysGit part, so to make sure you have the right file, it must have the similar name like this one:

Git-1.9.5-preview20150319.exe

UPDATE: Since May 2015. first official 2.x versions became available, without “preview” part. Additionally, exe file name contains 32-bit and 64-bit platform designation. Portable (non-installation) versions became available, as well. The update cycle seems to be extremely accelerated, with new versions being released on a weekly basis.

Filename begins with “Git” and that is the most important part. Next is the version number, then comes the confusing word “preview” (do not worry, technically all Git for Windows releases are still considered as preview versions – not final, but that does not mean they are unstable or anything), and lastly comes a release date with .exe extension. Now, by the time you will be reading this there could be a newer versions like 2.0, and the word “preview” might be removed from the filename, but it will be similar to the above pattern anyway.

Once you download it, install it like any other Windows Application (just use default options) and you should initially see Git Bash icon on your Desktop. However, in Start menu you will also find Git GUI shortcut, so you can copy it onto Desktop, since in this tutorial we are only going to use GUI version of Git:

Git for Windows - Git Bash - Git GUI icons shortcuts

Git for Windows Git Bash/Git GUI

Since 2.x rhombus background of the icons is replaced with a 4-color Microsoft Windows styled version instead of single-colored classic red kind.

IMPORTANT NOTE: We will skip the part where you need to generate SSH key (.ssh file) in your C:UsersUser… or C:Documents and Settings… folder) with credentials such as your device/computer label and your passphrase, since this tutorial is focused on local/private projects which will not be synced with public repositories hosted on GitHub, GitLab, BitBucket and so on in case you wish to use SSH for access. In case you wish to use HTTPS, no SSH keys are actually required!

GIT FOR WINDOWS – 10 MINUTES TUTORIAL
HOW TO BECOME A GIT MASTER WITH ZERO COMMAND LINES

STEP 1: We will create an empty directory* (folder) that will hold our project. It will be called git-basics and we will place our project under XAMPP server htdocs directory. You can place your project wherever you want: on C: drive, Z:drive, under My Documents, and you can have as many projects as you like — across all places around. However, if you like to be organized, better stick with one universal location that you will dedicate to Git projects.

Git Basics 01 Create Empty Project Folder

Git Basics 01 Create Empty Project Folder

* There is one important difference regarding this step when working with local (private) and publicly available repositories.

Remember:

  • When you work with local repositories (as in this tutorial) you must create an empty directory/folder that will keep your local project.
  • However, if you wish to clone/sync existing public repository (e.g. from GitHub), you MUST NOT create the directory in advance (only specify the proper path to the directory you would like that project to be copied into)! Git client will refuse to proceed otherwise, during the setup/cloning stage.

STEP 2: Run Git GUI and select Create New Repository option:

Git Basics 02 Create New Repository

Git Basics 02 Create New Repository

STEP 3: Set Directory for New Repository Path to Created Empty Folder in previous step:

Git Basics 03 Set New Repository Path To Created Empty Folder

Git Basics 03 Set New Repository Path To Created Empty Folder

STEP 4-1: Git New Project Window will look like this:

Git Basics 04 New Project Window (Part 1)

Git Basics 04 New Project Window (Part 1)

STEP 4-2: You will frequently access Visualize master’s History option from the Repository menu, and since we have a blank new project — let’s see what will happen when we try it:

Git Basics 04 New Project Window (Part 2) - Visualize Master's History

Git Basics 04 New Project Window (Part 2) – Visualize Master’s History

STEP 4-3: … and here comes our first error:

Git Basics 04 New Project Window (Part 3) - Visualize Master's History Error

Git Basics 04 New Project Window (Part 3) – Visualize Master’s History Error

Thing is our project has no commits yet (commit is simply a “change” or series of changes to our files/project) and this function does not work yet.

STEP 5: Let’s go back to our project’s directory and see what happen there in the meantime:

Git Basics 05 Project Hidden .git Folder Created

Git Basics 05 Project Hidden .git Folder Created

We can see that Git created a special hidden .git folder that contains some system files. This is the actual structure that contains all the tracking info of our changes, git project database and stuff. If you delete this directory — your Git project will be dead. So, don’t unless you really want it to.

STEP 6: Let’s create our first empty file in our project — we code in PHP, so the first file will be called index.php

Git Basics 06 Create Empty PHP File

Git Basics 06 Create Empty PHP File

STEP 7: Now, go back to Git GUI window and press Rescan button to scan project’s folder for any changes:

Git Basics 07 Rescan Project Folder For Changes

Git Basics 07 Rescan Project Folder For Changes

This step is necessary each time you make a change to your files/project.

STEP 8: Once the Rescan task is completed (usually lasts couple of nanoseconds), you will see a message window like this:

Git Basics 08 Rescan Completed - Check Changed File Status

Git Basics 08 Rescan Completed – Check Changed File Status

On the upper left side is the small window that contains a list of changed files — you may click on each to see the status of the tracking. For our index.php file the status is:

Untracked, not staged

What does this mean?

Untracked means that Git is not aware of this file and any change you made before and you may make in the future will NOT be recorded in Git’s project database. Remember, all the fuss about SVN/RCS/VCS is to record/track any file changes that we create during development phase (and then some more).

Not staged means that Git is not prepared this file for commit yet (that is, it will not be added to the project’s database at all — it is not even “elected” for commit yet, let alone be actually merged into project’s tracking history). Every change you make needs 2 steps-process to be added/tracked/recorded into Git:

(1) stage/staging phase and (2) commit phase

Stage is just a yellow traffic light here saying: “This file will be added once the Commit button is pressed, but not before that. You are now just in a ready & wait state.”

For all practical purposes, think about “STAGE” command as a safe-guard and protection for yourself, if you accidentally add something into commit pipeline that it should not be there in the first place.

STEP 9-1: OK, lets perform those staging and commits, then: Stage New Changes (Part 1)

Git Basics 09 Stage New Changes (Part 1)

Git Basics 09 Stage New Changes (Part 1)

STEP 9-2: Stage New Changes (Part 2)

Git Basics 09 Stage New Changes (Part 2)

Git Basics 09 Stage New Changes (Part 2)

As we can see above, Git has detected a new file that we created (upper right window field) and in the lower left smaller window Staged Changes (Will Commit) title is enlisted our index.php file. So far – so good!

NOTE:

At this point you will probably (maybe – maybe not) trigger a warning message like this:

Updating the Git index failed. A rescan will be automatically started to resynchronize git-gui.

warning: LF will be replaced by CRLF in /path/to/file.
The file will have its original line endings in your working directory.

My thought is that this is happening because of Windows/Unix differences between line ends styles, Notepad++ Editor and the default installation setup you picked when you installed Git for Windows. In any case, select “Unlock Index” and it should replace them, or “Continue” to avoid EOL conversion process. Read here for more details.

STEP 10: Now we finally need to apply our changes and record them – via Commit command:

Git Basics 10 Commit New Changes To Project (Part 1)

Git Basics 10 Commit New Changes To Project (1)

Once you press on Commit button, we will receive an error stating: “Please supply a commit message.” This is actually a good thing, it forces us to input at least some short description about what we are doing and the changes we have made:

Git Basics 10 Commit New Changes To Project (Part 2)

Git Basics 10 Commit New Changes To Project (2)

Try to be concise and creative here:

Git Basics 10 Commit New Changes To Project (Part 3)

Git Basics 10 Commit New Changes To Project (3)

After a successful commit you will see a small notification about it in the lower status bar — and that’s it. As if nothing big just happened!

Git Basics 10 Commit New Changes To Project (Part 4)

Git Basics 10 Commit New Changes To Project (4)

STEP 11: Time for some fancy stuff. Let’s go back to our Visualize master’s History command that did not work before and check if it will be the same this time:

Git Basics 11 Project Visualize Master's History (Part 1)

Git Basics 11 Project Visualize Master’s History (1)

It works! Now, we have officially made our first commit in our private, super-cool, top-secret project :)

Git Basics 11 Project Visualize Master's History (Part 2)

Git Basics 11 Project Visualize Master’s History (2)

And not just it looks great, but we can easily scroll to all our changes that we’ve made with recorded date and time, our contact information and so on (obviously, we’ve removed our email address from above screenshot for privacy reasons).

STEP 12: We will return to our index.php file once again and make some changes inside it. We will use Notepad++ text/code editor for this task (free/open-source/portable/great). Essentially, we will summarize steps 6-10 once again.

Git Basics 12 Edit Existing PHP File (Part 1) Modify Your Files

Git Basics 12 Edit Existing PHP File (Part 1) Modify Your Files

Git Basics 12 Edit Existing PHP File (Part 1) Modify Your Files

Git Basics 12 Edit Existing PHP File (Part 2) Rescan New Changes

Git Basics 12 Edit Existing PHP File (Part 2) Rescan New Changes

Git Basics 12 Edit Existing PHP File (Part 2) Rescan New Changes

Git Basics 12 Edit Existing PHP File (Part 3) Stage New Changes

Git Basics 12 Edit Existing PHP File (Part 3) Stage New Changes

Git Basics 12 Edit Existing PHP File (Part 3) Stage New Changes

Git Basics 12 Edit Existing PHP File (Part 4) Commit New Changes

Git Basics 12 Edit Existing PHP File (Part 4) Commit New Changes

Git Basics 12 Edit Existing PHP File (Part 4) Commit New Changes

Git Basics 12 Edit Existing PHP File (Part 5) Do Not Forget Commit Description Message

Git Basics 12 Edit Existing PHP File (Part 5) Do Not Forget Commit Description Message

Git Basics 12 Edit Existing PHP File (Part 5) Do Not Forget Commit Description Message

Git Basics 12 Edit Existing PHP File (Part 6) Do Not Forget Commit Description Message (cont.)

Git Basics 12 Edit Existing PHP File (Part 6) Do Not Forget Commit Description Message

Git Basics 12 Edit Existing PHP File (Part 6) Do Not Forget Commit Description Message

Git Basics 12 Edit Existing PHP File (Part 7) Visualize Master Branch History

Git Basics 12 Edit Existing PHP File (Part 7) Visualize Master Branch History

Git Basics 12 Edit Existing PHP File (Part 7) Visualize Master Branch History

Notice that changes are nicely colored: plus (+) sign at the beginning of the line means that the code was added (it is new) and it is in green, and the deleted or removed code starts with minus (-) sign at the beginning of each line and it is in red. Simple and effective! Blue lines represents internal Git’s comments with no changes.

ADVANCED TIPS: GIT SUBPROJECT MODULE

Of course, this is just the beginning and a tip of the iceberg. There are few more tricks inside Git for Windows GUI that you will master over time, but this is a good start. For example, say, in our project we wish to add another subproject (a 3rd party plugin, library, extension, module or whatever code not created by ourselves). IF that author also uses Git for tracking (and probability for that is extremely high nowadays), you may find a hidden .git file once you unpack that code you’d like to embed:

Git Basics 13 Advanced Tips (Part 1) Adding SubProject Module To Existing Project

Git Basics 13 Advanced Tips (Part 1) Adding SubProject Module To Existing Project

The “subproject_module” directory name is just for educational purposes only, it may be a wordpress site, a plugin or whatever you need. And inside it we also discover a .git file that was NOT created by our Git app.

Git Basics 13 Advanced Tips (Part 2) Adding SubProject Module To Existing Project

Git Basics 13 Advanced Tips (Part 2) Adding SubProject Module To Existing Project

As we can see in our next screenshot, staging and committing a subdirectory that also contains a “3rd party” .git subfolder will be treated as a “subproject” in this case (another Git technical term that you need to learn) and you may Rescan, Stage and Commit as much as you want, but it will always return Modified, not staged message with subproject module list:

Git Basics 13 Advanced Tips (Part 3) Submodule Project Contains Untracked Content Issue

Git Basics 13 Advanced Tips (Part 3) Submodule Project Contains Untracked Content Issue

The solution for this issue is to simply remove / delete .gitignore file and/or entire .git folder from your subdirectory (sometimes it may be hidden in sub-sub-subdirectory that you should be aware of, so pay attention what you are adding!):

Git Basics 13 Advanced Tips (Part 4) Delete .git Folder From Submodule Project

Git Basics 13 Advanced Tips (Part 4) Delete .git Folder From Submodule Project

CONCLUSION

This is the end of our basic Git for Windows Tutorial. Hope you learned something about Git, but keep in mind this is just a beginning. There are other topics you should learn about: how to create a remote repository (for example, hosted on GitHub, GitLab, BitBucket etc.) and sync with your local files. Learn about branches and merge between them, FETCH and PUSH commands and so on.

Git for Windows is one of the simplest GUI tools that are built around Git version control protocol, but it covers all the basics and then some more. Git BASH is a command line terminal that can do so much more than the GUI version, but that’s left for some other tutorial.

Понравилась статья? Поделить с друзьями:
  • Работа с двумя мониторами windows 10 горячие клавиши
  • Путь к загрузчику windows system32 winload exe
  • Работа с ftp сервером на windows
  • Работа с виртуальными рабочими столами windows 10
  • Путь к загрузчику windows system32 winload efi