List of usage examples for org.eclipse.jgit.lib Repository resolve
@Nullable public ObjectId resolve(String revstr) throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException
From source file:org.eclipse.orion.server.gerritfs.GitDiff.java
License:Open Source License
private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException { final ObjectId id = db.resolve(name); if (id == null) throw new IllegalArgumentException(name); final CanonicalTreeParser p = new CanonicalTreeParser(); final ObjectReader or = db.newObjectReader(); RevWalk rw = new RevWalk(db); try {/* w ww. j av a2s .com*/ p.reset(or, rw.parseTree(id)); return p; } finally { or.release(); rw.release(); } }
From source file:org.eclipse.orion.server.git.jobs.ListBranchesJob.java
License:Open Source License
@Override protected IStatus performJob() { try {//from ww w .j av a 2s . co m File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); Git git = new Git(db); List<Ref> branchRefs = git.branchList().call(); List<Branch> branches = new ArrayList<Branch>(branchRefs.size()); for (Ref ref : branchRefs) { branches.add(new Branch(cloneLocation, db, ref)); } Collections.sort(branches, Branch.COMPARATOR); JSONObject result = new JSONObject(); JSONArray children = new JSONArray(); int firstBranch = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastBranch = pageSize > 0 ? firstBranch + pageSize - 1 : branches.size() - 1; lastBranch = lastBranch > branches.size() - 1 ? branches.size() - 1 : lastBranch; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastBranch < branches.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstBranch; i <= lastBranch; i++) { Branch branch = branches.get(i); if (commitsSize == 0) { children.put(branch.toJSON()); } else { String branchName = branch.getName(true, false); ObjectId toObjectId = db.resolve(branchName); Ref toRefId = db.getRef(branchName); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", branchName); return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); } toObjectId = getCommitObjectId(db, toObjectId); Log log = null; // single commit is requested and we already know it, no need for LogCommand if (commitsSize == 1 && toObjectId instanceof RevCommit) { log = new Log(cloneLocation, db, Collections.singleton((RevCommit) toObjectId), null, null, toRefId); } else { LogCommand lc = git.log(); // set the commit range lc.add(toObjectId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); log = new Log(cloneLocation, db, commits, null, null, toRefId); } log.setPaging(1, commitsSize); children.put(branch.toJSON(log.toJSON())); } } result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(ProtocolConstants.KEY_TYPE, Branch.TYPE); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing branches for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
From source file:org.eclipse.orion.server.git.jobs.ListTagsJob.java
License:Open Source License
@Override protected IStatus performJob() { try {//ww w. j a va 2 s . c o m // list all tags File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); Git git = new Git(db); List<Ref> refs = git.tagList().call(); JSONObject result = new JSONObject(); List<Tag> tags = new ArrayList<Tag>(); for (Ref ref : refs) { Tag tag = new Tag(cloneLocation, db, ref); tags.add(tag); } Collections.sort(tags, Tag.COMPARATOR); JSONArray children = new JSONArray(); int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1; lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastTag < tags.size() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } for (int i = firstTag; i <= lastTag; i++) { Tag tag = tags.get(i); if (this.commitsSize == 0) { children.put(tag.toJSON()); } else { // add info about commits if requested LogCommand lc = git.log(); String toCommitName = tag.getRevCommitName(); ObjectId toCommitId = db.resolve(toCommitName); Ref toCommitRef = db.getRef(toCommitName); toCommitId = getCommitObjectId(db, toCommitId); lc.add(toCommitId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef); log.setPaging(1, commitsSize); children.put(tag.toJSON(log.toJSON())); } } result.put(ProtocolConstants.KEY_CHILDREN, children); result.put(ProtocolConstants.KEY_TYPE, Tag.TYPE); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } catch (Exception e) { String msg = NLS.bind("An error occured when listing tags for {0}", path); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
From source file:org.eclipse.orion.server.git.jobs.RemoteDetailsJob.java
License:Open Source License
@Override protected IStatus performJob() { try {/*w ww.j a v a 2s . c om*/ File gitDir = GitUtils.getGitDir(path); Repository db = new FileRepository(gitDir); Git git = new Git(db); Set<String> configNames = db.getConfig().getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION); for (String configN : configNames) { if (configN.equals(configName)) { Remote remote = new Remote(cloneLocation, db, configN); JSONObject result = remote.toJSON(); if (!result.has(ProtocolConstants.KEY_CHILDREN)) { return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } JSONArray children = result.getJSONArray(ProtocolConstants.KEY_CHILDREN); if (children.length() == 0 || (commitsSize == 0 && pageSize < 0)) { return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } int firstChild = pageSize > 0 ? pageSize * (pageNo - 1) : 0; int lastChild = pageSize > 0 ? firstChild + pageSize - 1 : children.length() - 1; lastChild = lastChild > children.length() - 1 ? children.length() - 1 : lastChild; if (pageNo > 1 && baseLocation != null) { String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev); } if (lastChild < children.length() - 1) { String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize; if (commitsSize > 0) { next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize; } result.put(ProtocolConstants.KEY_NEXT_LOCATION, next); } JSONArray newChildren = new JSONArray(); for (int i = firstChild; i <= lastChild; i++) { JSONObject branch = children.getJSONObject(i); if (commitsSize == 0) { newChildren.put(branch); } else { LogCommand lc = git.log(); String branchName = branch.getString(ProtocolConstants.KEY_ID); ObjectId toObjectId = db.resolve(branchName); Ref toRefId = db.getRef(branchName); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", branchName); return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); } toObjectId = getCommitObjectId(db, toObjectId); // set the commit range lc.add(toObjectId); lc.setMaxCount(this.commitsSize); Iterable<RevCommit> commits = lc.call(); Log log = new Log(cloneLocation, db, commits, null, null, toRefId); log.setPaging(1, commitsSize); branch.put(GitConstants.KEY_TAG_COMMIT, log.toJSON()); newChildren.put(branch); } } result.put(ProtocolConstants.KEY_CHILDREN, newChildren); return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } } String msg = NLS.bind("Couldn't find remote : {0}", configName); return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null); } catch (Exception e) { String msg = NLS.bind("Couldn't get remote details : {0}", configName); return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e); } }
From source file:org.eclipse.orion.server.git.objects.Diff.java
License:Open Source License
private URI getBaseLocation(URI location, Repository db, IPath path) throws URISyntaxException, IOException { String scope = path.segment(0); if (scope.contains("..")) { //$NON-NLS-1$ String[] commits = scope.split("\\.\\."); //$NON-NLS-1$ if (commits.length != 2) { throw new IllegalArgumentException( NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope)); }/*from w w w . j ava2 s .c o m*/ ThreeWayMerger merger = new ResolveMerger(db) { protected boolean mergeImpl() throws IOException { // do nothing return false; } }; // use #merge to set sourceObjects String tip0 = GitUtils.decode(commits[0]); String tip1 = GitUtils.decode(commits[1]); merger.merge(new ObjectId[] { db.resolve(tip0), db.resolve(tip1) }); RevCommit baseCommit = merger.getBaseCommit(0, 1); IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(baseCommit.getId().getName()) .append(path.removeFirstSegments(1)); return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null); //$NON-NLS-1$ } else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) { // HEAD is the base IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD) .append(path.removeFirstSegments(1)); return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null); //$NON-NLS-1$ } else { // index is the base IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1)); return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), null, null); } }
From source file:org.eclipse.orion.server.git.objects.Tag.java
License:Open Source License
public Tag(URI cloneLocation, Repository db, Ref ref) throws IOException, CoreException { super(cloneLocation, db); RevWalk rw = new RevWalk(db); RevObject any;/*from w w w . ja v a 2 s . c om*/ try { any = rw.parseAny(db.resolve(ref.getName())); } finally { rw.dispose(); } if (any instanceof RevTag) this.tag = (RevTag) any; else this.ref = ref; }
From source file:org.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private boolean handleGetCommitBody(HttpServletRequest request, HttpServletResponse response, Repository db, String ref, String pattern) throws AmbiguousObjectException, IOException, ServletException { ObjectId refId = db.resolve(ref); if (refId == null) { String msg = NLS.bind("Failed to generate commit log for ref {0}", ref); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); }/*from ww w . j a v a 2 s.c o m*/ RevWalk walk = new RevWalk(db); walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(pattern)), TreeFilter.ANY_DIFF)); RevCommit commit = walk.parseCommit(refId); final TreeWalk w = TreeWalk.forPath(db, pattern, commit.getTree()); if (w == null) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, null, null)); } ObjectId blobId = w.getObjectId(0); ObjectStream stream = db.open(blobId, Constants.OBJ_BLOB).openStream(); IOUtilities.pipe(stream, response.getOutputStream(), true, false); return true; }
From source file:org.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private boolean handleGetCommitLog(HttpServletRequest request, HttpServletResponse response, Repository db, String refIdsRange, String path) throws AmbiguousObjectException, IOException, ServletException, JSONException, URISyntaxException, CoreException { int page = request.getParameter("page") != null ? new Integer(request.getParameter("page")).intValue() : 0; //$NON-NLS-1$ //$NON-NLS-2$ int pageSize = request.getParameter("pageSize") != null //$NON-NLS-1$ ? new Integer(request.getParameter("pageSize")).intValue() //$NON-NLS-1$ : PAGE_SIZE;/* www. j ava 2 s .c o m*/ ObjectId toObjectId = null; ObjectId fromObjectId = null; Ref toRefId = null; Ref fromRefId = null; Git git = new Git(db); LogCommand log = git.log(); if (refIdsRange != null) { // git log <since>..<until> if (refIdsRange.contains("..")) { //$NON-NLS-1$ String[] commits = refIdsRange.split("\\.\\."); //$NON-NLS-1$ if (commits.length != 2) { String msg = NLS.bind("Failed to generate commit log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } fromObjectId = db.resolve(commits[0]); fromRefId = db.getRef(commits[0]); if (fromObjectId == null) { String msg = NLS.bind("Failed to generate commit log for ref {0}", commits[0]); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } toObjectId = db.resolve(commits[1]); toRefId = db.getRef(commits[1]); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", commits[1]); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } else { toObjectId = db.resolve(refIdsRange); toRefId = db.getRef(refIdsRange); if (toObjectId == null) { String msg = NLS.bind("No ref or commit found: {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null)); } } // set the commit range log.add(toObjectId); if (fromObjectId != null) log.not(fromObjectId); } else { // git log --all // workaround for git log --all - see bug 353310 List<Ref> branches = git.branchList().setListMode(ListMode.ALL).call(); for (Ref branch : branches) { log.add(branch.getObjectId()); } } // set the path filter TreeFilter filter = null; boolean isRoot = true; if (path != null && !"".equals(path)) { //$NON-NLS-1$ filter = AndTreeFilter.create(PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF); log.addPath(path); isRoot = false; } try { Iterable<RevCommit> commits = log.call(); Map<ObjectId, JSONArray> commitToBranchMap = getCommitToBranchMap(db); JSONObject result = toJSON(db, OrionServlet.getURI(request), commits, commitToBranchMap, page, pageSize, filter, isRoot); result.put(GitConstants.KEY_REPOSITORY_PATH, isRoot ? "" : path); //$NON-NLS-1$ if (refIdsRange == null) result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT)); else result.put(GitConstants.KEY_CLONE, BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT_REFRANGE)); if (toRefId != null) { result.put(GitConstants.KEY_REMOTE, BaseToRemoteConverter.getRemoteBranchLocation(getURI(request), Repository.shortenRefName(toRefId.getName()), db, BaseToRemoteConverter.REMOVE_FIRST_3)); String refTargetName = toRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_TO_REF, BranchToJSONConverter.toJSON(toRefId.getTarget(), db, getURI(request), 3)); } } if (fromRefId != null) { String refTargetName = fromRefId.getTarget().getName(); if (refTargetName.startsWith(Constants.R_HEADS)) { // this is a branch result.put(GitConstants.KEY_LOG_FROM_REF, BranchToJSONConverter.toJSON(fromRefId.getTarget(), db, getURI(request), 3)); } } OrionServlet.writeJSONResponse(request, response, result); return true; } catch (NoHeadException e) { String msg = NLS.bind("No HEAD reference found when generating log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } catch (JGitInternalException e) { String msg = NLS.bind("An internal error occured when generating log for ref {0}", refIdsRange); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); } }
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 {// w w w.ja v 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.eclipse.orion.server.git.servlets.GitCommitHandlerV1.java
License:Open Source License
private boolean merge(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToMerge) throws ServletException, JSONException { try {//from www.j a va 2 s.c om ObjectId objectId = db.resolve(commitToMerge); Git git = new Git(db); MergeResult mergeResult = git.merge().include(objectId).call(); JSONObject result = new JSONObject(); result.put(GitConstants.KEY_RESULT, mergeResult.getMergeStatus().name()); OrionServlet.writeJSONResponse(request, response, result); return true; } catch (IOException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e)); } catch (GitAPIException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e)); } catch (JGitInternalException e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occured when merging.", e.getCause())); } }