List of usage examples for org.eclipse.jgit.api CommitCommand setAmend
public CommitCommand setAmend(boolean amend)
From source file:com.google.gerrit.acceptance.git.GitUtil.java
License:Apache License
private static Commit createCommit(Git git, PersonIdent i, String msg, String changeId) throws GitAPIException, IOException { final CommitCommand commitCmd = git.commit(); commitCmd.setAmend(changeId != null); commitCmd.setAuthor(i);//from w ww . j a v a 2 s . c om commitCmd.setCommitter(i); if (changeId == null) { ObjectId id = computeChangeId(git, i, msg); changeId = "I" + id.getName(); } msg = ChangeIdUtil.insertId(msg, ObjectId.fromString(changeId.substring(1))); commitCmd.setMessage(msg); RevCommit c = commitCmd.call(); return new Commit(c, changeId); }
From source file:com.rimerosolutions.ant.git.tasks.CommitTask.java
License:Apache License
@Override protected void doExecute() throws BuildException { try {/*from www .j a va 2 s. com*/ setFailOnError(true); CommitCommand cmd = git.commit(); if (!GitTaskUtils.isNullOrBlankString(message)) { cmd.setMessage(brandedMessage ? GitTaskUtils.BRANDING_MESSAGE + " " : "" + message); } else { cmd.setMessage(GitTaskUtils.BRANDING_MESSAGE); } String prefix = getDirectory().getCanonicalPath(); String[] allFiles = getPath().list(); if (!GitTaskUtils.isNullOrBlankString(only)) { cmd.setOnly(only); } else if (allFiles.length > 0) { for (String file : allFiles) { String modifiedFile = translateFilePathUsingPrefix(file, prefix); log("Will commit " + modifiedFile); cmd.setOnly(modifiedFile); } } else { cmd.setAll(true); } GitSettings gitSettings = lookupSettings(); if (gitSettings == null) { throw new MissingRequiredGitSettingsException(); } cmd.setAmend(amend).setAuthor(gitSettings.getIdentity()).setCommitter(gitSettings.getIdentity()); if (reflogComment != null) { cmd.setReflogComment(reflogComment); } RevCommit revCommit = cmd.call(); if (revCommitIdProperty != null) { String revisionId = ObjectId.toString(revCommit.getId()); getProject().setProperty(revCommitIdProperty, revisionId); } log(revCommit.getFullMessage()); } catch (IOException ioe) { throw new GitBuildException(MESSAGE_COMMIT_FAILED, ioe); } catch (GitAPIException ex) { throw new GitBuildException(MESSAGE_COMMIT_FAILED, ex); } }
From source file:de.ks.blogging.grav.pages.GravPages.java
License:Apache License
public void addCommit(String msg) throws RuntimeException { Git git = getGit();/*from ww w. j a v a 2s. c om*/ if (git != null) { try { Status status = git.status().call(); Set<String> modified = status.getModified(); Set<String> untracked = status.getUntracked(); AddCommand add = git.add(); modified.forEach(s -> add.addFilepattern(s)); untracked.forEach(s -> add.addFilepattern(s)); add.call(); CommitCommand commit = git.commit(); if (msg == null || msg.isEmpty()) { commit.setAmend(true); } else { commit.setMessage(msg); } RevCommit rev = commit.call(); log.info("Commited change {} with new rev {}", msg, rev); } catch (Exception e) { log.error("Could not add and commit ", e); throw new RuntimeException(e); } } }
From source file:net.polydawn.mdm.commands.MdmReleaseCommand.java
License:Open Source License
public MdmExitMessage call() throws IOException, MdmException, MdmExitMessage { MdmModuleRelease relModule = loadReleaseModule(); Repository relRepo = relModule.getRepo(); relModule.assertPresentsAsReleaseRepo(); assertReleaseRepoDoesntAlreadyContain(relModule, version); assertReleaseRepoClean(relModule);//from w w w . j a v a2s . c o m List<String> inputFiles = selectInputFiles(); // create a branch for the release commit. depending on whether or not infix mode is enabled, this is either branching from the infix branch, or it's founding a new root of history. boolean infixMode = relRepo.getRef("refs/heads/mdm/infix") != null; if (infixMode) try { new Git(relRepo).checkout().setCreateBranch(true).setStartPoint("mdm/infix") .setName("mdm/release/" + version).call(); } catch (RefAlreadyExistsException e) { return new MdmExitMessage(":'(", "the releases repo already has a release point labeled version " + version + " !"); } catch (RefNotFoundException e) { throw new MdmException("aborted due to concurrent modification of repo"); } catch (InvalidRefNameException e) { return new MdmExitMessage(":(", "you can't use version names that git rejects as branch names."); } catch (CheckoutConflictException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } else { Plumbing.createOrphanBranch(relRepo, "mdm/release/" + version); try { new Git(relRepo).checkout().setName("mdm/release/" + version).call(); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } } // enumerate and copy in artifact files. File inputBase = new File(inputPath).getCanonicalFile(); if (inputBase.isFile()) inputBase = inputBase.getParentFile(); File relRepoFile = new File(relRepoPath).getCanonicalFile(); for (String input : inputFiles) { File inputFull = new File(inputBase, input); File dest = new File(relRepoFile, input); if (inputFull.isDirectory()) FileUtils.copyDirectory(inputFull, dest, new FileFilter() { public boolean accept(File file) { return !(file.isDirectory() && file.listFiles().length == 0); } }, true, false); else FileUtils.copyFile(inputFull, dest, true, false); } // commit the changes try { new Git(relRepo).add().addFilepattern(".").call(); } catch (NoFilepatternException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } try { CommitCommand commit = new Git(relRepo).commit().setMessage("release version " + version); if (!infixMode) { commit.setAmend(true); // because our mechanism for creating an orphan branch starts us with an empty commit. PersonIdent convergenceIdent = new PersonIdent("mdm", "", new Date(0), TimeZone.getTimeZone("GMT")); commit.setAuthor(convergenceIdent); commit.setCommitter(convergenceIdent); } commit.call(); // this tag will be removed in a future release, as it's no longer required for any structural purpose // (long long ago in a galaxy far away, this was used as an easy way for `mdm status` to report version names... but execing `git describe --tags` hasn't been the way we do this anymore for a long time now) new Git(relRepo).tag().setName("release/" + version).setAnnotated(false).call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (ConcurrentRefUpdateException e) { throw new MdmException("aborted due to concurrent modification of repo"); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (UnmergedPathsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } // generate an accumulation commit. do this from the master branch, but don't submit it yet, because when we roll in the artifacts we want them in a subdirectory so that when master is checked out all the versions are splayed out in the working tree at once. try { new Git(relRepo).checkout().setName("master").call(); } catch (RefAlreadyExistsException e) { throw new MajorBug(e); // not even valid unless we're creating a new branch, which we aren't. } catch (RefNotFoundException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (InvalidRefNameException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (CheckoutConflictException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } try { new Git(relRepo).merge().include(relRepo.getRef("mdm/release/" + version)) .setFastForward(FastForwardMode.NO_FF).setCommit(false).call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (ConcurrentRefUpdateException e) { throw new MdmException("aborted due to concurrent modification of repo"); } catch (CheckoutConflictException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (InvalidMergeHeadsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? also, we're not even making a commit here. } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } // move the artifact files into a version-named directory File artifactDestFile = new File(relRepoFile, version); if (!artifactDestFile.mkdir()) return new MdmExitMessage(":'(", "couldn't make the directory named \"" + version + "\" to put the releases into because there was already something there."); for (String input : inputFiles) new File(relRepoFile, input).renameTo(new File(artifactDestFile, input)); // now fire off the accumulation commit, and that commit now becomes head of the master branch. try { RmCommand rmc = new Git(relRepo).rm(); for (String input : inputFiles) rmc.addFilepattern(input); rmc.call(); new Git(relRepo).add().addFilepattern(version).call(); } catch (NoFilepatternException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } try { new Git(relRepo).commit().setMessage("merge release version " + version + " to master").call(); new Git(relRepo).tag().setName("mdm/master/" + version).setAnnotated(false).call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (ConcurrentRefUpdateException e) { throw new MdmException("aborted due to concurrent modification of repo"); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (UnmergedPathsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } // commit the new hash of the releases-repo into the project main repo (if we are operating in a canonically placed releases submodule) if (isInRepoRoot() && relRepoPath.equals("releases") && Plumbing.isCommitedGitlink(repo, "releases")) { try { new Git(repo).commit().setOnly("releases").setMessage("release version " + version).call(); new Git(repo).tag().setName("release/" + version).setAnnotated(false).call(); } catch (NoHeadException e) { throw new MdmException("your repository is in an invalid state!", e); } catch (ConcurrentRefUpdateException e) { throw new MdmException("aborted due to concurrent modification of repo"); } catch (NoMessageException e) { throw new MajorBug(e); // why would an api throw exceptions like this *checked*? } catch (UnmergedPathsException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (WrongRepositoryStateException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } catch (GitAPIException e) { throw new MajorBug("an unrecognized problem occurred. please file a bug report.", e); } } return new MdmExitMessage(":D", "release version " + version + " complete"); }
From source file:org.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private boolean handlePost(HttpServletRequest request, HttpServletResponse response, Repository db, Path path) throws ServletException, NoFilepatternException, IOException, JSONException, CoreException, URISyntaxException {/*from ww w. j av a 2s . c om*/ IPath filePath = path.hasTrailingSeparator() ? path.removeFirstSegments(1) : path.removeFirstSegments(1).removeLastSegments(1); Set<Entry<IPath, File>> set = GitUtils.getGitDirs(filePath, Traverse.GO_UP).entrySet(); File gitDir = set.iterator().next().getValue(); if (gitDir == null) return false; // TODO: or an error response code, 405? db = new FileRepository(gitDir); JSONObject requestObject = OrionServlet.readJSONRequest(request); String commitToMerge = requestObject.optString(GitConstants.KEY_MERGE, null); if (commitToMerge != null) { return merge(request, response, db, commitToMerge); } String commitToRebase = requestObject.optString(GitConstants.KEY_REBASE, null); String rebaseOperation = requestObject.optString(GitConstants.KEY_OPERATION, null); if (commitToRebase != null) { return rebase(request, response, db, commitToRebase, rebaseOperation); } String commitToCherryPick = requestObject.optString(GitConstants.KEY_CHERRY_PICK, null); if (commitToCherryPick != null) { return cherryPick(request, response, db, commitToCherryPick); } // continue with creating new commit location String newCommitToCreatelocation = requestObject.optString(GitConstants.KEY_COMMIT_NEW, null); if (newCommitToCreatelocation != null) return createCommitLocation(request, response, db, newCommitToCreatelocation); ObjectId refId = db.resolve(path.segment(0)); if (refId == null || !Constants.HEAD.equals(path.segment(0))) { String msg = NLS.bind("Commit failed. Ref must be HEAD and is {0}", path.segment(0)); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } String message = requestObject.optString(GitConstants.KEY_COMMIT_MESSAGE, null); if (message == null || message.isEmpty()) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit message.", null)); } boolean amend = Boolean.parseBoolean(requestObject.optString(GitConstants.KEY_COMMIT_AMEND, null)); String committerName = requestObject.optString(GitConstants.KEY_COMMITTER_NAME, null); String committerEmail = requestObject.optString(GitConstants.KEY_COMMITTER_EMAIL, null); String authorName = requestObject.optString(GitConstants.KEY_AUTHOR_NAME, null); String authorEmail = requestObject.optString(GitConstants.KEY_AUTHOR_EMAIL, null); Git git = new Git(db); CommitCommand commit = git.commit(); // workaround of a bug in JGit which causes invalid // support of null values of author/committer name/email PersonIdent defPersonIdent = new PersonIdent(db); if (committerName == null) committerName = defPersonIdent.getName(); if (committerEmail == null) committerEmail = defPersonIdent.getEmailAddress(); if (authorName == null) authorName = committerName; if (authorEmail == null) authorEmail = committerEmail; commit.setCommitter(committerName, committerEmail); commit.setAuthor(authorName, authorEmail); // support for committing by path: "git commit -o path" boolean isRoot = true; String pattern = GitUtils.getRelativePath(path.removeFirstSegments(1), set.iterator().next().getKey()); if (!pattern.isEmpty()) { commit.setOnly(pattern); isRoot = false; } try { // "git commit [--amend] -m '{message}' [-a|{path}]" RevCommit lastCommit = commit.setAmend(amend).setMessage(message).call(); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = toJSON(db, lastCommit, commitToBranchMap, getURI(request), null, isRoot); OrionServlet.writeJSONResponse(request, response, result); return true; } catch (GitAPIException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "An error occured when commiting.", e)); } catch (JGitInternalException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An internal error occured when commiting.", e)); } }
From source file:org.flowerplatform.web.git.operation.CommitOperation.java
License:Open Source License
public boolean commit(String repositoryLocation, List<CommitResourceDto> files, String author, String committer, String message, boolean amending) { ProgressMonitor monitor = ProgressMonitor .create(GitPlugin.getInstance().getMessage("git.commit.monitor.title"), channel); try {// w ww . j ava 2 s. co m Repository repo = GitPlugin.getInstance().getUtils().getRepository(new File(repositoryLocation)); Collection<String> notTracked = new HashSet<String>(); Collection<String> resources = new HashSet<String>(); for (CommitResourceDto file : files) { resources.add(file.getPath()); if (file.getState() == CommitResourceDto.UNTRACKED) { notTracked.add(file.getPath()); } } monitor.beginTask(GitPlugin.getInstance().getMessage("git.commit.monitor.message"), 10); addUntracked(notTracked, repo); monitor.worked(1); CommitCommand commitCommand = new Git(repo).commit(); commitCommand.setAmend(amending).setMessage(message); for (String path : resources) { commitCommand.setOnly(path); } Date commitDate = new Date(); TimeZone timeZone = TimeZone.getDefault(); PersonIdent enteredAuthor = RawParseUtils.parsePersonIdent(author); PersonIdent enteredCommitter = RawParseUtils.parsePersonIdent(committer); if (enteredAuthor == null) { channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance() .getMessage("git.commit.errorParsingPersonIdent", new Object[] { author }), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } if (enteredCommitter == null) { channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand( CommonPlugin.getInstance().getMessage("error"), GitPlugin.getInstance() .getMessage("git.commit.errorParsingPersonIdent", new Object[] { committer }), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } PersonIdent authorIdent = new PersonIdent(enteredAuthor, commitDate, timeZone); PersonIdent committerIdent = new PersonIdent(enteredCommitter, commitDate, timeZone); if (amending) { RevCommit headCommit = GitPlugin.getInstance().getUtils().getHeadCommit(repo); if (headCommit != null) { PersonIdent headAuthor = headCommit.getAuthorIdent(); authorIdent = new PersonIdent(enteredAuthor, headAuthor.getWhen(), headAuthor.getTimeZone()); } } commitCommand.setAuthor(authorIdent); commitCommand.setCommitter(committerIdent); monitor.worked(1); commitCommand.call(); if (monitor.isCanceled()) { return false; } monitor.worked(8); // GitLightweightDecorator.refresh(); // // updateDispatcher.dispatchContentUpdate(null, repo, GitTreeUpdateDispatcher.COMMIT, null); return true; } catch (Exception e) { logger.debug(GitPlugin.getInstance().getMessage("git.commit.error"), e); channel.appendOrSendCommand( new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"), e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR)); return false; } finally { monitor.done(); } }