org.eclipse.jgit.api.MergeCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.MergeCommand. 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 netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the repository configuration file and returns the default fast-forward merge
 * option set for the repository and its current branch.
 * 
 * @return the default fast-forward option for the current repository and the active branch.
 * @throws GitException an error occurs
 * @since 1.26
 */
public FastForwardOption getDefaultFastForwardOption () throws GitException {
    JGitRepository repository = getRepository();
    repository.increaseClientUsage();
    try {
        MergeConfig cfg = MergeConfig.getConfigForCurrentBranch(repository.getRepository());
        MergeCommand.FastForwardMode mode = cfg.getFastForwardMode();
        switch (mode) {
            case FF_ONLY:
                return FastForwardOption.FAST_FORWARD_ONLY;
            case NO_FF:
                return FastForwardOption.NO_FAST_FORWARD;
            default:
                return FastForwardOption.FAST_FORWARD;
        }
    } finally {
        repository.decreaseClientUsage();
    }
}
 
Example #2
Source File: NearestPolicyWithEqualDistanceTest.java    From jgitver with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the following repository.
 * <pre>
 * *   600a017 - (HEAD -> master) D :: merge C into B (17 seconds ago) <Matthieu Brouillard>
 * |\
 * | * eea9071 - (tag: 2.0, br) content C (17 seconds ago) <Matthieu Brouillard>
 * |/
 * * f57604c - (tag: 1.0) content B (17 seconds ago) <Matthieu Brouillard>
 * * 0cece48 - content A (17 seconds ago) <Matthieu Brouillard>
 * </pre>
 * @return the built scenario
 */
private static Scenarios.Scenario buildScenario() {
    Scenarios.ScenarioBuilder builder = new Scenarios.ScenarioBuilder();

    builder.commit("content", "A")
            .commit("content", "B")
            .branchOnAppId("br", "B")
            .commit("content", "C")
            .master()
            .merge("C", "D", MergeCommand.FastForwardMode.NO_FF);

    builder.tag("1.0", "B");

    // wait 2 seconds
    mute(() -> Thread.sleep(TimeUnit.SECONDS.toMillis(2)));

    builder.tag("2.0", "C");

    return builder.getScenario();
}
 
Example #3
Source File: Scenarios.java    From jgitver with Apache License 2.0 6 votes vote down vote up
/**
 * Merges commit with id given as parameter with current branch using given FastForwardMode.
 * @param sourceId the application identifier to use as merge source
 * @param id the application identifier to use to store the git commitID of merge commit
 * @param mode the non null fast forward strategy to use for the merge
 * @return the builder itself to continue building the scenario
 */
public ScenarioBuilder merge(String sourceId, String id, MergeCommand.FastForwardMode mode) {
    try {
        ObjectId other = scenario.getCommits().get(sourceId);
        ObjectId head = repository.resolve(Constants.HEAD);
        String nameOfHead = scenario.nameOf(head);
        MergeResult rc = git.merge()
                .setFastForward(mode)
                .setMessage(String.format("%s :: merge %s into %s", id, sourceId, nameOfHead))
                .include(other)
                .call();
        scenario.getCommits().put(id, rc.getNewHead());
    } catch (Exception ex) {
        throw new IllegalStateException(String.format("error merging %s", id), ex);
    }
    return this;
}
 
Example #4
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
public Pair<Boolean, String> merge(String branchToUpdate, String branchHead, boolean commit) {
    
    Pair<Boolean, String> ret = new Pair<>(false, "");
    MergeCommand command = _git.merge();
    try {
        String refName =
                !branchHead.contains(REFS_HEADS) ? REFS_REMOTES + branchHead : branchHead;
        command.include(_repo.getRef(refName));
        command.setCommit(commit);
        MergeResult mergeResult = command.call();
        ret = checkResult(branchToUpdate, branchHead, ret, mergeResult);
    } catch (Throwable e) {
        VerigreenLogger.get().log(
                getClass().getName(),
                RuntimeUtils.getCurrentMethodName(),
                String.format(
                        "Failed to update branch [%s] with parent branch [%s]",
                        branchToUpdate,
                        branchHead));
    }
    
    return ret;
}
 
Example #5
Source File: StudioNodeSyncGlobalRepoTask.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(Constants.MASTER);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS + Constants.MASTER);
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            mergeCommand.call();
        }
    }

    Files.delete(tempKey);
}
 
Example #6
Source File: GitMapSourceFactory.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Iterator<? extends MapSource> loadNewSources() throws MapMissingException {
  try {
    git.pull()
        .setCredentialsProvider(credentials)
        .setFastForward(MergeCommand.FastForwardMode.FF)
        .call();
  } catch (GitAPIException e) {
    throw new MapMissingException(
        git.getRepository().getDirectory().getPath(), e.getMessage(), e.getCause());
  }

  return Iterators.emptyIterator();
}
 
Example #7
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
public void updateChanges(ProgressMonitor monitor) throws Exception {
    Git git = getGit(monitor);

    FetchCommand fetch = git.fetch();
    fetch.setCredentialsProvider(credentialsProvider);
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    fetch.call();

    SyncState state = getSyncState(git);
    Ref fetchHead = git.getRepository().getRef("FETCH_HEAD");
    switch (state) {
        case Equal:
            // Do nothing
            Log.d("Git", "Local branch is up-to-date");
            break;

        case Ahead:
            Log.d("Git", "Local branch ahead, pushing changes to remote");
            git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            break;

        case Behind:
            Log.d("Git", "Local branch behind, fast forwarding changes");
            MergeResult result = git.merge().include(fetchHead).setFastForward(MergeCommand.FastForwardMode.FF_ONLY).call();
            if (result.getMergeStatus().isSuccessful() == false)
                throw new IllegalStateException("Fast forward failed on behind merge");
            break;

        case Diverged:
            Log.d("Git", "Branches are diverged, merging with strategy " + mergeStrategy.getName());
            MergeResult mergeResult = git.merge().include(fetchHead).setStrategy(mergeStrategy).call();
            if (mergeResult.getMergeStatus().isSuccessful()) {
                git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            } else
                throw new IllegalStateException("Merge failed for diverged branches using strategy " + mergeStrategy.getName());
            break;
    }
}
 
Example #8
Source File: StudioNodeSyncSandboxTask.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private void updateBranch(Git git, ClusterMember remoteNode) throws CryptoException, GitAPIException,
        IOException, ServiceLayerException {
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");
    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(REPO_SANDBOX_BRANCH);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS +
                    studioConfiguration.getProperty(REPO_SANDBOX_BRANCH));
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            MergeResult result = mergeCommand.call();
            if (result.getMergeStatus().isSuccessful()) {
                deploymentService.syncAllContentToPreview(siteId, true);
            }
        }
    }

    Files.delete(tempKey);
}
 
Example #9
Source File: MergeTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
@Override
public void doExecute() {
        try {
                MergeCommand mergeCommand = git.merge().setSquash(squash);
                mergeCommand.include(mergeCommand.getRepository().getRef(branchname));

                setupCredentials(mergeCommand);

                MergeResult mergeResult = null;
                try {
                        mergeResult = mergeCommand.call();
                } catch (CheckoutConflictException conflicts) {
                        throw new BuildException(String.format("%s - Checkout conflicts: %s", MESSAGE_MERGE_FAILED, conflicts.getConflictingPaths()));
                }

                if (!mergeResult.getMergeStatus().isSuccessful()) {

                        if (mergeResult.getCheckoutConflicts() != null && mergeResult.getCheckoutConflicts().size() > 0) {
                                throw new BuildException(String.format("%s - Checkout conflicts: %s", MESSAGE_MERGE_FAILED, mergeResult.getCheckoutConflicts()));
                        }

                        if (mergeResult.getFailingPaths() != null && mergeResult.getFailingPaths().size() > 0) {
                                throw new BuildException(String.format("%s - Failing paths: %s", MESSAGE_MERGE_FAILED, mergeResult.getFailingPaths()));
                        }

                        throw new BuildException(String.format(MESSAGE_MERGE_FAILED_WITH_STATUS, mergeResult.getMergeStatus().name()));
                }
        } catch (Exception e) {
                throw new GitBuildException(String.format(MESSAGE_MERGE_FAILED_WITH_URI, getUri()), e);
        }
}
 
Example #10
Source File: Scenarios.java    From jgitver with Apache License 2.0 4 votes vote down vote up
/**
 * Builds repository with a feature branch that contains less commits than the master branch
 * <pre>
 * {@code
 * *   318c3c9 (HEAD -> master) M2 :: merge F into H
 * |\
 * * | a50dde7 content H
 * * | 4d841f6 content G
 * | * 368e6d8 (b2) content F
 * * |   ed0a74c M1 :: merge E into D
 * |\ \
 * | * | 0d42532 (b1) content E
 * * | | 4a2582a content D
 * * | | 5fcc09c content C
 * | |/
 * * | fe753dd content B
 * |/
 * * d74b251 (tag: 1.0.0) content A
 * }
 * </pre>
 * @return the scenario object corresponding to the above git repository
 */
public static ScenarioBuilder s17_feature_branches_with_shorter_path() {
    return new ScenarioBuilder()
            .commit("content", "A")
            .tag("1.0.0")
            .commit("content", "B")
            .commit("content", "C")
            .commit("content", "D")
            .branchOnAppId("b1","A")
            .commit("content", "E")
            .branchOnAppId("b2","A")
            .commit("content", "F")
            .master()
            .merge("E", "M1", MergeCommand.FastForwardMode.NO_FF)
            .commit("content", "G")
            .commit("content", "H")
            .merge("F", "M2", MergeCommand.FastForwardMode.NO_FF)
            .commit("content", "I");
}
 
Example #11
Source File: Scenarios.java    From jgitver with Apache License 2.0 4 votes vote down vote up
/**
 * Feature branch, wrapped inside another one
 * <pre>
 * {@code
 * * c1faa0c - (HEAD -> master) content H
 * *   93ac330 - M2 :: merge C2 into M1
 * |\
 * | * 16adcca - (bC) content C2
 * | * 71b4228 - content C1
 * * |   ae2d477 - M1 :: merge E2 into D
 * |\ \
 * | * | 381c149 - (bE) content E2
 * | * | 0dce471 - content E1
 * |/ /
 * * | 91fc982 - content D
 * |/
 * * f8b17eb - content B
 * * 9e90b91 - content A
 * }
 * </pre>
 * @return
 */
public static ScenarioBuilder s18_wrapped_feature_branches() {
    return new Scenarios.ScenarioBuilder()
            .commit("content", "A")
            .commit("content", "B")
            .branchOnAppId("bC", "B")
            .commit("content", "C1")
            .commit("content", "C2")
            .master()
            .commit("content", "D")
            .branchOnAppId("bE", "D")
            .commit("content", "E1")
            .commit("content", "E2")
            .master()
            .merge("E2", "M1", MergeCommand.FastForwardMode.NO_FF)
            .merge("C2", "M2", MergeCommand.FastForwardMode.NO_FF)
            .commit("content", "H");
}
 
Example #12
Source File: Scenarios.java    From jgitver with Apache License 2.0 4 votes vote down vote up
/**
 * Merges performed inside a feature branch
 * <pre>
 * {@code
 * * 7b786d9 - (HEAD -> master) content E
 * *   3e1fd7f - M2 :: merge C3 into B
 * |\
 * | * 8e25e94 - (bC) content C3
 * | *   bd2a45f - M1 :: merge D2 into C2
 * | |\
 * | | * c2fa692 - (bD) content D2
 * | | * 272629b - content D1
 * | * | ed6874e - content C2
 * | |/
 * | * e9dff65 - content C1
 * |/
 * * 012d0e3 - content B
 * * 6873a91 - content A
 * }
 * </pre>
 * @return
 */
public static ScenarioBuilder s19_merges_in_feature_branch() {
    return new Scenarios.ScenarioBuilder()
            .commit("content", "A")
            .commit("content", "B")
            .branchOnAppId("bC", "B")
            .commit("content", "C1")
            .commit("content", "C2")
            .branchOnAppId("bD", "C1")
            .commit("content", "D1")
            .commit("content", "D2")
            .checkoutBranch("bC")
            .merge("D2", "M1", MergeCommand.FastForwardMode.NO_FF)
            .commit("content", "C3")
            .master()
            .merge("C3", "M2", MergeCommand.FastForwardMode.NO_FF)
            .commit("content", "E");
}
 
Example #13
Source File: GitHelper.java    From repairnator with MIT License 4 votes vote down vote up
public boolean mergeTwoCommitsForPR(Git git, Build build, PullRequest prInformation, String repository, AbstractStep step, List<String> paths) {
    try {
        String remoteBranchPath = Utils.getCompleteGithubRepoUrl(prInformation.getOtherRepo().getFullName());

        RemoteAddCommand remoteBranchCommand = git.remoteAdd();
        remoteBranchCommand.setName("PR");
        remoteBranchCommand.setUri(new URIish(remoteBranchPath));
        remoteBranchCommand.call();

        git.fetch().setRemote("PR").call();

        String commitHeadSha = this.testCommitExistence(git, prInformation.getHead().getSHA1(), step, build);
        String commitBaseSha = this.testCommitExistence(git, prInformation.getBase().getSHA1(), step, build);

        if (commitHeadSha == null) {
            step.addStepError("Commit head ref cannot be retrieved from the repository: "
                    + prInformation.getHead().getSHA1() + ". Operation aborted.");
            return false;
        }

        if (commitBaseSha == null) {
            step.addStepError("Commit base ref cannot be retrieved from the repository: "
                    + prInformation.getBase().getSHA1() + ". Operation aborted.");
            return false;
        }

        this.getLogger().debug("Step " + step.getName() + " - Get the commit " + commitHeadSha + " for repo " + repository);

        if (paths != null) {
            this.gitResetPaths(commitHeadSha, paths, git.getRepository().getDirectory().getParentFile());
            git.commit().setMessage("Undo changes on source code").setAuthor(this.getCommitterIdent()).setCommitter(this.getCommitterIdent()).call();
        } else {
            git.checkout().setName(commitHeadSha).call();
        }

        RevWalk revwalk = new RevWalk(git.getRepository());
        RevCommit revCommitBase = revwalk.lookupCommit(git.getRepository().resolve(commitBaseSha));

        this.getLogger().debug("Step " + step.getName() + " - Do the merge with the PR commit for repo " + repository);
        MergeResult result = git.merge().include(revCommitBase).setFastForward(MergeCommand.FastForwardMode.NO_FF).call();
        this.nbCommits++;
    } catch (Exception e) {
        step.addStepError(e.getMessage());
        this.getLogger().error("Step " + step.getName() + " - Repository " + repository + " cannot be cloned.",e);
        return false;
    }
    return true;
}
 
Example #14
Source File: JGitEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Test
public void testRefreshWithoutFetch() throws Exception {
	Git git = mock(Git.class);

	CloneCommand cloneCommand = mock(CloneCommand.class);
	when(cloneCommand.setURI(anyString())).thenReturn(cloneCommand);
	when(cloneCommand.setDirectory(any(File.class))).thenReturn(cloneCommand);
	when(cloneCommand.call()).thenReturn(git);

	MockGitFactory factory = new MockGitFactory(git, cloneCommand);

	StatusCommand statusCommand = mock(StatusCommand.class);
	CheckoutCommand checkoutCommand = mock(CheckoutCommand.class);
	Status status = mock(Status.class);
	Repository repository = mock(Repository.class, Mockito.RETURNS_DEEP_STUBS);
	StoredConfig storedConfig = mock(StoredConfig.class);
	Ref ref = mock(Ref.class);
	ListBranchCommand listBranchCommand = mock(ListBranchCommand.class);
	FetchCommand fetchCommand = mock(FetchCommand.class);
	FetchResult fetchResult = mock(FetchResult.class);
	Ref branch1Ref = mock(Ref.class);

	when(git.branchList()).thenReturn(listBranchCommand);
	when(git.status()).thenReturn(statusCommand);
	when(git.getRepository()).thenReturn(repository);
	when(git.checkout()).thenReturn(checkoutCommand);
	when(git.fetch()).thenReturn(fetchCommand);
	when(git.merge())
			.thenReturn(mock(MergeCommand.class, Mockito.RETURNS_DEEP_STUBS));
	when(repository.getConfig()).thenReturn(storedConfig);
	when(storedConfig.getString("remote", "origin", "url"))
			.thenReturn("http://example/git");
	when(statusCommand.call()).thenReturn(status);
	when(checkoutCommand.call()).thenReturn(ref);
	when(listBranchCommand.call()).thenReturn(Arrays.asList(branch1Ref));
	when(fetchCommand.call()).thenReturn(fetchResult);
	when(branch1Ref.getName()).thenReturn("origin/master");
	when(status.isClean()).thenReturn(true);

	JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment,
			new JGitEnvironmentProperties());
	repo.setGitFactory(factory);
	repo.setUri("http://somegitserver/somegitrepo");
	repo.setBasedir(this.basedir);

	// Set the refresh rate to 2 seconds and last update before 100ms. There should be
	// no remote repo fetch.
	repo.setLastRefresh(System.currentTimeMillis() - 100);
	repo.setRefreshRate(2);

	repo.refresh("master");

	// Verify no fetch but merge only.
	verify(git, times(0)).fetch();
	verify(git).merge();
}
 
Example #15
Source File: StudioNodeSyncPublishedTask.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
private void updatePublishedBranch(Git git, ClusterMember remoteNode, String branch) throws CryptoException,
        GitAPIException, IOException, ServiceLayerException {
    logger.debug("Update published environment " + branch + " from " + remoteNode.getLocalAddress() +
            " for site " + siteId);
    final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp");

    Repository repo = git.getRepository();
    Ref ref = repo.exactRef(Constants.R_HEADS + branch);
    boolean createBranch = (ref == null);

    logger.debug("Checkout " + branch);
    CheckoutCommand checkoutCommand = git.checkout()
            .setName(branch)
            .setCreateBranch(createBranch);
    if (createBranch) {
        checkoutCommand.setStartPoint(remoteNode.getGitRemoteName() + "/" + branch);
    }
    checkoutCommand.call();

    FetchCommand fetchCommand = git.fetch().setRemote(remoteNode.getGitRemoteName());
    fetchCommand = configureAuthenticationForCommand(remoteNode, fetchCommand, tempKey);
    FetchResult fetchResult = fetchCommand.call();

    ObjectId commitToMerge;
    Ref r;
    if (fetchResult != null) {
        r = fetchResult.getAdvertisedRef(branch);
        if (r == null) {
            r = fetchResult.getAdvertisedRef(Constants.R_HEADS + branch);
        }
        if (r != null) {
            commitToMerge = r.getObjectId();

            MergeCommand mergeCommand = git.merge();
            mergeCommand.setMessage(studioConfiguration.getProperty(REPO_SYNC_DB_COMMIT_MESSAGE_NO_PROCESSING));
            mergeCommand.setCommit(true);
            mergeCommand.include(remoteNode.getGitRemoteName(), commitToMerge);
            mergeCommand.setStrategy(MergeStrategy.THEIRS);
            mergeCommand.call();
        }
    }

    Files.delete(tempKey);
}
 
Example #16
Source File: Scenarios.java    From jgitver with Apache License 2.0 2 votes vote down vote up
/**
 * Merges commit with id given as parameter with current branch. Tries a fast forward merge.
 * @param sourceId the application identifier to use as merge source
 * @param id the application identifier to use to store the git commitID of merge commit
 * @return the builder itself to continue building the scenario
 */
public ScenarioBuilder merge(String sourceId, String id) {
    return merge(sourceId, id, MergeCommand.FastForwardMode.FF);
}