package de.hftstuttgart.dtabackend.utils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.springframework.stereotype.Component; import org.springframework.util.FileSystemUtils; import java.io.File; import java.io.IOException; import java.util.regex.Matcher; @Component public class JGitUtil { private static final Logger LOG = LogManager.getLogger(JGitUtil.class); public JGitUtil() {} public void cloneRepository(Matcher config, String targetPath, String subDir) { LOG.debug(String.format("cloning repository: %s", config.group(1))); File targetDirectory = new File(targetPath); if (targetDirectory.exists()) { LOG.debug("clone target directory existing yet, deleting now"); FileSystemUtils.deleteRecursively(targetDirectory); } File checkoutDirectory = targetDirectory; //if an optional directory parameter was given if(subDir!="") { //create companion checkout dir "targetPath"+"_checkout" checkoutDirectory = new File(targetPath+"_checkout"); if (targetDirectory.exists()) { LOG.debug("clone checkout directory existing yet, deleting now"); FileSystemUtils.deleteRecursively(checkoutDirectory); } } try { LOG.debug("preparing clone"); CloneCommand cloneCommand = Git.cloneRepository() .setDirectory(checkoutDirectory) .setURI(config.group(1)); if (!config.group(2).equals("none") && !config.group(3).equals("none")) { LOG.debug("setting credentials"); cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(config.group(2), config.group(3))); } LOG.debug("cloning..."); cloneCommand.call().close(); //if an optional directory parameter was given if(subDir!="") { //copy appropriate path from checkout directory to target directory FileSystemUtils.copyRecursively(targetDirectory, new File(checkoutDirectory+subDir)); } } catch (IOException e) { LOG.error(String.format("Error while cloning from %s: could not copy to unit test dir", config.group(1)), e); } catch (GitAPIException e) { LOG.error(String.format("Error while cloning from %s: could not read from Git", config.group(1)), e); } LOG.debug(String.format("cloned from %s to %s", config.group(1), targetDirectory)); } }