Search in sources :

Example 6 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class EventBroker method isVisibleTo.

protected boolean isVisibleTo(Change change, CurrentUser user) throws OrmException {
    if (change == null) {
        return false;
    }
    ProjectState pe = projectCache.get(change.getProject());
    if (pe == null) {
        return false;
    }
    ProjectControl pc = pe.controlFor(user);
    ReviewDb db = dbProvider.get();
    return pc.controlFor(db, change).isVisible(db);
}
Also used : ProjectState(com.google.gerrit.server.project.ProjectState) ProjectControl(com.google.gerrit.server.project.ProjectControl) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 7 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class CherryPickChange method cherryPick.

public Change.Id cherryPick(BatchUpdate.Factory batchUpdateFactory, @Nullable Change.Id sourceChangeId, @Nullable PatchSet.Id sourcePatchId, @Nullable Branch.NameKey sourceBranch, @Nullable String sourceChangeTopic, Project.NameKey project, ObjectId sourceCommit, CherryPickInput input, String targetRef, RefControl targetRefControl) throws OrmException, IOException, InvalidChangeOperationException, IntegrationException, UpdateException, RestApiException {
    if (Strings.isNullOrEmpty(targetRef)) {
        throw new InvalidChangeOperationException("Cherry Pick: Destination branch cannot be null or empty");
    }
    String destinationBranch = RefNames.shortName(targetRef);
    IdentifiedUser identifiedUser = user.get();
    try (Repository git = gitManager.openRepository(project);
        // before patch sets are updated.
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(reader)) {
        Ref destRef = git.getRefDatabase().exactRef(targetRef);
        if (destRef == null) {
            throw new InvalidChangeOperationException(String.format("Branch %s does not exist.", destinationBranch));
        }
        CodeReviewCommit mergeTip = revWalk.parseCommit(destRef.getObjectId());
        CodeReviewCommit commitToCherryPick = revWalk.parseCommit(sourceCommit);
        if (input.parent <= 0 || input.parent > commitToCherryPick.getParentCount()) {
            throw new InvalidChangeOperationException(String.format("Cherry Pick: Parent %s does not exist. Please specify a parent in" + " range [1, %s].", input.parent, commitToCherryPick.getParentCount()));
        }
        Timestamp now = TimeUtil.nowTs();
        PersonIdent committerIdent = identifiedUser.newCommitterIdent(now, serverTimeZone);
        final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(commitToCherryPick.getTree(), mergeTip, commitToCherryPick.getAuthorIdent(), committerIdent, input.message);
        String commitMessage = ChangeIdUtil.insertId(input.message, computedChangeId).trim() + '\n';
        CodeReviewCommit cherryPickCommit;
        try {
            ProjectState projectState = targetRefControl.getProjectControl().getProjectState();
            cherryPickCommit = mergeUtilFactory.create(projectState).createCherryPickFromCommit(oi, git.getConfig(), mergeTip, commitToCherryPick, committerIdent, commitMessage, revWalk, input.parent - 1, false);
            Change.Key changeKey;
            final List<String> idList = cherryPickCommit.getFooterLines(FooterConstants.CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                changeKey = new Change.Key("I" + computedChangeId.name());
            }
            Branch.NameKey newDest = new Branch.NameKey(project, destRef.getName());
            List<ChangeData> destChanges = queryProvider.get().setLimit(2).byBranchKey(newDest, changeKey);
            if (destChanges.size() > 1) {
                throw new InvalidChangeOperationException("Several changes with key " + changeKey + " reside on the same branch. " + "Cannot create a new patch set.");
            }
            try (BatchUpdate bu = batchUpdateFactory.create(db.get(), project, identifiedUser, now)) {
                bu.setRepository(git, revWalk, oi);
                Change.Id result;
                if (destChanges.size() == 1) {
                    // The change key exists on the destination branch. The cherry pick
                    // will be added as a new patch set.
                    ChangeControl destCtl = targetRefControl.getProjectControl().controlFor(destChanges.get(0).notes());
                    result = insertPatchSet(bu, git, destCtl, cherryPickCommit, input);
                } else {
                    // Change key not found on destination branch. We can create a new
                    // change.
                    String newTopic = null;
                    if (!Strings.isNullOrEmpty(sourceChangeTopic)) {
                        newTopic = sourceChangeTopic + "-" + newDest.getShortName();
                    }
                    result = createNewChange(bu, cherryPickCommit, targetRefControl.getRefName(), newTopic, sourceBranch, sourceCommit, input);
                    if (sourceChangeId != null && sourcePatchId != null) {
                        bu.addOp(sourceChangeId, new AddMessageToSourceChangeOp(changeMessagesUtil, sourcePatchId, destinationBranch, cherryPickCommit));
                    }
                }
                bu.execute();
                return result;
            }
        } catch (MergeIdenticalTreeException | MergeConflictException e) {
            throw new IntegrationException("Cherry pick failed: " + e.getMessage());
        }
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) Branch(com.google.gerrit.reviewdb.client.Branch) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) IntegrationException(com.google.gerrit.server.git.IntegrationException) ObjectId(org.eclipse.jgit.lib.ObjectId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) Change(com.google.gerrit.reviewdb.client.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) ChangeData(com.google.gerrit.server.query.change.ChangeData) MergeIdenticalTreeException(com.google.gerrit.server.git.MergeIdenticalTreeException) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ProjectState(com.google.gerrit.server.project.ProjectState)

Example 8 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class ApplyFix method apply.

@Override
public Response<EditInfo> apply(FixResource fixResource, Void nothing) throws AuthException, OrmException, ResourceConflictException, IOException, ResourceNotFoundException, PermissionBackendException {
    RevisionResource revisionResource = fixResource.getRevisionResource();
    Project.NameKey project = revisionResource.getProject();
    ProjectState projectState = revisionResource.getControl().getProjectControl().getProjectState();
    PatchSet patchSet = revisionResource.getPatchSet();
    ObjectId patchSetCommitId = ObjectId.fromString(patchSet.getRevision().get());
    try (Repository repository = gitRepositoryManager.openRepository(project)) {
        List<TreeModification> treeModifications = fixReplacementInterpreter.toTreeModifications(repository, projectState, patchSetCommitId, fixResource.getFixReplacements());
        ChangeEdit changeEdit = changeEditModifier.combineWithModifiedPatchSetTree(repository, revisionResource.getControl(), patchSet, treeModifications);
        return Response.ok(changeEditJson.toEditInfo(changeEdit, false));
    } catch (InvalidChangeOperationException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}
Also used : Project(com.google.gerrit.reviewdb.client.Project) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) Repository(org.eclipse.jgit.lib.Repository) ChangeEdit(com.google.gerrit.server.edit.ChangeEdit) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectId(org.eclipse.jgit.lib.ObjectId) ProjectState(com.google.gerrit.server.project.ProjectState) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) TreeModification(com.google.gerrit.server.edit.tree.TreeModification)

Example 9 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class AdminSetParent method run.

@Override
protected void run() throws Failure {
    if (oldParent == null && children.isEmpty()) {
        throw die("child projects have to be specified as " + "arguments or the --children-of option has to be set");
    }
    if (oldParent == null && !excludedChildren.isEmpty()) {
        throw die("--exclude can only be used together with --children-of");
    }
    final StringBuilder err = new StringBuilder();
    final Set<Project.NameKey> grandParents = new HashSet<>();
    grandParents.add(allProjectsName);
    if (newParent != null) {
        newParentKey = newParent.getProject().getNameKey();
        // Catalog all grandparents of the "parent", we want to
        // catch a cycle in the parent pointers before it occurs.
        //
        Project.NameKey gp = newParent.getProject().getParent();
        while (gp != null && grandParents.add(gp)) {
            final ProjectState s = projectCache.get(gp);
            if (s != null) {
                gp = s.getProject().getParent();
            } else {
                break;
            }
        }
    }
    final List<Project.NameKey> childProjects = new ArrayList<>();
    for (final ProjectControl pc : children) {
        childProjects.add(pc.getProject().getNameKey());
    }
    if (oldParent != null) {
        try {
            childProjects.addAll(getChildrenForReparenting(oldParent));
        } catch (PermissionBackendException e) {
            throw new Failure(1, "permissions unavailable", e);
        }
    }
    for (final Project.NameKey nameKey : childProjects) {
        final String name = nameKey.get();
        if (allProjectsName.equals(nameKey)) {
            // Don't allow the wild card project to have a parent.
            //
            err.append("error: Cannot set parent of '").append(name).append("'\n");
            continue;
        }
        if (grandParents.contains(nameKey) || nameKey.equals(newParentKey)) {
            // Try to avoid creating a cycle in the parent pointers.
            //
            err.append("error: Cycle exists between '").append(name).append("' and '").append(newParentKey != null ? newParentKey.get() : allProjectsName.get()).append("'\n");
            continue;
        }
        try (MetaDataUpdate md = metaDataUpdateFactory.create(nameKey)) {
            ProjectConfig config = ProjectConfig.read(md);
            config.getProject().setParentName(newParentKey);
            md.setMessage("Inherit access from " + (newParentKey != null ? newParentKey.get() : allProjectsName.get()) + "\n");
            config.commit(md);
        } catch (RepositoryNotFoundException notFound) {
            err.append("error: Project ").append(name).append(" not found\n");
        } catch (IOException | ConfigInvalidException e) {
            final String msg = "Cannot update project " + name;
            log.error(msg, e);
            err.append("error: ").append(msg).append("\n");
        }
        projectCache.evict(nameKey);
    }
    if (err.length() > 0) {
        while (err.charAt(err.length() - 1) == '\n') {
            err.setLength(err.length() - 1);
        }
        throw die(err.toString());
    }
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ArrayList(java.util.ArrayList) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) ProjectControl(com.google.gerrit.server.project.ProjectControl) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ProjectState(com.google.gerrit.server.project.ProjectState) HashSet(java.util.HashSet) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 10 with ProjectState

use of com.google.gerrit.server.project.ProjectState in project gerrit by GerritCodeReview.

the class Mergeable method apply.

@Override
public MergeableInfo apply(RevisionResource resource) throws AuthException, ResourceConflictException, BadRequestException, OrmException, IOException {
    Change change = resource.getChange();
    PatchSet ps = resource.getPatchSet();
    MergeableInfo result = new MergeableInfo();
    if (!change.getStatus().isOpen()) {
        throw new ResourceConflictException("change is " + ChangeUtil.status(change));
    } else if (!ps.getId().equals(change.currentPatchSetId())) {
        // Only the current revision is mergeable. Others always fail.
        return result;
    }
    ChangeData cd = changeDataFactory.create(db.get(), resource.getControl());
    result.submitType = getSubmitType(cd, ps);
    try (Repository git = gitManager.openRepository(change.getProject())) {
        ObjectId commit = toId(ps);
        Ref ref = git.getRefDatabase().exactRef(change.getDest().get());
        ProjectState projectState = projectCache.get(change.getProject());
        String strategy = mergeUtilFactory.create(projectState).mergeStrategyName();
        result.strategy = strategy;
        result.mergeable = isMergable(git, change, commit, ref, result.submitType, strategy);
        if (otherBranches) {
            result.mergeableInto = new ArrayList<>();
            BranchOrderSection branchOrder = projectState.getBranchOrderSection();
            if (branchOrder != null) {
                int prefixLen = Constants.R_HEADS.length();
                String[] names = branchOrder.getMoreStable(ref.getName());
                Map<String, Ref> refs = git.getRefDatabase().exactRef(names);
                for (String n : names) {
                    Ref other = refs.get(n);
                    if (other == null) {
                        continue;
                    }
                    if (cache.get(commit, other, SubmitType.CHERRY_PICK, strategy, change.getDest(), git)) {
                        result.mergeableInto.add(other.getName().substring(prefixLen));
                    }
                }
            }
        }
    }
    return result;
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) BranchOrderSection(com.google.gerrit.server.git.BranchOrderSection) ChangeData(com.google.gerrit.server.query.change.ChangeData) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) MergeableInfo(com.google.gerrit.extensions.common.MergeableInfo) ProjectState(com.google.gerrit.server.project.ProjectState)

Aggregations

ProjectState (com.google.gerrit.server.project.ProjectState)86 Project (com.google.gerrit.entities.Project)20 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)19 IOException (java.io.IOException)18 Repository (org.eclipse.jgit.lib.Repository)18 AuthException (com.google.gerrit.extensions.restapi.AuthException)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)14 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)14 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)13 Change (com.google.gerrit.entities.Change)13 ObjectId (org.eclipse.jgit.lib.ObjectId)13 Test (org.junit.Test)13 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)12 ChangeData (com.google.gerrit.server.query.change.ChangeData)11 Inject (com.google.inject.Inject)10 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)10 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)10 StorageException (com.google.gerrit.exceptions.StorageException)9 ProjectInfo (com.google.gerrit.extensions.common.ProjectInfo)9 ProjectResource (com.google.gerrit.server.project.ProjectResource)9