public void reset(final int noOfCommitsToRevert, final String message) { final Repository repository = getRepository(); final RevCommit commit = findCommit(Constants.HEAD + REVISION_STRING_DELIMITER + noOfCommitsToRevert, repository); if (commit == null) { return; } try { final Git git = new Git(repository); git.reset().setRef(commit.getName()).setMode(ResetType.HARD).call(); // Commit changes commitAllChanges(message); LOGGER.info("Reset of last " + (noOfCommitsToRevert + 1) + " successful."); } catch (final Exception e) { throw new IllegalStateException("Reset did not succeed.", e); } }
private void cherryPickCommitToBranch(ObjectId id, Project project, Branch branch) { doWithGit(project, git -> { try { checkout(project, branch); } catch (RuntimeException o_O) { logger.log(project, "Couldn't check out branch %s. Skipping cherrypick of commit %s.", branch, id.getName()); return; } logger.log(project, "git cp %s", id.getName()); CherryPickResult result = git.cherryPick().include(id).call(); if (result.getStatus().equals(CherryPickStatus.OK)) { logger.log(project, "Successfully cherry-picked commit %s to branch %s.", id.getName(), branch); } else { logger.warn(project, "Cherry pick failed. aborting…"); logger.log(project, "git reset --hard"); git.reset().setMode(ResetType.HARD).call(); } }); }
@Override protected void buttonPressed(int buttonId) { switch (buttonId) { case IDialogConstants.PROCEED_ID: CommitUI commitUI = new CommitUI(getShell(), repository, new IResource[0], true); shouldContinue = commitUI.commit(); break; case IDialogConstants.ABORT_ID: final ResetOperation operation = new ResetOperation(repository, Constants.HEAD, ResetType.HARD); String jobname = NLS.bind(UIText.ResetAction_reset, Constants.HEAD); JobUtil.scheduleUserWorkspaceJob(operation, jobname, JobFamilies.RESET); shouldContinue = true; break; case IDialogConstants.SKIP_ID: StashCreateUI stashCreateUI = new StashCreateUI(repository); shouldContinue = stashCreateUI.createStash(getShell()); break; case IDialogConstants.CANCEL_ID: } super.buttonPressed(buttonId); }
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor; if (m == null) monitor = new NullProgressMonitor(); else monitor = m; if (type == ResetType.HARD) { IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { reset(actMonitor); } }; // lock workspace to protect working tree changes ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); } else { reset(monitor); } }
public static void pullRepository() { try { logger.info("Scanning devices folder for changes."); git.add().addFilepattern(".").call(); Status status = git.status().call(); if (status.getChanged().size()>0 || status.getAdded().size()>0 || status.getModified().size()>0) { logger.info("Changes have been found. Doing a hard reset (removing user modifications)."); ResetCommand reset = git.reset(); reset.setMode(ResetType.HARD); reset.setRef(Constants.HEAD); reset.call(); } logger.info("Pulling changes from github."); git.pull().call(); } catch (NoHeadException e) { logger.info("Pull failed. Trying to clone repository instead"); closeRepository(); cloneRepository(); } catch (Exception e1) { closeRepository(); } }
private Ref resetHard(Git git, String label, String ref) { ResetCommand reset = git.reset(); reset.setRef(ref); reset.setMode(ResetType.HARD); try { Ref resetRef = reset.call(); if (resetRef != null) { this.logger.info( "Reset label " + label + " to version " + resetRef.getObjectId()); } return resetRef; } catch (Exception ex) { String message = "Could not reset to remote for " + label + " (current ref=" + ref + "), remote: " + git.getRepository().getConfig() .getString("remote", "origin", "url"); warn(message, ex); return null; } }
/** * Switch to the main branch and delete the temporary branch. * * @throws GitAPIException * @throws RefAlreadyExistsException * @throws RefNotFoundException * @throws InvalidRefNameException * @throws CheckoutConflictException * @throws NotMergedException * @throws CannotDeleteCurrentBranchException */ private void switchToMainAndDeleteFrom(final String tempBranch) throws GitAPIException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, CheckoutConflictException, NotMergedException, CannotDeleteCurrentBranchException { try { repository.reset().setMode(ResetType.HARD).call(); } finally { try { repository.checkout().setCreateBranch(false) .setName(mainBranchName).setForce(true).call(); } finally { try { repository.reset().setMode(ResetType.HARD).call(); } finally { repository.branchDelete().setForce(true) .setBranchNames(tempBranch).call(); } } } }
@Override public void checkout(String hash) { LOG.info(String.format("Checking out %s.", hash)); File lockFile = new File(git.getRepository().getDirectory(), "git/index.lock"); if (lockFile.exists()) { lockFile.delete(); } try { git.reset().setMode(ResetType.HARD).call(); git.checkout().setName("master").call(); git.checkout().setCreateBranch(true).setName("rm_branch"+branchCounter++) .setStartPoint(hash).setForce(true).setOrphan(true).call(); } catch (GitAPIException e) { close(); throw new RepositoryMinerException(e); } }
/** * If mode is set, apply the specified mode according to Git manual. * * @antdoc.notrequired * @param mode the mode used to perform git reset. (Default is MIXED) */ public void setMode(String mode) { if ("soft".equalsIgnoreCase(mode)) { this.mode = ResetType.SOFT; } else if ("mixed".equalsIgnoreCase(mode)) { this.mode = ResetType.MIXED; } else if ("hard".equalsIgnoreCase(mode)) { this.mode = ResetType.HARD; } else if ("merge".equalsIgnoreCase(mode)) { this.mode = ResetType.MERGE; } else if ("keep".equalsIgnoreCase(mode)) { this.mode = ResetType.KEEP; } else { this.mode = ResetType.MIXED; } }
private void resetAndRemoveUntrackedFiles( final Git repository ) throws GitAPIException, CheckoutConflictException { repository.clean() // .setCleanDirectories( true ) // .setForce( true ) // .setIgnore( false ) // .call(); // repository.reset() // .setMode( ResetType.HARD ) // .call(); // }
/** * Restore to the initial state of the repository. Only applicable if the * repository has conflicts */ public void restartMerge() { try { AnyObjectId commitToMerge = git.getRepository().resolve("MERGE_HEAD"); git.clean().call(); git.reset().setMode(ResetType.HARD).call(); git.merge().include(commitToMerge).setStrategy(MergeStrategy.RECURSIVE).call(); fireFileStateChanged(new ChangeEvent(GitCommand.MERGE_RESTART, Collections.<String> emptyList())); } catch (GitAPIException | IOException e) { if (logger.isDebugEnabled()) { logger.debug(END_FETCH_DEBUG_MESSAGE); } } }
public void reset() { /* delete lock file if one is present */ File f = new File(gitRepoPath + "/.git/index.lock"); if(f.exists()) { f.delete(); } /* reset --hard HEAD */ try { git.reset().setMode(ResetType.HARD).call(); } catch (Exception e) { e.printStackTrace(); } }
public void close() throws GitAPIException { Git git = gitRepository.getGit(); git.reset().setMode(ResetType.HARD).call(); if (indexUpdate != null) { indexUpdate.close(); } }
private void reset(Project project, Branch branch) throws Exception { logger.log(project, "git reset --hard origin/%s", branch); doWithGit(project, git -> { git.reset()// .setMode(ResetType.HARD)// .setRef("origin/".concat(branch.toString()))// .call(); }); }
@Override public void reset(ResetParams params) throws GitException { try { ResetCommand resetCommand = getGit().reset(); resetCommand.setRef(params.getCommit()); List<String> patterns = params.getFilePattern(); patterns.forEach(resetCommand::addPath); if (params.getType() != null && patterns.isEmpty()) { switch (params.getType()) { case HARD: resetCommand.setMode(ResetType.HARD); break; case KEEP: resetCommand.setMode(ResetType.KEEP); break; case MERGE: resetCommand.setMode(ResetType.MERGE); break; case MIXED: resetCommand.setMode(ResetType.MIXED); break; case SOFT: resetCommand.setMode(ResetType.SOFT); break; } } resetCommand.call(); } catch (GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } }
public void reset(String refToResetTo) { ResetCommand command = _git.reset(); command.setRef(refToResetTo); command.setMode(ResetType.HARD); try { command.call(); } catch (Throwable e) { throw new RuntimeException(String.format("Failed to reset to [%s]", refToResetTo), e); } }
public void dumpConfiguration(Configuration config, Entry e) throws Exception { Preconditions.checkNotNull(config, "Configuration must be supplied."); Preconditions.checkNotNull(e, "Entry must be supplied."); AddCommand add = git.add(); CommitCommand commit = git.commit(); try { //Dump Zookeeper String instanceId = config.getConnector().getInstance().getInstanceID(); String zkPath = Constants.ZROOT + "/" + instanceId; File zkDump = new File(gitDir, ZK_DUMP_FILE); LOG.debug("Dump ZooKeeper configuration at {} to {}", zkPath, zkDump); FileOutputStream out = new FileOutputStream(zkDump); DumpZookeeper.run(out, zkPath); out.close(); //Dump the configuration LOG.debug("Dumping Accumulo configuration to {}", gitDir); DumpConfigCommand command = new DumpConfigCommand(); command.allConfiguration = true; command.directory = gitDir.getAbsolutePath(); Instance instance = config.getConnector().getInstance(); String principal = config.getUsername(); PasswordToken token = new PasswordToken(config.getPassword().getBytes()); Admin.printConfig(instance, principal, token, command); //Add, commit, and tag add.addFilepattern(".").call(); commit.setMessage("Backup " + e.getUUID().toString()).call(); git.tag().setName(e.getUUID().toString()).call(); LOG.debug("Git tag {} created.", e.getUUID()); //Should we remove all of the files from the existing git workspace? } catch (Exception ex) { LOG.error("Error saving configuration", ex); git.reset().setMode(ResetType.HARD).setRef("HEAD").call(); throw ex; } }
Ref resetHard() { try { ResetCommand resetCmd = git.reset().setMode(ResetType.HARD); return resetCmd.call(); } catch (GitAPIException ex) { throw new IllegalStateException("Cannot reset workspace", ex); } }
private void resetHard(final Git git, ObjectId remoteId) throws ProjectException { log.info(this + ": Reseting HEAD to: " + remoteId); try { git.reset().setMode(ResetType.HARD).setRef(remoteId.name()).call(); } catch (GitAPIException e) { throw new ProjectException(this + ": Failed to reset HEAD"); } }
private void resetToBranch() throws IOException, GitAPIException { Ref master = repository.getRef(Constants.R_HEADS + "master"); if (master != null) { Git git = new Git(repository); git.reset().setMode(ResetType.HARD).setRef(master.getName()).call(); } }
@Test public void remoteToLocal() throws Exception { final Entry<JsonNode> expectedInitialMirrorState = expectedMirrorState("/"); pushMirrorSettings(null, null); final Revision rev0 = client.normalizeRevision(projName, REPO_MAIN, Revision.HEAD).join(); // Mirror an empty git repository, which will; // - Create /mirror_state.json // - Remove the sample files created by createProject(). mirroringService.mirror().join(); //// Make sure a new commit is added. final Revision rev1 = client.normalizeRevision(projName, REPO_MAIN, Revision.HEAD).join(); assertThat(rev1).isEqualTo(rev0.forward(1)); //// Make sure /mirror_state.json exists (and nothing else.) assertThat(client.getFiles(projName, REPO_MAIN, rev1, "/**").join().values()) .containsExactly(expectedInitialMirrorState); // Try to mirror again with no changes in the git repository. mirroringService.mirror().join(); //// Make sure it does not try to produce an empty commit. final Revision rev2 = client.normalizeRevision(projName, REPO_MAIN, Revision.HEAD).join(); assertThat(rev2).isEqualTo(rev1); // Now, add some files to the git repository and mirror. //// This file should not be mirrored because it does not conform to CD's file naming rule. addToGitIndex(".gitkeep", ""); addToGitIndex("first/light.txt", "26-Aug-2014"); addToGitIndex("second/son.json", "{\"release_date\": \"21-Mar-2014\"}"); git.commit().setMessage("Add the release dates of the 'Infamous' series").call(); final Entry<JsonNode> expectedSecondMirrorState = expectedMirrorState("/"); mirroringService.mirror().join(); //// Make sure a new commit is added. final Revision rev3 = client.normalizeRevision(projName, REPO_MAIN, Revision.HEAD).join(); assertThat(rev3).isEqualTo(rev2.forward(1)); //// Make sure the two files are all there. assertThat(client.getFiles(projName, REPO_MAIN, rev3, "/**").join().values()) .containsExactlyInAnyOrder(expectedSecondMirrorState, Entry.ofDirectory("/first"), Entry.ofText("/first/light.txt", "26-Aug-2014\n"), Entry.ofDirectory("/second"), Entry.ofJson("/second/son.json", "{\"release_date\": \"21-Mar-2014\"}")); // Rewrite the history of the git repository and mirror. git.reset().setMode(ResetType.HARD).setRef("HEAD^").call(); addToGitIndex("final_fantasy_xv.txt", "29-Nov-2016"); git.commit().setMessage("Add the release date of the 'Final Fantasy XV'").call(); final Entry<JsonNode> expectedThirdMirrorState = expectedMirrorState("/"); mirroringService.mirror().join(); //// Make sure a new commit is added. final Revision rev4 = client.normalizeRevision(projName, REPO_MAIN, Revision.HEAD).join(); assertThat(rev4).isEqualTo(rev3.forward(1)); //// Make sure the rewritten content is mirrored. assertThat(client.getFiles(projName, REPO_MAIN, rev4, "/**").join().values()) .containsExactlyInAnyOrder(expectedThirdMirrorState, Entry.ofText("/final_fantasy_xv.txt", "29-Nov-2016\n")); }
@VisibleForTesting void resetHard() throws Exception { git.reset().setMode( ResetType.HARD ).call(); }
public void hardReset() throws Exception { git.reset().setMode(ResetType.HARD).call(); git.clean().call(); }
public void restore() throws GitAPIException { if (branchName != null) { git.reset().setMode(ResetType.HARD).call(); } }
public ISchedulingRule getSchedulingRule() { if (type == ResetType.HARD) return RuleUtil.getRule(repository); else return null; }
private void resetTargetHard(Git git) throws Exception { git.reset().setMode(ResetType.HARD) .setRef("origin/" + request.getTarget().getBranch()).call(); notifier.message("Reset origin/" + request.getTarget().getBranch()); }
/** * Tests a special use case where the remote repository has been updated * with a forced push conflicting with the local repo of the Config Server. * The Config Server has to reset hard on the new reference because a simple * pull operation could result in a conflicting local repository. */ @Test public void pullDirtyRepo() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); // Create a remote bare repository. Repository remote = ConfigServerTestUtils.prepareBareRemote(); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), commitToRevertBeforePull); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), conflictingCommit); assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean()); }
/** * Construct a {@link ResetOperation} * * @param repository * @param refName * @param type */ public ResetOperation(Repository repository, String refName, ResetType type, boolean closeRemovedProjects) { this.repository = repository; this.refName = refName; this.type = type; this.closeRemovedProjects = closeRemovedProjects; }