Java Code Examples for org.eclipse.jgit.api.Git#close()

The following examples show how to use org.eclipse.jgit.api.Git#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GithubApi.java    From karamel with Apache License 2.0 6 votes vote down vote up
/**
 * Scaffolds a Karamel/chef project for an experiment and adds it to the github repo. You still need to commit and
 * push the changes to github.
 *
 * @param repoName
 * @throws KaramelException
 */
public static void scaffoldRepo(String repoName) throws KaramelException {
  File repoDir = getRepoDirectory(repoName);

  Git git = null;
  try {
    git = Git.open(repoDir);

    CookbookScaffolder.create(repoName);

    git.add().addFilepattern("Berksfile").addFilepattern("metadata.rb")
        .addFilepattern("Karamelfile")
        .addFilepattern(".kitchen.yml").addFilepattern("attributes").addFilepattern("recipes")
        .addFilepattern("templates").addFilepattern("README.md").call();

  } catch (IOException | GitAPIException ex) {
    throw new KaramelException("Problem scaffolding a new Repository: " + ex.getMessage());
  } finally {
    if (git != null) {
      git.close();
    }
  }
}
 
Example 2
Source File: GitManager.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Date getDateForRevision(VcsRepository repository, String revision) throws Exception {
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	walk.parseCommit(iterator.next());
	
	Date date = null;
	while (iterator.hasNext()) {
		RevCommit commit = iterator.next();
		if (commit.getId().getName().equals(revision)) {
			date = new Date(Long.valueOf(commit.getCommitTime())*1000); 
		}
	}
	
	repo.close();
	git.close();

	return date;
}
 
Example 3
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
private Ref checkoutBranch(File projectDir, String branch) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	CheckoutCommand command = git.checkout().setName(branch);
	try {
		if (shouldTrack(git, branch)) {
			trackBranch(command, branch);
		}
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example 4
Source File: GitManager.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getFirstRevision(VcsRepository repository) throws Exception {
	Git git = getGit((GitRepository)repository);
	
	Repository repo = git.getRepository();
	RevWalk walk = new RevWalk(repo);
	
	Iterator<RevCommit> iterator = git.log().call().iterator();
	walk.parseCommit(iterator.next());
	
	String revision = null;
	
	// The commits are ordered latest first, so we want the last one.
	while(iterator.hasNext()) { 
		RevCommit commit = iterator.next();
		if (!iterator.hasNext()) {
			revision = commit.getId().getName();
		}
	}
	
	repo.close();
	git.close();
	
	return revision;
}
 
Example 5
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
/**
 * Clones the project.
 * @param projectUri - URI of the project
 * @return file where the project was cloned
 */
File cloneProject(URI projectUri) {
	try {
		log.info("Cloning repo from [" + projectUri + "] to [" + this.basedir + "]");
		Git git = cloneToBasedir(projectUri, this.basedir);
		if (git != null) {
			git.close();
		}
		File clonedRepo = git.getRepository().getWorkTree();
		log.info("Cloned repo to [" + clonedRepo + "]");
		return clonedRepo;
	}
	catch (Exception e) {
		throw new IllegalStateException("Exception occurred while cloning repo", e);
	}
}
 
Example 6
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Clones the project.
 * @param projectUri - URI of the project
 * @return file where the project was cloned
 */
File cloneProject(URIish projectUri) {
	try {
		log.info("Cloning repo from [{}] to [{}]", projectUri,
				humanishDestination(projectUri, this.basedir));
		Git git = cloneToBasedir(projectUri, this.basedir);
		if (git != null) {
			git.close();
		}
		File clonedRepo = git.getRepository().getWorkTree();
		log.info("Cloned repo to [{}]", clonedRepo);
		return clonedRepo;
	}
	catch (Exception e) {
		throw new IllegalStateException("Exception occurred while cloning repo", e);
	}
}
 
Example 7
Source File: JGitEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
/**
 * Clones the remote repository and then opens a connection to it.
 * @throws GitAPIException when cloning fails
 * @throws IOException when repo opening fails
 */
private void initClonedRepository() throws GitAPIException, IOException {
	if (!getUri().startsWith(FILE_URI_PREFIX)) {
		deleteBaseDirIfExists();
		Git git = cloneToBasedir();
		if (git != null) {
			git.close();
		}
		git = openGitRepository();
		if (git != null) {
			git.close();
		}
	}

}
 
Example 8
Source File: GitFXGsonUtil.java    From GitFx with Apache License 2.0 5 votes vote down vote up
public static boolean cloneGitRepository(String repoURL,String localPath){
        try{
        Git result = Git.cloneRepository()
                .setURI(repoURL)
                .setDirectory(new File(localPath))
                .call();
        result.close();
        return true;
        }
        catch(GitAPIException e){
//[LOG]            logger.debug("Error creating Git repository",e.getMessage());
            return false;
        }
    }
 
Example 9
Source File: GitManager.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
@Override
	public String[] getRevisionsForDate(VcsRepository repository, Date date) throws Exception {
		long epoch = date.toJavaDate().getTime();
		
		List<String> revisions = new ArrayList<String>();
		
		Git git = getGit((GitRepository)repository);
		
		Repository repo = git.getRepository();
		RevWalk walk = new RevWalk(repo);
		
		Iterator<RevCommit> iterator = git.log().call().iterator();
		
		boolean foundDate = false;
		while(iterator.hasNext()) { 
			RevCommit commit = walk.parseCommit(iterator.next());
			
//			System.out.println(Long.valueOf(commit.getCommitTime())*1000 + " == " + epoch); 
//			System.err.println("comparing " +new Date(Long.valueOf(commit.getCommitTime())*1000) + " with date " + date + " and epoch " + epoch);
			if (new Date(Long.valueOf(commit.getCommitTime())*1000).compareTo(date) == 0) {
				foundDate = true;
				revisions.add(0, commit.getId().getName());
				//FIXME: Added the zero index to in an attempt to bugfix
			} else if (foundDate) {
				break;
			}
		}
		
		repo.close();
		git.close();
		
		return revisions.toArray(new String[revisions.size()]);
	}
 
Example 10
Source File: GitFXGsonUtil.java    From GitFx with Apache License 2.0 5 votes vote down vote up
public static void initializeGitRepository(String serverName,
            String projectName,String projectPath){
        try{
        File localPath = new File(projectPath);
        Git git;
                git = Git.init().setDirectory(localPath).call();
        git.close();
        }
        catch(GitAPIException e){
//[LOG]            logger.debug("Error creating Git repository",e.getMessage());
        }
    }
 
Example 11
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private Ref reset(File projectDir) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	ResetCommand command = git.reset().setMode(ResetCommand.ResetType.HARD);
	try {
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example 12
Source File: GitRepo.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
private FetchResult fetch(File projectDir) throws GitAPIException {
	Git git = this.gitFactory.open(projectDir);
	FetchCommand command = git.fetch();
	try {
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
	finally {
		git.close();
	}
}
 
Example 13
Source File: GithubApi.java    From karamel with Apache License 2.0 5 votes vote down vote up
/**
 * Clone an existing github repo.
 *
 * @param owner
 * @param repoName
 * @throws se.kth.karamel.common.exception.KaramelException
 */
public synchronized static void cloneRepo(String owner, String repoName) throws KaramelException {
  Git result = null;
  try {
    RepositoryService rs = new RepositoryService(client);
    Repository r = rs.getRepository(owner, repoName);

    String cloneURL = r.getSshUrl();
    // prepare a new folder for the cloned repository
    File localPath = new File(Settings.COOKBOOKS_PATH + File.separator + repoName);
    if (localPath.isDirectory() == false) {
      localPath.mkdirs();
    } else {
      throw new KaramelException("Local directory already exists. Delete it first: " + localPath);
    }

    logger.debug("Cloning from " + cloneURL + " to " + localPath);
    result = Git.cloneRepository()
        .setURI(cloneURL)
        .setDirectory(localPath)
        .call();
    // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks!
    logger.debug("Cloned repository: " + result.getRepository().getDirectory());
  } catch (IOException | GitAPIException ex) {
    throw new KaramelException("Problem cloning repo: " + ex.getMessage());
  } finally {
    if (result != null) {
      result.close();
    }
  }

}
 
Example 14
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private String currentBranch(File projectDir) {
	Git git = this.gitFactory.open(projectDir);
	try {
		return git.getRepository().getBranch();
	}
	catch (IOException e) {
		throw new IllegalStateException(e);
	}
	finally {
		git.close();
	}
}
 
Example 15
Source File: GitUtils.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
public static File cloneRepBySSh(String remoteUri, String tempFolder, String branch, String user, String passwd,
		String pathprivatekey, String pathPubkey) {
	File file = new File(tempFolder);
	if (file.exists()) {
		deleteFolder(file);
	}
	file.mkdirs();

	Git gitc = cloneRepositoryGit(user, branch, remoteUri, file, passwd, pathprivatekey, pathPubkey);
	// cloneGit = gitc;
	if (gitc != null) {
		gitc.close();
	}
	return file;
}
 
Example 16
Source File: WalkCommitTreeAdapter.java    From coderadar with MIT License 5 votes vote down vote up
@Override
public void walkCommitTree(
    String projectRoot, String name, WalkTreeCommandInterface commandInterface)
    throws UnableToWalkCommitTreeException {
  try {
    Git git = Git.open(new File(projectRoot));
    ObjectId commitId = git.getRepository().resolve(name);

    RevWalk walk = new RevWalk(git.getRepository());
    RevCommit commit = walk.parseCommit(commitId);
    RevTree tree = commit.getTree();
    TreeWalk treeWalk = new TreeWalk(git.getRepository());
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);

    while (treeWalk.next()) {
      if (!treeWalk.getPathString().endsWith(".java")
          || treeWalk.getPathString().contains("build")
          || treeWalk.getPathString().contains("out")
          || treeWalk.getPathString().contains("classes")
          || treeWalk.getPathString().contains("node_modules")
          || treeWalk.getPathString().contains("test")) {
        continue;
      }
      commandInterface.walkMethod(treeWalk.getPathString());
    }
    git.close();
  } catch (IOException e) {
    throw new UnableToWalkCommitTreeException(e.getMessage());
  }
}
 
Example 17
Source File: PipelineHookTriggerHandlerImplTest.java    From gitlab-plugin with GNU General Public License v2.0 4 votes vote down vote up
@Before
public void setup() throws IOException, GitAPIException {

    List<String> allowedStates = new ArrayList<>();
    allowedStates.add("success");

    User user = new User();
    user.setName("test");
    user.setId(1);

    Git.init().setDirectory(tmp.getRoot()).call();
    tmp.newFile("test");
    Git git = Git.open(tmp.getRoot());
    git.add().addFilepattern("test");
    git.commit().setMessage("test").call();
    ObjectId head = git.getRepository().resolve(Constants.HEAD);

    pipelineHookTriggerHandler = new PipelineHookTriggerHandlerImpl(allowedStates);
    pipelineHook = pipelineHook()
        .withUser(user)
        .withRepository(repository()
            .withName("test")
            .withHomepage("https://gitlab.org/test")
            .withUrl("[email protected]:test.git")
            .withGitSshUrl("[email protected]:test.git")
            .withGitHttpUrl("https://gitlab.org/test.git")
            .build())
        .withProject(project()
            .withNamespace("test-namespace")
            .withWebUrl("https://gitlab.org/test")
            .withId(1)
            .build())
        .withObjectAttributes(pipelineEventObjectAttributes()
            .withId(1)
            .withStatus("success")
            .withSha("bcbb5ec396a2c0f828686f14fac9b80b780504f2")
            .withStages(new ArrayList<String>())
            .withRef("refs/heads/" + git.nameRev().add(head).call().get(head))
            .build())

        .build();
    git.close();
}
 
Example 18
Source File: RepositorySearcher.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
private RepositoryClone cloneRepo(Repository repository) {

		RepositoryClone repositoryCloneInst = new RepositoryClone();

		final String CLONE_SOURCE = repository.getUrl() + ".git";

		final File CLONE_PARENT_DESTINATION = TechAnalysisProperties.CLONE_PARENT_DESTINATION;

		final File CLONE_REPO_DESTINATION = new File(CLONE_PARENT_DESTINATION + File.separator
				+ createUniqueFolderForRepo(repository.getName(), repository.getUrl()));

		//
		workflow.log(CrossflowLogger.SEVERITY.INFO, "cloning: " + CLONE_SOURCE);
		workflow.log(CrossflowLogger.SEVERITY.INFO, "into: " + CLONE_REPO_DESTINATION);
		//

		String clonedRepoLocalPath = CLONE_REPO_DESTINATION.getPath();

		repositoryCloneInst.setUrl(repository.getUrl());
		repositoryCloneInst.setName(repository.getName());
		repositoryCloneInst.setLocalPath(clonedRepoLocalPath);

		try {
			// clean local clone parent destination if it exists
			if (CLONE_PARENT_DESTINATION.exists()) {
				if (replace) {
					FileUtils.deleteDirectory(CLONE_PARENT_DESTINATION);
					workflow.log(CrossflowLogger.SEVERITY.INFO, "Successfully cleaned local clone parent destination: "
							+ CLONE_PARENT_DESTINATION.getAbsolutePath());
					CLONE_PARENT_DESTINATION.mkdir();
				} else {
					// System.out.println("Parent Directory exists, leaving it
					// unchanged.");
				}
			} else
				CLONE_PARENT_DESTINATION.mkdir();

			//
			if (CLONE_REPO_DESTINATION.exists() && !replace) {
				workflow.log(CrossflowLogger.SEVERITY.INFO,
						"Repo already exists and replace is false, not doing anything...");
				return repositoryCloneInst;
			}

			// create local clone destination
			if (!CLONE_REPO_DESTINATION.exists()) {
				CLONE_REPO_DESTINATION.mkdir();
				System.out.println("Successfully created local repository clone destination for specified repository: "
						+ CLONE_REPO_DESTINATION.getAbsolutePath());
			}
			Git git = Git.cloneRepository().setURI(CLONE_SOURCE).setDirectory(CLONE_REPO_DESTINATION).call();
			git.close();
			workflow.log(CrossflowLogger.SEVERITY.INFO,
					"Successfully cloned specified repo to local clone destination: "
							+ CLONE_REPO_DESTINATION.getAbsolutePath());

		} catch (Exception e) {
			workflow.log(CrossflowLogger.SEVERITY.ERROR, "Error in creating clone:");
			workflow.log(CrossflowLogger.SEVERITY.ERROR, "Repo name chars: ");
			for (char c : CLONE_REPO_DESTINATION.getPath().toCharArray())
				workflow.log(CrossflowLogger.SEVERITY.ERROR, c + " | ");
			workflow.log(CrossflowLogger.SEVERITY.ERROR, "");
			e.printStackTrace();
		}

		return repositoryCloneInst;

	}
 
Example 19
Source File: GetDiffEntriesForCommitsAdapter.java    From coderadar with MIT License 4 votes vote down vote up
@Override
public List<DiffEntry> getDiffs(String projectRoot, String commitName1, String commitName2)
    throws UnableToGetDiffsFromCommitsException {
  try {
    Git git = Git.open(new File(projectRoot));
    Repository repository = git.getRepository();
    RevCommit commit1 = repository.parseCommit(ObjectId.fromString(commitName1));
    RevCommit commit2 = repository.parseCommit(ObjectId.fromString(commitName2));
    // change commits so that commit2 is the older one
    if (commit1.getCommitTime() > commit2.getCommitTime()) {
      RevCommit tmp = commit1;
      commit1 = commit2;
      commit2 = tmp;
    }

    ObjectReader reader = git.getRepository().newObjectReader();

    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    ObjectId oldTree = commit1.getTree();
    oldTreeIter.reset(reader, oldTree);

    CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
    ObjectId newTree = commit2.getTree();
    newTreeIter.reset(reader, newTree);

    DiffFormatter df = new DiffFormatter(new ByteArrayOutputStream());
    df.setRepository(repository);
    List<DiffEntry> entries =
        df.scan(oldTreeIter, newTreeIter).stream()
            .map(
                diffEntry -> {
                  DiffEntry entry = new DiffEntry();
                  entry.setNewPath(diffEntry.getNewPath());
                  entry.setOldPath(diffEntry.getOldPath());
                  entry.setChangeType(
                      ChangeTypeMapper.jgitToCoderadar(diffEntry.getChangeType()).ordinal());
                  return entry;
                })
            .collect(Collectors.toList());
    git.close();
    return entries;
  } catch (IOException e) {
    throw new UnableToGetDiffsFromCommitsException(e.getMessage());
  }
}
 
Example 20
Source File: DeleteRepositoryAdapterTest.java    From coderadar with MIT License 4 votes vote down vote up
@BeforeEach
public void setUp() throws GitAPIException {
  Git git = Git.cloneRepository().setURI(testRepoURL.toString()).setDirectory(folder).call();
  git.close();
}