From f424c843f200ad6395ce4f5d0497877f9138d81e Mon Sep 17 00:00:00 2001
From: Philippe Canal <pcanal@fnal.gov>
Date: Fri, 26 Feb 2021 18:12:20 -0600
Subject: [PATCH] TFileMerger: only delete the directory if the merger created
 it.

This is necessary to support the 'fast' incremental merge where the input will continue to be used.
---
 io/io/src/TFileMerger.cxx | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/io/io/src/TFileMerger.cxx b/io/io/src/TFileMerger.cxx
index e1f20451782..33b0a323f9b 100644
--- a/io/io/src/TFileMerger.cxx
+++ b/io/io/src/TFileMerger.cxx
@@ -458,7 +458,8 @@ Bool_t TFileMerger::MergeOne(TDirectory *target, TList *sourcelist, Int_t type,
       if (!obj && key) {
          obj = key->ReadObj();
          ownobj = kTRUE;
-      } else if (obj && info.fIsFirst && current_sourcedir != target) {
+      } else if (obj && info.fIsFirst && current_sourcedir != target
+                 && !cl->InheritsFrom( TDirectory::Class() )) {
          R__ASSERT(cl->IsTObject());
          TDirectory::TContext ctxt(current_sourcedir);
          obj = obj->Clone();
@@ -682,7 +683,7 @@ Bool_t TFileMerger::MergeOne(TDirectory *target, TList *sourcelist, Int_t type,
       // and we are in incremental mode (because it will be reused
       // and has not been written to disk (for performance reason).
       // coverity[var_deref_model] the IsA()->InheritsFrom guarantees that the dynamic_cast will succeed.
-      if (!(type & kIncremental) || dirobj->GetFile() != target) {
+      if (ownobj && (!(type & kIncremental) || dirobj->GetFile() != target)) {
          dirobj->ResetBit(kMustCleanup);
          delete dirobj;
       }
-- 
GitLab