fs.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import errno
  2. import os
  3. import shutil
  4. from .log import debug
  5. __all__ = ['copy_file', 'copy_tree', 'make_tree', 'remove_file', 'remove_tree']
  6. # Wrap some file system related functions
  7. def make_tree(path):
  8. '''Create directories recursively if they don't exist
  9. '''
  10. debug('MKDIR', path)
  11. return os.makedirs(path, exist_ok=True)
  12. def copy_file(source, destination, update=False, verbose=True):
  13. '''
  14. '''
  15. name = os.path.basename(source)
  16. if verbose:
  17. debug('COPY', '%s from %s', name, os.path.dirname(source))
  18. if os.path.exists(source) and (
  19. not update
  20. or (
  21. not os.path.exists(destination)
  22. or (os.path.getmtime(source) > os.path.getmtime(destination))
  23. )
  24. ):
  25. shutil.copy(source, destination)
  26. def copy_tree(source, destination):
  27. '''Copy (or update) a directory preserving symlinks
  28. '''
  29. if not os.path.exists(source):
  30. raise OSError(errno.ENOENT, 'No such file or directory: ' + source)
  31. name = os.path.basename(source)
  32. debug('COPY', '%s from %s', name, os.path.dirname(source))
  33. for root, _, files in os.walk(source):
  34. relpath = os.path.relpath(root, source)
  35. dirname = os.path.join(destination, relpath)
  36. os.makedirs(dirname, exist_ok=True)
  37. for file_ in files:
  38. src = os.path.join(root, file_)
  39. dst = os.path.join(dirname, file_)
  40. if os.path.islink(src):
  41. try:
  42. os.remove(dst)
  43. except OSError:
  44. pass
  45. linkto = os.readlink(src)
  46. os.symlink(linkto, dst)
  47. else:
  48. copy_file(src, dst, update=True, verbose=False)
  49. def remove_file(path):
  50. '''remove a file if it exists
  51. '''
  52. name = os.path.basename(path)
  53. debug('REMOVE', '%s from %s', name, os.path.dirname(path))
  54. try:
  55. os.remove(path)
  56. except OSError:
  57. pass
  58. def remove_tree(path):
  59. '''remove a directory if it exists
  60. '''
  61. name = os.path.basename(path)
  62. debug('REMOVE', '%s from %s', name, os.path.dirname(path))
  63. try:
  64. shutil.rmtree(path)
  65. except OSError:
  66. pass