org.eclipse.jgit.api.ResetCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.ResetCommand. 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: GitRepository.java    From CardinalPGM with MIT License 6 votes vote down vote up
@Override
public void refreshRepo() throws RotationLoadException, IOException {
    try {
        if (git == null) {
            if (new File(getPath() + File.separator + ".git").exists())
                this.git = Git.open(new File(getPath()));
            else
                this.git = ((CloneCommand) addCredentials(
                        Git.cloneRepository().setURI(gitUrl.toString()).setDirectory(new File(getPath())))).call();
        }
        git.clean().call();
        addCredentials(git.fetch()).call();
        git.reset().setRef("@{upstream}").setMode(ResetCommand.ResetType.HARD).call();
    } catch (GitAPIException e) {
        e.printStackTrace();
        throw new RotationLoadException("Could not load git repository: " + gitUrl);
    }
    super.refreshRepo();
}
 
Example #2
Source File: JGitEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
private Ref resetHard(Git git, String label, String ref) {
	ResetCommand reset = git.reset();
	reset.setRef(ref);
	reset.setMode(ResetType.HARD);
	try {
		Ref resetRef = reset.call();
		if (resetRef != null) {
			this.logger.info(
					"Reset label " + label + " to version " + resetRef.getObjectId());
		}
		return resetRef;
	}
	catch (Exception ex) {
		String message = "Could not reset to remote for " + label + " (current ref="
				+ ref + "), remote: " + git.getRepository().getConfig()
						.getString("remote", "origin", "url");
		warn(message, ex);
		return null;
	}
}
 
Example #3
Source File: ContractProjectUpdaterTest.java    From spring-cloud-contract with Apache License 2.0 6 votes vote down vote up
@Test
public void should_push_changes_to_current_branch() throws Exception {
	File stubs = new File(
			GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());

	this.updater.updateContractProject("hello-world", stubs.toPath());

	// project, not origin, cause we're making one more clone of the local copy
	try (Git git = openGitProject(this.project)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage())
				.isEqualTo("Updating project [hello-world] with stubs");
		// I have no idea but the file gets deleted after pushing
		git.reset().setMode(ResetCommand.ResetType.HARD).call();
	}
	BDDAssertions.then(new File(this.project,
			"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
			.exists();
	BDDAssertions.then(this.gitRepo.gitFactory.provider).isNull();
	BDDAssertions.then(this.outputCapture.toString())
			.contains("No custom credentials provider will be set");
}
 
Example #4
Source File: DevicesGit.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void pullRepository() {
	try {
 	logger.info("Scanning devices folder for changes.");
 	git.add().addFilepattern(".").call();
 	Status status = git.status().call();
 	if (status.getChanged().size()>0 || status.getAdded().size()>0 || status.getModified().size()>0) {
 		logger.info("Changes have been found. Doing a hard reset (removing user modifications).");
 		ResetCommand reset = git.reset();
 		reset.setMode(ResetType.HARD);
 		reset.setRef(Constants.HEAD);
 		reset.call();
 	}
 	logger.info("Pulling changes from github.");
 	git.pull().call();
	} catch (NoHeadException e) {
		logger.info("Pull failed. Trying to clone repository instead");
		closeRepository();
		cloneRepository();
	}
	catch (Exception e1) {
		closeRepository();
	}
}
 
Example #5
Source File: DifferentFilesHttpFetchTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void fetch() throws Exception {
    addCommitToRemoteRepo(FETCH_FILE);
    projectProperties.setProperty(Property.fetchReferenceBranch.fullName(), "true");
    projectProperties.setProperty(Property.referenceBranch.fullName(), REMOTE_DEVELOP);

    invokeUnderTest();

    Git localGit = localRepoMock.getGit();
    localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    localGit.checkout().setName(REMOTE_DEVELOP).call();
    assertCommitExists(FETCH_FILE, localGit);
}
 
Example #6
Source File: ResetTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute() {
        try {
                ResetCommand resetCommand = git.reset();

                resetCommand.setMode(mode).call();
        } catch (Exception e) {
                throw new GitBuildException("Unexpected exception: " + e.getMessage(), e);
        }
}
 
Example #7
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean cancelFailedPull(String siteId) throws ServiceLayerException, CryptoException {
    logger.debug("To cancel failed pull, reset hard needs to be executed");
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    try (Git git = new Git(repo)) {
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
    } catch (GitAPIException e) {
        logger.error("Error while canceling failed pull for site " + siteId, e);
        throw new ServiceLayerException("Reset hard failed for site " + siteId, e);
    }
    return true;
}
 
Example #8
Source File: GitProjectRepo.java    From writelatex-git-bridge with MIT License 5 votes vote down vote up
public void resetHard() throws IOException {
    Git git = new Git(getJGitRepository());
    try {
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
    } catch (GitAPIException e) {
        throw new IOException(e);
    }
}
 
Example #9
Source File: GitConfigurationPersistenceResource.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void rollback() {
    super.rollback();
    try (Git git = repository.getGit()) {
        git.reset().setMode(ResetCommand.ResetType.HARD).setRef(Constants.HEAD).call();
    } catch (GitAPIException ex) {
        MGMT_OP_LOGGER.failedToStoreConfiguration(ex, file.getName());
    }
}
 
Example #10
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @throws GitAPIException
 * @throws IOException
 */
List<DiffEntry> getChanges() throws GitAPIException, IOException {
  // get tree for last processed commit
  ObjectId oldHeadTree = git.getRepository().resolve(this.lastProcessedGitHash + "^{tree}");

  // refresh to latest and reset hard to handle forced pushes
  this.git.fetch()
      .setRemote(REMOTE_NAME)
      .setCredentialsProvider(getCredentialsProvider())
      .setTransportConfigCallback(buildTransportConfigCallback())
      .call();
  // reset hard to get a clean working set since pull --rebase may leave files around
  this.git.reset().setMode(ResetCommand.ResetType.HARD).setRef(REMOTE_NAME + "/" + this.branchName).call();

  ObjectId head = this.git.getRepository().resolve("HEAD");
  ObjectId headTree = this.git.getRepository().resolve("HEAD^{tree}");

  // remember the hash for the current HEAD. This will be checkpointed after the diff is processed.
  latestGitHash = head.getName();

  // diff old and new heads to find changes
  ObjectReader reader = this.git.getRepository().newObjectReader();
  CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
  oldTreeIter.reset(reader, oldHeadTree);
  CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
  newTreeIter.reset(reader, headTree);

  return this.git.diff()
      .setNewTree(newTreeIter)
      .setOldTree(oldTreeIter)
      .setShowNameAndStatusOnly(true)
      .call();
}
 
Example #11
Source File: JGitOperator.java    From verigreen with Apache License 2.0 5 votes vote down vote up
public void reset(String refToResetTo) {
    
    ResetCommand command = _git.reset();
    command.setRef(refToResetTo);
    command.setMode(ResetType.HARD);
    try {
        command.call();
    } catch (Throwable e) {
        throw new RuntimeException(String.format("Failed to reset to [%s]", refToResetTo), e);
    }
}
 
Example #12
Source File: UpdateLocalRepositoryAdapter.java    From coderadar with MIT License 5 votes vote down vote up
private void resetRepository(String repositoryRoot) throws IOException, GitAPIException {
  FileRepositoryBuilder builder = new FileRepositoryBuilder();
  Repository repository;
  repository = builder.setWorkTree(new File(repositoryRoot)).build();
  Git git = new Git(repository);
  git.reset().setMode(ResetCommand.ResetType.HARD).call();
  git.getRepository().close();
  git.close();
}
 
Example #13
Source File: DifferentFilesSshFetchTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
private void test() throws Exception {
    addCommitToRemoteRepo(FETCH_FILE);
    projectProperties.setProperty(Property.fetchReferenceBranch.fullName(), "true");
    projectProperties.setProperty(Property.referenceBranch.fullName(), REMOTE_DEVELOP);

    invokeUnderTest();

    Git localGit = localRepoMock.getGit();
    localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    localGit.checkout().setName(REMOTE_DEVELOP).call();
    assertCommitExists(FETCH_FILE, localGit);
}
 
Example #14
Source File: DifferentFilesHttpFetchBasicAuthTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void fetch() throws Exception {
    addCommitToRemoteRepo(FETCH_FILE);
    projectProperties.setProperty(Property.fetchReferenceBranch.fullName(), "true");
    projectProperties.setProperty(Property.referenceBranch.fullName(), REMOTE_DEVELOP);
    Files.write(userHome.resolve(".git-credentials"), buildCredentialsFileContent().getBytes());

    invokeUnderTest();

    Git localGit = localRepoMock.getGit();
    localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    localGit.checkout().setName(REMOTE_DEVELOP).call();
    assertCommitExists(FETCH_FILE, localGit);
}
 
Example #15
Source File: LocalGitProvider.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void resetHard(List<String> rootDirPath) {
    File root = new File(fileSystemProvider.getURL(rootDirPath));

    try {
        Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
        new Git(repo).reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call();
        repo.close();
    } catch (IOException | GitAPIException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: DifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void fetchNonExistent() throws Exception {
    addCommitToRemoteRepo(FETCH_FILE);
    Git localGit = localRepoMock.getGit();
    localGit.branchDelete().setBranchNames(DEVELOP).call();
    localGit.branchDelete().setBranchNames(REMOTE_DEVELOP).call();
    projectProperties.setProperty(Property.fetchReferenceBranch.fullName(), "true");
    projectProperties.setProperty(Property.referenceBranch.fullName(), REMOTE_DEVELOP);

    invokeUnderTest();

    localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    localGit.checkout().setName(REMOTE_DEVELOP).call();
    assertCommitExists(FETCH_FILE, localGit);
}
 
Example #17
Source File: DifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void fetch() throws Exception {
    addCommitToRemoteRepo(FETCH_FILE);
    projectProperties.setProperty(Property.fetchReferenceBranch.fullName(), "true");
    projectProperties.setProperty(Property.referenceBranch.fullName(), REMOTE_DEVELOP);

    invokeUnderTest();

    Git localGit = localRepoMock.getGit();
    localGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    localGit.checkout().setName(REMOTE_DEVELOP).call();
    assertCommitExists(FETCH_FILE, localGit);
}
 
Example #18
Source File: DifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void listComparedToMergeBase() throws Exception {
    localRepoMock.getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
    localRepoMock.getGit().checkout().setName(REFS_HEADS_FEATURE_2).call();
    localRepoMock.getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
    projectProperties.setProperty(Property.baseBranch.fullName(), REFS_HEADS_FEATURE_2);
    projectProperties.setProperty(Property.compareToMergeBase.fullName(), "true");

    assertTrue(invokeUnderTest().stream().anyMatch(repoPath.resolve("parent/feature2-only-file.txt")::equals));

    verify(loggerSpy).info(contains("59dc82fa887d9ca82a0d3d1790c6d767e738e71a"));
}
 
Example #19
Source File: DifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
@Test
public void listWithCheckout() throws Exception {
    localRepoMock.getGit().reset().setRef(HEAD).setMode(ResetCommand.ResetType.HARD).call();
    projectProperties.setProperty(Property.baseBranch.fullName(), "refs/heads/feature/2");
    projectProperties.setProperty(Property.baseBranch.fullName(), "refs/heads/feature/2");

    invokeUnderTest();

    verify(loggerSpy).info(contains("Checking out base branch refs/heads/feature/2"));
}
 
Example #20
Source File: BaseDifferentFilesTest.java    From gitflow-incremental-builder with MIT License 5 votes vote down vote up
protected void addCommitToRemoteRepo(String newFileNameAndMessage) throws Exception {
    Git remoteGit = localRepoMock.getRemoteRepo().getGit();
    remoteGit.reset().setMode(ResetCommand.ResetType.HARD).call();
    remoteGit.checkout().setName(DEVELOP).call();
    remoteGit.getRepository().getDirectory().toPath().resolve(newFileNameAndMessage).toFile().createNewFile();
    remoteGit.add().addFilepattern(".").call();
    remoteGit.commit().setMessage(newFileNameAndMessage).call();
    assertCommitExists(newFileNameAndMessage, remoteGit);
}
 
Example #21
Source File: ContractProjectUpdaterTest.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void should_push_changes_to_current_branch_using_root_credentials()
		throws Exception {
	StubRunnerOptions options = new StubRunnerOptionsBuilder()
			.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
			.withStubsMode(StubRunnerProperties.StubsMode.REMOTE).withUsername("foo")
			.withPassword("bar").build();
	ContractProjectUpdater updater = new ContractProjectUpdater(options);
	File stubs = new File(
			GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());

	updater.updateContractProject("hello-world", stubs.toPath());

	// project, not origin, cause we're making one more clone of the local copy
	try (Git git = openGitProject(this.project)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage())
				.isEqualTo("Updating project [hello-world] with stubs");
		// I have no idea but the file gets deleted after pushing
		git.reset().setMode(ResetCommand.ResetType.HARD).call();
	}
	BDDAssertions.then(new File(this.project,
			"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
			.exists();
	BDDAssertions.then(this.outputCapture.toString()).contains(
			"Passed username and password - will set a custom credentials provider");
}
 
Example #22
Source File: ContractProjectUpdaterTest.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void should_push_changes_to_current_branch_using_credentials()
		throws Exception {
	StubRunnerOptions options = new StubRunnerOptionsBuilder()
			.withStubRepositoryRoot("file://" + this.project.getAbsolutePath() + "/")
			.withStubsMode(StubRunnerProperties.StubsMode.REMOTE)
			.withProperties(new HashMap<String, String>() {
				{
					put("git.username", "foo");
					put("git.password", "bar");
				}
			}).build();
	ContractProjectUpdater updater = new ContractProjectUpdater(options);
	File stubs = new File(
			GitRepoTests.class.getResource("/git_samples/sample_stubs").toURI());

	updater.updateContractProject("hello-world", stubs.toPath());

	// project, not origin, cause we're making one more clone of the local copy
	try (Git git = openGitProject(this.project)) {
		RevCommit revCommit = git.log().call().iterator().next();
		then(revCommit.getShortMessage())
				.isEqualTo("Updating project [hello-world] with stubs");
		// I have no idea but the file gets deleted after pushing
		git.reset().setMode(ResetCommand.ResetType.HARD).call();
	}
	BDDAssertions.then(new File(this.project,
			"META-INF/com.example/hello-world/0.0.2/mappings/someMapping.json"))
			.exists();
	BDDAssertions.then(this.outputCapture.toString()).contains(
			"Passed username and password - will set a custom credentials provider");
}
 
Example #23
Source File: GitRepo.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
void reset(File project) {
	try (Git git = this.gitFactory.open(file(project))) {
		git.reset().setMode(ResetCommand.ResetType.HARD).call();
	}
	catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #24
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 #25
Source File: AbstractSpringAcceptanceTests.java    From spring-cloud-release-tools with Apache License 2.0 5 votes vote down vote up
public void checkoutReleaseTrainBranch(String fileToRepo, String branch)
		throws GitAPIException, URISyntaxException {
	File file = file(fileToRepo);
	Git git = GitTestUtils.openGitProject(file);
	git.reset().setMode(ResetCommand.ResetType.HARD).call();
	if (new File(file, ".travis.yml").exists()) {
		new File(file, ".travis.yml").delete();
	}
	git.checkout().setForce(true).setName(branch).call();
}
 
Example #26
Source File: MavenIntegrationTest.java    From gitflow-incremental-builder with MIT License 4 votes vote down vote up
private void checkoutDevelop() throws GitAPIException, CheckoutConflictException, RefAlreadyExistsException,
        RefNotFoundException, InvalidRefNameException {
    Git git = localRepoMock.getGit();
    git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD").call();
    git.checkout().setName("develop").call();
}
 
Example #27
Source File: GitRepository.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Reset hard on HEAD.
 *
 * @throws GitAPIException
 */
public void rollback() throws GitAPIException {
    try (Git git = getGit()) {
        git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();
    }
}
 
Example #28
Source File: AppManager.java    From app-runner with MIT License 4 votes vote down vote up
private void gitUpdateFromOrigin() throws GitAPIException {
    git.fetch().setRemote("origin").setTimeout(REMOTE_GIT_TIMEOUT).call();
    git.reset().setMode(ResetCommand.ResetType.HARD).setRef("origin/master").call();
    this.contributors = getContributorsFromRepo();
}
 
Example #29
Source File: ThemeServiceImpl.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
private void pullFromGit(@NonNull ThemeProperty themeProperty) throws
    IOException, GitAPIException, URISyntaxException {
    Assert.notNull(themeProperty, "Theme property must not be null");

    // Get branch
    String branch = StringUtils.isBlank(themeProperty.getBranch()) ?
        DEFAULT_REMOTE_BRANCH : themeProperty.getBranch();

    Git git = null;

    try {
        git = GitUtils.openOrInit(Paths.get(themeProperty.getThemePath()));

        Repository repository = git.getRepository();

        RevWalk revWalk = new RevWalk(repository);

        Ref ref = repository.findRef(Constants.HEAD);

        Assert.notNull(ref, Constants.HEAD + " ref was not found!");

        RevCommit lastCommit = revWalk.parseCommit(ref.getObjectId());

        // Force to set remote name
        git.remoteRemove().setRemoteName(THEME_PROVIDER_REMOTE_NAME).call();
        RemoteConfig remoteConfig = git.remoteAdd()
            .setName(THEME_PROVIDER_REMOTE_NAME)
            .setUri(new URIish(themeProperty.getRepo()))
            .call();

        // Add all changes
        git.add()
            .addFilepattern(".")
            .call();
        // Commit the changes
        git.commit().setMessage("Commit by halo automatically").call();

        // Check out to specified branch
        if (!StringUtils.equalsIgnoreCase(branch, git.getRepository().getBranch())) {
            boolean present = git.branchList()
                .call()
                .stream()
                .map(Ref::getName)
                .anyMatch(name -> StringUtils.equalsIgnoreCase(name, branch));

            git.checkout()
                .setCreateBranch(true)
                .setForced(!present)
                .setName(branch)
                .call();
        }

        // Pull with rebasing
        PullResult pullResult = git.pull()
            .setRemote(remoteConfig.getName())
            .setRemoteBranchName(branch)
            .setRebase(true)
            .call();

        if (!pullResult.isSuccessful()) {
            log.debug("Rebase result: [{}]", pullResult.getRebaseResult());
            log.debug("Merge result: [{}]", pullResult.getMergeResult());

            throw new ThemeUpdateException("拉取失败!您与主题作者可能同时更改了同一个文件");
        }

        // updated successfully.
        ThemeProperty updatedThemeProperty = getProperty(Paths.get(themeProperty.getThemePath()));

        // Not support current halo version.
        if (StringUtils.isNotEmpty(updatedThemeProperty.getRequire()) && !VersionUtil.compareVersion(HaloConst.HALO_VERSION, updatedThemeProperty.getRequire())) {
            // reset theme version
            git.reset()
                .setMode(ResetCommand.ResetType.HARD)
                .setRef(lastCommit.getName())
                .call();
            throw new ThemeNotSupportException("新版本主题仅支持 Halo " + updatedThemeProperty.getRequire() + " 以上的版本");
        }
    } finally {
        GitUtils.closeQuietly(git);
    }

}