From 99af2f4efbf3f9eb20cc2a314b4231a2e4573746 Mon Sep 17 00:00:00 2001
From: Yaroslav Halchenko <debian@onerussian.com>
Date: Fri, 29 Jul 2016 09:24:39 -0400
Subject: [PATCH 1/2] RF/ENH: remove file prior writing in to_filename

Closes #465
---
 nibabel/filebasedimages.py | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/nibabel/filebasedimages.py b/nibabel/filebasedimages.py
index 3d73c3cdf5..8942982a2d 100644
--- a/nibabel/filebasedimages.py
+++ b/nibabel/filebasedimages.py
@@ -8,6 +8,7 @@
 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
 ''' Common interface for any image format--volume or surface, binary or xml.'''
 
+import os
 import warnings
 
 from .externals.six import string_types
@@ -347,7 +348,15 @@ def to_filename(self, filename):
         -------
         None
         '''
-        self.file_map = self.filespec_to_file_map(filename)
+        self.file_map = file_map = self.filespec_to_file_map(filename)
+        for _, fh in file_map.items():
+            if not isinstance(fh, FileHolder):
+                continue
+            if os.path.exists(fh.filename):
+                # Remove previous file where new file would be saved
+                # Necessary e.g. for cases where file is a symlink pointing
+                # to some non-writable file (e.g. under git annex control)
+                os.unlink(fh.filename)
         self.to_file_map()
 
     def to_filespec(self, filename):

From cf564b6320eb1290d21dda2e070d63f63425c53a Mon Sep 17 00:00:00 2001
From: Yaroslav Halchenko <debian@onerussian.com>
Date: Mon, 1 Aug 2016 12:28:04 -0400
Subject: [PATCH 2/2] RF: git-annex specific handling in to_filename + allow
 NIBABEL_REMOVE_BEFORE_TO_FILENAME env var

---
 nibabel/filebasedimages.py | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/nibabel/filebasedimages.py b/nibabel/filebasedimages.py
index 8942982a2d..4ed678f24b 100644
--- a/nibabel/filebasedimages.py
+++ b/nibabel/filebasedimages.py
@@ -17,6 +17,14 @@
                               splitext_addext)
 from .openers import ImageOpener
 
+# OS-specific path
+_GIT_ANNEX_OBJECTS_PATH = os.path.join('.git', 'annex', 'objects')
+
+
+def _is_annex_symlink(path):
+    """Return True if file is a symlink to the git-annex objects"""
+    return os.path.islink(path) and _GIT_ANNEX_OBJECTS_PATH in os.path.realpath(path)
+
 
 class ImageFileError(Exception):
     pass
@@ -349,10 +357,11 @@ def to_filename(self, filename):
         None
         '''
         self.file_map = file_map = self.filespec_to_file_map(filename)
+        remove_env = os.environ.get('NIBABEL_REMOVE_BEFORE_TO_FILENAME', None)
         for _, fh in file_map.items():
             if not isinstance(fh, FileHolder):
                 continue
-            if os.path.exists(fh.filename):
+            if os.path.lexists(fh.filename) and (remove_env or _is_annex_symlink(fh.filename)):
                 # Remove previous file where new file would be saved
                 # Necessary e.g. for cases where file is a symlink pointing
                 # to some non-writable file (e.g. under git annex control)