List of usage examples for org.eclipse.jgit.api Git reset
public ResetCommand reset()
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryTests.java
License:Apache License
@Test public void testResetHardException() throws Exception { Git git = mock(Git.class); CloneCommand cloneCommand = mock(CloneCommand.class); MockGitFactory factory = new MockGitFactory(git, cloneCommand); JGitEnvironmentRepository repo = new JGitEnvironmentRepository(this.environment); this.repository.setGitFactory(factory); //refresh()->shouldPull StatusCommand statusCommand = mock(StatusCommand.class); Status status = mock(Status.class); when(git.status()).thenReturn(statusCommand); Repository repository = mock(Repository.class); when(git.getRepository()).thenReturn(repository); StoredConfig storedConfig = mock(StoredConfig.class); when(repository.getConfig()).thenReturn(storedConfig); when(storedConfig.getString("remote", "origin", "url")).thenReturn("http://example/git"); when(statusCommand.call()).thenReturn(status); when(status.isClean()).thenReturn(true).thenReturn(false); //refresh()->fetch FetchCommand fetchCommand = mock(FetchCommand.class); FetchResult fetchResult = mock(FetchResult.class); when(git.fetch()).thenReturn(fetchCommand); when(fetchCommand.setRemote(anyString())).thenReturn(fetchCommand); when(fetchCommand.call()).thenReturn(fetchResult); when(fetchResult.getTrackingRefUpdates()).thenReturn(Collections.EMPTY_LIST); //refresh()->checkout CheckoutCommand checkoutCommand = mock(CheckoutCommand.class); //refresh()->checkout->containsBranch ListBranchCommand listBranchCommand = mock(ListBranchCommand.class); when(git.checkout()).thenReturn(checkoutCommand); when(git.branchList()).thenReturn(listBranchCommand); List<Ref> refs = new ArrayList<>(); Ref ref = mock(Ref.class); refs.add(ref);// w w w . ja v a 2 s. c om when(ref.getName()).thenReturn("/master"); when(listBranchCommand.call()).thenReturn(refs); //refresh()->merge MergeCommand mergeCommand = mock(MergeCommand.class); when(git.merge()).thenReturn(mergeCommand); when(mergeCommand.call()).thenThrow(new NotMergedException()); //here is our exception we are testing //refresh()->hardReset ResetCommand resetCommand = mock(ResetCommand.class); when(git.reset()).thenReturn(resetCommand); when(resetCommand.call()).thenReturn(ref); //refresh()->return git.getRepository().getRef("HEAD").getObjectId().getName(); Ref headRef = mock(Ref.class); when(repository.getRef(anyString())).thenReturn(headRef); ObjectId newObjectId = ObjectId.fromRaw(new int[] { 1, 2, 3, 4, 5 }); when(headRef.getObjectId()).thenReturn(newObjectId); SearchPathLocator.Locations locations = this.repository.getLocations("bar", "staging", "master"); assertEquals(locations.getVersion(), newObjectId.getName()); }
From source file:pl.project13.jgit.DescribeCommandTagsIntegrationTest.java
License:Open Source License
@Test public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTags() throws Exception { // given/*from w w w. j a va 2 s . c o m*/ mavenSandbox.withParentProject(PROJECT_NAME, "jar").withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(FileSystemMavenSandbox.CleanUp.CLEANUP_FIRST); String snapshotTag = "0.0.1-SNAPSHOT"; String latestTag = "OName-0.0.1"; Repository repo = git().getRepository(); Git jgit = Git.wrap(repo); jgit.reset().setMode(ResetCommand.ResetType.HARD).call(); // when jgit.tag().setName(snapshotTag).call(); Thread.sleep(2000); jgit.tag().setName(latestTag).call(); DescribeResult res = DescribeCommand.on(repo).tags().setVerbose(true).call(); // then assertThat(res.toString()).isEqualTo(latestTag); }
From source file:pl.project13.jgit.DescribeCommandTagsIntegrationTest.java
License:Open Source License
@Test public void shouldUseTheNewestTagOnACommitIfItHasMoreThanOneTagsReversedCase() throws Exception { // given/*from ww w.j ava 2s . com*/ mavenSandbox.withParentProject(PROJECT_NAME, "jar").withNoChildProject() .withGitRepoInParent(AvailableGitTestRepo.WITH_LIGHTWEIGHT_TAG_BEFORE_ANNOTATED_TAG) .create(FileSystemMavenSandbox.CleanUp.CLEANUP_FIRST); String beforeTag = "OName-0.0.1"; String latestTag = "0.0.1-SNAPSHOT"; Repository repo = git().getRepository(); Git jgit = Git.wrap(repo); jgit.reset().setMode(ResetCommand.ResetType.HARD).call(); // when jgit.tag().setName(beforeTag).call(); jgit.tag().setName(latestTag).call(); DescribeResult res = DescribeCommand.on(repo).tags().setVerbose(true).call(); // then assertThat(res.toString()).isEqualTo(latestTag); }
From source file:plumber.core.git.test.BasicGitTest.java
License:Apache License
@Test public void testGitInit() throws IOException, GitAPIException { String targetPath = getClass().getProtectionDomain().getCodeSource().getLocation().getFile() + "/.."; System.setProperty(PLUMBER_GIT_URL.configKey(), "git@github.com:github/testrepo.git"); System.setProperty(PLUMBER_GIT_PATH.configKey(), targetPath + "/junit-git-iaac"); PlumberConfig.reload();/*w ww . ja v a 2 s. c o m*/ System.clearProperty(PLUMBER_GIT_URL.configKey()); System.clearProperty(PLUMBER_GIT_PATH.configKey()); File gitFolder = new File(PlumberConfig.get(PLUMBER_GIT_PATH)); if (gitFolder.exists() && gitFolder.isDirectory()) { FileUtils.deleteDirectory(gitFolder); } assertTrue(gitFolder.mkdirs()); GitWorker gitWorker = new GitWorker(PlumberConfig.get(PLUMBER_GIT_URL), PlumberConfig.get(PLUMBER_GIT_PATH)); gitWorker.init(); gitWorker = new GitWorker(PlumberConfig.get(PLUMBER_GIT_URL), PlumberConfig.get(PLUMBER_GIT_PATH)); gitWorker.init(); Git git = gitWorker.getGit(); assertNotNull(git); Iterator<RevCommit> log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRef = log.next().getName(); assertTrue(log.hasNext()); String previousRef = log.next().getName(); assertNotEquals(latestRef, previousRef); ResetCommand resetCommand = git.reset(); resetCommand.setMode(ResetCommand.ResetType.HARD); resetCommand.setRef("HEAD~1"); resetCommand.call(); assertTrue(git.log().call().iterator().hasNext()); log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRefAfterRebase = log.next().getName(); assertEquals(previousRef, latestRefAfterRebase); PullResult pullResult = gitWorker.pull(); assertTrue(pullResult.isSuccessful()); assertEquals(MergeResult.MergeStatus.FAST_FORWARD, pullResult.getMergeResult().getMergeStatus()); log = git.log().call().iterator(); assertTrue(log.hasNext()); String latestRefAfterRePull = log.next().getName(); assertEquals(latestRef, latestRefAfterRePull); if (gitFolder.exists() && gitFolder.isDirectory()) { FileUtils.deleteDirectory(gitFolder); } }
From source file:replicatorg.app.ui.panels.UpdateChecker.java
License:Open Source License
private void updateFilaments() { final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder(); final Git git; final Status repoStatus; final RemoteAddCommand remoteAddCmd; ResetCommand resetCmd;/*from ww w. j a v a2 s .c om*/ CheckoutCommand checkoutCmd; final String currentBranch, newBranch; final List<Ref> branchList; Repository filamentsRepo; boolean branchFoundLocally = false; RevCommit stash = null; repoBuilder.setMustExist(true); repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git")); try { try { Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass()); filamentsRepo = repoBuilder.build(); } catch (RepositoryNotFoundException ex) { try { Base.writeLog("Repository wasn't initialized, initializing it to the given URL: " + FILAMENTS_REPO_URL, this.getClass()); repoBuilder.setMustExist(false); filamentsRepo = repoBuilder.build(); filamentsRepo.create(); } catch (IOException ex1) { Base.writeLog("IOException while attempting to initialize repository, not updating filaments", this.getClass()); return; } } currentBranch = filamentsRepo.getBranch(); } catch (IOException ex) { Base.writeLog("IOException while attempting to open repository, not updating filaments", this.getClass()); return; } git = new Git(filamentsRepo); try { // it should be only 1, but it shortens the code needed, as the call() // method returns an iterable for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Current commit hash: " + commit, this.getClass()); } } catch (GitAPIException ex) { Base.writeLog( "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update", this.getClass()); } try { remoteAddCmd = git.remoteAdd(); remoteAddCmd.setName("origin"); remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL)); remoteAddCmd.call(); } catch (URISyntaxException ex) { Base.writeLog("Invalid git filament repo remote URL!", this.getClass()); return; } catch (GitAPIException ex) { Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass()); return; } try { if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH + ", searching for it", this.getClass()); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); branchList = git.branchList().call(); for (Ref ref : branchList) { if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) { Base.writeLog("Correct branch was found locally", this.getClass()); branchFoundLocally = true; break; } } if (branchFoundLocally == false) { Base.writeLog( "No correct branch was found locally, attempting to checkout a new branch tracking the remote", this.getClass()); checkoutCmd.setCreateBranch(true); checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH); git.fetch().call(); } RevCommit backup = null; if (git.status().call().isClean() == false) { git.add().addFilepattern(".").call(); backup = git.commit().setMessage("local backup of user modifications").call(); } newBranch = checkoutCmd.call().getName(); if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Unable to change to correct branch, aborting update", this.getClass()); return; } else { Base.writeLog("Changed to correct branch, " + newBranch, this.getClass()); } try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after branch change: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update", this.getClass()); } if (backup != null) { // TODO: restore backup of user modifications //git.cherryPick().setNoCommit(true).include(backup).call(); } } repoStatus = git.status().call(); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); checkoutCmd.call(); git.fetch(); resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); git.pull().call(); /* repoStatus = git.status().call(); if (repoStatus.hasUncommittedChanges()) { Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass()); stash = git.stashCreate().call(); git.pull().call(); git.stashApply().call(); // will apply the last stash made git.stashDrop().call(); // remove the last stash made } else { Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass()); git.pull().call(); } */ Base.writeLog("Filament update concluded successfully!", this.getClass()); try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after update process finished: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update", this.getClass()); } } catch (GitAPIException ex) { Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass()); try { resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); if (stash != null) { git.stashApply().call(); git.stashDrop().call(); } } catch (GitAPIException ex1) { Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...", this.getClass()); } } }
From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java
License:Apache License
/** * Link and fetch from remote.//from w w w .j a v a 2 s . c o m * * @param remoteAddress the remote address * @param username the username * @param password the password * @throws IllegalArgumentException the illegal argument exception * @throws IOException Signals that an I/O exception has occurred. * @throws AuthenticationException the authentication exception * @see sh.isaac.api.sync.SyncFiles#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String) */ @Override public void linkAndFetchFromRemote(String remoteAddress, String username, char[] password) throws IllegalArgumentException, IOException, AuthenticationException { LOG.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", this.localFolder, remoteAddress, username); Repository r = null; Git git = null; try { final File gitFolder = new File(this.localFolder, ".git"); r = new FileRepository(gitFolder); if (!gitFolder.isDirectory()) { LOG.debug("Root folder does not contain a .git subfolder. Creating new git repository."); r.create(); } relinkRemote(remoteAddress, username, password); git = new Git(r); final CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username, ((password == null) ? new char[] {} : password)); LOG.debug("Fetching"); final FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call(); LOG.debug("Fetch messages: {}", fr.getMessages()); boolean remoteHasMaster = false; final Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call(); for (final Ref ref : refs) { if ("refs/heads/master".equals(ref.getName())) { remoteHasMaster = true; LOG.debug("Remote already has 'heads/master'"); break; } } if (remoteHasMaster) { // we need to fetch and (maybe) merge - get onto origin/master. LOG.debug("Fetching from remote"); final String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages(); LOG.debug("Fetch Result: {}", fetchResult); LOG.debug("Resetting to origin/master"); git.reset().setMode(ResetType.MIXED).setRef("origin/master").call(); // Get the files from master that we didn't have in our working folder LOG.debug("Checking out missing files from origin/master"); for (final String missing : git.status().call().getMissing()) { LOG.debug("Checkout {}", missing); git.checkout().addPath(missing).call(); } for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) { LOG.debug("Adding and committing {}", newFile); git.add().addFilepattern(newFile).call(); git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call(); for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) { LOG.debug("Push Message: {}", pr.getMessages()); } } } else { // just push // make sure we have something to push for (final String newFile : makeInitialFilesAsNecessary(this.localFolder)) { LOG.debug("Adding and committing {}", newFile); git.add().addFilepattern(newFile).call(); } git.commit().setMessage("Adding initial files").setAuthor(username, "42").call(); LOG.debug("Pushing repository"); for (final PushResult pr : git.push().setCredentialsProvider(cp).call()) { LOG.debug("Push Result: {}", pr.getMessages()); } } LOG.info("linkAndFetchFromRemote Complete. Current status: " + statusToString(git.status().call())); } catch (final TransportException te) { if (te.getMessage().contains("Auth fail") || te.getMessage().contains("not authorized")) { LOG.info("Auth fail", te); throw new AuthenticationException("Auth fail"); } else { LOG.error("Unexpected", te); throw new IOException("Internal error", te); } } catch (final GitAPIException e) { LOG.error("Unexpected", e); throw new IOException("Internal error", e); } finally { if (git != null) { git.close(); } if (r != null) { r.close(); } } }
From source file:to.sauerkraut.krautadmin.core.Toolkit.java
License:Open Source License
public static boolean updateFromGit(final File repositoryDirectory, final URI repositoryUri) throws Exception { final String unexpectedExceptionText = "incremental plugin-update from git failed"; final String upstream = "refs/remotes/origin/master"; boolean hasUpdated = false; Git gitRepo = null; try {//from w ww . j ava 2s.c o m gitRepo = Git.open(repositoryDirectory); // first reset local changes gitRepo.reset().setMode(ResetCommand.ResetType.HARD).call(); LOG.info("starting incremental plugin-update from git..."); gitRepo.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call(); final RebaseResult rebaseResult = gitRepo.rebase().setStrategy(MergeStrategy.THEIRS) .setUpstream(upstream).setUpstreamName(upstream).call(); final Status rebaseStatus = rebaseResult.getStatus(); if (rebaseStatus.isSuccessful()) { if (!(Status.UP_TO_DATE.equals(rebaseStatus))) { hasUpdated = true; } } else { throw new WTFException(unexpectedExceptionText); } if (hasUpdated) { LOG.info("incremental plugin-update from git successful"); } else { LOG.info("plugin-files are up-to-date"); } } finally { try { if (gitRepo != null) { gitRepo.close(); } } catch (Exception closex) { LOG.debug("closing git repo failed"); } } return hasUpdated; }