Sign In
Sign In

How to Install and Use Gitea

How to Install and Use Gitea
Hostman Team
Technical writer
Git
28.06.2024
Reading time: 13 min

Gitea is a lightweight and accessible version control system based on Git, designed for ease and efficiency for both individual users and teams. The platform is open source, making it freely available for use and modification. The main advantage of Gitea is that it can be deployed on a user's private server, ensuring complete control over data and configuration.

Gitea offers all the essential Git features, such as branching, merging, and tagging, as well as additional project management conveniences, including a task tracking system, wiki pages, and code review tools. This makes it an ideal solution for development teams who want to collaborate on projects in an isolated and secure environment.

As more organizations and individuals recognize the importance of digital security and autonomy, Gitea stands out as a reliable and convenient solution for self-managing data and projects. An active community and extensive documentation further simplify the adoption and use of this system in various contexts.

Version control systems are traditionally associated with software development, but their potential applications are much broader. For non-programmers, they can become powerful tools for solving diverse data management and project coordination tasks.

One prominent example is using Gitea for synchronizing notes. For instance, users of note-taking applications like Obsidian can use Gitea to version their notes. This allows tracking changes, reverting to previous versions, and even collaborating on notes with other users.

Another common scenario is using Gitea as a tool for synchronizing and versioning passwords with a password manager like Pass. This approach increases password management security by providing change history, synchronization between devices, and the ability to restore previous states.

System administrators and Linux enthusiasts will also find Gitea particularly useful. For them, the system can serve as a reliable repository for system and application configuration files. In case of need, it's easy to track changes made to configuration files and, if necessary, revert to an earlier version. This is especially important when changes to the configuration can affect system stability.

Additionally, Gitea can serve to manage content and project documentation. For example, organizations can use built-in wikis to create and store technical manuals, instructions, and other documents, which is especially useful in conditions of frequent changes and the need to provide access to current information.

Gitea is supported by an active community of developers and users who regularly update and supplement the documentation, making the system accessible to both beginners and professionals. Users can seek help through GitHub, specialized forums, and chats where they can ask questions, share experiences, or find solutions to specific problems. This ensures reliable support and constant platform development.

Alternatives and When to Choose Gitea

Choosing the right version control system depends on the specific needs of the project or organization. Gitea stands out among similar systems due to its lightness and minimal resource requirements, making it ideal for small teams or individual developers who need a simple and effective tool without complex infrastructure.

Unlike GitHub, which is a popular commercial platform, Gitea provides full control over your data since it can be deployed in your own infrastructure. This can be critically important for organizations requiring strict adherence to privacy and security policies.

GitLab, while offering extensive CI/CD capabilities, requires significantly more resources for its operation and has a complex structure, which may be excessive for small projects. Moreover, not all GitLab features are available in the free version, which can also influence the choice in favor of more accessible solutions.

Thus, if your goal is to ensure ease of management, minimize infrastructure costs, and maintain full control over the system and data, Gitea is an excellent choice.

Installation Process

Before installing Gitea itself, we will perform a series of preparatory steps.

We will use a cloud server and install Gitea on Ubuntu 22.04, but it should be noted that the Gitea installation process in other Linux distributions is not significantly different.

Creating a Cloud Server

Go to the Hostman control panel and click Create server in the Cloud Servers section. Choose Ubuntu 22.04 as the operating system. Select the region and the minimum available server configuration. Leave the default settings for the network: create a public IP and no private network.

For increased reliability, consider enabling the backup service. This service can be important if additional data redundancy is needed. We will look at the process of creating backups manually, but a full server backup can be useful for ensuring redundancy.

Specify the SSH key, set the server name, and complete the order by clicking the Order button.

After creating the server, connect to it via SSH and update the system with the following commands:

apt update
apt upgrade

These commands will update the system to the latest available package versions.

Setting Up the Database

Before starting the installation, it is necessary to prepare the database that will be used to store all information related to the version control system. We will use MariaDB, a popular database management system known for its performance and compatibility with MySQL.

Installing MariaDB

First, install MariaDB on your server with the command:

apt install mariadb-server

This command will install MariaDB along with all necessary dependencies.

Securing MariaDB

After installation, run the mysql_secure_installation script, which will help to configure security settings:

  • set a password for the root user,

  • remove anonymous users,

  • restrict remote database access,

  • remove the test database.

This will improve the security of your database server:

mysql_secure_installation

Follow the on-screen prompts to complete the setup.

Creating a User and Database

Next, log in to the MariaDB console and create a user and database that will be used by the system:

mysql -u root -p

After logging in, execute the following commands:

CREATE USER 'hostmangitea'@'%' IDENTIFIED BY 'secretpass';

This command creates a new database user. Here 'hostmangitea'@'%' specifies the username and the host from which they can connect. The % symbol means that the user can connect from any host. The part IDENTIFIED BY 'secretpass' sets the password for this user. It is important to choose a reliable and secure password.

CREATE DATABASE giteadb CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_unicode_ci';

This command creates a new database named giteadb. It also specifies that the database will use UTF-8 for storing characters, which is suitable for texts in any language.

GRANT ALL PRIVILEGES ON giteadb.* TO 'hostmangitea';

This command grants the hostmangitea user all rights to work with the giteadb database. This includes read, write, and modify data rights, which are necessary for the full operation of the application.

FLUSH PRIVILEGES;

This command applies all privilege changes made. It updates the privileges so that the new settings take effect immediately without restarting the server. To exit mysql, press CTRL+D.

Installing Gitea

To install Gitea on your server, follow these steps.

Download and Install the Executable File

Download the latest stable version of Gitea from the official website:

wget -O gitea https://dl.gitea.io/gitea/1.22.0/gitea-1.22.0-linux-amd64

You can see the list of all available versions on the Gitea website.

Make the downloaded file executable:

chmod +x gitea

Check the Installed Version of Git

Make sure Git is installed on your server, as it is necessary for Gitea to work:

git --version

Create a System User

Create a separate user under which Gitea will run:

adduser \
   --system \
   --shell /bin/bash \
   --gecos 'Git Version Control' \
   --group \
   --disabled-password \
   --home /home/git \
 git

Set Up Directory Structure

Create the necessary directories for storing data, configurations, and logs:

mkdir -p /var/lib/gitea/{custom,data,log}
chown -R git:git /var/lib/gitea/
chmod -R 750 /var/lib/gitea/
mkdir /etc/gitea
chown root:git /etc/gitea
chmod 770 /etc/gitea

Set the Working Directory and Copying the File

Set the environment variable for the working directory and copy the executable file to the system directory:

export GITEA_WORK_DIR=/var/lib/gitea/
cp gitea /usr/local/bin/gitea

Creating and Configuring the Service for systemd

Create a service file for systemd so that Gitea starts automatically on system startup:

nano /etc/systemd/system/gitea.service

Insert the following configuration file in the editor window:

[Unit]
Description=MyGitea
After=network.target
Wants=mariadb.service
After=mariadb.service

[Service]
RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea

[Install]
WantedBy=multi-user.target

Then enable and start the service:

systemctl enable gitea
systemctl start gitea

Check that the service is running:

systemctl status gitea

Completing the Installation via the Web Interface

Now you can go to the IP address of your server and open the setup page in a browser: http://<your_server_ip>:3000. You will be greeted by the installation wizard. At this stage, you will need to configure the database connection and create an administrator account.

Database Configuration

  1. In the Database Type field, select MySQL, corresponding to your database type.

  2. In the Host field, leave the default value.

  3. Enter the database username in the Username field — in your case, it is hostmangitea.

  4. Enter the password you set when creating the database user in the Password field.

  5. In the Database Name field, specify the name of your database, which you set earlier, giteadb.

General Settings

In the General Settings section, you can leave the default values. These settings include path and base URL configurations, which can be changed later if necessary.

Creating an Administrator Account

In the Administrator Account Settings section, you need to create an administrator account by specifying the desired username, password, and contact email. This account will be used to log in to the system and manage Gitea.

Completing the Installation

After filling in all the necessary information, click the Install Gitea button. The installation process will begin, and after completion, you will be able to log into the system using the created administrator account.

Setting Up Nginx and SSL for Your Domain

After installation, to ensure security and proper operation on your own domain, it is recommended to configure the Nginx web server and install an SSL certificate. This will protect the data and ensure encryption during transmission over the internet.

Installing and Configuring Nginx

Install Nginx on your server:

sudo apt install nginx

Create a configuration file for your domain in Nginx:

nano /etc/nginx/sites-available/hostmangitea.test.ru

Insert the following configuration, replacing hostmangitea.test.ru with your domain:

server {
    listen 80;
    server_name hostmangitea.test.ru;

    location / {
        client_max_body_size 512M;
        proxy_pass http://127.0.0.1:3000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        add_header Strict-Transport-Security "max-age=15552000; includeSubDomains" always;
    }
}

Activate the new configuration by creating a symbolic link in the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/hostmangitea.test.ru /etc/nginx/sites-enabled/

Installing an SSL Certificate with Certbot

Install Certbot and its Nginx plugin:

sudo apt install certbot python3-certbot-nginx

Run Certbot to automatically install the SSL certificate for your domain:

certbot --non-interactive -m [email protected] --agree-tos --no-eff-email --nginx -d hostmangitea.test.ru

This command will issue and configure the SSL certificate, automatically updating the Nginx configuration to use HTTPS. In the command, change [email protected] to your email and hostmangitea.test.ru to your domain.

Restart Nginx to apply the changes:

sudo systemctl restart nginx

Now, the service is available over a secure HTTPS connection on your domain.

Additionally, you can edit the /etc/gitea/app.ini configuration file to set up the domain and access level. In the [server] section of the configuration file, change the values of SSH_DOMAIN, DOMAIN, and ROOT_URL to your domain instead of the IP address. This will correctly display links in your version control system.

In the [service] section of the /etc/gitea/app.ini file, you can set the DISABLE_REGISTRATION parameter to true to disable new user registrations. This will increase the security of your system by restricting access to selected users only.

To apply the changes, restart the service with the command:

sudo systemctl restart gitea

Security and Backup

To ensure the security of your data, configure a firewall on the server and set up a backup system.

Configuring the UFW Firewall

Properly configuring the firewall is important for securing your server. Using ufw (Uncomplicated Firewall), you can easily manage access to various ports and services. Below are the basic steps for configuring ufw:

Reset the current firewall settings:

sudo ufw reset

Deny incoming connections by default and allow outgoing:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow access to standard web ports and SSH:

sudo ufw allow 80
sudo ufw allow 443
sudo ufw allow 22

Deny access to your git server on ip:3000 for external connections:

sudo ufw allow from 127.0.0.1 to any port 3000
sudo ufw deny 3000

Activate and check the status of the firewall:

sudo ufw enable
sudo ufw status

Creating a Backup

Regular backups are a key aspect of maintaining data security. For Gitea, the backup process can be done as follows:

Switch to the user under which Gitea runs:

su git

Go to the directory where the backup will be created (e.g., /home/git):

cd /home/git

Run the command to create a data dump:

/usr/local/bin/gitea dump -c /etc/gitea/app.ini

This command will create an archive with the backup, including the database, configuration files, repositories, and other important data.

The created archive will contain important components such as:

  • app.ini — configuration file (if it was outside the standard custom/ folder),

  • custom/ — all custom settings if used,

  • data/ — application data including attachments and avatars,

  • repos/ — full copy of the repository directory,

  • gitea-db.sql — database dump,

  • log/ — various logs, although they are not essential for recovery.

Restoring from a Backup

To restore data from a backup, follow these steps:

Unzip the backup archive:

unzip gitea-dump-id.zip

Go to the directory with the extracted data:

cd gitea-dump-id

Now restore the main components. Configuration files:

mv app.ini /etc/gitea/conf/app.ini

Application data:

mv data/* /var/lib/gitea/data/

Logs:

mv log/* /var/lib/gitea/log/

Repositories:

mv repos/* /var/lib/gitea/gitea-repositories/

Update permissions:

chown -R gitea:gitea /etc/gitea/conf/app.ini /var/lib/gitea

Import the database dump into MySQL:

mysql --default-character-set=utf8mb4 -u$USER -p$PASS $DATABASE < gitea-db.sql

Replace $USER, $PASS, and $DATABASE with the username, password, and database name respectively.

These steps will allow you to restore all necessary information and data on your server after a failure or transfer to a new server.

Conclusion

In this article, we thoroughly reviewed the process of installing Gitea on your server as well as configuring it, starting from the basic installation, going through security and backup configuration, and ending with integration with external services for application deployment. Now you have the knowledge on how to effectively use version control systems to manage your code versions and automate development. The platform provides a reliable and scalable foundation, allowing you to significantly increase development productivity and enhance control over project changes.

Git
28.06.2024
Reading time: 13 min

Similar

Git

Git Fetch vs. Git Pull

In most cases, working with the Git version control system is done locally. However, you sometimes need to sync with a remote repository to update your local storage. Git provides two key commands for this: git fetch and git pull. A remote repository is a storage location hosted on the network, usually on platforms like GitHub, GitLab, or Bitbucket. These services allow developers to collaborate on projects, make changes, and synchronize code between local and remote versions. Both commands are used to download updates from a remote repository, but they work differently. In this guide, we will explore their practical applications and highlight their key differences. Prerequisites Since this article covers practical usage, you’ll need the following: A server, virtual machine, or computer with any operating system where Git can be installed. A Git client pre-installed. An account on GitHub. The git fetch Command Let’s start with what git fetch does. git fetch is used to grab the latest data from a remote repository and put it into your local storage without modifying any files in your working directory. Instead, it updates the so-called remote-tracking branches, which reflect the state of the remote repository at the time the command is executed. This is how git fetch works: Establishes a connection with the remote repository. Downloads new commits, files, branches, and tags. The data is added to the local repository but not merged with the current working branch. Basic syntax of git fetch: git fetch <remote-repository-url> Useful options: git fetch --all — Downloads updates from all remote repositories linked to the local storage. git fetch --dry-run — Checks for changes before downloading without making any actual changes. git fetch --force — Forcefully updates data in the local repository, overwriting any conflicts. git fetch --tags — Downloads all tags from the remote repository. git fetch --prune — Removes references to branches that were deleted in the remote repository. The git pull Command Unlike git fetch, the git pull command downloads the latest changes from a remote repository and automatically merges them into your current local branch. Essentially, executing git pull involves two operations: git fetch — Downloads new data. git merge — Merges the downloaded changes with the local branch. This is how git pull works: Establishes a connection with the remote repository. Downloads the latest data, including commits, files, tags, and branches. The downloaded changes are merged into the current local branch. Basic syntax of git pull: git pull Useful options: git pull [remote-repository] [branch] — Downloads changes only from the specified repository and branch. For example, git pull origin main updates the local main branch from the remote repository origin. git pull --rebase — Instead of performing a standard merge, this applies the changes on top of the local commits, helping to avoid unnecessary merge commits. Comparison: git fetch vs git pull To better understand the differences between these two commands, here's a comparison table: Criterion git fetch git pull Action Only downloads changes Downloads and merges changes Impact on Local Repository Does not modify files or branches Modifies the current branch and files Safety Safe, as it does not cause conflicts May cause conflicts during merging Previewing Changes Allows reviewing and analyzing changes before merging Automatically integrates changes without preview Flexibility Requires manual merging Merges automatically When to Use Git Fetch vs. Git Pull When to Use git fetch Before Making Changes to the Source Code: git fetch allows you to see which commits have been made on the remote branch and evaluate the changes before merging them into your local branch. When Working in a Team: If multiple developers are working on the project, git fetch helps you stay up-to-date with their work and minimize potential conflicts before integrating changes. To Retrieve New Branches and Tags: If a new branch or tag has been added to the remote repository, git fetch will download them without automatically switching to them. When to Use git pull To Get the Latest Changes: In team projects, members regularly make updates. To bring all the latest changes into your local repository, use git pull. For Quick Branch Updates: If you need to quickly update your branch without analyzing the changes beforehand, using git pull is the easiest approach. Using Git Fetch and Git Pull in Practice Creating a Repository on GitHub Log in to GitHub. If you don’t have an account, you can register a new one. Click on the New button to create a new repository. Provide a name for the repository and select the Public option. Click on your profile picture in the upper-right corner and select Settings from the drop-down menu. Scroll down to Developer settings on the left. Expand Personal access tokens and go to Tokens (classic). Click on Generate new token, then Generate new token (classic). If prompted, authenticate using the mobile app. Give the token a name and set an expiration date. Under permissions, select the repo category. Click on Generate token to create the token. Copy and save the token, as it won’t be shown again. Creating a Local Repository Go to the server where Git is installed. Create a new directory to store your files and navigate to it: mkdir test-git-fetch-pull && cd test-git-fetch-pull Initialize a new Git repository: git init Create a new file and add a line to it: echo "Test git fetch and pull commands!" > newfile1.txt Add the file to the staging area: git add newfile1.txt Create an initial commit: git commit -m "Initial commit" If you see the message: Author identity unknown*** Please tell me who you are You need to set your name and email using: git config --global user.email "[email protected]"git config --global user.name "<name>" Then, repeat the commit command: git commit -m "Initial commit" Add the remote repository. Use the command from the main page of your newly created repository on GitHub. For example: git remote add origin https://github.com/<github-account>/test-git-fetch-pull.git Push changes to the remote repository: git push -u origin main When prompted for Username for 'https://github.com', enter your GitHub username. When prompted for Password for 'https://<username>@github.com', enter the previously generated token. Go back to the GitHub web interface and check that the file is present in the repository. Working with Changes Now, let’s simulate changes in the remote repository. Open the file for editing directly in the GitHub interface. Add a new line at the end of the file. Click the Commit changes button on the right. Go back to the server where your local repository is located and run: git fetch origin Now, check the file content: cat newfile1.txt You'll notice that git fetch downloaded the changes from the remote repository, but the local branch (main) and the file remained unchanged. However, the changes can be seen in the remote branch: git log origin/main To see exactly what changes were made in the remote repository after running git fetch, use: git diff main origin/main Now, let's pull the changes into the local branch: git pull origin main Display the file content again: cat newfile1.txt Now, the changes made in the GitHub interface are applied to the local copy of the repository. Resolving Conflicts When Using git pull When using git pull, you may encounter conflicts. In Git terminology, a conflict occurs when the system cannot automatically merge changes from two different sources — the local and remote repositories. To learn how to resolve conflicts, let's go through a practical example. We'll simulate the following situation: We have a repository containing a file named future-file1.txt. Two developers (Developer 1 and Developer 2) are working on the same branch (main). Preparing the Repository Create a new repository in GitHub. Follow the same steps as in the previous chapter to create a new repository. On the server, create a new directory and navigate to it: mkdir git-conflicts && cd git-conflicts Initialize the Git repository: git init Create a new file: touch future-file1.txt Write the first line into the file: echo "First message" > future-file1.txt Stage the file: git add future-file1.txt Commit the changes: git commit -m "Initial commit" Connect the local repository to GitHub. Replace the URL with the one for your GitHub repository: git remote add origin https://github.com/<github-account>/git-conflicts.git Push changes to the remote repository: git push -u origin main You'll be prompted to enter your GitHub username and personal access token. Making Changes as Developer 2 Now, let's simulate the scenario from the perspective of the second developer (Developer 2). On another machine or in a new directory on the same server, run: git clone https://github.com/<github-account>/git-conflicts.git At this point, both developers have an up-to-date copy of the repository. Making Changes as Developer 1 Switch back to the local repository used by Developer 1: Add a new line by overwriting the content of future-file1.txt: echo "Second message" > future-file1.txt Stage the changes: git add future-file1.txt Commit the changes: git commit -m "Second commit" Push changes to the remote repository: git push origin main Conflict At this point, Developer 1's changes are in the remote repository. However, Developer 2 still has the old version of future-file1.txt. Navigate to the project folder that was previously cloned by Developer 2. Overwrite the file by adding a new message: echo "Third message" > future-file1.txt Stage the file: git add future-file1.txt Commit the changes: git commit -m "Third commit" Pull the latest changes from the remote repository: git pull origin main As you can see, Git has detected a conflict: When viewing the file, you will notice a conflict block in the file, marking the conflicting changes. Resolving the Conflict To resolve the conflict, you need to delete the lines starting with <<<<<<< and ending with >>>>>>>. Then, you can decide whether to keep only the local changes or to retain the old ones and add the new ones. As an example, let's keep the changes from both developers: Developer 1's message ("Second message") Developer 2's message ("Third message") After editing the file, stage it again: git add future-file1.txt Commit the resolved conflict: git commit -m "Resolved conflict" Push the changes to the remote repository: git push origin main You will need to enter your username and token to push the changes. Go to the GitHub interface and verify the result. Conclusion The git fetch and git pull commands are used to retrieve the latest changes from a remote repository into your local repository, but they do so differently. git fetch allows you to safely fetch updates and analyze the changes made by others without affecting your current working copy. This is especially useful for avoiding unexpected conflicts, as no changes are applied automatically. git pull fetches the data and immediately merges it into the local repository. This process requires caution. If conflicts occur, you will need to resolve them manually. The choice between these commands depends on your goals: If you want to check changes first, use git fetch. If you need to quickly update the code, use git pull, but be aware of the possible conflicts.
20 February 2025 · 10 min to read
Git

How to Use the Git Rebase Command

In Git, managing code history is important for tracking changes. For this purpose, git supports several commands, such as commit, log, diff, branch, merge, revert, and rebase. The git rebase command, in particular, is useful for keeping branch histories clean by allowing developers to reapply commits from one branch to another. In this article, we’ll discuss what git rebase is, how it differs from the git merge command, and how to use it to maintain a structured, linear commit history that’s easier to read and review. Understanding Git Rebase: What Is It? The git rebase command allows us to move, combine, reorder, edit, or remove commits. Moreover, it simplifies the project history by moving the commits of one branch onto the base of another branch. Rebase in git is especially useful when integrating changes into a feature branch, resulting in a streamlined history without unnecessary merge commits. Git Rebase vs. Git Merge: What’s the Difference? Both merge and rebase commands are used to combine branches, but they differ in how the commit history looks after one branch is added to another. Here’s a comparison to understand when to use rebase versus merge: Git Merge: It combines the histories of both branches and creates a merge commit, marking the point where they joined. This commit retains the complete history of both branches. Git Rebase: It applies changes from one branch to another and rewrites the history as though all work was done linearly. Git Merge maintains separate histories for each branch, while Git Rebase linearizes the history, making it appear as if all work was done in a straight line. When using git merge, the focus is on merging feature branches, whereas git rebase is used to rewrite and clean up the commit history for better organization and readability. Basic Syntax and Options for Git Rebase The git rebase command allows users to transfer commits from the current branch to the base of another branch. The basic syntax of the git rebase command is shown below: git rebase <target-branch> Users can use different options with the git rebase command, which are listed below:  git rebase master: This command adds all the changes from the master branch to your current branch. -I or --interactive: This option opens an editor to reorder, combine, or modify commits interactively. --onto <newbase>: This option enables us to set a new base commit for the rebase. We can use it to move several commits to a different branch or commit. --skip: This option skips a commit if there's a conflict during rebase. It tells Git to ignore that commit and continue with the rebase. --no-verify: This option ignores any pre-commit checks set up in the repository. It’s useful if we want to commit quickly without running those checks. --auto-squash: It automatically applies the fixup or squash flags to commits. This is helpful for cleaning up commit history during an interactive rebase. These git rebase options should be used carefully, as they can change the commit history of the repository. It is recommended to back up your code before running the rebase command in Git. This way, users can restore the original code if anything goes wrong. How to Perform an Interactive Rebase Interactive rebasing enables users to reorder, combine, or edit commit messages. This practice gives users precise control over their history. Go through the following steps to perform an interactive rebase: Step 1: Switch to the feature branch Users can use the git checkout command to navigate to a different branch in a Git repository: git checkout <feature-branch> This command changes the user's current working branch to the specified <feature-branch>. After switching, any subsequent Git operations, including rebase, will be performed in the context of that branch. Step 2: Start interactive rebase Users can run the rebase command with the -i option to perform an interactive rebase: git rebase -i <target-branch> When a user runs this command, it opens the default text editor. The user will see a list of commits from the current branch that are not present in <target-branch>. Each commit comes with actions to choose from, such as: pick: Keep the commit as it is. edit: Stop and allow changes to the commit (like the message or the files). squash: Combine this commit with the one before it. drop: Removes a commit.  After the user makes the desired changes and saves the file, Git will continue the rebase based on the selected choices. Handling Merge Conflicts During Rebase When rebasing, conflicts can occur if the same line of code is modified in both branches. In that case, Git pauses the rebase process, allowing users to resolve conflicts. Follow the steps below to resolve the merge conflicts during the rebase: Step 1: Identify Conflicting Files Run the git status command to see where the problem/conflict lies in a Git repository: git status This command displays a list of files that have conflicts, marked as unmerged. Step 2: Edit the Conflicted Files When there are conflicts during a Git operation, like a merge or rebase, Git marks the conflicting parts in the files with special markers: <<<<<<< HEAD: It shows the user's changes (from the current branch). =======: It separates the user's changes from the other branch's changes. >>>>>>> <branch-name>: It shows the end of the conflicting section and shows the name of the branch with the conflicting changes. To resolve the conflicts, users should open the files in a text editor and decide which changes to keep. They can choose to: Keep their changes. Keep the changes from the other branch. Combine both sets of changes. After making the edits, it's important to remove the conflict markers to clean up the code and make sure it works properly. Step 3: Stage the Resolved Files Once conflicts have been resolved, the next step is to stage the resolved files. This is done using the following command: git add <file-name> Replace <file-name> with the file’s name that was edited. If multiple files are resolved, they can be added simultaneously or individually. Step 4: Continue the Rebase After staging the resolved files, users can continue the rebase process with the command: git rebase --continue How to Abort, Skip, or Continue a Rebase Users can manage the rebase process by executing the git rebase command with the abort, skip, and continue options. Aborting the Rebase Run the git rebase command with the --abort option to cancel the ongoing rebase and return the branch to its original state: git rebase --abort Skipping the Rebase Similarly, if a user runs into unresolved conflicts during a rebase, he can execute the git rebase command with the --skip option to omit the problematic commit: git rebase --skip Continuing the Rebase If we encounter conflicts while rebasing, we need to resolve them first. After fixing the issues, we can run the rebase command with the --continue option to continue the rebasing process: git rebase --continue Common Mistakes Users can encounter several issues during Git rebase, such as merge conflicts, uncommitted changes, aborted rebase attempts, etc. Here are some common mistakes that users may face while rebasing: Merge Conflicts Users can face merging conflicts when changes in the rebased branch overlap with the base branch. These conflicts require manual resolution. Use the git add <filename> command to mark conflicts as resolved. Then, continue with the git rebase --continue command. Uncommitted Changes If you have uncommitted changes in your working directory, Git won't allow a rebase. In that case, commit or stash your changes with git stash before starting the rebase. Rebasing Shared Branches Rebasing the shared branches can create confusion and conflicts. To avoid this issue, users can rebase the branches that they own or are not currently used by anyone else. Complex History A branch with a complicated commit history can make the rebase process error-prone. In such cases, consider using git merge instead or simplify the history before rebasing. Incorrect Rebase Sequence Specifying the wrong base commit can lead to unexpected changes. Therefore, it is recommended to always double-check that you are rebasing onto the correct branch. Apart from this, the git rebase command has several disadvantages, including increased complexity compared to merging, especially with complex commit histories. It can lead to lost commits if the wrong branch is rebased or if conflicts are unresolved. Additionally, rebasing alters the commit history in public repositories, which makes collaboration difficult. Conclusion In Git, the rebase command helps maintain a clean and readable commit history. However, it requires careful usage due to certain challenges. Therefore, before making significant changes to a branch’s commit history, it’s important to carefully consider the risks and benefits of using the git rebase command.
30 October 2024 · 8 min to read
Git

How to Use the Git Reset Command

Today, it's hard to imagine the work of a programmer or IT professional without version control. Among the various SCM tools, Git stands out, having quickly gained popularity and becoming the de facto standard in the world of version control systems. Git allows you to easily track project file changes, manage branches, collaborate, and centrally store code and other files.  One of Git's strengths is its flexible ability to undo or remove changes. One such way to undo changes is with the git reset command, which supports three different modes. In this tutorial, we'll explore how to undo changes using git reset and its modes through practical examples. Prerequisites We'll focus on practical use cases of the git reset command, so it's necessary to have Git installed beforehand. We'll use a Linux-based operating system for this tutorial, specifically Ubuntu 22.04. However, any Linux distribution will work, as Git is available in nearly all modern package managers. In most distributions, Git comes pre-installed, though the version may not always be the latest. For Ubuntu-based systems, you can install Git from the official repository with the following commands: add-apt-repository ppa:git-core/ppa && apt -y install git For other Debian-based distributions (Debian, Linux Mint, Kali Linux, etc.), you can install Git using: apt -y install git For RHEL-based distributions (RedHat, CentOS, Fedora, Oracle Linux), the installation command will vary depending on the package manager: For yum package manager: yum -y install git For dnf package manager: dnf -y install git After installation, verify the Git version: git --version What is git reset? The git reset command is used to undo local changes. Technically speaking, git reset moves the HEAD pointer to a previous commit in the repository. HEAD is a pointer to the current branch and points to the latest commit in that branch. The git reset command operates with three key elements: the working directory, the HEAD pointer, and the index. These elements are often referred to as "trees" in Git, as they are structured using nodes and pointers. We'll go into detail about each of these elements below. It's worth noting that various Git-based web services like GitHub, GitLab, and Bitbucket offer the ability to undo actions through their web interface. However, they typically use a safer alternative, git revert, which preserves the entire project history, unlike git reset which can permanently remove commits. The Working Directory The working directory is where files are stored and tracked by Git. When you run the git reset command, Git knows which directory is being tracked because of a hidden .git folder created when you initialize a repository with git init. Here's how the working directory works in practice: Create a new directory and navigate into it: mkdir new_project && cd new_project Initialize a new Git repository: git init Once you initialize the repository, a hidden .git folder containing Git configuration files is created in the root directory. The HEAD Pointer HEAD points to the current branch and the latest commit in that branch. Every time you switch branches with git checkout, HEAD updates to point to the latest commit in the new branch. Here's a practical example: Create a new file: touch new1.txt Add the file to the repository: git add new1.txt Commit the file: git commit -m "Initial commit" To see where HEAD is pointing, use the git cat-file command: git cat-file -p HEAD Since there's only one commit, HEAD points to it. Now, let's modify the file and add it again. Modify the file: echo "This is a test file" > new1.txt Stage the file: git add new1.txt Commit the changes: git commit -m "Added content to new1.txt" Check the HEAD pointer again: git cat-file -p HEAD As you can see, HEAD now points to the new, latest commit. The Index The index (or "staging area") is where files go after being added with git add. Think of it as a pre-commit area. Files in the index are tracked by Git but not yet part of the actual commit. You can remove or modify files in the index before they are committed. Create a new file: touch new2.txt Add it to the index: git add new2.txt Check the status: git status The file is now in the staging area but not yet committed.   Git Reset Modes The git reset command supports three modes: soft, mixed, and hard. Soft Mode The soft mode undoes the last commit but keeps the changes in the index. This means that you can modify and recommit them. Create a new file: touch new3.txt Add it to the index: git add new3.txt Commit the file: git commit -m "Added new3.txt" If we run git log now, that's what we'll see: To undo the last commit: git reset --soft HEAD~1 The commit is undone, but the file remains in the index. Mixed Mode The mixed mode is the default for git reset. It undoes the commit and resets the index, but leaves the working directory untouched. Create three new files: touch new{1..3}.txt Add and commit them: git add new1.txt new2.txt new3.txtgit commit -m "Added three files" Now undo the commit: git reset HEAD~1 The files remain, but the last commit is removed. Hard Mode The hard mode deletes the commit, resets the index, and removes the files from the working directory. This is the most destructive option. Create and commit a file: touch readme.mdgit add readme.mdgit commit -m "Added readme.md" To remove the commit and the file: git reset --hard HEAD~1 The file and the commit are permanently deleted. Resetting to an Earlier Commit You can also reset to a specific commit using its hash: git reset --hard <commit-hash> This will reset the repository to that specific commit. Conclusion In this tutorial, we explored the git reset command and its modes: soft, mixed, and hard. While git reset is a powerful tool for undoing local changes, it's essential to understand each mode's impact, especially the potential risks of using the hard mode to avoid irreversible data loss.
26 September 2024 · 5 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support