use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.
the class ChangeJson method toChangeInfoImpl.
private ChangeInfo toChangeInfoImpl(ChangeData cd, Optional<PatchSet.Id> limitToPsId, List<PluginDefinedInfo> pluginInfos) throws PatchListNotAvailableException, GpgException, PermissionBackendException, IOException {
ChangeInfo out = new ChangeInfo();
CurrentUser user = userProvider.get();
if (has(CHECK)) {
out.problems = checkerProvider.get().check(cd.notes(), fix).problems();
// If any problems were fixed, the ChangeData needs to be reloaded.
for (ProblemInfo p : out.problems) {
if (p.status == ProblemInfo.Status.FIXED) {
cd = changeDataFactory.create(cd.project(), cd.getId());
break;
}
}
}
Change in = cd.change();
out.project = in.getProject().get();
out.branch = in.getDest().shortName();
out.topic = in.getTopic();
if (!cd.attentionSet().isEmpty()) {
out.removedFromAttentionSet = removalsOnly(cd.attentionSet()).stream().collect(toImmutableMap(a -> a.account().get(), a -> AttentionSetUtil.createAttentionSetInfo(a, accountLoader)));
out.attentionSet = // This filtering should match GetAttentionSet.
additionsOnly(cd.attentionSet()).stream().collect(toImmutableMap(a -> a.account().get(), a -> AttentionSetUtil.createAttentionSetInfo(a, accountLoader)));
}
out.assignee = in.getAssignee() != null ? accountLoader.get(in.getAssignee()) : null;
out.hashtags = cd.hashtags();
out.changeId = in.getKey().get();
if (in.isNew()) {
SubmitTypeRecord str = cd.submitTypeRecord();
if (str.isOk()) {
out.submitType = str.type;
}
if (includeMergeable) {
out.mergeable = cd.isMergeable();
}
if (has(SUBMITTABLE)) {
out.submittable = submittable(cd);
}
}
if (!has(SKIP_DIFFSTAT)) {
Optional<ChangedLines> changedLines = cd.changedLines();
if (changedLines.isPresent()) {
out.insertions = changedLines.get().insertions;
out.deletions = changedLines.get().deletions;
}
}
out.isPrivate = in.isPrivate() ? true : null;
out.workInProgress = in.isWorkInProgress() ? true : null;
out.hasReviewStarted = in.hasReviewStarted();
out.subject = in.getSubject();
out.status = in.getStatus().asChangeStatus();
out.owner = accountLoader.get(in.getOwner());
out.setCreated(in.getCreatedOn());
out.setUpdated(in.getLastUpdatedOn());
out._number = in.getId().get();
out.totalCommentCount = cd.totalCommentCount();
out.unresolvedCommentCount = cd.unresolvedCommentCount();
if (cd.getRefStates() != null) {
String metaName = RefNames.changeMetaRef(cd.getId());
Optional<RefState> metaState = cd.getRefStates().values().stream().filter(r -> r.ref().equals(metaName)).findAny();
// metaState should always be there, but it doesn't hurt to be extra careful.
metaState.ifPresent(rs -> out.metaRevId = rs.id().getName());
}
if (user.isIdentifiedUser()) {
Collection<String> stars = cd.stars(user.getAccountId());
out.starred = stars.contains(StarredChangesUtil.DEFAULT_LABEL) ? true : null;
if (!stars.isEmpty()) {
out.stars = stars;
}
}
if (in.isNew() && has(REVIEWED) && user.isIdentifiedUser()) {
out.reviewed = cd.isReviewedBy(user.getAccountId()) ? true : null;
}
out.labels = labelsJson.labelsFor(accountLoader, cd, has(LABELS), has(DETAILED_LABELS));
out.requirements = requirementsFor(cd);
out.submitRecords = submitRecordsFor(cd);
if (has(SUBMIT_REQUIREMENTS)) {
out.submitRequirements = submitRequirementsFor(cd);
}
if (out.labels != null && has(DETAILED_LABELS)) {
// list permitted labels, since users can't vote on those patch sets.
if (user.isIdentifiedUser() && (!limitToPsId.isPresent() || limitToPsId.get().equals(in.currentPatchSetId()))) {
out.permittedLabels = !cd.change().isAbandoned() ? labelsJson.permittedLabels(user.getAccountId(), cd) : ImmutableMap.of();
}
}
if (has(LABELS) || has(DETAILED_LABELS)) {
out.reviewers = reviewerMap(cd.reviewers(), cd.reviewersByEmail(), false);
out.pendingReviewers = reviewerMap(cd.pendingReviewers(), cd.pendingReviewersByEmail(), true);
out.removableReviewers = removableReviewers(cd, out);
}
setSubmitter(cd, out);
if (!pluginInfos.isEmpty()) {
out.plugins = pluginInfos;
}
out.revertOf = cd.change().getRevertOf() != null ? cd.change().getRevertOf().get() : null;
out.submissionId = cd.change().getSubmissionId();
out.cherryPickOfChange = cd.change().getCherryPickOf() != null ? cd.change().getCherryPickOf().changeId().get() : null;
out.cherryPickOfPatchSet = cd.change().getCherryPickOf() != null ? cd.change().getCherryPickOf().get() : null;
if (has(REVIEWER_UPDATES)) {
out.reviewerUpdates = reviewerUpdates(cd);
}
boolean needMessages = has(MESSAGES);
boolean needRevisions = has(ALL_REVISIONS) || has(CURRENT_REVISION) || limitToPsId.isPresent();
Map<PatchSet.Id, PatchSet> src;
if (needMessages || needRevisions) {
src = loadPatchSets(cd, limitToPsId);
} else {
src = null;
}
if (needMessages) {
out.messages = messages(cd);
}
finish(out);
// it will be passed to ActionVisitors as-is.
if (needRevisions) {
out.revisions = revisionJson.getRevisions(accountLoader, cd, src, limitToPsId, out);
if (out.revisions != null) {
for (Map.Entry<String, RevisionInfo> entry : out.revisions.entrySet()) {
if (entry.getValue().isCurrent) {
out.currentRevision = entry.getKey();
break;
}
}
}
}
if (has(CURRENT_ACTIONS) || has(CHANGE_ACTIONS)) {
actionJson.addChangeActions(out, cd);
}
if (has(TRACKING_IDS)) {
ListMultimap<String, String> set = trackingFooters.extract(cd.commitFooters());
out.trackingIds = set.entries().stream().map(e -> new TrackingIdInfo(e.getKey(), e.getValue())).collect(toList());
}
return out;
}
use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.
the class RebaseChangeOp method updateRepo.
@Override
public void updateRepo(RepoContext ctx) throws MergeConflictException, InvalidChangeOperationException, RestApiException, IOException, NoSuchChangeException, PermissionBackendException {
// Ok that originalPatchSet was not read in a transaction, since we just
// need its revision.
RevWalk rw = ctx.getRevWalk();
RevCommit original = rw.parseCommit(originalPatchSet.commitId());
rw.parseBody(original);
RevCommit baseCommit = rw.parseCommit(baseCommitId);
CurrentUser changeOwner = identifiedUserFactory.create(notes.getChange().getOwner());
String newCommitMessage;
if (detailedCommitMessage) {
rw.parseBody(baseCommit);
newCommitMessage = newMergeUtil().createCommitMessageOnSubmit(original, baseCommit, notes, originalPatchSet.id());
} else {
newCommitMessage = original.getFullMessage();
}
rebasedCommit = rebaseCommit(ctx, original, baseCommit, newCommitMessage);
Base base = rebaseUtil.parseBase(new RevisionResource(changeResourceFactory.create(notes, changeOwner), originalPatchSet), baseCommitId.name());
rebasedPatchSetId = ChangeUtil.nextPatchSetIdFromChangeRefs(ctx.getRepoView().getRefs(originalPatchSet.id().changeId().toRefPrefix()).keySet(), notes.getChange().currentPatchSetId());
patchSetInserter = patchSetInserterFactory.create(notes, rebasedPatchSetId, rebasedCommit).setDescription("Rebase").setFireRevisionCreated(fireRevisionCreated).setCheckAddPatchSetPermission(checkAddPatchSetPermission).setValidate(validate).setSendEmail(sendEmail).setStoreCopiedVotes(storeCopiedVotes);
if (!rebasedCommit.getFilesWithGitConflicts().isEmpty() && !notes.getChange().isWorkInProgress()) {
patchSetInserter.setWorkInProgress(true);
}
patchSetInserter.setValidationOptions(validationOptions);
if (postMessage) {
patchSetInserter.setMessage(messageForRebasedChange(rebasedPatchSetId, originalPatchSet.id(), rebasedCommit));
}
if (base != null && !base.notes().getChange().isMerged()) {
if (!base.notes().getChange().isMerged()) {
// Add to end of relation chain for open base change.
patchSetInserter.setGroups(base.patchSet().groups());
} else {
// If the base is merged, start a new relation chain.
patchSetInserter.setGroups(GroupCollector.getDefaultGroups(rebasedCommit));
}
}
ctx.getRevWalk().getObjectReader().getCreatedFromInserter().flush();
patchSetInserter.updateRepo(ctx);
}
use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.
the class ReviewersUtil method suggestReviewers.
public List<SuggestedReviewerInfo> suggestReviewers(ReviewerState reviewerState, @Nullable ChangeNotes changeNotes, SuggestReviewers suggestReviewers, ProjectState projectState, VisibilityControl visibilityControl, boolean excludeGroups) throws IOException, ConfigInvalidException, PermissionBackendException, BadRequestException {
CurrentUser currentUser = self.get();
if (changeNotes != null) {
logger.atFine().log("Suggesting reviewers for change %s to user %s.", changeNotes.getChangeId().get(), currentUser.getLoggableName());
} else {
logger.atFine().log("Suggesting default reviewers for project %s to user %s.", projectState.getName(), currentUser.getLoggableName());
}
String query = suggestReviewers.getQuery();
logger.atFine().log("Query: %s", query);
int limit = suggestReviewers.getLimit();
if (!suggestReviewers.getSuggestAccounts()) {
logger.atFine().log("Reviewer suggestion is disabled.");
return Collections.emptyList();
}
List<Account.Id> candidateList = new ArrayList<>();
if (!Strings.isNullOrEmpty(query)) {
candidateList = suggestAccounts(suggestReviewers);
logger.atFine().log("Candidate list: %s", candidateList);
}
List<Account.Id> sortedRecommendations = recommendAccounts(reviewerState, changeNotes, suggestReviewers, projectState, candidateList);
logger.atFine().log("Sorted recommendations: %s", sortedRecommendations);
// Filter accounts by visibility, skip service users and enforce limit
List<Account.Id> filteredRecommendations = new ArrayList<>();
try (Timer0.Context ctx = metrics.filterVisibility.start()) {
for (Account.Id reviewer : sortedRecommendations) {
if (filteredRecommendations.size() >= limit) {
break;
}
if (suggestReviewers.isSkipServiceUsers() && serviceUserClassifier.isServiceUser(reviewer)) {
continue;
}
// Check if change is visible to reviewer and if the current user can see reviewer
if (visibilityControl.isVisibleTo(reviewer) && accountControlFactory.get().canSee(reviewer)) {
filteredRecommendations.add(reviewer);
}
}
}
logger.atFine().log("Filtered recommendations: %s", filteredRecommendations);
List<SuggestedReviewerInfo> suggestedReviewers = suggestReviewers(suggestReviewers, projectState, visibilityControl, excludeGroups, filteredRecommendations);
logger.atFine().log("Suggested reviewers: %s", lazy(() -> formatSuggestedReviewers(suggestedReviewers)));
return suggestedReviewers;
}
use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.
the class TasksCollection method parse.
@Override
public TaskResource parse(ConfigResource parent, IdString id) throws ResourceNotFoundException, AuthException, PermissionBackendException, ResourceConflictException {
CurrentUser user = self.get();
if (!user.isIdentifiedUser()) {
throw new AuthException("Authentication required");
}
int taskId;
try {
taskId = (int) Long.parseLong(id.get(), 16);
} catch (NumberFormatException e) {
throw new ResourceNotFoundException(id, e);
}
Task<?> task = workQueue.getTask(taskId);
if (task instanceof ProjectTask) {
Project.NameKey nameKey = ((ProjectTask<?>) task).getProjectNameKey();
Optional<ProjectState> state = projectCache.get(nameKey);
if (!state.isPresent()) {
throw new ResourceNotFoundException(String.format("project %s not found", nameKey));
}
state.get().checkStatePermitsRead();
try {
permissionBackend.user(user).project(nameKey).check(ProjectPermission.ACCESS);
return new TaskResource(task);
} catch (AuthException e) {
// Fall through and try view queue permission.
}
}
if (task != null) {
try {
permissionBackend.user(user).check(GlobalPermission.VIEW_QUEUE);
return new TaskResource(task);
} catch (AuthException e) {
// Fall through and return not found.
}
}
throw new ResourceNotFoundException(id);
}
use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.
the class GroupsCollection method parse.
@Override
public GroupResource parse(TopLevelResource parent, IdString id) throws AuthException, ResourceNotFoundException {
final CurrentUser user = self.get();
if (user instanceof AnonymousUser) {
throw new AuthException("Authentication required");
} else if (!(user.isIdentifiedUser() || user.isInternalUser())) {
throw new ResourceNotFoundException(id);
}
GroupDescription.Basic group = groupResolver.parseId(id.get());
if (group == null) {
throw new ResourceNotFoundException(id.get());
}
GroupControl ctl = groupControlFactory.controlFor(group);
if (!ctl.isVisible()) {
throw new ResourceNotFoundException(id);
}
return new GroupResource(ctl);
}
Aggregations