Search in sources :

Example 76 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class RelatedChangesSorter method collectById.

private Map<ObjectId, PatchSetData> collectById(List<ChangeData> in) throws IOException {
    Project.NameKey project = in.get(0).change().getProject();
    Map<ObjectId, PatchSetData> result = Maps.newHashMapWithExpectedSize(in.size() * 3);
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        rw.setRetainBody(true);
        for (ChangeData cd : in) {
            checkArgument(cd.change().getProject().equals(project), "Expected change %s in project %s, found %s", cd.getId(), project, cd.change().getProject());
            for (PatchSet ps : cd.patchSets()) {
                RevCommit c = rw.parseCommit(ps.commitId());
                PatchSetData psd = PatchSetData.create(cd, ps, c);
                result.put(ps.commitId(), psd);
            }
        }
    }
    return result;
}
Also used : Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.entities.PatchSet) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 77 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class CommentPorter method portSamePatchset.

private ImmutableList<HumanComment> portSamePatchset(Project.NameKey project, Change change, PatchSet originalPatchset, PatchSet targetPatchset, ImmutableList<HumanComment> comments) {
    try (TraceTimer ignored = TraceContext.newTimer("Porting comments same patchset", Metadata.builder().projectName(project.get()).changeId(change.getChangeId()).patchSetId(originalPatchset.number()).build())) {
        Map<Short, List<HumanComment>> commentsPerSide = comments.stream().collect(groupingBy(comment -> comment.side));
        ImmutableList.Builder<HumanComment> portedComments = ImmutableList.builder();
        for (Map.Entry<Short, List<HumanComment>> sideAndComments : commentsPerSide.entrySet()) {
            portedComments.addAll(portSamePatchsetAndSide(project, change, originalPatchset, targetPatchset, sideAndComments.getValue(), sideAndComments.getKey()));
        }
        return portedComments.build();
    }
}
Also used : Patch(com.google.gerrit.entities.Patch) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) Mapping(com.google.gerrit.server.patch.GitPositionTransformer.Mapping) HumanComment(com.google.gerrit.entities.HumanComment) CommentsUtil(com.google.gerrit.server.CommentsUtil) Position(com.google.gerrit.server.patch.GitPositionTransformer.Position) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) Function(java.util.function.Function) BestPositionOnConflict(com.google.gerrit.server.patch.GitPositionTransformer.BestPositionOnConflict) DiffNotAvailableException(com.google.gerrit.server.patch.DiffNotAvailableException) ImmutableList(com.google.common.collect.ImmutableList) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Description(com.google.gerrit.metrics.Description) Map(java.util.Map) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Metadata(com.google.gerrit.server.logging.Metadata) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) TraceContext(com.google.gerrit.server.logging.TraceContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) DiffMappings(com.google.gerrit.server.patch.DiffMappings) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ObjectId(org.eclipse.jgit.lib.ObjectId) DiffOptions(com.google.gerrit.server.patch.DiffOptions) TaggedEdit(com.google.gerrit.server.patch.filediff.TaggedEdit) List(java.util.List) FileEdits(com.google.gerrit.server.patch.filediff.FileEdits) Stream(java.util.stream.Stream) GitPositionTransformer(com.google.gerrit.server.patch.GitPositionTransformer) DiffOperations(com.google.gerrit.server.patch.DiffOperations) FileMapping(com.google.gerrit.server.patch.GitPositionTransformer.FileMapping) Project(com.google.gerrit.entities.Project) PositionedEntity(com.google.gerrit.server.patch.GitPositionTransformer.PositionedEntity) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Counter0(com.google.gerrit.metrics.Counter0) MetricMaker(com.google.gerrit.metrics.MetricMaker) FluentLogger(com.google.common.flogger.FluentLogger) Range(com.google.gerrit.entities.Comment.Range) Singleton(com.google.inject.Singleton) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) HumanComment(com.google.gerrit.entities.HumanComment) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 78 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class GetBlame method apply.

@Override
public Response<List<BlameInfo>> apply(FileResource resource) throws RestApiException, IOException, InvalidChangeOperationException {
    Project.NameKey project = resource.getRevision().getChange().getProject();
    try (Repository repository = repoManager.openRepository(project);
        InMemoryInserter ins = new InMemoryInserter(repository);
        ObjectReader reader = ins.newReader();
        RevWalk revWalk = new RevWalk(reader)) {
        String refName = resource.getRevision().getEdit().isPresent() ? resource.getRevision().getEdit().get().getRefName() : resource.getRevision().getPatchSet().refName();
        Ref ref = repository.findRef(refName);
        if (ref == null) {
            throw new ResourceNotFoundException("unknown ref " + refName);
        }
        ObjectId objectId = ref.getObjectId();
        RevCommit revCommit = revWalk.parseCommit(objectId);
        RevCommit[] parents = revCommit.getParents();
        String path = resource.getPatchKey().fileName();
        List<BlameInfo> result;
        if (!base) {
            result = blame(revCommit, path, repository, revWalk);
        } else if (parents.length == 0) {
            throw new ResourceNotFoundException("Initial commit doesn't have base");
        } else if (parents.length == 1) {
            result = blame(parents[0], path, repository, revWalk);
        } else if (parents.length == 2) {
            ObjectId automerge = autoMerger.lookupFromGitOrMergeInMemory(repository, revWalk, ins, revCommit, mergeStrategy);
            result = blame(automerge, path, repository, revWalk);
        } else {
            throw new ResourceNotFoundException("Cannot generate blame for merge commit with more than 2 parents");
        }
        Response<List<BlameInfo>> r = Response.ok(result);
        if (resource.isCacheable()) {
            r.caching(CacheControl.PRIVATE(7, TimeUnit.DAYS));
        }
        return r;
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) InMemoryInserter(com.google.gerrit.server.git.InMemoryInserter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BlameInfo(com.google.gerrit.extensions.common.BlameInfo) Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ArrayList(java.util.ArrayList) List(java.util.List) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 79 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class Move method apply.

@Override
public Response<ChangeInfo> apply(ChangeResource rsrc, MoveInput input) throws RestApiException, UpdateException, PermissionBackendException, IOException {
    if (!moveEnabled) {
        // behavior. See: https://bugs.chromium.org/p/gerrit/issues/detail?id=9877
        throw new MethodNotAllowedException("move changes endpoint is disabled");
    }
    Change change = rsrc.getChange();
    Project.NameKey project = rsrc.getProject();
    IdentifiedUser caller = rsrc.getUser().asIdentifiedUser();
    if (input.destinationBranch == null) {
        throw new BadRequestException("destination branch is required");
    }
    input.destinationBranch = RefNames.fullName(input.destinationBranch);
    if (!change.isNew()) {
        throw new ResourceConflictException("Change is " + ChangeUtil.status(change));
    }
    BranchNameKey newDest = BranchNameKey.create(project, input.destinationBranch);
    if (change.getDest().equals(newDest)) {
        throw new ResourceConflictException("Change is already destined for the specified branch");
    }
    // Not allowed to move if the current patch set is locked.
    psUtil.checkPatchSetNotLocked(rsrc.getNotes());
    // Only administrators are allowed to keep all labels at their own risk.
    try {
        if (input.keepAllVotes) {
            permissionBackend.user(caller).check(GlobalPermission.ADMINISTRATE_SERVER);
        }
    } catch (AuthException denied) {
        throw new AuthException("move is not permitted with keepAllVotes option", denied);
    }
    // Move requires abandoning this change, and creating a new change.
    try {
        rsrc.permissions().check(ABANDON);
        permissionBackend.user(caller).ref(newDest).check(CREATE_CHANGE);
    } catch (AuthException denied) {
        throw new AuthException("move not permitted", denied);
    }
    projectCache.get(project).orElseThrow(illegalState(project)).checkStatePermitsWrite();
    Op op = new Op(input);
    try (BatchUpdate u = updateFactory.create(project, caller, TimeUtil.now())) {
        u.addOp(change.getId(), op);
        u.execute();
    }
    return Response.ok(json.noOptions().format(op.getChange()));
}
Also used : Project(com.google.gerrit.entities.Project) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) BranchNameKey(com.google.gerrit.entities.BranchNameKey) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.entities.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) BatchUpdate(com.google.gerrit.server.update.BatchUpdate)

Example 80 with Project

use of com.google.gerrit.entities.Project in project gerrit by GerritCodeReview.

the class ChangeIT method createNewPatchSetWithoutPermission.

@Test
public void createNewPatchSetWithoutPermission() throws Exception {
    // Create new project with clean permissions
    Project.NameKey p = projectOperations.newProject().create();
    // Clone separate repositories of the same project as admin and as user
    TestRepository<InMemoryRepository> adminTestRepo = cloneProject(p, admin);
    TestRepository<InMemoryRepository> userTestRepo = cloneProject(p, user);
    // Block default permission
    projectOperations.project(p).forUpdate().add(block(Permission.ADD_PATCH_SET).ref("refs/for/*").group(REGISTERED_USERS)).update();
    // Create change as admin
    PushOneCommit push = pushFactory.create(admin.newIdent(), adminTestRepo);
    PushOneCommit.Result r1 = push.to("refs/for/master");
    r1.assertOkStatus();
    // Fetch change
    GitUtil.fetch(userTestRepo, r1.getPatchSet().refName() + ":ps");
    userTestRepo.reset("ps");
    // Amend change as user
    PushOneCommit.Result r2 = amendChange(r1.getChangeId(), "refs/for/master", user, userTestRepo);
    r2.assertErrorStatus("cannot add patch set to " + r1.getChange().getId().get() + ".");
}
Also used : Project(com.google.gerrit.entities.Project) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Aggregations

Project (com.google.gerrit.entities.Project)184 Test (org.junit.Test)109 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)67 Change (com.google.gerrit.entities.Change)43 Repository (org.eclipse.jgit.lib.Repository)34 ChangeInfo (com.google.gerrit.extensions.common.ChangeInfo)33 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)32 InMemoryRepository (org.eclipse.jgit.internal.storage.dfs.InMemoryRepository)31 BranchNameKey (com.google.gerrit.entities.BranchNameKey)30 Config (org.eclipse.jgit.lib.Config)26 ObjectId (org.eclipse.jgit.lib.ObjectId)26 IOException (java.io.IOException)25 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)24 ProjectState (com.google.gerrit.server.project.ProjectState)23 Inject (com.google.inject.Inject)23 List (java.util.List)23 AuthException (com.google.gerrit.extensions.restapi.AuthException)22 ChangeData (com.google.gerrit.server.query.change.ChangeData)22 RevCommit (org.eclipse.jgit.revwalk.RevCommit)22 PatchSet (com.google.gerrit.entities.PatchSet)20