org.eclipse.jgit.api.ResetCommand.ResetType Java Examples

The following examples show how to use org.eclipse.jgit.api.ResetCommand.ResetType. 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: ResetTask.java    From ant-git-tasks with Apache License 2.0 6 votes vote down vote up
/**
 * If mode is set, apply the specified mode according to Git manual.
 *
 * @antdoc.notrequired
 * @param mode the mode used to perform git reset. (Default is MIXED)
 */
public void setMode(String mode) {
        if ("soft".equalsIgnoreCase(mode)) {
                this.mode = ResetType.SOFT;
        } else if ("mixed".equalsIgnoreCase(mode)) {
                this.mode = ResetType.MIXED;
        } else if ("hard".equalsIgnoreCase(mode)) {
                this.mode = ResetType.HARD;
        } else if ("merge".equalsIgnoreCase(mode)) {
                this.mode = ResetType.MERGE;
        } else if ("keep".equalsIgnoreCase(mode)) {
                this.mode = ResetType.KEEP;
        } else {
                this.mode = ResetType.MIXED;
        }
}
 
Example #2
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 6 votes vote down vote up
public void reset(ProgressMonitor monitor) {
    try {
        // create branch and set upstream
        gitRepo.branchCreate()
                .setName(branch)
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
                .setStartPoint("origin/" + branch)
                .setForce(true)
                .call();
        
        // reset to remote head
        gitRepo.reset()
                .setProgressMonitor(monitor)
                .setMode(ResetType.SOFT)
                .setRef("refs/remotes/origin/" + branch)
                .call();
    } catch (Exception e) {
        logger.error("Exception caught while reseting to remote head: ", e);
    }
}
 
Example #3
Source File: GitSCM.java    From repositoryminer with Apache License 2.0 6 votes vote down vote up
@Override
public void checkout(String hash) {
	LOG.info(String.format("Checking out %s.", hash));
	File lockFile = new File(git.getRepository().getDirectory(), "git/index.lock");
	if (lockFile.exists()) {
		lockFile.delete();
	}

	try {
		git.reset().setMode(ResetType.HARD).call();
		git.checkout().setName("master").call();

		git.checkout().setCreateBranch(true).setName("rm_branch" + branchCounter++).setStartPoint(hash)
				.setForce(true).setOrphan(true).call();
	} catch (GitAPIException e) {
		close();
		throw new RepositoryMinerException(e);
	}
}
 
Example #4
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testResetNotImplemented() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);

	String projectName = getMethodName().concat("Project");
	JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

	JSONObject testTxt = getChild(project, "test.txt");
	modifyFile(testTxt, "hello");

	JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
	String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);

	WebRequest request = getPostGitIndexRequest(gitIndexUri, ResetType.KEEP);
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_NOT_IMPLEMENTED, response.getResponseCode());

	request = getPostGitIndexRequest(gitIndexUri, ResetType.MERGE);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_NOT_IMPLEMENTED, response.getResponseCode());
}
 
Example #5
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 #6
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 #7
Source File: MicroGitSync.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public void reset() throws Exception{
	logger.debug("begin git sync loop");
       File file = new File(localPath);
       if(!file.exists()){
           logger.debug("rep not exist");
       }
       String localRepo=localPath+"/.git";
       Git git = new Git(new FileRepository(localRepo));
       git.reset().setMode(ResetType.HARD).call();
       logger.debug("end git sync loop");
}
 
Example #8
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private void resetToBranch() throws IOException, GitAPIException {
	Ref master = repository.getRef(Constants.R_HEADS + "master");
	if (master != null) {
		Git git = new Git(repository);
		git.reset().setMode(ResetType.HARD).setRef(master.getName()).call();
	}
}
 
Example #9
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 #10
Source File: GitOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void reset(Project project, Branch branch) {

		logger.log(project, "git reset --hard origin/%s", branch);

		doWithGit(project, git -> {

			git.reset()//
					.setMode(ResetType.HARD)//
					.setRef("origin/".concat(branch.toString()))//
					.call();
		});
	}
 
Example #11
Source File: GitOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private void cherryPickCommitToBranch(ObjectId id, Project project, Branch branch) {

		doWithGit(project, git -> {

			try {
				checkout(project, branch);
			} catch (RuntimeException o_O) {

				logger.warn(project, "Couldn't check out branch %s. Skipping cherrypick of commit %s.", branch, id.getName());
				return;
			}

			logger.log(project, "git cp %s", id.getName());

			// Required as the CherryPick command has no setter for a CredentialsProvide *sigh*
			if (gpg.isGpgAvailable()) {
				CredentialsProvider.setDefault(new GpgPassphraseProvider(gpg));
			}

			CherryPickResult result = git.cherryPick().include(id).call();

			if (result.getStatus().equals(CherryPickStatus.OK)) {
				logger.log(project, "Successfully cherry-picked commit %s to branch %s.", id.getName(), branch);
			} else {
				logger.warn(project, "Cherry pick failed. aborting…");
				logger.log(project, "git reset --hard");
				git.reset().setMode(ResetType.HARD).call();
			}
		});
	}
 
Example #12
Source File: MicroGitSync.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public void reset() throws Exception{
	logger.debug("begin git sync loop");
       File file = new File(localPath);
       if(!file.exists()){
           logger.debug("rep not exist");
       }
       String localRepo=localPath+"/.git";
       Git git = new Git(new FileRepository(localRepo));
       git.reset().setMode(ResetType.HARD).call();
       logger.debug("end git sync loop");
}
 
Example #13
Source File: MergeBaseCalculatorTest.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testCalculateMergeBase() throws Exception {

    try (Git git = new Git(db);
            ObjectReader reader  = git.getRepository().newObjectReader()) {

        File repoDir = git.getRepository().getDirectory().getParentFile();

        File file = new File(repoDir, "file.txt");
        writeStringToFile(file, "hello\n");
        git.add()
            .addFilepattern(file.getName())
            .call();
        RevCommit baseCommit = doCommit(git);

        writeStringToFile(file, "hello world\n");
        git.add()
            .addFilepattern(file.getName())
            .call();
        RevCommit commit1 = doCommit(git);

        git.reset().setMode(ResetType.HARD).setRef(baseCommit.name()).call();

        writeStringToFile(file, "hello code\n");
        git.add()
            .addFilepattern(file.getName())
            .call();
        RevCommit commit2 = doCommit(git);

        String mergeBase = new MergeBaseCalculator()
            .calculateMergeBase(repoDir, commit1.name(), commit2.name());

        Assert.assertEquals(baseCommit.name(), mergeBase);
    }

}
 
Example #14
Source File: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 5 votes vote down vote up
/**
 * {@code git fetch} {@code git reset --hard origin}
 */
private void revert() {
	try {
		repo.fetch().call();
		repo.reset().setMode(ResetType.HARD).setRef(mergeUnit.getBranchTarget()).call();
	} catch (GitAPIException e) {
		LOGGER.log(Level.SEVERE, String.format("Could no revert repository '%s'.", repoPath), e); //$NON-NLS-1$
	}
}
 
Example #15
Source File: VersionControlGit.java    From mdw with Apache License 2.0 4 votes vote down vote up
public void hardReset() throws Exception {
    git.reset().setMode(ResetType.HARD).call();
    git.clean().call();
}
 
Example #16
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testResetToRemoteBranch() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject folder = new JSONObject(response.getText());

		JSONObject testTxt = getChild(folder, "test.txt");
		modifyFile(testTxt, "file change");
		addFile(testTxt);
		commitFile(testTxt, "message", false);

		// git section for the folder
		JSONObject folderGitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		String folderGitStatusUri = folderGitSection.getString(GitConstants.KEY_STATUS);
		String folderGitRemoteUri = folderGitSection.getString(GitConstants.KEY_REMOTE);

		assertStatus(StatusResult.CLEAN, folderGitStatusUri);

		JSONArray commitsArray = log(testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));
		assertEquals(2, commitsArray.length());

		JSONObject remoteBranch = getRemoteBranch(folderGitRemoteUri, 1, 0, Constants.MASTER);
		String remoteBranchIndexUri = remoteBranch.getString(GitConstants.KEY_INDEX);
		String remoteBranchName = remoteBranch.getString(ProtocolConstants.KEY_NAME);
		request = getPostGitIndexRequest(remoteBranchIndexUri, remoteBranchName, ResetType.HARD);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		assertStatus(StatusResult.CLEAN, folderGitStatusUri);

		commitsArray = log(testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD));
		assertEquals(1, commitsArray.length());
	}
}
 
Example #17
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@Ignore("see bug 339397")
public void testResetAutocrlfTrue() throws Exception {

	// "git config core.autocrlf true"
	Git git = Git.wrap(db);
	StoredConfig config = git.getRepository().getConfig();
	config.setBoolean(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, Boolean.TRUE);
	config.save();

	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);

	String projectName = getMethodName().concat("Project");
	JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());
	String projectId = project.getString(ProtocolConstants.KEY_ID);

	JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
	String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
	String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
	String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

	// CRLF
	JSONObject testTxt = getChild(project, "test.txt");
	modifyFile(testTxt, "f" + "\r\n" + "older");
	addFile(testTxt);

	// commit
	WebRequest request = GitCommitTest.getPostGitCommitRequest(gitCommitUri, "added new line - crlf", false);
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// assert there is nothing to commit
	assertStatus(StatusResult.CLEAN, gitStatusUri);

	// create new file
	String fileName = "new.txt";
	// TODO: don't create URIs out of thin air
	request = getPostFilesRequest(projectId + "/", getNewFileJSON(fileName).toString(), fileName);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
	JSONObject file = new JSONObject(response.getText());
	String location = file.optString(ProtocolConstants.KEY_LOCATION, null);
	assertNotNull(location);

	// LF
	JSONObject newTxt = getChild(project, "new.txt");
	modifyFile(newTxt, "i'm" + "\n" + "new");

	// "git add ."
	request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* stage all */);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	// reset
	request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED);
	response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	assertStatus(new StatusResult().setUntracked(1), gitStatusUri);
}
 
Example #18
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testResetHardAll() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject folder = new JSONObject(response.getText());

		JSONObject testTxt = getChild(folder, "test.txt");
		modifyFile(testTxt, "hello");

		String fileName = "new.txt";
		request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

		JSONObject folder1 = getChild(folder, "folder");
		JSONObject folderTxt = getChild(folder1, "folder.txt");
		deleteFile(folderTxt);

		JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
		String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);

		// "git status"
		assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri);

		// "git add ."
		request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* add all */);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// "git status"
		assertStatus(new StatusResult().setAdded(1).setChanged(1).setRemoved(1), gitStatusUri);

		// "git reset --hard HEAD"
		request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.HARD);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// "git status", should be clean, nothing to commit
		assertStatus(StatusResult.CLEAN, gitStatusUri);
	}
}
 
Example #19
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testResetMixedAll() throws Exception {
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	IPath[] clonePaths = createTestProjects(workspaceLocation);

	for (IPath clonePath : clonePaths) {
		// clone a  repo
		JSONObject clone = clone(clonePath);
		String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

		// get project/folder metadata
		WebRequest request = getGetRequest(cloneContentLocation);
		WebResponse response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		JSONObject folder = new JSONObject(response.getText());

		JSONObject testTxt = getChild(folder, "test.txt");
		modifyFile(testTxt, "hello");

		String fileName = "new.txt";
		request = getPostFilesRequest(folder.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

		JSONObject folder1 = getChild(folder, "folder");
		JSONObject folderTxt = getChild(folder1, "folder.txt");
		deleteFile(folderTxt);

		JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
		String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);

		// "git status"
		assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri);

		// "git add ."
		request = GitAddTest.getPutGitIndexRequest(gitIndexUri /* add all */);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// "git status"
		assertStatus(new StatusResult().setAdded(1).setChanged(1).setRemoved(1), gitStatusUri);

		// "git reset --mixed HEAD"
		request = getPostGitIndexRequest(gitIndexUri /* reset all */, ResetType.MIXED);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		// "git status", should be the same result as called for the first time
		assertStatus(new StatusResult().setMissing(1).setModified(1).setUntracked(1), gitStatusUri);
	}
}
 
Example #20
Source File: JGitEnvironmentRepositoryIntegrationTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
/**
 * Tests a special use case where the remote repository has been updated with a forced
 * push conflicting with the local repo of the Config Server. The Config Server has to
 * reset hard on the new reference because a simple pull operation could result in a
 * conflicting local repository.
 * @throws Exception when git related exception happens
 */
@Test
public void pullDirtyRepo() throws Exception {
	ConfigServerTestUtils.prepareLocalRepo();
	String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");

	// Create a remote bare repository.
	Repository remote = ConfigServerTestUtils.prepareBareRemote();

	Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
	StoredConfig config = git.getRepository().getConfig();
	config.setString("remote", "origin", "url",
			remote.getDirectory().getAbsolutePath());
	config.setString("remote", "origin", "fetch",
			"+refs/heads/*:refs/remotes/origin/*");
	config.save();

	// Pushes the raw branch to remote repository.
	git.push().call();

	String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator()
			.next().getName();

	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.run("--spring.cloud.config.server.git.uri=" + uri);

	JGitEnvironmentRepository repository = this.context
			.getBean(JGitEnvironmentRepository.class);

	// Fetches the repository for the first time.
	SearchPathLocator.Locations locations = repository.getLocations("bar", "test",
			"raw");
	assertThat(commitToRevertBeforePull).isEqualTo(locations.getVersion());

	// Resets to the original commit.
	git.reset().setMode(ResetType.HARD).setRef("master").call();

	// Generate a conflicting commit who will be forced on the origin.
	Path applicationFilePath = Paths
			.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml");

	Files.write(applicationFilePath,
			Arrays.asList("info:", "  foo: bar", "raw: false"),
			StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING);
	git.add().addFilepattern(".").call();
	git.commit().setMessage("Conflicting commit.").call();
	git.push().setForce(true).call();
	String conflictingCommit = git.log().setMaxCount(1).call().iterator().next()
			.getName();

	// Reset to the raw branch.
	git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call();

	// Triggers the repository refresh.
	locations = repository.getLocations("bar", "test", "raw");
	assertThat(conflictingCommit).isEqualTo(locations.getVersion());

	assertThat(git.status().call().isClean())
			.as("Local repository is not cleaned after retrieving resources.")
			.isTrue();
}
 
Example #21
Source File: GitMirrorTest.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Test
void remoteToLocal() throws Exception {
    pushMirrorSettings(null, null);

    final Revision rev0 = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();

    // Mirror an empty git repository, which will;
    // - Create /mirror_state.json
    // - Remove the sample files created by createProject().
    mirroringService.mirror().join();

    //// Make sure a new commit is added.
    final Revision rev1 = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    assertThat(rev1).isEqualTo(rev0.forward(1));

    //// Make sure /mirror_state.json exists (and nothing else.)
    final Entry<JsonNode> expectedInitialMirrorState = expectedMirrorState(rev1, "/");
    assertThat(client.getFiles(projName, REPO_FOO, rev1, "/**").join().values())
            .containsExactly(expectedInitialMirrorState);

    // Try to mirror again with no changes in the git repository.
    mirroringService.mirror().join();

    //// Make sure it does not try to produce an empty commit.
    final Revision rev2 = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    assertThat(rev2).isEqualTo(rev1);

    // Now, add some files to the git repository and mirror.
    //// This file should not be mirrored because it does not conform to CD's file naming rule.
    addToGitIndex(".gitkeep", "");
    addToGitIndex("first/light.txt", "26-Aug-2014");
    addToGitIndex("second/son.json", "{\"release_date\": \"21-Mar-2014\"}");
    git.commit().setMessage("Add the release dates of the 'Infamous' series").call();

    mirroringService.mirror().join();

    //// Make sure a new commit is added.
    final Revision rev3 = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    assertThat(rev3).isEqualTo(rev2.forward(1));

    //// Make sure the two files are all there.
    final Entry<JsonNode> expectedSecondMirrorState = expectedMirrorState(rev3, "/");
    assertThat(client.getFiles(projName, REPO_FOO, rev3, "/**").join().values())
            .containsExactlyInAnyOrder(expectedSecondMirrorState,
                                       Entry.ofDirectory(rev3, "/first"),
                                       Entry.ofText(rev3, "/first/light.txt", "26-Aug-2014\n"),
                                       Entry.ofDirectory(rev3, "/second"),
                                       Entry.ofJson(rev3, "/second/son.json",
                                                    "{\"release_date\": \"21-Mar-2014\"}"));

    // Rewrite the history of the git repository and mirror.
    git.reset().setMode(ResetType.HARD).setRef("HEAD^").call();
    addToGitIndex("final_fantasy_xv.txt", "29-Nov-2016");
    git.commit().setMessage("Add the release date of the 'Final Fantasy XV'").call();

    mirroringService.mirror().join();

    //// Make sure a new commit is added.
    final Revision rev4 = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    assertThat(rev4).isEqualTo(rev3.forward(1));

    //// Make sure the rewritten content is mirrored.
    final Entry<JsonNode> expectedThirdMirrorState = expectedMirrorState(rev4, "/");
    assertThat(client.getFiles(projName, REPO_FOO, rev4, "/**").join().values())
            .containsExactlyInAnyOrder(expectedThirdMirrorState,
                                       Entry.ofText(rev4, "/final_fantasy_xv.txt", "29-Nov-2016\n"));
}
 
Example #22
Source File: UIGit.java    From hop with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void resetHard() throws Exception {
  git.reset().setMode( ResetType.HARD ).call();
}
 
Example #23
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a request to reset index.
 * @param location
 * @param resetType 
 * @throws JSONException 
 * @throws UnsupportedEncodingException 
 */
static WebRequest getPostGitIndexRequest(String location, ResetType resetType) throws JSONException, UnsupportedEncodingException {
	return getPostGitIndexRequest(location, null, null, resetType.toString());
}
 
Example #24
Source File: GitResetTest.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Creates a request to reset HEAD to the given commit.
 * @param location
 * @param resetType 
 * @throws JSONException 
 * @throws UnsupportedEncodingException 
 */
private WebRequest getPostGitIndexRequest(String location, String commit, ResetType resetType) throws JSONException, UnsupportedEncodingException {
	return getPostGitIndexRequest(location, null, commit, resetType.toString());
}