CodeOwnersBackend: Support updating code owner configs

Signed-off-by: Edwin Kempin <ekempin@google.com>
Change-Id: I515e65a2f0a5264201cd93e62eb8599057f45ce1
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java
index e069a7c..38e31bb 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/CodeOwnersBackend.java
@@ -14,6 +14,8 @@
 
 package com.google.gerrit.plugins.codeowners.backend;
 
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.server.IdentifiedUser;
 import java.util.Optional;
 
 /**
@@ -30,4 +32,24 @@
    * @return code owner config for the given key if it exists, otherwise {@link Optional#empty()}
    */
   Optional<CodeOwnerConfig> getCodeOwnerConfig(CodeOwnerConfig.Key codeOwnerConfigKey);
+
+  /**
+   * Updates/Creates a code owner config.
+   *
+   * <p>If the specified code owner config doesn't exist yet, it is created.
+   *
+   * <p>Fails with {@link IllegalStateException} if the branch in which the code owner config should
+   * be updated doesn't exist.
+   *
+   * @param codeOwnerConfigKey key of the code owner config
+   * @param codeOwnerConfigUpdate definition of the update that should be performed
+   * @param currentUser the current user if the code owner config update/creation was user
+   *     initiated, otherwise {@code null}
+   * @return the updated/created code owner config, {@link Optional#empty()} if the update led to a
+   *     deletion of the code owner config or if the creation was a no-op
+   */
+  Optional<CodeOwnerConfig> upsertCodeOwnerConfig(
+      CodeOwnerConfig.Key codeOwnerConfigKey,
+      CodeOwnerConfigUpdate codeOwnerConfigUpdate,
+      @Nullable IdentifiedUser currentUser);
 }
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
index 06e2838..8a5c368 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/CodeOwnerConfigFile.java
@@ -17,6 +17,7 @@
 import static com.google.common.base.Preconditions.checkState;
 
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableSet;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfigUpdate;
@@ -64,6 +65,25 @@
     /**
      * Creates a {@link CodeOwnerConfigFile} for a code owner config.
      *
+     * <p>Same as {@link #load(Repository, CodeOwnerConfig.Key)}, but takes care to open/close the
+     * repository.
+     *
+     * @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 {
+      try (Repository repository = repoManager.openRepository(codeOwnerConfigKey.project())) {
+        return load(repository, codeOwnerConfigKey);
+      }
+    }
+
+    /**
+     * 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()}.
      *
@@ -76,19 +96,18 @@
      * #setCodeOwnerConfigUpdate(CodeOwnerConfigUpdate)} and committing the {@link
      * CodeOwnerConfigUpdate} via {@link #commit(com.google.gerrit.server.git.meta.MetaDataUpdate)}.
      *
+     * @param repository the repository in which the code owner config is stored
      * @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)
+    CodeOwnerConfigFile load(Repository repository, CodeOwnerConfig.Key codeOwnerConfigKey)
         throws IOException, ConfigInvalidException {
       CodeOwnerConfigFile codeOwnerConfigFile =
           new CodeOwnerConfigFile(codeOwnerConfigParser, codeOwnerConfigKey);
-      try (Repository repository = repoManager.openRepository(codeOwnerConfigKey.project())) {
-        codeOwnerConfigFile.load(codeOwnerConfigKey.project(), repository);
-      }
+      codeOwnerConfigFile.load(codeOwnerConfigKey.project(), repository);
       return codeOwnerConfigFile;
     }
   }
@@ -132,9 +151,11 @@
    *
    * @param codeOwnerConfigUpdate an {@code CodeOwnerConfigUpdate} outlining the modifications which
    *     should be applied
+   * @return this {@code CodeOwnerConfigFile} instance to allow chaining calls
    */
-  public void setCodeOwnerConfigUpdate(CodeOwnerConfigUpdate codeOwnerConfigUpdate) {
+  public CodeOwnerConfigFile setCodeOwnerConfigUpdate(CodeOwnerConfigUpdate codeOwnerConfigUpdate) {
     this.codeOwnerConfigUpdate = Optional.of(codeOwnerConfigUpdate);
+    return this;
   }
 
   @Override
@@ -208,16 +229,25 @@
       return false;
     }
 
-    // Save the new code owner config.
+    // Compute the new content of the code owner config file.
     String codeOwnerConfigFileContent =
         codeOwnerConfigParser.formatAsString(updatedCodeOwnerConfig);
+
+    // Save the new code owner config.
     saveUTF8(codeOwnerConfigKey.filePathForJgit(FILE_NAME), codeOwnerConfigFileContent);
 
     // If the file content is empty, the update led to a deletion of the code owner config file.
-    loadedCodeOwnersConfig =
-        codeOwnerConfigFileContent.isEmpty()
-            ? Optional.empty()
-            : Optional.of(updatedCodeOwnerConfig);
+    boolean isDeleted = codeOwnerConfigFileContent.isEmpty();
+
+    // Set a commit message if none was set yet.
+    if (Strings.isNullOrEmpty(commit.getMessage())) {
+      commit.setMessage(
+          String.format(
+              "%s code owner config",
+              loadedCodeOwnersConfig.isPresent() ? (isDeleted ? "Delete" : "Update") : "Create"));
+    }
+
+    loadedCodeOwnersConfig = isDeleted ? Optional.empty() : Optional.of(updatedCodeOwnerConfig);
     codeOwnerConfigUpdate = Optional.empty();
 
     return true;
diff --git a/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java b/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java
index 0da94e6..125fa3d 100644
--- a/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java
+++ b/java/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackend.java
@@ -14,22 +14,46 @@
 
 package com.google.gerrit.plugins.codeowners.backend.findowners;
 
+import com.google.common.base.Throwables;
+import com.google.gerrit.common.Nullable;
+import com.google.gerrit.entities.Project;
 import com.google.gerrit.exceptions.StorageException;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfigUpdate;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnersBackend;
+import com.google.gerrit.server.GerritPersonIdent;
+import com.google.gerrit.server.IdentifiedUser;
+import com.google.gerrit.server.git.GitRepositoryManager;
+import com.google.gerrit.server.git.meta.MetaDataUpdate;
+import com.google.gerrit.server.update.RetryHelper;
 import com.google.inject.Inject;
 import com.google.inject.Singleton;
 import java.io.IOException;
 import java.util.Optional;
 import org.eclipse.jgit.errors.ConfigInvalidException;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Repository;
 
 @Singleton
 public class FindOwnersBackend implements CodeOwnersBackend {
   private final CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory;
+  private final GitRepositoryManager repoManager;
+  private final PersonIdent serverIdent;
+  private final MetaDataUpdate.InternalFactory metaDataUpdateInternalFactory;
+  private final RetryHelper retryHelper;
 
   @Inject
-  FindOwnersBackend(CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory) {
+  FindOwnersBackend(
+      CodeOwnerConfigFile.Factory codeOwnerConfigFileFactory,
+      GitRepositoryManager repoManager,
+      @GerritPersonIdent PersonIdent serverIdent,
+      MetaDataUpdate.InternalFactory metaDataUpdateInternalFactory,
+      RetryHelper retryHelper) {
     this.codeOwnerConfigFileFactory = codeOwnerConfigFileFactory;
+    this.repoManager = repoManager;
+    this.serverIdent = serverIdent;
+    this.metaDataUpdateInternalFactory = metaDataUpdateInternalFactory;
+    this.retryHelper = retryHelper;
   }
 
   @Override
@@ -41,4 +65,69 @@
           String.format("failed to load code owner config %s", codeOwnerConfigKey), e);
     }
   }
+
+  @Override
+  public Optional<CodeOwnerConfig> upsertCodeOwnerConfig(
+      CodeOwnerConfig.Key codeOwnerConfigKey,
+      CodeOwnerConfigUpdate codeOwnerConfigUpdate,
+      @Nullable IdentifiedUser currentUser)
+      throws StorageException {
+    try {
+      return retryHelper
+          .pluginUpdate(
+              "upsertCodeOwnerConfigInSourceBranch",
+              () ->
+                  upsertCodeOwnerConfigInSourceBranch(
+                      currentUser, codeOwnerConfigKey, codeOwnerConfigUpdate))
+          .call();
+    } catch (Exception e) {
+      Throwables.throwIfUnchecked(e);
+      throw new StorageException(e);
+    }
+  }
+
+  private Optional<CodeOwnerConfig> upsertCodeOwnerConfigInSourceBranch(
+      @Nullable IdentifiedUser currentUser,
+      CodeOwnerConfig.Key codeOwnerConfigKey,
+      CodeOwnerConfigUpdate codeOwnerConfigUpdate) {
+    try (Repository repository = repoManager.openRepository(codeOwnerConfigKey.project())) {
+      CodeOwnerConfigFile codeOwnerConfigFile =
+          codeOwnerConfigFileFactory
+              .load(repository, codeOwnerConfigKey)
+              .setCodeOwnerConfigUpdate(codeOwnerConfigUpdate);
+
+      try (MetaDataUpdate metaDataUpdate =
+          createMetaDataUpdate(codeOwnerConfigKey.project(), repository, currentUser)) {
+        codeOwnerConfigFile.commit(metaDataUpdate);
+      }
+
+      return codeOwnerConfigFile.getLoadedCodeOwnerConfig();
+    } catch (IOException | ConfigInvalidException e) {
+      throw new StorageException(
+          String.format("failed to upsert code owner config %s", codeOwnerConfigKey), e);
+    }
+  }
+
+  private MetaDataUpdate createMetaDataUpdate(
+      Project.NameKey project, Repository repository, @Nullable IdentifiedUser currentUser) {
+    MetaDataUpdate metaDataUpdate = metaDataUpdateInternalFactory.create(project, repository, null);
+    try {
+      metaDataUpdate.getCommitBuilder().setCommitter(serverIdent);
+      if (currentUser != null) {
+        // Using MetaDataUpdate#setAuthor copies the timezone and timestamp from the committer
+        // identity, so that it's ensured that the author and committer identities have the same
+        // timezone and timestamp.
+        metaDataUpdate.setAuthor(currentUser);
+      } else {
+        // In this case the author identity is the same as the committer identity, hence it already
+        // has the correct timezone and timestamp and we can set it on the commit builder directly.
+        metaDataUpdate.getCommitBuilder().setAuthor(serverIdent);
+      }
+      return metaDataUpdate;
+    } catch (Throwable t) {
+      metaDataUpdate.close();
+      Throwables.throwIfUnchecked(t);
+      throw new StorageException("Failed to create MetaDataUpdate", t);
+    }
+  }
 }
diff --git a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java
index df20ddc..2dac620 100644
--- a/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java
+++ b/javatests/com/google/gerrit/plugins/codeowners/backend/findowners/FindOwnersBackendTest.java
@@ -16,11 +16,21 @@
 
 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.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import com.google.gerrit.common.Nullable;
 import com.google.gerrit.plugins.codeowners.acceptance.AbstractCodeOwnersTest;
 import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfig;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerConfigUpdate;
+import com.google.gerrit.plugins.codeowners.backend.CodeOwnerReference;
 import com.google.gerrit.plugins.codeowners.testing.findowners.FindOwnersTestUtil;
+import com.google.gerrit.server.IdentifiedUser;
 import java.util.Optional;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -61,4 +71,223 @@
     assertThat(codeOwnerConfig).isPresent();
     assertThat(codeOwnerConfig.get()).isEqualTo(codeOwnerConfigInRepository);
   }
+
+  @Test
+  public void createCodeOwnerConfigInitiatedByServer() throws Exception {
+    testCreateCodeOwnerConfig(null);
+  }
+
+  @Test
+  public void createCodeOwnerConfigInitiatedByUser() throws Exception {
+    testCreateCodeOwnerConfig(identifiedUserFactory.create(user.id()));
+  }
+
+  private void testCreateCodeOwnerConfig(@Nullable IdentifiedUser currentUser) throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+
+    try (Repository repo = repoManager.openRepository(project)) {
+      // Remember head for later assertions.
+      RevCommit origHead = getHead(repo, codeOwnerConfigKey.ref());
+
+      // Create the code owner config.
+      Optional<CodeOwnerConfig> codeOwnerConfig =
+          findOwnersBackend.upsertCodeOwnerConfig(
+              codeOwnerConfigKey,
+              CodeOwnerConfigUpdate.builder()
+                  .setCodeOwnerModification(
+                      codeOwners ->
+                          Sets.union(
+                              codeOwners,
+                              ImmutableSet.of(CodeOwnerReference.create(admin.email()))))
+                  .build(),
+              currentUser);
+      assertThat(codeOwnerConfig).isPresent();
+      assertThat(codeOwnerConfig.get()).hasCodeOwnersEmailsThat().containsExactly(admin.email());
+
+      // Check the metadata of the created commit.
+      RevCommit newHead = getHead(repo, codeOwnerConfigKey.ref());
+      assertThat(newHead.getParent(0)).isEqualTo(origHead);
+      assertThat(newHead.getShortMessage()).isEqualTo("Create code owner config");
+
+      // Check author identity.
+      if (currentUser != null) {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(currentUser.getAccount().preferredEmail());
+      } else {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(serverIdent.get().getEmailAddress());
+        assertThat(newHead.getCommitterIdent()).isEqualTo(newHead.getAuthorIdent());
+      }
+
+      // Check committer identity.
+      assertThat(newHead.getCommitterIdent().getEmailAddress())
+          .isEqualTo(serverIdent.get().getEmailAddress());
+      assertThat(newHead.getCommitterIdent().getTimeZone())
+          .isEqualTo(newHead.getAuthorIdent().getTimeZone());
+      assertThat(newHead.getCommitterIdent().getWhen())
+          .isEqualTo(newHead.getAuthorIdent().getWhen());
+    }
+  }
+
+  @Test
+  public void updateCodeOwnerConfigInitiatedByServer() throws Exception {
+    testUpdateCodeOwnerConfig(null);
+  }
+
+  @Test
+  public void updateCodeOwnerConfigInitiatedByUser() throws Exception {
+    testUpdateCodeOwnerConfig(identifiedUserFactory.create(user.id()));
+  }
+
+  private void testUpdateCodeOwnerConfig(@Nullable IdentifiedUser currentUser) throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfigInRepository =
+        CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfigInRepository);
+
+    try (Repository repo = repoManager.openRepository(project)) {
+      // Remember head for later assertions.
+      RevCommit origHead = getHead(repo, codeOwnerConfigKey.ref());
+
+      // Create the code owner config.
+      Optional<CodeOwnerConfig> codeOwnerConfig =
+          findOwnersBackend.upsertCodeOwnerConfig(
+              codeOwnerConfigKey,
+              CodeOwnerConfigUpdate.builder()
+                  .setCodeOwnerModification(
+                      codeOwners ->
+                          Sets.union(
+                              codeOwners, ImmutableSet.of(CodeOwnerReference.create(user.email()))))
+                  .build(),
+              currentUser);
+      assertThat(codeOwnerConfig).isPresent();
+      assertThat(codeOwnerConfig.get())
+          .hasCodeOwnersEmailsThat()
+          .containsExactly(admin.email(), user.email());
+
+      // Check the metadata of the created commit.
+      RevCommit newHead = getHead(repo, codeOwnerConfigKey.ref());
+      assertThat(newHead.getParent(0)).isEqualTo(origHead);
+      assertThat(newHead.getShortMessage()).isEqualTo("Update code owner config");
+
+      // Check author identity.
+      if (currentUser != null) {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(currentUser.getAccount().preferredEmail());
+      } else {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(serverIdent.get().getEmailAddress());
+        assertThat(newHead.getCommitterIdent()).isEqualTo(newHead.getAuthorIdent());
+      }
+
+      // Check committer identity.
+      assertThat(newHead.getCommitterIdent().getEmailAddress())
+          .isEqualTo(serverIdent.get().getEmailAddress());
+      assertThat(newHead.getCommitterIdent().getTimeZone())
+          .isEqualTo(newHead.getAuthorIdent().getTimeZone());
+      assertThat(newHead.getCommitterIdent().getWhen())
+          .isEqualTo(newHead.getAuthorIdent().getWhen());
+    }
+  }
+
+  @Test
+  public void deleteCodeOwnerConfigInitiatedByServer() throws Exception {
+    testDeleteCodeOwnerConfigInitiatedByServer(null);
+  }
+
+  @Test
+  public void deleteCodeOwnerConfigInitiatedByUser() throws Exception {
+    testDeleteCodeOwnerConfigInitiatedByServer(identifiedUserFactory.create(user.id()));
+  }
+
+  private void testDeleteCodeOwnerConfigInitiatedByServer(@Nullable IdentifiedUser currentUser)
+      throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfigInRepository =
+        CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfigInRepository);
+
+    try (Repository repo = repoManager.openRepository(project)) {
+      // Remember head for later assertions.
+      RevCommit origHead = getHead(repo, codeOwnerConfigKey.ref());
+
+      // Create the code owner config.
+      Optional<CodeOwnerConfig> codeOwnerConfig =
+          findOwnersBackend.upsertCodeOwnerConfig(
+              codeOwnerConfigKey,
+              CodeOwnerConfigUpdate.builder()
+                  .setCodeOwnerModification(codeOwners -> ImmutableSet.of())
+                  .build(),
+              currentUser);
+      assertThat(codeOwnerConfig).isEmpty();
+
+      // Check the metadata of the created commit.
+      RevCommit newHead = getHead(repo, codeOwnerConfigKey.ref());
+      assertThat(newHead.getParent(0)).isEqualTo(origHead);
+      assertThat(newHead.getShortMessage()).isEqualTo("Delete code owner config");
+
+      // Check author identity.
+      if (currentUser != null) {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(currentUser.getAccount().preferredEmail());
+      } else {
+        assertThat(newHead.getAuthorIdent().getEmailAddress())
+            .isEqualTo(serverIdent.get().getEmailAddress());
+        assertThat(newHead.getCommitterIdent()).isEqualTo(newHead.getAuthorIdent());
+      }
+
+      // Check committer identity.
+      assertThat(newHead.getCommitterIdent().getEmailAddress())
+          .isEqualTo(serverIdent.get().getEmailAddress());
+      assertThat(newHead.getCommitterIdent().getTimeZone())
+          .isEqualTo(newHead.getAuthorIdent().getTimeZone());
+      assertThat(newHead.getCommitterIdent().getWhen())
+          .isEqualTo(newHead.getAuthorIdent().getWhen());
+    }
+  }
+
+  @Test
+  public void noOpCodeOwnerConfigUpdate() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey = CodeOwnerConfig.Key.create(project, "master", "/");
+    CodeOwnerConfig codeOwnerConfigInRepository =
+        CodeOwnerConfig.builder(codeOwnerConfigKey).addCodeOwnerEmail(admin.email()).build();
+    findOwnersTestUtil.writeCodeOwnerConfig(codeOwnerConfigInRepository);
+
+    try (Repository repo = repoManager.openRepository(project)) {
+      // Remember head for later assertions.
+      RevCommit origHead = getHead(repo, codeOwnerConfigKey.ref());
+
+      // Create the code owner config.
+      Optional<CodeOwnerConfig> codeOwnerConfig =
+          findOwnersBackend.upsertCodeOwnerConfig(
+              codeOwnerConfigKey, CodeOwnerConfigUpdate.builder().build(), null);
+      assertThat(codeOwnerConfig).isPresent();
+      assertThat(codeOwnerConfig.get()).hasCodeOwnersEmailsThat().containsExactly(admin.email());
+
+      // Check that no commit was created.
+      assertThat(getHead(repo, codeOwnerConfigKey.ref())).isEqualTo(origHead);
+    }
+  }
+
+  @Test
+  public void cannotUpdateCodeOwnerConfigInNonExistingBranch() throws Exception {
+    CodeOwnerConfig.Key codeOwnerConfigKey =
+        CodeOwnerConfig.Key.create(project, "non-existing", "/");
+
+    try (Repository repo = repoManager.openRepository(project)) {
+      // Create the code owner config.
+      IllegalStateException exception =
+          assertThrows(
+              IllegalStateException.class,
+              () ->
+                  findOwnersBackend.upsertCodeOwnerConfig(
+                      codeOwnerConfigKey, CodeOwnerConfigUpdate.builder().build(), null));
+      assertThat(exception)
+          .hasMessageThat()
+          .isEqualTo(String.format("branch %s does not exist", codeOwnerConfigKey.ref()));
+
+      // Check that the branch was not created.
+      assertThat(repo.exactRef(codeOwnerConfigKey.ref())).isNull();
+    }
+  }
 }