Commit c00fe84a authored by Michele Maris's avatar Michele Maris
Browse files

u

parent efa2ddca
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ from .ya_config import YA_CONFIG
from .ya_hdr_parser import YA_HDR_PARSER
from .ya_extended_csv import ya_extended_csv
from .files import moveFile2backup
from .files import backup_open
from .wavenumber_base import wavenumber_base
from .profiling import timer,timerDict
from .struct import struct
+68 −1
Original line number Diff line number Diff line
def moveFile2backup(fname,skipTestExists=False) :
   """if exists creates a backup file for the file fname
      skipTestExists=True skips the test

      **deprecated** use `backup_open` instead
   """
   import time
   import os
@@ -8,3 +10,68 @@ def moveFile2backup(fname,skipTestExists=False) :
   tt=fname+'.'+time.strftime('%y%m%dl%H%M%S',time.localtime())+'~'
   print('Existing '+fname+' -> ',tt)
   os.rename(fname,tt)

class backup_open:
   def __new__(cls, filename, mode='r', verbose=False, override=False, addtilde=False, policy='datetime', removebackup=False, *args, **kwargs):
      """ Acts as the starndard 'open' but if file is opened in writing ('w') and if the file already exists renames the old version to have a backup file
          mode = see `open` mode
          verbose      = print a message if renaming is done (False)
          policy       = policy for backup naming either: `bak`, `bak.number`, `number`, `datetime` (`datetime`)
          override     = does not create a backup but overrides the old file (False)
          removebackup = removes an existing backup file if present, to be used in `bak` policy (False)
      """
      import time
      import os
      tilde = '~' if addtilde else ''
      #
      # open without any test
      if override or not 'w' in mode:
         return open(filename, mode, *args, **kwargs)

      if os.path.exists(filename):
         if policy == 'bak' :
            backup_filename = f"{filename}.bak{tilde}"
         elif policy == 'bak.number' :
            n=0
            while True :
               backup_filename = f"{filename}.bak.{n}{tilde}"
               if not os.path.exists(backup_filename) or removebackup:
                  break
               n=n+1
         elif policy == 'number' :
            n=0
            while True :
               backup_filename = f"{filename}.{n}{tilde}"
               if not os.path.exists(backup_filename)  or removebackup:
                  break
               n=n+1
         elif policy == 'datetime' :
            n=0
            while True :
               pstfx=time.strftime('%y%m%dl%H%M%S',time.localtime())
               if n==0 :
                  backup_filename = f"{filename}.{pstfx}{tilde}"
               else :
                  backup_filename = f"{filename}.{pstfx}{n}{tilde}"
               if not os.path.exists(backup_filename) or removebackup:
                  break
               n=n+1
         else :
            raise Exception(f'policy "{policy}" is not a valid one, valid policies are "bak","number","bak.number","datetime","datetime.number"')

         # For cross-platform safety (especially Windows),
         # remove the old backup if it already exists before renaming
         if removebackup or policy == 'bak':
            if os.path.exists(backup_filename):
               os.remove(backup_filename)
               if verbose :
                  print(f"[Backup] already existing backup filename `{backup_filename}` removed")

         # rename the filename to backup
         os.rename(filename, backup_filename)
         if verbose :
            print(f"[Backup] Renamed existing '{filename}' to '{backup_filename}'")

      # Return a native file object using the built-in open()
      return open(filename, mode, *args, **kwargs)