__init__.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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, override = True, backup = False, backup_suffix = "~"):
  12. if os.path.exists(destination):
  13. if override:
  14. if backup:
  15. append_to_name(destination, backup_suffix)
  16. elif os.path.isdir(destination) and not os.path.islink(destination):
  17. raise OSError("may not override directory '%s'" % destination)
  18. else:
  19. raise OSError("path '%s' already exists" % destination)
  20. os.renames(source, destination)
  21. def symlink(source, link_name, relative = False, override = False, backup = True, backup_suffix = "~"):
  22. if relative:
  23. source = os.path.relpath(source, os.path.dirname(link_name))
  24. # os.path.lexists() returns True if path refers to an existing path and
  25. # True for broken symbolic links.
  26. if not os.path.lexists(link_name):
  27. os.symlink(source, link_name)
  28. elif not os.path.islink(link_name) or os.readlink(link_name) != source:
  29. if override:
  30. if backup:
  31. append_to_name(link_name, backup_suffix)
  32. else:
  33. if os.path.isdir(link_name):
  34. os.rmdir(link_name)
  35. else:
  36. os.remove(link_name)
  37. os.symlink(source, link_name)
  38. else:
  39. raise OSError("link's path '%s' already exists." % link_name)