__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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)
  40. def update_locate_database():
  41. import subprocess
  42. subprocess.call(['sudo', 'updatedb'])
  43. def locate(patterns, match_all = False, ignore_case = False, update_database = False):
  44. if update_database:
  45. update_locate_database()
  46. if type(patterns) is not list:
  47. patterns = [str(patterns)]
  48. patterns = [str(p) for p in patterns]
  49. options = []
  50. if match_all:
  51. options.append("--all")
  52. if ignore_case:
  53. options.append("--ignore-case")
  54. import subprocess
  55. try:
  56. output = subprocess.check_output(["locate"] + options + patterns)
  57. except subprocess.CalledProcessError as e:
  58. if e.returncode == 1:
  59. return []
  60. else:
  61. raise e
  62. return output.strip().split('\n')