Fix note creation when the same commit exists in another Git repository.

In case when the same commit was submitted in another repository we would load
more than one patch set for that commit. Instead of failing, iterate over the
found patch sets and find the one that belongs to this project. Create note for
that patch set only.

Bug: issue 2087
Change-Id: I11821d52fae33ba66f81503b88d3476f36bbaad1
diff --git a/src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java b/src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java
index 7232e26..83a25ab 100644
--- a/src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java
+++ b/src/main/java/com/googlesource/gerrit/plugins/reviewnotes/CreateReviewNotes.java
@@ -211,24 +211,37 @@
 
   private ObjectId createNoteContent(RevCommit c)
       throws OrmException, IOException {
-    List<PatchSet> patches = reviewDb.patchSets().byRevision(new RevId(c.name()))
-        .toList();
     HeaderFormatter fmt =
         new HeaderFormatter(gerritServerIdent.getTimeZone(), anonymousCowardName);
-    if (patches.isEmpty()) {
-      return null; // TODO: createNoCodeReviewNote(branch, c, fmt);
-    } else if (patches.size() == 1) {
+    PatchSet ps = loadPatchSet(c);
+    if (ps != null) {
       try {
-        createCodeReviewNote(patches.get(0), fmt);
+        createCodeReviewNote(ps, fmt);
+        return getInserter().insert(Constants.OBJ_BLOB,
+            fmt.toString().getBytes("UTF-8"));
       } catch (NoSuchChangeException e) {
         throw new IOException(e);
       }
-    } else {
-      log.error("Cannot create review note:"
-          + " more than one patch set found for the commit " + c.name());
-      return null;
     }
-    return getInserter().insert(Constants.OBJ_BLOB, fmt.toString().getBytes("UTF-8"));
+    return null;
+  }
+
+  private PatchSet loadPatchSet(RevCommit c) throws OrmException {
+    List<PatchSet> patches = reviewDb.patchSets().byRevision(new RevId(c.name()))
+        .toList();
+    if (patches.isEmpty()) {
+      return null; // TODO: createNoCodeReviewNote(branch, c, fmt);
+    } else if (patches.size() == 1) {
+      return patches.get(0);
+    } else {
+      for (PatchSet ps : patches) {
+        Change.Id cid = ps.getId().getParentKey();
+        if (reviewDb.changes().get(cid).getProject().equals(project)) {
+          return ps;
+        }
+      }
+    }
+    return null;
   }
 
   private void createCodeReviewNote(PatchSet ps, HeaderFormatter fmt)