__init__.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import os
  2. import sys
  3. def append_to_name(source_path, suffix):
  4. dest_path_prefix = source_path + suffix
  5. dest_path = dest_path_prefix
  6. dest_index = 0
  7. while os.path.lexists(dest_path):
  8. dest_index += 1
  9. dest_path = dest_path_prefix + str(dest_index)
  10. os.rename(source_path, dest_path)
  11. def renames(source, destination, backup = False, backup_suffix = "~"):
  12. if os.path.exists(destination):
  13. if backup:
  14. append_to_name(destination, backup_suffix)
  15. elif os.path.isdir(destination) and not os.path.islink(destination):
  16. raise OSError("may not override directory '%s'" % destination)
  17. os.renames(source, destination)
  18. def symlink(source, link_name, relative = False, override = False, backup = True, backup_suffix = "~"):
  19. if relative:
  20. source = os.path.relpath(source, os.path.dirname(link_name))
  21. # os.path.lexists() returns True if path refers to an existing path and
  22. # True for broken symbolic links.
  23. if not os.path.lexists(link_name):
  24. os.symlink(source, link_name)
  25. elif not os.path.islink(link_name) or os.readlink(link_name) != source:
  26. if override:
  27. if backup:
  28. append_to_name(link_name, backup_suffix)
  29. else:
  30. if os.path.isdir(link_name):
  31. os.rmdir(link_name)
  32. else:
  33. os.remove(link_name)
  34. os.symlink(source, link_name)
  35. else:
  36. raise OSError("link's path '%s' already exists." % link_name)