Search in sources :

Example 1 with ChangeJson

use of com.google.gerrit.server.change.ChangeJson in project gerrit by GerritCodeReview.

the class ProjectsConsistencyChecker method changeJson.

private ChangeJson changeJson(Boolean fix, ObjectId mergedAs) {
    ChangeJson changeJson = changeJsonFactory.create(ListChangesOption.CHECK);
    if (fix != null && fix.booleanValue()) {
        FixInput fixInput = new FixInput();
        fixInput.expectMergedAs = mergedAs.name();
        changeJson.fix(fixInput);
    }
    return changeJson;
}
Also used : ChangeJson(com.google.gerrit.server.change.ChangeJson) FixInput(com.google.gerrit.extensions.api.changes.FixInput)

Example 2 with ChangeJson

use of com.google.gerrit.server.change.ChangeJson in project gerrit by GerritCodeReview.

the class QueryChanges method query.

private List<List<ChangeInfo>> query() throws OrmException, QueryParseException {
    if (imp.isDisabled()) {
        throw new QueryParseException("query disabled");
    }
    if (queries == null || queries.isEmpty()) {
        queries = Collections.singletonList("status:open");
    } else if (queries.size() > 10) {
        // users from submitting too much to the server in a single call.
        throw new QueryParseException("limit of 10 queries");
    }
    int cnt = queries.size();
    List<QueryResult<ChangeData>> results = imp.query(qb.parse(queries));
    boolean requireLazyLoad = containsAnyOf(options, ImmutableSet.of(DETAILED_LABELS, LABELS)) && !qb.getArgs().getSchema().hasField(ChangeField.STORED_SUBMIT_RECORD_LENIENT);
    ChangeJson cjson = json.create(options);
    cjson.setPluginDefinedAttributesFactory(this.imp);
    List<List<ChangeInfo>> res = cjson.lazyLoad(requireLazyLoad || containsAnyOf(options, ChangeJson.REQUIRE_LAZY_LOAD)).formatQueryResults(results);
    for (int n = 0; n < cnt; n++) {
        List<ChangeInfo> info = res.get(n);
        if (results.get(n).more()) {
            info.get(info.size() - 1)._moreChanges = true;
        }
    }
    return res;
}
Also used : QueryResult(com.google.gerrit.server.query.QueryResult) ChangeJson(com.google.gerrit.server.change.ChangeJson) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ArrayList(java.util.ArrayList) List(java.util.List) QueryParseException(com.google.gerrit.server.query.QueryParseException)

Example 3 with ChangeJson

use of com.google.gerrit.server.change.ChangeJson in project gerrit by GerritCodeReview.

the class ProjectsConsistencyChecker method executeQueryAndAutoCloseChanges.

private ImmutableList<ChangeInfo> executeQueryAndAutoCloseChanges(Predicate<ChangeData> basePredicate, Set<Change.Id> seenChanges, List<Predicate<ChangeData>> predicates, boolean fix, Map<Change.Key, ObjectId> changeIdToMergedSha1, List<ObjectId> mergedSha1s) {
    if (predicates.isEmpty()) {
        return ImmutableList.of();
    }
    try {
        List<ChangeData> queryResult = retryHelper.changeIndexQuery("projectsConsistencyCheckerQueryChanges", q -> q.setRequestedFields(ChangeField.CHANGE, ChangeField.PATCH_SET).query(and(basePredicate, or(predicates)))).call();
        // Result for this query that we want to return to the client.
        ImmutableList.Builder<ChangeInfo> autoCloseableChangesByBranch = ImmutableList.builder();
        for (ChangeData autoCloseableChange : queryResult) {
            // earlier queries.
            if (seenChanges.add(autoCloseableChange.getId())) {
                retryHelper.changeUpdate("projectsConsistencyCheckerAutoCloseChanges", () -> {
                    // Auto-close by change
                    if (changeIdToMergedSha1.containsKey(autoCloseableChange.change().getKey())) {
                        autoCloseableChangesByBranch.add(changeJson(fix, changeIdToMergedSha1.get(autoCloseableChange.change().getKey())).format(autoCloseableChange));
                        return null;
                    }
                    // Auto-close by commit
                    for (ObjectId patchSetSha1 : autoCloseableChange.patchSets().stream().map(PatchSet::commitId).collect(toSet())) {
                        if (mergedSha1s.contains(patchSetSha1)) {
                            autoCloseableChangesByBranch.add(changeJson(fix, patchSetSha1).format(autoCloseableChange));
                            break;
                        }
                    }
                    return null;
                }).call();
            }
        }
        return autoCloseableChangesByBranch.build();
    } catch (Exception e) {
        Throwables.throwIfUnchecked(e);
        throw new StorageException(e);
    }
}
Also used : DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ChangePredicates(com.google.gerrit.server.query.change.ChangePredicates) RevWalk(org.eclipse.jgit.revwalk.RevWalk) CheckProjectResultInfo(com.google.gerrit.extensions.api.projects.CheckProjectResultInfo) Map(java.util.Map) RefNames(com.google.gerrit.entities.RefNames) RetryHelper(com.google.gerrit.server.update.RetryHelper) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) Predicate.or(com.google.gerrit.index.query.Predicate.or) Collectors.toSet(java.util.stream.Collectors.toSet) Set(java.util.Set) RevSort(org.eclipse.jgit.revwalk.RevSort) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Ref(org.eclipse.jgit.lib.Ref) ChangeJson(com.google.gerrit.server.change.ChangeJson) Singleton(com.google.inject.Singleton) AutoCloseableChangesCheckResult(com.google.gerrit.extensions.api.projects.CheckProjectResultInfo.AutoCloseableChangesCheckResult) IndexConfig(com.google.gerrit.index.IndexConfig) RevCommit(org.eclipse.jgit.revwalk.RevCommit) FixInput(com.google.gerrit.extensions.api.changes.FixInput) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) AutoCloseableChangesCheckInput(com.google.gerrit.extensions.api.projects.CheckProjectInput.AutoCloseableChangesCheckInput) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) Predicate(com.google.gerrit.index.query.Predicate) ListChangesOption(com.google.gerrit.extensions.client.ListChangesOption) ChangeStatusPredicate.open(com.google.gerrit.server.query.change.ChangeStatusPredicate.open) StorageException(com.google.gerrit.exceptions.StorageException) Predicate.and(com.google.gerrit.index.query.Predicate.and) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) ObjectId(org.eclipse.jgit.lib.ObjectId) ChangeField(com.google.gerrit.server.index.change.ChangeField) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Project(com.google.gerrit.entities.Project) CheckProjectInput(com.google.gerrit.extensions.api.projects.CheckProjectInput) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Repository(org.eclipse.jgit.lib.Repository) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) ImmutableList(com.google.common.collect.ImmutableList) PatchSet(com.google.gerrit.entities.PatchSet) ChangeData(com.google.gerrit.server.query.change.ChangeData) StorageException(com.google.gerrit.exceptions.StorageException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) StorageException(com.google.gerrit.exceptions.StorageException) IOException(java.io.IOException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException)

Example 4 with ChangeJson

use of com.google.gerrit.server.change.ChangeJson in project gerrit by GerritCodeReview.

the class CreateMergePatchSet method apply.

// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
@Override
public Response<ChangeInfo> apply(ChangeResource rsrc, MergePatchSetInput in) throws IOException, RestApiException, UpdateException, PermissionBackendException {
    // Not allowed to create a new patch set if the current patch set is locked.
    psUtil.checkPatchSetNotLocked(rsrc.getNotes());
    rsrc.permissions().check(ChangePermission.ADD_PATCH_SET);
    if (in.author != null) {
        permissionBackend.currentUser().project(rsrc.getProject()).ref(rsrc.getChange().getDest().branch()).check(RefPermission.FORGE_AUTHOR);
    }
    ProjectState projectState = projectCache.get(rsrc.getProject()).orElseThrow(illegalState(rsrc.getProject()));
    projectState.checkStatePermitsWrite();
    MergeInput merge = in.merge;
    if (merge == null || Strings.isNullOrEmpty(merge.source)) {
        throw new BadRequestException("merge.source must be non-empty");
    }
    if (in.author != null && (Strings.isNullOrEmpty(in.author.email) || Strings.isNullOrEmpty(in.author.name))) {
        throw new BadRequestException("Author must specify name and email");
    }
    in.baseChange = Strings.nullToEmpty(in.baseChange).trim();
    PatchSet ps = psUtil.current(rsrc.getNotes());
    Change change = rsrc.getChange();
    Project.NameKey project = change.getProject();
    BranchNameKey dest = change.getDest();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(reader)) {
        RevCommit sourceCommit = MergeUtil.resolveCommit(git, rw, merge.source);
        if (!commits.canRead(projectState, git, sourceCommit)) {
            throw new ResourceNotFoundException("cannot find source commit: " + merge.source + " to merge.");
        }
        RevCommit currentPsCommit;
        List<String> groups = null;
        if (!in.inheritParent && !in.baseChange.isEmpty()) {
            PatchSet basePS = findBasePatchSet(in.baseChange);
            currentPsCommit = rw.parseCommit(basePS.commitId());
            groups = basePS.groups();
        } else {
            currentPsCommit = rw.parseCommit(ps.commitId());
        }
        Instant now = TimeUtil.now();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = in.author == null ? me.newCommitterIdent(now, serverTimeZone) : new PersonIdent(in.author.name, in.author.email, Date.from(now), serverTimeZone);
        CodeReviewCommit newCommit = createMergeCommit(in, projectState, dest, git, oi, rw, currentPsCommit, sourceCommit, author, ObjectId.fromString(change.getKey().get().substring(1)));
        oi.flush();
        PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.id());
        PatchSetInserter psInserter = patchSetInserterFactory.create(rsrc.getNotes(), nextPsId, newCommit);
        try (BatchUpdate bu = updateFactory.create(project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.setNotify(NotifyResolver.Result.none());
            psInserter.setMessage(messageForChange(nextPsId, newCommit)).setWorkInProgress(!newCommit.getFilesWithGitConflicts().isEmpty()).setCheckAddPatchSetPermission(false);
            if (groups != null) {
                psInserter.setGroups(groups);
            }
            bu.addOp(rsrc.getId(), psInserter);
            bu.execute();
        }
        ChangeJson json = jsonFactory.create(ListChangesOption.CURRENT_REVISION);
        ChangeInfo changeInfo = json.format(psInserter.getChange());
        changeInfo.containsGitConflicts = !newCommit.getFilesWithGitConflicts().isEmpty() ? true : null;
        return Response.ok(changeInfo);
    } catch (InvalidMergeStrategyException | MergeWithConflictsNotSupportedException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : MergeInput(com.google.gerrit.extensions.common.MergeInput) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) BranchNameKey(com.google.gerrit.entities.BranchNameKey) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ChangeJson(com.google.gerrit.server.change.ChangeJson) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) Instant(java.time.Instant) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) PatchSet(com.google.gerrit.entities.PatchSet) Change(com.google.gerrit.entities.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) PatchSetInserter(com.google.gerrit.server.change.PatchSetInserter) InvalidMergeStrategyException(com.google.gerrit.exceptions.InvalidMergeStrategyException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) MergeWithConflictsNotSupportedException(com.google.gerrit.exceptions.MergeWithConflictsNotSupportedException) ProjectState(com.google.gerrit.server.project.ProjectState)

Aggregations

ChangeJson (com.google.gerrit.server.change.ChangeJson)4 ChangeInfo (com.google.gerrit.extensions.common.ChangeInfo)3 Change (com.google.gerrit.entities.Change)2 PatchSet (com.google.gerrit.entities.PatchSet)2 Project (com.google.gerrit.entities.Project)2 FixInput (com.google.gerrit.extensions.api.changes.FixInput)2 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Repository (org.eclipse.jgit.lib.Repository)2 RevCommit (org.eclipse.jgit.revwalk.RevCommit)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Strings (com.google.common.base.Strings)1 Throwables (com.google.common.base.Throwables)1 ImmutableList (com.google.common.collect.ImmutableList)1 BranchNameKey (com.google.gerrit.entities.BranchNameKey)1 RefNames (com.google.gerrit.entities.RefNames)1 InvalidMergeStrategyException (com.google.gerrit.exceptions.InvalidMergeStrategyException)1 MergeWithConflictsNotSupportedException (com.google.gerrit.exceptions.MergeWithConflictsNotSupportedException)1 StorageException (com.google.gerrit.exceptions.StorageException)1