JAL-3141 Changed suffix position to after the extension (removed extension detection...
[jalview.git] / src / jalview / io / BackupFiles.java
index ff23cbf..1553a41 100644 (file)
@@ -8,6 +8,7 @@ import jalview.util.MessageManager;
 import java.io.File;
 import java.io.IOException;
 import java.util.Arrays;
+import java.util.Map;
 import java.util.HashMap;
 import java.util.TreeMap;
 
@@ -15,7 +16,8 @@ import java.util.TreeMap;
  * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
  * User configurable options are:
  * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
- * BACKUPFILES_SUFFIX - a template to insert just before the file extension.  Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
+ * BACKUPFILES_SUFFIX - a template to insert after the file extension.  Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
+ * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep.
  * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file.
  * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc)
  * BACKUPFILES_REVERSE_ORDER - if true then "logfile" style numbering and file rolling will occur. If false then ever-increasing version numbering will occur, but old files will still be deleted if there are more than ROLL_MAX backup files. 
@@ -26,23 +28,27 @@ public class BackupFiles
 {
 
   // labels for saved params in Cache and .jalview_properties
-  private static String NS = "BACKUPFILES";
+  private static final String NS = "BACKUPFILES";
 
-  public static String ENABLED = NS + "_ENABLED";
+  public static final String ENABLED = NS + "_ENABLED";
 
-  public static String SUFFIX = NS + "_SUFFIX";
+  public static final String SUFFIX = NS + "_SUFFIX";
 
-  public static String ROLL_MAX = NS + "_ROLL_MAX";
+  public static final String NO_MAX = NS + "_NO_MAX";
 
-  public static String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
+  public static final String ROLL_MAX = NS + "_ROLL_MAX";
 
-  protected static String NUM_PLACEHOLDER = "%n";
+  public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
 
-  public static String REVERSE_ORDER = NS + "_REVERSE_ORDER";
+  public static final String NUM_PLACEHOLDER = "%n";
 
-  public static String CONFIRM_DELETE_OLD = NS + "_CONFIRM_DELETE_OLD";
+  public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
 
-  private static String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
+  public static final String CONFIRM_DELETE_OLD = NS + "_CONFIRM_DELETE_OLD";
+
+  private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
+
+  private static final String TEMP_FILE_EXT = ".tmp";
 
   // file - File object to be backed up and then updated (written over)
   private File file;
@@ -55,11 +61,12 @@ public class BackupFiles
   // deleting old backup/version files
   private static boolean confirmDelete;
 
-  private static boolean classInit = false;
-
   // defaultSuffix - default template to use to append to basename of file
   private String suffix;
 
+  // noMax - flag to turn off a maximum number of files
+  private boolean noMax;
+
   // defaultMax - default max number of backup files
   private int max;
 
@@ -81,19 +88,22 @@ public class BackupFiles
     this(new File(filename));
   }
 
-  // first time defaults for SUFFIX, ROLL_MAX, SUFFIX_DIGITS and REVERSE_ORDER
+  // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
+  // REVERSE_ORDER
   public BackupFiles(File file)
   {
-    this(file, "-v" + NUM_PLACEHOLDER, 4, 3, false);
+    this(file, ".v" + NUM_PLACEHOLDER, false, 4, 3, false);
   }
 
   public BackupFiles(File file,
-          String defaultSuffix, int defaultMax, int defaultDigits,
+          String defaultSuffix, boolean defaultNoMax, int defaultMax,
+          int defaultDigits,
           boolean defaultReverseOrder)
   {
     classInit();
     this.file = file;
     this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
+    this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
     this.max = Cache.getDefault(ROLL_MAX, defaultMax);
     this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
     this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
@@ -107,11 +117,11 @@ public class BackupFiles
       {
         String tempfilename = file.getName();
         File tempdir = file.getParentFile();
-        temp = File.createTempFile(tempfilename, ".tmp", tempdir);
+        temp = File.createTempFile(tempfilename, TEMP_FILE_EXT, tempdir);
       }
       else
       {
-        temp = File.createTempFile(DEFAULT_TEMP_FILE, ".tmp");
+        temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
       }
     } catch (IOException e)
     {
@@ -126,12 +136,8 @@ public class BackupFiles
 
   public static void classInit()
   {
-    if (!classInit)
-    {
-      setEnabled(Cache.getDefault(ENABLED, true));
-      setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
-      classInit = true;
-    }
+    setEnabled(Cache.getDefault(ENABLED, true));
+    setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
   }
 
   public static void setEnabled(boolean flag)
@@ -196,6 +202,7 @@ public class BackupFiles
 
   public boolean renameTempFile()
   {
+    System.out.println("RENAMING TEMP FILE '"+tempFile.getName() + "' TO '"+file.getName()+"'"); // DELETEME
     return tempFile.renameTo(file);
   }
 
@@ -205,7 +212,7 @@ public class BackupFiles
   {
 
     // file doesn't yet exist or backups are not enabled
-    if ((!file.exists()) || (!enabled) || (max < -1))
+    if ((!file.exists()) || (!enabled) || (max < 0))
     {
       // nothing to do
       return true;
@@ -227,15 +234,6 @@ public class BackupFiles
     }
     String filename = file.getName();
     String basename = filename;
-    String extension = "";
-    int dotcharpos = filename.lastIndexOf('.');
-    // don't split of filenames with the last '.' at the very beginning or
-    // very end of the filename
-    if ((dotcharpos > 0) && (dotcharpos < filename.length() - 1))
-    {
-      basename = filename.substring(0, dotcharpos);
-      extension = filename.substring(dotcharpos); // NOTE this includes the '.'
-    }
 
     boolean ret = true;
     // Create/move backups up one
@@ -244,8 +242,7 @@ public class BackupFiles
     
     // find existing backup files
     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
-            digits,
-            extension);
+            digits);
     File[] backupFiles = dirFile.listFiles(bff);
     int nextIndexNum = 0;
     String confirmDeleteExtraInfo = null;
@@ -257,43 +254,36 @@ public class BackupFiles
     }
     else
     {
-
-      // sort the backup files (based on integer found in the suffix) using a
-      // precomputed Hashmap for speed
-      HashMap<Integer, File> bfHashMap = new HashMap<>();
-      for (int i = 0; i < backupFiles.length; i++)
-      {
-        File f = backupFiles[i];
-        BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits, extension);
-        bfHashMap.put(bfp.indexNum(), f);
-      }
-      TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
-      bfTreeMap.putAll(bfHashMap);
+      TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename);
 
       if (reverseOrder)
       {
         // backup style numbering
 
         File lastfile = null;
-        int tempMax = max;
-        // max == -1 means no limits
+        int tempMax = noMax ? -1 : max;
+        // noMax == true means no limits
         // look for first "gap" in backupFiles
-        // if tempMax is -1 at this stage just keep going until there's a gap...
+        // if tempMax is -1 at this stage just keep going until there's a gap,
+        // then hopefully tempMax gets set to the right index (a positive
+        // integer so the loop breaks)...
         // why do I feel a little uneasy about this loop?..
-        for (int i = 1; tempMax < 0 || (max >= 0 && i <= max); i++)
+        for (int i = 1; tempMax < 0 || i <= max; i++)
         {
-          if (!bfTreeMap.containsKey(i)) // first non-existent backupfile
+          if (!bfTreeMap.containsKey(i)) // first index without existent
+                                         // backupfile
           {
             tempMax = i;
           }
         }
 
-        for (int m = 0; m < tempMax; m++)
+        // for (int m = 0; m < tempMax; m++)
+        for (int n = tempMax; n > 0; n--)
         {
-          int n = tempMax - m;
+          // int n = tempMax - m;
           String backupfilename = dir + File.separatorChar
-                  + BackupFilenameParts.getBackupFilename(n, basename,
-                          suffix, digits, extension);
+                  + BackupFilenameFilter.getBackupFilename(n, basename,
+                          suffix, digits);
           File backupfile_n = new File(backupfilename);
 
           if (!backupfile_n.exists())
@@ -302,12 +292,13 @@ public class BackupFiles
             continue;
           }
 
-          if (m == 0 && backupfile_n.exists())
+          // if (m == 0 && backupfile_n.exists())
+          if ((!noMax) && n == tempMax && backupfile_n.exists())
           {
             // move the largest (max) rolled file to a temp file and add to the delete list
             try
             {
-              File temp = File.createTempFile(backupfilename, ".tmp",
+              File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT,
                     dirFile);
               backupfile_n.renameTo(temp);
 
@@ -343,8 +334,8 @@ public class BackupFiles
 
         bfTreeMap.values().toArray(backupFiles);
 
-        // max value of -1 means keep all backup files
-        if (bfTreeMap.size() >= max && max != -1)
+        // noMax == true means keep all backup files
+        if ((!noMax) && bfTreeMap.size() >= max)
         {
           // need to delete some files to keep number of backups to designated
           // max
@@ -359,6 +350,19 @@ public class BackupFiles
       }
     }
 
+    deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
+
+    // Let's make the new backup file!! yay, got there at last!
+    String latestBackupFilename = dir + File.separatorChar
+            + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
+                    suffix, digits);
+    File latestBackupFile = new File(latestBackupFilename);
+    ret = ret && file.renameTo(latestBackupFile);
+
+    return ret;
+  }
+
+  private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
     if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
     {
       // delete old backup/version files
@@ -406,15 +410,21 @@ public class BackupFiles
       }
 
     }
+  }
 
-    // Let's make the new backup file!! yay, got there at last!
-    String latestBackupFilename = dir + File.separatorChar
-            + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
-                    suffix, digits, extension);
-    File latestBackupFile = new File(latestBackupFilename);
-    ret = ret && file.renameTo(latestBackupFile);
-
-    return ret;
+  private TreeMap sortBackupFilesAsTreeMap(File[] backupFiles, String basename) {
+      // sort the backup files (based on integer found in the suffix) using a
+      // precomputed Hashmap for speed
+      Map<Integer, File> bfHashMap = new HashMap<>();
+      for (int i = 0; i < backupFiles.length; i++)
+      {
+          File f = backupFiles[i];
+          BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits);
+          bfHashMap.put(bfp.indexNum(), f);
+      }
+      TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
+      bfTreeMap.putAll(bfHashMap);
+      return bfTreeMap;
   }
 
   public boolean rollBackupsAndRenameTempFile()
@@ -457,5 +467,50 @@ public class BackupFiles
     return rename;
   }
 
+  public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
+          String fileName,
+          String suffix, int digits)
+  {
+    File[] backupFiles = null;
+
+    File file = new File(fileName);
+
+    String dir = "";
+    File dirFile;
+    try
+    {
+      dirFile = file.getParentFile();
+      dir = dirFile.getCanonicalPath();
+    } catch (Exception e)
+    {
+      System.out.println(
+              "Could not get canonical path for file '" + file + "'");
+      return new TreeMap<>();
+    }
+
+    String filename = file.getName();
+    String basename = filename;
+    
+    // find existing backup files
+    BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits);
+    backupFiles = dirFile.listFiles(bff); // is clone needed?
+    
+    // sort the backup files (based on integer found in the suffix) using a
+    // precomputed Hashmap for speed
+    Map<Integer, File> bfHashMap = new HashMap<>();
+    for (int i = 0; i < backupFiles.length; i++)
+    {
+      File f = backupFiles[i];
+      BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
+              digits);
+      bfHashMap.put(bfp.indexNum(), f);
+    }
+    TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
+    bfTreeMap.putAll(bfHashMap);
+
+    return bfTreeMap;
+  }
+
+
 }