1
0

fs.py 2.6 KB

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