Merge "Upgrade soy to 2019-09-03"
diff --git a/.bazelversion b/.bazelversion
index ae6dd4e..8862dba 100644
--- a/.bazelversion
+++ b/.bazelversion
@@ -1 +1 @@
-0.29.0
+1.0.0rc2
diff --git a/Documentation/dev-crafting-changes.txt b/Documentation/dev-crafting-changes.txt
index 76baa8b..02b650a 100644
--- a/Documentation/dev-crafting-changes.txt
+++ b/Documentation/dev-crafting-changes.txt
@@ -115,7 +115,7 @@
 link:https://github.com/google/google-java-format[`google-java-format`]
 tool (version 1.7), and to format Bazel BUILD, WORKSPACE and .bzl files the
 link:https://github.com/bazelbuild/buildtools/tree/master/buildifier[`buildifier`]
-tool (version 0.26.0).
+tool (version 0.28.0).
 These tools automatically apply format according to the style guides; this
 streamlines code review by reducing the need for time-consuming, tedious,
 and contentious discussions about trivial issues like whitespace.
diff --git a/Documentation/pg-plugin-admin-api.txt b/Documentation/pg-plugin-admin-api.txt
index 1c724d0..084fa2c 100644
--- a/Documentation/pg-plugin-admin-api.txt
+++ b/Documentation/pg-plugin-admin-api.txt
@@ -4,7 +4,7 @@
 and provides customization of the admin menu.
 
 == addMenuLink
-`adminApi.addMenuLink(text, url, opt_external)`
+`adminApi.addMenuLink(text, url, opt_external, opt_capabilities)`
 
 Add a new link to the end of the admin navigation menu.
 
diff --git a/WORKSPACE b/WORKSPACE
index 2978175..6f1ee10 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -64,9 +64,14 @@
     urls = ["https://raw.githubusercontent.com/google/closure-compiler/35d2b3340ff23a69441f10fa3bc820691c2942f2/contrib/externs/polymer-1.0.js"],
 )
 
-load("@bazel_skylib//lib:versions.bzl", "versions")
+# Check Bazel version when invoked by Bazel directly
+load("//tools/bzl:bazelisk_version.bzl", "bazelisk_version")
 
-versions.check(minimum_bazel_version = "0.29.0")
+bazelisk_version(name = "bazelisk_version")
+
+load("@bazelisk_version//:check.bzl", "check_bazel_version")
+
+check_bazel_version()
 
 # Rules Python
 http_archive(
@@ -1095,18 +1100,18 @@
     sha1 = "0f5a654e4675769c716e5b387830d19b501ca191",
 )
 
-TESTCONTAINERS_VERSION = "1.12.0"
+TESTCONTAINERS_VERSION = "1.12.1"
 
 maven_jar(
     name = "testcontainers",
     artifact = "org.testcontainers:testcontainers:" + TESTCONTAINERS_VERSION,
-    sha1 = "ac89643ce1ddde504da09172086aba0c7df10bff",
+    sha1 = "1dc8666ead914c5515d087f75ffe92629414caf6",
 )
 
 maven_jar(
     name = "testcontainers-elasticsearch",
     artifact = "org.testcontainers:elasticsearch:" + TESTCONTAINERS_VERSION,
-    sha1 = "cd9020f1803396c45ef935312bf232f9b17332b0",
+    sha1 = "2491f792627a1f15d341bfcd6dd0ea7e3541d82f",
 )
 
 maven_jar(
diff --git a/contrib/remove-notedb-refs.sh b/contrib/remove-notedb-refs.sh
new file mode 100755
index 0000000..3c13067
--- /dev/null
+++ b/contrib/remove-notedb-refs.sh
@@ -0,0 +1,56 @@
+# Copyright (C) 2019 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.
+#!/usr/bin/env bash
+
+set -e
+
+if [[ "$#" -lt "2" ]] ; then
+  cat <<EOF
+Usage: run "$0 /path/to/git/dir [project...]" or "$0 /path/to/git/dir ALL"
+
+This util script can be used in case of rollback to ReviewDB during an unsuccessful
+migration to NoteDB or simply while testing the migration process.
+
+It will remove all the refs used by NoteDB added during the migration (i.e.: change meta refs and sequence ref).
+EOF
+  exit 1
+fi
+
+GERRIT_GIT_DIR=$1
+shift
+
+ALL_PROJECTS=$@
+if [[ "$2" -eq "ALL" ]] ; then
+ ALL_PROJECTS=`find "${GERRIT_GIT_DIR}" -type d -name "*.git"`
+fi
+
+ALL_PROJECTS_ARRAY=(${ALL_PROJECTS// / })
+
+for project in "${ALL_PROJECTS_ARRAY[@]}"
+do
+    if [[ "$project" =~ /All-Users\.git$ ]]; then
+        echo "Skipping $project ..."
+    else
+        echo "Removing meta ref for $project ..."
+        cd "$project"
+        if `git show-ref meta | grep -q "/meta$"`; then
+            git show-ref meta | grep "/meta$" | cut -d' ' -f2 | xargs -L1 git update-ref -d
+        fi
+    fi
+done
+
+echo "Remove sequence ref"
+allProjectDir="$GERRIT_GIT_DIR/All-Projects.git"
+cd $allProjectDir
+git update-ref -d refs/sequences/changes
diff --git a/java/com/google/gerrit/extensions/BUILD b/java/com/google/gerrit/extensions/BUILD
index b46b9cc..0022584 100644
--- a/java/com/google/gerrit/extensions/BUILD
+++ b/java/com/google/gerrit/extensions/BUILD
@@ -1,6 +1,6 @@
 load("@rules_java//java:defs.bzl", "java_binary", "java_library")
-load("//lib/jgit:jgit.bzl", "JGIT_DOC_URL")
 load("//lib:guava.bzl", "GUAVA_DOC_URL")
+load("//lib/jgit:jgit.bzl", "JGIT_DOC_URL")
 load("//tools/bzl:javadoc.bzl", "java_doc")
 
 java_binary(
diff --git a/java/com/google/gerrit/sshd/commands/FlushCaches.java b/java/com/google/gerrit/sshd/commands/FlushCaches.java
index df56cf4..98562b0 100644
--- a/java/com/google/gerrit/sshd/commands/FlushCaches.java
+++ b/java/com/google/gerrit/sshd/commands/FlushCaches.java
@@ -89,7 +89,8 @@
   @SuppressWarnings("unchecked")
   private void doList() {
     for (String name :
-        (List<String>) listCaches.setFormat(OutputFormat.LIST).apply(new ConfigResource())) {
+        (List<String>)
+            listCaches.setFormat(OutputFormat.LIST).apply(new ConfigResource()).value()) {
       stderr.print(name);
       stderr.print('\n');
     }
diff --git a/java/com/google/gerrit/sshd/commands/ShowCaches.java b/java/com/google/gerrit/sshd/commands/ShowCaches.java
index c19e790..3c617b0 100644
--- a/java/com/google/gerrit/sshd/commands/ShowCaches.java
+++ b/java/com/google/gerrit/sshd/commands/ShowCaches.java
@@ -194,7 +194,8 @@
 
   private Collection<CacheInfo> getCaches() {
     @SuppressWarnings("unchecked")
-    Map<String, CacheInfo> caches = (Map<String, CacheInfo>) listCaches.apply(new ConfigResource());
+    Map<String, CacheInfo> caches =
+        (Map<String, CacheInfo>) listCaches.apply(new ConfigResource()).value();
     for (Map.Entry<String, CacheInfo> entry : caches.entrySet()) {
       CacheInfo cache = entry.getValue();
       cache.name = entry.getKey();
diff --git a/lib/prolog/BUILD b/lib/prolog/BUILD
index 6ae4434..fa55682 100644
--- a/lib/prolog/BUILD
+++ b/lib/prolog/BUILD
@@ -44,14 +44,14 @@
 
 java_binary(
     name = "compiler-bin",
-    main_class = "BuckPrologCompiler",
+    main_class = "BazelPrologCompiler",
     visibility = ["//visibility:public"],
     runtime_deps = [":compiler-lib"],
 )
 
 java_library(
     name = "compiler-lib",
-    srcs = ["java/BuckPrologCompiler.java"],
+    srcs = ["java/BazelPrologCompiler.java"],
     visibility = ["//visibility:public"],
     deps = [
         ":compiler",
diff --git a/lib/prolog/java/BuckPrologCompiler.java b/lib/prolog/java/BazelPrologCompiler.java
similarity index 98%
rename from lib/prolog/java/BuckPrologCompiler.java
rename to lib/prolog/java/BazelPrologCompiler.java
index cc3e39e..37ea696 100644
--- a/lib/prolog/java/BuckPrologCompiler.java
+++ b/lib/prolog/java/BazelPrologCompiler.java
@@ -21,7 +21,7 @@
 import java.util.jar.JarEntry;
 import java.util.jar.JarOutputStream;
 
-public class BuckPrologCompiler {
+public class BazelPrologCompiler {
   private static File tmpdir;
 
   public static void main(String[] argv) throws IOException, CompileException {
diff --git a/plugins/replication b/plugins/replication
index 6f8b012..f5ebcbc 160000
--- a/plugins/replication
+++ b/plugins/replication
@@ -1 +1 @@
-Subproject commit 6f8b01263df591dbfef8e3052fd572edb35924cf
+Subproject commit f5ebcbcc93c4364f01a78a77d3b8741d0930d796
diff --git a/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior.html b/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior.html
index db11937..182d242 100644
--- a/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior.html
+++ b/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior.html
@@ -18,8 +18,6 @@
 (function(window) {
   'use strict';
 
-  const ACCOUNT_CAPABILITIES = ['createProject', 'createGroup', 'viewPlugins'];
-
   const ADMIN_LINKS = [{
     name: 'Repositories',
     noBaseUrl: true,
@@ -65,7 +63,7 @@
         return Promise.resolve(this._filterLinks(link => link.viewableToAll,
             getAdminMenuLinks, opt_options));
       }
-      return getAccountCapabilities(ACCOUNT_CAPABILITIES)
+      return getAccountCapabilities()
           .then(capabilities => {
             return this._filterLinks(link => {
               return !link.capability ||
@@ -97,9 +95,10 @@
       links.push(...getAdminMenuLinks().map(link => ({
         url: link.url,
         name: link.text,
+        capability: link.capability || null,
         noBaseUrl: !isExernalLink(link),
         view: null,
-        viewableToAll: true,
+        viewableToAll: !link.capability,
         target: isExernalLink(link) ? '_blank' : null,
       })));
 
diff --git a/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior_test.html b/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior_test.html
index 60817aa..f1e28d1 100644
--- a/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior_test.html
+++ b/polygerrit-ui/app/behaviors/gr-admin-nav-behavior/gr-admin-nav-behavior_test.html
@@ -310,5 +310,61 @@
         testAdminLinks(account, options, expected, done);
       });
     });
+
+
+    suite('view plugin screen with plugin capability', () => {
+      const account = {
+        name: 'test-user',
+      };
+      let expected;
+
+      setup(() => {
+        capabilityStub.returns(Promise.resolve({pluginCapability: true}));
+        expected = {};
+      });
+
+      test('with plugin with capabilities', done => {
+        let options;
+        const generatedLinks = [
+          {text: 'without capability', url: '/without'},
+          {text: 'with capability', url: '/with', capability: 'pluginCapability'},
+        ];
+        menuLinkStub.returns(generatedLinks);
+        expected = Object.assign(expected, {
+          totalLength: 4,
+          pluginGeneratedLinks: generatedLinks,
+        });
+        testAdminLinks(account, options, expected, done);
+      });
+    });
+
+
+    suite('view plugin screen without plugin capability', () => {
+      const account = {
+        name: 'test-user',
+      };
+      let expected;
+
+      setup(() => {
+        capabilityStub.returns(Promise.resolve({}));
+        expected = {};
+      });
+
+      test('with plugin with capabilities', done => {
+        let options;
+        const generatedLinks = [
+          {text: 'without capability', url: '/without'},
+          {text: 'with capability',
+            url: '/with',
+            capability: 'pluginCapability'},
+        ];
+        menuLinkStub.returns(generatedLinks);
+        expected = Object.assign(expected, {
+          totalLength: 3,
+          pluginGeneratedLinks: [generatedLinks[0]],
+        });
+        testAdminLinks(account, options, expected, done);
+      });
+    });
   });
 </script>
diff --git a/polygerrit-ui/app/elements/admin/gr-admin-view/gr-admin-view_test.html b/polygerrit-ui/app/elements/admin/gr-admin-view/gr-admin-view_test.html
index 178d056..984be19 100644
--- a/polygerrit-ui/app/elements/admin/gr-admin-view/gr-admin-view_test.html
+++ b/polygerrit-ui/app/elements/admin/gr-admin-view/gr-admin-view_test.html
@@ -160,6 +160,7 @@
       return element.reload().then(() => {
         assert.equal(element._filteredLinks.length, 3);
         assert.deepEqual(element._filteredLinks[1], {
+          capability: null,
           url: '/internal/link/url',
           name: 'internal link text',
           noBaseUrl: true,
@@ -168,6 +169,7 @@
           target: null,
         });
         assert.deepEqual(element._filteredLinks[2], {
+          capability: null,
           url: 'http://external/link/url',
           name: 'external link text',
           noBaseUrl: false,
diff --git a/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api.js b/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api.js
index 3959186..d1f8e56 100644
--- a/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api.js
+++ b/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api.js
@@ -30,8 +30,8 @@
    * @param {string} text
    * @param {string} url
    */
-  GrAdminApi.prototype.addMenuLink = function(text, url) {
-    this._menuLinks.push({text, url});
+  GrAdminApi.prototype.addMenuLink = function(text, url, opt_capability) {
+    this._menuLinks.push({text, url, capability: opt_capability || null});
   };
 
   GrAdminApi.prototype.getMenuLinks = function() {
diff --git a/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api_test.html b/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api_test.html
index 6883e7e..9cdcf76 100644
--- a/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api_test.html
+++ b/polygerrit-ui/app/elements/plugins/gr-admin-api/gr-admin-api_test.html
@@ -56,7 +56,15 @@
       adminApi.addMenuLink('text', 'url');
       const links = adminApi.getMenuLinks();
       assert.equal(links.length, 1);
-      assert.deepEqual(links[0], {text: 'text', url: 'url'});
+      assert.deepEqual(links[0], {text: 'text', url: 'url', capability: null});
+    });
+
+    test('addMenuLinkWithCapability', () => {
+      adminApi.addMenuLink('text', 'url', 'capability');
+      const links = adminApi.getMenuLinks();
+      assert.equal(links.length, 1);
+      assert.deepEqual(links[0],
+          {text: 'text', url: 'url', capability: 'capability'});
     });
   });
 </script>
diff --git a/tools/BUILD b/tools/BUILD
index c236957..29626d9 100644
--- a/tools/BUILD
+++ b/tools/BUILD
@@ -1,10 +1,10 @@
-load("@rules_python//python:defs.bzl", "py_binary")
-load("@rules_java//java:defs.bzl", "java_package_configuration")
 load(
     "@bazel_tools//tools/jdk:default_java_toolchain.bzl",
     "JDK9_JVM_OPTS",
     "default_java_toolchain",
 )
+load("@rules_java//java:defs.bzl", "java_package_configuration")
+load("@rules_python//python:defs.bzl", "py_binary")
 
 exports_files(["nongoogle.bzl"])
 
diff --git a/tools/bzl/bazelisk_version.bzl b/tools/bzl/bazelisk_version.bzl
new file mode 100644
index 0000000..d8b3d10
--- /dev/null
+++ b/tools/bzl/bazelisk_version.bzl
@@ -0,0 +1,16 @@
+_template = """
+load("@bazel_skylib//lib:versions.bzl", "versions")
+
+def check_bazel_version():
+  versions.check(minimum_bazel_version = "{version}")
+""".strip()
+
+def _impl(repository_ctx):
+    repository_ctx.symlink(Label("@//:.bazelversion"), ".bazelversion")
+    bazelversion = repository_ctx.read(".bazelversion").strip()
+
+    repository_ctx.file("BUILD", executable = False)
+
+    repository_ctx.file("check.bzl", executable = False, content = _template.format(version = bazelversion))
+
+bazelisk_version = repository_rule(implementation = _impl)
diff --git a/tools/bzl/classpath.bzl b/tools/bzl/classpath.bzl
index 0d43be7..3be7a12 100644
--- a/tools/bzl/classpath.bzl
+++ b/tools/bzl/classpath.bzl
@@ -1,10 +1,10 @@
 def _classpath_collector(ctx):
     all = []
     for d in ctx.attr.deps:
-        if hasattr(d, "java"):
-            all.append(d.java.transitive_runtime_deps)
-            if hasattr(d.java.compilation_info, "runtime_classpath"):
-                all.append(d.java.compilation_info.runtime_classpath)
+        if JavaInfo in d:
+            all.append(d[JavaInfo].transitive_runtime_deps)
+            if hasattr(d[JavaInfo].compilation_info, "runtime_classpath"):
+                all.append(d[JavaInfo].compilation_info.runtime_classpath)
         elif hasattr(d, "files"):
             all.append(d.files)
 
diff --git a/tools/bzl/javadoc.bzl b/tools/bzl/javadoc.bzl
index 754bd96..77c2d4a 100644
--- a/tools/bzl/javadoc.bzl
+++ b/tools/bzl/javadoc.bzl
@@ -17,8 +17,11 @@
 def _impl(ctx):
     zip_output = ctx.outputs.zip
 
-    transitive_jars = depset(transitive = [j.java.transitive_deps for j in ctx.attr.libs])
-    source_jars = depset(transitive = [j.java.source_jars for j in ctx.attr.libs])
+    transitive_jars = depset(transitive = [j[JavaInfo].transitive_deps for j in ctx.attr.libs])
+
+    # TODO(davido): Remove list to depset conversion on source_jars, when this issue is fixed:
+    # https://github.com/bazelbuild/bazel/issues/4221
+    source_jars = depset(transitive = [depset(j[JavaInfo].source_jars) for j in ctx.attr.libs])
 
     transitive_jar_paths = [j.path for j in transitive_jars.to_list()]
     dir = ctx.outputs.zip.path + ".dir"
diff --git a/tools/bzl/junit.bzl b/tools/bzl/junit.bzl
index 613efb1..1cf82ea 100644
--- a/tools/bzl/junit.bzl
+++ b/tools/bzl/junit.bzl
@@ -57,7 +57,7 @@
         ctx.attr.outname,
     ))
 
-_GenSuite = rule(
+_gen_suite = rule(
     attrs = {
         "srcs": attr.label_list(allow_files = True),
         "outname": attr.string(),
@@ -75,7 +75,7 @@
 
 def junit_tests(name, srcs, **kwargs):
     s_name = name.replace("-", "_") + "TestSuite"
-    _GenSuite(
+    _gen_suite(
         name = s_name,
         srcs = srcs,
         outname = s_name,
diff --git a/tools/bzl/pkg_war.bzl b/tools/bzl/pkg_war.bzl
index 90dc607..ab753bd 100644
--- a/tools/bzl/pkg_war.bzl
+++ b/tools/bzl/pkg_war.bzl
@@ -102,8 +102,8 @@
     transitive_context_libs = []
     if ctx.attr.context:
         for jar in ctx.attr.context:
-            if hasattr(jar, "java"):
-                transitive_context_libs.append(jar.java.transitive_runtime_deps)
+            if JavaInfo in jar:
+                transitive_context_libs.append(jar[JavaInfo].transitive_runtime_deps)
             elif hasattr(jar, "files"):
                 transitive_context_libs.append(jar.files)