fs.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Common File System Utilities."""
  2. import os
  3. import shutil
  4. def abspath(path):
  5. """
  6. Return an absolute path, while also expanding the '~' user directory
  7. shortcut.
  8. :param path: The original path to expand.
  9. :rtype: str
  10. """
  11. return os.path.abspath(os.path.expanduser(path))
  12. def backup(path, suffix='.bak'):
  13. """
  14. Rename a file or directory safely without overwriting an existing
  15. backup of the same name.
  16. :param path: The path to the file or directory to make a backup of.
  17. :param suffix: The suffix to rename files with.
  18. :returns: The new path of backed up file/directory
  19. :rtype: str
  20. """
  21. count = -1
  22. new_path = None
  23. while True:
  24. if os.path.exists(path):
  25. if count == -1:
  26. new_path = "%s%s" % (path, suffix)
  27. else:
  28. new_path = "%s%s.%s" % (path, suffix, count)
  29. if os.path.exists(new_path):
  30. count += 1
  31. continue
  32. else:
  33. if os.path.isfile(path):
  34. shutil.copy(path, new_path)
  35. elif os.path.isdir(path):
  36. shutil.copytree(path, new_path)
  37. break
  38. else:
  39. break
  40. return new_path
  41. # Kinda dirty, but should resolve issues on Windows per #183
  42. if 'HOME' in os.environ:
  43. HOME_DIR = abspath(os.environ['HOME'])
  44. else:
  45. HOME_DIR = abspath('~') # pragma: nocover