GitRepository.java
package org.docascode.api.core.git;
import org.docascode.api.core.errors.DocAsCodeException;
import org.docascode.api.event.Event;
import org.docascode.api.listener.EventListener;
import org.eclipse.jgit.internal.storage.file.FileRepository;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class GitRepository extends FileRepository implements EventListener {
public GitRepository(Repository repo) throws IOException {
super(repo.getDirectory());
}
private File getHooksDir(){
StoredConfig config = getConfig();
String hooksPath = config.getString("core",null,"hookspath");
if (hooksPath == null){
return new File(getWorkTree(),".git/hooks/");
} else {
File hooksPathFile = new File(hooksPath);
if (hooksPathFile.isAbsolute()){
return hooksPathFile;
} else {
return new File(getWorkTree(),hooksPath);
}
}
}
public File getPreCommit() {
return new File(getHooksDir(),"pre-commit");
}
public File getPostCommit() {
return new File(getHooksDir(),"post-commit");
}
public File getProjectConfigFile()
{
return new File(getWorkTree(),".docascode/config");
}
public StoredConfig getProjectConfig()
{
return new FileBasedConfig(
getProjectConfigFile(),
FS.detect());
}
public boolean hasEmptyTree() throws DocAsCodeException {
ObjectId head;
try {
head = resolve("HEAD^{tree}");
} catch (IOException e) {
throw new DocAsCodeException("Unable to read Tree repository.",e);
}
return (head == null);
}
private File getPreviewLockFile(){
return new File(getWorkTree(),".git/amend-commit.lock");
}
public void lock() throws DocAsCodeException {
try {
if(!getPreviewLockFile().createNewFile()){
throw new DocAsCodeException("Unable to lock repository for preview.");
}
} catch (IOException e) {
throw new DocAsCodeException("Unable to lock repository for preview.",e);
}
}
public void unlock() throws DocAsCodeException {
try {
if (isLocked()) {
Files.delete(Paths.get(getPreviewLockFile().getAbsolutePath()));
}
} catch (IOException e) {
throw new DocAsCodeException("Unable to unlock repository for preview.",e);
}
}
public boolean isLocked(){
return getPreviewLockFile().exists();
}
public GitRepository addListener(org.docascode.api.listener.EventListener listener){
this.listeners.add(listener);
return this;
}
private List<EventListener> listeners = new ArrayList<>();
@Override
public void fireEvent(Event e){
for (EventListener l : this.listeners){
l.fireEvent(e);
}
}
}