List of usage examples for org.eclipse.jgit.lib Repository getRefDatabase
@NonNull public abstract RefDatabase getRefDatabase();
From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.commands.ChangesActionsProvider.java
License:Open Source License
@Override protected IContributionItem[] getContributionItems() { ISelectionService selectionService = (ISelectionService) serviceLocator.getService(ISelectionService.class); Repository repository = RepositoryUtils.getRepository(selectionService.getSelection()); if (repository == null) { return new IContributionItem[0]; }//from www. j av a 2 s. com Set<String> stables = new TreeSet<String>(); try { for (String ref : repository.getRefDatabase().getRefs("refs/heads/changes/").keySet()) { IPath refPath = new Path(ref); if (refPath.segmentCount() > 1) { if (refPath.segment(0).equals("features") && refPath.segmentCount() > 3) { stables.add(refPath.uptoSegment(3).toString()); } else { stables.add(refPath.segment(0)); } } } } catch (IOException e) { //ignore } List<IContributionItem> result = new ArrayList<IContributionItem>(); for (String stable : stables) { result.add(new ChangesOnStableActionProvider(repository, stable)); } return result.toArray(new IContributionItem[result.size()]); }
From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.commands.CleanupChangesCommand.java
License:Open Source License
@Override protected Expression getEnabledWhenExpression() { if (enabledWhen == null) { enabledWhen = new Expression() { public EvaluationResult evaluate(IEvaluationContext context) throws CoreException { ISelection selection = InternalHandlerUtil.getCurrentSelection(context); Repository repo = RepositoryUtils.getRepository(selection); String curBranch = null; if (repo != null) { try { curBranch = repo.getFullBranch(); if (curBranch.startsWith("refs/heads/changes/")) { curBranch = curBranch.substring("refs/heads/changes/".length()); }/*from w w w . j a v a 2 s .com*/ } catch (IOException e) { //ignore } try { if (repo != null) { for (String branch : repo.getRefDatabase().getRefs("refs/heads/changes/") .keySet()) { if (!branch.equals(curBranch) && branch.indexOf('/') > 0) { return EvaluationResult.TRUE; } } } } catch (IOException ex) { //ignore } } return EvaluationResult.FALSE; } /* * (non-Javadoc) * * @see org.eclipse.core.expressions.Expression#collectExpressionInfo(org.eclipse.core.expressions.ExpressionInfo) */ public void collectExpressionInfo(ExpressionInfo info) { info.addVariableNameAccess(ISources.ACTIVE_CURRENT_SELECTION_NAME); } }; } return enabledWhen; }
From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.BranchingUtils.java
License:Open Source License
public static List<String> getBranches(Repository repository, int mode, String user) { if (repository == null) { return getBranches(RepositoryUtils.getAllRepositories(), mode, user); }//from www. j av a 2 s. c om List<String> result = new ArrayList<String>(); try { Map<String, Ref> remoteBranches = repository.getRefDatabase().getRefs("refs/remotes/origin/"); if ((mode & MODE_STABLE) != 0) { for (String branch : remoteBranches.keySet()) { if (branch.indexOf('/') < 0) { result.add("refs/heads/" + branch); } } } if ((mode & MODE_FEATURE) != 0) { String prefix = "features/" + user + "/"; boolean userBranchMode = (mode & MODE_FEATURE_USER) != 0; boolean othersBranchMode = (mode & MODE_FEATURE_OTHERS) != 0; for (String branch : remoteBranches.keySet()) { boolean userPrefixMatched = branch.startsWith(prefix); if ((userPrefixMatched && userBranchMode) || (!userPrefixMatched && othersBranchMode)) { result.add("refs/heads/" + branch); } } } } catch (Exception e) { GerritToolsPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID, "Cannot get list of branches", e)); } return result; }
From source file:com.gitblit.manager.GitblitManager.java
License:Apache License
/** * Creates a personal fork of the specified repository. The clone is view * restricted by default and the owner of the source repository is given * access to the clone.//from w w w . j av a 2 s. c o m * * @param repository * @param user * @return the repository model of the fork, if successful * @throws GitBlitException */ @Override public RepositoryModel fork(RepositoryModel repository, UserModel user) throws GitBlitException { String cloneName = MessageFormat.format("{0}/{1}.git", user.getPersonalPath(), StringUtils.stripDotGit(StringUtils.getLastPathElement(repository.name))); String fromUrl = MessageFormat.format("file://{0}/{1}", repositoryManager.getRepositoriesFolder().getAbsolutePath(), repository.name); // clone the repository try { Repository canonical = getRepository(repository.name); File folder = new File(repositoryManager.getRepositoriesFolder(), cloneName); CloneCommand clone = new CloneCommand(); clone.setBare(true); // fetch branches with exclusions Collection<Ref> branches = canonical.getRefDatabase().getRefs(Constants.R_HEADS).values(); List<String> branchesToClone = new ArrayList<String>(); for (Ref branch : branches) { String name = branch.getName(); if (name.startsWith(Constants.R_TICKET)) { // exclude ticket branches continue; } branchesToClone.add(name); } clone.setBranchesToClone(branchesToClone); clone.setURI(fromUrl); clone.setDirectory(folder); Git git = clone.call(); // fetch tags FetchCommand fetch = git.fetch(); fetch.setRefSpecs(new RefSpec("+refs/tags/*:refs/tags/*")); fetch.call(); git.getRepository().close(); } catch (Exception e) { throw new GitBlitException(e); } // create a Gitblit repository model for the clone RepositoryModel cloneModel = repository.cloneAs(cloneName); // owner has REWIND/RW+ permissions cloneModel.addOwner(user.username); // ensure initial access restriction of the fork // is not lower than the source repository (issue-495/ticket-167) if (repository.accessRestriction.exceeds(cloneModel.accessRestriction)) { cloneModel.accessRestriction = repository.accessRestriction; } repositoryManager.updateRepositoryModel(cloneName, cloneModel, false); // add the owner of the source repository to the clone's access list if (!ArrayUtils.isEmpty(repository.owners)) { for (String owner : repository.owners) { UserModel originOwner = userManager.getUserModel(owner); if (originOwner != null && !originOwner.canClone(cloneModel)) { // origin owner can't yet clone fork, grant explicit clone access originOwner.setRepositoryPermission(cloneName, AccessPermission.CLONE); reviseUser(originOwner.username, originOwner); } } } // grant origin's user list clone permission to fork List<String> users = repositoryManager.getRepositoryUsers(repository); List<UserModel> cloneUsers = new ArrayList<UserModel>(); for (String name : users) { if (!name.equalsIgnoreCase(user.username)) { UserModel cloneUser = userManager.getUserModel(name); if (cloneUser.canClone(repository) && !cloneUser.canClone(cloneModel)) { // origin user can't yet clone fork, grant explicit clone access cloneUser.setRepositoryPermission(cloneName, AccessPermission.CLONE); } cloneUsers.add(cloneUser); } } userManager.updateUserModels(cloneUsers); // grant origin's team list clone permission to fork List<String> teams = repositoryManager.getRepositoryTeams(repository); List<TeamModel> cloneTeams = new ArrayList<TeamModel>(); for (String name : teams) { TeamModel cloneTeam = userManager.getTeamModel(name); if (cloneTeam.canClone(repository) && !cloneTeam.canClone(cloneModel)) { // origin team can't yet clone fork, grant explicit clone access cloneTeam.setRepositoryPermission(cloneName, AccessPermission.CLONE); } cloneTeams.add(cloneTeam); } userManager.updateTeamModels(cloneTeams); // add this clone to the cached model repositoryManager.addToCachedRepositoryList(cloneModel); if (pluginManager != null) { for (RepositoryLifeCycleListener listener : pluginManager .getExtensions(RepositoryLifeCycleListener.class)) { try { listener.onFork(repository, cloneModel); } catch (Throwable t) { logger.error(String.format("failed to call plugin onFork %s", repository.name), t); } } } return cloneModel; }
From source file:com.gitblit.utils.JGitUtils.java
License:Apache License
/** * Returns a list of references in the repository matching "refs". If the * repository is null or empty, an empty list is returned. * * @param repository/*from www .j ava 2s. com*/ * @param refs * if unspecified, all refs are returned * @param fullName * if true, /refs/something/yadayadayada is returned. If false, * yadayadayada is returned. * @param maxCount * if < 0, all references are returned * @param offset * if maxCount provided sets the starting point of the records to return * @return list of references */ private static List<RefModel> getRefs(Repository repository, String refs, boolean fullName, int maxCount, int offset) { List<RefModel> list = new ArrayList<RefModel>(); if (maxCount == 0) { return list; } if (!hasCommits(repository)) { return list; } try { Map<String, Ref> map = repository.getRefDatabase().getRefs(refs); RevWalk rw = new RevWalk(repository); for (Entry<String, Ref> entry : map.entrySet()) { Ref ref = entry.getValue(); RevObject object = rw.parseAny(ref.getObjectId()); String name = entry.getKey(); if (fullName && !StringUtils.isEmpty(refs)) { name = refs + name; } list.add(new RefModel(name, ref, object)); } rw.dispose(); Collections.sort(list); Collections.reverse(list); if (maxCount > 0 && list.size() > maxCount) { if (offset < 0) { offset = 0; } int endIndex = offset + maxCount; if (endIndex > list.size()) { endIndex = list.size(); } list = new ArrayList<RefModel>(list.subList(offset, endIndex)); } } catch (IOException e) { error(e, repository, "{0} failed to retrieve {1}", refs); } return list; }
From source file:com.google.gerrit.httpd.rpc.changedetail.IncludedInDetailFactory.java
License:Apache License
private List<String> includedIn(final Repository repo, final RevWalk rw, final RevCommit rev, final String namespace) throws IOException, MissingObjectException, IncorrectObjectTypeException { final List<String> result = new ArrayList<String>(); for (final Ref ref : repo.getRefDatabase().getRefs(namespace).values()) { final RevCommit tip; try {/*from w w w .j ava 2 s. c om*/ tip = rw.parseCommit(ref.getObjectId()); } catch (IncorrectObjectTypeException notCommit) { // Its OK for a tag reference to point to a blob or a tree, this // is common in the Linux kernel or git.git repository. // continue; } catch (MissingObjectException notHere) { // Log the problem with this branch, but keep processing. // log.warn("Reference " + ref.getName() + " in " + repo.getDirectory() + " points to dangling object " + ref.getObjectId()); continue; } if (rw.isMergedInto(rev, tip)) { result.add(ref.getName().substring(namespace.length())); } } return result; }
From source file:com.google.gerrit.pgm.RebuildNotedb.java
License:Apache License
private void deleteDraftRefs(Repository allUsersRepo) throws IOException { RefDatabase refDb = allUsersRepo.getRefDatabase(); Map<String, Ref> allRefs = refDb.getRefs(RefNames.REFS_DRAFT_COMMENTS); BatchRefUpdate bru = refDb.newBatchUpdate(); for (Map.Entry<String, Ref> ref : allRefs.entrySet()) { bru.addCommand(new ReceiveCommand(ref.getValue().getObjectId(), ObjectId.zeroId(), RefNames.REFS_DRAFT_COMMENTS + ref.getKey())); }// w w w.j ava 2 s .c o m execute(bru, allUsersRepo); }
From source file:com.google.gerrit.server.change.CreateMergePatchSet.java
License:Apache License
private RevCommit createMergeCommit(MergePatchSetInput in, ProjectControl projectControl, Branch.NameKey dest, Repository git, ObjectInserter oi, RevWalk rw, RevCommit currentPsCommit, RevCommit sourceCommit, PersonIdent author, ObjectId changeId) throws ResourceNotFoundException, MergeIdenticalTreeException, MergeConflictException, IOException { ObjectId parentCommit;//ww w. ja v a 2s .c o m if (in.inheritParent) { // inherit first parent from previous patch set parentCommit = currentPsCommit.getParent(0); } else { // get the current branch tip of destination branch Ref destRef = git.getRefDatabase().exactRef(dest.get()); if (destRef != null) { parentCommit = destRef.getObjectId(); } else { throw new ResourceNotFoundException("cannot find destination branch"); } } RevCommit mergeTip = rw.parseCommit(parentCommit); String commitMsg; if (Strings.emptyToNull(in.subject) != null) { commitMsg = ChangeIdUtil.insertId(in.subject, changeId); } else { // reuse previous patch set commit message commitMsg = currentPsCommit.getFullMessage(); } String mergeStrategy = MoreObjects.firstNonNull(Strings.emptyToNull(in.merge.strategy), mergeUtilFactory.create(projectControl.getProjectState()).mergeStrategyName()); return MergeUtil.createMergeCommit(oi, git.getConfig(), mergeTip, sourceCommit, mergeStrategy, author, commitMsg, rw); }
From source file:com.google.gerrit.server.change.RebaseChange.java
License:Apache License
/** * Find the commit onto which a patch set should be rebased. * <p>//from w w w .j a v a2s.c om * This is defined as the latest patch set of the change corresponding to * this commit's parent, or the destination branch tip in the case where the * parent's change is merged. * * @param patchSet patch set for which the new base commit should be found. * @param destBranch the destination branch. * @param git the repository. * @param rw the RevWalk. * @return the commit onto which the patch set should be rebased. * @throws InvalidChangeOperationException if rebase is not possible or not * allowed. * @throws IOException if accessing the repository fails. * @throws OrmException if accessing the database fails. */ private String findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw) throws InvalidChangeOperationException, IOException, OrmException { String baseRev = null; RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); if (commit.getParentCount() > 1) { throw new InvalidChangeOperationException("Cannot rebase a change with multiple parents."); } else if (commit.getParentCount() == 0) { throw new InvalidChangeOperationException( "Cannot rebase a change without any parents" + " (is this the initial commit?)."); } RevId parentRev = new RevId(commit.getParent(0).name()); for (PatchSet depPatchSet : db.get().patchSets().byRevision(parentRev)) { Change.Id depChangeId = depPatchSet.getId().getParentKey(); Change depChange = db.get().changes().get(depChangeId); if (!depChange.getDest().equals(destBranch)) { continue; } if (depChange.getStatus() == Status.ABANDONED) { throw new InvalidChangeOperationException( "Cannot rebase a change with an abandoned parent: " + depChange.getKey()); } if (depChange.getStatus().isOpen()) { if (depPatchSet.getId().equals(depChange.currentPatchSetId())) { throw new InvalidChangeOperationException( "Change is already based on the latest patch set of the" + " dependent change."); } PatchSet latestDepPatchSet = db.get().patchSets().get(depChange.currentPatchSetId()); baseRev = latestDepPatchSet.getRevision().get(); } break; } if (baseRev == null) { // We are dependent on a merged PatchSet or have no PatchSet // dependencies at all. Ref destRef = git.getRefDatabase().exactRef(destBranch.get()); if (destRef == null) { throw new InvalidChangeOperationException( "The destination branch does not exist: " + destBranch.get()); } baseRev = destRef.getObjectId().getName(); if (baseRev.equals(parentRev.get())) { throw new InvalidChangeOperationException("Change is already up to date."); } } return baseRev; }
From source file:com.google.gerrit.server.change.RebaseUtil.java
License:Apache License
/** * Find the commit onto which a patch set should be rebased. * <p>/*from www . j a v a 2s . com*/ * This is defined as the latest patch set of the change corresponding to * this commit's parent, or the destination branch tip in the case where the * parent's change is merged. * * @param patchSet patch set for which the new base commit should be found. * @param destBranch the destination branch. * @param git the repository. * @param rw the RevWalk. * @return the commit onto which the patch set should be rebased. * @throws RestApiException if rebase is not possible. * @throws IOException if accessing the repository fails. * @throws OrmException if accessing the database fails. */ ObjectId findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw) throws RestApiException, IOException, OrmException { String baseRev = null; RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get())); if (commit.getParentCount() > 1) { throw new UnprocessableEntityException("Cannot rebase a change with multiple parents."); } else if (commit.getParentCount() == 0) { throw new UnprocessableEntityException( "Cannot rebase a change without any parents" + " (is this the initial commit?)."); } RevId parentRev = new RevId(commit.getParent(0).name()); CHANGES: for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentRev.get())) { for (PatchSet depPatchSet : cd.patchSets()) { if (!depPatchSet.getRevision().equals(parentRev)) { continue; } Change depChange = cd.change(); if (depChange.getStatus() == Status.ABANDONED) { throw new ResourceConflictException( "Cannot rebase a change with an abandoned parent: " + depChange.getKey()); } if (depChange.getStatus().isOpen()) { if (depPatchSet.getId().equals(depChange.currentPatchSetId())) { throw new ResourceConflictException( "Change is already based on the latest patch set of the" + " dependent change."); } baseRev = cd.currentPatchSet().getRevision().get(); } break CHANGES; } } if (baseRev == null) { // We are dependent on a merged PatchSet or have no PatchSet // dependencies at all. Ref destRef = git.getRefDatabase().exactRef(destBranch.get()); if (destRef == null) { throw new UnprocessableEntityException( "The destination branch does not exist: " + destBranch.get()); } baseRev = destRef.getObjectId().getName(); if (baseRev.equals(parentRev.get())) { throw new ResourceConflictException("Change is already up to date."); } } return ObjectId.fromString(baseRev); }