Add class for loading code owner configs from OWNERS files

The find-owners plugin reads code owner configurations from OWNERS files
that are stored in the source branches.

This change adds logic to the find-owners backend that can read such
files. Reading the files is implemented in the CodeOwnerConfigFile class
which is a subclass of VersionedMetaData. On load it reads and parses
the OWNERS file. The parsing is done by CodeOwnersConfigParser. After
the loading is done, callers can access the parsed CodeOwnerConfig.

CodeOwnerConfigFile will also be responsible for creating and updating
OWNERS files, but this part is not implemented yet (this will be done by
follow-up changes).

Since we have now more than one test, we introduce an abstract base
class for all code owner tests so that we do not need to repeat the
@TestPlugin annotation on all the test classes. The abstract base class
will also allow us to have the boilerplate code to instantiate code
owner API classes in a single place, so that not all code onwer tests
need to do this instantiation (this will be done only when the API
classes get implemented).

Signed-off-by: Edwin Kempin <ekempin@google.com>
Change-Id: If4bc673561665119dc06b5cc0896732cb5017523
diff --git a/java/com/google/gerrit/plugins/codeowners/acceptance/AbstractCodeOwnersTest.java b/java/com/google/gerrit/plugins/codeowners/acceptance/AbstractCodeOwnersTest.java
new file mode 100644
index 0000000..5ef2e76
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/acceptance/AbstractCodeOwnersTest.java
@@ -0,0 +1,37 @@
+// Copyright (C) 2020 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.plugins.codeowners.acceptance;
+
+import com.google.gerrit.acceptance.LightweightPluginDaemonTest;
+import com.google.gerrit.acceptance.TestPlugin;
+
+/**
+ * Base class for code owner integration tests.
+ *
+ * <p>There are 2 reasons why we have this base class:
+ *
+ * <ul>
+ *   <li>Hard-coding the {@link TestPlugin} annotation for each test class would be too much
+ *       overhead.
+ *   <li>The code owner API classes cannot be injected into the test classes because the plugin is
+ *       not loaded yet when injections are resolved. Instantiating them will require a bit of
+ *       boilerplate code. We prefer to have this boilerplate code only once here in this base
+ *       class, as having this code in every test class would be too much overhead.
+ * </ul>
+ */
+@TestPlugin(name = "code-owners", sysModule = "com.google.gerrit.plugins.codeowners.Module")
+public class AbstractCodeOwnersTest extends LightweightPluginDaemonTest {
+  // TODO(ekempin): Add code to instantiate the code owner API classes, once they exist.
+}
diff --git a/java/com/google/gerrit/plugins/codeowners/acceptance/BUILD b/java/com/google/gerrit/plugins/codeowners/acceptance/BUILD
new file mode 100644
index 0000000..5cde392
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/acceptance/BUILD
@@ -0,0 +1,16 @@
+load("@rules_java//java:defs.bzl", "java_library")
+
+package(
+    default_testonly = True,
+    default_visibility = ["//plugins/code-owners:visibility"],
+)
+
+java_library(
+    name = "acceptance",
+    srcs = glob(["*.java"]),
+    deps = [
+        "//java/com/google/gerrit/acceptance:lib",
+        "//plugins/code-owners:code-owners__plugin",
+    ],
+)
+
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfig.java b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfig.java
index 7b30f40..7ef5a5b 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfig.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfig.java
@@ -111,6 +111,56 @@
     public abstract Path folderPath();
 
     /**
+     * Gets the project to which the code owner config belongs.
+     *
+     * @return the project to which the code owner config belongs
+     */
+    public Project.NameKey project() {
+      return branch().project();
+    }
+
+    /**
+     * Gets the ref name of the branch to which the code owner config belongs.
+     *
+     * @return the ref name of the branch to which the code owner config belongs
+     */
+    public String ref() {
+      return branch().branch();
+    }
+
+    /**
+     * Gets the path for the given code owner config file name.
+     *
+     * @param codeOwnerConfigFileName the name of the code owner config file for which the path
+     *     should be returned
+     * @return the path for the given file code owner config file name
+     */
+    public Path filePath(String codeOwnerConfigFileName) {
+      return folderPath()
+          .resolve(requireNonNull(codeOwnerConfigFileName, "codeOwnerConfigFileName"));
+    }
+
+    /**
+     * Gets the path for the given code owner config file name as string that can be used for the
+     * jgit API.
+     *
+     * <p>The jgit API doesn't accept leading '/' for absolute paths, so this method makes sure to
+     * remove it.
+     *
+     * @param codeOwnerConfigFileName the name of the code owner config file for which the path
+     *     should be returned
+     * @return the path for the given file code owner config file name as string that can be used
+     *     for the jgit API
+     */
+    public String filePathForJgit(String codeOwnerConfigFileName) {
+      String filePath = filePath(codeOwnerConfigFileName).toString();
+      if (filePath.startsWith("/")) {
+        filePath = filePath.substring(1);
+      }
+      return filePath;
+    }
+
+    /**
      * Creates a code owner config key.
      *
      * @param project the project to which the code owner config belongs
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
new file mode 100644
index 0000000..a332cd9
--- /dev/null
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
@@ -0,0 +1,157 @@
+// Copyright (C) 2020 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.plugins.codeowners.backend.findowners;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.gerrit.extensions.restapi.NotImplementedException;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.gerrit.server.git.meta.VersionedMetaData;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import java.io.IOException;
+import java.util.Optional;
+import java.util.function.Consumer;
+import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.CommitBuilder;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.treewalk.TreeWalk;
+
+/**
+ * A representation of a code owner config that is stored as an {@code OWNERS} file in a source
+ * branch.
+ *
+ * <p>For reading code owner configs, refer to {@link Factory#load(CodeOwnerConfig.Key)}.
+ */
+class CodeOwnerConfigFile extends VersionedMetaData {
+  /** Name of the file in which the code owner config for a folder in a branch is stored. */
+  @VisibleForTesting static final String FILE_NAME = "OWNERS";
+
+  @Singleton
+  static class Factory {
+    private final GitRepositoryManager repoManager;
+    private final CodeOwnerConfigParser codeOwnerConfigParser;
+
+    @Inject
+    Factory(GitRepositoryManager repoManager, CodeOwnerConfigParser codeOwnerConfigParser) {
+      this.repoManager = repoManager;
+      this.codeOwnerConfigParser = codeOwnerConfigParser;
+    }
+
+    /**
+     * Creates a {@link CodeOwnerConfigFile} for a code owner config.
+     *
+     * <p>The code owner config is automatically loaded within this method and can be accessed via
+     * {@link #getLoadedCodeOwnerConfig()}.
+     *
+     * <p>It's safe to call this method for non-existing code owner configs. In that case, {@link
+     * #getLoadedCodeOwnerConfig()} won't return any code owner config. Thus, the existence of a
+     * code owner config can be easily tested.
+     *
+     * @param codeOwnerConfigKey the key of the code owner config
+     * @return a {@link CodeOwnerConfigFile} for the code owner config with the specified key
+     * @throws IOException if the repository can't be accessed for some reason
+     * @throws ConfigInvalidException if the code owner config exists but can't be read due to an
+     *     invalid format
+     */
+    CodeOwnerConfigFile load(CodeOwnerConfig.Key codeOwnerConfigKey)
+        throws IOException, ConfigInvalidException {
+      CodeOwnerConfigFile codeOwnerConfigFile =
+          new CodeOwnerConfigFile(codeOwnerConfigParser, codeOwnerConfigKey);
+      try (Repository repository = repoManager.openRepository(codeOwnerConfigKey.project())) {
+        codeOwnerConfigFile.load(codeOwnerConfigKey.project(), repository);
+      }
+      return codeOwnerConfigFile;
+    }
+  }
+
+  private final CodeOwnerConfigParser codeOwnerConfigParser;
+  private final CodeOwnerConfig.Key codeOwnerConfigKey;
+
+  private boolean isLoaded = false;
+  private Optional<CodeOwnerConfig> loadedCodeOwnersConfig = Optional.empty();
+
+  private CodeOwnerConfigFile(
+      CodeOwnerConfigParser codeOwnerConfigParser, CodeOwnerConfig.Key codeOwnerConfigKey) {
+    this.codeOwnerConfigParser = codeOwnerConfigParser;
+    this.codeOwnerConfigKey = codeOwnerConfigKey;
+  }
+
+  /**
+   * Returns the loaded code owner config if it exists.
+   *
+   * @return the loaded code owner config, or {@link Optional#empty()} if the code owner config
+   *     doesn't exist
+   */
+  public Optional<CodeOwnerConfig> getLoadedCodeOwnerConfig() {
+    checkLoaded();
+
+    return loadedCodeOwnersConfig;
+  }
+
+  @Override
+  protected String getRefName() {
+    return codeOwnerConfigKey.branch().branch();
+  }
+
+  @Override
+  protected void onLoad() throws IOException, ConfigInvalidException {
+    if (revision != null) {
+      loadFileIfItExists(
+          codeOwnerConfigKey.filePathForJgit(FILE_NAME),
+          codeOwnerConfigFileContent ->
+              loadedCodeOwnersConfig =
+                  Optional.of(
+                      codeOwnerConfigParser.parse(codeOwnerConfigKey, codeOwnerConfigFileContent)));
+    }
+
+    isLoaded = true;
+  }
+
+  /**
+   * Loads the file with the given path and invokes the given consumer with the file content.
+   *
+   * <p>No-op if a file with the given path doesn't exist.
+   *
+   * <p>This method allows us to differentiate between a non-existing file ({@code
+   * fileContentConsumer} is not invoked) and an empty file ({@code fileContentConsumer} is invoked
+   * with empty content).
+   *
+   * @param filePath the path of the file that should be loaded
+   * @param fileContentConsumer the consumer for the file content Os
+   */
+  private void loadFileIfItExists(String filePath, Consumer<String> fileContentConsumer)
+      throws IOException {
+    try (TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), filePath, revision.getTree())) {
+      if (tw != null) {
+        fileContentConsumer.accept(readUTF8(filePath));
+      }
+    }
+  }
+
+  @Override
+  protected boolean onSave(CommitBuilder commit) throws IOException, ConfigInvalidException {
+    checkLoaded();
+
+    // TODO(ekempin): Implement this method
+    throw new NotImplementedException();
+  }
+
+  private void checkLoaded() {
+    checkState(isLoaded, "Code owner config %s not loaded yet", codeOwnerConfigKey);
+  }
+}
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfigTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfigTest.java
index 7d24bf7..b2fca90 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfigTest.java
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/CodeOwnerConfigTest.java
@@ -15,11 +15,13 @@
 package com.google.gerrit.plugins.codeowners.backend;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth8.assertThat;
 import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerConfigSubject.assertThat;
 import static com.google.gerrit.testing.GerritJUnit.assertThrows;
 
 import com.google.gerrit.entities.BranchNameKey;
 import com.google.gerrit.entities.Project;
+import com.google.gerrit.entities.RefNames;
 import java.nio.file.Paths;
 import org.junit.Test;
 
@@ -39,6 +41,55 @@
   }
 
   @Test
+  public void getProject() throws Exception {
+    Project.NameKey project = Project.nameKey("project");
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "master", "/foo/bar/");
+    assertThat(codeOwnerConfigKey.project()).isEqualTo(project);
+  }
+
+  @Test
+  public void getRef() throws Exception {
+    String branch = "master";
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(Project.nameKey("project"), branch, "/foo/bar/");
+    assertThat(codeOwnerConfigKey.ref()).isEqualTo(RefNames.REFS_HEADS + branch);
+  }
+
+  @Test
+  public void getFilePath() throws Exception {
+    String folderPath = "/foo/bar/";
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(Project.nameKey("project"), "master", folderPath);
+    assertThat(codeOwnerConfigKey.filePath("OWNERS")).isEqualTo(Paths.get(folderPath, "OWNERS"));
+  }
+
+  @Test
+  public void cannotGetFilePathForNullFileName() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(Project.nameKey("project"), "master", "/foo/bar/");
+    NullPointerException npe =
+        assertThrows(NullPointerException.class, () -> codeOwnerConfigKey.filePath(null));
+    assertThat(npe).hasMessageThat().isEqualTo("codeOwnerConfigFileName");
+  }
+
+  @Test
+  public void getFilePathForJgit() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(Project.nameKey("project"), "master", "/foo/bar/");
+    assertThat(codeOwnerConfigKey.filePathForJgit("OWNERS")).isEqualTo("foo/bar/OWNERS");
+  }
+
+  @Test
+  public void cannotGetFilePathForJgitForNullFileName() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(Project.nameKey("project"), "master", "/foo/bar/");
+    NullPointerException npe =
+        assertThrows(NullPointerException.class, () -> codeOwnerConfigKey.filePathForJgit(null));
+    assertThat(npe).hasMessageThat().isEqualTo("codeOwnerConfigFileName");
+  }
+
+  @Test
   public void addCodeOwners() throws Exception {
     CodeOwnerReference codeOwner1 = CodeOwnerReference.create("jdoe@example.com");
     CodeOwnerReference codeOwner2 = CodeOwnerReference.create("jroe@example.com");
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
index 4ce19e0..b32e5b7 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/BUILD
@@ -5,6 +5,7 @@
     group = "findowners_backend",
     deps = [
         "//plugins/code-owners:code-owners__plugin",
+        "//plugins/code-owners/java/com/google/gerrit/plugins/codeowners/acceptance",
         "//plugins/code-owners/java/com/google/gerrit/plugins/codeowners/testing",
     ],
 )
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java
new file mode 100644
index 0000000..1824b94
--- /dev/null
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFileTest.java
@@ -0,0 +1,95 @@
+// Copyright (C) 2020 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.plugins.codeowners.backend.findowners;
+
+import static com.google.common.truth.Truth8.assertThat;
+import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerConfigSubject.assertThat;
+
+import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import org.eclipse.jgit.junit.TestRepository;
+import org.eclipse.jgit.lib.Repository;
+import org.junit.Before;
+import org.junit.Test;
+
+/** Tests for {@link CodeOwnerConfigFile}. */
+public class CodeOwnerConfigFileTest extends AbstractCodeOwnersTest {
+  private CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory;
+  private CodeOwnerConfigParser codeOwnerConfigParser;
+
+  @Before
+  public void setUpCodeOwnersPlugin() throws Exception {
+    codeOwnerConfigFileFactory =
+        plugin.getSysInjector().getInstance(CodeOwnerConfigFile.Factory.class);
+    codeOwnerConfigParser = plugin.getSysInjector().getInstance(CodeOwnerConfigParser.class);
+  }
+
+  @Test
+  public void loadNonExistingCodeOwnerConfigFile() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "master", "/non-existing/");
+    CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
+  }
+
+  @Test
+  public void loadCodeOwnerConfigFileFromNonExistingBranch() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "non-existing", "/");
+    CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isEmpty();
+  }
+
+  @Test
+  public void loadEmptyCodeOwnerConfigFile() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfig = CodeOwnerConfig.builder(codeOwnerConfigKey).build();
+    writeCodeOwnerConfig(codeOwnerConfig);
+
+    CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig().get()).hasCodeOwnersThat().isEmpty();
+  }
+
+  @Test
+  public void loadCodeOwnerConfigFile() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfig =
+        CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
+    writeCodeOwnerConfig(codeOwnerConfig);
+
+    CodeOwnerConfigFile codeOwnerConfigFile = codeOwnerConfigFileFactory.load(codeOwnerConfigKey);
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig()).isPresent();
+    assertThat(codeOwnerConfigFile.getLoadedCodeOwnerConfig().get())
+        .hasCodeOwnersEmailsThat()
+        .containsExactly(admin.email());
+  }
+
+  private void writeCodeOwnerConfig(CodeOwnerConfig codeOwnerConfig) throws Exception {
+    String formattedCodeOwnerConfig = codeOwnerConfigParser.formatAsString(codeOwnerConfig);
+    try (TestRepository<Repository> testRepo =
+        new TestRepository<>(repoManager.openRepository(project))) {
+      testRepo.update(
+          codeOwnerConfig.key().ref(),
+          testRepo
+              .commit()
+              .parent(getHead(testRepo.getRepository(), codeOwnerConfig.key().ref()))
+              .message("Add test code owner config")
+              .add(
+                  codeOwnerConfig.key().filePathForJgit(CodeOwnerConfigFile.FILE_NAME),
+                  formattedCodeOwnerConfig));
+    }
+  }
+}
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
index 2d2a02f..33b3b35 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigParserTest.java
@@ -17,16 +17,14 @@
 import static com.google.common.truth.Truth.assertThat;
 import static com.google.gerrit.plugins.codeowners.testing.CodeOwnerConfigSubject.assertThat;
 
-import com.google.gerrit.acceptance.LightweightPluginDaemonTest;
-import com.google.gerrit.acceptance.TestPlugin;
 import com.google.gerrit.entities.Project;
+import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
 import org.junit.Before;
 import org.junit.Test;
 
 /** Tests for {@link CodeOwnerConfigParser}. */
-@TestPlugin(name = "code-owners", sysModule = "com.google.gerrit.plugins.codeowners.Module")
-public class CodeOwnerConfigParserTest extends LightweightPluginDaemonTest {
+public class CodeOwnerConfigParserTest extends AbstractCodeOwnersTest {
   /** Callback interface that allows to assert a code owner config. */
   @FunctionalInterface
   interface CodeOwnerConfigAsserter {