Search in sources :

Example 16 with PatchSet

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

the class ChangeKindCacheImpl method getChangeKindInternal.

private static ChangeKind getChangeKindInternal(ChangeKindCache cache, @Nullable RevWalk rw, @Nullable Config repoConfig, ChangeData change, PatchSet patch) {
    ChangeKind kind = ChangeKind.REWORK;
    // the repository.
    if (patch.id().get() > 1) {
        try {
            Collection<PatchSet> patchSetCollection = change.patchSets();
            PatchSet priorPs = patch;
            for (PatchSet ps : patchSetCollection) {
                if (ps.id().get() < patch.id().get() && (ps.id().get() > priorPs.id().get() || priorPs == patch)) {
                    // We only want the previous patch set, so walk until the last one
                    priorPs = ps;
                }
            }
            // and deletes the draft.
            if (priorPs != patch) {
                kind = cache.getChangeKind(change.project(), rw, repoConfig, priorPs.commitId(), patch.commitId());
            }
        } catch (StorageException e) {
            // Do nothing; assume we have a complex change
            logger.atWarning().withCause(e).log("Unable to get change kind for patchSet %s of change %s", patch.number(), change.getId());
        }
    }
    logger.atFine().log("Change kind for patchSet %s of change %s: %s", patch.number(), change.getId(), kind);
    return kind;
}
Also used : PatchSet(com.google.gerrit.entities.PatchSet) StorageException(com.google.gerrit.exceptions.StorageException) ChangeKind(com.google.gerrit.extensions.client.ChangeKind)

Example 17 with PatchSet

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

the class ConsistencyChecker method checkPatchSets.

private boolean checkPatchSets() {
    List<PatchSet> all;
    try {
        // Iterate in descending order.
        all = PS_ID_ORDER.sortedCopy(psUtil.byChange(notes));
    } catch (StorageException e) {
        ProblemInfo problem = problem("Failed to look up patch sets");
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        return false;
    }
    patchSetsBySha = MultimapBuilder.hashKeys(all.size()).treeSetValues(PS_ID_ORDER).build();
    Map<String, Ref> refs;
    try {
        refs = repo.getRefDatabase().exactRef(all.stream().map(ps -> ps.id().toRefName()).toArray(String[]::new));
    } catch (IOException e) {
        ProblemInfo problem = problem("Error reading refs");
        logger.atWarning().withCause(e).log("Error in consistency check of change %s: %s", notes.getChangeId(), problem);
        refs = Collections.emptyMap();
    }
    List<DeletePatchSetFromDbOp> deletePatchSetOps = new ArrayList<>();
    for (PatchSet ps : all) {
        // Check revision format.
        int psNum = ps.id().get();
        String refName = ps.id().toRefName();
        ObjectId objId = ps.commitId();
        patchSetsBySha.put(objId, ps);
        // Check ref existence.
        ProblemInfo refProblem = null;
        Ref ref = refs.get(refName);
        if (ref == null) {
            refProblem = problem("Ref missing: " + refName);
        } else if (!objId.equals(ref.getObjectId())) {
            String actual = ref.getObjectId() != null ? ref.getObjectId().name() : "null";
            refProblem = problem(String.format("Expected %s to point to %s, found %s", ref.getName(), objId.name(), actual));
        }
        // Check object existence.
        RevCommit psCommit = parseCommit(objId, String.format("patch set %d", psNum));
        if (psCommit == null) {
            if (fix != null && fix.deletePatchSetIfCommitMissing) {
                deletePatchSetOps.add(new DeletePatchSetFromDbOp(lastProblem(), ps.id()));
            }
            continue;
        } else if (refProblem != null && fix != null) {
            fixPatchSetRef(refProblem, ps);
        }
        if (ps.id().equals(change().currentPatchSetId())) {
            currPsCommit = psCommit;
        }
    }
    // Delete any bad patch sets found above, in a single update.
    deletePatchSets(deletePatchSetOps);
    // Check for duplicates.
    for (Map.Entry<ObjectId, Collection<PatchSet>> e : patchSetsBySha.asMap().entrySet()) {
        if (e.getValue().size() > 1) {
            problem(String.format("Multiple patch sets pointing to %s: %s", e.getKey().name(), Collections2.transform(e.getValue(), PatchSet::number)));
        }
    }
    return currPs != null && currPsCommit != null;
}
Also used : ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) MultimapBuilder(com.google.common.collect.MultimapBuilder) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Inject(com.google.inject.Inject) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) Collections2(com.google.common.collect.Collections2) SubmissionId(com.google.gerrit.entities.SubmissionId) PatchSetInfoFactory(com.google.gerrit.server.patch.PatchSetInfoFactory) UpdateException(com.google.gerrit.server.update.UpdateException) Accounts(com.google.gerrit.server.account.Accounts) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Locale(java.util.Locale) Map(java.util.Map) RetryHelper(com.google.gerrit.server.update.RetryHelper) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) PluginItemContext(com.google.gerrit.server.plugincontext.PluginItemContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Collection(java.util.Collection) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) Status(com.google.gerrit.extensions.common.ProblemInfo.Status) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) PS_ID_ORDER(com.google.gerrit.server.ChangeUtil.PS_ID_ORDER) Nullable(com.google.gerrit.common.Nullable) Ref(org.eclipse.jgit.lib.Ref) AutoValue(com.google.auto.value.AutoValue) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) FluentLogger(com.google.common.flogger.FluentLogger) Iterables(com.google.common.collect.Iterables) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) FixInput(com.google.gerrit.extensions.api.changes.FixInput) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) PatchSetState(com.google.gerrit.server.notedb.PatchSetState) RepoContext(com.google.gerrit.server.update.RepoContext) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) Objects.requireNonNull(java.util.Objects.requireNonNull) REFS_CHANGES(com.google.gerrit.entities.RefNames.REFS_CHANGES) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Comparator.comparing(java.util.Comparator.comparing) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) PatchSetInfoNotAvailableException(com.google.gerrit.server.patch.PatchSetInfoNotAvailableException) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) CurrentUser(com.google.gerrit.server.CurrentUser) StorageException(com.google.gerrit.exceptions.StorageException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) SetMultimap(com.google.common.collect.SetMultimap) ObjectId(org.eclipse.jgit.lib.ObjectId) Provider(com.google.inject.Provider) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) Project(com.google.gerrit.entities.Project) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Collections(java.util.Collections) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) Repository(org.eclipse.jgit.lib.Repository) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) Ref(org.eclipse.jgit.lib.Ref) Collection(java.util.Collection) StorageException(com.google.gerrit.exceptions.StorageException) Map(java.util.Map) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 18 with PatchSet

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

the class Revisions method loadEdit.

// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
private ImmutableList<RevisionResource> loadEdit(ChangeResource change, @Nullable ObjectId commitId) throws AuthException, IOException {
    Optional<ChangeEdit> edit = editUtil.byChange(change.getNotes(), change.getUser());
    if (edit.isPresent()) {
        RevCommit editCommit = edit.get().getEditCommit();
        PatchSet ps = PatchSet.builder().id(PatchSet.id(change.getId(), 0)).commitId(editCommit).uploader(change.getUser().getAccountId()).createdOn(editCommit.getCommitterIdent().getWhen().toInstant()).build();
        if (commitId == null || editCommit.equals(commitId)) {
            return ImmutableList.of(new RevisionResource(change, ps, edit));
        }
    }
    return ImmutableList.of();
}
Also used : ChangeEdit(com.google.gerrit.server.edit.ChangeEdit) PatchSet(com.google.gerrit.entities.PatchSet) RevisionResource(com.google.gerrit.server.change.RevisionResource) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 19 with PatchSet

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

the class Submit method unmergeableChanges.

public Collection<ChangeData> unmergeableChanges(ChangeSet cs) throws IOException {
    Set<ChangeData> mergeabilityMap = new HashSet<>();
    Set<ObjectId> outDatedPatchsets = new HashSet<>();
    for (ChangeData change : cs.changes()) {
        mergeabilityMap.add(change);
        // Add all the patchsets commit ids except the current patchset.
        outDatedPatchsets.addAll(change.notes().getPatchSets().values().stream().map(p -> p.commitId()).collect(Collectors.toSet()));
        outDatedPatchsets.remove(change.currentPatchSet().commitId());
    }
    ListMultimap<BranchNameKey, ChangeData> cbb = cs.changesByBranch();
    for (BranchNameKey branch : cbb.keySet()) {
        Collection<ChangeData> targetBranch = cbb.get(branch);
        HashMap<Change.Id, RevCommit> commits = findCommits(targetBranch, branch.project());
        Set<ObjectId> allParents = Sets.newHashSetWithExpectedSize(cs.size());
        for (RevCommit commit : commits.values()) {
            for (RevCommit parent : commit.getParents()) {
                allParents.add(parent.getId());
            }
        }
        for (ChangeData change : targetBranch) {
            RevCommit commit = commits.get(change.getId());
            boolean isMergeCommit = commit.getParentCount() > 1;
            boolean isLastInChain = !allParents.contains(commit.getId());
            if (Arrays.stream(commit.getParents()).anyMatch(c -> outDatedPatchsets.contains(c.getId())) && !isCherryPickSubmit(change)) {
                // cherry-pick.
                continue;
            }
            // Recheck mergeability rather than using value stored in the index,
            // which may be stale.
            // TODO(dborowitz): This is ugly; consider providing a way to not read
            // stored fields from the index in the first place.
            change.setMergeable(null);
            Boolean mergeable = change.isMergeable();
            if (mergeable == null) {
                // Skip whole check, cannot determine if mergeable
                return null;
            }
            if (mergeable) {
                mergeabilityMap.remove(change);
            }
            if (isLastInChain && isMergeCommit && mergeable) {
                for (ChangeData c : targetBranch) {
                    mergeabilityMap.remove(c);
                }
                break;
            }
        }
    }
    return mergeabilityMap;
}
Also used : Arrays(java.util.Arrays) ListMultimap(com.google.common.collect.ListMultimap) ProjectCache(com.google.gerrit.server.project.ProjectCache) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Inject(com.google.inject.Inject) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) UpdateException(com.google.gerrit.server.update.UpdateException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) SubmitInput(com.google.gerrit.extensions.api.changes.SubmitInput) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) UiAction(com.google.gerrit.extensions.webui.UiAction) EnumSet(java.util.EnumSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) ImmutableMap(com.google.common.collect.ImmutableMap) SubmitType(com.google.gerrit.extensions.client.SubmitType) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) BranchNameKey(com.google.gerrit.entities.BranchNameKey) SubmitTypeRecord(com.google.gerrit.entities.SubmitTypeRecord) ChangeData(com.google.gerrit.server.query.change.ChangeData) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) ChangeJson(com.google.gerrit.server.change.ChangeJson) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) HashMap(java.util.HashMap) Response(com.google.gerrit.extensions.restapi.Response) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) MergeOp(com.google.gerrit.server.submit.MergeOp) ChangeResource(com.google.gerrit.server.change.ChangeResource) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) UsedAt(com.google.gerrit.common.UsedAt) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) CurrentUser(com.google.gerrit.server.CurrentUser) MergeSuperSet(com.google.gerrit.server.submit.MergeSuperSet) AccountResolver(com.google.gerrit.server.account.AccountResolver) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) ChangeSet(com.google.gerrit.server.submit.ChangeSet) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) MoreObjects(com.google.common.base.MoreObjects) ParameterizedString(com.google.gerrit.common.data.ParameterizedString) IOException(java.io.IOException) ObjectId(org.eclipse.jgit.lib.ObjectId) Provider(com.google.inject.Provider) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) RevisionResource(com.google.gerrit.server.change.RevisionResource) ProjectUtil(com.google.gerrit.server.ProjectUtil) Project(com.google.gerrit.entities.Project) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) ChangeData(com.google.gerrit.server.query.change.ChangeData) BranchNameKey(com.google.gerrit.entities.BranchNameKey) ObjectId(org.eclipse.jgit.lib.ObjectId) HashSet(java.util.HashSet) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 20 with PatchSet

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

the class Revert method apply.

@Override
public Response<ChangeInfo> apply(ChangeResource rsrc, RevertInput input) throws IOException, RestApiException, UpdateException, NoSuchChangeException, PermissionBackendException, NoSuchProjectException, ConfigInvalidException {
    Change change = rsrc.getChange();
    if (!change.isMerged()) {
        throw new ResourceConflictException("change is " + ChangeUtil.status(change));
    }
    contributorAgreements.check(rsrc.getProject(), rsrc.getUser());
    permissionBackend.user(rsrc.getUser()).ref(change.getDest()).check(CREATE_CHANGE);
    projectCache.get(rsrc.getProject()).orElseThrow(illegalState(rsrc.getProject())).checkStatePermitsWrite();
    rsrc.permissions().check(REVERT);
    ChangeNotes notes = rsrc.getNotes();
    Change.Id changeIdToRevert = notes.getChangeId();
    PatchSet.Id patchSetId = notes.getChange().currentPatchSetId();
    PatchSet patch = psUtil.get(notes, patchSetId);
    if (patch == null) {
        throw new ResourceNotFoundException(changeIdToRevert.toString());
    }
    return Response.ok(json.noOptions().format(rsrc.getProject(), commitUtil.createRevertChange(notes, rsrc.getUser(), input, TimeUtil.now())));
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSet(com.google.gerrit.entities.PatchSet) Change(com.google.gerrit.entities.Change) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

PatchSet (com.google.gerrit.entities.PatchSet)123 Change (com.google.gerrit.entities.Change)61 Test (org.junit.Test)48 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)41 ObjectId (org.eclipse.jgit.lib.ObjectId)35 RevCommit (org.eclipse.jgit.revwalk.RevCommit)29 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)28 Project (com.google.gerrit.entities.Project)25 StorageException (com.google.gerrit.exceptions.StorageException)25 Repository (org.eclipse.jgit.lib.Repository)22 IOException (java.io.IOException)20 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)19 ChangeData (com.google.gerrit.server.query.change.ChangeData)18 HumanComment (com.google.gerrit.entities.HumanComment)16 RevWalk (org.eclipse.jgit.revwalk.RevWalk)16 Inject (com.google.inject.Inject)14 Map (java.util.Map)14 List (java.util.List)13 ImmutableList (com.google.common.collect.ImmutableList)12 AuthException (com.google.gerrit.extensions.restapi.AuthException)11