+notmuch_status_t
+_find_parent_id (notmuch_database_t *notmuch,
+ const char *path,
+ Xapian::docid *parent_id)
+{
+ const char *slash, *parent_db_path;
+ char *parent_path;
+ notmuch_private_status_t private_status;
+ notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
+
+ if (path == NULL || *path == '\0') {
+ *parent_id = 0;
+ return NOTMUCH_STATUS_SUCCESS;
+ }
+
+ /* Find the last slash (not counting a trailing slash), if any. */
+
+ slash = path + strlen (path) - 1;
+
+ /* First, skip trailing slashes. */
+ while (slash != path) {
+ if (*slash != '/')
+ break;
+
+ --slash;
+ }
+
+ /* Then, find a slash. */
+ while (slash != path) {
+ if (*slash == '/')
+ break;
+
+ --slash;
+ }
+
+ /* Finally, skip multiple slashes. */
+ while (slash != path) {
+ if (*slash != '/')
+ break;
+
+ --slash;
+ }
+
+ if (slash == path)
+ parent_path = talloc_strdup (notmuch, "");
+ else
+ parent_path = talloc_strndup (notmuch, path, slash - path + 1);
+
+ parent_db_path = directory_db_path (parent_path);
+
+ private_status = find_unique_doc_id (notmuch, "directory",
+ parent_db_path, parent_id);
+ if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
+ status = notmuch_database_set_directory_mtime (notmuch,
+ parent_path, 0);
+ if (status)
+ return status;
+ private_status = find_unique_doc_id (notmuch, "directory",
+ parent_db_path, parent_id);
+ status = COERCE_STATUS (private_status, "_find_parent_id");
+ }
+
+ if (parent_db_path != parent_path)
+ free ((char *) parent_db_path);
+
+ talloc_free (parent_path);
+
+ return status;
+}
+