From 09fa51303c6ba5adfd2431d87663523aa799288b Mon Sep 17 00:00:00 2001
From: Yuri Volchkov <yuri.volchkov@gmail.com>
Date: Mon, 21 Aug 2017 17:44:48 +0200
Subject: [PATCH] show: workaround for the missing file problem

This patch fixes the 'Deleted first duplicate file does not stop
notmuch show from working' test.

If a message to be shown has several duplicated files, and for some
reason the first file in the list is not available anymore, notmuch
will exit with an error.

This is clearly a problem in the database, but we are not going to let
this problem be a show-stopper. Let's walk through the list, and show
the first existing file.

Signed-off-by: Yuri Volchkov <yuri.volchkov@gmail.com>
---
 mime-node.c                | 28 ++++++++++++++++++++++++----
 test/T670-duplicate-mid.sh |  1 -
 2 files changed, 24 insertions(+), 5 deletions(-)

diff --git a/mime-node.c b/mime-node.c
index bb0870d0..24d73afa 100644
--- a/mime-node.c
+++ b/mime-node.c
@@ -79,12 +79,32 @@ mime_node_open (const void *ctx, notmuch_message_t *message,
     }
     talloc_set_destructor (mctx, _mime_node_context_free);
 
+    /* Fast path */
     mctx->file = fopen (filename, "r");
     if (! mctx->file) {
-	fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
-	status = NOTMUCH_STATUS_FILE_ERROR;
-	goto DONE;
-    }
+	/* Slow path - for some reason the first file in the list is
+	 * not available anymore. This is clearly a problem in the
+	 * database, but we are not going to let this problem be a
+	 * show stopper */
+	notmuch_filenames_t *filenames;
+	for (filenames = notmuch_message_get_filenames (message);
+	     notmuch_filenames_valid (filenames);
+	     notmuch_filenames_move_to_next (filenames))
+	{
+	    filename = notmuch_filenames_get (filenames);
+	    mctx->file = fopen (filename, "r");
+	    if (mctx->file)
+		break;
+	}
+
+	talloc_free (filenames);
+	if (! mctx->file) {
+	    /* Give up */
+	    fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
+		status = NOTMUCH_STATUS_FILE_ERROR;
+		goto DONE;
+	    }
+	}
 
     mctx->stream = g_mime_stream_file_new (mctx->file);
     if (!mctx->stream) {
diff --git a/test/T670-duplicate-mid.sh b/test/T670-duplicate-mid.sh
index f6f16029..decbc0a4 100755
--- a/test/T670-duplicate-mid.sh
+++ b/test/T670-duplicate-mid.sh
@@ -39,7 +39,6 @@ test_expect_equal_file EXPECTED OUTPUT
 
 rm ${MAIL_DIR}/copy1
 test_begin_subtest 'Deleted first duplicate file does not stop notmuch show from working'
-test_subtest_known_broken
 output=$(notmuch show --body=false --format=json id:duplicate)
 expected='[[[{
     "id": "'duplicate'",
-- 
2.45.2