|
| 1 | +package com.gitblit.internal; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.IOException; |
| 5 | +import java.util.Collection; |
| 6 | +import java.util.LinkedList; |
| 7 | + |
| 8 | +import org.apache.commons.io.FileUtils; |
| 9 | +import org.eclipse.jgit.api.Git; |
| 10 | +import org.eclipse.jgit.api.errors.GitAPIException; |
| 11 | +import org.eclipse.jgit.lib.Repository; |
| 12 | +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; |
| 13 | + |
| 14 | +public class GitUtils { |
| 15 | + private static final Collection<Repository> TEMP_REPOSITORIES = new LinkedList<>(); |
| 16 | + |
| 17 | + private GitUtils() { |
| 18 | + } |
| 19 | + |
| 20 | + public static Repository createNewRepository() throws IOException { |
| 21 | + final File repoDir = File.createTempFile("TestTempRepository", ""); |
| 22 | + if (!repoDir.delete()) { |
| 23 | + throw new IOException("Could not delete temporary file " + repoDir); |
| 24 | + } |
| 25 | + final Repository repository = FileRepositoryBuilder.create(new File( |
| 26 | + repoDir, ".git")); |
| 27 | + repository.create(); |
| 28 | + TEMP_REPOSITORIES.add(repository); |
| 29 | + return repository; |
| 30 | + } |
| 31 | + |
| 32 | + public static File addAnEmptyFileAndCommit(Repository repository, |
| 33 | + String fileName) throws IOException, GitAPIException { |
| 34 | + try (Git git = new Git(repository)) { |
| 35 | + final File file = new File(repository.getDirectory().getParent(), |
| 36 | + fileName); |
| 37 | + if (!file.getParentFile().exists() |
| 38 | + && !file.getParentFile().mkdirs()) { |
| 39 | + throw new IOException("Could not create directory " |
| 40 | + + file.getParentFile()); |
| 41 | + } |
| 42 | + if (!file.createNewFile()) { |
| 43 | + throw new IOException("Could not create file " + file); |
| 44 | + } |
| 45 | + git.add().addFilepattern(fileName).call(); |
| 46 | + git.commit().setMessage("add " + fileName).call(); |
| 47 | + return file; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + public static void clearTempRepositories() throws IOException { |
| 52 | + for (Repository repository : TEMP_REPOSITORIES) { |
| 53 | + FileUtils |
| 54 | + .deleteDirectory(repository.getDirectory().getParentFile()); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments