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

The following examples show how to use org.eclipse.jgit.api.Git#wrap() . 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: DifferentFiles.java    From gitflow-incremental-builder with MIT License 6 votes vote down vote up
private Git setupGit(Configuration configuration) throws IOException {
    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File pomDir = mavenSession.getCurrentProject().getBasedir().toPath().toFile();
    builder.findGitDir(pomDir);
    if (builder.getGitDir() == null) {
        String gitDirNotFoundMessage = "Git repository root directory not found ascending from current working directory:'" + pomDir + "'.";
        logger.warn(gitDirNotFoundMessage + " Next step is determined by failOnMissingGitDir property.");
        if (configuration.failOnMissingGitDir) {
            throw new IllegalArgumentException(gitDirNotFoundMessage);
        } else {
            throw new SkipExecutionException(gitDirNotFoundMessage);
        }
    }
    if (isWorktree(builder)) {
        throw new SkipExecutionException(UNSUPPORTED_WORKTREE + builder.getGitDir());
    }
    return Git.wrap(builder.build());
}
 
Example 2
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testForCreateAnotationTag() throws GitAPIException, IOException {
    Git git = Git.wrap(repository);

    gitMgr.createTag(ws, "test", null, "test message", false);

    List<Ref> refs = git.tagList().call();
    assertEquals(1, refs.size());
    assertEquals("refs/tags/test", refs.get(0).getName());

    assertNotEquals(repository.resolve("HEAD"), refs.get(0).getObjectId());

    RevWalk walk = new RevWalk(repository);
    RevTag tag = walk.parseTag(refs.get(0).getObjectId());

    assertEquals("test message", tag.getFullMessage());
}
 
Example 3
Source File: GitCloneTest.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testGetCloneAndPull() throws Exception {
	// see bug 339254
	createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
	String workspaceId = getWorkspaceId(workspaceLocation);

	JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
	String contentLocation = clone(workspaceId, project).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

	JSONArray clonesArray = listClones(workspaceId, null);
	assertEquals(1, clonesArray.length());

	Repository r = getRepositoryForContentLocation(contentLocation);

	// overwrite user settings, do not rebase when pulling, see bug 372489
	StoredConfig cfg = r.getConfig();
	cfg.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants.CONFIG_KEY_REBASE, false);
	cfg.save();

	// TODO: replace with RESTful API when ready, see bug 339114
	Git git = Git.wrap(r);
	PullResult pullResult = git.pull().call();
	assertEquals(pullResult.getMergeResult().getMergeStatus(), MergeStatus.ALREADY_UP_TO_DATE);
	assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState());
}
 
Example 4
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testEmptyBlank() throws Exception {
    try (Git git = Git.wrap(repository)) {
        ws.write("testFile", "testFile", false, true, false);

        ws.mkdir("testDir");

        git.add().addFilepattern(".").call();

        CommitStatus status = gitMgr.getStatus(ws);

        assertEquals(1, status.getFiles().size());
    }
}
 
Example 5
Source File: GitMirrorTest.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Test
void remoteToLocal_submodule(TestInfo testInfo) throws Exception {
    pushMirrorSettings(null, null);

    // Create a new repository for a submodule.
    final String submoduleName = TestUtil.normalizedDisplayName(testInfo) + ".submodule";
    final File gitSubmoduleWorkTree =
            new File(gitRepoDir.getRoot().toFile(), submoduleName).getAbsoluteFile();
    final Repository gitSubmoduleRepo =
            new FileRepositoryBuilder().setWorkTree(gitSubmoduleWorkTree).build();
    createGitRepo(gitSubmoduleRepo);
    final Git gitSubmodule = Git.wrap(gitSubmoduleRepo);
    final String gitSubmoduleUri = "file://" +
             (gitSubmoduleWorkTree.getPath().startsWith(File.separator) ? "" : "/") +
             gitSubmoduleWorkTree.getPath().replace(File.separatorChar, '/') +
             "/.git";

    // Prepare the master branch of the submodule repository.
    addToGitIndex(gitSubmodule, gitSubmoduleWorkTree,
                  "in_submodule.txt", "This is a file in a submodule.");
    gitSubmodule.commit().setMessage("Initial commit").call();

    // Add the submodule.
    git.submoduleInit().call();
    git.submoduleAdd().setPath("submodule").setURI(gitSubmoduleUri).call();
    git.commit().setMessage("Add a new submodule").call();

    // Check the files under a submodule do not match nor trigger an 'unknown object' error.
    mirroringService.mirror().join();
    final Revision headRev = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    final Entry<JsonNode> expectedMirrorState = expectedMirrorState(headRev, "/");
    assertThat(client.getFiles(projName, REPO_FOO, Revision.HEAD, "/**").join().values())
            .containsExactly(expectedMirrorState);
}
 
Example 6
Source File: GitCloner.java    From smart-testing with Apache License 2.0 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());
        }
    }
}
 
Example 7
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testForCreateTagWithWithRef() throws GitAPIException, IOException {
    gitMgr.createTag(ws, "test", "branch1", null, false);

    Git git = Git.wrap(repository);

    List<Ref> refs = git.tagList().call();
    assertEquals(1, refs.size());
    assertEquals("refs/tags/test", refs.get(0).getName());

    assertEquals(repository.resolve("branch1"), refs.get(0).getObjectId());
}
 
Example 8
Source File: GitTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected void createRepository() throws IOException, GitAPIException, CoreException {
	IPath randomLocation = createTempDir();
	gitDir = randomLocation.toFile();
	randomLocation = randomLocation.addTrailingSeparator().append(Constants.DOT_GIT);
	File dotGitDir = randomLocation.toFile().getCanonicalFile();
	db = FileRepositoryBuilder.create(dotGitDir);
	toClose.add(db);
	assertFalse(dotGitDir.exists());
	db.create(false /* non bare */);

	testFile = new File(gitDir, "test.txt");
	testFile.createNewFile();
	createFile(testFile.toURI(), "test");
	File folder = new File(gitDir, "folder");
	folder.mkdir();
	File folderFile = new File(folder, "folder.txt");
	folderFile.createNewFile();
	createFile(folderFile.toURI(), "folder");

	Git git = Git.wrap(db);
	git.add().addFilepattern(".").call();
	git.commit().setMessage("Initial commit").call();

	// The system settings on eclipse.org was changed to receive.denyNonFastForward=true, see bug 343150.
	// Imitate the same setup when running tests locally, see bug 371881.
	StoredConfig cfg = db.getConfig();
	cfg.setBoolean("receive", null, "denyNonFastforwards", true);
	cfg.save();
}
 
Example 9
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testForResetWithMixed() throws Exception {
    try (Git git = Git.wrap(repository)) {

        writeFileAndCommit(git, "testReset", "testReset", "testReset");

        this.gitMgr.reset(ws, "HEAD~1", ResetType.MIXED);

        Status status = git.status().call();

        assertEquals(1, status.getUntracked().size());
        assertEquals(true, status.getUntracked().contains("testReset"));
    }
}
 
Example 10
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 11
Source File: GitMergeSquashTest.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void testMergeSquashRemovingFolders() throws Exception {
	// see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders()
	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());
		String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
		String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
		JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
		String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
		String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

		String folderName = "folder1";
		request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
		JSONObject folder1 = getChild(folder, "folder1");

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

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

		folderName = "folder2";
		request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
		JSONObject folder2 = getChild(folder, "folder2");

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

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

		request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		deleteFile(folder1);

		deleteFile(folder2);

		request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

		JSONArray commitsArray = log(gitHeadUri);
		assertEquals(3, commitsArray.length());
		JSONObject commit = commitsArray.getJSONObject(0);
		assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
		String toMerge = commit.getString(ProtocolConstants.KEY_NAME);
		commit = commitsArray.getJSONObject(1);
		assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
		String toCheckout = commit.getString(ProtocolConstants.KEY_NAME);

		Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
		Git git = Git.wrap(db1);
		git.checkout().setName(toCheckout).call();

		JSONObject merge = merge(gitHeadUri, toMerge, true);
		MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
		assertEquals(MergeStatus.FAST_FORWARD_SQUASHED, mergeResult);

		request = getGetRequest(folderChildrenLocation);
		response = webConversation.getResponse(request);
		assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
		List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));
		assertNull(getChildByName(children, "folder1"));
		assertNull(getChildByName(children, "folder2"));
	}
}
 
Example 12
Source File: Project.java    From onedev with MIT License 4 votes vote down vote up
public Git git() {
	return Git.wrap(getRepository()); 
}
 
Example 13
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testStateWithConflict() throws Exception {
    try (Git git = Git.wrap(repository)) {

        this.gitMgr.createBranch(ws, "rebaseBranch");
        this.gitMgr.checkout(ws, "rebaseBranch", null);

        writeFileAndCommit(git, "one", "rebase_one", "rebase one");

        this.gitMgr.checkout(ws, "master", null);

        writeFileAndCommit(git, "one", "one", "one");

        this.gitMgr.checkout(ws, "rebaseBranch", null);

        RebaseResponse response = this.gitMgr.rebase(ws, "master", false, false);

        assertEquals(STOPPED, response.getStatus());

        RepositoryState state = this.gitMgr.state(ws);
        assertEquals(RepositoryState.REBASING_MERGE, state);
    }
}
 
Example 14
Source File: PushJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example 15
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void checkoutStash() throws GitAPIException, IOException, GitOperationException {
    testStashCreate();

    assertStashListSize(1);

    Git git = Git.wrap(repository);

    String stashRef = "stash@{0}";
    String branch = "testCheckoutStash";

    gitMgr.checkoutStash(ws, stashRef, branch);

    assertStashListSize(0);

    assertEquals(branch, this.gitMgr.getBranch(ws));

    Status status = git.status().call();

    assertEquals(1, status.getAdded().size());
    assertEquals(true, status.getAdded().contains("test"));
}
 
Example 16
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void testCommitPartialWithMultiFile() throws IOException, GitAPIException {

    try (Git git = Git.wrap(repository)) {
        ws.write("test1", "this is test1 file", false, true, false);

        ws.write("test2", "This is test2 file", false, true, false);

        gitMgr.commit(ws, asList("test1", "test2"), "commit all");

        assertEquals(true, git.status().call().isClean());
    }
}
 
Example 17
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void testRebaseWithFastForward() throws IOException, GitAPIException, GitOperationException {
    try (Git git = Git.wrap(repository)) {

        this.gitMgr.createBranch(ws, "rebaseBranch");
        this.gitMgr.checkout(ws, "rebaseBranch", null);

        ws.write("two", "two", false, true, false);

        git.add().addFilepattern("two").call();

        git.commit().setMessage("rebase_two").call();

        this.gitMgr.checkout(ws, "master", null);

        ws.write("one", "one", false, true, false);

        git.add().addFilepattern("one").call();

        git.commit().setMessage("rebase_one").call();

        this.gitMgr.checkout(ws, "rebaseBranch", null);

        RebaseResponse response = this.gitMgr.rebase(ws, "master", false, false);

        assertEquals(OK, response.getStatus());
    }
}
 
Example 18
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void testLogWithDateFilter() throws IOException, GitAPIException, InterruptedException {
    PageRequest request = new PageRequest(0, 100);

    try (Git git = Git.wrap(repository)) {
        reCreateCleanRepo();

        RevCommit master1 = writeFileAndCommit(git, "master1", "master1", "master1");

        Thread.sleep(1000);

        RevCommit master2 = writeFileAndCommit(git, "master2", "master2", "master2");

        Thread.sleep(1000);

        RevCommit master3 = writeFileAndCommit(git, "master3", "master3", "master3");

        List<GitLog> logs = gitMgr.log(ws, null, null, null, null, 1000L * master2.getCommitTime(), request);

        assertEquals(2, logs.size());
        assertEquals(master2.name(), logs.get(0).getName());
        assertEquals(master1.name(), logs.get(1).getName());

        logs = gitMgr.log(ws, null, null, null, 1000L * master2.getCommitTime(), null, request);

        assertEquals(2, logs.size());
        assertEquals(master3.name(), logs.get(0).getName());
        assertEquals(master2.name(), logs.get(1).getName());

        logs = gitMgr.log(ws, null, null, null, 1000L * master2.getCommitTime(), 1000L * master2.getCommitTime(), request);

        assertEquals(1, logs.size());
        assertEquals(master2.name(), logs.get(0).getName());
    }
}
 
Example 19
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void testForResetWithHard() throws Exception {
    try (Git git = Git.wrap(repository)) {

        writeFileAndCommit(git, "testReset", "testReset", "testReset");

        this.gitMgr.reset(ws, "HEAD~1", ResetType.HARD);

        Status status = git.status().call();

        assertTrue(status.isClean());
    }
}
 
Example 20
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Test
public void testRebaseForInteractiveFixup() throws Exception {
    try (Git git = Git.wrap(repository)) {

        this.gitMgr.createBranch(ws, "rebase1");
        this.gitMgr.createBranch(ws, "rebase2");
        this.gitMgr.checkout(ws, "rebase1", null);

        writeFileAndCommit(git, "A", "add A", "A");

        this.gitMgr.checkout(ws, "rebase2", null);

        writeFileAndCommit(git, "B", "add B", "B");

        writeFileAndCommit(git, "C", "add C", "C");

        writeFileAndCommit(git, "D", "add D", "D");

        RebaseResponse response = this.gitMgr.rebase(ws, "rebase2", "rebase1", true, false);

        assertEquals(RebaseResponse.Status.INTERACTIVE_PREPARED, response.getStatus());

        // update rebase_todo
        List<RebaseResponse.RebaseTodoLine> lines = response.getRebaseTodoLines();

        lines.get(1).setAction(FIXUP);

        response = this.gitMgr.updateRebaseTodo(ws, lines);

        assertEquals(RebaseResponse.Status.OK, response.getStatus());
        assertEquals(true, response.isSuccess());

        Iterable<RevCommit> iterable = git.log().call();

        assertGitLogMessageEquals(iterable, "add D", "add B");
    }
}