Search in sources :

Example 81 with ChangeNotes

use of com.google.gerrit.server.notedb.ChangeNotes in project gerrit by GerritCodeReview.

the class PatchSetParser method parsePatchSet.

public PatchSet parsePatchSet(String token, ProjectState projectState, String branch) throws UnloggedFailure {
    // 
    if (token.matches("^([0-9a-fA-F]{4," + ObjectIds.STR_LEN + "})$")) {
        InternalChangeQuery query = queryProvider.get();
        List<ChangeData> cds;
        if (projectState != null) {
            Project.NameKey p = projectState.getNameKey();
            if (branch != null) {
                cds = query.byBranchCommit(p.get(), branch, token);
            } else {
                cds = query.byProjectCommit(p, token);
            }
        } else {
            cds = query.byCommit(token);
        }
        List<PatchSet> matches = new ArrayList<>(cds.size());
        for (ChangeData cd : cds) {
            Change c = cd.change();
            if (!(inProject(c, projectState) && inBranch(c, branch))) {
                continue;
            }
            for (PatchSet ps : cd.patchSets()) {
                if (ObjectIds.matchesAbbreviation(ps.commitId(), token)) {
                    matches.add(ps);
                }
            }
        }
        switch(matches.size()) {
            case 1:
                return matches.iterator().next();
            case 0:
                throw error("\"" + token + "\" no such patch set");
            default:
                throw error("\"" + token + "\" matches multiple patch sets");
        }
    }
    // 
    if (token.matches("^[1-9][0-9]*,[1-9][0-9]*$")) {
        PatchSet.Id patchSetId;
        try {
            patchSetId = PatchSet.Id.parse(token);
        } catch (IllegalArgumentException e) {
            throw error("\"" + token + "\" is not a valid patch set", e);
        }
        ChangeNotes notes = getNotes(projectState, patchSetId.changeId());
        PatchSet patchSet = psUtil.get(notes, patchSetId);
        if (patchSet == null) {
            throw error("\"" + token + "\" no such patch set");
        }
        if (projectState != null || branch != null) {
            Change change = notes.getChange();
            if (!inProject(change, projectState)) {
                throw error("change " + change.getId() + " not in project " + projectState.getName());
            }
            if (!inBranch(change, branch)) {
                throw error("change " + change.getId() + " not in branch " + branch);
            }
        }
        return patchSet;
    }
    throw error("\"" + token + "\" is not a valid patch set");
}
Also used : InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Project(com.google.gerrit.entities.Project) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.entities.PatchSet) Change(com.google.gerrit.entities.Change) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ChangeData(com.google.gerrit.server.query.change.ChangeData)

Example 82 with ChangeNotes

use of com.google.gerrit.server.notedb.ChangeNotes in project gerrit by GerritCodeReview.

the class SetHashtagsOp method updateChange.

@Override
public boolean updateChange(ChangeContext ctx) throws AuthException, BadRequestException, MethodNotAllowedException, IOException {
    if (input == null || (input.add == null && input.remove == null)) {
        updatedHashtags = ImmutableSortedSet.of();
        return false;
    }
    change = ctx.getChange();
    ChangeUpdate update = ctx.getUpdate(change.currentPatchSetId());
    ChangeNotes notes = update.getNotes().load();
    try {
        Set<String> existingHashtags = notes.getHashtags();
        Set<String> updated = new HashSet<>();
        toAdd = new HashSet<>(extractTags(input.add));
        toRemove = new HashSet<>(extractTags(input.remove));
        validationListeners.runEach(l -> l.validateHashtags(update.getChange(), toAdd, toRemove), ValidationException.class);
        updated.addAll(existingHashtags);
        toAdd.removeAll(existingHashtags);
        toRemove.retainAll(existingHashtags);
        if (updated()) {
            updated.addAll(toAdd);
            updated.removeAll(toRemove);
            update.setHashtags(updated);
            addMessage(ctx);
        }
        updatedHashtags = ImmutableSortedSet.copyOf(updated);
        return true;
    } catch (ValidationException | InvalidHashtagException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
Also used : InvalidHashtagException(com.google.gerrit.server.change.HashtagsUtil.InvalidHashtagException) ValidationException(com.google.gerrit.server.validators.ValidationException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) HashSet(java.util.HashSet)

Example 83 with ChangeNotes

use of com.google.gerrit.server.notedb.ChangeNotes in project gerrit by GerritCodeReview.

the class Comments method parse.

@Override
public HumanCommentResource parse(RevisionResource rev, IdString id) throws ResourceNotFoundException {
    String uuid = id.get();
    ChangeNotes notes = rev.getNotes();
    for (HumanComment c : commentsUtil.publishedByPatchSet(notes, rev.getPatchSet().id())) {
        if (uuid.equals(c.key.uuid)) {
            return new HumanCommentResource(rev, c);
        }
    }
    throw new ResourceNotFoundException(id);
}
Also used : HumanCommentResource(com.google.gerrit.server.change.HumanCommentResource) IdString(com.google.gerrit.extensions.restapi.IdString) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) HumanComment(com.google.gerrit.entities.HumanComment)

Example 84 with ChangeNotes

use of com.google.gerrit.server.notedb.ChangeNotes in project gerrit by GerritCodeReview.

the class CreateChange method createNewChange.

// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
private ChangeInfo createNewChange(ChangeInput input, IdentifiedUser me, ProjectState projectState, BatchUpdate.Factory updateFactory) throws RestApiException, PermissionBackendException, IOException, ConfigInvalidException, UpdateException {
    logger.atFine().log("Creating new change for target branch %s in project %s" + " (new branch = %s, base change = %s, base commit = %s)", input.branch, projectState.getName(), input.newBranch, input.baseChange, input.baseCommit);
    try (Repository git = gitManager.openRepository(projectState.getNameKey());
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(reader)) {
        PatchSet basePatchSet = null;
        List<String> groups = Collections.emptyList();
        if (input.baseChange != null) {
            ChangeNotes baseChange = getBaseChange(input.baseChange);
            basePatchSet = psUtil.current(baseChange);
            groups = basePatchSet.groups();
            logger.atFine().log("base patch set = %s (groups = %s)", basePatchSet.id(), groups);
        }
        ObjectId parentCommit = getParentCommit(git, rw, input.branch, input.newBranch, basePatchSet, input.baseCommit, input.merge);
        logger.atFine().log("parent commit = %s", parentCommit != null ? parentCommit.name() : "NULL");
        RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
        Instant now = TimeUtil.now();
        PersonIdent committer = me.newCommitterIdent(now, serverTimeZone);
        PersonIdent author = input.author == null ? committer : new PersonIdent(input.author.name, input.author.email, Date.from(now), serverTimeZone);
        String commitMessage = getCommitMessage(input.subject, me);
        CodeReviewCommit c;
        if (input.merge != null) {
            // create a merge commit
            c = newMergeCommit(git, oi, rw, projectState, mergeTip, input.merge, author, committer, commitMessage);
            if (!c.getFilesWithGitConflicts().isEmpty()) {
                logger.atFine().log("merge commit has conflicts in the following files: %s", c.getFilesWithGitConflicts());
            }
        } else {
            // create an empty commit
            c = newCommit(oi, rw, author, committer, mergeTip, commitMessage);
        }
        // Flush inserter so that commit becomes visible to validators
        oi.flush();
        Change.Id changeId = Change.id(seq.nextChangeId());
        ChangeInserter ins = changeInserterFactory.create(changeId, c, input.branch);
        ins.setMessage(messageForNewChange(ins.getPatchSetId(), c));
        ins.setTopic(input.topic);
        ins.setPrivate(input.isPrivate);
        ins.setWorkInProgress(input.workInProgress || !c.getFilesWithGitConflicts().isEmpty());
        ins.setGroups(groups);
        if (input.validationOptions != null) {
            ImmutableListMultimap.Builder<String, String> validationOptions = ImmutableListMultimap.builder();
            input.validationOptions.entrySet().forEach(e -> validationOptions.put(e.getKey(), e.getValue()));
            ins.setValidationOptions(validationOptions.build());
        }
        try (BatchUpdate bu = updateFactory.create(projectState.getNameKey(), me, now)) {
            bu.setRepository(git, rw, oi);
            bu.setNotify(notifyResolver.resolve(firstNonNull(input.notify, NotifyHandling.ALL), input.notifyDetails));
            bu.insertChange(ins);
            bu.execute();
        }
        ChangeInfo changeInfo = jsonFactory.noOptions().format(ins.getChange());
        changeInfo.containsGitConflicts = !c.getFilesWithGitConflicts().isEmpty() ? true : null;
        return changeInfo;
    } catch (InvalidMergeStrategyException | MergeWithConflictsNotSupportedException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) Instant(java.time.Instant) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) PatchSet(com.google.gerrit.entities.PatchSet) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) Change(com.google.gerrit.entities.Change) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Repository(org.eclipse.jgit.lib.Repository) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) InvalidMergeStrategyException(com.google.gerrit.exceptions.InvalidMergeStrategyException) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) MergeWithConflictsNotSupportedException(com.google.gerrit.exceptions.MergeWithConflictsNotSupportedException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ChangeInserter(com.google.gerrit.server.change.ChangeInserter) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 85 with ChangeNotes

use of com.google.gerrit.server.notedb.ChangeNotes in project gerrit by GerritCodeReview.

the class CreateChange method getBaseChange.

private ChangeNotes getBaseChange(String baseChange) throws UnprocessableEntityException, PermissionBackendException {
    List<ChangeNotes> notes = changeFinder.find(baseChange);
    if (notes.size() != 1) {
        throw new UnprocessableEntityException("Base change not found: " + baseChange);
    }
    ChangeNotes change = Iterables.getOnlyElement(notes);
    try {
        permissionBackend.currentUser().change(change).check(ChangePermission.READ);
    } catch (AuthException e) {
        throw new UnprocessableEntityException("Read not permitted for " + baseChange, e);
    }
    return change;
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AuthException(com.google.gerrit.extensions.restapi.AuthException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes)

Aggregations

ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)134 Test (org.junit.Test)54 Change (com.google.gerrit.entities.Change)47 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)43 PatchSet (com.google.gerrit.entities.PatchSet)42 ObjectId (org.eclipse.jgit.lib.ObjectId)33 StorageException (com.google.gerrit.exceptions.StorageException)22 Change (com.google.gerrit.reviewdb.client.Change)21 Project (com.google.gerrit.entities.Project)17 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)16 FixInput (com.google.gerrit.extensions.api.changes.FixInput)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)14 HumanComment (com.google.gerrit.entities.HumanComment)13 TestChanges.newPatchSet (com.google.gerrit.testing.TestChanges.newPatchSet)12 IOException (java.io.IOException)12 RevCommit (org.eclipse.jgit.revwalk.RevCommit)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)10 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)10 AuthException (com.google.gerrit.extensions.restapi.AuthException)9