### Core Repository Configuration Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md An example of the [core] section in a Git configuration file. ```ini [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ``` -------------------------------- ### User Identity Configuration Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md An example of the [user] section in a Git configuration file. ```ini [user] name = John Doe email = john@example.com ``` -------------------------------- ### Documentation Structure Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/README.md Illustrates the standard structure for each API reference file, including component and method details, parameters, return types, exceptions, usage examples, and source locations. ```markdown ## Component Name ### Method/Class Name - Full signature - Parameters table (name | type | required | default | description) - Return type - Throws (error conditions) - Usage example - Source location ``` -------------------------------- ### Remote Repository Configuration Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Examples of [remote "origin"] and [remote "upstream"] sections in a Git configuration file, specifying URLs and fetch refspecs. ```ini [remote "origin"] url = https://github.com/user/repo.git fetch = +refs/heads/*:refs/remotes/origin/* [remote "upstream"] url = https://github.com/upstream/repo.git fetch = +refs/heads/*:refs/remotes/upstream/* ``` -------------------------------- ### Opening a JGit Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/README.md This is the starting point for most JGit operations. It demonstrates how to open an existing JGit repository. ```java Repository repo = CookbookHelper.openJGitCookbookRepository(); ``` -------------------------------- ### Branch Configuration Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Examples of [branch "master"] and [branch "develop"] sections in a Git configuration file, specifying the remote and merge upstream branch. ```ini [branch "master"] remote = origin merge = refs/heads/master [branch "develop"] remote = origin merge = refs/heads/develop ``` -------------------------------- ### Configure and Start Jetty HTTP Server with GitServlet Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Configures and starts a Jetty web server on port 8080. It sets up a context handler and registers the GitServlet to handle requests at the /repo/* path, enabling Git operations over HTTP. ```Java Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(gs, "/repo/*"); server.start(); return server; ``` -------------------------------- ### Gradle Run Command Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Execute the Gradle run task to start the HTTP server application. ```bash cd httpserver ./gradlew run ``` -------------------------------- ### Clone Command Line Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Standard git command to clone a repository from an HTTP URL. Replace 'some_repo' with the actual repository name. ```bash git clone http://localhost:8080/repo/some_repo ``` -------------------------------- ### Configure HTTP Protocol Settings Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Example INI file configuration for the HTTP protocol section in JGit. ```ini [http] receivepack = true uploadpack = true sslVerify = true ``` -------------------------------- ### Basic Repository Resolver Setup Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Sets a basic repository resolver for the GitServlet that always returns the same repository instance and increments its open count. ```java GitServlet gs = new GitServlet(); gs.setRepositoryResolver((req, name) -> { repository.incrementOpen(); return repository; }); ``` -------------------------------- ### Implementing a Cancellable Progress Monitor Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Provides an example of a custom ProgressMonitor implementation that allows for operation cancellation. ```java class SmartProgressMonitor implements ProgressMonitor { private volatile boolean cancelled = false; @Override public boolean isCancelled() { return cancelled; } public void requestCancel() { cancelled = true; } } SmartProgressMonitor monitor = new SmartProgressMonitor(); try { git.fetch().setProgressMonitor(monitor).call(); } catch (CanceledException e) { System.out.println("Operation cancelled"); } ``` -------------------------------- ### Open JGit Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/INDEX.md Opens an existing JGit repository. This is a helper method for cookbook examples. ```java CookbookHelper.openJGitCookbookRepository() ``` -------------------------------- ### Push Command Line Example Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Standard git command to push local changes to the 'origin' remote, specifically for the 'master' branch. Requires server-side configuration for write operations. ```bash git push origin master ``` -------------------------------- ### Configure ServletContextHandler with GitServlet Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Configure a ServletContextHandler to serve Git operations under a specific context path. This example adds a SecurityFilter and the GitServlet. ```java ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); // Add security filter context.addFilter(new FilterHolder(new SecurityFilter()), "/*", EnumSet.of(DispatcherType.REQUEST)); // Add GitServlet context.addServlet(gs, "/git/*"); server.setHandler(context); ``` -------------------------------- ### Basic HTTP Basic Authentication Handler Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Provides a basic example of how to check for the Authorization header in an HTTP request to implement authentication. Returns a 401 if the header is missing. ```java // Custom handler for HTTP Basic Auth String auth = request.getHeader("Authorization"); if (auth == null) { // Return 401 } ``` -------------------------------- ### List All Commits in a Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Walks through all commits in the repository history, starting from the tips of all references. This is a more comprehensive log than 'git log'. ```java import org.eclipse.jgit.api.Git; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.errors.RevisionSyntaxException; import org.eclipse.jgit.errors.IncorrectObjectTypeException; import org.eclipse.jgit.errors.MissingObjectException; import org.eclipse.jgit.errors.AmbiguousObjectException; import org.eclipse.jgit.api.errors.GitAPIException; import java.io.File; import java.io.IOException; public class WalkAllCommits { public static void main(String[] args) throws IOException, GitAPIException { File repoPath = new File("my_repo"); // Replace with your repository path try (Repository repository = org.eclipse.jgit.storage.file.FileRepositoryBuilder.create(new org.eclipse.jgit.lib.FileRepository(new File(repoPath, ".git")))) { try (RevWalk walk = new RevWalk(repository)) { // Get the HEAD commit ObjectId head = repository.resolve("HEAD"); if (head == null) { System.out.println("Repository is empty or HEAD is not set."); return; } RevCommit commit = walk.parseCommit(head); // Iterate through all commits reachable from HEAD walk.markStart(walk.parseCommit(repository.resolve("HEAD"))); for (RevCommit revCommit : walk) { System.out.println("Commit: " + revCommit.getId().getName()); System.out.println("Author: " + revCommit.getAuthorIdent().getName()); System.out.println("Date: " + revCommit.getAuthorIdent().getWhen()); System.out.println("Message: " + revCommit.getShortMessage()); System.out.println("--------------------"); } } } } } ``` -------------------------------- ### Handling Specific Git Exceptions Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/README.md This example shows how to catch specific JGit exceptions to handle different error scenarios gracefully, such as an empty repository or a missing reference. ```java catch (NoHeadException e) { /* empty repository */ } catch (RefNotFoundException e) { /* missing ref */ } catch (GitAPIException e) { /* other git error */ } ``` -------------------------------- ### Custom Multi-Repository Resolver Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Implement a custom RepositoryResolver to support multiple repositories based on a base directory. This example locates repositories by appending '.git' to the provided name within the base directory. ```java class MultiRepoResolver implements RepositoryResolver { private File baseDir; @Override public Repository open(HttpServletRequest req, String name) { File repoDir = new File(baseDir, name + ".git"); if (!repoDir.exists()) { throw new RepositoryNotFoundException(name); } Repository repo = new FileRepositoryBuilder() .setGitDir(repoDir) .build(); repo.incrementOpen(); return repo; } } ``` -------------------------------- ### Create New Repository From Scratch Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/03-porcelain-basic.md Demonstrates the process of creating a completely new Git repository from the ground up. This is useful for setting up a repository for the first time. ```java try (Repository repository = CookbookHelper.createNewRepository()) { try (Git git = new Git(repository)) { // Use the repository } } ``` -------------------------------- ### Initialize Repository Builder Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/overview.md Demonstrates how to initialize a FileRepositoryBuilder to find and build a Git repository. ```java FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder .readEnvironment() .findGitDir() .build(); ``` -------------------------------- ### SimpleProgressMonitor Start Task Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/01-helpers.md Signals the start of work on multiple tasks for the SimpleProgressMonitor. This method should be called once at the beginning of a batch operation. ```java public void start(int totalTasks) ``` -------------------------------- ### Populate Git Repository with Sample Data Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Populates an existing Git repository by creating a test file, adding it to the index, and making an initial commit. This snippet also configures the repository to allow HTTP push operations. ```Java repository.getConfig().setString("http", null, "receivepack", "true"); ``` ```Java try (Git git = new Git(repository)) { File myfile = new File(repository.getDirectory().getParent(), "testfile"); if(!myfile.createNewFile()) { throw new IOException("Could not create file " + myfile); } git.add().addFilepattern("testfile").call(); System.out.println("Added file " + myfile + " to repository at " + repository.getDirectory()); git.commit().setMessage("Test-Checkin").call(); } ``` -------------------------------- ### Iterate Commits Starting from a Reference Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/02-lowlevel-api.md Uses RevWalk to iterate over all commits reachable from a specified starting point. This is fundamental for traversing commit history. ```java try (RevWalk walk = new RevWalk(repository)) { RevCommit start = walk.parseCommit(headRef.getObjectId()); walk.markStart(start); for (RevCommit commit : walk) { System.out.println("Commit: " + commit.getName()); } } ``` -------------------------------- ### Iterate Through Commit History Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Use RevWalk to traverse the commit graph starting from a specific commit. Mark start points and iterate to process each commit. ```java try (RevWalk walk = new RevWalk(repository)) { RevCommit start = walk.parseCommit(startId); walk.markStart(start); for (RevCommit commit : walk) { System.out.println(commit.getFullMessage()); } } ``` -------------------------------- ### Initialize a New Git Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Use this to create a new, empty Git repository. Ensure the directory exists before initialization. ```java import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import java.io.File; import java.io.IOException; public class InitRepository { public static void main(String[] args) throws IOException, GitAPIException { // Create a new repository here File repoPath = new File("my_new_repo"); if (!repoPath.exists()) { repoPath.mkdirs(); } // Initialize the repository try (Git git = Git.init().setDirectory(repoPath).call()) { System.out.println("Initialized empty Git repository in " + repoPath.getAbsolutePath()); } } } ``` -------------------------------- ### Build Repository with Environment and GitDir Search Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Construct a Repository instance by reading environment variables and searching parent directories for the .git directory. This pattern is useful for flexible repository location. ```java FileRepositoryBuilder builder = new FileRepositoryBuilder(); try (Repository repository = builder .readEnvironment() .findGitDir() .build()) { // Use repository } ``` -------------------------------- ### Get Ref Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/INDEX.md Retrieves a Git reference object by its name using the low-level API. ```java repository.getRef(String) ``` -------------------------------- ### Set GIT_WORK_TREE Environment Variable Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Example of setting GIT_DIR and GIT_WORK_TREE environment variables in bash. ```bash export GIT_DIR=/path/to/.git export GIT_WORK_TREE=/path/to/working/tree ``` -------------------------------- ### Resource Management with Try-with-Resources Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Shows how to ensure resources like Repository, Git, and RevWalk are automatically closed, even if exceptions occur. ```java try (Repository repo = openRepository(); Git git = new Git(repo); RevWalk walk = new RevWalk(repo)) { // Operations } catch (IOException e) { // Resources automatically closed even on error } ``` -------------------------------- ### CreateNewRepository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/03-porcelain-basic.md Demonstrates creating a completely new Git repository from scratch using JGit. ```APIDOC ## CreateNewRepository ### Description Demonstrates creating a completely new repository from scratch. ### Usage Pattern ```java try (Repository repository = CookbookHelper.createNewRepository()) { try (Git git = new Git(repository)) { // Use the repository } } ``` ``` -------------------------------- ### Set GIT_DIR Environment Variable Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Example of setting the GIT_DIR environment variable in bash for JGit. ```bash export GIT_DIR=/path/to/.git java -jar application.jar ``` -------------------------------- ### Recover from Missing Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Demonstrates creating a new repository if an IOException occurs during the attempt to open an existing one. Useful for scenarios where a repository might not yet exist. ```java try { Repository repo = CookbookHelper.openJGitCookbookRepository(); } catch (IOException e) { // Create new repository instead repo = CookbookHelper.createNewRepository(); } ``` -------------------------------- ### Open Existing Git Repository with JGit Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Demonstrates how to open an existing Git repository using JGit. Ensure the repository path is valid. ```Java package org.dstadler.jgit; import java.io.File; import java.io.IOException; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; public class OpenRepository { public static void main(String[] args) { Repository repository = null; try { // build repository FileRepositoryBuilder builder = new FileRepositoryBuilder(); repository = builder.setGitDir(new File(".git")) // sets the directory for the .git folder .readEnvironment() // scan environment GIT_DIR, GIT_WORK_TREE, ... .findCommonDir() // find the common directory for the .git folder .build(); System.out.println("Opened repository at " + repository.getDirectory()); } catch (IOException e) { e.printStackTrace(); } finally { if (repository != null) { repository.close(); } } } } ``` -------------------------------- ### Retrieve an exact Ref Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Get a specific reference by its full name, ensuring an exact match. ```java Ref exactRef = repository.exactRef("refs/heads/master"); ``` -------------------------------- ### InitRepository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/03-porcelain-basic.md Initializes a new Git repository in an existing directory. This is the high-level equivalent of `git init`. ```APIDOC ## InitRepository ### Description Initializes a new Git repository in an existing directory. ### Usage Pattern ```java InitCommand init = Git.init() .setDirectory(new File("/path/to/repo")); try (Git git = init.call()) { // Repository is now initialized } ``` ### Equivalent Git Command `git init` ``` -------------------------------- ### Direct FileRepositoryBuilder Usage Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/01-helpers.md Demonstrates the direct usage of FileRepositoryBuilder for more granular control when setting up a repository. Reads environment variables and builds the repository. ```java FileRepositoryBuilder builder = new FileRepositoryBuilder(); try (Repository repository = builder.setGitDir(new File(".git")) .readEnvironment() .build()) { // Use repository } ``` -------------------------------- ### Create New JGit Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/INDEX.md Creates a new JGit repository. This is a helper method for cookbook examples. ```java CookbookHelper.createNewRepository() ``` -------------------------------- ### Create and Delete Branches Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Demonstrates how to create a new branch and delete an existing one. Ensure the branch to be deleted is not the current HEAD. ```java import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import java.io.File; import java.io.IOException; public class CreateAndDeleteBranch { public static void main(String[] args) throws IOException, GitAPIException { File repoPath = new File("my_repo"); // Replace with your repository path String newBranchName = "my-new-branch"; String branchToDelete = "my-old-branch"; try (Git git = Git.open(repoPath)) { // Create a new branch git.branchCreate().setName(newBranchName).call(); System.out.println("Branch '" + newBranchName + "' created."); // Delete a branch (ensure it's not the current branch) // git.branchDelete().setBranchNames(branchToDelete).call(); // System.out.println("Branch '" + branchToDelete + "' deleted."); } } } ``` -------------------------------- ### Get ObjectId Name and Abbreviated Form Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Retrieve the full hexadecimal name and an abbreviated form of an ObjectId. ```java String hex = id.getName(); String short = id.abbreviate(7).name(); ``` -------------------------------- ### Retrieve a specific Ref Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Get a specific reference (like a branch or tag) from the repository by its full name. ```java Ref ref = repository.getRef("refs/heads/master"); ``` -------------------------------- ### Use Try-with-Resources for Repository Management Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/overview.md Illustrates the use of try-with-resources for ensuring proper management and closing of a Git repository. ```java try (Repository repository = ...) { // Use repository } ``` -------------------------------- ### Set GIT_SSH_COMMAND Environment Variable Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Example of setting the GIT_SSH_COMMAND environment variable in bash with custom SSH options. ```bash export GIT_SSH_COMMAND="ssh -i ~/.ssh/custom_key -o StrictHostKeyChecking=no" ``` -------------------------------- ### Chaining Exceptions to Get Underlying Cause Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Demonstrates how to inspect the cause of a GitAPIException to retrieve more detailed error information. ```java try { doGitOperation(); } catch (GitAPIException e) { if (e.getCause() != null) { // Underlying cause may provide more detail System.err.println("Caused by: " + e.getCause().getMessage()); } } ``` -------------------------------- ### Enable Push over HTTP Configuration Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Configure the repository to allow pushing over HTTP. Ensure this setting is used cautiously and with appropriate security measures. ```java repository.getConfig().setString("http", null, "receivepack", "true"); repository.getConfig().save(); ``` -------------------------------- ### Recursive Tree Walk Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Iterate through all entries in a repository's tree recursively. Ensure the repository and commit are valid before starting. ```java try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(commit.getTree()); walk.setRecursive(true); while (walk.next()) { String path = walk.getPathString(); System.out.println(path); } } ``` -------------------------------- ### Accessing Core Repository Configuration Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Demonstrates reading boolean values for core repository settings like filemode and bare repository status, and setting the ignorecase option. ```java boolean fileMode = config.getBoolean("core", null, "filemode", true); boolean bare = config.getBoolean("core", null, "bare", false); config.setBoolean("core", null, "ignorecase", true); ``` -------------------------------- ### Set GIT_CONFIG Environment Variable Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Example of setting the GIT_CONFIG environment variable in bash to specify an additional config file path. ```bash export GIT_CONFIG=/etc/git/config.local ``` -------------------------------- ### Create, List, Apply, and Drop Stashes Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/04-porcelain-remote.md Demonstrates how to manage stashed changes in a Git repository using JGit's Porcelain API. This includes creating a stash, listing existing stashes, applying a stash without removing it, and applying and then dropping a stash. ```java try (Git git = new Git(repository)) { // Stash current changes RevCommit stash = git.stashCreate().call(); System.out.println("Stashed: " + stash); // List stashes List stashList = git.stashList().call(); for (RevCommit commit : stashList) { System.out.println("Stash: " + commit.getShortMessage()); } // Apply stash (keeps it) git.stashApply() .setStashRef(0) // Apply first stash .call(); // Pop stash (applies and removes) RevCommit popped = git.stashApply() .setStashRef(0) .call(); git.stashDrop() .setStashRef(0) .call(); } ``` -------------------------------- ### Configure Git.cloneRepository() in JGit Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Demonstrates the configuration options available for cloning a repository using JGit's command builder. ```java Git.cloneRepository() .setURI(String) // Remote URL (required) .setDirectory(File) // Clone destination (required) .setBranch(String) // Specific branch (default: remote default) .setCloneAllBranches(boolean) // Clone all branches .setNoCheckout(boolean) // Skip working tree checkout .setDepth(int) // Shallow clone depth .setProgressMonitor(ProgressMonitor) // Progress tracking .setCredentialsProvider(CredentialsProvider) // Authentication .setTimeout(int) // Network timeout (seconds) .call() ``` -------------------------------- ### Walk Commits Between Two References Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/02-lowlevel-api.md Iterates through commits that are present in a starting reference but not in an ending reference. This is useful for finding differences between branches. ```java try (RevWalk walk = new RevWalk(repository)) { RevCommit start = walk.parseCommit(repository.resolve("master")); RevCommit end = walk.parseCommit(repository.resolve("develop")); walk.markStart(start); walk.markUninteresting(end); // Exclude this and its ancestors for (RevCommit commit : walk) { // Commits in master but not in develop } } ``` -------------------------------- ### Accessing User Identity Configuration Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Shows how to read and set the user's name, email, and signing key from the [user] configuration section. ```java String name = config.getString("user", null, "name"); String email = config.getString("user", null, "email"); config.setString("user", null, "name", "John Doe"); config.setString("user", null, "email", "john@example.com"); config.save(); ``` -------------------------------- ### Create New Git Repository with JGit Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Demonstrates how to create a new Git repository using JGit. This will create a new .git directory in the specified path. ```Java package org.dstadler.jgit; import java.io.File; import java.io.IOException; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Repository; public class CreateNewRepository { public static void main(String[] args) { // Define the path for the new repository File repoPath = new File("new-repo"); try (Repository repository = Git.init().setDirectory(repoPath).call().getRepository()) { System.out.println("Created new repository at " + repository.getDirectory()); } catch (IOException | GitAPIException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Get SHA-1 Ref from Name (Java) Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Retrieves the SHA-1 identifier for a given Git reference name, such as 'refs/heads/master'. Requires a JGit Repository object. ```Java import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import java.io.IOException; public class GetRefFromName { public static void main(String[] args) throws IOException { try (Repository repository = new FileRepositoryBuilder() .setGitDir(new java.io.File(".git")) .readEnvironment() .findGitDir() .build()) { String refName = "refs/heads/master"; Ref ref = repository.findRef(refName); if (ref != null) { System.out.println("SHA-1 for " + refName + ": " + ref.getObjectId().getName()); } else { System.out.println("Ref " + refName + " not found."); } } } } ``` -------------------------------- ### Accessing Branch Configuration Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Demonstrates reading and setting the default remote and merge branch for a specific local branch. ```java String remote = config.getString("branch", "develop", "remote"); String merge = config.getString("branch", "develop", "merge"); config.setString("branch", "develop", "remote", "origin"); config.setString("branch", "develop", "merge", "refs/heads/develop"); config.save(); ``` -------------------------------- ### Custom Authenticating Repository Resolver Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Implement a custom RepositoryResolver to add authentication to repository access. This example checks for a valid Authorization header before opening a repository. ```java class AuthenticatingRepositoryResolver implements RepositoryResolver { @Override public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { String auth = req.getHeader("Authorization"); if (!isValidAuth(auth)) { throw new ServiceNotEnabledException(); } Repository repo = getRepository(name); repo.incrementOpen(); return repo; } } ``` -------------------------------- ### Configure Git.log() in JGit Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Demonstrates the configuration options available for retrieving commit logs using JGit's command builder. ```java git.log() .add(ObjectId) // Include commits from ref .not(ObjectId) // Exclude commits from ref .all() // Include all refs .addPath(String) // Filter by file path .setMaxCount(int) // Limit results .setSkip(int) // Skip first N commits .setAuthor(String) // Filter by author (regex) .setCommitter(String) // Filter by committer (regex) .since(Date) // Commits after date .until(Date) // Commits before date .call() ``` -------------------------------- ### Common Java Imports for Git Server Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/05-http-server.md Essential import statements for building a Git HTTP server using Jetty and JGit. ```java import org.eclipse.jetty.ee10.servlet.ServletContextHandler; import org.eclipse.jetty.server.Server; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.http.server.GitServlet; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import java.io.File; import java.io.IOException; ``` -------------------------------- ### Get Blame Information for a File Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/04-porcelain-remote.md Determines which commit last modified each line of a specified file. This is useful for understanding the history and authorship of specific lines of code. ```java try (Git git = new Git(repository)) { BlameResult blameResult = git.blame() .setFilePath("src/Main.java") .call(); for (int i = 0; i < blameResult.getResultSize(); i++) { RevCommit commit = blameResult.getSourceCommit(i); String author = commit.getAuthorIdent().getName(); String line = blameResult.getResultContents().getString(i); System.out.printf("%s: %s%n", author, line); } } ``` -------------------------------- ### Get Git Reference by Name Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/02-lowlevel-api.md Retrieves a Git reference (Ref) object for a given reference string like 'refs/heads/master'. Use exactRef for an exact match. ```Java try (Repository repository = CookbookHelper.openJGitCookbookRepository()) { Ref head = repository.exactRef("refs/heads/master"); System.out.println("Ref: " + head.getName() + " -> " + head.getObjectId().getName()); } ``` -------------------------------- ### Handling Empty Repository Exception Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Demonstrates catching NoHeadException for an empty repository and returning an empty list. ```java try (Git git = new Git(repository)) { return git.log().call(); } catch (NoHeadException e) { System.out.println("Repository is empty. Create initial commit first."); return Collections.emptyList(); } ``` -------------------------------- ### Get Commit Message (Java) Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Extracts the commit message from a given commit object. This requires a RevCommit object, which can be obtained using methods like `repository.parseCommit()`. ```Java import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.revwalk.RevWalk; import java.io.IOException; public class GetCommitMessage { public static void main(String[] args) throws IOException { try (Repository repository = new FileRepositoryBuilder() .setGitDir(new java.io.File(".git")) .readEnvironment() .findGitDir() .build()) { String commitIdString = "HEAD"; // or a SHA-1 string ObjectId commitId = repository.resolve(commitIdString); if (commitId != null) { try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(commitId); System.out.println("Commit Message: " + commit.getFullMessage()); } } else { System.out.println("Commit " + commitIdString + " not found."); } } } } ``` -------------------------------- ### Handle Temporary File Creation Failure Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Illustrates how to handle errors during temporary file or directory creation. This code checks for deletion and creation success, throwing an IOException if they fail. ```java File tempDir = File.createTempFile("git", ""); if (!tempDir.delete()) { throw new IOException("Could not delete temp file: " + tempDir); } if (!tempDir.mkdirs()) { throw new IOException("Could not create temp directory: " + tempDir); } ``` -------------------------------- ### OpenRepository Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/03-porcelain-basic.md Opens an existing Git repository using `FileRepositoryBuilder`. ```APIDOC ## OpenRepository ### Description Opens an existing repository using `FileRepositoryBuilder`. ### Usage Pattern ```java FileRepositoryBuilder builder = new FileRepositoryBuilder(); try (Repository repository = builder.setGitDir(new File(".git")) .readEnvironment() .build()) { // Use repository } ``` ``` -------------------------------- ### Get Tree Object from Commit (Java) Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Retrieves the tree object associated with a commit. This is useful for accessing the file structure of a commit. Requires a Repository and a commit identifier. ```Java import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.treewalk.RevTree; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.revwalk.RevWalk; import java.io.IOException; public class GetRevTreeFromObjectId { public static void main(String[] args) throws IOException { try (Repository repository = new FileRepositoryBuilder() .setGitDir(new java.io.File(".git")) .readEnvironment() .findGitDir() .build()) { String commitIdString = "HEAD"; // or a SHA-1 string ObjectId commitId = repository.resolve(commitIdString); if (commitId != null) { try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(commitId); RevTree tree = commit.getTree(); System.out.println("Tree SHA-1: " + tree.getId().getName()); } } else { System.out.println("Commit " + commitIdString + " not found."); } } } } ``` -------------------------------- ### Show Change Type for Files Between Commits Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/03-porcelain-basic.md Extends the previous example to explicitly print the file name and its change type (added, modified, deleted, etc.) between two commits. ```java for (DiffEntry diff : diffs) { System.out.println("File: " + diff.getNewPath()); System.out.println("Change: " + diff.getChangeType()); } ``` -------------------------------- ### Implement Simple Progress Monitor Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md A basic implementation of the ProgressMonitor interface for tracking task progress. Useful for providing user feedback during long-running operations. ```java public class SimpleProgressMonitor implements ProgressMonitor { private int totalTasks; private String currentTask; @Override public void start(int totalTasks) { this.totalTasks = totalTasks; } @Override public void beginTask(String title, int totalWork) { this.currentTask = title; System.out.println("Starting: " + title); } @Override public void update(int completed) { System.out.print("."); } @Override public void endTask() { System.out.println("Done: " + currentTask); } @Override public boolean isCancelled() { return false; } @Override public void showDuration(boolean show) { } } ``` -------------------------------- ### Accessing Remote Repository Configuration Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/configuration.md Shows how to read remote repository URLs, add new remotes using RemoteConfig, and list all configured remotes. ```java // Read remote URL String url = config.getString("remote", "origin", "url"); // Add remote RemoteConfig remote = new RemoteConfig(config, "upstream"); remote.addURI(new URIish("https://github.com/upstream/repo.git")); remote.update(config); config.save(); // List all remotes Set remotes = config.getSubsections("remote"); for (String remoteName : remotes) { String remoteUrl = config.getString("remote", remoteName, "url"); System.out.println(remoteName + " = " + remoteUrl); } ``` -------------------------------- ### Iterate Through a Tree's Contents Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Use TreeWalk to recursively traverse a repository tree and access file paths and object IDs. Ensure the repository and tree are valid before starting. ```java try (TreeWalk walk = new TreeWalk(repository)) { walk.addTree(tree); walk.setRecursive(true); while (walk.next()) { String path = walk.getPathString(); ObjectId objectId = walk.getObjectId(0); } } ``` -------------------------------- ### Handling Repository Not Found Exception Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/errors.md Illustrates wrapping an IOException in an IllegalStateException when a repository cannot be found. ```java try { return CookbookHelper.openJGitCookbookRepository(); } catch (IOException e) { throw new IllegalStateException( "Could not find repository. Make sure you're in a git directory or " + "that $GIT_DIR is set.", e); } ``` -------------------------------- ### SimpleProgressMonitor Begin Task Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/api-reference/01-helpers.md Begins a specific named task within the SimpleProgressMonitor. It prints the task title and total work units to standard output. Use this to delineate sub-operations. ```java public void beginTask(String title, int totalWork) ``` -------------------------------- ### Iterate Over Commits on a Branch (Java) Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Walks through all commits on a specified branch, starting from the branch's tip and going back in history. Requires a Repository object and a branch name. ```Java import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.lib.ObjectId; import java.io.IOException; public class WalkRev { public static void main(String[] args) throws IOException { try (Repository repository = new FileRepositoryBuilder() .setGitDir(new java.io.File(".git")) .readEnvironment() .findGitDir() .build()) { String branchName = "refs/heads/master"; // or "master" ObjectId branchTip = repository.resolve(branchName); if (branchTip != null) { try (RevWalk revWalk = new RevWalk(repository)) { RevCommit commit = revWalk.parseCommit(branchTip); revWalk.markStart(commit); System.out.println("Commits on branch '" + branchName + "':"); for (RevCommit rev : revWalk) { System.out.println("- " + rev.getName() + ": " + rev.getShortMessage()); } } } else { System.out.println("Branch '" + branchName + "' not found."); } } } } ``` -------------------------------- ### Retrieve Working Directory and Index Status Source: https://github.com/centic9/jgit-cookbook/blob/master/_autodocs/types.md Use the Git.status() command to get a Status object representing the current state of the repository. Check if the repository is clean or if there are modified files. ```java try (Git git = new Git(repository)) { Status status = git.status().call(); if (!status.isClean()) { System.out.println("Changes: " + status.getModified()); } } ``` -------------------------------- ### List All Tags in a Repository Source: https://github.com/centic9/jgit-cookbook/blob/master/README.md Fetches and displays all tags present in the Git repository. This is equivalent to 'git tag'. ```java import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ListTagCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.Ref; import java.io.File; import java.io.IOException; import java.util.Collection; public class ListTags { public static void main(String[] args) throws IOException, GitAPIException { File repoPath = new File("my_repo"); // Replace with your repository path try (Git git = Git.open(repoPath)) { ListTagCommand listTagCommand = git.tagList(); Collection tags = listTagCommand.call(); System.out.println("Tags in the repository:"); if (tags.isEmpty()) { System.out.println("No tags found."); } else { for (Ref tag : tags) { System.out.println(tag.getName()); } } } } } ```