org.eclipse.jgit.merge.MergeStrategy Java Examples

The following examples show how to use org.eclipse.jgit.merge.MergeStrategy. 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: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
private boolean mergeBranch( String value, String mergeStrategy ) {
  try {
    ObjectId obj = git.getRepository().resolve( value );
    MergeResult result = git.merge()
      .include( obj )
      .setStrategy( MergeStrategy.get( mergeStrategy ) )
      .call();
    if ( result.getMergeStatus().isSuccessful() ) {
      showMessageBox( BaseMessages.getString( PKG, "Dialog.Success" ), BaseMessages.getString( PKG, "Dialog.Success" ) );
      return true;
    } else {
      showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), result.getMergeStatus().toString() );
      if ( result.getMergeStatus() == MergeStatus.CONFLICTING ) {
        result.getConflicts().keySet().forEach( path -> {
          checkout( path, Constants.HEAD, ".ours" );
          checkout( path, getExpandedName( value, IVCS.TYPE_BRANCH ), ".theirs" );
        } );
        return true;
      }
    }
  } catch ( Exception e ) {
    showMessageBox( BaseMessages.getString( PKG, "Dialog.Error" ), e.getMessage() );
  }
  return false;
}
 
Example #2
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 #3
Source File: WrapGit.java    From jphp with Apache License 2.0 6 votes vote down vote up
@Signature
public Memory stashApply(ArrayMemory settings) throws GitAPIException {
    StashApplyCommand command = getWrappedObject().stashApply();

    if (settings != null) {
        command.setApplyIndex(settings.valueOfIndex("applyIndex").toBoolean());
        command.setApplyUntracked(settings.valueOfIndex("applyUntracked").toBoolean());

        Memory stashRef = settings.valueOfIndex("stashRef");
        if (stashRef.isNotNull()) {
            command.setStashRef(stashRef.toString());
        }

        Memory strategy = settings.valueOfIndex("strategy");
        if (strategy.isNotNull()) {
            command.setStrategy(MergeStrategy.get(strategy.toString()));
        }
    }

    return GitUtils.valueOf(command.call());
}
 
Example #4
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(source);
  		RevCommit targetCommit = revWalk.parseCommit(target);
  		revWalk.setRevFilter(RevFilter.NO_MERGES);
  		List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
  		Collections.reverse(commits);
  		RevCommit headCommit = targetCommit;
  		for (RevCommit commit: commits) {
      		ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
      		merger.setBase(commit.getParent(0));
      		if (merger.merge(headCommit, commit)) {
			if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
				if (!commit.getTree().getId().equals(merger.getResultTreeId()) 
						|| !commit.getParent(0).equals(headCommit)) {
			        CommitBuilder commitBuilder = new CommitBuilder();
			        commitBuilder.setAuthor(commit.getAuthorIdent());
			        commitBuilder.setCommitter(committer);
			        commitBuilder.setParentId(headCommit);
			        commitBuilder.setMessage(commit.getFullMessage());
			        commitBuilder.setTreeId(merger.getResultTreeId());
			        headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
				} else {
					headCommit = commit;
				}
			}
      		} else {
      			return null;
      		}
  		}
  		inserter.flush();
  		return headCommit.copy();
  	} catch (IOException e) {
  		throw new RuntimeException(e);
}
  }
 
Example #5
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId, 
  		boolean squash, PersonIdent committer, PersonIdent author, String commitMessage, 
  		boolean useOursOnConflict) {
  	boolean prevUseOursOnConflict = UseOursOnConflict.get();
  	UseOursOnConflict.set(useOursOnConflict);
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
  		RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
  		Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
  		if (merger.merge(targetCommit, sourceCommit)) {
        CommitBuilder mergedCommit = new CommitBuilder();
        mergedCommit.setAuthor(author);
        mergedCommit.setCommitter(committer);
        if (squash)
        	mergedCommit.setParentId(targetCommit);
        else
        	mergedCommit.setParentIds(targetCommit, sourceCommit);
        mergedCommit.setMessage(commitMessage);
        mergedCommit.setTreeId(merger.getResultTreeId());
        ObjectId mergedCommitId = inserter.insert(mergedCommit);
        inserter.flush();
        return mergedCommitId;
  		} else {
  			return null;
  		}
  	} catch (IOException e) {
  		throw new RuntimeException(e);
} finally {
	UseOursOnConflict.set(prevUseOursOnConflict);
}
  }
 
Example #6
Source File: GfsMergeGeneralCaseTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void mergeWithSpecifiedStrategy_theBehaviourShouldChangeAccordingly() throws IOException {
  clearCache();
  byte[] expected = someBytes();
  writeToCache("/our_file.txt", expected);
  commitToBranch(THEIRS);
  Result result = merge(gfs).source(THEIRS).strategy(MergeStrategy.THEIRS).execute();

  assertTrue(result.isSuccessful());
  assertArrayEquals(expected, readAllBytes(gfs.getPath("/our_file.txt")));
}
 
Example #7
Source File: GfsMergeGeneralCaseTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void mergeWithSpecifiedStrategy_theBehaviourShouldChangeAccordingly() throws IOException {
  clearCache();
  byte[] expected = someBytes();
  writeToCache("/our_file.txt", expected);
  commitToBranch(THEIRS);
  Result result = merge(gfs).source(THEIRS).strategy(MergeStrategy.THEIRS).execute();

  assertTrue(result.isSuccessful());
  assertArrayEquals(expected, readAllBytes(gfs.getPath("/our_file.txt")));
}
 
Example #8
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
public JGitWrapper(SharedPreferences preferences) throws Exception {
    localPath = preferences.getString("git_local_path", "");
    if (TextUtils.isEmpty(localPath))
        throw new IllegalArgumentException("Must specify local git path");

    String url = preferences.getString("git_url", "");
    if (TextUtils.isEmpty(url))
        throw new IllegalArgumentException("Must specify remote git url");
    try {
        URIish urIish = new URIish(url);
        if (urIish.getUser() == null) {
            String username = preferences.getString("git_username", "");
            urIish = urIish.setUser(username);
        }
        remotePath = urIish.toString();
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid remote git url");
    }

    branch = preferences.getString("git_branch", "master");
    if (branch.isEmpty())
        throw new IllegalArgumentException("Must specify a git branch");

    commitAuthor = preferences.getString("git_commit_author", "");
    commitEmail = preferences.getString("git_commit_email", "");

    String mergeStrategyString = preferences.getString("git_merge_strategy", "theirs");
    mergeStrategy = MergeStrategy.get(mergeStrategyString);
    if (mergeStrategy == null)
        throw new IllegalArgumentException("Invalid merge strategy: " + mergeStrategyString);

    setupJGitAuthentication(preferences);
}
 
Example #9
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 #10
Source File: WrapGit.java    From jphp with Apache License 2.0 5 votes vote down vote up
@Signature
public Memory merge(String[] refs, ArrayMemory settings) throws IOException, GitAPIException {
    MergeCommand command = getWrappedObject().merge();

    for (String ref : refs) {
        Repository repository = getWrappedObject().getRepository();
        ObjectId objectId = repository.resolve(ref);
        command.include(objectId);
    }

    if (settings != null) {
        command.setCommit(settings.valueOfIndex("commit").toBoolean());
        command.setMessage(settings.valueOfIndex("message").toString());
        command.setSquash(settings.valueOfIndex("squash").toBoolean());

        Memory fastForward = settings.valueOfIndex("fastForward");
        
        if (fastForward.isNumber()) {
            command.setFastForward(MergeCommand.FastForwardMode.valueOf(fastForward.toString()));
        }

        Memory strategy = settings.valueOfIndex("strategy");
        if (strategy.isNotNull()) {
            command.setStrategy(MergeStrategy.get(strategy.toString()));
        }
    }

    MergeResult call = command.call();
    return GitUtils.valueOf(call);
}
 
Example #11
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 #12
Source File: WrapGit.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public Memory pull(String remote, ArrayMemory settings) throws GitAPIException {
    PullCommand command = getWrappedObject().pull();

    command.setRemote(remote);

    command.setTransportConfigCallback(transportConfigCallback);
    if (credentialsProvider != null) {
        command.setCredentialsProvider(credentialsProvider);
    }

    if (settings != null) {
        command.setRebase(settings.valueOfIndex("rebase").toBoolean());

        Memory branch = settings.valueOfIndex("branch");
        if (branch.isNotNull()) {
            command.setRemoteBranchName(branch.toString());
        }

        Memory strategy = settings.valueOfIndex("strategy");
        if (strategy.isNotNull()) {
            command.setStrategy(MergeStrategy.get(strategy.toString()));
        }

        Memory tagOpt = settings.valueOfIndex("tagOpt");
        if (tagOpt.isNotNull()) {
            command.setTagOpt(TagOpt.valueOf(tagOpt.toString()));
        }

        Memory timeout = settings.valueOfIndex("timeout");
        if (timeout.isNotNull()) {
            command.setTimeout(timeout.toInteger());
        }

        Memory credentials = settings.valueOfIndex("credentials");
        if (credentials.isNotNull()) {
            command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(
                    credentials.valueOfIndex("username").toString(),
                    credentials.valueOfIndex("password").toString()
            ));
        }
    }

    return GitUtils.valueOf(command.call());
}
 
Example #13
Source File: StashApplyCommand.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * @param strategy
 *            The merge strategy to use in order to merge during this command execution.
 * @return {@code this}
 * @since 3.4
 */
public StashApplyCommand setStrategy(MergeStrategy strategy) {
	this.strategy = strategy;
	return this;
}