I have the following code to generate a new git repo and put a .gitignore into it:
Repository repo = new FileRepositoryBuilder().setGitDir(gitProjectDir.toFile())
.setWorkTree(gitProjectDir.toFile())
.build();
repo.create();
// Add a file from the resources to the repository
try (Git git = new Git(repo))
{
Files.copy(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("gitignore.txt"), gitProjectDir.resolve(".gitignore"),
StandardCopyOption.REPLACE_EXISTING);
try
{
git.add()
.addFilepattern(".gitignore")
.call();
git.commit()
.setAuthor("CMBUILD", "cmbuild@continentale.de")
.setMessage(jiraTicket + ": Hinzufügen von .gitignore")
.call();
}
catch (GitAPIException e)
{
throw new IOException(
"Could not create the commit", e);
}
}
While this seems to work (if you clone the resulting repo, you get one commit that contains the .gitignore
file), it also seems to be not quite correct because the git repo (not the clone!) that I generate looks like this:
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 28.08.2023 11:22 branches
d----- 28.08.2023 11:22 hooks
d----- 28.08.2023 11:22 logs
d----- 28.08.2023 11:22 objects
d----- 28.08.2023 11:22 refs
-a---- 28.08.2023 11:22 105 .git
-a---- 28.08.2023 11:22 4505 .gitignore
-a---- 28.08.2023 11:22 36 COMMIT_EDITMSG
-a---- 28.08.2023 11:22 214 config
-a---- 28.08.2023 11:22 23 HEAD
-a---- 28.08.2023 11:22 112 index
So the .gitignore
just lies within the repository files.
How can I adjust the code to avoid this?
You're using setGitDir
incorrectly. From an archived version of the API I could find;
Set the Git directory storing the repository metadata.
In other words, you're telling jgit not to use the .git
directory but instead use the project dir itself.