Open In App

Configuring Repository Settings with JGit

Last Updated : 04 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

JGit is a lightweight and pure Java library that implements the Git version control system. It allows the Java developers to work with Git repositories programmatically. This article will guide you to focus on configuring repository settings using JGit including setting up the environment, fetching and pushing with authentication, and handling the merge conflicts.

The main concept that involves using the JGit to perform the Git operations such as fetching, pushing, and merging the branches, handling the conflicts, and committing the changes. JGit can simplify the programmatic interactions with Git. Making it possible to automate and integrate the Git operations within the Java applications.

Implementation to Configure Repository Settings with JGit

Below are the implementation steps to configure repository settings with JGit.

Step 1: Create a Maven Project

Create a new maven project using Intellij Idea and after creating the project, the file structure will look like the below image.

Folder Structure


Step 2: JGit Dependency

Open the pom.xml file and add the JGit dependency into the project.

 <!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
            <dependency>
                <groupId>org.eclipse.jgit</groupId>
                <artifactId>org.eclipse.jgit</artifactId>
                <version>6.9.0.202403050737-r</version>
            </dependency>


Step 3: Create the GitRepository Class

This class provides the method to open the existing Git repository located at the specified path of the repository.

Java
package org.example;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.File;
import java.io.IOException;

/**
 * Utility class to open a Git repository located at the specified path.
 */
public class GitRepository {
    
    /**
     * Opens an existing Git repository located at the specified path.
     *
     * @param repoPath the path to the Git repository
     * @return an instance of the Git class representing the repository
     * @throws IOException if an I/O error occurs
     */
    public static Git openRepository(String repoPath) throws IOException {
        // Create a FileRepositoryBuilder to build the repository
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        
        // Set the path to the .git directory, read the environment, and find the git directory
        return new Git(builder.setGitDir(new File(repoPath))
                .readEnvironment()
                .findGitDir()
                .build());
    }
}


Step 3: Create the GitService

This class encapsulates various Git operations such as the merging branches, resolving the conflicts, committing changes, fetching and pushing with authentication of the repository.

Java
package org.example;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeResult;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheBuilder;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.IOException;

/**
 * Service class to encapsulate various Git operations.
 */
public class GitService {

    private final Git git;

    /**
     * Constructor to initialize GitService with the repository located at the specified path.
     *
     * @param repoPath the path to the Git repository
     * @throws IOException if an I/O error occurs
     */
    public GitService(String repoPath) throws IOException {
        this.git = GitRepository.openRepository(repoPath);
    }

    /**
     * Merges the specified branch into the current branch.
     *
     * @param branchName the name of the branch to merge
     * @return the result of the merge operation
     * @throws GitAPIException if a Git API error occurs
     * @throws IOException if an I/O error occurs
     */
    public MergeResult mergeBranch(String branchName) throws GitAPIException, IOException {
        return git.merge()
                .include(git.getRepository().findRef(branchName))
                .call();
    }

    /**
     * Resolves conflicts for the specified file path.
     *
     * @param conflictFilePath the file path of the conflict to resolve
     * @throws IOException if an I/O error occurs
     */
    public void resolveConflicts(String conflictFilePath) throws IOException {
        Repository repository = git.getRepository();
        DirCache dirCache = repository.lockDirCache();
        DirCacheBuilder builder = dirCache.builder();

        ObjectId blobId = repository.resolve("HEAD:" + conflictFilePath);
        DirCacheEntry entry = new DirCacheEntry(conflictFilePath);
        entry.setObjectId(blobId);
        entry.setFileMode(FileMode.REGULAR_FILE);

        builder.add(entry);
        builder.commit();
        dirCache.write();
        dirCache.unlock();
    }

    /**
     * Commits a merge with the specified commit message.
     *
     * @param message the commit message
     * @throws GitAPIException if a Git API error occurs
     */
    public void commitMerge(String message) throws GitAPIException {
        git.commit()
                .setMessage(message)
                .call();
    }

    /**
     * Fetches from the remote repository with authentication.
     *
     * @param username the username for authentication
     * @param password the password for authentication
     * @throws GitAPIException if a Git API error occurs
     */
    public void fetchWithAuth(String username, String password) throws GitAPIException {
        git.fetch()
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .call();
    }

    /**
     * Pushes to the remote repository with authentication.
     *
     * @param username the username for authentication
     * @param password the password for authentication
     * @throws GitAPIException if a Git API error occurs
     */
    public void pushWithAuth(String username, String password) throws GitAPIException {
        git.push()
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .call();
    }
}


Step 4: Main class

The Main Class can be executing the Git operations defined in the GitService. It demonstrates how to fetch, merge, resolve the conflicts, commit and push the changes using JGit.

Java
package org.example;

import org.eclipse.jgit.api.MergeResult;
import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        String repoPath = "C:/Users/Mahesh/Documents/check/securing-RESTful-API-Demo/.git";
        String featureBranch = "master";
        String conflictFilePath = "C:/Users/Mahesh/Documents/check/securing-RESTful-API-Demo/blob/master/src/main/java/org/example/securingrestfulapi/controller/AuthController.java";
        String username = "i#####e%%h123";
        String password = "##$$%%$@123";

        try {
            GitService gitService = new GitService(repoPath);

            // Fetching with authentication
            gitService.fetchWithAuth(username, password);
            System.out.println("Fetched from remote repository.");

            // Merging the feature branch
            MergeResult mergeResult = gitService.mergeBranch(featureBranch);

            switch (mergeResult.getMergeStatus()) {
                case CONFLICTING:
                    System.out.println("Conflicts detected:");
                    mergeResult.getConflicts().forEach((path, conflict) -> {
                        System.out.println("Conflict in file: " + path);
                    });

                    // Resolve conflicts manually (edit the conflicting files here)
                    gitService.resolveConflicts(conflictFilePath);
                    System.out.println("Conflicts resolved.");
                    break;

                case MERGED:
                    System.out.println("Merged successfully.");
                    break;

                default:
                    System.out.println("Merge status: " + mergeResult.getMergeStatus());
            }

            // Committing the merge
            gitService.commitMerge("Resolved merge conflicts");
            System.out.println("Merge committed.");
            System.out.println("Pushed to remote repository.");

            // Pushing with authentication
            gitService.pushWithAuth(username, password);
            System.out.println("Pushed to remote repository.");

        } catch (IOException | GitAPIException e) {
            e.printStackTrace();
        }
    }
}


pom.xml file:

Java
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>Jgit-Conflict-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

        <dependencies>
            <!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
            <dependency>
                <groupId>org.eclipse.jgit</groupId>
                <artifactId>org.eclipse.jgit</artifactId>
                <version>6.9.0.202403050737-r</version>
            </dependency>
        </dependencies>

</project>


Step 5: Run the application

Now, run the application and it will show below as output.

Output Console


Next Article
Article Tags :
Practice Tags :

Similar Reads