Java Code Examples for org.eclipse.jgit.api.errors.GitAPIException

The following are top voted examples for showing how to use org.eclipse.jgit.api.errors.GitAPIException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: warrior-jenkins-plugin   File: WarriorPluginBuilder.java   View source code 9 votes vote down vote up
@Override
public Boolean invoke(File file, VirtualChannel channel){
    try{
        Git git = Git.cloneRepository()
                .setURI(url)
                .setDirectory(localDir)
                .setTransportConfigCallback(getTransportConfigCallback())
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password))
                .call();

        // Default branch to checkout is master
        if(branch==null || branch.isEmpty()){
            branch = "master";
        } else if (cloneType.equals("branch")){
            branch = "origin" + File.separator + branch;
        }
        git.checkout().setName(branch).call();
        git.close();
        }catch(GitAPIException e){
            status = false;
            e.printStackTrace(listener.getLogger());
        }
    return status;
}
 
Example 2
Project: wherehowsX   File: GitUtil.java   View source code 6 votes vote down vote up
/**
 * Cloning the remote git repo to local directory
 * @param remoteUri remote git url e.g. git://gitli.example.com/project/repo.git
 * @param localDir local destination clone directory
 * @throws IOException
 * @throws GitAPIException
 */
public static void clone(String remoteUri, String localDir) throws IOException, GitAPIException {
  //create local git directory
  File localGitRepo = new File(localDir);
  if (localGitRepo.exists()) {
    if (localGitRepo.isDirectory()) {
      // clean up directory
      FileUtils.cleanDirectory(localGitRepo);
    } else {
      throw new IOException("File exists: " + localDir);
    }
  } else {
    localGitRepo.mkdirs();
  }

  Git g = Git.cloneRepository().setURI(remoteUri).setDirectory(localGitRepo).call();
  g.close();
}
 
Example 3
Project: incubator-netbeans   File: BlameCommand.java   View source code 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    org.eclipse.jgit.api.BlameCommand cmd = new Git(repository).blame();
    cmd.setFilePath(Utils.getRelativePath(getRepository().getWorkTree(), file));
    if (revision != null) {
        cmd.setStartCommit(Utils.findCommit(repository, revision));
    } else if (repository.getConfig().get(WorkingTreeOptions.KEY).getAutoCRLF() != CoreConfig.AutoCRLF.FALSE) {
        // work-around for autocrlf
        cmd.setTextComparator(new AutoCRLFComparator());
    }
    cmd.setFollowFileRenames(true);
    try {
        BlameResult cmdResult = cmd.call();
        if (cmdResult != null) {
            result = getClassFactory().createBlameResult(cmdResult, repository);
        }
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example 4
Project: gmds   File: Branches.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException {
        Repository repo = Commands.getRepo(Consts.META_REPO_PATH);

        Git git = new Git(repo);

        // Create a new branch
        git.branchCreate().setName("newBranch").call();
// Checkout the new branch
        git.checkout().setName("newBranch").call();
        // List the existing branches
        List<Ref> listRefsBranches = git.branchList().setListMode(ListMode.ALL).call();
        listRefsBranches.forEach((refBranch) -> {
            System.out.println("Branch : " + refBranch.getName());
        });
// Go back on "master" branch and remove the created one
        git.checkout().setName("master");
        git.branchDelete().setBranchNames("newBranch");
    }
 
Example 5
Project: incubator-netbeans   File: CreateTagCommand.java   View source code 6 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    try {
        RevObject obj = Utils.findObject(repository, taggedObject);
        TagCommand cmd = new Git(repository).tag();
        cmd.setName(tagName);
        cmd.setForceUpdate(forceUpdate);
        cmd.setObjectId(obj);
        cmd.setAnnotated(message != null && !message.isEmpty() || signed);
        if (cmd.isAnnotated()) {
            cmd.setMessage(message);
            cmd.setSigned(signed);
        }
        cmd.call();
        ListTagCommand tagCmd = new ListTagCommand(repository, getClassFactory(), false, new DelegatingGitProgressMonitor(monitor));
        tagCmd.run();
        Map<String, GitTag> tags = tagCmd.getTags();
        tag = tags.get(tagName);
    } catch (JGitInternalException | GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example 6
Project: gmds   File: RefList.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException {
    
    Repository repo = new FileRepository(Consts.META_REPO_PATH + ".git");
    
    // get a list of all known heads, tags, remotes, ...
    Collection<Ref> allRefs = repo.getAllRefs().values();

    // a RevWalk allows to walk over commits based on some filtering that is defined
    try (RevWalk revWalk = new RevWalk(repo)) {
        for (Ref ref : allRefs) {
            revWalk.markStart(revWalk.parseCommit(ref.getObjectId()));
        }
        System.out.println("Walking all commits starting with " + allRefs.size() + " refs: " + allRefs);
        int count = 0;
        for (RevCommit commit : revWalk) {
            System.out.println("Commit: " + commit);
            count++;
        }
        System.out.println("Had " + count + " commits");
    }
}
 
Example 7
Project: spring-cloud-release-tools   File: GitRepo.java   View source code 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 8
Project: gmds   File: Diffs.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException, GitAPIException {

        Repository repo = Commands.getRepo(Consts.META_REPO_PATH);

        // Get the id of the tree associated to the two commits
        ObjectId head = repo.resolve("HEAD^{tree}");
        ObjectId previousHead = repo.resolve("HEAD~^{tree}");

        List<DiffEntry> list = listDiffs(repo, previousHead, head);
        if(list != null){            
            // Simply display the diff between the two commits
            list.forEach((diff) -> {
                System.out.println(diff);
            });
        }
    }
 
Example 9
Project: smart-testing   File: GitCloner.java   View source code 6 votes vote down vote up
public Repository cloneRepositoryToTempFolder(boolean checkoutAll) throws GitAPIException, IOException {
    this.targetFolder = createTempFolder(repositoryName);
    final Repository repository = Git.cloneRepository()
                .setURI(repositoryUrl)
                .setDirectory(targetFolder)
                .setCloneAllBranches(true)
                .setBranch("master")
            .call()
        .getRepository();

    if (checkoutAll) {
        checkoutAllBranches(repository);
    }

    LOGGER.info("Cloned test repository to: " + targetFolder);
    return repository;
}
 
Example 10
Project: smart-testing   File: ChangeApplier.java   View source code 6 votes vote down vote up
private void applyStashChangesLocally(List<RevCommit> stashesToApply) throws GitAPIException {
    RevCommit tmpCommit = null;
    // We cannot just apply changes from stash one after the other
    // as git will complain about uncommitted changes when trying
    // to apply second consecutive stash.
    // So we create temporary commits to overcome this issue
    // and reset softly on the way to have it all as local changes
    for (final RevCommit stash : stashesToApply) {
        if (stash == null){
            continue;
        }
        git.stashApply().setStashRef(stash.getName()).call();
        if (tmpCommit != null) {
            git.reset().setRef(ONE_BACK).setMode(SOFT).call();
        }
        tmpCommit = createTemporaryCommit();
    }
    if (tmpCommit != null) {
        git.reset().setRef(ONE_BACK).setMode(SOFT).call();
    }
    git.stashDrop().setAll(true).call();
}
 
Example 11
Project: smart-testing   File: NewTestsGitBasedDetectorTest.java   View source code 6 votes vote down vote up
@Test
public void should_find_local_newly_staged_files_as_new() throws IOException, GitAPIException {
    //given
    Configuration configuration = createConfiguration("a4261d5", "1ee4abf");
    final File testFile = gitFolder.newFile("core/src/test/java/org/arquillian/smart/testing/CalculatorTest.java");
    Files.write(testFile.toPath(), getContentsOfClass().getBytes(), StandardOpenOption.APPEND);

    GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.getAbsolutePath());

    final NewTestsDetector newTestsDetector =
        new NewTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(), path -> true, configuration);

    // when
    final Collection<TestSelection> newTests = newTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.CalculatorTest",
            "org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest");
}
 
Example 12
Project: smart-testing   File: ChangedTestsDetectorTest.java   View source code 6 votes vote down vote up
@Test
public void should_find_modified_staged_tests_as_changed() throws IOException, GitAPIException {
    //given
    Configuration configuration = createConfiguration("7699c2c", "04d04fe");
    final Path testFile = Paths.get(gitFolder.getRoot().getAbsolutePath(),
        "core/src/test/java/org/arquillian/smart/testing/FilesTest.java");
    Files.write(testFile, "//This is a test".getBytes(), StandardOpenOption.APPEND);
    GitRepositoryOperations.addFile(gitFolder.getRoot(), testFile.toString());

    final ChangedTestsDetector changedTestsDetector =
        new ChangedTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(),
            className -> className.endsWith("Test"), configuration);

    // when
    final Collection<TestSelection> newTests = changedTestsDetector.getTests();

    // then
    assertThat(newTests).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest",
            "org.arquillian.smart.testing.FilesTest");
}
 
Example 13
Project: smart-testing   File: GitChangeResolverTest.java   View source code 6 votes vote down vote up
@Test
public void should_fetch_all_untracked_files_for_first_commit() throws IOException, GitAPIException {
    // given
    final File parent = gitFolder.newFolder("parent");
    final File newGitFolder = parent.getParentFile();

    gitFolder.newFile("parent/foo.txt");

    try (Git git = Git.init()
        .setDirectory(newGitFolder)
        .call()) {
    }

    this.gitChangeResolver = new GitChangeResolver();

    // when
    final Set<Change> untrackedChanges = gitChangeResolver.diff(newGitFolder, "HEAD~0", "HEAD");

    // then
    assertThat(untrackedChanges).hasSize(1).extracting(Change::getLocation, Change::getChangeType).containsOnly(tuple(
        relative("parent/foo.txt"), ChangeType.ADD));
}
 
Example 14
Project: oxygen-git-plugin   File: GitAccessPushTest.java   View source code 6 votes vote down vote up
@Test
public void testPushOK()
		throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected {
	gitAccess.setRepository(LOCAL_TEST_REPOSITPRY);
	final StoredConfig config = gitAccess.getRepository().getConfig();
	RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
	URIish uri = new URIish(db2.getDirectory().toURI().toURL());
	remoteConfig.addURI(uri);
	remoteConfig.update(config);
	config.save();

	gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt"));
	gitAccess.commit("file test added");

	gitAccess.push("", "");

	assertEquals(db1.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"),
			db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"));

}
 
Example 15
Project: gitplex-mit   File: Project.java   View source code 6 votes vote down vote up
public void deleteTag(String tag) {
  	String refName = GitUtils.tag2ref(tag);
  	ObjectId commitId = getRevCommit(refName).getId();
  	try {
	git().tagDelete().setTags(tag).call();
} catch (GitAPIException e) {
	throw new RuntimeException(e);
}
  	Subject subject = SecurityUtils.getSubject();
  	GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {

	@Override
	public void run() {
		ThreadContext.bind(subject);
		try {
			Project project = GitPlex.getInstance(ProjectManager.class).load(getId());
			GitPlex.getInstance(ListenerRegistry.class).post(
					new RefUpdated(project, refName, commitId, ObjectId.zeroId()));
		} finally {
			ThreadContext.unbindSubject();
		}
	}
  		
  	});
  }
 
Example 16
Project: flow-platform   File: JGitBasedClient.java   View source code 6 votes vote down vote up
@Override
public File clone(String branch, boolean noCheckout) throws GitException {
    checkGitUrl();

    CloneCommand cloneCommand = Git.cloneRepository()
        .setURI(gitUrl)
        .setNoCheckout(noCheckout)
        .setBranch(branch)
        .setDirectory(targetDir.toFile());

    try (Git git = buildCommand(cloneCommand).call()) {
        return git.getRepository().getDirectory();
    } catch (GitAPIException e) {
        throw new GitException("Fail to clone git repo", e);
    }
}
 
Example 17
Project: flow-platform   File: JGitBasedClient.java   View source code 6 votes vote down vote up
@Override
public List<String> tags() throws GitException {
    try {
        Collection<Ref> refs = buildCommand(Git.lsRemoteRepository()
            .setTags(true)
            .setTimeout(GIT_TRANS_TIMEOUT)
            .setRemote(gitUrl)).call();


        List<Ref> listRefs = Lists.newArrayList(refs);
        listRefs.sort(JGitUtil.REF_COMPARATOR);

        return JGitUtil.simpleRef(refs);
    } catch (GitAPIException e) {
        throw new GitException("Fail to list tags from remote repo", ExceptionUtil.findRootCause(e));
    }
}
 
Example 18
Project: oxygen-git-plugin   File: GitAccessPushTest.java   View source code 6 votes vote down vote up
@Test(expected = MissingObjectException.class)
public void testRemoteRepositoryHasNoCommitst()
		throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected {
	gitAccess.setRepository(LOCAL_TEST_REPOSITPRY);
	final StoredConfig config = gitAccess.getRepository().getConfig();
	RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
	URIish uri = new URIish(db2.getDirectory().toURI().toURL());
	remoteConfig.addURI(uri);
	remoteConfig.update(config);
	config.save();

	gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt"));
	gitAccess.commit("file test added");

	// throws missingObjectException
	db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}");
}
 
Example 19
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Creates a blank new Repository.
 * 
 * @param path
 *          - A string that specifies the git Repository folder
 */
public void createNewRepository(String path) {
   if (git != null) {
     // Stop intercepting authentication requests.
     AuthenticationInterceptor.unbind(getHostName());
     git.close();
   }

	try {
		git = Git.init().setBare(false).setDirectory(new File(path)).call();
	} catch (IllegalStateException | GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
	
	fireRepositoryChanged();
}
 
Example 20
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Returns for the given submodule the SHA-1 commit id for the Index if the
 * given index boolean is <code>true</code> or the SHA-1 commit id for the
 * HEAD if the given index boolean is <code>false</code>
 * 
 * @param submodulePath
 *          - the path to get the submodule
 * @param index
 *          - boolean to determine what commit id to return
 * @return the SHA-1 id
 */
public ObjectId submoduleCompare(String submodulePath, boolean index) {
	try {
		SubmoduleStatus submoduleStatus = git.submoduleStatus().addPath(submodulePath).call().get(submodulePath);
		if (submoduleStatus != null) {
		  if (index) {
		    return submoduleStatus.getIndexId();
		  } else {
		    return submoduleStatus.getHeadId();
		  }
		}
	} catch (GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
	return null;
}
 
Example 21
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Adds a single file to the staging area. Preparing it for commit
 * 
 * @param file
 *          - the name of the file to be added
 */
public void add(FileStatus file) {
	try {
		if (file.getChangeType().equals(GitChangeType.REMOVED)) {
			git.rm().addFilepattern(file.getFileLocation()).call();
		} else {
			git.add().addFilepattern(file.getFileLocation()).call();
		}
		
		fireFileStateChanged(new ChangeEvent(GitCommand.STAGE, getPaths(Arrays.asList(file))));
	} catch (GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
}
 
Example 22
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Gets the conflicting file from the git status
 * 
 * @return the conflicting files list
 */
public List<FileStatus> getConflictingFiles() {
	if (git != null) {
		try {
			Status status = git.status().call();
			List<FileStatus> stagedFiles = new ArrayList<FileStatus>();
			for (String fileName : status.getConflicting()) {
				stagedFiles.add(new FileStatus(GitChangeType.CONFLICT, fileName));
			}

			return stagedFiles;
		} catch (GitAPIException e) {
			if (logger.isDebugEnabled()) {
				logger.debug(e, e);
			}
		}
	}

	return new ArrayList<FileStatus>();
}
 
Example 23
Project: oxygen-git-plugin   File: GitAccess.java   View source code 6 votes vote down vote up
/**
 * Reset all the specified files from the staging area.
 * 
 * @param fileNames
 *          - the list of file to be removed
 */
public void resetAll(List<FileStatus> files) {
	try {
		if (!files.isEmpty()) {
			ResetCommand reset = git.reset();
			for (FileStatus file : files) {
				reset.addPath(file.getFileLocation());

			}
			reset.call();
		}
		
     fireFileStateChanged(new ChangeEvent(GitCommand.UNSTAGE, getPaths(files)));
     
	} catch (GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(e, e);
		}
	}
}
 
Example 24
Project: incubator-netbeans   File: SubmoduleInitializeCommand.java   View source code 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    File workTree = repository.getWorkTree();
    org.eclipse.jgit.api.SubmoduleInitCommand cmd = new Git(repository).submoduleInit();
    for (String path : Utils.getRelativePaths(workTree, roots)) {
        cmd.addPath(path);
    }
    try {
        cmd.call();
        statusCmd.run();
    } catch (GitAPIException | JGitInternalException ex) {
        throw new GitException(ex);
    }
}
 
Example 25
Project: incubator-netbeans   File: StashSaveCommand.java   View source code 5 votes vote down vote up
@Override
protected void run () throws GitException {
    Repository repository = getRepository();
    try {
        StashCreateCommand cmd = new Git(repository).stashCreate()
                .setIncludeUntracked(includeUntracked)
                .setWorkingDirectoryMessage(message);
        RevCommit commit = cmd.call();
        this.stash = getClassFactory().createRevisionInfo(commit, repository);
    } catch (GitAPIException ex) {
        throw new GitException(ex);
    }
}
 
Example 26
Project: gocd-phabricator-staging-material   File: JGitWrapperIntegrationTest.java   View source code 5 votes vote down vote up
private Path defaultRepository() throws java.io.IOException, GitAPIException {
    Path repositoryPath = uninitializedRepository();
    Files.createFile(repositoryPath.resolve("file1"));
    Files.createFile(repositoryPath.resolve("file2"));
    org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.init().setDirectory(repositoryPath.toFile()).call();
    git.add().addFilepattern("file1").call();
    git.commit().setMessage( "Create file1" ).call();
    git.tag().setName("phabricator/base/1").setAnnotated(false).call();
    git.tag().setName("phabricator/diff/1").setAnnotated(false).call();
    git.add().addFilepattern("file2").call();
    git.commit().setMessage( "Create file2").call();
    git.tag().setName("phabricator/base/2").setAnnotated(false).call();
    git.tag().setName("phabricator/diff/2").setAnnotated(false).call();
    git.branchCreate().setName("branch1").call();
    git.branchCreate().setName("branch2").call();

    git.checkout().setName("branch1").call();
    Files.createFile(repositoryPath.resolve("file3"));
    git.add().addFilepattern("file3").call();
    git.commit().setMessage( "Create file3" ).call();

    git.checkout().setName("branch2").call();
    Files.createFile(repositoryPath.resolve("file4"));
    git.add().addFilepattern("file4").call();
    git.commit().setMessage( "Create file4" ).call();
    return repositoryPath;
}
 
Example 27
Project: pdi-git-plugin   File: UIGit.java   View source code 5 votes vote down vote up
@Override
public void removeRemote() {
  RemoteRemoveCommand cmd = git.remoteRemove();
  cmd.setName( Constants.DEFAULT_REMOTE_NAME );
  try {
    cmd.call();
  } catch ( GitAPIException e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
}
 
Example 28
Project: launcher-backend   File: AbstractGitRepoStep.java   View source code 5 votes vote down vote up
public static void importNewGitProject(UserDetails userDetails, File basedir, String message, String gitUrl, String branch, String origin, Logger logger) throws GitAPIException {
    GitUtils.disableSslCertificateChecks();
    InitCommand initCommand = Git.init();
    initCommand.setDirectory(basedir);
    Git git = initCommand.call();
    logger.info("Initialised an empty git configuration repo at {}", basedir.getAbsolutePath());
    gitAddCommitAndPush(git, gitUrl, userDetails, basedir, message, branch, origin, logger);
}
 
Example 29
Project: launcher-backend   File: AbstractGitRepoStep.java   View source code 5 votes vote down vote up
private static void gitAddCommitAndPush(Git git, String gitUrl, UserDetails userDetails, File basedir, String message, String branch, String origin, Logger logger) throws GitAPIException {
    PersonIdent personIdent = userDetails.createPersonIdent();

    GitUtils.configureBranch(git, branch, origin, gitUrl);
    GitUtils.addDummyFileToEmptyFolders(basedir);
    logger.info("About to git commit and push to: " + gitUrl + " and remote name " + origin);
    int retryCount = 5;
    for (int i = retryCount; i > 0; i--) {
        if (i < retryCount) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
        try {
            GitUtils.doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message, true);
            return;
        } catch (TransportException e) {
            if (i <= 1) {
                throw e;
            } else {
                logger.info("Caught a transport exception: " + e + " so retrying");
            }
        }
    }
}
 
Example 30
Project: launcher-backend   File: GitProvider.java   View source code 5 votes vote down vote up
public Git cloneRepo(CloneRepoAttributes attributes) throws GitAPIException {
    CloneCommand command = Git.cloneRepository();
    String gitUri = attributes.getUri();

    UserDetails userDetails = attributes.getUserDetails();
    CredentialsProvider credentialsProvider = userDetails.createCredentialsProvider();
    GitUtils.configureCommand(command, credentialsProvider, userDetails.getSshPrivateKey(), userDetails.getSshPublicKey());

    command = command.setCredentialsProvider(credentialsProvider).
            setCloneAllBranches(attributes.isCloneAll()).
            setURI(gitUri).
            setDirectory(attributes.getDirectory()).setRemote(attributes.getRemote());

    return command.call();
}
 
Example 31
Project: spring-cloud-release-tools   File: GitRepo.java   View source code 5 votes vote down vote up
private void printLog(Git git) throws GitAPIException, IOException {
	int maxCount = 5;
	String currentBranch = git.getRepository().getBranch();
	log.info("Printing [{}] last commits for branch [{}]", maxCount, currentBranch);
	Iterable<RevCommit> commits = git.log().setMaxCount(maxCount).call();
	for (RevCommit commit : commits) {
		log.info("Name [{}], msg [{}]", commit.getId().name(), commit.getShortMessage());
	}
}
 
Example 32
Project: spring-cloud-release-tools   File: GitRepo.java   View source code 5 votes vote down vote up
private Git cloneToBasedir(URI projectUrl, File destinationFolder)
		throws GitAPIException {
	CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository()
			.setURI(projectUrl.toString() + ".git").setDirectory(destinationFolder);
	try {
		return command.call();
	}
	catch (GitAPIException e) {
		deleteBaseDirIfExists();
		throw e;
	}
}
 
Example 33
Project: spring-cloud-release-tools   File: GitRepo.java   View source code 5 votes vote down vote up
private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode)
		throws GitAPIException {
	ListBranchCommand command = git.branchList();
	if (listMode != null) {
		command.setListMode(listMode);
	}
	List<Ref> branches = command.call();
	for (Ref ref : branches) {
		if (ref.getName().endsWith("/" + label)) {
			return true;
		}
	}
	return false;
}
 
Example 34
Project: spring-cloud-release-tools   File: GitTestUtils.java   View source code 5 votes vote down vote up
public static void setOriginOnProjectToTmp(File origin, File project)
		throws GitAPIException, MalformedURLException {
	try(Git git = openGitProject(project)) {
		RemoteRemoveCommand remove = git.remoteRemove();
		remove.setName("origin");
		remove.call();
		RemoteSetUrlCommand command = git.remoteSetUrl();
		command.setUri(new URIish(origin.toURI().toURL()));
		command.setName("origin");
		command.setPush(true);
		command.call();
	}
}
 
Example 35
Project: oxygen-git-plugin   File: GitAccessPushTest.java   View source code 5 votes vote down vote up
@Test
public void testNoPushesAhead() throws RepositoryNotFoundException, IOException, URISyntaxException, NoRepositorySelected, InvalidRemoteException, TransportException, GitAPIException{
	gitAccess.setRepository(LOCAL_TEST_REPOSITPRY);
	final StoredConfig config = gitAccess.getRepository().getConfig();
	RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
	URIish uri = new URIish(db2.getDirectory().toURI().toURL());
	remoteConfig.addURI(uri);
	remoteConfig.update(config);
	config.save();

	int actual = gitAccess.getPushesAhead();
	int expected = 0;
	
	assertEquals(expected, actual);
}
 
Example 36
Project: oxygen-git-plugin   File: GitAccess.java   View source code 5 votes vote down vote up
/**
 * Return the submodule head commit to the previously one
 */
public void discardSubmodule() {
	try {
		git.submoduleSync().call();
		git.submoduleUpdate().setStrategy(MergeStrategy.RECURSIVE).call();
	} catch (GitAPIException e) {
		if (logger.isDebugEnabled()) {
			logger.debug(END_FETCH_DEBUG_MESSAGE);
		}
	}
}
 
Example 37
Project: cf-mta-deploy-service   File: GitRepoCloner.java   View source code 5 votes vote down vote up
public void cloneRepo(final String gitUri, final Path repoDir) throws InvalidRemoteException, GitAPIException, IOException {
    if (Files.exists(repoDir)) {
        LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString());
        com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir);
    }

    configureGitSslValidation();
    if (shoudlUseToken(gitServiceUrlString, gitUri)) {
        cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token));
    }
    if (refName != null && !refName.isEmpty()) {
        String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName;
        cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName }));
        cloneCommand.setBranch(fullRefName);
    }
    cloneCommand.setTimeout(290);
    cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile());
    cloneCommand.setURI(gitUri);
    LOGGER.debug(
        MessageFormat.format("cloning repo with url {0} in repo dir {1} ref '{2}'", gitUri, repoDir.toAbsolutePath().toString()));
    try (Git callInstance = cloneCommand.call()) {
        Repository repo = callInstance.getRepository();
        repo.close();
    } catch (TransportException e) {
        Throwable cause1 = e.getCause();
        if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) {
            throw new SLException(cause1.getCause(), "Failed to establish ssl connection"); // NOSONAR
        }
        throw e;
    }
}
 
Example 38
Project: smart-testing   File: LazilyLoadedRepository.java   View source code 5 votes vote down vote up
void cloneRepository() {
    try {
        if (!repository.isPresent()) {
            this.repository = Optional.of(gitCloner.cloneRepositoryToTempFolder(true));
        }
    } catch (GitAPIException | IOException e) {
        throw new RuntimeException("Failed cloning repository [" + gitCloner.getRepositoryName() + ", " + gitCloner.getRepositoryUrl() + "].", e);
    }

}
 
Example 39
Project: smart-testing   File: AfterReceivePackResetFilter.java   View source code 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
    chain.doFilter(request, response);
    try {
        for (final LazilyLoadedRepository repository : repositories) {
            Git.wrap(repository.get()).reset().setMode(HARD).call();
        }
    } catch (GitAPIException e) {
        throw new ServletException(e);
    }
}
 
Example 40
Project: smart-testing   File: GitCloner.java   View source code 5 votes vote down vote up
private void checkoutAllBranches(Repository repository) throws GitAPIException {
    final Git git = Git.wrap(repository);
    for (final Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.REMOTE).call()) {
        final String refName = ref.getName();
        final String branchName = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            git.checkout().setCreateBranch(true).setName(branchName).setStartPoint("origin/" + branchName).call();
        } catch (RefAlreadyExistsException e) {
            LOGGER.warning("Already exists, so ignoring " + e.getMessage());
        }
    }
}