org.eclipse.jgit.api.MergeResult Java Examples

The following examples show how to use org.eclipse.jgit.api.MergeResult. 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: GitUtils.java    From gitPic with MIT License 8 votes vote down vote up
public static void pull(Repository repository) {
    Git git = new Git(repository);
    try {
        PullResult result = git.pull().call();
        FetchResult fetchResult = result.getFetchResult();
        MergeResult mergeResult = result.getMergeResult();
        if (fetchResult.getMessages() != null && !fetchResult.getMessages().isEmpty()) {
            logger.info(fetchResult.getMessages());
        }
        logger.info(mergeResult.getMergeStatus().toString());
        if (!mergeResult.getMergeStatus().isSuccessful()) {
            throw new TipException(mergeResult.getMergeStatus().toString());
        }
    } catch (GitAPIException e) {
        logger.error(e.getMessage(), e);
        throw new TipException("git commit 异常");
    }
}
 
Example #2
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 #3
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 #4
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 #5
Source File: GitUtils.java    From jphp with Apache License 2.0 5 votes vote down vote up
public static ArrayMemory valueOf(MergeResult call) {
    ArrayMemory memory = new ArrayMemory();
    memory.refOfIndex("base").assign(valueOf(call.getBase()));
    memory.refOfIndex("newHead").assign(valueOf(call.getNewHead()));

    memory.refOfIndex("status").assign(call.getMergeStatus().name());
    memory.refOfIndex("success").assign(call.getMergeStatus().isSuccessful());

    memory.refOfIndex("checkoutConflicts").assign(ArrayMemory.ofStringCollection(call.getCheckoutConflicts()));

    return memory;
}
 
Example #6
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 #7
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 #8
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 #9
Source File: GitSynchronizeWindow.java    From XACML with MIT License 5 votes vote down vote up
protected void synchronize() {
	//
	// Grab our working repository
	//
	Path repoPath = ((XacmlAdminUI)getUI()).getUserGitPath();
	try {
		final Git git = Git.open(repoPath.toFile());
		
		PullResult result = git.pull().call();
		FetchResult fetch = result.getFetchResult();
		MergeResult merge = result.getMergeResult();
		RebaseResult rebase = result.getRebaseResult();
		if (result.isSuccessful()) {
			//
			// TODO add more notification
			//
			this.textAreaResults.setValue("Successful!");
		} else {
			//
			// TODO
			//
			this.textAreaResults.setValue("Failed.");
		}
	} catch (IOException | GitAPIException e) {
		e.printStackTrace();
	}
	this.buttonSynchronize.setCaption("Ok");
}
 
Example #10
Source File: JGitOperator.java    From verigreen with Apache License 2.0 5 votes vote down vote up
private String createMessageAutoCommit(MergeResult mergeResult) {
	StringBuffer message = new StringBuffer("Auto merge commit between:");
	
	 for (Object commit : mergeResult.getMergedCommits()) {
		 message.append(" ").append(((RevCommit)commit).getName().substring(0, 7));//no check for null
	}
	
	return message.toString();
}
 
Example #11
Source File: GitMergeTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testMergeAlreadyUpToDate() 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, "change in master");

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

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

	assertStatus(new StatusResult().setChanged(1), gitStatusUri);

	// "git merge master"
	JSONObject merge = merge(gitHeadUri, Constants.MASTER);
	MergeStatus mergeResult = MergeResult.MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
	assertEquals(MergeResult.MergeStatus.ALREADY_UP_TO_DATE, mergeResult);

	// status hasn't changed
	assertStatus(new StatusResult().setChanged(1), gitStatusUri);
}
 
Example #12
Source File: GitMergeSquashTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testMergeSquashAlreadyUpToDate() 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, "change in master");

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

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

	assertStatus(new StatusResult().setChanged(1), gitStatusUri);

	// "git merge master"
	JSONObject merge = merge(gitHeadUri, Constants.MASTER, true);
	MergeStatus mergeResult = MergeResult.MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
	assertEquals(MergeResult.MergeStatus.ALREADY_UP_TO_DATE, mergeResult);

	// status hasn't changed
	assertStatus(new StatusResult().setChanged(1), gitStatusUri);
}
 
Example #13
Source File: GitMergeResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<File> getFailures (MergeResult result) {
    List<File> files = new LinkedList<File>();
    Map<String, ResolveMerger.MergeFailureReason> obstructions = result.getFailingPaths();
    if (obstructions != null) {
        for (Map.Entry<String, ResolveMerger.MergeFailureReason> failure : obstructions.entrySet()) {
            files.add(new File(workDir, failure.getKey()));
        }
    }
    return Collections.unmodifiableList(files);
}
 
Example #14
Source File: GitMergeResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private List<File> getConflicts(MergeResult result) {
    List<File> files = new LinkedList<File>();
    Map<String, int[][]> mergeConflicts = result.getConflicts();
    if (mergeConflicts != null) {
        for (Map.Entry<String, int[][]> conflict : mergeConflicts.entrySet()) {
            files.add(new File(workDir, conflict.getKey()));
        }
    }
    return Collections.unmodifiableList(files);
}
 
Example #15
Source File: GitMergeResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String[] getMergedCommits (MergeResult result) {
    ObjectId[] mergedObjectIds = result.getMergedCommits();
    String[] commits = new String[mergedObjectIds.length];
    for (int i = 0; i < mergedObjectIds.length; ++i) {
        commits[i] = ObjectId.toString(mergedObjectIds[i]);
    }
    return commits;
}
 
Example #16
Source File: GitMergeResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static MergeStatus parseMergeStatus (MergeResult.MergeStatus mergeStatus) {
    if (mergeStatus == MergeResult.MergeStatus.FAST_FORWARD_SQUASHED) {
        mergeStatus = MergeResult.MergeStatus.FAST_FORWARD;
    } else if (mergeStatus == MergeResult.MergeStatus.MERGED_SQUASHED) {
        mergeStatus = MergeResult.MergeStatus.MERGED;
    } else if (mergeStatus == MergeResult.MergeStatus.MERGED_NOT_COMMITTED) {
        mergeStatus = MergeResult.MergeStatus.MERGED;
    } else if (mergeStatus == MergeResult.MergeStatus.MERGED_SQUASHED_NOT_COMMITTED) {
        mergeStatus = MergeResult.MergeStatus.MERGED;
    } else if (mergeStatus == MergeResult.MergeStatus.CHECKOUT_CONFLICT) {
        mergeStatus = MergeResult.MergeStatus.CONFLICTING;
    }
    return GitMergeResult.MergeStatus.valueOf(mergeStatus.name());
}
 
Example #17
Source File: GitMergeResult.java    From netbeans with Apache License 2.0 5 votes vote down vote up
GitMergeResult (MergeResult result, File workDir) {
    this.mergeStatus = parseMergeStatus(result.getMergeStatus());
    this.workDir = workDir;
    this.newHead = result.getNewHead() == null ? null : result.getNewHead().getName();
    this.base = result.getBase() == null ? null : result.getBase().getName();
    this.mergedCommits = getMergedCommits(result);
    this.conflicts = getConflicts(result);
    this.failures = getFailures(result);
}
 
Example #18
Source File: GitMirrorTest.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Test
void remoteToLocal_merge() throws Exception {
    pushMirrorSettings(null, null);

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

    // Create a text file, modify it in two branches ('master' and 'fork') and merge 'fork' into 'master'.
    addToGitIndex("alphabets.txt", // 'c' and 'x' are missing.
                  "a\nb\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\ny\nz\n");
    git.commit().setMessage("Add alphabets.txt").call();

    //// Create a new branch 'fork' and add the missing 'x'.
    git.checkout().setCreateBranch(true).setName("fork").call();
    addToGitIndex("alphabets.txt", // Add the missing 'x'.
                  "a\nb\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\n");
    final RevCommit commit1 = git.commit().setMessage("Add missing 'x'").call();

    //// Check out 'master' and add the missing 'c'.
    git.checkout().setName("master").call();
    addToGitIndex("alphabets.txt", // Add the missing 'c'.
                  "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\ny\nz\n");
    final RevCommit commit2 = git.commit().setMessage("Add missing 'c'").call();

    //// Merge 'fork' into 'master' to create a merge commit.
    final MergeResult mergeResult = git.merge()
                                       .include(commit1.getId())
                                       .setFastForward(FastForwardMode.NO_FF)
                                       .setMessage("Merge 'fork'").call();

    //// Make sure the merge commit has been added.
    assertThat(mergeResult.getMergeStatus()).isEqualTo(MergeStatus.MERGED);
    final RevCommit lastCommit = git.log().all().call().iterator().next();
    assertThat(lastCommit.getParentCount()).isEqualTo(2);
    assertThat(lastCommit.getParents()).containsExactlyInAnyOrder(commit1, commit2);

    // Run the mirror and ensure alphabets.txt contains all alphabets.
    mirroringService.mirror().join();

    final Revision headRev = client.normalizeRevision(projName, REPO_FOO, Revision.HEAD).join();
    final Entry<JsonNode> expectedMirrorState = expectedMirrorState(headRev, "/");
    final Entry<String> expectedAlphabets = Entry.ofText(
            headRev,
            "/alphabets.txt",
            "a\nb\nc\nd\ne\nf\ng\nh\ni\nj\nk\nl\nm\nn\no\np\nq\nr\ns\nt\nu\nv\nw\nx\ny\nz\n");

    assertThat(client.getFiles(projName, REPO_FOO, Revision.HEAD, "/**").join().values())
            .containsExactlyInAnyOrder(expectedMirrorState, expectedAlphabets);
}
 
Example #19
Source File: GitEnumsStateTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testMergeStatus () {
    for (MergeResult.MergeStatus status : MergeResult.MergeStatus.values()) {
        assertNotNull(GitMergeResult.parseMergeStatus(status));
    }
}
 
Example #20
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 #21
Source File: GitClassFactoryImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public GitMergeResult createMergeResult (MergeResult mergeResult, File workTree) {
    return new GitMergeResult(mergeResult, workTree);
}
 
Example #22
Source File: JGitOperator.java    From verigreen with Apache License 2.0 4 votes vote down vote up
private Pair<Boolean, String> checkResult(
         String branchToUpdate,
         String branchHead,
         Pair<Boolean, String> ret,
         MergeResult mergeResult) throws IOException {
     
     if (mergeResult.getMergeStatus().equals(MergeStatus.CONFLICTING)
         || mergeResult.getMergeStatus().equals(MergeStatus.FAILED)) {
         VerigreenLogger.get().log(
                 getClass().getName(),
                 RuntimeUtils.getCurrentMethodName(),
                 String.format(
                         "Merge conflicts for parent_branch:%s into:%s. rejecting commit",
                         branchHead,
                         branchToUpdate));
         reset(_repo.getRef(branchToUpdate).getName());
     } else if (mergeResult.getMergeStatus().equals(MergeStatus.ALREADY_UP_TO_DATE)
                || mergeResult.getMergeStatus().equals(MergeStatus.FAST_FORWARD)) {
         VerigreenLogger.get().log(
                 getClass().getName(),
                 RuntimeUtils.getCurrentMethodName(),
                 String.format(
                         "Merge not needed for parent_branch:%s into:%s",
                         branchHead,
                         branchToUpdate));
         ret = new Pair<>(true, "");
     } else if (mergeResult.getMergeStatus().equals(MergeStatus.MERGED_NOT_COMMITTED)) {
         String autoMergeMessage = createMessageAutoCommit(mergeResult);
String commitId = commit(commited_By_Collector, email_Address, autoMergeMessage );
String adjustCommitId = commitId.substring(0,7) + "_" + commited_By_Collector;
         VerigreenLogger.get().log(
                 getClass().getName(),
                 RuntimeUtils.getCurrentMethodName(),
                 String.format(
                         "Verigreen merge for parent_branch:%s into:%s was not committed. Performing auto commit [%s]",
                         branchHead,
                         branchToUpdate,
                         adjustCommitId));
         ret = new Pair<>(true, adjustCommitId);
     }else if (mergeResult.getMergeStatus().equals(MergeStatus.MERGED)) {
      VerigreenLogger.get().log(
              getClass().getName(),
              RuntimeUtils.getCurrentMethodName(),
              "Merge was made after diverted branch with auto commit");
      ret = new Pair<>(true, "");
      new RestClientImpl().post(CollectorApi.getPostVerigreenNeededRequest(mergeResult.getNewHead().getName().substring(0, 7)));
  }
     return ret;
 }
 
Example #23
Source File: Pull.java    From wandora with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void execute(Wandora wandora, Context context) {

    try {
        Git git = getGit();
        if(git != null) {
            if(isNotEmpty(getGitRemoteUrl())) {
                PullCommand pull = git.pull();
                String user = getUsername();
                if(user == null) {
                    if(pullUI == null) {
                        pullUI = new PullUI();
                    }
                    pullUI.setUsername(getUsername());
                    pullUI.setPassword(getPassword());
                    pullUI.setRemoteUrl(getGitRemoteUrl());

                    pullUI.openInDialog();

                    if(pullUI.wasAccepted()) {
                        setUsername(pullUI.getUsername());
                        setPassword(pullUI.getPassword());
                        // setGitRemoteUrl(pullUI.getRemoteUrl());    
                        
                        // pull.setRemote(pullUI.getRemoteUrl());
                        if(isNotEmpty(getUsername())) {
                            CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( getUsername(), getPassword() );
                            pull.setCredentialsProvider(credentialsProvider);
                        }
                    }
                    else {
                        return;
                    }
                }

                setDefaultLogger();
                setLogTitle("Git pull");

                log("Pulling changes from remote repository...");
                PullResult result = pull.call();

                FetchResult fetchResult = result.getFetchResult();
                MergeResult mergeResult = result.getMergeResult();
                MergeStatus mergeStatus = mergeResult.getMergeStatus();

                String fetchResultMessages = fetchResult.getMessages();
                if(isNotEmpty(fetchResultMessages)) {
                    log(fetchResult.getMessages());
                }
                log(mergeStatus.toString());

                if(mergeStatus.equals(MergeStatus.MERGED)) {
                    int a = WandoraOptionPane.showConfirmDialog(wandora, "Reload Wandora project after pull?", "Reload Wandora project after pull?", WandoraOptionPane.YES_NO_OPTION);
                    if(a == WandoraOptionPane.YES_OPTION) {
                        reloadWandoraProject();
                    }
                }
                log("Ready.");
            }
            else {
                log("Repository has no remote origin and can't be pulled. " 
                    + "Initialize repository by cloning remote repository to set the remote origin.");
            }
        }
        else {
            logAboutMissingGitRepository();
        }
    }
    catch(GitAPIException gae) {
        log(gae.toString());
    }
    catch(NoWorkTreeException nwte) {
        log(nwte.toString());
    }
    catch(Exception e) {
        log(e);
    }
    setState(WAIT);
}
 
Example #24
Source File: GitClassFactory.java    From netbeans with Apache License 2.0 votes vote down vote up
public abstract GitMergeResult createMergeResult (MergeResult mergeResult, File workTree);