Add first version of the simple-submit-rules plugin
Add a REST API to configure the rules and labels.
Add the "Unresolved Comments" rule.
Add the "Require non Author Approval" rule.
Add tests, documentation and required bootstrap files (BUILD).
Change-Id: I0167ffa57e27b10d5e977ef2684f20759531ccc6
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4e6c840
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+/.classpath
+/.project
+/.settings/
+*.iml
diff --git a/BUILD b/BUILD
new file mode 100644
index 0000000..b4c70b6
--- /dev/null
+++ b/BUILD
@@ -0,0 +1,37 @@
+load("//tools/bzl:plugin.bzl", "gerrit_plugin", "PLUGIN_DEPS", "PLUGIN_TEST_DEPS")
+load("//tools/bzl:junit.bzl", "junit_tests")
+
+gerrit_plugin(
+ name = "simple-submit-rules",
+ srcs = glob(["src/main/java/**/*.java"]),
+ manifest_entries = [
+ "Gerrit-PluginName: simple-submit-rules",
+ "Gerrit-Module: com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesModule",
+ ],
+ resources = glob(["src/main/resources/**/*"]),
+)
+
+ABSTRACT_TEST_BASE = ["src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/AbstractSimpleSubmitRulesIT.java"]
+
+java_library(
+ name = "abstract_test_base",
+ testonly = 1,
+ srcs = ABSTRACT_TEST_BASE,
+ visibility = ["//visibility:public"],
+ deps = PLUGIN_TEST_DEPS + PLUGIN_DEPS + [
+ ":simple-submit-rules__plugin",
+ ],
+)
+
+junit_tests(
+ name = "tests",
+ srcs = glob(
+ ["src/test/java/**/*.java"],
+ exclude = ABSTRACT_TEST_BASE,
+ ),
+ visibility = ["//visibility:public"],
+ deps = PLUGIN_TEST_DEPS + PLUGIN_DEPS + [
+ ":abstract_test_base",
+ ":simple-submit-rules__plugin",
+ ],
+)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+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.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..debca3a
--- /dev/null
+++ b/README.md
@@ -0,0 +1,11 @@
+# Simple Submit Rules plugin
+Gerrit plugin to provide simple submit rules and a rest API to configure them.
+
+By *simple*, we mean any rule that can be described in one sentence.
+Or fits in a tweet.
+
+Having a set of simple rules makes **composition** easier, thus allowing harder
+rules to be defined ... in a simple way :)
+
+Of course, this plugin can't contain all the simple rules one can think of,
+and will only contain rules that seem popular or interesting to have.
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesConfig.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesConfig.java
new file mode 100644
index 0000000..856e71a
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesConfig.java
@@ -0,0 +1,22 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules;
+
+public final class SimpleSubmitRulesConfig {
+ public static final String KEY_REQUIRE_NON_AUTHOR_APPROVAL = "nonAuthorApprovalRequired";
+ public static final String KEY_BLOCK_IF_UNRESOLVED_COMMENTS = "blockIfUnresolvedComments";
+
+ private SimpleSubmitRulesConfig() {}
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesModule.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesModule.java
new file mode 100644
index 0000000..821f794
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/SimpleSubmitRulesModule.java
@@ -0,0 +1,79 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.registration.DynamicSet;
+import com.google.gerrit.extensions.restapi.RestApiModule;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.gerrit.server.project.NoSuchProjectException;
+import com.google.gerrit.server.project.ProjectResource;
+import com.google.gerrit.server.query.change.ChangeData;
+import com.google.gerrit.server.rules.SubmitRule;
+import com.google.inject.AbstractModule;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.config.ConfigServlet;
+import com.googlesource.gerrit.plugins.simplesubmitrules.config.ConfigTranslator;
+import com.googlesource.gerrit.plugins.simplesubmitrules.rules.NoUnresolvedCommentsRule;
+import com.googlesource.gerrit.plugins.simplesubmitrules.rules.RequireNonAuthorApprovalRule;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Bootstraps the Simple Submit Rules plugin */
+public class SimpleSubmitRulesModule extends AbstractModule {
+ private static final Logger log = LoggerFactory.getLogger(SimpleSubmitRulesModule.class);
+
+ /** Name of this plugin, as defined in the BUILD file */
+ @VisibleForTesting protected static final String PLUGIN_NAME = "simple-submit-rules";
+
+ private static final String API_ENDPOINT = PLUGIN_NAME;
+ private final PluginConfigFactory pluginConfigFactory;
+ private final String pluginName;
+
+ @Inject
+ public SimpleSubmitRulesModule(
+ PluginConfigFactory pluginConfigFactory, @PluginName String pluginName) {
+ this.pluginConfigFactory = pluginConfigFactory;
+ this.pluginName = pluginName;
+ }
+
+ @Override
+ protected void configure() {
+ bind(ConfigTranslator.class);
+
+ install(
+ new RestApiModule() {
+ @Override
+ protected void configure() {
+ get(ProjectResource.PROJECT_KIND, API_ENDPOINT).to(ConfigServlet.class);
+ put(ProjectResource.PROJECT_KIND, API_ENDPOINT).to(ConfigServlet.class);
+ }
+ });
+
+ DynamicSet.bind(binder(), SubmitRule.class).to(RequireNonAuthorApprovalRule.class);
+ DynamicSet.bind(binder(), SubmitRule.class).to(NoUnresolvedCommentsRule.class);
+ }
+
+ public PluginConfig getConfig(ChangeData changeData) {
+ try {
+ return pluginConfigFactory.getFromProjectConfig(changeData.project(), pluginName);
+ } catch (NoSuchProjectException e) {
+ log.error("Could not load plugin configuration", e);
+ return null;
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServlet.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServlet.java
new file mode 100644
index 0000000..468969b
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServlet.java
@@ -0,0 +1,81 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.config;
+
+import com.google.gerrit.extensions.restapi.AuthException;
+import com.google.gerrit.extensions.restapi.RestApiException;
+import com.google.gerrit.extensions.restapi.RestModifyView;
+import com.google.gerrit.extensions.restapi.RestReadView;
+import com.google.gerrit.server.IdentifiedUser;
+import com.google.gerrit.server.git.meta.MetaDataUpdate;
+import com.google.gerrit.server.permissions.PermissionBackend;
+import com.google.gerrit.server.permissions.PermissionBackendException;
+import com.google.gerrit.server.permissions.ProjectPermission;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.gerrit.server.project.ProjectResource;
+import com.google.inject.Inject;
+import java.io.IOException;
+
+/** REST Endpoint to configure labels and our simple submit rules */
+public class ConfigServlet
+ implements RestReadView<ProjectResource>, RestModifyView<ProjectResource, SubmitConfig> {
+ private final ProjectCache projectCache;
+ private final PermissionBackend permissionBackend;
+ private final MetaDataUpdate.User metaDataUpdateFactory;
+ private final ConfigTranslator configTranslator;
+
+ @Inject
+ ConfigServlet(
+ ProjectCache projectCache,
+ PermissionBackend permissionBackend,
+ MetaDataUpdate.User metaDataUpdateFactory,
+ ConfigTranslator configTranslator) {
+ this.projectCache = projectCache;
+ this.permissionBackend = permissionBackend;
+ this.metaDataUpdateFactory = metaDataUpdateFactory;
+ this.configTranslator = configTranslator;
+ }
+
+ @Override
+ public Object apply(ProjectResource resource) throws AuthException, PermissionBackendException {
+ permissionBackend
+ .user(resource.getUser())
+ .project(resource.getNameKey())
+ .check(ProjectPermission.READ_CONFIG);
+
+ return configTranslator.convertFrom(resource.getProjectState());
+ }
+
+ @Override
+ public Object apply(
+ ProjectResource resource,
+ com.googlesource.gerrit.plugins.simplesubmitrules.config.SubmitConfig inConfig)
+ throws PermissionBackendException, RestApiException, IOException {
+
+ permissionBackend
+ .user(resource.getUser())
+ .project(resource.getNameKey())
+ .check(ProjectPermission.WRITE_CONFIG);
+
+ IdentifiedUser user = resource.getUser().asIdentifiedUser();
+ try (MetaDataUpdate md = metaDataUpdateFactory.create(resource.getNameKey(), user)) {
+ configTranslator.applyTo(inConfig, resource.getProjectState());
+ resource.getProjectState().getConfig().commit(md);
+ projectCache.evict(resource.getNameKey());
+ }
+
+ return configTranslator.convertFrom(resource.getProjectState());
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslator.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslator.java
new file mode 100644
index 0000000..9087bdd
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslator.java
@@ -0,0 +1,146 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.config;
+
+import com.google.gerrit.common.data.LabelType;
+import com.google.gerrit.common.data.LabelTypes;
+import com.google.gerrit.extensions.annotations.PluginName;
+import com.google.gerrit.extensions.restapi.BadRequestException;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.config.PluginConfigFactory;
+import com.google.gerrit.server.project.ProjectConfig;
+import com.google.gerrit.server.project.ProjectState;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesConfig;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Map;
+
+/** Codec class used to convert {@link SubmitConfig} from/to a Gerrit config */
+public final class ConfigTranslator {
+ private final PluginConfigFactory pluginConfigFactory;
+ private final String pluginName;
+
+ @Inject
+ public ConfigTranslator(PluginConfigFactory pluginConfigFactory, @PluginName String pluginName) {
+ this.pluginConfigFactory = pluginConfigFactory;
+ this.pluginName = pluginName;
+ }
+
+ static void extractLabelCopyScores(
+ LabelType labelType, SubmitConfig.LabelDefinition labelDefinition) {
+ labelDefinition.copyScores = new HashSet<>();
+ if (labelType.isCopyMinScore()) {
+ labelDefinition.copyScores.add(ProjectConfig.KEY_COPY_MIN_SCORE);
+ }
+ if (labelType.isCopyMaxScore()) {
+ labelDefinition.copyScores.add(ProjectConfig.KEY_COPY_MAX_SCORE);
+ }
+ if (labelType.isCopyAllScoresIfNoChange()) {
+ labelDefinition.copyScores.add(ProjectConfig.KEY_COPY_ALL_SCORES_IF_NO_CHANGE);
+ }
+ if (labelType.isCopyAllScoresIfNoCodeChange()) {
+ labelDefinition.copyScores.add(ProjectConfig.KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE);
+ }
+ if (labelType.isCopyAllScoresOnMergeFirstParentUpdate()) {
+ labelDefinition.copyScores.add(
+ ProjectConfig.KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE);
+ }
+ if (labelType.isCopyAllScoresOnTrivialRebase()) {
+ labelDefinition.copyScores.add(ProjectConfig.KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE);
+ }
+ }
+
+ static void applyCopyScoresTo(Collection<String> copyScores, LabelType labelType) {
+ labelType.setCopyMinScore(copyScores.contains(ProjectConfig.KEY_COPY_MIN_SCORE));
+
+ labelType.setCopyMaxScore(copyScores.contains(ProjectConfig.KEY_COPY_MAX_SCORE));
+
+ labelType.setCopyAllScoresIfNoChange(
+ copyScores.contains(ProjectConfig.KEY_COPY_ALL_SCORES_IF_NO_CHANGE));
+
+ labelType.setCopyAllScoresIfNoCodeChange(
+ copyScores.contains(ProjectConfig.KEY_COPY_ALL_SCORES_IF_NO_CODE_CHANGE));
+
+ labelType.setCopyAllScoresOnMergeFirstParentUpdate(
+ copyScores.contains(ProjectConfig.KEY_COPY_ALL_SCORES_ON_MERGE_FIRST_PARENT_UPDATE));
+
+ labelType.setCopyAllScoresOnTrivialRebase(
+ copyScores.contains(ProjectConfig.KEY_COPY_ALL_SCORES_ON_TRIVIAL_REBASE));
+ }
+
+ SubmitConfig convertFrom(ProjectState projectState) {
+ SubmitConfig submitConfig = new SubmitConfig();
+ PluginConfig config =
+ pluginConfigFactory.getFromProjectConfigWithInheritance(projectState, pluginName);
+
+ submitConfig.comments.blockIfUnresolvedComments =
+ config.getBoolean(SimpleSubmitRulesConfig.KEY_BLOCK_IF_UNRESOLVED_COMMENTS, false);
+
+ projectState
+ .getLabelTypes()
+ .getLabelTypes()
+ .forEach(
+ labelType -> {
+ extractLabelSettings(labelType, submitConfig);
+ });
+
+ return submitConfig;
+ }
+
+ void applyTo(SubmitConfig inConfig, ProjectState projectState) throws BadRequestException {
+ PluginConfig pluginConfig = pluginConfigFactory.getFromProjectConfig(projectState, pluginName);
+ applyCommentRulesTo(inConfig.comments, pluginConfig);
+ applyLabelsTo(inConfig.labels, projectState.getLabelTypes());
+ }
+
+ private static void applyLabelsTo(
+ Map<String, SubmitConfig.LabelDefinition> labels, LabelTypes config)
+ throws BadRequestException {
+ for (Map.Entry<String, SubmitConfig.LabelDefinition> entry : labels.entrySet()) {
+ String label = entry.getKey();
+ SubmitConfig.LabelDefinition definition = entry.getValue();
+ LabelType labelType = config.byLabel(label);
+
+ if (labelType == null) {
+ throw new BadRequestException(
+ "The label " + label + " does not exist. You can't change its config.");
+ }
+
+ definition.getFunction().ifPresent(labelType::setFunction);
+
+ applyCopyScoresTo(definition.copyScores, labelType);
+ }
+ }
+
+ private static void extractLabelSettings(LabelType labelType, SubmitConfig config) {
+ if (labelType == null) {
+ return;
+ }
+
+ SubmitConfig.LabelDefinition labelDefinition = new SubmitConfig.LabelDefinition();
+ config.labels.put(labelType.getName(), labelDefinition);
+
+ labelDefinition.function = labelType.getFunction().getFunctionName();
+ extractLabelCopyScores(labelType, labelDefinition);
+ }
+
+ private static void applyCommentRulesTo(
+ SubmitConfig.CommentsRules comments, PluginConfig config) {
+ config.setBoolean(
+ SimpleSubmitRulesConfig.KEY_BLOCK_IF_UNRESOLVED_COMMENTS,
+ comments.blockIfUnresolvedComments);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/SubmitConfig.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/SubmitConfig.java
new file mode 100644
index 0000000..20712a9
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/SubmitConfig.java
@@ -0,0 +1,65 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.config;
+
+import com.google.common.base.MoreObjects;
+import com.google.gerrit.common.data.LabelFunction;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+public class SubmitConfig {
+ public Map<String, LabelDefinition> labels = new HashMap<>();
+ public CommentsRules comments = new CommentsRules();
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("labels", labels)
+ .add("comments", comments)
+ .toString();
+ }
+
+ static class LabelDefinition {
+ String function;
+ boolean ignoreSelfApproval;
+ Set<String> copyScores;
+
+ Optional<LabelFunction> getFunction() {
+ return LabelFunction.parse(function);
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("function", function)
+ .add("ignoreSelfApproval", ignoreSelfApproval)
+ .add("copyScores", copyScores)
+ .toString();
+ }
+ }
+
+ static class CommentsRules {
+ boolean blockIfUnresolvedComments = false;
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("blockIfUnresolvedComments", blockIfUnresolvedComments)
+ .toString();
+ }
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRule.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRule.java
new file mode 100644
index 0000000..6712782
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRule.java
@@ -0,0 +1,81 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.rules;
+
+import com.google.common.collect.ImmutableList;
+import com.google.gerrit.common.data.SubmitRecord;
+import com.google.gerrit.common.data.SubmitRecord.Status;
+import com.google.gerrit.common.data.SubmitRequirement;
+import com.google.gerrit.server.config.PluginConfig;
+import com.google.gerrit.server.project.SubmitRuleOptions;
+import com.google.gerrit.server.query.change.ChangeData;
+import com.google.gerrit.server.rules.SubmitRule;
+import com.google.gwtorm.server.OrmException;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesConfig;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesModule;
+import java.util.Collection;
+import java.util.Collections;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Simple rule: block submission when unresolved comments are present. */
+public class NoUnresolvedCommentsRule implements SubmitRule {
+ private static final Logger log = LoggerFactory.getLogger(NoUnresolvedCommentsRule.class);
+ private static final SubmitRequirement REQUIREMENT =
+ SubmitRequirement.builder()
+ .setType("unresolved_comments")
+ .setFallbackText("Resolve all comments")
+ .build();
+ private final SimpleSubmitRulesModule plugin;
+
+ @Inject
+ public NoUnresolvedCommentsRule(SimpleSubmitRulesModule plugin) {
+ this.plugin = plugin;
+ }
+
+ @Override
+ public Collection<SubmitRecord> evaluate(ChangeData cd, SubmitRuleOptions options) {
+ PluginConfig config = plugin.getConfig(cd);
+ boolean blockIfUnresolvedComments =
+ config.getBoolean(SimpleSubmitRulesConfig.KEY_BLOCK_IF_UNRESOLVED_COMMENTS, false);
+
+ if (!blockIfUnresolvedComments) {
+ return Collections.emptyList();
+ }
+
+ Integer unresolvedComments;
+ try {
+ unresolvedComments = cd.unresolvedCommentCount();
+ } catch (OrmException e) {
+ log.error("Error when counting unresolved comments for change {}", cd.getId(), e);
+
+ SubmitRecord sr = new SubmitRecord();
+ sr.status = Status.RULE_ERROR;
+ sr.errorMessage = "Error when counting unresolved comments";
+ return ImmutableList.of(sr);
+ }
+
+ SubmitRecord sr = new SubmitRecord();
+ sr.requirements = Collections.singletonList(REQUIREMENT);
+ if (unresolvedComments == null || unresolvedComments > 0) {
+ sr.status = Status.NOT_READY;
+ } else {
+ sr.status = Status.OK;
+ }
+
+ return ImmutableList.of(sr);
+ }
+}
diff --git a/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRule.java b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRule.java
new file mode 100644
index 0000000..648c71b
--- /dev/null
+++ b/src/main/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRule.java
@@ -0,0 +1,139 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.rules;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gerrit.common.data.LabelFunction;
+import com.google.gerrit.common.data.LabelType;
+import com.google.gerrit.common.data.SubmitRecord;
+import com.google.gerrit.reviewdb.client.Account;
+import com.google.gerrit.reviewdb.client.PatchSetApproval;
+import com.google.gerrit.server.project.ProjectCache;
+import com.google.gerrit.server.project.ProjectConfig;
+import com.google.gerrit.server.project.ProjectState;
+import com.google.gerrit.server.project.SubmitRuleOptions;
+import com.google.gerrit.server.query.change.ChangeData;
+import com.google.gerrit.server.rules.SubmitRule;
+import com.google.gwtorm.server.OrmException;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesConfig;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.eclipse.jgit.lib.Config;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Simple rule: require a non-author approval or block submission */
+public class RequireNonAuthorApprovalRule implements SubmitRule {
+ private static final Logger log = LoggerFactory.getLogger(RequireNonAuthorApprovalRule.class);
+ private static final String E_UNABLE_TO_FETCH_CHANGE_OWNER = "Unable to fetch the change owner";
+ private static final String E_UNABLE_TO_FETCH_LABELS =
+ "Unable to fetch labels and approvals for the change";
+ private final ProjectCache projectCache;
+
+ @Inject
+ public RequireNonAuthorApprovalRule(ProjectCache projectCache) {
+ this.projectCache = projectCache;
+ }
+
+ @Override
+ public Collection<SubmitRecord> evaluate(ChangeData cd, SubmitRuleOptions options) {
+ ProjectState projectState = projectCache.get(cd.project());
+ Config config = projectState.getConfig(ProjectConfig.PROJECT_CONFIG).getWithInheritance();
+
+ Account.Id owner;
+ try {
+ owner = cd.change().getOwner();
+ } catch (OrmException e) {
+ log.error(E_UNABLE_TO_FETCH_CHANGE_OWNER, e);
+
+ SubmitRecord submitRecord = new SubmitRecord();
+ submitRecord.errorMessage = E_UNABLE_TO_FETCH_CHANGE_OWNER;
+ submitRecord.status = SubmitRecord.Status.RULE_ERROR;
+ return Collections.singletonList(submitRecord);
+ }
+
+ List<LabelType> labelTypes;
+ List<PatchSetApproval> approvals;
+ try {
+ labelTypes = cd.getLabelTypes().getLabelTypes();
+ approvals = cd.currentApprovals();
+ } catch (OrmException e) {
+ log.error(E_UNABLE_TO_FETCH_LABELS, e);
+
+ SubmitRecord submitRecord = new SubmitRecord();
+ submitRecord.errorMessage = E_UNABLE_TO_FETCH_LABELS;
+ submitRecord.status = SubmitRecord.Status.RULE_ERROR;
+
+ return Collections.singletonList(submitRecord);
+ }
+
+ SubmitRecord submitRecord = new SubmitRecord();
+ submitRecord.status = SubmitRecord.Status.OK;
+ submitRecord.labels = new ArrayList<>(labelTypes.size());
+
+ for (LabelType t : labelTypes) {
+ if (!config.getBoolean(
+ t.getName(), SimpleSubmitRulesConfig.KEY_REQUIRE_NON_AUTHOR_APPROVAL, false)) {
+ // The default rules are enough in this case.
+ continue;
+ }
+
+ LabelFunction labelFunction = t.getFunction();
+ if (labelFunction == null) {
+ continue;
+ }
+
+ Collection<PatchSetApproval> approvalsForLabel = getApprovalsForLabel(approvals, t, owner);
+ SubmitRecord.Label label = labelFunction.check(t, approvalsForLabel);
+
+ switch (label.status) {
+ case OK:
+ case MAY:
+ break;
+
+ case NEED:
+ case REJECT:
+ case IMPOSSIBLE:
+ submitRecord.labels.add(label);
+ submitRecord.status = SubmitRecord.Status.NOT_READY;
+ break;
+ }
+ }
+
+ if (submitRecord.labels.isEmpty()) {
+ return Collections.emptyList();
+ }
+
+ return Collections.singletonList(submitRecord);
+ }
+
+ /**
+ * Returns the approvals for a given label, for everyone except from `user`, except if the vote is
+ * negative.
+ */
+ @VisibleForTesting
+ static Collection<PatchSetApproval> getApprovalsForLabel(
+ Collection<PatchSetApproval> approvals, LabelType t, Account.Id user) {
+ return approvals
+ .stream()
+ .filter(input -> input.getValue() < 0 || !input.getAccountId().equals(user))
+ .filter(input -> input.getLabel().equals(t.getLabelId().get()))
+ .collect(Collectors.toList());
+ }
+}
diff --git a/src/main/resources/Documentation/about.md b/src/main/resources/Documentation/about.md
new file mode 100644
index 0000000..574a427
--- /dev/null
+++ b/src/main/resources/Documentation/about.md
@@ -0,0 +1,105 @@
+This plugin provides simple-to-use submit rules, hence the name.
+
+## Features
+- REST API to configure the options and labels.
+- Ability to prevent submission if there are unresolved comments.
+- Ability to require approval, and to consider approval from the change author or not.
+- (soon!) a simple PolyGerrit UI to configure the labels and how they work.
+
+### Inheritance
+This plugin supports configuration inheritance, following a worst case scenario when this is
+possible. That is, children projects can't use weaker options that their parents.
+
+The REST API provides a view of the configuration including inheritance.
+The PUT method only changes the current project's configuration.
+
+The Copy Scores are handled by Core Gerrit.
+
+## The REST API
+This plugin exposes a REST API to configure the labels and simple rules. It is available via the
+following endpoints:
+
+Anonymously: `@URL@projects/ProjectName/simple-submit-rules`
+
+Authenticated: `@URL@a/projects/ProjectName/simple-submit-rules`
+
+The authenticated endpoint uses the default Gerrit authentication and permissions systems.
+
+The `READ_CONFIG` permission is required to access the configuration.
+
+The `WRITE_CONFIG` permission is required to make changes to the configuration.
+
+The project name in the URI must be urlencoded if it contains special characters like a slash.
+This follows the current conventions used in Gerrit.
+
+This endpoint is available using two HTTP methods: `GET` and `PUT`.
+
+The GET request serves a JSON response with the current settings. The scheme used in this response
+is the same used for the PUT request body, so it will only be described once.
+
+## Schema
+
+```
+{
+ "comments": CommentsRules,
+ "labels": {
+ "Verified": LabelDefinition,
+ "Code-Review": LabelDefinition
+ }
+}
+```
+
+The comments section defines the rules to apply to comments (can the change be submitted with
+unresolved comments, …). The labels section defines each label.
+
+It is reasonable to consider that a label missing from the labels section won't be reset, but
+consumers should not rely upon it.
+
+### CommentsRules
+
+```
+{
+ "block-if-unresolved-comments": boolean
+}
+```
+
+When block-if-unresolved-comments is set to true, a Change with unresolved comments CAN'T be
+submitted.
+
+### LabelDefinition
+
+```
+{
+ "function": LabelFunction,
+ "ignore-self-approval": boolean,
+ "copy-scores": CopyScoreRule[]
+}
+```
+
+The LabelFunction specifies the behavior to use for this label.
+It allows marking a label as mandatory, and defines if negative votes are blocking or not.
+The list of functions is defined under.
+
+When ignore-self-approval is set, the change author can't vote to approve their own change.
+
+The copy-scores list defines under what circumstances the votes (for this specific label) should be
+kept. The list of rules is defined below.
+
+
+### CopyScoreRule
+CopyScoreRule value is an enum value, encoded as a string.
+
+Each rule defines a behavior when a change is updated.
+
+The possible options are: `copy-min-score`, `copy-max-score`, `copy-all-scores-if-no-change`
+`copy-all-scores-if-no-code-change`, `copy-all-scores-on-merge-commit-first-parent-update`, and
+`copy-all-scores-on-trivial-rebase`
+
+See the Labels documentation page for more information.
+
+### LabelFunction
+The LabelFunction is an enum value, encoded as a string.
+
+Example: `MaxWithBlock`, `AnyWithBlock`...
+
+See the Labels documentation page for more information.
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/AbstractSimpleSubmitRulesIT.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/AbstractSimpleSubmitRulesIT.java
new file mode 100644
index 0000000..d1f4f45
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/AbstractSimpleSubmitRulesIT.java
@@ -0,0 +1,63 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules;
+
+import com.google.gerrit.acceptance.GitUtil;
+import com.google.gerrit.acceptance.LightweightPluginDaemonTest;
+import com.google.gerrit.acceptance.PushOneCommit;
+import com.google.gerrit.acceptance.TestPlugin;
+import com.google.gerrit.reviewdb.client.RefNames;
+import com.google.gerrit.server.project.ProjectConfig;
+import java.util.function.Consumer;
+import org.eclipse.jgit.internal.storage.dfs.InMemoryRepository;
+import org.eclipse.jgit.junit.TestRepository;
+import org.eclipse.jgit.lib.Config;
+import org.junit.Ignore;
+
+@TestPlugin(
+ name = SimpleSubmitRulesModule.PLUGIN_NAME,
+ sysModule = "com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesModule"
+)
+@Ignore
+/** Base class used by IT tests, loads the Simple Submit Rules plugin. */
+public abstract class AbstractSimpleSubmitRulesIT extends LightweightPluginDaemonTest {
+ /** Helper method to change the project.config file using a provided consumer. */
+ protected void changeProjectConfig(Consumer<Config> callback) throws Exception {
+ TestRepository<InMemoryRepository> projectRepo = cloneProject(project, admin);
+ // Fetch permission ref
+ GitUtil.fetch(projectRepo, "refs/meta/config:cfg");
+ projectRepo.reset("cfg");
+
+ String rawConfig =
+ gApi.projects()
+ .name(project.get())
+ .branch(RefNames.REFS_CONFIG)
+ .file(ProjectConfig.PROJECT_CONFIG)
+ .asString();
+
+ Config config = new Config();
+ config.fromText(rawConfig);
+
+ // Apply our custom function to the config
+ callback.accept(config);
+
+ rawConfig = config.toText();
+
+ PushOneCommit push =
+ pushFactory.create(
+ db, admin.getIdent(), projectRepo, "Subject", ProjectConfig.PROJECT_CONFIG, rawConfig);
+ push.to(RefNames.REFS_CONFIG).assertOkStatus();
+ }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServletIT.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServletIT.java
new file mode 100644
index 0000000..6b1e2ba
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigServletIT.java
@@ -0,0 +1,92 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.config;
+
+import static com.google.gerrit.server.project.testing.Util.value;
+
+import com.google.common.base.Charsets;
+import com.google.gerrit.acceptance.RestResponse;
+import com.google.gerrit.common.RawInputUtil;
+import com.google.gerrit.common.data.LabelFunction;
+import com.google.gerrit.extensions.restapi.RawInput;
+import com.google.gerrit.reviewdb.client.Project.NameKey;
+import com.googlesource.gerrit.plugins.simplesubmitrules.AbstractSimpleSubmitRulesIT;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ConfigServletIT extends AbstractSimpleSubmitRulesIT {
+ @Before
+ public void setUp() throws Exception {
+ configLabel(
+ project,
+ "Code-Review",
+ LabelFunction.MAX_WITH_BLOCK,
+ value(1, "Passes"),
+ value(0, "No score"),
+ value(-1, "Failed"));
+ }
+
+ @Test
+ public void adminCanFetchConfig() throws Exception {
+ RestResponse r = adminRestSession.getJsonAccept(endpointUrl(project));
+ r.assertOK();
+ }
+
+ @Test
+ public void adminCanModifyConfig() throws Exception {
+ RawInput rawInput = createConfig();
+ RestResponse r = adminRestSession.putRaw(endpointUrl(project), rawInput);
+ r.assertOK();
+ }
+
+ @Test
+ public void userCanNotFetchConfig() throws Exception {
+ RestResponse r = userRestSession.getJsonAccept(endpointUrl(project));
+ r.assertForbidden();
+ }
+
+ @Test
+ public void userCanNotModifyConfig() throws Exception {
+ RawInput rawInput = createConfig();
+ RestResponse r = userRestSession.putRaw(endpointUrl(project), rawInput);
+ r.assertForbidden();
+ }
+
+ private static RawInput createConfig() {
+ return RawInputUtil.create(
+ ("{\n"
+ + " \"labels\": {\n"
+ + " \"Code-Review\": {\n"
+ + " \"function\": \"MaxWithBlock\",\n"
+ + " \"ignore_self_approval\": false,\n"
+ + " \"copy_scores\": [\n"
+ + " \"copyAllScoresIfNoChange\",\n"
+ + " \"copyMinScore\",\n"
+ + " \"copyAllScoresOnTrivialRebase\"\n"
+ + " ]\n"
+ + " }\n"
+ + " },\n"
+ + " \"comments\": {\n"
+ + " \"block_if_unresolved_comments\": true\n"
+ + " }\n"
+ + "}")
+ .getBytes(Charsets.UTF_8),
+ "application/json");
+ }
+
+ private static String endpointUrl(NameKey project) {
+ return "/projects/" + project.get() + "/simple-submit-rules";
+ }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslatorTest.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslatorTest.java
new file mode 100644
index 0000000..f3b95ca
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/config/ConfigTranslatorTest.java
@@ -0,0 +1,109 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.config;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.ImmutableList;
+import com.google.gerrit.common.data.LabelType;
+import com.googlesource.gerrit.plugins.simplesubmitrules.config.SubmitConfig.LabelDefinition;
+import java.util.function.BiConsumer;
+import java.util.function.Predicate;
+import org.junit.Test;
+
+public class ConfigTranslatorTest {
+ /** Test the translations for each config key */
+ @Test
+ public void checkLabelTranslation() {
+ checkTranslation("copyMinScore", LabelType::isCopyMinScore, LabelType::setCopyMinScore);
+ checkTranslation("copyMaxScore", LabelType::isCopyMaxScore, LabelType::setCopyMaxScore);
+
+ checkTranslation(
+ "copyAllScoresIfNoChange",
+ LabelType::isCopyAllScoresIfNoChange,
+ LabelType::setCopyAllScoresIfNoChange);
+
+ checkTranslation(
+ "copyAllScoresIfNoCodeChange",
+ LabelType::isCopyAllScoresIfNoCodeChange,
+ LabelType::setCopyAllScoresIfNoCodeChange);
+
+ checkTranslation(
+ "copyAllScoresOnMergeFirstParentUpdate",
+ LabelType::isCopyAllScoresOnMergeFirstParentUpdate,
+ LabelType::setCopyAllScoresOnMergeFirstParentUpdate);
+
+ checkTranslation(
+ "copyAllScoresOnTrivialRebase",
+ LabelType::isCopyAllScoresOnTrivialRebase,
+ LabelType::setCopyAllScoresOnTrivialRebase);
+ }
+
+ /** Helper method to check that conversion from/to Gerrit works for both true and false values */
+ private static void checkTranslation(
+ String copyScoreName,
+ Predicate<LabelType> functionToCheck,
+ BiConsumer<LabelType, Boolean> functionToSet) {
+ checkLabelToGerritPresent(copyScoreName, functionToCheck);
+ checkLabelToGerritAbsent(copyScoreName, functionToCheck);
+
+ checkLabelFromGerritPresent(copyScoreName, functionToSet);
+ checkLabelFromGerritAbsent(copyScoreName, functionToSet);
+ }
+
+ private static void checkLabelFromGerritPresent(
+ String copyScoreName, BiConsumer<LabelType, Boolean> functionToSet) {
+
+ LabelType label = LabelType.withDefaultValues("Verified");
+ LabelDefinition labelDefinition = new SubmitConfig.LabelDefinition();
+
+ functionToSet.accept(label, false);
+ ConfigTranslator.extractLabelCopyScores(label, labelDefinition);
+
+ assertThat(labelDefinition.copyScores)
+ .named("[case %s:false]", copyScoreName)
+ .doesNotContain(copyScoreName);
+ }
+
+ private static void checkLabelFromGerritAbsent(
+ String copyScoreName, BiConsumer<LabelType, Boolean> functionToSet) {
+
+ LabelType label = LabelType.withDefaultValues("Verified");
+ LabelDefinition labelDefinition = new SubmitConfig.LabelDefinition();
+
+ functionToSet.accept(label, true);
+ ConfigTranslator.extractLabelCopyScores(label, labelDefinition);
+
+ assertThat(labelDefinition.copyScores)
+ .named("[case %s:true]", copyScoreName)
+ .contains(copyScoreName);
+ }
+
+ private static void checkLabelToGerritPresent(
+ String copyScoreName, Predicate<LabelType> functionToCheck) {
+ LabelType label = LabelType.withDefaultValues("Verified");
+
+ ConfigTranslator.applyCopyScoresTo(ImmutableList.of(copyScoreName), label);
+ assertThat(functionToCheck.test(label)).named("[case %s:true]", copyScoreName).isTrue();
+ }
+
+ private static void checkLabelToGerritAbsent(
+ String copyScoreName, Predicate<LabelType> functionToCheck) {
+ LabelType label = LabelType.withDefaultValues("Verified");
+
+ ConfigTranslator.applyCopyScoresTo(ImmutableList.of(), label);
+ assertThat(functionToCheck.test(label)).named("[case %s:false]", copyScoreName).isFalse();
+ }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRuleIT.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRuleIT.java
new file mode 100644
index 0000000..3ae48f1
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/NoUnresolvedCommentsRuleIT.java
@@ -0,0 +1,131 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.rules;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.gerrit.acceptance.NoHttpd;
+import com.google.gerrit.acceptance.PushOneCommit;
+import com.google.gerrit.common.data.SubmitRecord;
+import com.google.gerrit.extensions.api.changes.ReviewInput;
+import com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput;
+import com.google.gerrit.extensions.client.Side;
+import com.google.gerrit.server.project.SubmitRuleOptions;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.AbstractSimpleSubmitRulesIT;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesConfig;
+import java.util.Collection;
+import org.junit.Before;
+import org.junit.Test;
+
+@NoHttpd
+public class NoUnresolvedCommentsRuleIT extends AbstractSimpleSubmitRulesIT {
+ private static final String FILENAME = "my.file";
+ @Inject private NoUnresolvedCommentsRule rule;
+
+ @Before
+ public void enableRuleBeforeTest() throws Exception {
+ enableRule(true);
+ }
+
+ @Test
+ public void blocksWithUnresolvedComments() throws Exception {
+ CommentInput comment = newFileComment();
+ comment.unresolved = true;
+ PushOneCommit.Result r = createChangeWithComment(comment);
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(r.getChange(), SubmitRuleOptions.defaults());
+
+ assertThat(submitRecords).hasSize(1);
+ SubmitRecord result = submitRecords.iterator().next();
+ assertThat(result.status).isEqualTo(SubmitRecord.Status.NOT_READY);
+ assertThat(result.labels).isNull();
+ assertThat(result.requirements).hasSize(1);
+ }
+
+ @Test
+ public void doesNotBlockWithNoComments() throws Exception {
+ CommentInput comment = newFileComment();
+ comment.unresolved = false;
+ PushOneCommit.Result r = createChangeWithComment(comment);
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(r.getChange(), SubmitRuleOptions.defaults());
+
+ assertThat(submitRecords).hasSize(1);
+ SubmitRecord result = submitRecords.iterator().next();
+ assertThat(result.status).isEqualTo(SubmitRecord.Status.OK);
+ assertThat(result.labels).isNull();
+ assertThat(result.requirements).hasSize(1);
+ }
+
+ @Test
+ public void doesNotBlockWithOnlyResolvedComments() throws Exception {
+ PushOneCommit.Result change = createChange("refs/for/master");
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(change.getChange(), SubmitRuleOptions.defaults());
+
+ assertThat(submitRecords).hasSize(1);
+ SubmitRecord result = submitRecords.iterator().next();
+ assertThat(result.status).isEqualTo(SubmitRecord.Status.OK);
+ assertThat(result.labels).isNull();
+ assertThat(result.requirements).hasSize(1);
+ }
+
+ @Test
+ public void doesNothingByDefault() throws Exception {
+ CommentInput comment = newFileComment();
+ comment.unresolved = true;
+
+ PushOneCommit.Result r = createChangeWithComment(comment);
+
+ enableRule(false);
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(r.getChange(), SubmitRuleOptions.defaults());
+ assertThat(submitRecords).isEmpty();
+ }
+
+ private PushOneCommit.Result createChangeWithComment(CommentInput comment) throws Exception {
+ PushOneCommit.Result r = createChange("My change", FILENAME, "new content");
+ ReviewInput reviewInput = new ReviewInput();
+ reviewInput.comments = ImmutableMap.of(comment.path, ImmutableList.of(comment));
+ revision(r).review(reviewInput);
+
+ return r;
+ }
+
+ private void enableRule(boolean newState) throws Exception {
+ changeProjectConfig(
+ config ->
+ config.setBoolean(
+ "plugin",
+ plugin.getName(),
+ SimpleSubmitRulesConfig.KEY_BLOCK_IF_UNRESOLVED_COMMENTS,
+ newState));
+ }
+
+ private static CommentInput newFileComment() {
+ CommentInput c = new CommentInput();
+ c.path = FILENAME;
+ c.side = Side.REVISION;
+ c.message = "nit: double space.";
+ return c;
+ }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleIT.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleIT.java
new file mode 100644
index 0000000..1f989d5
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleIT.java
@@ -0,0 +1,83 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.rules;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import com.google.gerrit.acceptance.NoHttpd;
+import com.google.gerrit.acceptance.PushOneCommit;
+import com.google.gerrit.common.data.SubmitRecord;
+import com.google.gerrit.extensions.api.changes.ReviewInput;
+import com.google.gerrit.server.project.SubmitRuleOptions;
+import com.google.inject.Inject;
+import com.googlesource.gerrit.plugins.simplesubmitrules.AbstractSimpleSubmitRulesIT;
+import com.googlesource.gerrit.plugins.simplesubmitrules.SimpleSubmitRulesConfig;
+import java.util.Collection;
+import org.junit.Before;
+import org.junit.Test;
+
+@NoHttpd
+public class RequireNonAuthorApprovalRuleIT extends AbstractSimpleSubmitRulesIT {
+ private static final String FILENAME = "my.file";
+ @Inject private RequireNonAuthorApprovalRule rule;
+
+ @Before
+ public void enableRuleBeforeTest() throws Exception {
+ enableRule("Code-Review", true);
+ }
+
+ @Test
+ public void blocksWhenAutorIsOnlyApprover() throws Exception {
+ PushOneCommit.Result r = createChangeWithVote(2);
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(r.getChange(), SubmitRuleOptions.defaults());
+
+ assertThat(submitRecords).hasSize(1);
+ SubmitRecord result = submitRecords.iterator().next();
+ assertThat(result.status).isEqualTo(SubmitRecord.Status.NOT_READY);
+ assertThat(result.labels).isNotEmpty();
+ }
+
+ @Test
+ public void doesNothingByDefault() throws Exception {
+ PushOneCommit.Result r = createChangeWithVote(+2);
+
+ enableRule("Code-Review", false);
+
+ Collection<SubmitRecord> submitRecords =
+ rule.evaluate(r.getChange(), SubmitRuleOptions.defaults());
+ assertThat(submitRecords).isEmpty();
+ }
+
+ private PushOneCommit.Result createChangeWithVote(int value) throws Exception {
+ PushOneCommit.Result r = createChange("My change", FILENAME, "new content");
+ ReviewInput reviewInput = new ReviewInput();
+ reviewInput.label("Code-Review", value);
+ revision(r).review(reviewInput);
+
+ return r;
+ }
+
+ private void enableRule(String labelName, boolean newState) throws Exception {
+ changeProjectConfig(
+ config ->
+ config.setBoolean(
+ labelName,
+ null,
+ SimpleSubmitRulesConfig.KEY_REQUIRE_NON_AUTHOR_APPROVAL,
+ newState));
+ }
+}
diff --git a/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleTest.java b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleTest.java
new file mode 100644
index 0000000..b1e0082
--- /dev/null
+++ b/src/test/java/com/googlesource/gerrit/plugins/simplesubmitrules/rules/RequireNonAuthorApprovalRuleTest.java
@@ -0,0 +1,97 @@
+// Copyright (C) 2018 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.googlesource.gerrit.plugins.simplesubmitrules.rules;
+
+import static com.google.common.truth.Truth.assertThat;
+import static com.googlesource.gerrit.plugins.simplesubmitrules.rules.RequireNonAuthorApprovalRule.getApprovalsForLabel;
+
+import com.google.common.collect.ImmutableList;
+import com.google.gerrit.common.data.LabelType;
+import com.google.gerrit.common.data.LabelValue;
+import com.google.gerrit.reviewdb.client.Account;
+import com.google.gerrit.reviewdb.client.Change;
+import com.google.gerrit.reviewdb.client.LabelId;
+import com.google.gerrit.reviewdb.client.PatchSet;
+import com.google.gerrit.reviewdb.client.PatchSet.Id;
+import com.google.gerrit.reviewdb.client.PatchSetApproval;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import org.junit.Test;
+
+public class RequireNonAuthorApprovalRuleTest {
+ private static final Change.Id CHANGE_ID = new Change.Id(100);
+ private static final PatchSet.Id PS_ID = new PatchSet.Id(CHANGE_ID, 1);
+ private static final LabelType VERIFIED = makeLabel("Verified");
+ private static final Account.Id USER1 = makeAccount(100001);
+ private static final Account.Id USER2 = makeAccount(100002);
+
+ @Test
+ public void filtersByLabel() {
+ LabelType codeReview = makeLabel("Code-Review");
+ PatchSetApproval approvalVerified = makeApproval(VERIFIED.getLabelId(), USER1, 2);
+ PatchSetApproval approvalCr = makeApproval(codeReview.getLabelId(), USER1, 2);
+
+ Collection<PatchSetApproval> filteredApprovals =
+ getApprovalsForLabel(ImmutableList.of(approvalVerified, approvalCr), codeReview, USER2);
+
+ assertThat(filteredApprovals).containsExactly(approvalCr);
+ }
+
+ @Test
+ public void filtersVotesFromUser() {
+ PatchSetApproval approvalM2 = makeApproval(VERIFIED.getLabelId(), USER1, -2);
+ PatchSetApproval approvalM1 = makeApproval(VERIFIED.getLabelId(), USER1, -1);
+
+ ImmutableList<PatchSetApproval> approvals =
+ ImmutableList.of(
+ approvalM2,
+ approvalM1,
+ makeApproval(VERIFIED.getLabelId(), USER1, 0),
+ makeApproval(VERIFIED.getLabelId(), USER1, +1),
+ makeApproval(VERIFIED.getLabelId(), USER1, +2));
+
+ Collection<PatchSetApproval> filteredApprovals =
+ getApprovalsForLabel(approvals, VERIFIED, USER1);
+
+ assertThat(filteredApprovals).containsExactly(approvalM1, approvalM2);
+ }
+
+ private static LabelType makeLabel(String labelName) {
+ List<LabelValue> values = new ArrayList<>();
+ // The label text is irrelevant here, only the numerical value is used
+ values.add(new LabelValue((short) -2, "-2"));
+ values.add(new LabelValue((short) -1, "-1"));
+ values.add(new LabelValue((short) 0, "No vote."));
+ values.add(new LabelValue((short) 1, "+1"));
+ values.add(new LabelValue((short) 2, "+2"));
+ return new LabelType(labelName, values);
+ }
+
+ private static PatchSetApproval makeApproval(LabelId labelId, Account.Id accountId, int value) {
+ PatchSetApproval.Key key = makeKey(PS_ID, accountId, labelId);
+ return new PatchSetApproval(key, (short) value, Date.from(Instant.now()));
+ }
+
+ private static PatchSetApproval.Key makeKey(Id psId, Account.Id accountId, LabelId labelId) {
+ return new PatchSetApproval.Key(psId, accountId, labelId);
+ }
+
+ private static Account.Id makeAccount(int account) {
+ return new Account.Id(account);
+ }
+}