---
metadata:
  - name: generator
    content: Diplodoc Platform v5.55.2
alternate:
  - https://sourcecraft.dev/portal/docs/en/sourcecraft/tutorials/quickstart-git.md
  - https://sourcecraft.dev/portal/docs/ru/sourcecraft/tutorials/quickstart-git.md
  - href: en/sourcecraft/tutorials/quickstart-git.md
    type: text/markdown
    title: Markdown version
  - href: ../../llms.txt
    type: text/markdown
    title: llms.txt
---
> **Documentation Index:** Fetch the complete configuration index at https://sourcecraft.dev/portal/docs/en/llms.txt

# Getting started with Git

[Git](https://git-scm.com/) is a distributed version control system that enables developers to track code changes, collaborate in teams, and manage project history. In Git, you can store different file versions, access them when needed, and work together on a project with no risk of data loss.

Git streamlines complex project work, delivers transparency of changes, and helps avoid teamwork conflicts.

In this tutorial, we will explore the main commands for using Git without the GUI.

1. [Getting started](#before-you-begin).
1. [Working with repositories](#repo).
1. [Working with branches](#branches).
1. [Commits](#commits).
1. [Pushing changes](#push).
1. [Conflict resolution](#conflicts).
1. [Additional commands](#additional-commands).

## Getting started {#before-you-begin}

Install Git:

{% list tabs group=instructions %}

- Windows {#windows}

  1. Download Git from the [official website](https://git-scm.com/downloads).
  1. Run the installation file and follow the setup wizard's prompts.
  1. During the installation, select to integrate with the command line or PowerShell.

- Linux {#linux}
  
  In the terminal, run this command:

  ```bash
  sudo apt update && \
  sudo apt install git
  ```

  {% note info %}

  If you are using a distribution other than Ubuntu or Debian, install Git using your package manager.

  {% endnote %}

- macOS {#macos}

  1. Install [Homebrew](https://brew.sh/) by running the following command in the terminal:
  
      ```bash
      /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
      ```

  1. Install Git:
  
      ```bash
      brew update && \
      brew install git
      ```

{% endlist %}

## Working with repositories {#repo}

### Initializing a repository (git init) {#new-repo}

_Initialization_ allows Git to index files and start tracking changes in a directory. 

1. Create a directory for your project by running this command in the terminal:
  
    ```bash
    mkdir <path_to_directory>
    ```

    If you need to initialize a repository in an existing directory, skip this step.

1. Navigate to the project directory:

    ```bash
    cd <path_to_directory>
    ```

1. To initialize the repository, run this command:

    ```bash
    git init
    ```

This will create Git files in the current directory for Git to treat it as a repository.

{% note tip %}

You can also [create](https://sourcecraft.dev/portal/docs/en/sourcecraft/operations/repo-create.md) a repository in SourceCraft and [clone](#clone-repo) an initialized repository.

{% endnote %}

### Cloning an existing repository (git clone) {#clone-repo}

To clone an existing repository, run this command:

```bash
git clone <repository_link>
```

This will create a local copy of the remote repository on your computer.

<!-- source: en/_includes/sourcecraft/private-repo-clone-note.md -->
{% note warning %}

To clone a [private or internal repository](https://sourcecraft.dev/portal/docs/en/sourcecraft/concepts/index.md#repos), authenticate with a [personal access token (PAT)](https://sourcecraft.dev/portal/docs/en/sourcecraft/security/pat.md) or [SSH key](https://sourcecraft.dev/portal/docs/en/sourcecraft/security/ssh.md).

{% endnote %}
<!-- endsource: en/_includes/sourcecraft/private-repo-clone-note.md -->

### Updating a local copy of a repository (git fetch and git pull) {#fetch-repo}

To fetch changes from a remote repository, run this command:

```bash
git fetch
```

This will fetch changes into Git’s internal storage; they will be available in remote branches, such as `origin/main`, while your local branches remain unchanged.

To merge these changes into your current branch, run the following command:

```bash
git pull
```

## Working with branches {#branches}

_Repository branches_ are separate project copies that enable working on changes independently, without affecting the main version. Branches can be either local or remote. Local branches reside on your computer, while remote branches are hosted on the server and are typically used for team collaboration.

### Main branch {#main-branch}

In most projects, this branch is referred to as `main` or `master`. Typically, it stores the stable project version ready for release or deployment. When making changes, avoid pushing them directly to the main branch; instead, create separate branches for new features or bug fixes.

To view all local branches, run the following command:

```bash
git branch
```

The current branch will be marked with `*`.

{% note tip %}

Also, you can view all repository branches in the SourceCraft interface. To do this, under ![image](../../_assets/console-icons/code.svg) **Code** on the repository page, go to ![image](../../_assets/console-icons/code-trunk.svg) **Branches**.

{% endnote %}

### Creating a new branch (git branch) {#new-branch}

You can use the `git branch` command to create an independent copy of your current repository branch and work on changes without affecting the main line of development. Before you start, always run `git pull` to make sure your branch and its data are up to date.

To create a new branch, run this command:

```bash
git branch <branch_name>
```

To create a new branch and switch to it right away, run this command:

```bash
git checkout -b <branch_name>
```

### Switching between branches (git checkout) {#switch-branch}

To switch to another branch, run the following command:

```bash
git checkout <branch_name>
``` 

### Merging branches (git merge) {#merge-branch}

Merging is used to integrate changes from one branch into another, e.g., to update the main branch with fixes or new features. When performing a merge, you join the selected branches into a single unified branch, which will incorporate all the changes. 

Once you finish working on a branch, run the following commands one by one to merge it into the main branch:

1. Switch to the target branch, e.g., `main`:
   
    ```bash
    git checkout main
    ```

1. Perform the merge:

    ```bash
    git merge <name_of_branch_with_changes>
    ```

If there are any merge conflicts, you need to [resolve](#conflicts) them manually.

After a successful merge, the merging branch is typically not deleted automatically and requires manual [deletion](#delete-branch).

{% note tip %}

SourceCraft supports [pull requests](https://sourcecraft.dev/portal/docs/en/sourcecraft/concepts/index.md#pr) to make sure branches are merged safely after a change review and automated checks. For more information, see [Creating a pull request in a SourceCraft repository](https://sourcecraft.dev/portal/docs/en/sourcecraft/operations/pr-create.md).

{% endnote %}

### Deleting a branch (git branch -d) {#delete-branch}

If you no longer need a branch, run the following command to delete it:

```bash
git branch -d <branch_name>
```

If your branch contains uncommitted changes that may be lost upon deletion, the command will return an error. To view the current uncommitted changes, run this command:

```bash
git status
```

The command output will show files with changes that have not been staged for commit.

To forcibly delete a branch, run the following command:

```bash
git branch -D <branch_name>
```

{% note warning %}

When you forcibly delete a branch, any uncommitted changes will be lost. Make sure nothing important is left unsaved.

{% endnote %}

### Additional actions with branches {#additional-actions}

To push a branch to the server, run this command:

```bash
git push origin <branch_name>
```

This command will push your local branch to the remote repository, making it available to other contributors.

To view all branches in your repository, run the following command:

```bash
git branch -a
```

You will get a list of all branches in your repository, including those stored on the server.

To restore a previously deleted branch, run this command:

```bash
git checkout -b <new_branch_name> <deleted_branch_name>
```

This will create a new branch based the deleted one, allowing you to restore data that was lost or deleted by mistake.

## Commits {#commits}

After saving changes in the repository files, you need to stage them to be committed.

_Commits_ are snapshots of your files at a specific point in time. They enable you to track the change history and roll back to the versions you need.

{% note tip %}

Commit your changes regularly, even minor ones.

{% endnote %}

### Staging changes for a commit (git add) {#add-commit}

1. View the unstaged changes:

    ```bash
    git status
    ```

1. Stage the changes for the commit using one of the following methods:
    * Stage the changes in a specific file:
  
      ```bash
      git add <file_name>
      ```

    * Stage all modified files in the current directory:

      ```bash
      git add .
      ```

    * Stage all modified files in the repository:

      ```bash
      git add --all
      ```

### Creating a commit with a message (git commit) {#commit-with-desc}

To create a commit with a message describing the changes, run the following command:

```bash
git commit -m "Commit message"
```

{% note tip %}

Keep your commit messages short for easier navigation.

{% endnote %}

### Modifying the last commit (git commit --amend -m) {#change-commit}

To modify your most recent commit, e.g., to edit the commit message, run this command:

```bash
git commit --amend -m "Updated commit message"
```

### Squashing commits (git rebase) {#squash-commits}

Squashing the last few commits makes the history more readable and groups related changes together.

To achieve this, use interactive rebasing (`git rebase -i`) that enables you to select commits for squashing or change their order and contents.

To start rebasing, run this command:

```bash
git rebase -i HEAD~N
```

Where `N` is the number of most recent commits to process.

This will open the editor with the list of selected commits. To squash the most recent commits with the older ones, replace `pick` with `squash` or `s`.

{% note info %}

Rebasing may cause commit conflicts; you will need to [resolve](#conflicts) them manually and then run this command to proceed with the rebase:

```bash
git rebase --continue
```

{% endnote %}

#### Example of squashing commits {#squash-example}

Here is an example of the `git rebase -i HEAD~3` command output in the editor:

```text
pick e3a1b35 Correcting a typo
pick 7ac9a67 Adding a new feature
pick 4f5d6e2 Updating documentation
```

To squash the last three commits into one, replace `pick` with `squash` (or `s`) for the second and third commits.

```text
pick e3a1b35 Correcting a typo
squash 7ac9a67 Adding a new feature
squash 4f5d6e2 Updating documentation
```

Once done, save the file and close the editor. The selected commits will now be squashed.

### Deleting commits (git reset) {#delete-commits}

To delete the most recent commit, run this command:

```bash
git reset --hard HEAD~1
```

To delete the few most recent commits, run this command:

```bash
git reset --hard HEAD~N
```

Where `N` is the number of recent commits to delete.

This will fully delete all changes related to the selected commits from the current branch. 

{% note warning %}

Be careful when using `git reset`. You may lose important changes that have not been committed in other branches or saved elsewhere.

{% endnote %}

### Restoring a commit (git cherry-pick) {#backup-commit}

To restore a previously deleted commit, you will need its hash (SHA).

A _commit hash_ is a unique short code automatically created for every committed change in the project.

{% note info %}

You can only restore a commit that is still in the repository history. If deleted completely, e.g., with `git push --force`, the commit cannot be restored.

{% endnote %}

1. To find the commit you need, check the reference log by running the following command:
  
    ```bash
    git reflog
    ```
  
    Command output example:
  
    ```bash
    abc1234 (HEAD -> master) HEAD@{0}: reset --hard HEAD~1
    def5678 (branch: master) HEAD@{1}: commit: Added a description
    ghi9012 HEAD@{2}: commit: Fixed a bug
    ```

    Where:
    * `def5678`: Commit hash.
    * `commit: Added a description`: Commit message.

1. In the command output, find the commit you need by its message.
1. Copy its hash. Normally, this is the first seven to ten characters in the line.
1. Select a restore option:

    {% list tabs %}

    - To a new branch

      To create a new branch from a commit and switch to it immediately, run the following command:
  
      ```bash
      git checkout -b <new_branch_name> <commit_hash>
      ```
  
      Here is an example:
  
      ```bash
      git checkout -b restored-branch def5678
      ```
     
      While restoring, you may run into conflicts that require manual [resolution](#conflicts).
   
    - To the current branch

      The commit will be added to the current branch as the most recent one. The changes saved in it will be added to target branch history without affecting other current changes. While adding the commit, you may run into conflicts that require manual [resolution](#conflicts).
  
      To restore a commit to the current branch, run this command:
  
      ```bash
      git cherry-pick <commit_hash>
      ```

    - Reset the current branch to the commit’s state

      The deleted commit will be restored in the history. The branch will be reset to the commit’s state, discarding all later changes. Be careful, as all current unsaved changes will be lost.

      To reset a branch to the specified commit, run the following command:
  
      ```bash
      git reset --hard <commit_hash>
      ```

    {% endlist %}

### Viewing a commit (git show) {#look-commit}
  
You can view a commit independently of any branch. To view the commit contents directly in the terminal, run this command:
  
```bash
git show <commit_hash>
```
    
To exit the viewing mode, press `q`.
  
## Pushing changes {#push}

The _push_ command uploads changes from your computer to the server, allowing other contributors to see and use them.

{% note info %}

Attempting to send a large file to Git over HTTPS may cause errors. For more information, see [How to use git in SourceCraft](https://sourcecraft.dev/portal/docs/en/sourcecraft/qa/sourcecraft-git.md#large-file).

{% endnote %}

### Pushing changes (git push) {#send-push}

To push the current changes to a remote repository, run this command:

```bash
git push origin <branch_name_in_remote_repository>
```

### Undoing pushed changes (git reset and git push) {#cancel-push}

To undo your latest changes on the server and restore the branch to its previous state, follow these steps:

1. Reset the local branch to its pre-commit state. To do this, run the following command that deletes the last commit and restores the files to their previous state:

    ```bash
    git reset --hard HEAD^
    ```

1. Update the remote branch to match your local branch by running the force push command:

    ```bash
    git push --force
    ```
  
    Be careful: using `--force` may lead to data loss for other project contributors if they have already synced with the remote repository. Any changes they made after synchronization will also be lost. Before running this command, notify your team or make sure nobody will lose crucial data.

    {% note info %}

    If your changes are not yet committed, commit them first and then push to the remote repository.

    {% endnote %}

## Conflict resolution {#conflicts}

<!-- source: en/_includes/sourcecraft/git-conflicts.md -->
_Merge conflicts_ occur when [git](https://git-scm.com/) is unable to automatically merge changes from different branches. This happens when there are conflicting changes in the same places in the repository.

The causes of conflicts may include:
* Multiple users editing the same files at once.
* Pulling remote repository changes ([`git pull`](https://sourcecraft.dev/portal/docs/en/sourcecraft/tutorials/quickstart-git.md#fetch-repo)) that conflict with your local edits.
* Merging branches ([`git merge`](https://sourcecraft.dev/portal/docs/en/sourcecraft/tutorials/quickstart-git.md#merge-branch)) with conflicting changes made to the same lines of code.
* Pushing changes ([`git push`](https://sourcecraft.dev/portal/docs/en/sourcecraft/tutorials/quickstart-git.md#send-push)) to the remote repository that has commits conflicting with your local edits.

Types of conflicts:
* [Line update conflicts](#resolve-cli) are the most common type of conflict, which occurs when the same file line is updated differently in different branches.
* [File structure conflicts](#tree-conflicts) occur when one user updates a file and another user deletes it.

### What conflicts look like in files {#conflict-markers}

When `git` detects a conflict, it marks the problematic sections with special markers:

```text
Common part of the text before the conflict
<<<<<<< HEAD
Changes in the current branch
=======
Changes in the incoming branch
>>>>>>> branch-name
```

Where:
* `<<<<<<< HEAD` marks the beginning of changes in the current branch.
* `=======` is the separator between versions.
* `>>>>>>> branch-name` marks the end of changes in the incoming branch.

### Conflict resolution {#resolve}

{% list tabs group=instructions %}

- SourceCraft UI {#src}

  <iframe width="640" height="360" src="https://runtime.strm.yandex.ru/player/video/vplvor2l7ieyypvhqrjh?autoplay=0&mute=0" allow="autoplay; fullscreen; picture-in-picture; encrypted-media" frameborder="0" scrolling="no"></iframe>

  {% note warning %}

  Resolving [file structure conflicts](#tree-conflicts) is not available in the SourceCraft interface. To resolve such conflicts, use the command line or [SourceCraft Spaces](https://sourcecraft.dev/portal/docs/en/sourcecraft/concepts/spaces.md).

  {% endnote %}

  1. Open the [SourceCraft home page](https://sourcecraft.dev).
  1. On the ![image](../../_assets/console-icons/house.svg) **Home** tab, under ![image](../../_assets/console-icons/layout-tabs.svg) **Your craftspace**, navigate to ![image](../../_assets/console-icons/archive.svg) **Repositories**.
  1. Select a repository.
  1. Under ![image](../../_assets/console-icons/code.svg) **Code** on the repository page, go to ![image](../../_assets/console-icons/code-pull-request.svg) **Pull requests**.
  1. Select a pull request and click ![image](../../_assets/console-icons/code-pull-request.svg) **Merge** in the top-right corner.
  1. On the pull request page, review the conflict message, for example:

      ```text
      Merge blocked
      ...
      This branch has conflicts that must be resolved
      filename.js
      CONFLICT (content): Automatic merge failed to resolve conflict in filename.js; Manual content merge required
      ```

  1. Click **Resolve in UI**.
  1. This will open a code editor, where the conflicting sections will be marked with specials markers:

      ```text
       1    ...
       2    Common part of the text before the conflict
       3    ...
            [Accept current change] [Accept incoming change] [Accept both changes]
       4    <<<<<<< main
       5    Changes in the current branch
       6    =======
       7    Changes in the incoming branch
       8    >>>>>>> feature-branch
       9    ...
      10    Common part of the text after the conflict
      11    ...
      ```

      Where:
      * `Accept current change`, `Accept incoming change`, and `Accept both changes` are buttons for resolving an individual conflict.
      * `<<<<<<< main` marks the beginning of changes in the current branch.
      * `=======` is the separator between versions.
      * `>>>>>>> feature-branch` marks the end of changes in the incoming branch.

  1. Resolve the conflicts:

      * To resolve an individual conflict, next to the section in question, click:
          * **Accept current change**: Accept the changes from the current branch.
          * **Accept incoming change**: Accept the changes from the incoming branch.
          * **Accept both changes**: Accept the changes from both branches.

      * To resolve all conflicts, at the top right, click:
          * **Accept current**: Accept all changes from the current branch.
          * **Accept incoming**: Accept all changes from the incoming branch.

          {% note warning %}

          In this case, all changes will be merged even if you previously resolved individual conflicts differently.

          {% endnote %}

  1. Click **Mark as resolved** and **Commit changes**.

- Command line {#cli}

  1. Identify the files with conflicts by executing this command:

      ```bash
      git status
      ```

      Files with conflicts will be displayed marked with `both modified`.
  1. Open the file with the conflict in the text editor.
  1. Locate the conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`).
  1. Choose the conflict resolution option:
      * Delete the version you do not need.
      * Create new code to merge both versions.

      After the changes are introduced, remove all conflict markers.
  1. Save the file.
  1. Add the updated file into the index:

      ```bash
      git add <file_name>
      ```

  1. Finish the merge:

      ```bash
      git commit -m "Resolve merge conflict"
      ```

  1. Push the changes:
      
      ```bash
      git push
      ```

{% endlist %}

### File structure conflicts {#tree-conflicts}

To resolve a conflict when a file was updated in one branch and deleted in another:
1. Check the conflict status:

    ```bash
    git status
    ```

1. Choose the next action with the file:
    * To keep the file, run this command:

      ```bash
      git add <file_name>
      ```

    * To delete the file, run this command:

      ```bash
      git rm <file_name>
      ```

1. Finish the merge:

    ```bash
    git commit -m "Resolve file deletion conflict"
    ```

### Using merge tools {#merge-tools}

You can use graphical tools for convenient conflict resolution.
To start the configured merge tool, such as VS Code, Sublime Merge, or others, run this command:

```bash
git mergetool
```

### Aborting the merge {#abort-merge}

To abort the merge and revert to the state before the operation started, run this command:

```bash
git merge --abort
```
<!-- endsource: en/_includes/sourcecraft/git-conflicts.md -->

For more on resolving merge conflicts, see [here](https://sourcecraft.dev/portal/docs/en/sourcecraft/operations/resolve-merge-conflicts.md).

## Additional commands {#additional-commands}

| Command | Use case |
| ------- | ------------------ |
| `git log` | Viewing history. |
| `git blame <file_name>` | Viewing changes in a specific file. This command shows who made the changes and in which lines. |
| `git blame -L <start_line>,`<br>`<end_line> <file_name>` | Viewing changes within a given line range in the selected file. |
| `git branch` | Viewing all repository branches. The current branch will be marked with `*`. |
| `git checkout -- <file>` | Undoing file changes. This command resets the file to its last committed state. |
| `git diff` | Viewing differences between your local unpushed changes and the latest branch version. |
| `git diff <branch_name>` | Viewing differences between your local unpushed changes and the latest version of another branch |
| `git gc` | Optimizing the local repository by freeing up disk space and deleting orphaned or lost data which remains in the repository but is no longer used by current branches. |
| `git tag` | Creating tags to mark important milestones in the project history, such as releases. |
| `git remote add <repository_name>`<br>`<repository_link>` | Connecting your local repository to the remote one to push changes and pull updates. |
| `git remote -v` | Viewing all remote repositories for the project. |
| `git stash` | Stashing changes. |
| `git stash pop` | Restoring stashed changes. |
| `git reflog` | Listing all changes in the Git logs. By default, the list of `HEAD` changes is displayed. |

### Useful links {#see-also}

* [Git reference](https://git-scm.com/docs)
* [Getting started with SourceCraft](https://sourcecraft.dev/portal/docs/en/sourcecraft/quickstart.md)
* [SourceCraft resource relationships](https://sourcecraft.dev/portal/docs/en/sourcecraft/concepts/index.md)
