This is an automated email from the ASF dual-hosted git repository.
slawekjaranowski pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven-scm.git
The following commit(s) were added to refs/heads/master by this push:
new 2bb0c7196 Fix JGit repository close handling (#1413)
2bb0c7196 is described below
commit 2bb0c7196bee902547e02f11b407cdf4f53b7dbb
Author: Efe <[email protected]>
AuthorDate: Tue Nov 17 00:15:05 2026 +0300
Fix JGit repository close handling (#1413)
* Fix JGit repository close handling
Use JGit open semantics that retain parent-directory discovery while
ensuring the returned Git instance owns the repository lifecycle.
Signed-off-by: Efe Gökdemir <[email protected]>
* Close temporary JGit repository with try-with-resources
* Avoid private JGit field access in test
* Preserve JGit repository environment when managing its lifetime
Keep the repository discovered by RepositoryBuilder so Git worktree,
index, and object-directory environment settings are not lost when
returning a close-owning Git handle.
Cover nested and explicit Git-directory discovery, missing repositories,
worktree/index environment selection, and packed-file closure in isolated
child processes.
---------
Signed-off-by: Efe Gökdemir <[email protected]>
---
.../scm/provider/git/jgit/command/JGitUtils.java | 12 +-
.../provider/git/jgit/command/JGitUtilsTest.java | 192 +++++++++++++++++++++
2 files changed, 202 insertions(+), 2 deletions(-)
diff --git
a/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtils.java
b/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtils.java
index b0c852c4a..e2efd5edd 100644
---
a/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtils.java
+++
b/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/main/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtils.java
@@ -90,16 +90,24 @@ private JGitUtils() {
/**
* Opens a JGit repository in the current directory or a parent directory.
+ * The returned Git instance owns the repository and must be closed by the
caller.
*
* @param basedir the directory to start with
* @throws IOException if the repository cannot be opened
*/
public static Git openRepo(File basedir) throws IOException {
- return new Git(new RepositoryBuilder()
+ Repository repository = new RepositoryBuilder()
.readEnvironment()
.findGitDir(basedir)
.setMustExist(true)
- .build());
+ .build();
+ // Git.open(File) would discard environment-selected work trees,
indexes and object directories.
+ return new Git(repository) {
+ @Override
+ public void close() {
+ getRepository().close();
+ }
+ };
}
/**
diff --git
a/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/test/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtilsTest.java
b/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/test/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtilsTest.java
new file mode 100644
index 000000000..2d196f2b2
--- /dev/null
+++
b/maven-scm-providers/maven-scm-providers-git/maven-scm-provider-jgit/src/test/java/org/apache/maven/scm/provider/git/jgit/command/JGitUtilsTest.java
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.scm.provider.git.jgit.command;
+
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.storage.file.WindowCacheStats;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class JGitUtilsTest {
+ @Test
+ void openRepoReturnsAnOpenRepositoryForNestedDirectory(@TempDir Path
tempDir) throws Exception {
+ initializeRepository(tempDir);
+ Files.createDirectory(tempDir.resolve("nested"));
+ runProbe(tempDir, "nested");
+ }
+
+ @Test
+ void openRepoAcceptsGitDirectory(@TempDir Path tempDir) throws Exception {
+ initializeRepository(tempDir);
+ runProbe(tempDir, "git-directory");
+ }
+
+ @Test
+ void openRepoRejectsMissingRepository(@TempDir Path tempDir) throws
Exception {
+ runProbe(tempDir, "missing");
+ assertFalse(Files.exists(tempDir.resolve(".git")));
+ }
+
+ @Test
+ void openRepoPreservesWorkTreeEnvironment(@TempDir Path tempDir) throws
Exception {
+ initializeRepository(tempDir);
+ Path workTree = Files.createDirectory(tempDir.resolve("alternate"));
+ Files.write(workTree.resolve("tracked.txt"),
"changed\n".getBytes(StandardCharsets.UTF_8));
+ runProbe(tempDir, "work-tree");
+ }
+
+ @Test
+ void openRepoPreservesIndexEnvironment(@TempDir Path tempDir) throws
Exception {
+ initializeRepository(tempDir);
+ Files.copy(tempDir.resolve(".git/index"),
tempDir.resolve("alternate.index"));
+ Files.write(tempDir.resolve("tracked.txt"),
"changed\n".getBytes(StandardCharsets.UTF_8));
+ runProbe(tempDir, "index");
+ try (Git git = Git.open(tempDir.toFile())) {
+
assertTrue(git.status().call().getModified().contains("tracked.txt"));
+ assertTrue(git.status().call().getChanged().isEmpty(), "the
default index must not be changed");
+ }
+ }
+
+ @Test
+ void closingGitClosesRepositoryPackFiles(@TempDir Path tempDir) throws
Exception {
+ initializeRepository(tempDir);
+ try (Git git = Git.open(tempDir.toFile())) {
+ git.gc().call();
+ }
+ runProbe(tempDir, "close");
+ }
+
+ private static void initializeRepository(Path directory) throws Exception {
+ try (Git git = Git.init().setDirectory(directory.toFile()).call()) {
+ Files.write(directory.resolve("tracked.txt"),
"initial\n".getBytes(StandardCharsets.UTF_8));
+ git.add().addFilepattern("tracked.txt").call();
+ git.commit()
+ .setMessage("initial")
+ .setAuthor("SCM Test", "[email protected]")
+ .setCommitter("SCM Test", "[email protected]")
+ .call();
+ }
+ }
+
+ private static void runProbe(Path directory, String mode) throws Exception
{
+ String java = new File(System.getProperty("java.home"),
"bin/java").getAbsolutePath();
+ String classPath = System.getProperty("surefire.test.class.path",
System.getProperty("java.class.path"));
+ Path output = directory.resolve("probe-" + mode + ".log");
+ ProcessBuilder builder =
+ new ProcessBuilder(java, "-cp", classPath,
RepositoryProbe.class.getName(), directory.toString(), mode);
+ Map<String, String> environment = builder.environment();
+ environment.keySet().removeIf(name -> name.startsWith("GIT_"));
+ environment.put("GIT_CEILING_DIRECTORIES",
directory.getParent().toString());
+ if (mode.equals("work-tree")) {
+ environment.put("GIT_DIR", directory.resolve(".git").toString());
+ environment.put("GIT_WORK_TREE",
directory.resolve("alternate").toString());
+ } else if (mode.equals("index")) {
+ environment.put(
+ "GIT_INDEX_FILE",
directory.resolve("alternate.index").toString());
+ }
+ Process process = builder.redirectErrorStream(true)
+ .redirectOutput(output.toFile())
+ .start();
+ try {
+ if (!process.waitFor(30, TimeUnit.SECONDS)) {
+ process.destroyForcibly();
+ process.waitFor(5, TimeUnit.SECONDS);
+ throw new AssertionError("Repository probe timed out: " +
mode);
+ }
+ assertEquals(0, process.exitValue(), new
String(Files.readAllBytes(output), StandardCharsets.UTF_8));
+ } catch (InterruptedException e) {
+ process.destroyForcibly();
+ try {
+ process.waitFor(5, TimeUnit.SECONDS);
+ } catch (InterruptedException cleanupInterrupted) {
+ e.addSuppressed(cleanupInterrupted);
+ }
+ Thread.currentThread().interrupt();
+ throw e;
+ }
+ }
+
+ /** Exercises environment-dependent behavior without changing the test
JVM's global environment. */
+ public static class RepositoryProbe {
+ public static void main(String[] args) throws Exception {
+ Path directory = new File(args[0]).toPath();
+ String mode = args[1];
+ if (mode.equals("missing")) {
+ try (Git ignored = JGitUtils.openRepo(directory.toFile())) {
+ throw new AssertionError("A missing repository must not be
opened");
+ } catch (IllegalArgumentException expected) {
+ return;
+ }
+ }
+ File basedir = directory.toFile();
+ if (mode.equals("nested")) {
+ basedir = directory.resolve("nested").toFile();
+ } else if (mode.equals("git-directory")) {
+ basedir = directory.resolve(".git").toFile();
+ } else if (mode.equals("work-tree")) {
+ basedir = directory.resolve("alternate").toFile();
+ }
+ long initialOpenFiles =
WindowCacheStats.getStats().getOpenFileCount();
+ try (Git git = JGitUtils.openRepo(basedir)) {
+ Repository repository = git.getRepository();
+ assertEquals(
+ directory.resolve(".git").toFile().getCanonicalFile(),
+ repository.getDirectory().getCanonicalFile());
+ assertTrue(repository.getObjectDatabase().exists());
+ if (mode.equals("work-tree")) {
+ assertEquals(
+
directory.resolve("alternate").toFile().getCanonicalFile(),
+ repository.getWorkTree().getCanonicalFile());
+
assertTrue(git.status().call().getModified().contains("tracked.txt"));
+ } else {
+ assertEquals(
+ directory.toFile().getCanonicalFile(),
+ repository.getWorkTree().getCanonicalFile());
+ }
+ if (mode.equals("index")) {
+ assertEquals(
+
directory.resolve("alternate.index").toFile().getCanonicalFile(),
+ repository.getIndexFile().getCanonicalFile());
+ git.add().addFilepattern("tracked.txt").call();
+
assertTrue(git.status().call().getChanged().contains("tracked.txt"));
+ assertTrue(git.status().call().getModified().isEmpty());
+ }
+ if (mode.equals("close")) {
+ repository.open(repository.resolve("HEAD")).getBytes();
+ assertTrue(WindowCacheStats.getStats().getOpenFileCount()
> initialOpenFiles);
+ }
+ }
+ if (mode.equals("close")) {
+ assertEquals(initialOpenFiles,
WindowCacheStats.getStats().getOpenFileCount());
+ }
+ }
+ }
+}