PageRenderTime 61ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/fabric/contrib/files.py

https://github.com/pavanmishra/fabric
Python | 255 lines | 205 code | 13 blank | 37 comment | 15 complexity | 4d6451f43a41e775cf4a1772cf650b58 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. Module providing easy API for working with remote files and folders.
  3. """
  4. from __future__ import with_statement
  5. import tempfile
  6. import re
  7. from fabric.api import run, sudo, settings, put, hide, abort
  8. def exists(path, use_sudo=False, verbose=False):
  9. """
  10. Return True if given path exists on the current remote host.
  11. If ``use_sudo`` is True, will use `sudo` instead of `run`.
  12. `exists` will, by default, hide all output (including the run line, stdout,
  13. stderr and any warning resulting from the file not existing) in order to
  14. avoid cluttering output. You may specify ``verbose=True`` to change this
  15. behavior.
  16. """
  17. func = use_sudo and sudo or run
  18. cmd = 'ls -d --color=never %s' % path
  19. # If verbose, run normally
  20. if verbose:
  21. with settings(warn_only=True):
  22. return func(cmd)
  23. # Otherwise, be quiet
  24. with settings(hide('everything'), warn_only=True):
  25. return func(cmd)
  26. def first(*args, **kwargs):
  27. """
  28. Given one or more file paths, returns first one found, or None if none
  29. exist. May specify ``use_sudo`` which is passed to `exists`.
  30. """
  31. for directory in args:
  32. if not kwargs.get('use_sudo'):
  33. if exists(directory, sudo=False):
  34. return directory
  35. else:
  36. if exists(directory):
  37. return directory
  38. def upload_template(filename, destination, context=None, use_jinja=False,
  39. template_dir=None, use_sudo=False):
  40. """
  41. Render and upload a template text file to a remote host.
  42. ``filename`` should be the path to a text file, which may contain Python
  43. string interpolation formatting and will be rendered with the given context
  44. dictionary ``context`` (if given.)
  45. Alternately, if ``use_jinja`` is set to True and you have the Jinja2
  46. templating library available, Jinja will be used to render the template
  47. instead. Templates will be loaded from the invoking user's current working
  48. directory by default, or from ``template_dir`` if given.
  49. The resulting rendered file will be uploaded to the remote file path
  50. ``destination`` (which should include the desired remote filename.) If the
  51. destination file already exists, it will be renamed with a ``.bak``
  52. extension.
  53. By default, the file will be copied to ``destination`` as the logged-in
  54. user; specify ``use_sudo=True`` to use `sudo` instead.
  55. """
  56. with tempfile.NamedTemporaryFile() as output:
  57. # Init
  58. text = None
  59. if use_jinja:
  60. try:
  61. from jinja2 import Environment, FileSystemLoader
  62. jenv = Environment(loader=FileSystemLoader(template_dir or '.'))
  63. text = jenv.get_template(filename).render(**context or {})
  64. except ImportError, e:
  65. abort("tried to use Jinja2 but was unable to import: %s" % e)
  66. else:
  67. with open(filename) as inputfile:
  68. text = inputfile.read()
  69. if context:
  70. text = text % context
  71. output.write(text)
  72. output.flush()
  73. put(output.name, "/tmp/" + filename)
  74. func = use_sudo and sudo or run
  75. # Back up any original file (need to do figure out ultimate destination)
  76. to_backup = destination
  77. with settings(hide('everything'), warn_only=True):
  78. # Is destination a directory?
  79. if func('test -f %s' % to_backup).failed:
  80. # If so, tack on the filename to get "real" destination
  81. to_backup = destination + '/' + filename
  82. if exists(to_backup):
  83. func("cp %s %s.bak" % (to_backup, to_backup))
  84. # Actually move uploaded template to destination
  85. func("mv /tmp/%s %s" % (filename, destination))
  86. def sed(filename, before, after, limit='', use_sudo=False, backup='.bak'):
  87. """
  88. Run a search-and-replace on ``filename`` with given regex patterns.
  89. Equivalent to ``sed -i<backup> -e "/<limit>/ s/<before>/<after>/g
  90. <filename>"``.
  91. For convenience, ``before`` and ``after`` will automatically escape forward
  92. slashes (and **only** forward slashes) for you, so you don't need to
  93. specify e.g. ``http:\/\/foo\.com``, instead just using ``http://foo\.com``
  94. is fine.
  95. If ``use_sudo`` is True, will use `sudo` instead of `run`.
  96. `sed` will pass ``shell=False`` to `run`/`sudo`, in order to avoid problems
  97. with many nested levels of quotes and backslashes.
  98. """
  99. func = use_sudo and sudo or run
  100. expr = r"sed -i%s -r -e '%ss/%s/%s/g' %s"
  101. before = before.replace('/', r'\/')
  102. after = after.replace('/', r'\/')
  103. if limit:
  104. limit = r'/%s/ ' % limit
  105. command = expr % (backup, limit, before, after, filename)
  106. return func(command, shell=False)
  107. def uncomment(filename, regex, use_sudo=False, char='#', backup='.bak'):
  108. """
  109. Attempt to uncomment all lines in ``filename`` matching ``regex``.
  110. The default comment delimiter is `#` and may be overridden by the ``char``
  111. argument.
  112. This function uses the `sed` function, and will accept the same
  113. ``use_sudo`` and ``backup`` keyword arguments that `sed` does.
  114. `uncomment` will remove a single whitespace character following the comment
  115. character, if it exists, but will preserve all preceding whitespace. For
  116. example, ``# foo`` would become ``foo`` (the single space is stripped) but
  117. `` # foo`` would become `` foo`` (the single space is still stripped,
  118. but the preceding 4 spaces are not.)
  119. """
  120. return sed(
  121. filename,
  122. before=r'^([[:space:]]*)%s[[:space:]]?' % char,
  123. after=r'\1',
  124. limit=regex,
  125. use_sudo=use_sudo,
  126. backup=backup
  127. )
  128. def comment(filename, regex, use_sudo=False, char='#', backup='.bak'):
  129. """
  130. Attempt to comment out all lines in ``filename`` matching ``regex``.
  131. The default commenting character is `#` and may be overridden by the
  132. ``char`` argument.
  133. This function uses the `sed` function, and will accept the same
  134. ``use_sudo`` and ``backup`` keyword arguments that `sed` does.
  135. `comment` will prepend the comment character to the beginning of the line,
  136. so that lines end up looking like so::
  137. this line is uncommented
  138. #this line is commented
  139. # this line is indented and commented
  140. In other words, comment characters will not "follow" indentation as they
  141. sometimes do when inserted by hand. Neither will they have a trailing space
  142. unless you specify e.g. ``char='# '``.
  143. .. note::
  144. In order to preserve the line being commented out, this function will
  145. wrap your ``regex`` argument in parentheses, so you don't need to. It
  146. will ensure that any preceding/trailing ``^`` or ``$`` characters are
  147. correctly moved outside the parentheses. For example, calling
  148. ``comment(filename, r'^foo$')`` will result in a `sed` call with the
  149. "before" regex of ``r'^(foo)$'`` (and the "after" regex, naturally, of
  150. ``r'#\\1'``.)
  151. """
  152. carot = ''
  153. dollar = ''
  154. if regex.startswith('^'):
  155. carot = '^'
  156. regex = regex[1:]
  157. if regex.endswith('$'):
  158. dollar = '$'
  159. regex = regex[:1]
  160. regex = "%s(%s)%s" % (carot, regex, dollar)
  161. return sed(
  162. filename,
  163. before=regex,
  164. after=r'%s\1' % char,
  165. use_sudo=use_sudo,
  166. backup=backup
  167. )
  168. def contains(text, filename, exact=False, use_sudo=False):
  169. """
  170. Return True if ``filename`` contains ``text``.
  171. By default, this function will consider a partial line match (i.e. where
  172. the given text only makes up part of the line it's on). Specify
  173. ``exact=True`` to change this behavior so that only a line containing
  174. exactly ``text`` results in a True return value.
  175. Double-quotes in either ``text`` or ``filename`` will be automatically
  176. backslash-escaped in order to behave correctly during the remote shell
  177. invocation.
  178. If ``use_sudo`` is True, will use `sudo` instead of `run`.
  179. """
  180. func = use_sudo and sudo or run
  181. if exact:
  182. text = "^%s$" % text
  183. with settings(hide('everything'), warn_only=True):
  184. return func('egrep "%s" "%s"' % (
  185. text.replace('"', r'\"'),
  186. filename.replace('"', r'\"')
  187. ))
  188. def append(text, filename, use_sudo=False):
  189. """
  190. Append string (or list of strings) ``text`` to ``filename``.
  191. When a list is given, each string inside is handled independently (but in
  192. the order given.)
  193. If ``text`` is already found as a discrete line in ``filename``, the append
  194. is not run, and None is returned immediately. Otherwise, the given text is
  195. appended to the end of the given ``filename`` via e.g. ``echo '$text' >>
  196. $filename``.
  197. Because ``text`` is single-quoted, single quotes will be transparently
  198. backslash-escaped.
  199. If ``use_sudo`` is True, will use `sudo` instead of `run`.
  200. """
  201. func = use_sudo and sudo or run
  202. # Normalize non-list input to be a list
  203. if isinstance(text, str):
  204. text = [text]
  205. for line in text:
  206. if (contains('^' + re.escape(line), filename, use_sudo=use_sudo)
  207. and line):
  208. continue
  209. func("echo '%s' >> %s" % (line.replace("'", r'\''), filename))