fs.py 2.0 KB

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