Search in sources :

Example 1 with Predicate

use of com.google.gerrit.server.query.Predicate in project gerrit by GerritCodeReview.

the class IsWatchedByPredicate method filters.

protected static List<Predicate<ChangeData>> filters(ChangeQueryBuilder.Arguments args, boolean checkIsVisible) throws QueryParseException {
    List<Predicate<ChangeData>> r = new ArrayList<>();
    ChangeQueryBuilder builder = new ChangeQueryBuilder(args);
    for (ProjectWatchKey w : getWatches(args)) {
        Predicate<ChangeData> f = null;
        if (w.filter() != null) {
            try {
                f = builder.parse(w.filter());
                if (QueryBuilder.find(f, IsWatchedByPredicate.class) != null) {
                    // another user is filtering on. :-)
                    continue;
                }
            } catch (QueryParseException e) {
                continue;
            }
        }
        Predicate<ChangeData> p;
        if (w.project().equals(args.allProjectsName)) {
            p = null;
        } else {
            p = builder.project(w.project().get());
        }
        if (p != null && f != null) {
            r.add(and(p, f));
        } else if (p != null) {
            r.add(p);
        } else if (f != null) {
            r.add(f);
        } else {
            r.add(builder.status_open());
        }
    }
    if (r.isEmpty()) {
        return none();
    } else if (checkIsVisible) {
        return ImmutableList.of(or(r), builder.is_visible());
    } else {
        return ImmutableList.of(or(r));
    }
}
Also used : ProjectWatchKey(com.google.gerrit.server.account.WatchConfig.ProjectWatchKey) ArrayList(java.util.ArrayList) AndPredicate(com.google.gerrit.server.query.AndPredicate) Predicate(com.google.gerrit.server.query.Predicate) QueryParseException(com.google.gerrit.server.query.QueryParseException)

Example 2 with Predicate

use of com.google.gerrit.server.query.Predicate in project gerrit by GerritCodeReview.

the class ConflictsPredicate method predicates.

public static List<Predicate<ChangeData>> predicates(final Arguments args, String value, List<Change> changes) throws QueryParseException, OrmException {
    int indexTerms = 0;
    List<Predicate<ChangeData>> changePredicates = Lists.newArrayListWithCapacity(changes.size());
    final Provider<ReviewDb> db = args.db;
    for (final Change c : changes) {
        final ChangeDataCache changeDataCache = new ChangeDataCache(c, db, args.changeDataFactory, args.projectCache);
        List<String> files = listFiles(c, args, changeDataCache);
        indexTerms += 3 + files.size();
        if (indexTerms > args.indexConfig.maxTerms()) {
            // later on in the query parsing.
            throw new QueryParseException(TOO_MANY_FILES);
        }
        List<Predicate<ChangeData>> filePredicates = Lists.newArrayListWithCapacity(files.size());
        for (String file : files) {
            filePredicates.add(new EqualsPathPredicate(ChangeQueryBuilder.FIELD_PATH, file));
        }
        List<Predicate<ChangeData>> predicatesForOneChange = Lists.newArrayListWithCapacity(5);
        predicatesForOneChange.add(not(new LegacyChangeIdPredicate(c.getId())));
        predicatesForOneChange.add(new ProjectPredicate(c.getProject().get()));
        predicatesForOneChange.add(new RefPredicate(c.getDest().get()));
        predicatesForOneChange.add(or(or(filePredicates), new IsMergePredicate(args, value)));
        predicatesForOneChange.add(new ChangeOperatorPredicate(ChangeQueryBuilder.FIELD_CONFLICTS, value) {

            @Override
            public boolean match(ChangeData object) throws OrmException {
                Change otherChange = object.change();
                if (otherChange == null) {
                    return false;
                }
                if (!otherChange.getDest().equals(c.getDest())) {
                    return false;
                }
                SubmitTypeRecord str = object.submitTypeRecord();
                if (!str.isOk()) {
                    return false;
                }
                ObjectId other = ObjectId.fromString(object.currentPatchSet().getRevision().get());
                ConflictKey conflictsKey = new ConflictKey(changeDataCache.getTestAgainst(), other, str.type, changeDataCache.getProjectState().isUseContentMerge());
                Boolean conflicts = args.conflictsCache.getIfPresent(conflictsKey);
                if (conflicts != null) {
                    return conflicts;
                }
                try (Repository repo = args.repoManager.openRepository(otherChange.getProject());
                    CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
                    conflicts = !args.submitDryRun.run(str.type, repo, rw, otherChange.getDest(), changeDataCache.getTestAgainst(), other, getAlreadyAccepted(repo, rw));
                    args.conflictsCache.put(conflictsKey, conflicts);
                    return conflicts;
                } catch (IntegrationException | NoSuchProjectException | IOException e) {
                    throw new OrmException(e);
                }
            }

            @Override
            public int getCost() {
                return 5;
            }

            private Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw) throws IntegrationException {
                try {
                    Set<RevCommit> accepted = new HashSet<>();
                    SubmitDryRun.addCommits(changeDataCache.getAlreadyAccepted(repo), rw, accepted);
                    ObjectId tip = changeDataCache.getTestAgainst();
                    if (tip != null) {
                        accepted.add(rw.parseCommit(tip));
                    }
                    return accepted;
                } catch (OrmException | IOException e) {
                    throw new IntegrationException("Failed to determine already accepted commits.", e);
                }
            }
        });
        changePredicates.add(and(predicatesForOneChange));
    }
    return changePredicates;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) OrPredicate(com.google.gerrit.server.query.OrPredicate) Predicate(com.google.gerrit.server.query.Predicate) OrmException(com.google.gwtorm.server.OrmException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) 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) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) RevWalk(org.eclipse.jgit.revwalk.RevWalk) QueryParseException(com.google.gerrit.server.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository) SubmitTypeRecord(com.google.gerrit.common.data.SubmitTypeRecord)

Example 3 with Predicate

use of com.google.gerrit.server.query.Predicate in project gerrit by GerritCodeReview.

the class ReviewerRecommender method baseRankingForCandidateList.

private Map<Account.Id, MutableDouble> baseRankingForCandidateList(List<Account.Id> candidates, ProjectControl projectControl, double baseWeight) throws OrmException {
    // Get each reviewer's activity based on number of applied labels
    // (weighted 10d), number of comments (weighted 0.5d) and number of owned
    // changes (weighted 1d).
    Map<Account.Id, MutableDouble> reviewers = new LinkedHashMap<>();
    if (candidates.size() == 0) {
        return reviewers;
    }
    List<Predicate<ChangeData>> predicates = new ArrayList<>();
    for (Account.Id id : candidates) {
        try {
            Predicate<ChangeData> projectQuery = changeQueryBuilder.project(projectControl.getProject().getName());
            // Get all labels for this project and create a compound OR query to
            // fetch all changes where users have applied one of these labels
            List<LabelType> labelTypes = projectControl.getLabelTypes().getLabelTypes();
            List<Predicate<ChangeData>> labelPredicates = new ArrayList<>(labelTypes.size());
            for (LabelType type : labelTypes) {
                labelPredicates.add(changeQueryBuilder.label(type.getName() + ",user=" + id));
            }
            Predicate<ChangeData> reviewerQuery = Predicate.and(projectQuery, Predicate.or(labelPredicates));
            Predicate<ChangeData> ownerQuery = Predicate.and(projectQuery, changeQueryBuilder.owner(id.toString()));
            Predicate<ChangeData> commentedByQuery = Predicate.and(projectQuery, changeQueryBuilder.commentby(id.toString()));
            predicates.add(reviewerQuery);
            predicates.add(ownerQuery);
            predicates.add(commentedByQuery);
            reviewers.put(id, new MutableDouble());
        } catch (QueryParseException e) {
            // Unhandled: If an exception is thrown, we won't increase the
            // candidates's score
            log.error("Exception while suggesting reviewers", e);
        }
    }
    List<List<ChangeData>> result = internalChangeQuery.setLimit(25).setRequestedFields(ImmutableSet.of()).query(predicates);
    Iterator<List<ChangeData>> queryResultIterator = result.iterator();
    Iterator<Account.Id> reviewersIterator = reviewers.keySet().iterator();
    int i = 0;
    Account.Id currentId = null;
    while (queryResultIterator.hasNext()) {
        List<ChangeData> currentResult = queryResultIterator.next();
        if (i % WEIGHTS.length == 0) {
            currentId = reviewersIterator.next();
        }
        reviewers.get(currentId).add(WEIGHTS[i % WEIGHTS.length] * baseWeight * currentResult.size());
        i++;
    }
    return reviewers;
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) MutableDouble(org.apache.commons.lang.mutable.MutableDouble) ArrayList(java.util.ArrayList) ChangeData(com.google.gerrit.server.query.change.ChangeData) LinkedHashMap(java.util.LinkedHashMap) Predicate(com.google.gerrit.server.query.Predicate) QueryParseException(com.google.gerrit.server.query.QueryParseException) LabelType(com.google.gerrit.common.data.LabelType) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List)

Example 4 with Predicate

use of com.google.gerrit.server.query.Predicate in project gerrit by GerritCodeReview.

the class ParentProjectPredicate method predicates.

protected static List<Predicate<ChangeData>> predicates(ProjectCache projectCache, Provider<ListChildProjects> listChildProjects, Provider<CurrentUser> self, String value) {
    ProjectState projectState = projectCache.get(new Project.NameKey(value));
    if (projectState == null) {
        return Collections.emptyList();
    }
    List<Predicate<ChangeData>> r = new ArrayList<>();
    r.add(new ProjectPredicate(projectState.getProject().getName()));
    try {
        ProjectResource proj = new ProjectResource(projectState.controlFor(self.get()));
        ListChildProjects children = listChildProjects.get();
        children.setRecursive(true);
        for (ProjectInfo p : children.apply(proj)) {
            r.add(new ProjectPredicate(p.name));
        }
    } catch (PermissionBackendException e) {
        log.warn("cannot check permissions to expand child projects", e);
    }
    return r;
}
Also used : Project(com.google.gerrit.reviewdb.client.Project) ListChildProjects(com.google.gerrit.server.project.ListChildProjects) ArrayList(java.util.ArrayList) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) ProjectState(com.google.gerrit.server.project.ProjectState) ProjectResource(com.google.gerrit.server.project.ProjectResource) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) OrPredicate(com.google.gerrit.server.query.OrPredicate) Predicate(com.google.gerrit.server.query.Predicate)

Example 5 with Predicate

use of com.google.gerrit.server.query.Predicate in project gerrit by GerritCodeReview.

the class ChangeQueryBuilder method label.

@Operator
public Predicate<ChangeData> label(String name) throws QueryParseException, OrmException {
    Set<Account.Id> accounts = null;
    AccountGroup.UUID group = null;
    // Parse for:
    // label:CodeReview=1,user=jsmith or
    // label:CodeReview=1,jsmith or
    // label:CodeReview=1,group=android_approvers or
    // label:CodeReview=1,android_approvers
    // user/groups without a label will first attempt to match user
    // Special case: votes by owners can be tracked with ",owner":
    // label:Code-Review+2,owner
    // label:Code-Review+2,user=owner
    String[] splitReviewer = name.split(",", 2);
    // remove all but the vote piece, e.g.'CodeReview=1'
    name = splitReviewer[0];
    if (splitReviewer.length == 2) {
        // process the user/group piece
        PredicateArgs lblArgs = new PredicateArgs(splitReviewer[1]);
        for (Map.Entry<String, String> pair : lblArgs.keyValue.entrySet()) {
            if (pair.getKey().equalsIgnoreCase(ARG_ID_USER)) {
                if (pair.getValue().equals(ARG_ID_OWNER)) {
                    accounts = Collections.singleton(OWNER_ACCOUNT_ID);
                } else {
                    accounts = parseAccount(pair.getValue());
                }
            } else if (pair.getKey().equalsIgnoreCase(ARG_ID_GROUP)) {
                group = parseGroup(pair.getValue()).getUUID();
            } else {
                throw new QueryParseException("Invalid argument identifier '" + pair.getKey() + "'");
            }
        }
        for (String value : lblArgs.positional) {
            if (accounts != null || group != null) {
                throw new QueryParseException("more than one user/group specified (" + value + ")");
            }
            try {
                if (value.equals(ARG_ID_OWNER)) {
                    accounts = Collections.singleton(OWNER_ACCOUNT_ID);
                } else {
                    accounts = parseAccount(value);
                }
            } catch (QueryParseException qpex) {
                // (accounts get precedence)
                try {
                    group = parseGroup(value).getUUID();
                } catch (QueryParseException e) {
                    throw error("Neither user nor group " + value + " found", e);
                }
            }
        }
    }
    // expand a group predicate into multiple user predicates
    if (group != null) {
        Set<Account.Id> allMembers = args.listMembers.get().setRecursive(true).apply(group).stream().map(a -> new Account.Id(a._accountId)).collect(toSet());
        int maxLimit = args.indexConfig.maxLimit();
        if (allMembers.size() > maxLimit) {
            // limit the number of query terms otherwise Gerrit will barf
            accounts = ImmutableSet.copyOf(Iterables.limit(allMembers, maxLimit));
        } else {
            accounts = allMembers;
        }
    }
    // If the vote piece looks like Code-Review=NEED with a valid non-numeric
    // submit record status, interpret as a submit record query.
    int eq = name.indexOf('=');
    if (args.getSchema().hasField(ChangeField.SUBMIT_RECORD) && eq > 0) {
        String statusName = name.substring(eq + 1).toUpperCase();
        if (!isInt(statusName)) {
            SubmitRecord.Label.Status status = Enums.getIfPresent(SubmitRecord.Label.Status.class, statusName).orNull();
            if (status == null) {
                throw error("Invalid label status " + statusName + " in " + name);
            }
            return SubmitRecordPredicate.create(name.substring(0, eq), status, accounts);
        }
    }
    return new LabelPredicate(args, name, accounts, group);
}
Also used : AllUsersName(com.google.gerrit.server.config.AllUsersName) GroupBackend(com.google.gerrit.server.account.GroupBackend) ChangeControl(com.google.gerrit.server.project.ChangeControl) OrmException(com.google.gwtorm.server.OrmException) 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) Config(org.eclipse.jgit.lib.Config) ChangeTriplet(com.google.gerrit.server.change.ChangeTriplet) CapabilityControl(com.google.gerrit.server.account.CapabilityControl) VersionedAccountQueries(com.google.gerrit.server.account.VersionedAccountQueries) Map(java.util.Map) CHANGE_ID_PATTERN(com.google.gerrit.reviewdb.client.Change.CHANGE_ID_PATTERN) ProvisionException(com.google.inject.ProvisionException) SubmitDryRun(com.google.gerrit.server.git.strategy.SubmitDryRun) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSet(com.google.common.collect.ImmutableSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Schema(com.google.gerrit.server.index.Schema) Collection(java.util.Collection) ListChildProjects(com.google.gerrit.server.project.ListChildProjects) Set(java.util.Set) Collectors(java.util.stream.Collectors) Predicate(com.google.gerrit.server.query.Predicate) Objects(java.util.Objects) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) List(java.util.List) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) RefNames(com.google.gerrit.reviewdb.client.RefNames) ChangeData.asChanges(com.google.gerrit.server.query.change.ChangeData.asChanges) Optional(java.util.Optional) Providers(com.google.inject.util.Providers) Pattern(java.util.regex.Pattern) NotesMigration(com.google.gerrit.server.notedb.NotesMigration) GroupReference(com.google.gerrit.common.data.GroupReference) Branch(com.google.gerrit.reviewdb.client.Branch) ChangeIndexRewriter(com.google.gerrit.server.index.change.ChangeIndexRewriter) AccountCache(com.google.gerrit.server.account.AccountCache) Iterables(com.google.common.collect.Iterables) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Change(com.google.gerrit.reviewdb.client.Change) GroupBackends(com.google.gerrit.server.account.GroupBackends) CommentsUtil(com.google.gerrit.server.CommentsUtil) Function(java.util.function.Function) Enums(com.google.common.base.Enums) SubmitRecord(com.google.gerrit.common.data.SubmitRecord) HashSet(java.util.HashSet) NotSignedInException(com.google.gerrit.common.errors.NotSignedInException) IndexConfig(com.google.gerrit.server.index.IndexConfig) Lists(com.google.common.collect.Lists) Account(com.google.gerrit.reviewdb.client.Account) SchemaUtil(com.google.gerrit.server.index.SchemaUtil) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResolver(com.google.gerrit.server.account.AccountResolver) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) PatchListCache(com.google.gerrit.server.patch.PatchListCache) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) VersionedAccountDestinations(com.google.gerrit.server.account.VersionedAccountDestinations) Ints(com.google.common.primitives.Ints) ChangeField(com.google.gerrit.server.index.change.ChangeField) QueryParseException(com.google.gerrit.server.query.QueryParseException) Collectors.toList(java.util.stream.Collectors.toList) Address(com.google.gerrit.server.mail.Address) LimitPredicate(com.google.gerrit.server.query.LimitPredicate) Provider(com.google.inject.Provider) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) ListMembers(com.google.gerrit.server.group.ListMembers) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) TrackingFooters(com.google.gerrit.server.config.TrackingFooters) FieldDef(com.google.gerrit.server.index.FieldDef) ChangeIndexCollection(com.google.gerrit.server.index.change.ChangeIndexCollection) VisibleForTesting(com.google.common.annotations.VisibleForTesting) QueryBuilder(com.google.gerrit.server.query.QueryBuilder) ChangeIndex(com.google.gerrit.server.index.change.ChangeIndex) Collections(java.util.Collections) Repository(org.eclipse.jgit.lib.Repository) StarredChangesUtil(com.google.gerrit.server.StarredChangesUtil) QueryParseException(com.google.gerrit.server.query.QueryParseException) SubmitRecord(com.google.gerrit.common.data.SubmitRecord) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) Map(java.util.Map) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap)

Aggregations

Predicate (com.google.gerrit.server.query.Predicate)5 QueryParseException (com.google.gerrit.server.query.QueryParseException)4 ArrayList (java.util.ArrayList)3 Account (com.google.gerrit.reviewdb.client.Account)2 Change (com.google.gerrit.reviewdb.client.Change)2 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)2 ListChildProjects (com.google.gerrit.server.project.ListChildProjects)2 List (java.util.List)2 Collectors.toList (java.util.stream.Collectors.toList)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Enums (com.google.common.base.Enums)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Iterables (com.google.common.collect.Iterables)1 Lists (com.google.common.collect.Lists)1 Ints (com.google.common.primitives.Ints)1 GroupReference (com.google.gerrit.common.data.GroupReference)1 LabelType (com.google.gerrit.common.data.LabelType)1 SubmitRecord (com.google.gerrit.common.data.SubmitRecord)1 SubmitTypeRecord (com.google.gerrit.common.data.SubmitTypeRecord)1