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; }
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; }
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); }
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()); }
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; }
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); }
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); }
public static MergeResult mergeWithSquash(Git git, MergeStrategy strategy, List<Ref> commitsByRef, List<AnyObjectId> commitsById, List<NamedCommit> commitsByNameAndId, MergeCommand.FastForwardMode fastForwardMode, ProgressMonitor monitor) throws GitAPIException { MergeCommand merge = git.merge(); setupMergeCommand(merge, commitsByRef, commitsById, commitsByNameAndId, monitor, strategy, fastForwardMode); return merge .setStrategy(strategy) .setFastForward(fastForwardMode) .setSquash(true) .call(); }
public static MergeResult mergeWithoutCommit(Git git, MergeStrategy strategy, List<Ref> commitsByRef, List<AnyObjectId> commitsById, List<NamedCommit> commitsByNameAndId, MergeCommand.FastForwardMode fastForwardMode, ProgressMonitor monitor) throws GitAPIException { MergeCommand merge = git.merge(); setupMergeCommand(merge, commitsByRef, commitsById, commitsByNameAndId, monitor, strategy, fastForwardMode); return merge .setStrategy(strategy) .setFastForward(fastForwardMode) .setCommit(false) .call(); }
public static MergeResult mergeWithCommit(Git git, MergeStrategy strategy, List<Ref> commitsByRef, List<AnyObjectId> commitsById, List<NamedCommit> commitsByNameAndId, String commitMessage, MergeCommand.FastForwardMode fastForwardMode, ProgressMonitor monitor) throws GitAPIException { MergeCommand merge = git.merge(); setupMergeCommand(merge, commitsByRef, commitsById, commitsByNameAndId, monitor, strategy, fastForwardMode); return git.merge() .setMessage(commitMessage) // message to be used for merge commit .call(); }
/** * merges the selected local branch with the current local branch * @throws GitAPIException if there is a merging error * @throws IOException if there is an error with the file access of merge */ private void localBranchMerge() throws GitAPIException, IOException { logger.info("Merging selected branch with current"); // Get the branch to merge with LocalBranchHelper selectedBranch = this.branchDropdownSelector.getSelectionModel().getSelectedItem(); // Get the merge result from the branch merge MergeResult mergeResult= this.branchModel.mergeWithBranch(selectedBranch); if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.CONFLICTING)){ this.showConflictsNotification(); this.sessionController.gitStatus(); ConflictingFileWatcher.watchConflictingFiles(sessionModel.getCurrentRepoHelper()); } else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) { this.showUpToDateNotification(); } else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.FAILED)) { this.showFailedMergeNotification(); } else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.MERGED) || mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.MERGED_NOT_COMMITTED)) { this.showMergeSuccessNotification(); } else if (mergeResult.getMergeStatus().equals(MergeResult.MergeStatus.FAST_FORWARD)) { this.showFastForwardMergeNotification(); } else { System.out.println(mergeResult.getMergeStatus()); // todo: handle all cases (maybe combine some) } // Tell the rest of the UI to update sessionController.gitStatus(); }
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(); }
private List<Commit> mergePullRequestBranchWithTarget(Git git) throws Exception { notifier.message("Merging source " + request.getNumber() + " into target " + request.getTarget().getBranch()); MergeResult result = git.merge() .setFastForward(FastForwardMode.FF_ONLY) .include(git.getRepository().getRef(String.valueOf(request.getNumber()))) .call(); if(!result.getMergeStatus().isSuccessful()) { throw new RuntimeException("Merge not successfull, status " + result.getMergeStatus()); } else { notifier.message("Merged " + request + " : " + result.getMergeStatus()); } return GitUtil.toCommitList(result.getMergedCommits()); }
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"); }
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; } }
@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); } }
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; }
@Override public GitMergeResult createMergeResult (MergeResult mergeResult, File workTree) { return new GitMergeResult(mergeResult, workTree); }
public void testMergeStatus () { for (MergeResult.MergeStatus status : MergeResult.MergeStatus.values()) { assertNotNull(GitMergeResult.parseMergeStatus(status)); } }
@Test public 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 Entry<JsonNode> expectedMirrorState = expectedMirrorState("/"); final Entry<String> expectedAlphabets = Entry.ofText( "/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_MAIN, Revision.HEAD, "/**").join().values()) .containsExactlyInAnyOrder(expectedMirrorState, expectedAlphabets); }
@Test public void testMergeSelectedBranchWithCurrent() throws Exception { // first fetch from remote RefSpec fetchSpec = new RefSpec ("+refs/heads/*:refs/remotes/origin/*"); new Git(helper.getRepo()).fetch().setRefSpecs(fetchSpec).call(); // start tracking the remote branch "random" new Git(helper.getRepo()).checkout(). setCreateBranch(true). setForce(true). setName("random"). setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). setStartPoint("origin/random"). call(); // make changes to local file and commit File file = Paths.get(this.repoPath.toString(), "test.txt").toFile(); assertTrue(file.exists()); try(PrintWriter fileTextWriter = new PrintWriter( file )){ fileTextWriter.println("Add a line to the file"); } this.helper.addFilePathTest(file.toPath()); this.helper.commit("Modified test.txt in a unit test!"); new Git(helper.getRepo()).checkout().setName("master").call(); // merge master into random MergeCommand merge = new Git(helper.getRepo()).merge(); merge.include(helper.getRepo().resolve("refs/heads/random")); MergeResult mergeResult = merge.call(); assertEquals(mergeResult.getMergeStatus(), MergeResult.MergeStatus.FAST_FORWARD); // TODO: fix this if you ever run it //CommitTreeController.update(helper); // after update, should expect the heads of two branches // are the same commit helper.getBranchModel().updateLocalBranches(); assertEquals(helper.getBranchModel().getBranchListTyped(BranchModel.BranchType.LOCAL).size(), 2); String masterHead = helper.getBranchModel().getBranchListTyped(BranchModel.BranchType.LOCAL).get(0).getHeadId().getName(); String randomHead = helper.getBranchModel().getBranchListTyped(BranchModel.BranchType.LOCAL).get(1).getHeadId().getName(); assertEquals(masterHead, randomHead); }
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; }
@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); }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = CookbookHelper.createNewRepository()) { try (Git git = new Git(repository)) { // create some commit on master createCommit(repository, git, "masterFile", "content12"); // create branch "changes" Ref changes = git.branchCreate().setName("changes").call(); System.out.println("Result of creating the branch: " + changes); // now start a change on master createCommit(repository, git, "sharedFile", "content12"); // check out branch "changes" Ref checkout = git.checkout().setName("changes").call(); System.out.println("Result of checking out the branch: " + checkout); // create some commit on branch "changes", one of them conflicting with the change on master createCommit(repository, git, "branchFile", "content98"); createCommit(repository, git, "sharedFile", "content98"); // check out "master" checkout = git.checkout().setName("master").call(); System.out.println("Result of checking out master: " + checkout); // retrieve the objectId of the latest commit on branch ObjectId mergeBase = repository.resolve("changes"); // perform the actual merge, here we disable FastForward to see the // actual merge-commit even though the merge is trivial MergeResult merge = git.merge(). include(mergeBase). setCommit(true). setFastForward(MergeCommand.FastForwardMode.NO_FF). //setSquash(false). setMessage("Merged changes"). call(); System.out.println("Merge-Results for id: " + mergeBase + ": " + merge); for (Map.Entry<String,int[][]> entry : merge.getConflicts().entrySet()) { System.out.println("Key: " + entry.getKey()); for(int[] arr : entry.getValue()) { System.out.println("value: " + Arrays.toString(arr)); } } } } }
public abstract GitMergeResult createMergeResult (MergeResult mergeResult, File workTree);