pathutils.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2013, Mahmoud Hashemi
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions are
  6. # met:
  7. #
  8. # * Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. #
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following
  13. # disclaimer in the documentation and/or other materials provided
  14. # with the distribution.
  15. #
  16. # * The names of the contributors may not be used to endorse or
  17. # promote products derived from this software without specific
  18. # prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """
  32. Functions for working with filesystem paths.
  33. The :func:`expandpath` function expands the tilde to $HOME and environment
  34. variables to their values.
  35. The :func:`augpath` function creates variants of an existing path without
  36. having to spend multiple lines of code splitting it up and stitching it back
  37. together.
  38. The :func:`shrinkuser` function replaces your home directory with a tilde.
  39. """
  40. from __future__ import print_function
  41. from os.path import (expanduser, expandvars, join, normpath, split, splitext)
  42. import os
  43. __all__ = [
  44. 'augpath', 'shrinkuser', 'expandpath',
  45. ]
  46. def augpath(path, suffix='', prefix='', ext=None, base=None, dpath=None,
  47. multidot=False):
  48. """
  49. Augment a path by modifying its components.
  50. Creates a new path with a different extension, basename, directory, prefix,
  51. and/or suffix.
  52. A prefix is inserted before the basename. A suffix is inserted
  53. between the basename and the extension. The basename and extension can be
  54. replaced with a new one. Essentially a path is broken down into components
  55. (dpath, base, ext), and then recombined as (dpath, prefix, base, suffix,
  56. ext) after replacing any specified component.
  57. Args:
  58. path (str | PathLike): a path to augment
  59. suffix (str, default=''): placed between the basename and extension
  60. prefix (str, default=''): placed in front of the basename
  61. ext (str, default=None): if specified, replaces the extension
  62. base (str, default=None): if specified, replaces the basename without
  63. extension
  64. dpath (str | PathLike, default=None): if specified, replaces the
  65. directory
  66. multidot (bool, default=False): Allows extensions to contain multiple
  67. dots. Specifically, if False, everything after the last dot in the
  68. basename is the extension. If True, everything after the first dot
  69. in the basename is the extension.
  70. Returns:
  71. str: augmented path
  72. Example:
  73. >>> path = 'foo.bar'
  74. >>> suffix = '_suff'
  75. >>> prefix = 'pref_'
  76. >>> ext = '.baz'
  77. >>> newpath = augpath(path, suffix, prefix, ext=ext, base='bar')
  78. >>> print('newpath = %s' % (newpath,))
  79. newpath = pref_bar_suff.baz
  80. Example:
  81. >>> augpath('foo.bar')
  82. 'foo.bar'
  83. >>> augpath('foo.bar', ext='.BAZ')
  84. 'foo.BAZ'
  85. >>> augpath('foo.bar', suffix='_')
  86. 'foo_.bar'
  87. >>> augpath('foo.bar', prefix='_')
  88. '_foo.bar'
  89. >>> augpath('foo.bar', base='baz')
  90. 'baz.bar'
  91. >>> augpath('foo.tar.gz', ext='.zip', multidot=True)
  92. 'foo.zip'
  93. >>> augpath('foo.tar.gz', ext='.zip', multidot=False)
  94. 'foo.tar.zip'
  95. >>> augpath('foo.tar.gz', suffix='_new', multidot=True)
  96. 'foo_new.tar.gz'
  97. """
  98. # Breakup path
  99. orig_dpath, fname = split(path)
  100. if multidot:
  101. # The first dot defines the extension
  102. parts = fname.split('.', 1)
  103. orig_base = parts[0]
  104. orig_ext = '' if len(parts) == 1 else '.' + parts[1]
  105. else:
  106. # The last dot defines the extension
  107. orig_base, orig_ext = splitext(fname)
  108. # Replace parts with specified augmentations
  109. if dpath is None:
  110. dpath = orig_dpath
  111. if ext is None:
  112. ext = orig_ext
  113. if base is None:
  114. base = orig_base
  115. # Recombine into new path
  116. new_fname = ''.join((prefix, base, suffix, ext))
  117. newpath = join(dpath, new_fname)
  118. return newpath
  119. def shrinkuser(path, home='~'):
  120. """
  121. Inverse of :func:`os.path.expanduser`.
  122. Args:
  123. path (str | PathLike): path in system file structure
  124. home (str, default='~'): symbol used to replace the home path.
  125. Defaults to '~', but you might want to use '$HOME' or
  126. '%USERPROFILE%' instead.
  127. Returns:
  128. str: path: shortened path replacing the home directory with a tilde
  129. Example:
  130. >>> path = expanduser('~')
  131. >>> assert path != '~'
  132. >>> assert shrinkuser(path) == '~'
  133. >>> assert shrinkuser(path + '1') == path + '1'
  134. >>> assert shrinkuser(path + '/1') == join('~', '1')
  135. >>> assert shrinkuser(path + '/1', '$HOME') == join('$HOME', '1')
  136. """
  137. path = normpath(path)
  138. userhome_dpath = expanduser('~')
  139. if path.startswith(userhome_dpath):
  140. if len(path) == len(userhome_dpath):
  141. path = home
  142. elif path[len(userhome_dpath)] == os.path.sep:
  143. path = home + path[len(userhome_dpath):]
  144. return path
  145. def expandpath(path):
  146. """
  147. Shell-like expansion of environment variables and tilde home directory.
  148. Args:
  149. path (str | PathLike): the path to expand
  150. Returns:
  151. str : expanded path
  152. Example:
  153. >>> import os
  154. >>> os.environ['SPAM'] = 'eggs'
  155. >>> assert expandpath('~/$SPAM') == expanduser('~/eggs')
  156. >>> assert expandpath('foo') == 'foo'
  157. """
  158. path = expanduser(path)
  159. path = expandvars(path)
  160. return path