Merge changes from topics "autovalue-audit", "autovalue-patchsetapproval", "autovalue-patchset"

* changes:
  Remove AccountGroupById and AccountGroupMember
  Flatten group audit keys into containing types
  Rename AccountGroupByIdAud to AccountGroupByIdAudit
  Rename group audit methods to remove get prefix
  Convert account audit types to AutoValue
  Group audits: Convert nullable methods to Optional
  AccountLoader: Mark methods and args as nullable
  Rename PatchSetApproval methods
  Convert PatchSetApproval to AutoValue
  ChangeNotesParser: Replace ApprovalKey with PatchSetApproval.Key
  PatchSetApproval: Convert getTag to return Optional
  PatchSetApproval: Add setValue(int) convenience method
  PatchSetApproval: Replace copy constructors with instance methods
  Rename PatchSet methods
  Convert PatchSet to AutoValue with builder
  PatchSet: Rewrite splitGroups/joinGroups
This commit is contained in:
Dave Borowitz
2019-05-09 14:12:29 +00:00
committed by Gerrit Code Review
155 changed files with 1414 additions and 1739 deletions

View File

@@ -98,18 +98,18 @@ public enum LabelFunction {
}
for (PatchSetApproval a : approvals) {
if (a.getValue() == 0) {
if (a.value() == 0) {
continue;
}
if (isBlock && labelType.isMaxNegative(a)) {
submitRecordLabel.appliedBy = a.getAccountId();
submitRecordLabel.appliedBy = a.accountId();
submitRecordLabel.status = SubmitRecord.Label.Status.REJECT;
return submitRecordLabel;
}
if (labelType.isMaxPositive(a) || !requiresMaxValue) {
submitRecordLabel.appliedBy = a.getAccountId();
submitRecordLabel.appliedBy = a.accountId();
submitRecordLabel.status = SubmitRecord.Label.Status.MAY;
if (isRequired) {

View File

@@ -155,7 +155,7 @@ public class LabelType {
}
public boolean matches(PatchSetApproval psa) {
return psa.getLabelId().get().equalsIgnoreCase(name);
return psa.labelId().get().equalsIgnoreCase(name);
}
public LabelFunction getFunction() {
@@ -279,11 +279,11 @@ public class LabelType {
}
public boolean isMaxNegative(PatchSetApproval ca) {
return maxNegative == ca.getValue();
return maxNegative == ca.value();
}
public boolean isMaxPositive(PatchSetApproval ca) {
return maxPositive == ca.getValue();
return maxPositive == ca.value();
}
public LabelValue getValue(short value) {
@@ -291,7 +291,7 @@ public class LabelType {
}
public LabelValue getValue(PatchSetApproval ca) {
return byValue.get(ca.getValue());
return byValue.get(ca.value());
}
public LabelId getLabelId() {

View File

@@ -15,6 +15,7 @@
package com.google.gerrit.extensions.common;
import java.sql.Timestamp;
import java.util.Optional;
public abstract class GroupAuditEventInfo {
public enum Type {
@@ -30,35 +31,35 @@ public abstract class GroupAuditEventInfo {
public static UserMemberAuditEventInfo createAddUserEvent(
AccountInfo user, Timestamp date, AccountInfo member) {
return new UserMemberAuditEventInfo(Type.ADD_USER, user, date, member);
return new UserMemberAuditEventInfo(Type.ADD_USER, user, Optional.of(date), member);
}
public static UserMemberAuditEventInfo createRemoveUserEvent(
AccountInfo user, Timestamp date, AccountInfo member) {
AccountInfo user, Optional<Timestamp> date, AccountInfo member) {
return new UserMemberAuditEventInfo(Type.REMOVE_USER, user, date, member);
}
public static GroupMemberAuditEventInfo createAddGroupEvent(
AccountInfo user, Timestamp date, GroupInfo member) {
return new GroupMemberAuditEventInfo(Type.ADD_GROUP, user, date, member);
return new GroupMemberAuditEventInfo(Type.ADD_GROUP, user, Optional.of(date), member);
}
public static GroupMemberAuditEventInfo createRemoveGroupEvent(
AccountInfo user, Timestamp date, GroupInfo member) {
AccountInfo user, Optional<Timestamp> date, GroupInfo member) {
return new GroupMemberAuditEventInfo(Type.REMOVE_GROUP, user, date, member);
}
protected GroupAuditEventInfo(Type type, AccountInfo user, Timestamp date) {
protected GroupAuditEventInfo(Type type, AccountInfo user, Optional<Timestamp> date) {
this.type = type;
this.user = user;
this.date = date;
this.date = date.orElse(null);
}
public static class UserMemberAuditEventInfo extends GroupAuditEventInfo {
public AccountInfo member;
public UserMemberAuditEventInfo(
Type type, AccountInfo user, Timestamp date, AccountInfo member) {
private UserMemberAuditEventInfo(
Type type, AccountInfo user, Optional<Timestamp> date, AccountInfo member) {
super(type, user, date);
this.member = member;
}
@@ -67,8 +68,8 @@ public abstract class GroupAuditEventInfo {
public static class GroupMemberAuditEventInfo extends GroupAuditEventInfo {
public GroupInfo member;
public GroupMemberAuditEventInfo(
Type type, AccountInfo user, Timestamp date, GroupInfo member) {
private GroupMemberAuditEventInfo(
Type type, AccountInfo user, Optional<Timestamp> date, GroupInfo member) {
super(type, user, date);
this.member = member;
}

View File

@@ -139,7 +139,7 @@ public class CatServlet extends HttpServlet {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
revision = patchSet.getCommitId().name();
revision = patchSet.commitId().name();
}
} catch (ResourceConflictException | NoSuchChangeException | AuthException e) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);

View File

@@ -37,8 +37,6 @@ import java.util.Optional;
* <li>ExternalId: OpenID identities and email addresses known to be registered to this user.
* Multiple records can exist when the user has more than one public identity, such as a work
* and a personal email address.
* <li>{@link AccountGroupMember}: membership of the user in a specific human managed {@link
* AccountGroup}. Multiple records can exist when the user is a member of more than one group.
* <li>AccountSshKey: user's public SSH keys, for authentication through the internal SSH daemon.
* One record per SSH key uploaded by the user, keys are checked in random order until a match
* is found.

View File

@@ -1,67 +0,0 @@
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import java.util.Objects;
/** Membership of an {@link AccountGroup} in an {@link AccountGroup}. */
public final class AccountGroupById {
public static Key key(AccountGroup.Id groupId, AccountGroup.UUID includeUuid) {
return new AutoValue_AccountGroupById_Key(groupId, includeUuid);
}
@AutoValue
public abstract static class Key {
public abstract AccountGroup.Id groupId();
public abstract AccountGroup.UUID includeUuid();
}
protected Key key;
protected AccountGroupById() {}
public AccountGroupById(AccountGroupById.Key k) {
key = k;
}
public AccountGroupById.Key getKey() {
return key;
}
public AccountGroup.Id getGroupId() {
return key.groupId();
}
public AccountGroup.UUID getIncludeUuid() {
return key.includeUuid();
}
@Override
public boolean equals(Object o) {
return (o instanceof AccountGroupById) && Objects.equals(key, ((AccountGroupById) o).key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "{key=" + key + "}";
}
}

View File

@@ -1,127 +0,0 @@
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import com.google.gerrit.common.Nullable;
import java.sql.Timestamp;
import java.util.Objects;
/** Inclusion of an {@link AccountGroup} in another {@link AccountGroup}. */
public final class AccountGroupByIdAud {
public static Key key(AccountGroup.Id groupId, AccountGroup.UUID includeUuid, Timestamp addedOn) {
return new AutoValue_AccountGroupByIdAud_Key(groupId, includeUuid, addedOn);
}
@AutoValue
public abstract static class Key {
public abstract AccountGroup.Id groupId();
public abstract AccountGroup.UUID includeUuid();
public abstract Timestamp addedOn();
}
protected Key key;
protected Account.Id addedBy;
@Nullable protected Account.Id removedBy;
@Nullable protected Timestamp removedOn;
protected AccountGroupByIdAud() {}
public AccountGroupByIdAud(final AccountGroupById m, Account.Id adder, Timestamp when) {
final AccountGroup.Id group = m.getGroupId();
final AccountGroup.UUID include = m.getIncludeUuid();
key = key(group, include, when);
addedBy = adder;
}
public AccountGroupByIdAud(AccountGroupByIdAud.Key key, Account.Id adder) {
this.key = key;
addedBy = adder;
}
public AccountGroupByIdAud.Key getKey() {
return key;
}
public AccountGroup.Id getGroupId() {
return key.groupId();
}
public AccountGroup.UUID getIncludeUUID() {
return key.includeUuid();
}
public boolean isActive() {
return removedOn == null;
}
public void removed(Account.Id deleter, Timestamp when) {
removedBy = deleter;
removedOn = when;
}
public Account.Id getAddedBy() {
return addedBy;
}
public Timestamp getAddedOn() {
return key.addedOn();
}
public Account.Id getRemovedBy() {
return removedBy;
}
public Timestamp getRemovedOn() {
return removedOn;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AccountGroupByIdAud)) {
return false;
}
AccountGroupByIdAud a = (AccountGroupByIdAud) o;
return Objects.equals(key, a.key)
&& Objects.equals(addedBy, a.addedBy)
&& Objects.equals(removedBy, a.removedBy)
&& Objects.equals(removedOn, a.removedOn);
}
@Override
public int hashCode() {
return Objects.hash(key, addedBy, removedBy, removedOn);
}
@Override
public String toString() {
return getClass().getSimpleName()
+ "{"
+ "key="
+ key
+ ", addedBy="
+ addedBy
+ ", removedBy="
+ removedBy
+ ", removedOn="
+ removedOn
+ "}";
}
}

View File

@@ -0,0 +1,66 @@
// Copyright (C) 2011 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import java.sql.Timestamp;
import java.util.Optional;
/** Inclusion of an {@link AccountGroup} in another {@link AccountGroup}. */
@AutoValue
public abstract class AccountGroupByIdAudit {
public static Builder builder() {
return new AutoValue_AccountGroupByIdAudit.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder groupId(AccountGroup.Id groupId);
public abstract Builder includeUuid(AccountGroup.UUID includeUuid);
public abstract Builder addedBy(Account.Id addedBy);
public abstract Builder addedOn(Timestamp addedOn);
abstract Builder removedBy(Account.Id removedBy);
abstract Builder removedOn(Timestamp removedOn);
public Builder removed(Account.Id removedBy, Timestamp removedOn) {
return removedBy(removedBy).removedOn(removedOn);
}
public abstract AccountGroupByIdAudit build();
}
public abstract AccountGroup.Id groupId();
public abstract AccountGroup.UUID includeUuid();
public abstract Account.Id addedBy();
public abstract Timestamp addedOn();
public abstract Optional<Account.Id> removedBy();
public abstract Optional<Timestamp> removedOn();
public abstract Builder toBuilder();
public boolean isActive() {
return !removedOn().isPresent();
}
}

View File

@@ -1,67 +0,0 @@
// Copyright (C) 2008 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import java.util.Objects;
/** Membership of an {@link Account} in an {@link AccountGroup}. */
public final class AccountGroupMember {
public static Key key(Account.Id accountId, AccountGroup.Id groupId) {
return new AutoValue_AccountGroupMember_Key(accountId, groupId);
}
@AutoValue
public abstract static class Key {
public abstract Account.Id accountId();
public abstract AccountGroup.Id groupId();
}
protected Key key;
protected AccountGroupMember() {}
public AccountGroupMember(AccountGroupMember.Key k) {
key = k;
}
public AccountGroupMember.Key getKey() {
return key;
}
public Account.Id getAccountId() {
return key.accountId();
}
public AccountGroup.Id getAccountGroupId() {
return key.groupId();
}
@Override
public boolean equals(Object o) {
return (o instanceof AccountGroupMember) && Objects.equals(key, ((AccountGroupMember) o).key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "{key=" + key + "}";
}
}

View File

@@ -15,118 +15,60 @@
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import com.google.gerrit.common.Nullable;
import java.sql.Timestamp;
import java.util.Objects;
import java.util.Optional;
/** Membership of an {@link Account} in an {@link AccountGroup}. */
public final class AccountGroupMemberAudit {
public static Key key(Account.Id accountId, AccountGroup.Id groupId, Timestamp addedOn) {
return new AutoValue_AccountGroupMemberAudit_Key(accountId, groupId, addedOn);
@AutoValue
public abstract class AccountGroupMemberAudit {
public static Builder builder() {
return new AutoValue_AccountGroupMemberAudit.Builder();
}
@AutoValue
public abstract static class Key {
public abstract Account.Id accountId();
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder groupId(AccountGroup.Id groupId);
public abstract AccountGroup.Id groupId();
public abstract Builder memberId(Account.Id accountId);
public abstract Timestamp addedOn();
public abstract Builder addedBy(Account.Id addedBy);
abstract Account.Id addedBy();
public abstract Builder addedOn(Timestamp addedOn);
abstract Timestamp addedOn();
abstract Builder removedBy(Account.Id removedBy);
abstract Builder removedOn(Timestamp removedOn);
public Builder removed(Account.Id removedBy, Timestamp removedOn) {
return removedBy(removedBy).removedOn(removedOn);
}
public Builder removedLegacy() {
return removed(addedBy(), addedOn());
}
public abstract AccountGroupMemberAudit build();
}
protected Key key;
public abstract AccountGroup.Id groupId();
protected Account.Id addedBy;
public abstract Account.Id memberId();
@Nullable protected Account.Id removedBy;
public abstract Account.Id addedBy();
@Nullable protected Timestamp removedOn;
public abstract Timestamp addedOn();
protected AccountGroupMemberAudit() {}
public abstract Optional<Account.Id> removedBy();
public AccountGroupMemberAudit(final AccountGroupMember m, Account.Id adder, Timestamp addedOn) {
final Account.Id who = m.getAccountId();
final AccountGroup.Id group = m.getAccountGroupId();
key = key(who, group, addedOn);
addedBy = adder;
}
public abstract Optional<Timestamp> removedOn();
public AccountGroupMemberAudit(AccountGroupMemberAudit.Key key, Account.Id adder) {
this.key = key;
addedBy = adder;
}
public AccountGroupMemberAudit.Key getKey() {
return key;
}
public AccountGroup.Id getGroupId() {
return key.groupId();
}
public Account.Id getMemberId() {
return key.accountId();
}
public abstract Builder toBuilder();
public boolean isActive() {
return removedOn == null;
}
public void removed(Account.Id deleter, Timestamp when) {
removedBy = deleter;
removedOn = when;
}
public void removedLegacy() {
removedBy = addedBy;
removedOn = key.addedOn();
}
public Account.Id getAddedBy() {
return addedBy;
}
public Timestamp getAddedOn() {
return key.addedOn();
}
public Account.Id getRemovedBy() {
return removedBy;
}
public Timestamp getRemovedOn() {
return removedOn;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AccountGroupMemberAudit)) {
return false;
}
AccountGroupMemberAudit a = (AccountGroupMemberAudit) o;
return Objects.equals(key, a.key)
&& Objects.equals(addedBy, a.addedBy)
&& Objects.equals(removedBy, a.removedBy)
&& Objects.equals(removedOn, a.removedOn);
}
@Override
public int hashCode() {
return Objects.hash(key, addedBy, removedBy, removedOn);
}
@Override
public String toString() {
return getClass().getSimpleName()
+ "{"
+ "key="
+ key
+ ", addedBy="
+ addedBy
+ ", removedBy="
+ removedBy
+ ", removedOn="
+ removedOn
+ "}";
return !removedOn().isPresent();
}
}

View File

@@ -15,21 +15,22 @@
package com.google.gerrit.reviewdb.client;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.util.Objects.requireNonNull;
import com.google.auto.value.AutoValue;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.Nullable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.eclipse.jgit.lib.ObjectId;
/** A single revision of a {@link Change}. */
public final class PatchSet {
@AutoValue
public abstract class PatchSet {
/** Is the reference name a change reference? */
public static boolean isChangeRef(String name) {
return Id.fromRef(name) != null;
@@ -46,38 +47,15 @@ public final class PatchSet {
}
public static String joinGroups(List<String> groups) {
if (groups == null) {
throw new IllegalArgumentException("groups may not be null");
requireNonNull(groups);
for (String group : groups) {
checkArgument(!group.contains(","), "group may not contain ',': %s", group);
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String g : groups) {
if (!first) {
sb.append(',');
} else {
first = false;
}
sb.append(g);
}
return sb.toString();
return String.join(",", groups);
}
public static List<String> splitGroups(String joinedGroups) {
if (joinedGroups == null) {
throw new IllegalArgumentException("groups may not be null");
}
List<String> groups = new ArrayList<>();
int i = 0;
while (true) {
int idx = joinedGroups.indexOf(',', i);
if (idx < 0) {
groups.add(joinedGroups.substring(i));
break;
}
groups.add(joinedGroups.substring(i, idx));
i = idx + 1;
}
return groups;
public static ImmutableList<String> splitGroups(String joinedGroups) {
return Streams.stream(Splitter.on(',').split(joinedGroups)).collect(toImmutableList());
}
public static Id id(Change.Id changeId, int id) {
@@ -101,7 +79,7 @@ public final class PatchSet {
checkArgument(test, "invalid patch set ID: %s", input);
}
/** Parse a PatchSet.Id from a {@link PatchSet#getRefName()} result. */
/** Parse a PatchSet.Id from a {@link #refName()} result. */
public static Id fromRef(String ref) {
int cs = Change.Id.startIndex(ref);
if (cs < 0) {
@@ -156,14 +134,70 @@ public final class PatchSet {
}
}
protected Id id;
public static Builder builder() {
return new AutoValue_PatchSet.Builder().groups(ImmutableList.of());
}
protected ObjectId commitId;
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder id(Id id);
protected Account.Id uploader;
public abstract Id id();
/** When this patch set was first introduced onto the change. */
protected Timestamp createdOn;
public abstract Builder commitId(ObjectId commitId);
public abstract Optional<ObjectId> commitId();
public abstract Builder uploader(Account.Id uploader);
public abstract Builder createdOn(Timestamp createdOn);
public abstract Builder groups(Iterable<String> groups);
public abstract ImmutableList<String> groups();
public abstract Builder pushCertificate(Optional<String> pushCertificate);
public abstract Builder pushCertificate(String pushCertificate);
public abstract Builder description(Optional<String> description);
public abstract Builder description(String description);
public abstract Optional<String> description();
public abstract PatchSet build();
}
/** ID of the patch set. */
public abstract Id id();
/**
* Commit ID of the patch set, also known as the revision.
*
* <p>If this is a deserialized instance that was originally serialized by an older version of
* Gerrit, and the old data erroneously did not include a {@code commitId}, then this method will
* return {@link ObjectId#zeroId()}.
*/
public abstract ObjectId commitId();
/**
* Account that uploaded the patch set.
*
* <p>If this is a deserialized instance that was originally serialized by an older version of
* Gerrit, and the old data erroneously did not include an {@code uploader}, then this method will
* return an account ID of 0.
*/
public abstract Account.Id uploader();
/**
* When this patch set was first introduced onto the change.
*
* <p>If this is a deserialized instance that was originally serialized by an older version of
* Gerrit, and the old data erroneously did not include a {@code createdOn}, then this method will
* return a timestamp of 0.
*/
public abstract Timestamp createdOn();
/**
* Opaque group identifier, usually assigned during creation.
@@ -174,127 +208,26 @@ public final class PatchSet {
* <p>Changes on the same branch having patch sets with intersecting groups are considered
* related, as in the "Related Changes" tab.
*/
@Nullable protected String groups;
// DELETED id = 7 (pushCertficate)
public abstract ImmutableList<String> groups();
/** Certificate sent with a push that created this patch set. */
@Nullable protected String pushCertificate;
public abstract Optional<String> pushCertificate();
/**
* Optional user-supplied description for this patch set.
*
* <p>When this field is null, the description was never set on the patch set. When this field is
* an empty string, the description was set and later cleared.
* <p>When this field is an empty {@code Optional}, the description was never set on the patch
* set. When this field is present but an empty string, the description was set and later cleared.
*/
@Nullable protected String description;
public abstract Optional<String> description();
public PatchSet(PatchSet.Id id, ObjectId commitId) {
this.id = requireNonNull(id);
this.commitId = commitId.copy();
/** Patch set number. */
public int number() {
return id().get();
}
public PatchSet(PatchSet src) {
this.id = src.id;
this.commitId = src.commitId;
this.uploader = src.uploader;
this.createdOn = src.createdOn;
this.groups = src.groups;
this.pushCertificate = src.pushCertificate;
this.description = src.description;
}
public PatchSet.Id getId() {
return id;
}
public int getPatchSetId() {
return id.get();
}
/**
* Get the ID of the commit associated with this patch set.
*
* <p>The commit associated with a patch set is also known as the <strong>revision</strong>.
*
* @return the commit ID, never null.
*/
public ObjectId getCommitId() {
return commitId;
}
public Account.Id getUploader() {
return uploader;
}
public void setUploader(Account.Id who) {
uploader = who;
}
public Timestamp getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Timestamp ts) {
createdOn = ts;
}
public List<String> getGroups() {
if (groups == null) {
return Collections.emptyList();
}
return splitGroups(groups);
}
public void setGroups(List<String> groups) {
if (groups == null) {
groups = Collections.emptyList();
}
this.groups = joinGroups(groups);
}
public String getRefName() {
return id.toRefName();
}
public String getPushCertificate() {
return pushCertificate;
}
public void setPushCertificate(String cert) {
pushCertificate = cert;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PatchSet)) {
return false;
}
PatchSet p = (PatchSet) o;
return Objects.equals(id, p.id)
&& Objects.equals(commitId, p.commitId)
&& Objects.equals(uploader, p.uploader)
&& Objects.equals(createdOn, p.createdOn)
&& Objects.equals(groups, p.groups)
&& Objects.equals(pushCertificate, p.pushCertificate)
&& Objects.equals(description, p.description);
}
@Override
public int hashCode() {
return Objects.hash(id, commitId, uploader, createdOn, groups, pushCertificate, description);
}
@Override
public String toString() {
return "[PatchSet " + getId().toString() + "]";
/** Name of the corresponding patch set ref. */
public String refName() {
return id().toRefName();
}
}

View File

@@ -15,13 +15,14 @@
package com.google.gerrit.reviewdb.client;
import com.google.auto.value.AutoValue;
import com.google.gerrit.common.Nullable;
import com.google.common.primitives.Shorts;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
/** An approval (or negative approval) on a patch set. */
public final class PatchSetApproval {
@AutoValue
public abstract class PatchSetApproval {
public static Key key(PatchSet.Id patchSetId, Account.Id accountId, LabelId labelId) {
return new AutoValue_PatchSetApproval_Key(patchSetId, accountId, labelId);
}
@@ -33,9 +34,55 @@ public final class PatchSetApproval {
public abstract Account.Id accountId();
public abstract LabelId labelId();
public boolean isLegacySubmit() {
return LabelId.LEGACY_SUBMIT_NAME.equals(labelId().get());
}
}
protected Key key;
public static Builder builder() {
return new AutoValue_PatchSetApproval.Builder().postSubmit(false);
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Builder key(Key key);
public abstract Key key();
public abstract Builder value(short value);
public Builder value(int value) {
return value(Shorts.checkedCast(value));
}
public abstract Builder granted(Timestamp granted);
public Builder granted(Date granted) {
return granted(new Timestamp(granted.getTime()));
}
public abstract Builder tag(String tag);
public abstract Builder tag(Optional<String> tag);
public abstract Builder realAccountId(Account.Id realAccountId);
abstract Optional<Account.Id> realAccountId();
public abstract Builder postSubmit(boolean isPostSubmit);
abstract PatchSetApproval autoBuild();
public PatchSetApproval build() {
if (!realAccountId().isPresent()) {
realAccountId(key().accountId());
}
return autoBuild();
}
}
public abstract Key key();
/**
* Value assigned by the user.
@@ -53,143 +100,40 @@ public final class PatchSetApproval {
* and in the negative and positive direction a magnitude can be assumed.The further from 0 the
* more assertive the approval.
*/
protected short value;
public abstract short value();
protected Timestamp granted;
public abstract Timestamp granted();
@Nullable protected String tag;
public abstract Optional<String> tag();
/** Real user that made this approval on behalf of the user recorded in {@link Key#accountId}. */
@Nullable protected Account.Id realAccountId;
public abstract Account.Id realAccountId();
protected boolean postSubmit;
public abstract boolean postSubmit();
// DELETED: id = 4 (changeOpen)
// DELETED: id = 5 (changeSortKey)
public abstract Builder toBuilder();
protected PatchSetApproval() {}
public PatchSetApproval(PatchSetApproval.Key k, short v, Date ts) {
key = k;
setValue(v);
setGranted(ts);
public PatchSetApproval copyWithPatchSet(PatchSet.Id psId) {
return toBuilder().key(key(psId, key().accountId(), key().labelId())).build();
}
public PatchSetApproval(PatchSet.Id psId, PatchSetApproval src) {
key = key(psId, src.getAccountId(), src.getLabelId());
value = src.getValue();
granted = src.granted;
realAccountId = src.realAccountId;
tag = src.tag;
postSubmit = src.postSubmit;
public PatchSet.Id patchSetId() {
return key().patchSetId();
}
public PatchSetApproval(PatchSetApproval src) {
this(src.getPatchSetId(), src);
public Account.Id accountId() {
return key().accountId();
}
public PatchSetApproval.Key getKey() {
return key;
public LabelId labelId() {
return key().labelId();
}
public PatchSet.Id getPatchSetId() {
return key.patchSetId();
}
public Account.Id getAccountId() {
return key.accountId();
}
public Account.Id getRealAccountId() {
return realAccountId != null ? realAccountId : getAccountId();
}
public void setRealAccountId(Account.Id id) {
// Use null for same real author, as before the column was added.
realAccountId = Objects.equals(getAccountId(), id) ? null : id;
}
public LabelId getLabelId() {
return key.labelId();
}
public short getValue() {
return value;
}
public void setValue(short v) {
value = v;
}
public Timestamp getGranted() {
return granted;
}
public void setGranted(Date when) {
if (when instanceof Timestamp) {
granted = (Timestamp) when;
} else {
granted = new Timestamp(when.getTime());
}
}
public void setTag(String t) {
tag = t;
}
public String getLabel() {
return getLabelId().get();
public String label() {
return labelId().get();
}
public boolean isLegacySubmit() {
return LabelId.LEGACY_SUBMIT_NAME.equals(getLabel());
}
public String getTag() {
return tag;
}
public void setPostSubmit(boolean postSubmit) {
this.postSubmit = postSubmit;
}
public boolean isPostSubmit() {
return postSubmit;
}
@Override
public String toString() {
StringBuilder sb =
new StringBuilder("[")
.append(key)
.append(": ")
.append(value)
.append(",tag:")
.append(tag)
.append(",realAccountId:")
.append(realAccountId);
if (postSubmit) {
sb.append(",postSubmit");
}
return sb.append(']').toString();
}
@Override
public boolean equals(Object o) {
if (o instanceof PatchSetApproval) {
PatchSetApproval p = (PatchSetApproval) o;
return Objects.equals(key, p.key)
&& Objects.equals(value, p.value)
&& Objects.equals(granted, p.granted)
&& Objects.equals(tag, p.tag)
&& Objects.equals(realAccountId, p.realAccountId)
&& postSubmit == p.postSubmit;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(key, value, granted, tag, realAccountId, postSubmit);
return key().isLegacySubmit();
}
}

View File

@@ -34,21 +34,18 @@ public enum PatchSetApprovalProtoConverter
public Entities.PatchSetApproval toProto(PatchSetApproval patchSetApproval) {
Entities.PatchSetApproval.Builder builder =
Entities.PatchSetApproval.newBuilder()
.setKey(patchSetApprovalKeyProtoConverter.toProto(patchSetApproval.getKey()))
.setValue(patchSetApproval.getValue())
.setGranted(patchSetApproval.getGranted().getTime())
.setPostSubmit(patchSetApproval.isPostSubmit());
.setKey(patchSetApprovalKeyProtoConverter.toProto(patchSetApproval.key()))
.setValue(patchSetApproval.value())
.setGranted(patchSetApproval.granted().getTime())
.setPostSubmit(patchSetApproval.postSubmit());
String tag = patchSetApproval.getTag();
if (tag != null) {
builder.setTag(tag);
}
Account.Id realAccountId = patchSetApproval.getRealAccountId();
patchSetApproval.tag().ifPresent(builder::setTag);
Account.Id realAccountId = patchSetApproval.realAccountId();
// PatchSetApproval#getRealAccountId automatically delegates to PatchSetApproval#getAccountId if
// the real author is not set. However, the previous protobuf representation kept
// 'realAccountId' empty if it wasn't set. To ensure binary compatibility, simulate the previous
// behavior.
if (realAccountId != null && !Objects.equals(realAccountId, patchSetApproval.getAccountId())) {
if (realAccountId != null && !Objects.equals(realAccountId, patchSetApproval.accountId())) {
builder.setRealAccountId(accountIdConverter.toProto(realAccountId));
}
@@ -57,21 +54,19 @@ public enum PatchSetApprovalProtoConverter
@Override
public PatchSetApproval fromProto(Entities.PatchSetApproval proto) {
PatchSetApproval patchSetApproval =
new PatchSetApproval(
patchSetApprovalKeyProtoConverter.fromProto(proto.getKey()),
(short) proto.getValue(),
new Timestamp(proto.getGranted()));
PatchSetApproval.Builder builder =
PatchSetApproval.builder()
.key(patchSetApprovalKeyProtoConverter.fromProto(proto.getKey()))
.value(proto.getValue())
.granted(new Timestamp(proto.getGranted()))
.postSubmit(proto.getPostSubmit());
if (proto.hasTag()) {
patchSetApproval.setTag(proto.getTag());
builder.tag(proto.getTag());
}
if (proto.hasRealAccountId()) {
patchSetApproval.setRealAccountId(accountIdConverter.fromProto(proto.getRealAccountId()));
builder.realAccountId(accountIdConverter.fromProto(proto.getRealAccountId()));
}
if (proto.hasPostSubmit()) {
patchSetApproval.setPostSubmit(proto.getPostSubmit());
}
return patchSetApproval;
return builder.build();
}
@Override

View File

@@ -14,8 +14,7 @@
package com.google.gerrit.reviewdb.converter;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.proto.Entities;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.PatchSet;
@@ -37,54 +36,55 @@ public enum PatchSetProtoConverter implements ProtoConverter<Entities.PatchSet,
@Override
public Entities.PatchSet toProto(PatchSet patchSet) {
Entities.PatchSet.Builder builder =
Entities.PatchSet.newBuilder().setId(patchSetIdConverter.toProto(patchSet.getId()));
builder.setCommitId(objectIdConverter.toProto(patchSet.getCommitId()));
Account.Id uploader = patchSet.getUploader();
if (uploader != null) {
builder.setUploaderAccountId(accountIdConverter.toProto(uploader));
}
Timestamp createdOn = patchSet.getCreatedOn();
if (createdOn != null) {
builder.setCreatedOn(createdOn.getTime());
}
List<String> groups = patchSet.getGroups();
Entities.PatchSet.newBuilder()
.setId(patchSetIdConverter.toProto(patchSet.id()))
.setCommitId(objectIdConverter.toProto(patchSet.commitId()))
.setUploaderAccountId(accountIdConverter.toProto(patchSet.uploader()))
.setCreatedOn(patchSet.createdOn().getTime());
List<String> groups = patchSet.groups();
if (!groups.isEmpty()) {
builder.setGroups(PatchSet.joinGroups(groups));
}
String pushCertificate = patchSet.getPushCertificate();
if (pushCertificate != null) {
builder.setPushCertificate(pushCertificate);
}
String description = patchSet.getDescription();
if (description != null) {
builder.setDescription(description);
}
patchSet.pushCertificate().ifPresent(builder::setPushCertificate);
patchSet.description().ifPresent(builder::setDescription);
return builder.build();
}
@Override
public PatchSet fromProto(Entities.PatchSet proto) {
checkArgument(proto.hasCommitId(), "missing commit_id: %s", proto);
PatchSet patchSet =
new PatchSet(
patchSetIdConverter.fromProto(proto.getId()),
objectIdConverter.fromProto(proto.getCommitId()));
if (proto.hasUploaderAccountId()) {
patchSet.setUploader(accountIdConverter.fromProto(proto.getUploaderAccountId()));
}
if (proto.hasCreatedOn()) {
patchSet.setCreatedOn(new Timestamp(proto.getCreatedOn()));
}
if (proto.hasGroups()) {
patchSet.setGroups(PatchSet.splitGroups(proto.getGroups()));
}
PatchSet.Builder builder =
PatchSet.builder()
.id(patchSetIdConverter.fromProto(proto.getId()))
.groups(
proto.hasGroups() ? PatchSet.splitGroups(proto.getGroups()) : ImmutableList.of());
if (proto.hasPushCertificate()) {
patchSet.setPushCertificate(proto.getPushCertificate());
builder.pushCertificate(proto.getPushCertificate());
}
if (proto.hasDescription()) {
patchSet.setDescription(proto.getDescription());
builder.description(proto.getDescription());
}
return patchSet;
// The following fields used to theoretically be nullable in PatchSet, but in practice no
// production codepath should have ever serialized an instance that was missing one of these
// fields.
//
// However, since some protos may theoretically be missing these fields, we need to support
// them. Populate specific sentinel values for each field as documented in the PatchSet javadoc.
// Callers that encounter one of these sentinels will likely fail, for example by failing to
// look up the zeroId. They would have also failed back when the fields were nullable, for
// example with NPE; the current behavior just fails slightly differently.
builder
.commitId(
proto.hasCommitId()
? objectIdConverter.fromProto(proto.getCommitId())
: ObjectId.zeroId())
.uploader(
proto.hasUploaderAccountId()
? accountIdConverter.fromProto(proto.getUploaderAccountId())
: Account.id(0))
.createdOn(proto.hasCreatedOn() ? new Timestamp(proto.getCreatedOn()) : new Timestamp(0));
return builder.build();
}
@Override

View File

@@ -104,13 +104,13 @@ public class ApprovalCopier {
Table<String, Account.Id, PatchSetApproval> wontCopy = HashBasedTable.create();
for (PatchSetApproval psa : dontCopy) {
wontCopy.put(psa.getLabel(), psa.getAccountId(), psa);
wontCopy.put(psa.label(), psa.accountId(), psa);
}
Table<String, Account.Id, PatchSetApproval> byUser = HashBasedTable.create();
for (PatchSetApproval psa : all.get(ps.getId())) {
if (!wontCopy.contains(psa.getLabel(), psa.getAccountId())) {
byUser.put(psa.getLabel(), psa.getAccountId(), psa);
for (PatchSetApproval psa : all.get(ps.id())) {
if (!wontCopy.contains(psa.label(), psa.accountId())) {
byUser.put(psa.label(), psa.accountId(), psa);
}
}
@@ -118,29 +118,29 @@ public class ApprovalCopier {
// Walk patch sets strictly less than current in descending order.
Collection<PatchSet> allPrior =
patchSets.descendingMap().tailMap(ps.getId().get(), false).values();
patchSets.descendingMap().tailMap(ps.id().get(), false).values();
for (PatchSet priorPs : allPrior) {
List<PatchSetApproval> priorApprovals = all.get(priorPs.getId());
List<PatchSetApproval> priorApprovals = all.get(priorPs.id());
if (priorApprovals.isEmpty()) {
continue;
}
ChangeKind kind =
changeKindCache.getChangeKind(
project.getNameKey(), rw, repoConfig, priorPs.getCommitId(), ps.getCommitId());
project.getNameKey(), rw, repoConfig, priorPs.commitId(), ps.commitId());
for (PatchSetApproval psa : priorApprovals) {
if (wontCopy.contains(psa.getLabel(), psa.getAccountId())) {
if (wontCopy.contains(psa.label(), psa.accountId())) {
continue;
}
if (byUser.contains(psa.getLabel(), psa.getAccountId())) {
if (byUser.contains(psa.label(), psa.accountId())) {
continue;
}
if (!canCopy(project, psa, ps.getId(), kind)) {
wontCopy.put(psa.getLabel(), psa.getAccountId(), psa);
if (!canCopy(project, psa, ps.id(), kind)) {
wontCopy.put(psa.label(), psa.accountId(), psa);
continue;
}
byUser.put(psa.getLabel(), psa.getAccountId(), copy(psa, ps.getId()));
byUser.put(psa.label(), psa.accountId(), psa.copyWithPatchSet(ps.id()));
}
}
return labelNormalizer.normalize(notes, byUser.values()).getNormalized();
@@ -153,16 +153,16 @@ public class ApprovalCopier {
Collection<PatchSet> patchSets = cd.patchSets();
TreeMap<Integer, PatchSet> result = new TreeMap<>();
for (PatchSet ps : patchSets) {
result.put(ps.getId().get(), ps);
result.put(ps.id().get(), ps);
}
return result;
}
private static boolean canCopy(
ProjectState project, PatchSetApproval psa, PatchSet.Id psId, ChangeKind kind) {
int n = psa.getKey().patchSetId().get();
int n = psa.key().patchSetId().get();
checkArgument(n != psId.get());
LabelType type = project.getLabelTypes().byLabel(psa.getLabelId());
LabelType type = project.getLabelTypes().byLabel(psa.labelId());
if (type == null) {
return false;
} else if ((type.isCopyMinScore() && type.isMaxNegative(psa))
@@ -186,11 +186,4 @@ public class ApprovalCopier {
return false;
}
}
private static PatchSetApproval copy(PatchSetApproval src, PatchSet.Id psId) {
if (src.getKey().patchSetId().equals(psId)) {
return src;
}
return new PatchSetApproval(psId, src);
}
}

View File

@@ -25,7 +25,6 @@ import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.primitives.Shorts;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelTypes;
@@ -76,20 +75,20 @@ import org.eclipse.jgit.revwalk.RevWalk;
public class ApprovalsUtil {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
public static PatchSetApproval newApproval(
public static PatchSetApproval.Builder newApproval(
PatchSet.Id psId, CurrentUser user, LabelId labelId, int value, Date when) {
PatchSetApproval psa =
new PatchSetApproval(
PatchSetApproval.key(psId, user.getAccountId(), labelId),
Shorts.checkedCast(value),
when);
user.updateRealAccountId(psa::setRealAccountId);
return psa;
PatchSetApproval.Builder b =
PatchSetApproval.builder()
.key(PatchSetApproval.key(psId, user.getAccountId(), labelId))
.value(value)
.granted(when);
user.updateRealAccountId(b::realAccountId);
return b;
}
private static Iterable<PatchSetApproval> filterApprovals(
Iterable<PatchSetApproval> psas, Account.Id accountId) {
return Iterables.filter(psas, a -> Objects.equals(a.getAccountId(), accountId));
return Iterables.filter(psas, a -> Objects.equals(a.accountId(), accountId));
}
private final ApprovalCopier copier;
@@ -147,7 +146,7 @@ public class ApprovalsUtil {
update,
labelTypes,
change,
ps.getId(),
ps.id(),
info.getAuthor().getAccount(),
info.getCommitter().getAccount(),
wantReviewers,
@@ -207,8 +206,11 @@ public class ApprovalsUtil {
LabelId labelId = Iterables.getLast(allTypes).getLabelId();
for (Account.Id account : need) {
cells.add(
new PatchSetApproval(
PatchSetApproval.key(psId, account, labelId), (short) 0, update.getWhen()));
PatchSetApproval.builder()
.key(PatchSetApproval.key(psId, account, labelId))
.value(0)
.granted(update.getWhen())
.build());
update.putReviewer(account, REVIEWER);
}
return Collections.unmodifiableList(cells);
@@ -274,10 +276,10 @@ public class ApprovalsUtil {
throws RestApiException, PermissionBackendException {
Account.Id accountId = user.getAccountId();
checkArgument(
accountId.equals(ps.getUploader()),
accountId.equals(ps.uploader()),
"expected user %s to match patch set uploader %s",
accountId,
ps.getUploader());
ps.uploader());
if (approvals.isEmpty()) {
return ImmutableList.of();
}
@@ -286,10 +288,10 @@ public class ApprovalsUtil {
Date ts = update.getWhen();
for (Map.Entry<String, Short> vote : approvals.entrySet()) {
LabelType lt = labelTypes.byLabel(vote.getKey());
cells.add(newApproval(ps.getId(), user, lt.getLabelId(), vote.getValue(), ts));
cells.add(newApproval(ps.id(), user, lt.getLabelId(), vote.getValue(), ts).build());
}
for (PatchSetApproval psa : cells) {
update.putApproval(psa.getLabel(), psa.getValue());
update.putApproval(psa.label(), psa.value());
}
return cells;
}
@@ -357,8 +359,8 @@ public class ApprovalsUtil {
}
PatchSetApproval submitter = null;
for (PatchSetApproval a : approvals) {
if (a.getPatchSetId().equals(c) && a.getValue() > 0 && a.isLegacySubmit()) {
if (submitter == null || a.getGranted().compareTo(submitter.getGranted()) > 0) {
if (a.patchSetId().equals(c) && a.value() > 0 && a.isLegacySubmit()) {
if (submitter == null || a.granted().compareTo(submitter.granted()) > 0) {
submitter = a;
}
}
@@ -372,7 +374,7 @@ public class ApprovalsUtil {
if (!n.isEmpty()) {
boolean first = true;
for (Map.Entry<String, Short> e : n.entrySet()) {
if (c.containsKey(e.getKey()) && c.get(e.getKey()).getValue() == e.getValue()) {
if (c.containsKey(e.getKey()) && c.get(e.getKey()).value() == e.getValue()) {
continue;
}
if (first) {

View File

@@ -40,7 +40,7 @@ public class ChangeUtil {
private static final BaseEncoding UUID_ENCODING = BaseEncoding.base16().lowerCase();
public static final Ordering<PatchSet> PS_ID_ORDER =
Ordering.from(comparingInt(PatchSet::getPatchSetId));
Ordering.from(comparingInt(PatchSet::number));
/** @return a new unique identifier for change message entities. */
public static String messageUuid() {

View File

@@ -308,9 +308,9 @@ public class CommentsUtil {
public static void setCommentCommitId(Comment c, PatchListCache cache, Change change, PatchSet ps)
throws PatchListNotAvailableException {
checkArgument(
c.key.patchSetId == ps.getId().get(),
c.key.patchSetId == ps.id().get(),
"cannot set commit ID for patch set %s on comment %s",
ps.getId(),
ps.id(),
c);
if (c.getCommitId() == null) {
if (Side.fromShort(c.side) == Side.PARENT) {
@@ -320,7 +320,7 @@ public class CommentsUtil {
c.setCommitId(cache.getOldId(change, ps, null));
}
} else {
c.setCommitId(ps.getCommitId());
c.setCommitId(ps.commitId());
}
}
}

View File

@@ -20,6 +20,7 @@ import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.data.LabelFunction;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
@@ -38,6 +39,7 @@ import com.google.inject.Singleton;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
@@ -88,8 +90,8 @@ public class PatchSetUtil {
PatchSet.Id psId,
ObjectId commit,
List<String> groups,
String pushCertificate,
String description)
@Nullable String pushCertificate,
@Nullable String description)
throws IOException {
requireNonNull(groups, "groups may not be null");
ensurePatchSetMatches(psId, update);
@@ -98,13 +100,15 @@ public class PatchSetUtil {
update.setPsDescription(description);
update.setGroups(groups);
PatchSet ps = new PatchSet(psId, commit);
ps.setUploader(update.getAccountId());
ps.setCreatedOn(new Timestamp(update.getWhen().getTime()));
ps.setGroups(groups);
ps.setPushCertificate(pushCertificate);
ps.setDescription(description);
return ps;
return PatchSet.builder()
.id(psId)
.commitId(commit)
.uploader(update.getAccountId())
.createdOn(new Timestamp(update.getWhen().getTime()))
.groups(groups)
.pushCertificate(Optional.ofNullable(pushCertificate))
.description(Optional.ofNullable(description))
.build();
}
private static void ensurePatchSetMatches(PatchSet.Id psId, ChangeUpdate update) {
@@ -125,11 +129,6 @@ public class PatchSetUtil {
}
}
public void setGroups(ChangeUpdate update, PatchSet ps, List<String> groups) {
ps.setGroups(groups);
update.setGroups(groups);
}
/** Check if the current patch set of the change is locked. */
public void checkPatchSetNotLocked(ChangeNotes notes)
throws IOException, ResourceConflictException {
@@ -153,10 +152,8 @@ public class PatchSetUtil {
ApprovalsUtil approvalsUtil = approvalsUtilProvider.get();
for (PatchSetApproval ap :
approvalsUtil.byPatchSet(notes, change.currentPatchSetId(), null, null)) {
LabelType type = projectState.getLabelTypes(notes).byLabel(ap.getLabel());
if (type != null
&& ap.getValue() == 1
&& type.getFunction() == LabelFunction.PATCH_SET_LOCK) {
LabelType type = projectState.getLabelTypes(notes).byLabel(ap.label());
if (type != null && ap.value() == 1 && type.getFunction() == LabelFunction.PATCH_SET_LOCK) {
return true;
}
}
@@ -167,7 +164,7 @@ public class PatchSetUtil {
public RevCommit getRevCommit(Project.NameKey project, PatchSet patchSet) throws IOException {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
RevCommit src = rw.parseCommit(patchSet.getCommitId());
RevCommit src = rw.parseCommit(patchSet.commitId());
rw.parseBody(src);
return src;
}

View File

@@ -44,14 +44,14 @@ public class ReviewerSet {
first = psa;
} else {
checkArgument(
first.getKey().patchSetId().changeId().equals(psa.getKey().patchSetId().changeId()),
first.key().patchSetId().changeId().equals(psa.key().patchSetId().changeId()),
"multiple change IDs: %s, %s",
first.getKey(),
psa.getKey());
first.key(),
psa.key());
}
Account.Id id = psa.getAccountId();
reviewers.put(REVIEWER, id, psa.getGranted());
if (psa.getValue() != 0) {
Account.Id id = psa.accountId();
reviewers.put(REVIEWER, id, psa.granted());
if (psa.value() != 0) {
reviewers.remove(CC, id);
}
}

View File

@@ -17,6 +17,7 @@ package com.google.gerrit.server.account;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.Iterables;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.account.AccountDirectory.FillOptions;
@@ -67,7 +68,8 @@ public class AccountLoader {
provided = new ArrayList<>();
}
public synchronized AccountInfo get(Account.Id id) {
@Nullable
public synchronized AccountInfo get(@Nullable Account.Id id) {
if (id == null) {
return null;
}
@@ -95,7 +97,8 @@ public class AccountLoader {
fill();
}
public AccountInfo fillOne(Account.Id id) throws PermissionBackendException {
@Nullable
public AccountInfo fillOne(@Nullable Account.Id id) throws PermissionBackendException {
AccountInfo info = get(id);
fill();
return info;

View File

@@ -476,7 +476,7 @@ class RevisionApiImpl implements RevisionApi {
// Reread change to pick up new notes refs.
return changes
.id(revision.getChange().getId().get())
.revision(revision.getPatchSet().getId().get())
.revision(revision.getPatchSet().id().get())
.draft(id);
} catch (Exception e) {
throw asRestApiException("Cannot create draft", e);
@@ -587,20 +587,20 @@ class RevisionApiImpl implements RevisionApi {
ListMultimapBuilder.treeKeys().arrayListValues().build();
try {
Iterable<PatchSetApproval> approvals =
approvalsUtil.byPatchSet(revision.getNotes(), revision.getPatchSet().getId(), null, null);
approvalsUtil.byPatchSet(revision.getNotes(), revision.getPatchSet().id(), null, null);
AccountLoader accountLoader =
accountLoaderFactory.create(
EnumSet.of(
FillOptions.ID, FillOptions.NAME, FillOptions.EMAIL, FillOptions.USERNAME));
for (PatchSetApproval approval : approvals) {
String label = approval.getLabel();
String label = approval.label();
ApprovalInfo info =
new ApprovalInfo(
approval.getAccountId().get(),
Integer.valueOf(approval.getValue()),
approval.accountId().get(),
Integer.valueOf(approval.value()),
null,
approval.getTag(),
approval.getGranted());
approval.tag().orElse(null),
approval.granted());
accountLoader.put(info);
result.get(label).add(info);
}

View File

@@ -240,7 +240,7 @@ public class AddReviewersOp implements BatchUpdateOp {
addReviewersEmail.emailReviewers(
ctx.getUser().asIdentifiedUser(),
change,
Lists.transform(addedReviewers, PatchSetApproval::getAccountId),
Lists.transform(addedReviewers, PatchSetApproval::accountId),
addedCCs,
addedReviewersByEmail,
addedCCsByEmail,
@@ -249,7 +249,7 @@ public class AddReviewersOp implements BatchUpdateOp {
if (!addedReviewers.isEmpty()) {
List<AccountState> reviewers =
addedReviewers.stream()
.map(r -> accountCache.get(r.getAccountId()))
.map(r -> accountCache.get(r.accountId()))
.flatMap(Streams::stream)
.collect(toList());
reviewerAdded.fire(change, patchSet, reviewers, ctx.getAccount(), ctx.getWhen());

View File

@@ -426,9 +426,9 @@ public class ChangeInserter implements InsertChangeOp {
if (message != null) {
changeMessage =
ChangeMessagesUtil.newMessage(
patchSet.getId(),
patchSet.id(),
ctx.getUser(),
patchSet.getCreatedOn(),
patchSet.createdOn(),
message,
ChangeMessagesUtil.uploadedPatchSetTag(workInProgress));
cmUtil.addChangeMessage(update, changeMessage);
@@ -453,7 +453,7 @@ public class ChangeInserter implements InsertChangeOp {
cm.setNotify(notify);
cm.addReviewers(
reviewerAdditions.flattenResults(AddReviewersOp.Result::addedReviewers).stream()
.map(PatchSetApproval::getAccountId)
.map(PatchSetApproval::accountId)
.collect(toImmutableSet()));
cm.addReviewersByEmail(
reviewerAdditions.flattenResults(AddReviewersOp.Result::addedReviewersByEmail));

View File

@@ -286,7 +286,7 @@ public class ChangeJson {
public ChangeInfo format(RevisionResource rsrc) {
ChangeData cd = changeDataFactory.create(rsrc.getNotes());
return format(cd, Optional.of(rsrc.getPatchSet().getId()), true, ChangeInfo::new);
return format(cd, Optional.of(rsrc.getPatchSet().id()), true, ChangeInfo::new);
}
public List<List<ChangeInfo>> format(List<QueryResult<ChangeData>> in)
@@ -656,8 +656,8 @@ public class ChangeJson {
if (!s.isPresent()) {
return;
}
out.submitted = s.get().getGranted();
out.submitter = accountLoader.get(s.get().getAccountId());
out.submitted = s.get().granted();
out.submitter = accountLoader.get(s.get().accountId());
}
private Collection<ChangeMessageInfo> messages(ChangeData cd) {
@@ -784,7 +784,7 @@ public class ChangeJson {
}
Map<PatchSet.Id, PatchSet> map = Maps.newHashMapWithExpectedSize(src.size());
for (PatchSet patchSet : src) {
map.put(patchSet.getId(), patchSet);
map.put(patchSet.id(), patchSet);
}
return map;
}

View File

@@ -367,13 +367,13 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to use
// the repository.
if (patch.getId().get() > 1) {
if (patch.id().get() > 1) {
try {
Collection<PatchSet> patchSetCollection = change.patchSets();
PatchSet priorPs = patch;
for (PatchSet ps : patchSetCollection) {
if (ps.getId().get() < patch.getId().get()
&& (ps.getId().get() > priorPs.getId().get() || priorPs == patch)) {
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;
}
@@ -386,13 +386,13 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
if (priorPs != patch) {
kind =
cache.getChangeKind(
change.project(), rw, repoConfig, priorPs.getCommitId(), patch.getCommitId());
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.getPatchSetId(), change.getId());
patch.number(), change.getId());
}
}
return kind;
@@ -408,7 +408,7 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
ChangeKind kind = ChangeKind.REWORK;
// Trivial case: if we're on the first patch, we don't need to open
// the repository.
if (patch.getId().get() > 1) {
if (patch.id().get() > 1) {
try (Repository repo = repoManager.openRepository(change.getProject());
RevWalk rw = new RevWalk(repo)) {
kind =
@@ -418,7 +418,7 @@ public class ChangeKindCacheImpl implements ChangeKindCache {
// 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.getPatchSetId(), change.getChangeId());
patch.number(), change.getChangeId());
}
}
return kind;

View File

@@ -149,7 +149,7 @@ public class ChangeResource implements RestResource, HasETag {
accounts.add(getChange().getAssignee());
}
try {
patchSetUtil.byChange(notes).stream().map(PatchSet::getUploader).forEach(accounts::add);
patchSetUtil.byChange(notes).stream().map(PatchSet::uploader).forEach(accounts::add);
// It's intentional to include the states for *all* reviewers into the ETag computation.
// We need the states of all current reviewers and CCs because they are part of ChangeInfo.

View File

@@ -265,7 +265,7 @@ public class ConsistencyChecker {
try {
refs =
repo.getRefDatabase()
.exactRef(all.stream().map(ps -> ps.getId().toRefName()).toArray(String[]::new));
.exactRef(all.stream().map(ps -> ps.id().toRefName()).toArray(String[]::new));
} catch (IOException e) {
error("error reading refs", e);
refs = Collections.emptyMap();
@@ -274,9 +274,9 @@ public class ConsistencyChecker {
List<DeletePatchSetFromDbOp> deletePatchSetOps = new ArrayList<>();
for (PatchSet ps : all) {
// Check revision format.
int psNum = ps.getId().get();
String refName = ps.getId().toRefName();
ObjectId objId = ps.getCommitId();
int psNum = ps.id().get();
String refName = ps.id().toRefName();
ObjectId objId = ps.commitId();
patchSetsBySha.put(objId, ps);
// Check ref existence.
@@ -296,13 +296,13 @@ public class ConsistencyChecker {
RevCommit psCommit = parseCommit(objId, String.format("patch set %d", psNum));
if (psCommit == null) {
if (fix != null && fix.deletePatchSetIfCommitMissing) {
deletePatchSetOps.add(new DeletePatchSetFromDbOp(lastProblem(), ps.getId()));
deletePatchSetOps.add(new DeletePatchSetFromDbOp(lastProblem(), ps.id()));
}
continue;
} else if (refProblem != null && fix != null) {
fixPatchSetRef(refProblem, ps);
}
if (ps.getId().equals(change().currentPatchSetId())) {
if (ps.id().equals(change().currentPatchSetId())) {
currPsCommit = psCommit;
}
}
@@ -316,7 +316,7 @@ public class ConsistencyChecker {
problem(
String.format(
"Multiple patch sets pointing to %s: %s",
e.getKey().name(), Collections2.transform(e.getValue(), PatchSet::getPatchSetId)));
e.getKey().name(), Collections2.transform(e.getValue(), PatchSet::number)));
}
}
@@ -348,10 +348,10 @@ public class ConsistencyChecker {
try {
merged = rw.isMergedInto(currPsCommit, tip);
} catch (IOException e) {
problem("Error checking whether patch set " + currPs.getId().get() + " is merged");
problem("Error checking whether patch set " + currPs.id().get() + " is merged");
return;
}
checkMergedBitMatchesStatus(currPs.getId(), currPsCommit, merged);
checkMergedBitMatchesStatus(currPs.id(), currPsCommit, merged);
}
}
@@ -376,7 +376,7 @@ public class ConsistencyChecker {
formatProblemMessage(
"Patch set %d (%s) is not merged into"
+ " destination ref %s (%s), but change status is %s",
currPs.getId().get(), commit.name(), refName, tip.name()));
currPs.id().get(), commit.name(), refName, tip.name()));
}
}
@@ -601,9 +601,9 @@ public class ConsistencyChecker {
private void fixPatchSetRef(ProblemInfo p, PatchSet ps) {
try {
RefUpdate ru = repo.updateRef(ps.getId().toRefName());
RefUpdate ru = repo.updateRef(ps.id().toRefName());
ru.setForceUpdate(true);
ru.setNewObjectId(ps.getCommitId());
ru.setNewObjectId(ps.commitId());
ru.setRefLogIdent(newRefLogIdent());
ru.setRefLogMessage("Repair patch set ref", true);
RefUpdate.Result result = ru.update();
@@ -630,7 +630,7 @@ public class ConsistencyChecker {
}
} catch (IOException e) {
String msg = "Error fixing patch set ref";
logger.atWarning().withCause(e).log("%s %s", msg, ps.getId().toRefName());
logger.atWarning().withCause(e).log("%s %s", msg, ps.id().toRefName());
p.status = Status.FIX_FAILED;
p.outcome = msg;
}
@@ -714,8 +714,8 @@ public class ConsistencyChecker {
// and whether they are seen by this op; we are already given the full set
// of patch sets that will eventually be deleted in this update.
for (PatchSet ps : psUtil.byChange(ctx.getNotes())) {
if (!toDelete.contains(ps.getId())) {
all.add(ps.getId());
if (!toDelete.contains(ps.id())) {
all.add(ps.id());
}
}
if (all.isEmpty()) {

View File

@@ -86,8 +86,7 @@ public class DeleteChangeOp implements BatchUpdateOp {
if (isPatchSetMerged(ctx, patchSet)) {
throw new ResourceConflictException(
String.format(
"Cannot delete change %s: patch set %s is already merged",
id, patchSet.getPatchSetId()));
"Cannot delete change %s: patch set %s is already merged", id, patchSet.number()));
}
}
}
@@ -100,12 +99,12 @@ public class DeleteChangeOp implements BatchUpdateOp {
RevWalk revWalk = ctx.getRevWalk();
return revWalk.isMergedInto(
revWalk.parseCommit(patchSet.getCommitId()), revWalk.parseCommit(destId.get()));
revWalk.parseCommit(patchSet.commitId()), revWalk.parseCommit(destId.get()));
}
private void cleanUpReferences(Change.Id id, Collection<PatchSet> patchSets) throws IOException {
for (PatchSet ps : patchSets) {
accountPatchReviewStore.run(s -> s.clearReviewed(ps.getId()));
accountPatchReviewStore.run(s -> s.clearReviewed(ps.id()));
}
// Non-atomic operation on All-Users refs; not much we can do to make it atomic.

View File

@@ -134,14 +134,14 @@ public class DeleteReviewerOp implements BatchUpdateOp {
// Check if removing this vote is OK
removeReviewerControl.checkRemoveReviewer(ctx.getNotes(), ctx.getUser(), a);
del.add(a);
if (a.getPatchSetId().equals(currPs.getId()) && a.getValue() != 0) {
oldApprovals.put(a.getLabel(), a.getValue());
if (a.patchSetId().equals(currPs.id()) && a.value() != 0) {
oldApprovals.put(a.label(), a.value());
removedVotesMsg
.append("* ")
.append(a.getLabel())
.append(formatLabelValue(a.getValue()))
.append(a.label())
.append(formatLabelValue(a.value()))
.append(" by ")
.append(userFactory.create(a.getAccountId()).getNameEmail())
.append(userFactory.create(a.accountId()).getNameEmail())
.append("\n");
votesRemoved = true;
}
@@ -152,7 +152,7 @@ public class DeleteReviewerOp implements BatchUpdateOp {
} else {
msg.append(".");
}
ChangeUpdate update = ctx.getUpdate(currPs.getId());
ChangeUpdate update = ctx.getUpdate(currPs.id());
update.removeReviewer(reviewerId);
changeMessage =
@@ -195,7 +195,7 @@ public class DeleteReviewerOp implements BatchUpdateOp {
private Iterable<PatchSetApproval> approvals(ChangeContext ctx, Account.Id accountId) {
Iterable<PatchSetApproval> approvals;
approvals = approvalsUtil.byChange(ctx.getNotes()).values();
return Iterables.filter(approvals, psa -> accountId.equals(psa.getAccountId()));
return Iterables.filter(approvals, psa -> accountId.equals(psa.accountId()));
}
private String formatLabelValue(short value) {

View File

@@ -129,7 +129,7 @@ public class EmailReviewComments implements Runnable, RequestContext {
cm.setNotify(notify);
cm.send();
} catch (Exception e) {
logger.atSevere().withCause(e).log("Cannot email comments for %s", patchSet.getId());
logger.atSevere().withCause(e).log("Cannot email comments for %s", patchSet.id());
} finally {
requestContext.setContext(old);
}

View File

@@ -43,13 +43,13 @@ public class FileInfoJson {
public Map<String, FileInfo> toFileInfoMap(Change change, PatchSet patchSet)
throws PatchListNotAvailableException {
return toFileInfoMap(change, patchSet.getCommitId(), null);
return toFileInfoMap(change, patchSet.commitId(), null);
}
public Map<String, FileInfo> toFileInfoMap(
Change change, ObjectId objectId, @Nullable PatchSet base)
throws PatchListNotAvailableException {
ObjectId a = base != null ? base.getCommitId() : null;
ObjectId a = base != null ? base.commitId() : null;
return toFileInfoMap(change, PatchListKey.againstCommit(a, objectId, Whitespace.IGNORE_NONE));
}

View File

@@ -29,7 +29,7 @@ public class FileResource implements RestResource {
public FileResource(RevisionResource rev, String name) {
this.rev = rev;
this.key = Patch.key(rev.getPatchSet().getId(), name);
this.key = Patch.key(rev.getPatchSet().id(), name);
}
public Patch.Key getPatchKey() {

View File

@@ -88,24 +88,23 @@ public class LabelNormalizer {
List<PatchSetApproval> deleted = Lists.newArrayListWithCapacity(approvals.size());
LabelTypes labelTypes = projectCache.checkedGet(notes.getProjectName()).getLabelTypes(notes);
for (PatchSetApproval psa : approvals) {
Change.Id changeId = psa.getKey().patchSetId().changeId();
Change.Id changeId = psa.key().patchSetId().changeId();
checkArgument(
changeId.equals(notes.getChangeId()),
"Approval %s does not match change %s",
psa.getKey(),
psa.key(),
notes.getChange().getKey());
if (psa.isLegacySubmit()) {
unchanged.add(psa);
continue;
}
LabelType label = labelTypes.byLabel(psa.getLabelId());
LabelType label = labelTypes.byLabel(psa.labelId());
if (label == null) {
deleted.add(psa);
continue;
}
PatchSetApproval copy = copy(psa);
applyTypeFloor(label, copy);
if (copy.getValue() != psa.getValue()) {
PatchSetApproval copy = applyTypeFloor(label, psa);
if (copy.value() != psa.value()) {
updated.add(copy);
} else {
unchanged.add(psa);
@@ -114,18 +113,16 @@ public class LabelNormalizer {
return Result.create(unchanged, updated, deleted);
}
private PatchSetApproval copy(PatchSetApproval src) {
return new PatchSetApproval(src.getPatchSetId(), src);
}
private void applyTypeFloor(LabelType lt, PatchSetApproval a) {
private PatchSetApproval applyTypeFloor(LabelType lt, PatchSetApproval a) {
PatchSetApproval.Builder b = a.toBuilder();
LabelValue atMin = lt.getMin();
if (atMin != null && a.getValue() < atMin.getValue()) {
a.setValue(atMin.getValue());
if (atMin != null && a.value() < atMin.getValue()) {
b.value(atMin.getValue());
}
LabelValue atMax = lt.getMax();
if (atMax != null && a.getValue() > atMax.getValue()) {
a.setValue(atMax.getValue());
if (atMax != null && a.value() > atMax.getValue()) {
b.value(atMax.getValue());
}
return b.build();
}
}

View File

@@ -206,8 +206,8 @@ public class LabelsJson {
if (standard) {
for (PatchSetApproval psa : cd.currentApprovals()) {
if (type.matches(psa)) {
short val = psa.getValue();
Account.Id accountId = psa.getAccountId();
short val = psa.value();
Account.Id accountId = psa.accountId();
setLabelScores(accountLoader, type, e.getValue(), val, accountId);
}
}
@@ -260,7 +260,7 @@ public class LabelsJson {
accountId,
null,
null)) {
result.put(psa.getLabel(), psa.getValue());
result.put(psa.label(), psa.value());
}
return result;
}
@@ -279,7 +279,7 @@ public class LabelsJson {
// we aren't including 0 votes for all users below, so we can just look at
// the latest patch set (in the next loop).
for (PatchSetApproval psa : cd.approvals().values()) {
allUsers.add(psa.getAccountId());
allUsers.add(psa.accountId());
}
}
@@ -287,13 +287,13 @@ public class LabelsJson {
SetMultimap<Account.Id, PatchSetApproval> current =
MultimapBuilder.hashKeys().hashSetValues().build();
for (PatchSetApproval a : cd.currentApprovals()) {
allUsers.add(a.getAccountId());
LabelType type = labelTypes.byLabel(a.getLabelId());
allUsers.add(a.accountId());
LabelType type = labelTypes.byLabel(a.labelId());
if (type != null) {
labelNames.add(type.getName());
// Not worth the effort to distinguish between votable/non-votable for 0
// values on closed changes, since they can't vote anyway.
current.put(a.getAccountId(), a);
current.put(a.accountId(), a);
}
}
@@ -335,19 +335,19 @@ public class LabelsJson {
}
}
for (PatchSetApproval psa : current.get(accountId)) {
LabelType type = labelTypes.byLabel(psa.getLabelId());
LabelType type = labelTypes.byLabel(psa.labelId());
if (type == null) {
continue;
}
short val = psa.getValue();
short val = psa.value();
ApprovalInfo info = byLabel.get(type.getName());
if (info != null) {
info.value = Integer.valueOf(val);
info.permittedVotingRange = pvr.getOrDefault(type.getName(), null);
info.date = psa.getGranted();
info.tag = psa.getTag();
if (psa.isPostSubmit()) {
info.date = psa.granted();
info.tag = psa.tag().orElse(null);
if (psa.postSubmit()) {
info.postSubmit = true;
}
}
@@ -441,13 +441,13 @@ public class LabelsJson {
Set<Account.Id> allUsers = new HashSet<>();
allUsers.addAll(cd.reviewers().byState(ReviewerStateInternal.REVIEWER));
for (PatchSetApproval psa : cd.approvals().values()) {
allUsers.add(psa.getAccountId());
allUsers.add(psa.accountId());
}
Table<Account.Id, String, PatchSetApproval> current =
HashBasedTable.create(allUsers.size(), cd.getLabelTypes().getLabelTypes().size());
for (PatchSetApproval psa : cd.currentApprovals()) {
current.put(psa.getAccountId(), psa.getLabel(), psa);
current.put(psa.accountId(), psa.label(), psa);
}
LabelTypes labelTypes = cd.getLabelTypes();
@@ -467,16 +467,16 @@ public class LabelsJson {
Timestamp date = null;
PatchSetApproval psa = current.get(accountId, lt.getName());
if (psa != null) {
value = Integer.valueOf(psa.getValue());
value = Integer.valueOf(psa.value());
if (value == 0) {
// This may be a dummy approval that was inserted when the reviewer
// was added. Explicitly check whether the user can vote on this
// label.
value = perm.test(new LabelPermission(lt)) ? 0 : null;
}
tag = psa.getTag();
date = psa.getGranted();
if (psa.isPostSubmit()) {
tag = psa.tag().orElse(null);
date = psa.granted();
if (psa.postSubmit()) {
logger.atWarning().log("unexpected post-submit approval on open change: %s", psa);
}
} else {

View File

@@ -208,7 +208,7 @@ public class PatchSetInserter implements BatchUpdateOp {
if (newGroups.isEmpty()) {
PatchSet prevPs = psUtil.current(ctx.getNotes());
if (prevPs != null) {
newGroups = prevPs.getGroups();
newGroups = prevPs.groups();
}
}
patchSet =
@@ -222,7 +222,7 @@ public class PatchSetInserter implements BatchUpdateOp {
if (message != null) {
changeMessage =
ChangeMessagesUtil.newMessage(
patchSet.getId(),
patchSet.id(),
ctx.getUser(),
ctx.getWhen(),
message,

View File

@@ -54,6 +54,6 @@ public class PureRevert {
}
return pureRevertCache.isPureRevert(
notes.getProjectName(), notes.getCurrentPatchSet().getCommitId(), claimedOriginalObjectId);
notes.getProjectName(), notes.getCurrentPatchSet().commitId(), claimedOriginalObjectId);
}
}

View File

@@ -151,7 +151,7 @@ public class RebaseChangeOp implements BatchUpdateOp {
// Ok that originalPatchSet was not read in a transaction, since we just
// need its revision.
RevWalk rw = ctx.getRevWalk();
RevCommit original = rw.parseCommit(originalPatchSet.getCommitId());
RevCommit original = rw.parseCommit(originalPatchSet.commitId());
rw.parseBody(original);
RevCommit baseCommit = rw.parseCommit(baseCommitId);
CurrentUser changeOwner = identifiedUserFactory.create(notes.getChange().getOwner());
@@ -161,7 +161,7 @@ public class RebaseChangeOp implements BatchUpdateOp {
rw.parseBody(baseCommit);
newCommitMessage =
newMergeUtil()
.createCommitMessageOnSubmit(original, baseCommit, notes, originalPatchSet.getId());
.createCommitMessageOnSubmit(original, baseCommit, notes, originalPatchSet.id());
} else {
newCommitMessage = original.getFullMessage();
}
@@ -175,7 +175,7 @@ public class RebaseChangeOp implements BatchUpdateOp {
rebasedPatchSetId =
ChangeUtil.nextPatchSetIdFromChangeRefs(
ctx.getRepoView().getRefs(originalPatchSet.getId().changeId().toRefPrefix()).keySet(),
ctx.getRepoView().getRefs(originalPatchSet.id().changeId().toRefPrefix()).keySet(),
notes.getChange().currentPatchSetId());
patchSetInserter =
patchSetInserterFactory
@@ -190,14 +190,14 @@ public class RebaseChangeOp implements BatchUpdateOp {
"Patch Set "
+ rebasedPatchSetId.get()
+ ": Patch Set "
+ originalPatchSet.getId().get()
+ originalPatchSet.id().get()
+ " was rebased");
}
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().getGroups());
patchSetInserter.setGroups(base.patchSet().groups());
} else {
// If the base is merged, start a new relation chain.
patchSetInserter.setGroups(GroupCollector.getDefaultGroups(rebasedCommit));

View File

@@ -64,7 +64,7 @@ public class RebaseUtil {
return false;
} catch (StorageException | IOException e) {
logger.atWarning().withCause(e).log(
"Error checking if patch set %s on %s can be rebased", patchSet.getId(), dest);
"Error checking if patch set %s on %s can be rebased", patchSet.id(), dest);
return false;
}
}
@@ -108,10 +108,10 @@ public class RebaseUtil {
Base ret = null;
for (ChangeData cd : queryProvider.get().byProjectCommit(rsrc.getProject(), base)) {
for (PatchSet ps : cd.patchSets()) {
if (!ObjectIds.matchesAbbreviation(ps.getCommitId(), base)) {
if (!ObjectIds.matchesAbbreviation(ps.commitId(), base)) {
continue;
}
if (ret == null || ret.patchSet().getId().get() < ps.getId().get()) {
if (ret == null || ret.patchSet().id().get() < ps.id().get()) {
ret = Base.create(cd.notes(), ps);
}
}
@@ -144,7 +144,7 @@ public class RebaseUtil {
PatchSet patchSet, BranchNameKey destBranch, Repository git, RevWalk rw)
throws RestApiException, IOException {
ObjectId baseId = null;
RevCommit commit = rw.parseCommit(patchSet.getCommitId());
RevCommit commit = rw.parseCommit(patchSet.commitId());
if (commit.getParentCount() > 1) {
throw new UnprocessableEntityException("Cannot rebase a change with multiple parents.");
@@ -158,7 +158,7 @@ public class RebaseUtil {
CHANGES:
for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentId.name())) {
for (PatchSet depPatchSet : cd.patchSets()) {
if (!depPatchSet.getCommitId().equals(parentId)) {
if (!depPatchSet.commitId().equals(parentId)) {
continue;
}
Change depChange = cd.change();
@@ -168,11 +168,11 @@ public class RebaseUtil {
}
if (depChange.isNew()) {
if (depPatchSet.getId().equals(depChange.currentPatchSetId())) {
if (depPatchSet.id().equals(depChange.currentPatchSetId())) {
throw new ResourceConflictException(
"Change is already based on the latest patch set of the dependent change.");
}
baseId = cd.currentPatchSet().getCommitId();
baseId = cd.currentPatchSet().commitId();
}
break CHANGES;
}

View File

@@ -469,8 +469,8 @@ public class ReviewerAdder {
// New reviewers have value 0, don't bother normalizing.
result.reviewers.add(
json.format(
new ReviewerInfo(psa.getAccountId().get()),
psa.getAccountId(),
new ReviewerInfo(psa.accountId().get()),
psa.accountId(),
cd,
ImmutableList.of(psa)));
}

View File

@@ -111,9 +111,9 @@ public class ReviewerJson {
out.approvals = new TreeMap<>(labelTypes.nameComparator());
for (PatchSetApproval ca : approvals) {
LabelType at = labelTypes.byLabel(ca.getLabelId());
LabelType at = labelTypes.byLabel(ca.labelId());
if (at != null) {
out.approvals.put(at.getName(), formatValue(ca.getValue()));
out.approvals.put(at.getName(), formatValue(ca.value()));
}
}

View File

@@ -216,7 +216,7 @@ public class RevisionJson {
try (Repository repo = openRepoIfNecessary(cd.project());
RevWalk rw = newRevWalk(repo)) {
for (PatchSet in : map.values()) {
PatchSet.Id id = in.getId();
PatchSet.Id id = in.id();
boolean want;
if (has(ALL_REVISIONS)) {
want = true;
@@ -227,7 +227,7 @@ public class RevisionJson {
}
if (want) {
res.put(
in.getCommitId().name(),
in.commitId().name(),
toRevisionInfo(accountLoader, cd, in, repo, rw, false, changeInfo));
}
}
@@ -251,7 +251,7 @@ public class RevisionJson {
String projectName = cd.project().get();
String url = scheme.getUrl(projectName);
String refName = in.getRefName();
String refName = in.refName();
FetchInfo fetchInfo = new FetchInfo(url, refName);
r.put(schemeName, fetchInfo);
@@ -275,14 +275,14 @@ public class RevisionJson {
throws PatchListNotAvailableException, GpgException, IOException, PermissionBackendException {
Change c = cd.change();
RevisionInfo out = new RevisionInfo();
out.isCurrent = in.getId().equals(c.currentPatchSetId());
out._number = in.getId().get();
out.ref = in.getRefName();
out.created = in.getCreatedOn();
out.uploader = accountLoader.get(in.getUploader());
out.isCurrent = in.id().equals(c.currentPatchSetId());
out._number = in.id().get();
out.ref = in.refName();
out.created = in.createdOn();
out.uploader = accountLoader.get(in.uploader());
out.fetch = makeFetchMap(cd, in);
out.kind = changeKindCache.getChangeKind(rw, repo != null ? repo.getConfig() : null, cd, in);
out.description = in.getDescription();
out.description = in.description().orElse(null);
boolean setCommit = has(ALL_COMMITS) || (out.isCurrent && has(CURRENT_COMMIT));
boolean addFooters = out.isCurrent && has(COMMIT_FOOTERS);
@@ -290,7 +290,7 @@ public class RevisionJson {
checkState(rw != null);
checkState(repo != null);
Project.NameKey project = c.getProject();
String rev = in.getCommitId().name();
String rev = in.commitId().name();
RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
rw.parseBody(commit);
if (setCommit) {
@@ -306,7 +306,7 @@ public class RevisionJson {
out.commitWithFooters =
mergeUtilFactory
.create(projectCache.get(project))
.createCommitMessageOnSubmit(commit, mergeTip, cd.notes(), in.getId());
.createCommitMessageOnSubmit(commit, mergeTip, cd.notes(), in.id());
}
}
@@ -324,10 +324,10 @@ public class RevisionJson {
}
if (gpgApi.isEnabled() && has(PUSH_CERTIFICATES)) {
if (in.getPushCertificate() != null) {
if (in.pushCertificate().isPresent()) {
out.pushCertificate =
gpgApi.checkPushCertificate(
in.getPushCertificate(), userFactory.create(in.getUploader()));
in.pushCertificate().get(), userFactory.create(in.uploader()));
} else {
out.pushCertificate = new PushCertificateInfo();
}

View File

@@ -114,7 +114,7 @@ public class RevisionResource implements RestResource, HasETag {
@Override
public String toString() {
String s = ps.getId().toString();
String s = ps.id().toString();
if (edit.isPresent()) {
s = "edit:" + s;
}
@@ -122,6 +122,6 @@ public class RevisionResource implements RestResource, HasETag {
}
public boolean isCurrent() {
return ps.getId().equals(getChange().currentPatchSetId());
return ps.id().equals(getChange().currentPatchSetId());
}
}

View File

@@ -222,7 +222,7 @@ public class WalkSorter {
for (ChangeData cd : in) {
PatchSet maxPs = null;
for (PatchSet ps : cd.patchSets()) {
if (shouldInclude(ps) && (maxPs == null || ps.getId().get() > maxPs.getId().get())) {
if (shouldInclude(ps) && (maxPs == null || ps.id().get() > maxPs.id().get())) {
maxPs = ps;
}
}
@@ -230,18 +230,18 @@ public class WalkSorter {
continue; // No patch sets matched.
}
try {
RevCommit c = rw.parseCommit(maxPs.getCommitId());
RevCommit c = rw.parseCommit(maxPs.commitId());
byCommit.put(c, PatchSetData.create(cd, maxPs, c));
} catch (MissingObjectException | IncorrectObjectTypeException e) {
logger.atWarning().withCause(e).log(
"missing commit %s for patch set %s", maxPs.getCommitId().name(), maxPs.getId());
"missing commit %s for patch set %s", maxPs.commitId().name(), maxPs.id());
}
}
return byCommit;
}
private boolean shouldInclude(PatchSet ps) {
return includePatchSets.isEmpty() || includePatchSets.contains(ps.getId());
return includePatchSets.isEmpty() || includePatchSets.contains(ps.id());
}
private static void markStart(RevWalk rw, Iterable<RevCommit> commits) throws IOException {

View File

@@ -51,8 +51,8 @@ public class ChangeEditJson {
public EditInfo toEditInfo(ChangeEdit edit, boolean downloadCommands) {
EditInfo out = new EditInfo();
out.commit = fillCommit(edit.getEditCommit());
out.baseRevision = edit.getBasePatchSet().getCommitId().name();
out.basePatchSetNumber = edit.getBasePatchSet().getPatchSetId();
out.baseRevision = edit.getBasePatchSet().commitId().name();
out.basePatchSetNumber = edit.getBasePatchSet().number();
out.ref = edit.getRefName();
if (downloadCommands) {
out.fetch = fillFetchMap(edit);

View File

@@ -124,7 +124,7 @@ public class ChangeEditModifier {
}
PatchSet currentPatchSet = lookupCurrentPatchSet(notes);
ObjectId patchSetCommitId = currentPatchSet.getCommitId();
ObjectId patchSetCommitId = currentPatchSet.commitId();
createEdit(repository, notes, currentPatchSet, patchSetCommitId, TimeUtil.nowTs());
}
@@ -157,7 +157,7 @@ public class ChangeEditModifier {
throw new InvalidChangeOperationException(
String.format(
"Change edit for change %s is already based on latest patch set %s",
notes.getChangeId(), currentPatchSet.getId()));
notes.getChangeId(), currentPatchSet.id()));
}
rebase(repository, changeEdit, currentPatchSet);
@@ -421,10 +421,10 @@ public class ChangeEditModifier {
String.format(
"Only the patch set %s on which the existing change edit is based may be modified "
+ "(specified patch set: %s)",
changeEdit.getBasePatchSet().getId(), patchSet.getId()));
changeEdit.getBasePatchSet().id(), patchSet.id()));
}
} else {
PatchSet.Id patchSetId = patchSet.getId();
PatchSet.Id patchSetId = patchSet.id();
PatchSet.Id currentPatchSetId = notes.getChange().currentPatchSetId();
if (!patchSetId.equals(currentPatchSetId)) {
throw new InvalidChangeOperationException(
@@ -451,12 +451,12 @@ public class ChangeEditModifier {
private static boolean isBasedOn(ChangeEdit changeEdit, PatchSet patchSet) {
PatchSet editBasePatchSet = changeEdit.getBasePatchSet();
return editBasePatchSet.getId().equals(patchSet.getId());
return editBasePatchSet.id().equals(patchSet.id());
}
private static RevCommit lookupCommit(Repository repository, PatchSet patchSet)
throws IOException {
ObjectId patchSetCommitId = patchSet.getCommitId();
ObjectId patchSetCommitId = patchSet.commitId();
return lookupCommit(repository, patchSetCommitId);
}
@@ -483,7 +483,7 @@ public class ChangeEditModifier {
private static ObjectId merge(Repository repository, ChangeEdit changeEdit, ObjectId newTreeId)
throws IOException, MergeConflictException {
PatchSet basePatchSet = changeEdit.getBasePatchSet();
ObjectId basePatchSetCommitId = basePatchSet.getCommitId();
ObjectId basePatchSetCommitId = basePatchSet.commitId();
ObjectId editCommitId = changeEdit.getEditCommit();
ThreeWayMerger threeWayMerger = MergeStrategy.RESOLVE.newMerger(repository, true);
@@ -540,7 +540,7 @@ public class ChangeEditModifier {
private String getEditRefName(Change change, PatchSet basePatchSet) {
IdentifiedUser me = currentUser.get().asIdentifiedUser();
return RefNames.refsEdit(me.getAccountId(), change.getId(), basePatchSet.getId());
return RefNames.refsEdit(me.getAccountId(), change.getId(), basePatchSet.id());
}
private ChangeEdit updateEdit(

View File

@@ -162,7 +162,7 @@ public class ChangeEditUtil {
ObjectReader reader = oi.newReader();
RevWalk rw = new RevWalk(reader)) {
PatchSet basePatchSet = edit.getBasePatchSet();
if (!basePatchSet.getId().equals(change.currentPatchSetId())) {
if (!basePatchSet.id().equals(change.currentPatchSetId())) {
throw new ResourceConflictException("only edit for current patch set can be published");
}
@@ -174,17 +174,14 @@ public class ChangeEditUtil {
new StringBuilder("Patch Set ").append(inserter.getPatchSetId().get()).append(": ");
// Previously checked that the base patch set is the current patch set.
ObjectId prior = basePatchSet.getCommitId();
ObjectId prior = basePatchSet.commitId();
ChangeKind kind =
changeKindCache.getChangeKind(change.getProject(), rw, repo.getConfig(), prior, squashed);
if (kind == ChangeKind.NO_CODE_CHANGE) {
message.append("Commit message was updated.");
inserter.setDescription("Edit commit message");
} else {
message
.append("Published edit on patch set ")
.append(basePatchSet.getPatchSetId())
.append(".");
message.append("Published edit on patch set ").append(basePatchSet.number()).append(".");
}
try (BatchUpdate bu = updateFactory.create(change.getProject(), user, TimeUtil.nowTs())) {
@@ -232,7 +229,7 @@ public class ChangeEditUtil {
private RevCommit squashEdit(
RevWalk rw, ObjectInserter inserter, RevCommit edit, PatchSet basePatchSet)
throws IOException, ResourceConflictException {
RevCommit parent = rw.parseCommit(basePatchSet.getCommitId());
RevCommit parent = rw.parseCommit(basePatchSet.commitId());
if (parent.getTree().equals(edit.getTree())
&& edit.getFullMessage().equals(parent.getFullMessage())) {
throw new ResourceConflictException("identical tree and message");

View File

@@ -285,7 +285,7 @@ public class EventFactory {
private void addDependsOn(RevWalk rw, ChangeAttribute ca, Change change, PatchSet currentPs)
throws IOException {
RevCommit commit = rw.parseCommit(currentPs.getCommitId());
RevCommit commit = rw.parseCommit(currentPs.commitId());
final List<String> parentNames = new ArrayList<>(commit.getParentCount());
for (RevCommit p : commit.getParents()) {
parentNames.add(p.name());
@@ -296,7 +296,7 @@ public class EventFactory {
for (ChangeData cd : queryProvider.get().byProjectCommits(change.getProject(), parentNames)) {
for (PatchSet ps : cd.patchSets()) {
for (String p : parentNames) {
if (!ps.getCommitId().name().equals(p)) {
if (!ps.commitId().name().equals(p)) {
continue;
}
ca.dependsOn.add(newDependsOn(requireNonNull(cd.change()), ps));
@@ -318,18 +318,18 @@ public class EventFactory {
private void addNeededBy(RevWalk rw, ChangeAttribute ca, Change change, PatchSet currentPs)
throws IOException {
if (currentPs.getGroups().isEmpty()) {
if (currentPs.groups().isEmpty()) {
return;
}
String rev = currentPs.getCommitId().name();
String rev = currentPs.commitId().name();
// Find changes in the same related group as this patch set, having a patch
// set whose parent matches this patch set's revision.
for (ChangeData cd :
InternalChangeQuery.byProjectGroups(
queryProvider, indexConfig, change.getProject(), currentPs.getGroups())) {
queryProvider, indexConfig, change.getProject(), currentPs.groups())) {
PATCH_SETS:
for (PatchSet ps : cd.patchSets()) {
RevCommit commit = rw.parseCommit(ps.getCommitId());
RevCommit commit = rw.parseCommit(ps.commitId());
for (RevCommit p : commit.getParents()) {
if (!p.name().equals(rev)) {
continue;
@@ -343,7 +343,7 @@ public class EventFactory {
private DependencyAttribute newDependsOn(Change c, PatchSet ps) {
DependencyAttribute d = newDependencyAttribute(c, ps);
d.isCurrentPatchSet = ps.getId().equals(c.currentPatchSetId());
d.isCurrentPatchSet = ps.id().equals(c.currentPatchSetId());
return d;
}
@@ -355,8 +355,8 @@ public class EventFactory {
DependencyAttribute d = new DependencyAttribute();
d.number = c.getId().get();
d.id = c.getKey().toString();
d.revision = ps.getCommitId().name();
d.ref = ps.getRefName();
d.revision = ps.commitId().name();
d.ref = ps.refName();
return d;
}
@@ -400,7 +400,7 @@ public class EventFactory {
for (PatchSet p : ps) {
PatchSetAttribute psa = asPatchSetAttribute(revWalk, change, p);
if (approvals != null) {
addApprovals(psa, p.getId(), approvals, labelTypes);
addApprovals(psa, p.id(), approvals, labelTypes);
}
ca.patchSets.add(psa);
if (includeFiles) {
@@ -463,12 +463,12 @@ public class EventFactory {
*/
public PatchSetAttribute asPatchSetAttribute(RevWalk revWalk, Change change, PatchSet patchSet) {
PatchSetAttribute p = new PatchSetAttribute();
p.revision = patchSet.getCommitId().name();
p.number = patchSet.getPatchSetId();
p.ref = patchSet.getRefName();
p.uploader = asAccountAttribute(patchSet.getUploader());
p.createdOn = patchSet.getCreatedOn().getTime() / 1000L;
PatchSet.Id pId = patchSet.getId();
p.revision = patchSet.commitId().name();
p.number = patchSet.number();
p.ref = patchSet.refName();
p.uploader = asAccountAttribute(patchSet.uploader());
p.createdOn = patchSet.createdOn().getTime() / 1000L;
PatchSet.Id pId = patchSet.id();
try {
p.parents = new ArrayList<>();
RevCommit c = revWalk.parseCommit(ObjectId.fromString(p.revision));
@@ -495,7 +495,7 @@ public class EventFactory {
}
p.kind = changeKindCache.getChangeKind(change, patchSet);
} catch (IOException | StorageException e) {
logger.atSevere().withCause(e).log("Cannot load patch set data for %s", patchSet.getId());
logger.atSevere().withCause(e).log("Cannot load patch set data for %s", patchSet.id());
} catch (PatchListObjectTooLargeException e) {
logger.atWarning().log("Cannot get size information for %s: %s", pId, e.getMessage());
} catch (PatchListNotAvailableException e) {
@@ -540,7 +540,7 @@ public class EventFactory {
if (!list.isEmpty()) {
p.approvals = new ArrayList<>(list.size());
for (PatchSetApproval a : list) {
if (a.getValue() != 0) {
if (a.value() != 0) {
p.approvals.add(asApprovalAttribute(a, labelTypes));
}
}
@@ -599,13 +599,13 @@ public class EventFactory {
*/
public ApprovalAttribute asApprovalAttribute(PatchSetApproval approval, LabelTypes labelTypes) {
ApprovalAttribute a = new ApprovalAttribute();
a.type = approval.getLabelId().get();
a.value = Short.toString(approval.getValue());
a.by = asAccountAttribute(approval.getAccountId());
a.grantedOn = approval.getGranted().getTime() / 1000L;
a.type = approval.labelId().get();
a.value = Short.toString(approval.value());
a.by = asAccountAttribute(approval.accountId());
a.grantedOn = approval.granted().getTime() / 1000L;
a.oldValue = null;
LabelType lt = labelTypes.byLabel(approval.getLabelId());
LabelType lt = labelTypes.byLabel(approval.labelId());
if (lt != null) {
a.description = lt.getName();
}

View File

@@ -84,7 +84,7 @@ public class EventUtil {
public RevisionInfo revisionInfo(Project.NameKey project, PatchSet ps)
throws PatchListNotAvailableException, GpgException, IOException, PermissionBackendException {
ChangeData cd = changeDataFactory.create(project, ps.getId().changeId());
ChangeData cd = changeDataFactory.create(project, ps.id().changeId());
return revisionJsonFactory.create(CHANGE_OPTIONS).getRevisionInfo(cd, ps);
}

View File

@@ -82,9 +82,9 @@ public class GroupCollector {
if (rsrc.getEdit().isPresent()) {
// Groups for an edit are just the base revision's groups, since they have
// the same parent.
return rsrc.getEdit().get().getBasePatchSet().getGroups();
return rsrc.getEdit().get().getBasePatchSet().groups();
}
return rsrc.getPatchSet().getGroups();
return rsrc.getPatchSet().groups();
}
private interface Lookup {
@@ -109,7 +109,7 @@ public class GroupCollector {
// TODO(dborowitz): Reuse open repository from caller.
ChangeNotes notes = notesFactory.createChecked(project, psId.changeId());
PatchSet ps = psUtil.get(notes, psId);
return ps != null ? ps.getGroups() : null;
return ps != null ? ps.groups() : null;
});
}

View File

@@ -522,7 +522,7 @@ public class MergeUtil {
PatchSetApproval submitAudit = null;
for (PatchSetApproval a : safeGetApprovals(notes, psId)) {
if (a.getValue() <= 0) {
if (a.value() <= 0) {
// Negative votes aren't counted.
continue;
}
@@ -530,13 +530,13 @@ public class MergeUtil {
if (a.isLegacySubmit()) {
// Submit is treated specially, below (becomes committer)
//
if (submitAudit == null || a.getGranted().compareTo(submitAudit.getGranted()) > 0) {
if (submitAudit == null || a.granted().compareTo(submitAudit.granted()) > 0) {
submitAudit = a;
}
continue;
}
final Account acc = identifiedUserFactory.create(a.getAccountId()).getAccount();
final Account acc = identifiedUserFactory.create(a.accountId()).getAccount();
final StringBuilder identbuf = new StringBuilder();
if (acc.getFullName() != null && acc.getFullName().length() > 0) {
if (identbuf.length() > 0) {
@@ -561,12 +561,12 @@ public class MergeUtil {
}
final String tag;
if (isCodeReview(a.getLabelId())) {
if (isCodeReview(a.labelId())) {
tag = "Reviewed-by";
} else if (isVerified(a.getLabelId())) {
} else if (isVerified(a.labelId())) {
tag = "Tested-by";
} else {
final LabelType lt = project.getLabelTypes().byLabel(a.getLabelId());
final LabelType lt = project.getLabelTypes().byLabel(a.labelId());
if (lt == null) {
continue;
}

View File

@@ -21,9 +21,7 @@ import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.client.LabelId;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.PatchSetApproval;
import com.google.gerrit.reviewdb.client.PatchSetInfo;
import com.google.gerrit.server.ApprovalsUtil;
import com.google.gerrit.server.ChangeMessagesUtil;
import com.google.gerrit.server.PatchSetUtil;
import com.google.gerrit.server.config.SendEmailExecutor;
@@ -148,12 +146,7 @@ public class MergedByPushOp implements BatchUpdateOp {
ChangeMessagesUtil.newMessage(
psId, ctx.getUser(), ctx.getWhen(), msgBuf.toString(), ChangeMessagesUtil.TAG_MERGED);
cmUtil.addChangeMessage(update, msg);
PatchSetApproval submitter =
ApprovalsUtil.newApproval(
change.currentPatchSetId(), ctx.getUser(), LabelId.legacySubmit(), 1, ctx.getWhen());
update.putApproval(submitter.getLabel(), submitter.getValue());
update.putApproval(LabelId.legacySubmit().get(), (short) 1);
return true;
}
@@ -188,12 +181,12 @@ public class MergedByPushOp implements BatchUpdateOp {
}));
changeMerged.fire(
change, patchSet, ctx.getAccount(), patchSet.getCommitId().name(), ctx.getWhen());
change, patchSet, ctx.getAccount(), patchSet.commitId().name(), ctx.getWhen());
}
private PatchSetInfo getPatchSetInfo(ChangeContext ctx) throws IOException {
RevWalk rw = ctx.getRevWalk();
RevCommit commit = rw.parseCommit(requireNonNull(patchSet).getCommitId());
RevCommit commit = rw.parseCommit(requireNonNull(patchSet).commitId());
return patchSetInfoFactory.get(rw, commit, psId);
}
}

View File

@@ -97,8 +97,8 @@ public class PureRevertCache {
claimedRevert.getProjectName(), claimedRevert.getChange().getRevertOf());
return isPureRevert(
claimedRevert.getProjectName(),
claimedRevert.getCurrentPatchSet().getCommitId(),
claimedOriginal.getCurrentPatchSet().getCommitId());
claimedRevert.getCurrentPatchSet().commitId(),
claimedOriginal.getCurrentPatchSet().commitId());
}
/**

View File

@@ -2187,7 +2187,7 @@ class ReceiveCommits {
// Schedule as a replacement to this one matching change.
//
ObjectId currentPs = changes.get(0).currentPatchSet().getCommitId();
ObjectId currentPs = changes.get(0).currentPatchSet().commitId();
// If Commit is already current PatchSet of target Change.
if (p.commit.equals(currentPs)) {
if (pending.size() == 1) {
@@ -2817,7 +2817,7 @@ class ReceiveCommits {
}
if (edit.isPresent()) {
if (edit.get().getBasePatchSet().getId().equals(psId)) {
if (edit.get().getBasePatchSet().id().equals(psId)) {
// replace edit
cmd =
new ReceiveCommand(edit.get().getEditCommit(), newCommitId, edit.get().getRefName());
@@ -2911,7 +2911,7 @@ class ReceiveCommits {
@Override
public boolean updateChange(ChangeContext ctx) {
PatchSet ps = psUtil.get(ctx.getNotes(), psId);
List<String> oldGroups = ps.getGroups();
List<String> oldGroups = ps.groups();
if (oldGroups == null) {
if (groups == null) {
return false;
@@ -2919,7 +2919,7 @@ class ReceiveCommits {
} else if (sameGroups(oldGroups, groups)) {
return false;
}
psUtil.setGroups(ctx.getUpdate(psId), ps, groups);
ctx.getUpdate(psId).setGroups(groups);
return true;
}
});

View File

@@ -111,8 +111,8 @@ public class ReceiveCommitsAdvertiseRefsHook implements AdvertiseRefsHook {
// Ensure we actually observed a patch set ref pointing to this
// object, in case the database is out of sync with the repo and the
// object doesn't actually exist.
if (allPatchSets.contains(ps.getCommitId())) {
r.add(ps.getCommitId());
if (allPatchSets.contains(ps.commitId())) {
r.add(ps.commitId());
}
}
}

View File

@@ -250,7 +250,7 @@ public class ReplaceOp implements BatchUpdateOp {
}
if (groups.isEmpty()) {
PatchSet prevPs = psUtil.current(notes);
groups = prevPs != null ? prevPs.getGroups() : ImmutableList.of();
groups = prevPs != null ? prevPs.groups() : ImmutableList.of();
}
ChangeData cd = changeDataFactory.create(ctx.getNotes());
@@ -454,7 +454,7 @@ public class ReplaceOp implements BatchUpdateOp {
continue;
}
LabelType lt = projectState.getLabelTypes().byLabel(a.getLabelId());
LabelType lt = projectState.getLabelTypes().byLabel(a.labelId());
if (lt != null) {
current.put(lt.getName(), a);
}
@@ -551,7 +551,7 @@ public class ReplaceOp implements BatchUpdateOp {
Streams.concat(
oldRecipients.getReviewers().stream(),
reviewerAdditions.flattenResults(AddReviewersOp.Result::addedReviewers).stream()
.map(PatchSetApproval::getAccountId))
.map(PatchSetApproval::accountId))
.collect(toImmutableSet()));
cm.addExtraCC(
Streams.concat(
@@ -562,7 +562,7 @@ public class ReplaceOp implements BatchUpdateOp {
cm.send();
} catch (Exception e) {
logger.atSevere().withCause(e).log(
"Cannot send email for new patch set %s", newPatchSet.getId());
"Cannot send email for new patch set %s", newPatchSet.id());
}
}

View File

@@ -14,6 +14,8 @@
package com.google.gerrit.server.group.db;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ListMultimap;
@@ -21,7 +23,7 @@ import com.google.common.collect.MultimapBuilder;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.AccountGroupByIdAud;
import com.google.gerrit.reviewdb.client.AccountGroupByIdAudit;
import com.google.gerrit.reviewdb.client.AccountGroupMemberAudit;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.config.AllUsersName;
@@ -69,66 +71,75 @@ public class AuditLogReader {
private ImmutableList<AccountGroupMemberAudit> getMembersAudit(
AccountGroup.Id groupId, List<ParsedCommit> commits) {
ListMultimap<MemberKey, AccountGroupMemberAudit> audits =
ListMultimap<MemberKey, AccountGroupMemberAudit.Builder> audits =
MultimapBuilder.hashKeys().linkedListValues().build();
ImmutableList.Builder<AccountGroupMemberAudit> result = ImmutableList.builder();
List<AccountGroupMemberAudit.Builder> result = new ArrayList<>();
for (ParsedCommit pc : commits) {
for (Account.Id id : pc.addedMembers()) {
MemberKey key = MemberKey.create(groupId, id);
AccountGroupMemberAudit audit =
new AccountGroupMemberAudit(
AccountGroupMemberAudit.key(id, groupId, pc.when()), pc.authorId());
AccountGroupMemberAudit.Builder audit =
AccountGroupMemberAudit.builder()
.memberId(id)
.groupId(groupId)
.addedOn(pc.when())
.addedBy(pc.authorId());
audits.put(key, audit);
result.add(audit);
}
for (Account.Id id : pc.removedMembers()) {
List<AccountGroupMemberAudit> adds = audits.get(MemberKey.create(groupId, id));
List<AccountGroupMemberAudit.Builder> adds = audits.get(MemberKey.create(groupId, id));
if (!adds.isEmpty()) {
AccountGroupMemberAudit audit = adds.remove(0);
AccountGroupMemberAudit.Builder audit = adds.remove(0);
audit.removed(pc.authorId(), pc.when());
} else {
// Match old behavior of DbGroupAuditListener and add a "legacy" add/remove pair.
AccountGroupMemberAudit audit =
new AccountGroupMemberAudit(
AccountGroupMemberAudit.key(id, groupId, pc.when()), pc.authorId());
audit.removedLegacy();
AccountGroupMemberAudit.Builder audit =
AccountGroupMemberAudit.builder()
.groupId(groupId)
.memberId(id)
.addedOn(pc.when())
.addedBy(pc.authorId())
.removedLegacy();
result.add(audit);
}
}
}
return result.build();
return result.stream().map(AccountGroupMemberAudit.Builder::build).collect(toImmutableList());
}
public ImmutableList<AccountGroupByIdAud> getSubgroupsAudit(
public ImmutableList<AccountGroupByIdAudit> getSubgroupsAudit(
Repository repo, AccountGroup.UUID uuid) throws IOException, ConfigInvalidException {
return getSubgroupsAudit(getGroupId(repo, uuid), parseCommits(repo, uuid));
}
private ImmutableList<AccountGroupByIdAud> getSubgroupsAudit(
private ImmutableList<AccountGroupByIdAudit> getSubgroupsAudit(
AccountGroup.Id groupId, List<ParsedCommit> commits) {
ListMultimap<SubgroupKey, AccountGroupByIdAud> audits =
ListMultimap<SubgroupKey, AccountGroupByIdAudit.Builder> audits =
MultimapBuilder.hashKeys().linkedListValues().build();
ImmutableList.Builder<AccountGroupByIdAud> result = ImmutableList.builder();
List<AccountGroupByIdAudit.Builder> result = new ArrayList<>();
for (ParsedCommit pc : commits) {
for (AccountGroup.UUID uuid : pc.addedSubgroups()) {
SubgroupKey key = SubgroupKey.create(groupId, uuid);
AccountGroupByIdAud audit =
new AccountGroupByIdAud(
AccountGroupByIdAud.key(groupId, uuid, pc.when()), pc.authorId());
AccountGroupByIdAudit.Builder audit =
AccountGroupByIdAudit.builder()
.groupId(groupId)
.includeUuid(uuid)
.addedOn(pc.when())
.addedBy(pc.authorId());
audits.put(key, audit);
result.add(audit);
}
for (AccountGroup.UUID uuid : pc.removedSubgroups()) {
List<AccountGroupByIdAud> adds = audits.get(SubgroupKey.create(groupId, uuid));
List<AccountGroupByIdAudit.Builder> adds = audits.get(SubgroupKey.create(groupId, uuid));
if (!adds.isEmpty()) {
AccountGroupByIdAud audit = adds.remove(0);
AccountGroupByIdAudit.Builder audit = adds.remove(0);
audit.removed(pc.authorId(), pc.when());
} else {
// Unlike members, DbGroupAuditListener didn't insert an add/remove pair here.
}
}
}
return result.build();
return result.stream().map(AccountGroupByIdAudit.Builder::build).collect(toImmutableList());
}
private Optional<ParsedCommit> parse(AccountGroup.UUID uuid, RevCommit c) {

View File

@@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.reviewdb.client.AccountGroupByIdAud;
import com.google.gerrit.reviewdb.client.AccountGroupByIdAudit;
import com.google.gerrit.reviewdb.client.AccountGroupMemberAudit;
import com.google.gerrit.server.config.AllUsersName;
import com.google.gerrit.server.git.GitRepositoryManager;
@@ -152,7 +152,7 @@ public class Groups {
* @throws IOException if an error occurs while reading from NoteDb
* @throws ConfigInvalidException if the group couldn't be retrieved from NoteDb
*/
public List<AccountGroupByIdAud> getSubgroupsAudit(Repository repo, AccountGroup.UUID groupUuid)
public List<AccountGroupByIdAudit> getSubgroupsAudit(Repository repo, AccountGroup.UUID groupUuid)
throws IOException, ConfigInvalidException {
return auditLogReader.getSubgroupsAudit(repo, groupUuid);
}

View File

@@ -451,7 +451,7 @@ public class ChangeField {
exact(ChangeQueryBuilder.FIELD_EXACTCOMMIT).buildRepeatable(ChangeField::getRevisions);
private static ImmutableSet<String> getRevisions(ChangeData cd) {
return cd.patchSets().stream().map(ps -> ps.getCommitId().name()).collect(toImmutableSet());
return cd.patchSets().stream().map(ps -> ps.commitId().name()).collect(toImmutableSet());
}
/** Tracking id extracted from a footer. */
@@ -467,13 +467,12 @@ public class ChangeField {
Set<String> allApprovals = new HashSet<>();
Set<String> distinctApprovals = new HashSet<>();
for (PatchSetApproval a : cd.currentApprovals()) {
if (a.getValue() != 0 && !a.isLegacySubmit()) {
allApprovals.add(formatLabel(a.getLabel(), a.getValue(), a.getAccountId()));
if (owners && cd.change().getOwner().equals(a.getAccountId())) {
allApprovals.add(
formatLabel(a.getLabel(), a.getValue(), ChangeQueryBuilder.OWNER_ACCOUNT_ID));
if (a.value() != 0 && !a.isLegacySubmit()) {
allApprovals.add(formatLabel(a.label(), a.value(), a.accountId()));
if (owners && cd.change().getOwner().equals(a.accountId())) {
allApprovals.add(formatLabel(a.label(), a.value(), ChangeQueryBuilder.OWNER_ACCOUNT_ID));
}
distinctApprovals.add(formatLabel(a.getLabel(), a.getValue()));
distinctApprovals.add(formatLabel(a.label(), a.value()));
}
}
allApprovals.addAll(distinctApprovals);
@@ -663,8 +662,7 @@ public class ChangeField {
public static final FieldDef<ChangeData, Iterable<String>> GROUP =
exact(ChangeQueryBuilder.FIELD_GROUP)
.buildRepeatable(
cd ->
cd.patchSets().stream().flatMap(ps -> ps.getGroups().stream()).collect(toSet()));
cd -> cd.patchSets().stream().flatMap(ps -> ps.groups().stream()).collect(toSet()));
/** Serialized patch set object, used for pre-populating results. */
public static final FieldDef<ChangeData, Iterable<byte[]>> PATCH_SET =

View File

@@ -330,7 +330,7 @@ public class MailProcessor {
approvalsUtil
.byPatchSetUser(
notes, psId, ctx.getAccountId(), ctx.getRevWalk(), ctx.getRepoView().getConfig())
.forEach(a -> approvals.put(a.getLabel(), a.getValue()));
.forEach(a -> approvals.put(a.label(), a.value()));
// Fire Gerrit event. Note that approvals can't be granted via email, so old and new approvals
// are always the same here.
commentAdded.fire(
@@ -386,7 +386,7 @@ public class MailProcessor {
commentsUtil.newComment(
ctx,
fileName,
patchSetForComment.getId(),
patchSetForComment.id(),
(short) side.ordinal(),
mailComment.getMessage(),
false,

View File

@@ -156,10 +156,10 @@ public abstract class ChangeEmail extends NotificationEmail {
}
if (patchSet != null) {
setHeader(MailHeader.PATCH_SET.fieldName(), patchSet.getPatchSetId() + "");
setHeader(MailHeader.PATCH_SET.fieldName(), patchSet.number() + "");
if (patchSetInfo == null) {
try {
patchSetInfo = args.patchSetInfoFactory.get(changeData.notes(), patchSet.getId());
patchSetInfo = args.patchSetInfoFactory.get(changeData.notes(), patchSet.id());
} catch (PatchSetInfoNotAvailableException | StorageException err) {
patchSetInfo = null;
}
@@ -205,7 +205,7 @@ public abstract class ChangeEmail extends NotificationEmail {
private void setCommitIdHeader() {
if (patchSet != null) {
setHeader(MailHeader.COMMIT.fieldName(), patchSet.getCommitId().name());
setHeader(MailHeader.COMMIT.fieldName(), patchSet.commitId().name());
}
}
@@ -286,7 +286,7 @@ public abstract class ChangeEmail extends NotificationEmail {
/** Get the patch list corresponding to patch set patchSetId of this change. */
protected PatchList getPatchList(int patchSetId) throws PatchListNotAvailableException {
PatchSet ps;
if (patchSetId == patchSet.getPatchSetId()) {
if (patchSetId == patchSet.number()) {
ps = patchSet;
} else {
try {
@@ -411,7 +411,7 @@ public abstract class ChangeEmail extends NotificationEmail {
case ALL:
default:
if (patchSet != null) {
authors.add(patchSet.getUploader());
authors.add(patchSet.uploader());
}
if (patchSetInfo != null) {
if (patchSetInfo.getAuthor().getAccount() != null) {
@@ -461,8 +461,8 @@ public abstract class ChangeEmail extends NotificationEmail {
soyContext.put("change", changeData);
Map<String, Object> patchSetData = new HashMap<>();
patchSetData.put("patchSetId", patchSet.getPatchSetId());
patchSetData.put("refName", patchSet.getRefName());
patchSetData.put("patchSetId", patchSet.number());
patchSetData.put("refName", patchSet.refName());
soyContext.put("patchSet", patchSetData);
Map<String, Object> patchSetInfoData = new HashMap<>();
@@ -472,7 +472,7 @@ public abstract class ChangeEmail extends NotificationEmail {
footers.add(MailHeader.CHANGE_ID.withDelimiter() + change.getKey().get());
footers.add(MailHeader.CHANGE_NUMBER.withDelimiter() + Integer.toString(change.getChangeId()));
footers.add(MailHeader.PATCH_SET.withDelimiter() + patchSet.getPatchSetId());
footers.add(MailHeader.PATCH_SET.withDelimiter() + patchSet.number());
footers.add(MailHeader.OWNER.withDelimiter() + getNameEmailFor(change.getOwner()));
if (change.getAssignee() != null) {
footers.add(MailHeader.ASSIGNEE.withDelimiter() + getNameEmailFor(change.getAssignee()));

View File

@@ -69,15 +69,15 @@ public class MergedSender extends ReplyToChangeSender {
Table<Account.Id, String, PatchSetApproval> pos = HashBasedTable.create();
Table<Account.Id, String, PatchSetApproval> neg = HashBasedTable.create();
for (PatchSetApproval ca :
args.approvalsUtil.byPatchSet(changeData.notes(), patchSet.getId(), null, null)) {
LabelType lt = labelTypes.byLabel(ca.getLabelId());
args.approvalsUtil.byPatchSet(changeData.notes(), patchSet.id(), null, null)) {
LabelType lt = labelTypes.byLabel(ca.labelId());
if (lt == null) {
continue;
}
if (ca.getValue() > 0) {
pos.put(ca.getAccountId(), lt.getName(), ca);
} else if (ca.getValue() < 0) {
neg.put(ca.getAccountId(), lt.getName(), ca);
if (ca.value() > 0) {
pos.put(ca.accountId(), lt.getName(), ca);
} else if (ca.value() < 0) {
neg.put(ca.accountId(), lt.getName(), ca);
}
}
@@ -117,7 +117,7 @@ public class MergedSender extends ReplyToChangeSender {
} else {
txt.append(lt.getName());
txt.append('=');
txt.append(LabelValue.formatValue(ca.getValue()));
txt.append(LabelValue.formatValue(ca.value()));
}
}
txt.append('\n');

View File

@@ -62,7 +62,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
@@ -77,7 +76,7 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
static final Ordering<PatchSetApproval> PSA_BY_TIME =
Ordering.from(comparing(PatchSetApproval::getGranted));
Ordering.from(comparing(PatchSetApproval::granted));
public static final Ordering<ChangeMessage> MESSAGE_BY_TIME =
Ordering.from(comparing(ChangeMessage::getWrittenOn));
@@ -330,9 +329,7 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
if (patchSets == null) {
ImmutableSortedMap.Builder<PatchSet.Id, PatchSet> b =
ImmutableSortedMap.orderedBy(comparing(PatchSet.Id::get));
for (Map.Entry<PatchSet.Id, PatchSet> e : state.patchSets()) {
b.put(e.getKey(), new PatchSet(e.getValue()));
}
b.putAll(state.patchSets());
patchSets = b.build();
}
return patchSets;
@@ -340,12 +337,7 @@ public class ChangeNotes extends AbstractChangeNotes<ChangeNotes> {
public ImmutableListMultimap<PatchSet.Id, PatchSetApproval> getApprovals() {
if (approvals == null) {
ImmutableListMultimap.Builder<PatchSet.Id, PatchSetApproval> b =
ImmutableListMultimap.builder();
for (Map.Entry<PatchSet.Id, PatchSetApproval> e : state.approvals()) {
b.put(e.getKey(), new PatchSetApproval(e.getValue()));
}
approvals = b.build();
approvals = ImmutableListMultimap.copyOf(state.approvals());
}
return approvals;
}

View File

@@ -40,7 +40,6 @@ import static com.google.gerrit.server.notedb.NoteDbTable.CHANGES;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
import com.google.common.base.Enums;
import com.google.common.base.Splitter;
import com.google.common.collect.HashBasedTable;
@@ -48,6 +47,7 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableTable;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder;
import com.google.common.collect.Sets;
import com.google.common.collect.Table;
@@ -100,31 +100,6 @@ import org.eclipse.jgit.util.RawParseUtils;
class ChangeNotesParser {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
@AutoValue
abstract static class ApprovalKey {
abstract PatchSet.Id psId();
abstract Account.Id accountId();
abstract String label();
private static ApprovalKey create(PatchSet.Id psId, Account.Id accountId, String label) {
return new AutoValue_ChangeNotesParser_ApprovalKey(psId, accountId, label);
}
}
/**
* Subset of field on patch sets that are mutable after patch set creation, and therefore may be
* parsed before the rest of the patch set is available.
*
* <p>In the future, if {@code PatchSet} becomes an immutable type with a builder, this class can
* be replaced with the builder. For now, keep it as simple as possible.
*/
static class PendingPatchSetFields {
List<String> groups = Collections.emptyList();
String description;
}
// Private final members initialized in the constructor.
private final ChangeNoteJson changeNoteJson;
private final LegacyChangeNoteRead legacyChangeNoteRead;
@@ -142,13 +117,12 @@ class ChangeNotesParser {
private final List<ReviewerStatusUpdate> reviewerUpdates;
private final List<SubmitRecord> submitRecords;
private final ListMultimap<ObjectId, Comment> comments;
private final Map<PatchSet.Id, PatchSet> patchSets;
private final Map<PatchSet.Id, PendingPatchSetFields> pendingPatchSets;
private final Map<PatchSet.Id, PatchSet.Builder> patchSets;
private final Set<PatchSet.Id> deletedPatchSets;
private final Map<PatchSet.Id, PatchSetState> patchSetStates;
private final List<PatchSet.Id> currentPatchSets;
private final Map<ApprovalKey, PatchSetApproval> approvals;
private final List<PatchSetApproval> bufferedApprovals;
private final Map<PatchSetApproval.Key, PatchSetApproval.Builder> approvals;
private final List<PatchSetApproval.Builder> bufferedApprovals;
private final List<ChangeMessage> allChangeMessages;
// Non-final private members filled in during the parsing process.
@@ -201,7 +175,6 @@ class ChangeNotesParser {
allChangeMessages = new ArrayList<>();
comments = MultimapBuilder.hashKeys().arrayListValues().build();
patchSets = new HashMap<>();
pendingPatchSets = new HashMap<>();
deletedPatchSets = new HashSet<>();
patchSetStates = new HashMap<>();
currentPatchSets = new ArrayList<>();
@@ -242,7 +215,7 @@ class ChangeNotesParser {
return revisionNoteMap;
}
private ChangeNotesState buildState() {
private ChangeNotesState buildState() throws ConfigInvalidException {
return ChangeNotesState.create(
tip.copy(),
id,
@@ -260,7 +233,7 @@ class ChangeNotesParser {
status,
Sets.newLinkedHashSet(Lists.reverse(pastAssignees)),
firstNonNull(hashtags, ImmutableSet.of()),
patchSets,
buildPatchSets(),
buildApprovals(),
ReviewerSet.fromTable(Tables.transpose(reviewers)),
ReviewerByEmailSet.fromTable(Tables.transpose(reviewersByEmail)),
@@ -278,11 +251,26 @@ class ChangeNotesParser {
updateCount);
}
private Map<PatchSet.Id, PatchSet> buildPatchSets() throws ConfigInvalidException {
Map<PatchSet.Id, PatchSet> result = Maps.newHashMapWithExpectedSize(patchSets.size());
for (Map.Entry<PatchSet.Id, PatchSet.Builder> e : patchSets.entrySet()) {
try {
PatchSet ps = e.getValue().build();
result.put(ps.id(), ps);
} catch (Exception ex) {
ConfigInvalidException cie = parseException("Error building patch set %s", e.getKey());
cie.initCause(ex);
throw cie;
}
}
return result;
}
private PatchSet.Id buildCurrentPatchSetId() {
// currentPatchSets are in parse order, i.e. newest first. Pick the first
// patch set that was marked as current, excluding deleted patch sets.
for (PatchSet.Id psId : currentPatchSets) {
if (patchSets.containsKey(psId)) {
if (patchSetCommitParsed(psId)) {
return psId;
}
}
@@ -292,14 +280,14 @@ class ChangeNotesParser {
private ListMultimap<PatchSet.Id, PatchSetApproval> buildApprovals() {
ListMultimap<PatchSet.Id, PatchSetApproval> result =
MultimapBuilder.hashKeys().arrayListValues().build();
for (PatchSetApproval a : approvals.values()) {
if (!patchSets.containsKey(a.getPatchSetId())) {
for (PatchSetApproval.Builder a : approvals.values()) {
if (!patchSetCommitParsed(a.key().patchSetId())) {
continue; // Patch set deleted or missing.
} else if (allPastReviewers.contains(a.getAccountId())
&& !reviewers.containsRow(a.getAccountId())) {
} else if (allPastReviewers.contains(a.key().accountId())
&& !reviewers.containsRow(a.key().accountId())) {
continue; // Reviewer was explicitly removed.
}
result.put(a.getPatchSetId(), a);
result.put(a.key().patchSetId(), a.build());
}
result.keySet().forEach(k -> result.get(k).sort(ChangeNotes.PSA_BY_TIME));
return result;
@@ -496,25 +484,27 @@ class ChangeNotesParser {
if (accountId == null) {
throw parseException("patch set %s requires an identified user as uploader", psId.get());
}
if (patchSets.containsKey(psId)) {
if (patchSetCommitParsed(psId)) {
if (deletedPatchSets.contains(psId)) {
// Do not update PS details as PS was deleted and this meta data is of no relevance.
return;
}
ObjectId commitId = patchSets.get(psId).commitId().orElseThrow(IllegalStateException::new);
throw new ConfigInvalidException(
String.format(
"Multiple revisions parsed for patch set %s: %s and %s",
psId.get(), patchSets.get(psId).getCommitId().name(), rev.name()));
}
PatchSet ps = new PatchSet(psId, rev);
patchSets.put(psId, ps);
ps.setUploader(accountId);
ps.setCreatedOn(ts);
PendingPatchSetFields pending = pendingPatchSets.remove(psId);
if (pending != null) {
ps.setGroups(pending.groups);
ps.setDescription(pending.description);
psId.get(), commitId.name(), rev.name()));
}
patchSets
.computeIfAbsent(psId, id -> PatchSet.builder())
.id(psId)
.commitId(rev)
.uploader(accountId)
.createdOn(ts);
// Fields not set here:
// * Groups, parsed earlier in parseGroups.
// * Description, parsed earlier in parseDescription.
// * Push certificate, parsed later in parseNotes.
}
private void parseGroups(PatchSet.Id psId, ChangeNotesCommit commit)
@@ -523,13 +513,10 @@ class ChangeNotesParser {
if (groupsStr == null) {
return;
}
if (patchSets.containsKey(psId)) {
throw patchSetFieldBeforeDefinition(psId, FOOTER_GROUPS);
}
PendingPatchSetFields pending =
pendingPatchSets.computeIfAbsent(psId, p -> new PendingPatchSetFields());
if (pending.groups.isEmpty()) {
pending.groups = PatchSet.splitGroups(groupsStr);
checkPatchSetCommitNotParsed(psId, FOOTER_GROUPS);
PatchSet.Builder pending = patchSets.computeIfAbsent(psId, id -> PatchSet.builder());
if (pending.groups().isEmpty()) {
pending.groups(PatchSet.splitGroups(groupsStr));
}
}
@@ -625,9 +612,9 @@ class ChangeNotesParser {
// exception is the legacy SUBM approval, which is never considered post-submit, but might end
// up sorted after the submit during rebuilding.
if (status == Change.Status.MERGED) {
for (PatchSetApproval psa : bufferedApprovals) {
if (!psa.isLegacySubmit()) {
psa.setPostSubmit(true);
for (PatchSetApproval.Builder psa : bufferedApprovals) {
if (!psa.key().isLegacySubmit()) {
psa.postSubmit(true);
}
}
}
@@ -673,15 +660,12 @@ class ChangeNotesParser {
return;
}
if (patchSets.containsKey(psId)) {
throw patchSetFieldBeforeDefinition(psId, FOOTER_PATCH_SET_DESCRIPTION);
}
checkPatchSetCommitNotParsed(psId, FOOTER_PATCH_SET_DESCRIPTION);
if (descLines.size() == 1) {
String desc = descLines.get(0).trim();
PendingPatchSetFields pending =
pendingPatchSets.computeIfAbsent(psId, p -> new PendingPatchSetFields());
if (pending.description == null) {
pending.description = desc;
PatchSet.Builder pending = patchSets.computeIfAbsent(psId, p -> PatchSet.builder());
if (!pending.description().isPresent()) {
pending.description(Optional.of(desc));
}
} else {
throw expectedOneFooter(FOOTER_PATCH_SET_DESCRIPTION, descLines);
@@ -740,10 +724,15 @@ class ChangeNotesParser {
}
}
for (PatchSet ps : patchSets.values()) {
ChangeRevisionNote rn = rns.get(ps.getCommitId());
for (PatchSet.Builder b : patchSets.values()) {
ObjectId commitId =
b.commitId()
.orElseThrow(
() ->
new IllegalStateException("never parsed commit ID for patch set " + b.id()));
ChangeRevisionNote rn = rns.get(commitId);
if (rn != null && rn.getPushCert() != null) {
ps.setPushCertificate(rn.getPushCert());
b.pushCertificate(Optional.of(rn.getPushCert()));
}
}
}
@@ -754,7 +743,7 @@ class ChangeNotesParser {
if (accountId == null) {
throw parseException("patch set %s requires an identified user as uploader", psId.get());
}
PatchSetApproval psa;
PatchSetApproval.Builder psa;
if (line.startsWith("-")) {
psa = parseRemoveApproval(psId, accountId, realAccountId, ts, line);
} else {
@@ -763,7 +752,7 @@ class ChangeNotesParser {
bufferedApprovals.add(psa);
}
private PatchSetApproval parseAddApproval(
private PatchSetApproval.Builder parseAddApproval(
PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line)
throws ConfigInvalidException {
// There are potentially 3 accounts involved here:
@@ -800,23 +789,20 @@ class ChangeNotesParser {
throw pe;
}
PatchSetApproval psa =
new PatchSetApproval(
PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(l.label())),
l.value(),
ts);
psa.setTag(tag);
PatchSetApproval.Builder psa =
PatchSetApproval.builder()
.key(PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(l.label())))
.value(l.value())
.granted(ts)
.tag(Optional.ofNullable(tag));
if (!Objects.equals(realAccountId, committerId)) {
psa.setRealAccountId(realAccountId);
}
ApprovalKey k = ApprovalKey.create(psId, effectiveAccountId, l.label());
if (!approvals.containsKey(k)) {
approvals.put(k, psa);
psa.realAccountId(realAccountId);
}
approvals.putIfAbsent(psa.key(), psa);
return psa;
}
private PatchSetApproval parseRemoveApproval(
private PatchSetApproval.Builder parseRemoveApproval(
PatchSet.Id psId, Account.Id committerId, Account.Id realAccountId, Timestamp ts, String line)
throws ConfigInvalidException {
// See comments in parseAddApproval about the various users involved.
@@ -843,16 +829,15 @@ class ChangeNotesParser {
// Store an actual 0-vote approval in the map for a removed approval, because ApprovalCopier
// needs an actual approval in order to block copying an earlier approval over a later delete.
PatchSetApproval remove =
new PatchSetApproval(
PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(label)), (short) 0, ts);
PatchSetApproval.Builder remove =
PatchSetApproval.builder()
.key(PatchSetApproval.key(psId, effectiveAccountId, LabelId.create(label)))
.value(0)
.granted(ts);
if (!Objects.equals(realAccountId, committerId)) {
remove.setRealAccountId(realAccountId);
}
ApprovalKey k = ApprovalKey.create(psId, effectiveAccountId, label);
if (!approvals.containsKey(k)) {
approvals.put(k, remove);
remove.realAccountId(realAccountId);
}
approvals.putIfAbsent(remove.key(), remove);
return remove;
}
@@ -1014,7 +999,7 @@ class ChangeNotesParser {
private void updatePatchSetStates() {
Set<PatchSet.Id> missing = new TreeSet<>(comparing(PatchSet.Id::get));
missing.addAll(pendingPatchSets.keySet());
missing.addAll(patchSets.keySet());
for (Map.Entry<PatchSet.Id, PatchSetState> e : patchSetStates.entrySet()) {
switch (e.getValue()) {
case PUBLISHED:
@@ -1038,7 +1023,7 @@ class ChangeNotesParser {
comments.values(), c -> PatchSet.id(id, c.key.patchSetId), missing);
pruned +=
pruneEntitiesForMissingPatchSets(
approvals.values(), PatchSetApproval::getPatchSetId, missing);
approvals.values(), psa -> psa.key().patchSetId(), missing);
if (!missing.isEmpty()) {
logger.atWarning().log(
@@ -1051,7 +1036,7 @@ class ChangeNotesParser {
int pruned = 0;
for (Iterator<T> it = ents.iterator(); it.hasNext(); ) {
PatchSet.Id psId = psIdFunc.apply(it.next());
if (!patchSets.containsKey(psId)) {
if (!patchSetCommitParsed(psId)) {
pruned++;
missing.add(psId);
it.remove();
@@ -1094,11 +1079,18 @@ class ChangeNotesParser {
}
}
private ConfigInvalidException patchSetFieldBeforeDefinition(
PatchSet.Id psId, FooterKey footerPatchSetDescription) {
return parseException(
"%s field found for patch set %s before it was defined",
footerPatchSetDescription.getName(), psId.get());
private void checkPatchSetCommitNotParsed(PatchSet.Id psId, FooterKey footer)
throws ConfigInvalidException {
if (patchSetCommitParsed(psId)) {
throw parseException(
"%s field found for patch set %s before patch set was originally defined",
footer.getName(), psId.get());
}
}
private boolean patchSetCommitParsed(PatchSet.Id psId) {
PatchSet.Builder pending = patchSets.get(psId);
return pending != null && pending.commitId().isPresent();
}
private ConfigInvalidException parseException(String fmt, Object... args) {

View File

@@ -555,12 +555,12 @@ public abstract class ChangeNotesState {
.patchSets(
proto.getPatchSetList().stream()
.map(bytes -> parseProtoFrom(PatchSetProtoConverter.INSTANCE, bytes))
.map(ps -> Maps.immutableEntry(ps.getId(), ps))
.map(ps -> Maps.immutableEntry(ps.id(), ps))
.collect(toImmutableList()))
.approvals(
proto.getApprovalList().stream()
.map(bytes -> parseProtoFrom(PatchSetApprovalProtoConverter.INSTANCE, bytes))
.map(a -> Maps.immutableEntry(a.getPatchSetId(), a))
.map(a -> Maps.immutableEntry(a.patchSetId(), a))
.collect(toImmutableList()))
.reviewers(toReviewerSet(proto.getReviewerList()))
.reviewersByEmail(toReviewerByEmailSet(proto.getReviewerByEmailList()))

View File

@@ -134,7 +134,7 @@ public class PatchListCacheImpl implements PatchListCache {
private PatchList get(Change change, PatchSet patchSet, Integer parentNum)
throws PatchListNotAvailableException {
Project.NameKey project = change.getProject();
ObjectId b = patchSet.getCommitId();
ObjectId b = patchSet.commitId();
Whitespace ws = Whitespace.IGNORE_NONE;
if (parentNum != null) {
return get(PatchListKey.againstParentNum(parentNum, b, ws), project);

View File

@@ -268,7 +268,7 @@ public class PatchScriptFactory implements Callable<PatchScript> {
if (ps == null) {
throw new NoSuchChangeException(psId.changeId());
}
return ps.getCommitId();
return ps.commitId();
}
private ObjectId getEditRev() throws AuthException, IOException {
@@ -303,7 +303,7 @@ public class PatchScriptFactory implements Callable<PatchScript> {
switch (changeType) {
case COPIED:
case RENAMED:
if (ps.getId().equals(psa)) {
if (ps.id().equals(psa)) {
name = oldName;
}
break;
@@ -316,7 +316,7 @@ public class PatchScriptFactory implements Callable<PatchScript> {
}
}
Patch p = new Patch(Patch.key(ps.getId(), name));
Patch p = new Patch(Patch.key(ps.id(), name));
history.add(p);
byKey.put(p.getKey(), p);
}

View File

@@ -76,8 +76,8 @@ public class PatchSetInfoFactory {
throws PatchSetInfoNotAvailableException {
try (Repository repo = repoManager.openRepository(project);
RevWalk rw = new RevWalk(repo)) {
RevCommit src = rw.parseCommit(patchSet.getCommitId());
PatchSetInfo info = get(rw, src, patchSet.getId());
RevCommit src = rw.parseCommit(patchSet.commitId());
PatchSetInfo info = get(rw, src, patchSet.id());
info.setParents(toParentInfos(src.getParents(), rw));
return info;
} catch (IOException | StorageException e) {

View File

@@ -297,7 +297,7 @@ public class ProjectsConsistencyChecker {
// Auto-close by commit
for (ObjectId patchSetSha1 :
autoCloseableChange.patchSets().stream()
.map(PatchSet::getCommitId)
.map(PatchSet::commitId)
.collect(toSet())) {
if (mergedSha1s.contains(patchSetSha1)) {
autoCloseableChangesByBranch.add(

View File

@@ -47,7 +47,7 @@ public class RemoveReviewerControl {
public void checkRemoveReviewer(
ChangeNotes notes, CurrentUser currentUser, PatchSetApproval approval)
throws PermissionBackendException, AuthException {
checkRemoveReviewer(notes, currentUser, approval.getAccountId(), approval.getValue());
checkRemoveReviewer(notes, currentUser, approval.accountId(), approval.value());
}
/**

View File

@@ -74,6 +74,7 @@ import com.google.gerrit.server.project.ProjectCache;
import com.google.gerrit.server.project.ProjectState;
import com.google.gerrit.server.project.SubmitRuleEvaluator;
import com.google.gerrit.server.project.SubmitRuleOptions;
import com.google.gerrit.server.util.time.TimeUtil;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import java.io.IOException;
@@ -227,7 +228,13 @@ public class ChangeData {
new ChangeData(
null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, project, id, null, null);
cd.currentPatchSet = new PatchSet(PatchSet.id(id, currentPatchSetId), commitId);
cd.currentPatchSet =
PatchSet.builder()
.id(PatchSet.id(id, currentPatchSetId))
.commitId(commitId)
.uploader(Account.id(1000))
.createdOn(TimeUtil.nowTs())
.build();
return cd;
}
@@ -387,7 +394,7 @@ public class ChangeData {
return Optional.empty();
}
ObjectId id = ps.getCommitId();
ObjectId id = ps.commitId();
Whitespace ws = Whitespace.IGNORE_NONE;
PatchListKey pk =
parentCount > 1
@@ -497,7 +504,7 @@ public class ChangeData {
return null;
}
for (PatchSet p : patchSets()) {
if (p.getId().equals(c.currentPatchSetId())) {
if (p.id().equals(c.currentPatchSetId())) {
currentPatchSet = p;
return p;
}
@@ -582,7 +589,7 @@ public class ChangeData {
}
try (Repository repo = repoManager.openRepository(project());
RevWalk walk = new RevWalk(repo)) {
RevCommit c = walk.parseCommit(ps.getCommitId());
RevCommit c = walk.parseCommit(ps.commitId());
commitMessage = c.getFullMessage();
commitFooters = c.getFooterLines();
author = c.getAuthorIdent();
@@ -609,11 +616,11 @@ public class ChangeData {
/** @return patch with the given ID, or null if it does not exist. */
public PatchSet patchSet(PatchSet.Id psId) {
if (currentPatchSet != null && currentPatchSet.getId().equals(psId)) {
if (currentPatchSet != null && currentPatchSet.id().equals(psId)) {
return currentPatchSet;
}
for (PatchSet ps : patchSets()) {
if (ps.getId().equals(psId)) {
if (ps.id().equals(psId)) {
return ps;
}
}
@@ -896,8 +903,7 @@ public class ChangeData {
String mergeStrategy =
mergeUtilFactory.create(projectCache.get(project())).mergeStrategyName();
mergeable =
mergeabilityCache.get(
ps.getCommitId(), ref, str.type, mergeStrategy, c.getDest(), repo);
mergeabilityCache.get(ps.commitId(), ref, str.type, mergeStrategy, c.getDest(), repo);
} catch (IOException e) {
throw new StorageException(e);
}
@@ -975,11 +981,11 @@ public class ChangeData {
PatchSet ps = currentPatchSet();
if (ps != null) {
if (stars.contains(StarredChangesUtil.REVIEWED_LABEL + "/" + ps.getPatchSetId())) {
if (stars.contains(StarredChangesUtil.REVIEWED_LABEL + "/" + ps.number())) {
return true;
}
if (stars.contains(StarredChangesUtil.UNREVIEWED_LABEL + "/" + ps.getPatchSetId())) {
if (stars.contains(StarredChangesUtil.UNREVIEWED_LABEL + "/" + ps.number())) {
return false;
}
}

View File

@@ -47,9 +47,9 @@ public class CommitPredicate extends ChangeIndexPredicate {
protected boolean equals(PatchSet p, String id) {
if (getField() == EXACT_COMMIT) {
return p.getCommitId().name().equals(id);
return p.commitId().name().equals(id);
}
return matchesAbbreviation(p.getCommitId(), id);
return matchesAbbreviation(p.commitId(), id);
}
@Override

View File

@@ -131,7 +131,7 @@ public class ConflictsPredicate {
return false;
}
other = object.currentPatchSet().getCommitId();
other = object.currentPatchSet().commitId();
ConflictKey conflictsKey =
ConflictKey.create(
changeDataCache.getTestAgainst(),
@@ -207,7 +207,7 @@ public class ConflictsPredicate {
ObjectId getTestAgainst() {
if (testAgainst == null) {
testAgainst = cd.currentPatchSet().getCommitId();
testAgainst = cd.currentPatchSet().commitId();
}
return testAgainst;
}

View File

@@ -76,7 +76,7 @@ public class EqualsLabelPredicate extends ChangeIndexPredicate {
for (PatchSetApproval p : object.currentApprovals()) {
if (labelType.matches(p)) {
hasVote = true;
if (match(object, p.getValue(), p.getAccountId())) {
if (match(object, p.value(), p.accountId())) {
return true;
}
}

View File

@@ -26,7 +26,7 @@ public class GroupPredicate extends ChangeIndexPredicate {
@Override
public boolean match(ChangeData cd) {
for (PatchSet ps : cd.patchSets()) {
List<String> groups = ps.getGroups();
List<String> groups = ps.groups();
if (groups != null && groups.contains(getValue())) {
return true;
}

View File

@@ -75,7 +75,7 @@ public class ApplyFix implements RestModifyView<FixResource, Void> {
try (Repository repository = gitRepositoryManager.openRepository(project)) {
List<TreeModification> treeModifications =
fixReplacementInterpreter.toTreeModifications(
repository, projectState, patchSet.getCommitId(), fixResource.getFixReplacements());
repository, projectState, patchSet.commitId(), fixResource.getFixReplacements());
ChangeEdit changeEdit =
changeEditModifier.combineWithModifiedPatchSetTree(
repository, revisionResource.getNotes(), patchSet, treeModifications);

View File

@@ -357,7 +357,7 @@ public class ChangeEdits implements ChildCollection<ChangeResource, ChangeEditRe
return Response.ok(
fileContentUtil.getContent(
projectCache.checkedGet(rsrc.getChangeResource().getProject()),
base ? edit.getBasePatchSet().getCommitId() : edit.getEditCommit(),
base ? edit.getBasePatchSet().commitId() : edit.getEditCommit(),
rsrc.getPath(),
null));
} catch (ResourceNotFoundException | BadRequestException e) {
@@ -384,8 +384,8 @@ public class ChangeEdits implements ChildCollection<ChangeResource, ChangeEditRe
webLinks.getDiffLinks(
change.getProject().get(),
change.getChangeId(),
edit.getBasePatchSet().getPatchSetId(),
edit.getBasePatchSet().getRefName(),
edit.getBasePatchSet().number(),
edit.getBasePatchSet().refName(),
rsrc.getPath(),
0,
edit.getRefName(),
@@ -458,7 +458,7 @@ public class ChangeEdits implements ChildCollection<ChangeResource, ChangeEditRe
if (base) {
try (Repository repo = repoManager.openRepository(rsrc.getProject());
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(edit.get().getBasePatchSet().getCommitId());
RevCommit commit = rw.parseCommit(edit.get().getBasePatchSet().commitId());
msg = commit.getFullMessage();
}
} else {

View File

@@ -39,6 +39,6 @@ public class ChangeIncludedIn implements RestReadView<ChangeResource> {
@Override
public IncludedInInfo apply(ChangeResource rsrc) throws RestApiException, IOException {
PatchSet ps = psUtil.current(rsrc.getNotes());
return includedIn.apply(rsrc.getProject(), ps.getCommitId().name());
return includedIn.apply(rsrc.getProject(), ps.commitId().name());
}
}

View File

@@ -143,7 +143,7 @@ public class CherryPickChange {
throws IOException, InvalidChangeOperationException, IntegrationException, UpdateException,
RestApiException, ConfigInvalidException, NoSuchProjectException {
return cherryPick(
batchUpdateFactory, change, change.getProject(), patch.getCommitId(), input, dest);
batchUpdateFactory, change, change.getProject(), patch.commitId(), input, dest);
}
public Result cherryPick(

View File

@@ -58,7 +58,7 @@ public class Comments implements ChildCollection<RevisionResource, CommentResour
String uuid = id.get();
ChangeNotes notes = rev.getNotes();
for (Comment c : commentsUtil.publishedByPatchSet(notes, rev.getPatchSet().getId())) {
for (Comment c : commentsUtil.publishedByPatchSet(notes, rev.getPatchSet().id())) {
if (uuid.equals(c.key.uuid)) {
return new CommentResource(rev, c);
}

View File

@@ -277,7 +277,7 @@ public class CreateChange
if (input.baseChange != null) {
ChangeNotes baseChange = getBaseChange(input.baseChange);
basePatchSet = psUtil.current(baseChange);
groups = basePatchSet.getGroups();
groups = basePatchSet.groups();
}
ObjectId parentCommit =
getParentCommit(git, rw, input.branch, input.newBranch, basePatchSet, input.baseCommit);
@@ -345,7 +345,7 @@ public class CreateChange
throws BadRequestException, IOException, UnprocessableEntityException,
ResourceConflictException {
if (basePatchSet != null) {
return basePatchSet.getCommitId();
return basePatchSet.commitId();
}
Ref destRef = repo.getRefDatabase().exactRef(inputBranch);

View File

@@ -84,7 +84,7 @@ public class CreateDraftComment
try (BatchUpdate bu =
updateFactory.create(rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Op op = new Op(rsrc.getPatchSet().getId(), in);
Op op = new Op(rsrc.getPatchSet().id(), in);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
return Response.created(
@@ -115,7 +115,7 @@ public class CreateDraftComment
comment =
commentsUtil.newComment(
ctx, in.path, ps.getId(), in.side(), in.message.trim(), in.unresolved, parentUuid);
ctx, in.path, ps.id(), in.side(), in.message.trim(), in.unresolved, parentUuid);
comment.setLineNbrAndRange(in.line, in.range);
comment.tag = in.tag;

View File

@@ -154,10 +154,10 @@ public class CreateMergePatchSet
List<String> groups = null;
if (!in.inheritParent && !in.baseChange.isEmpty()) {
PatchSet basePS = findBasePatchSet(in.baseChange);
currentPsCommit = rw.parseCommit(basePS.getCommitId());
groups = basePS.getGroups();
currentPsCommit = rw.parseCommit(basePS.commitId());
groups = basePS.groups();
} else {
currentPsCommit = rw.parseCommit(ps.getCommitId());
currentPsCommit = rw.parseCommit(ps.commitId());
}
Timestamp now = TimeUtil.nowTs();
@@ -176,7 +176,7 @@ public class CreateMergePatchSet
author,
ObjectId.fromString(change.getKey().get().substring(1)));
PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.getId());
PatchSet.Id nextPsId = ChangeUtil.nextPatchSetId(ps.id());
PatchSetInserter psInserter =
patchSetInserterFactory.create(rsrc.getNotes(), nextPsId, newCommit);
try (BatchUpdate bu = updateFactory.create(project, me, now)) {

View File

@@ -175,11 +175,11 @@ public class DeleteVote extends RetryingRestModifyView<VoteResource, DeleteVoteI
for (PatchSetApproval a :
approvalsUtil.byPatchSetUser(
ctx.getNotes(), psId, accountId, ctx.getRevWalk(), ctx.getRepoView().getConfig())) {
if (labelTypes.byLabel(a.getLabelId()) == null) {
if (labelTypes.byLabel(a.labelId()) == null) {
continue; // Ignore undefined labels.
} else if (!a.getLabel().equals(label)) {
} else if (!a.label().equals(label)) {
// Populate map for non-matching labels, needed by VoteDeleted.
newApprovals.put(a.getLabel(), a.getValue());
newApprovals.put(a.label(), a.value());
continue;
} else {
try {
@@ -189,11 +189,11 @@ public class DeleteVote extends RetryingRestModifyView<VoteResource, DeleteVoteI
}
}
// Set the approval to 0 if vote is being removed.
newApprovals.put(a.getLabel(), (short) 0);
newApprovals.put(a.label(), (short) 0);
found = true;
// Set old value, as required by VoteDeleted.
oldApprovals.put(a.getLabel(), a.getValue());
oldApprovals.put(a.label(), a.value());
break;
}
if (!found) {

View File

@@ -45,6 +45,6 @@ public class DownloadContent implements RestReadView<FileResource> {
String path = rsrc.getPatchKey().fileName();
RevisionResource rev = rsrc.getRevision();
return fileContentUtil.downloadContent(
projectCache.checkedGet(rev.getProject()), rev.getPatchSet().getCommitId(), path, parent);
projectCache.checkedGet(rev.getProject()), rev.getPatchSet().commitId(), path, parent);
}
}

View File

@@ -66,7 +66,7 @@ public class DraftComments implements ChildCollection<RevisionResource, DraftCom
String uuid = id.get();
for (Comment c :
commentsUtil.draftByPatchSetAuthor(
rev.getPatchSet().getId(), rev.getAccountId(), rev.getNotes())) {
rev.getPatchSet().id(), rev.getAccountId(), rev.getNotes())) {
if (uuid.equals(c.key.uuid)) {
return new DraftCommentResource(rev, c);
}

View File

@@ -162,13 +162,13 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
Response.ok(
fileInfoJson.toFileInfoMap(
resource.getChange(),
resource.getPatchSet().getCommitId(),
resource.getPatchSet().commitId(),
baseResource.getPatchSet()));
} else if (parentNum > 0) {
r =
Response.ok(
fileInfoJson.toFileInfoMap(
resource.getChange(), resource.getPatchSet().getCommitId(), parentNum - 1));
resource.getChange(), resource.getPatchSet().commitId(), parentNum - 1));
} else {
r = Response.ok(fileInfoJson.toFileInfoMap(resource.getChange(), resource.getPatchSet()));
}
@@ -205,7 +205,7 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
ObjectReader or = git.newObjectReader();
RevWalk rw = new RevWalk(or);
TreeWalk tw = new TreeWalk(or)) {
RevCommit c = rw.parseCommit(resource.getPatchSet().getCommitId());
RevCommit c = rw.parseCommit(resource.getPatchSet().commitId());
tw.addTree(c.getTree());
tw.setRecursive(true);
@@ -229,11 +229,11 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
Account.Id userId = user.getAccountId();
PatchSet patchSetId = resource.getPatchSet();
Optional<PatchSetWithReviewedFiles> o;
o = accountPatchReviewStore.call(s -> s.findReviewed(patchSetId.getId(), userId));
o = accountPatchReviewStore.call(s -> s.findReviewed(patchSetId.id(), userId));
if (o.isPresent()) {
PatchSetWithReviewedFiles res = o.get();
if (res.patchSetId().equals(patchSetId.getId())) {
if (res.patchSetId().equals(patchSetId.id())) {
return res.files();
}
@@ -312,7 +312,7 @@ public class Files implements ChildCollection<RevisionResource, FileResource> {
}
accountPatchReviewStore.run(
s -> s.markReviewed(resource.getPatchSet().getId(), userId, pathList));
s -> s.markReviewed(resource.getPatchSet().id(), userId, pathList));
return pathList;
}
}

View File

@@ -54,7 +54,7 @@ public class Fixes implements ChildCollection<RevisionResource, FixResource> {
ChangeNotes changeNotes = revisionResource.getNotes();
List<RobotComment> robotComments =
commentsUtil.robotCommentsByPatchSet(changeNotes, revisionResource.getPatchSet().getId());
commentsUtil.robotCommentsByPatchSet(changeNotes, revisionResource.getPatchSet().id());
for (RobotComment robotComment : robotComments) {
for (FixSuggestion fixSuggestion : robotComment.fixSuggestions) {
if (Objects.equals(fixId, fixSuggestion.fixId)) {

View File

@@ -66,7 +66,7 @@ public class GetArchive implements RestReadView<RevisionResource> {
final RevCommit commit;
String name;
try (RevWalk rw = new RevWalk(repo)) {
commit = rw.parseCommit(rsrc.getPatchSet().getCommitId());
commit = rw.parseCommit(rsrc.getPatchSet().commitId());
name = name(f, rw, commit);
}

View File

@@ -87,7 +87,7 @@ public class GetBlame implements RestReadView<FileResource> {
String refName =
resource.getRevision().getEdit().isPresent()
? resource.getRevision().getEdit().get().getRefName()
: resource.getRevision().getPatchSet().getRefName();
: resource.getRevision().getPatchSet().refName();
Ref ref = repository.findRef(refName);
if (ref == null) {

View File

@@ -54,7 +54,7 @@ public class GetCommit implements RestReadView<RevisionResource> {
Project.NameKey p = rsrc.getChange().getProject();
try (Repository repo = repoManager.openRepository(p);
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(rsrc.getPatchSet().getCommitId());
RevCommit commit = rw.parseCommit(rsrc.getPatchSet().commitId());
rw.parseBody(commit);
CommitInfo info =
json.create(ImmutableSet.of())

View File

@@ -76,7 +76,7 @@ public class GetContent implements RestReadView<FileResource> {
}
return fileContentUtil.getContent(
projectCache.checkedGet(rsrc.getRevision().getProject()),
rsrc.getRevision().getPatchSet().getCommitId(),
rsrc.getRevision().getPatchSet().commitId(),
path,
parent);
}
@@ -90,7 +90,7 @@ public class GetContent implements RestReadView<FileResource> {
try (Repository git = gitManager.openRepository(notes.getProjectName());
RevWalk revWalk = new RevWalk(git)) {
RevCommit commit = revWalk.parseCommit(ps.getCommitId());
RevCommit commit = revWalk.parseCommit(ps.commitId());
return commit.getFullMessage();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);
@@ -107,7 +107,7 @@ public class GetContent implements RestReadView<FileResource> {
try (Repository git = gitManager.openRepository(notes.getProjectName());
RevWalk revWalk = new RevWalk(git)) {
return Text.forMergeList(
ComparisonType.againstAutoMerge(), revWalk.getObjectReader(), ps.getCommitId())
ComparisonType.againstAutoMerge(), revWalk.getObjectReader(), ps.commitId())
.getContent();
} catch (RepositoryNotFoundException e) {
throw new NoSuchChangeException(changeId, e);

View File

@@ -14,7 +14,6 @@
package com.google.gerrit.server.restapi.change;
import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.server.change.RevisionResource;
import com.google.inject.Singleton;
@@ -23,6 +22,6 @@ import com.google.inject.Singleton;
public class GetDescription implements RestReadView<RevisionResource> {
@Override
public String apply(RevisionResource rsrc) {
return Strings.nullToEmpty(rsrc.getPatchSet().getDescription());
return rsrc.getPatchSet().description().orElse("");
}
}

View File

@@ -147,7 +147,7 @@ public class GetDiff implements RestReadView<FileResource> {
RevisionResource baseResource =
revisions.parse(resource.getRevision().getChangeResource(), IdString.fromDecoded(base));
basePatchSet = baseResource.getPatchSet();
psf = patchScriptFactoryFactory.create(notes, fileName, basePatchSet.getId(), pId, prefs);
psf = patchScriptFactoryFactory.create(notes, fileName, basePatchSet.id(), pId, prefs);
} else if (parentNum > 0) {
psf = patchScriptFactoryFactory.create(notes, fileName, parentNum - 1, pId, prefs);
} else {
@@ -195,17 +195,17 @@ public class GetDiff implements RestReadView<FileResource> {
ProjectState state = projectCache.get(resource.getRevision().getChange().getProject());
DiffInfo result = new DiffInfo();
String revA = basePatchSet != null ? basePatchSet.getRefName() : content.commitIdA;
String revA = basePatchSet != null ? basePatchSet.refName() : content.commitIdA;
String revB =
resource.getRevision().getEdit().isPresent()
? resource.getRevision().getEdit().get().getRefName()
: resource.getRevision().getPatchSet().getRefName();
: resource.getRevision().getPatchSet().refName();
List<DiffWebLinkInfo> links =
webLinks.getDiffLinks(
state.getName(),
resource.getPatchKey().patchSetId().changeId().get(),
basePatchSet != null ? basePatchSet.getId().get() : null,
basePatchSet != null ? basePatchSet.id().get() : null,
revA,
MoreObjects.firstNonNull(ps.getOldName(), ps.getNewName()),
resource.getPatchKey().patchSetId().get(),

View File

@@ -66,7 +66,7 @@ public class GetMergeList implements RestReadView<RevisionResource> {
Project.NameKey p = rsrc.getChange().getProject();
try (Repository repo = repoManager.openRepository(p);
RevWalk rw = new RevWalk(repo)) {
RevCommit commit = rw.parseCommit(rsrc.getPatchSet().getCommitId());
RevCommit commit = rw.parseCommit(rsrc.getPatchSet().commitId());
rw.parseBody(commit);
if (uninterestingParent < 1 || uninterestingParent > commit.getParentCount()) {

View File

@@ -66,7 +66,7 @@ public class GetPatch implements RestReadView<RevisionResource> {
try {
final RevWalk rw = new RevWalk(repo);
try {
final RevCommit commit = rw.parseCommit(rsrc.getPatchSet().getCommitId());
final RevCommit commit = rw.parseCommit(rsrc.getPatchSet().commitId());
RevCommit[] parents = commit.getParents();
if (parents.length > 1) {
throw new ResourceConflictException("Revision has more than 1 parent.");

View File

@@ -102,7 +102,7 @@ public class GetRelated implements RestReadView<RevisionResource> {
for (RelatedChangesSorter.PatchSetData d : sorter.sort(cds, basePs)) {
PatchSet ps = d.patchSet();
RevCommit commit;
if (isEdit && ps.getId().equals(basePs.getId())) {
if (isEdit && ps.id().equals(basePs.id())) {
// Replace base of an edit with the edit itself.
ps = rsrc.getPatchSet();
commit = rsrc.getEdit().get().getEditCommit();
@@ -114,7 +114,7 @@ public class GetRelated implements RestReadView<RevisionResource> {
if (result.size() == 1) {
RelatedChangeAndCommitInfo r = result.get(0);
if (r.commit != null && r.commit.commit.equals(rsrc.getPatchSet().getCommitId().name())) {
if (r.commit != null && r.commit.commit.equals(rsrc.getPatchSet().commitId().name())) {
return Collections.emptyList();
}
}
@@ -123,13 +123,13 @@ public class GetRelated implements RestReadView<RevisionResource> {
@VisibleForTesting
public static Set<String> getAllGroups(ChangeNotes notes, PatchSetUtil psUtil) {
return psUtil.byChange(notes).stream().flatMap(ps -> ps.getGroups().stream()).collect(toSet());
return psUtil.byChange(notes).stream().flatMap(ps -> ps.groups().stream()).collect(toSet());
}
private void reloadChangeIfStale(List<ChangeData> cds, PatchSet wantedPs) {
for (ChangeData cd : cds) {
if (cd.getId().equals(wantedPs.getId().changeId())) {
if (cd.patchSet(wantedPs.getId()) == null) {
if (cd.getId().equals(wantedPs.id().changeId())) {
if (cd.patchSet(wantedPs.id()) == null) {
cd.reloadChange();
}
}
@@ -144,7 +144,7 @@ public class GetRelated implements RestReadView<RevisionResource> {
if (change != null) {
info.changeId = change.getKey().get();
info._changeNumber = change.getChangeId();
info._revisionNumber = ps != null ? ps.getPatchSetId() : null;
info._revisionNumber = ps != null ? ps.number() : null;
PatchSet.Id curr = change.currentPatchSetId();
info._currentRevisionNumber = curr != null ? curr.get() : null;
info.status = ChangeUtil.status(change).toUpperCase(Locale.US);

View File

@@ -37,6 +37,6 @@ public class ListRevisionComments extends ListRevisionDrafts {
@Override
protected Iterable<Comment> listComments(RevisionResource rsrc) {
ChangeNotes notes = rsrc.getNotes();
return commentsUtil.publishedByPatchSet(notes, rsrc.getPatchSet().getId());
return commentsUtil.publishedByPatchSet(notes, rsrc.getPatchSet().id());
}
}

View File

@@ -40,7 +40,7 @@ public class ListRevisionDrafts implements RestReadView<RevisionResource> {
protected Iterable<Comment> listComments(RevisionResource rsrc) {
return commentsUtil.draftByPatchSetAuthor(
rsrc.getPatchSet().getId(), rsrc.getAccountId(), rsrc.getNotes());
rsrc.getPatchSet().id(), rsrc.getAccountId(), rsrc.getNotes());
}
protected boolean includeAuthorInfo() {

View File

@@ -58,6 +58,6 @@ public class ListRobotComments implements RestReadView<RevisionResource> {
}
private Iterable<RobotComment> listComments(RevisionResource rsrc) {
return commentsUtil.robotCommentsByPatchSet(rsrc.getNotes(), rsrc.getPatchSet().getId());
return commentsUtil.robotCommentsByPatchSet(rsrc.getNotes(), rsrc.getPatchSet().id());
}
}

Some files were not shown because too many files have changed in this diff Show More