shellutils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. # copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
  2. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This file is part of logilab-common.
  5. #
  6. # logilab-common is free software: you can redistribute it and/or modify it under
  7. # the terms of the GNU Lesser General Public License as published by the Free
  8. # Software Foundation, either version 2.1 of the License, or (at your option) any
  9. # later version.
  10. #
  11. # logilab-common is distributed in the hope that it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  13. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  14. # details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public License along
  17. # with logilab-common. If not, see <http://www.gnu.org/licenses/>.
  18. """shell/term utilities, useful to write some python scripts instead of shell
  19. scripts.
  20. """
  21. __docformat__ = "restructuredtext en"
  22. import os
  23. import glob
  24. import shutil
  25. import stat
  26. import sys
  27. import tempfile
  28. import time
  29. import fnmatch
  30. import errno
  31. import string
  32. import random
  33. from os.path import exists, isdir, islink, basename, join
  34. from logilab.common import STD_BLACKLIST, _handle_blacklist
  35. from logilab.common.compat import raw_input
  36. from logilab.common.compat import str_to_bytes
  37. try:
  38. from logilab.common.proc import ProcInfo, NoSuchProcess
  39. except ImportError:
  40. # windows platform
  41. class NoSuchProcess(Exception): pass
  42. def ProcInfo(pid):
  43. raise NoSuchProcess()
  44. class tempdir(object):
  45. def __enter__(self):
  46. self.path = tempfile.mkdtemp()
  47. return self.path
  48. def __exit__(self, exctype, value, traceback):
  49. # rmtree in all cases
  50. shutil.rmtree(self.path)
  51. return traceback is None
  52. class pushd(object):
  53. def __init__(self, directory):
  54. self.directory = directory
  55. def __enter__(self):
  56. self.cwd = os.getcwd()
  57. os.chdir(self.directory)
  58. return self.directory
  59. def __exit__(self, exctype, value, traceback):
  60. os.chdir(self.cwd)
  61. def chown(path, login=None, group=None):
  62. """Same as `os.chown` function but accepting user login or group name as
  63. argument. If login or group is omitted, it's left unchanged.
  64. Note: you must own the file to chown it (or be root). Otherwise OSError is raised.
  65. """
  66. if login is None:
  67. uid = -1
  68. else:
  69. try:
  70. uid = int(login)
  71. except ValueError:
  72. import pwd # Platforms: Unix
  73. uid = pwd.getpwnam(login).pw_uid
  74. if group is None:
  75. gid = -1
  76. else:
  77. try:
  78. gid = int(group)
  79. except ValueError:
  80. import grp
  81. gid = grp.getgrnam(group).gr_gid
  82. os.chown(path, uid, gid)
  83. def mv(source, destination, _action=shutil.move):
  84. """A shell-like mv, supporting wildcards.
  85. """
  86. sources = glob.glob(source)
  87. if len(sources) > 1:
  88. assert isdir(destination)
  89. for filename in sources:
  90. _action(filename, join(destination, basename(filename)))
  91. else:
  92. try:
  93. source = sources[0]
  94. except IndexError:
  95. raise OSError('No file matching %s' % source)
  96. if isdir(destination) and exists(destination):
  97. destination = join(destination, basename(source))
  98. try:
  99. _action(source, destination)
  100. except OSError, ex:
  101. raise OSError('Unable to move %r to %r (%s)' % (
  102. source, destination, ex))
  103. def rm(*files):
  104. """A shell-like rm, supporting wildcards.
  105. """
  106. for wfile in files:
  107. for filename in glob.glob(wfile):
  108. if islink(filename):
  109. os.remove(filename)
  110. elif isdir(filename):
  111. shutil.rmtree(filename)
  112. else:
  113. os.remove(filename)
  114. def cp(source, destination):
  115. """A shell-like cp, supporting wildcards.
  116. """
  117. mv(source, destination, _action=shutil.copy)
  118. def find(directory, exts, exclude=False, blacklist=STD_BLACKLIST):
  119. """Recursively find files ending with the given extensions from the directory.
  120. :type directory: str
  121. :param directory:
  122. directory where the search should start
  123. :type exts: basestring or list or tuple
  124. :param exts:
  125. extensions or lists or extensions to search
  126. :type exclude: boolean
  127. :param exts:
  128. if this argument is True, returning files NOT ending with the given
  129. extensions
  130. :type blacklist: list or tuple
  131. :param blacklist:
  132. optional list of files or directory to ignore, default to the value of
  133. `logilab.common.STD_BLACKLIST`
  134. :rtype: list
  135. :return:
  136. the list of all matching files
  137. """
  138. if isinstance(exts, basestring):
  139. exts = (exts,)
  140. if exclude:
  141. def match(filename, exts):
  142. for ext in exts:
  143. if filename.endswith(ext):
  144. return False
  145. return True
  146. else:
  147. def match(filename, exts):
  148. for ext in exts:
  149. if filename.endswith(ext):
  150. return True
  151. return False
  152. files = []
  153. for dirpath, dirnames, filenames in os.walk(directory):
  154. _handle_blacklist(blacklist, dirnames, filenames)
  155. # don't append files if the directory is blacklisted
  156. dirname = basename(dirpath)
  157. if dirname in blacklist:
  158. continue
  159. files.extend([join(dirpath, f) for f in filenames if match(f, exts)])
  160. return files
  161. def globfind(directory, pattern, blacklist=STD_BLACKLIST):
  162. """Recursively finds files matching glob `pattern` under `directory`.
  163. This is an alternative to `logilab.common.shellutils.find`.
  164. :type directory: str
  165. :param directory:
  166. directory where the search should start
  167. :type pattern: basestring
  168. :param pattern:
  169. the glob pattern (e.g *.py, foo*.py, etc.)
  170. :type blacklist: list or tuple
  171. :param blacklist:
  172. optional list of files or directory to ignore, default to the value of
  173. `logilab.common.STD_BLACKLIST`
  174. :rtype: iterator
  175. :return:
  176. iterator over the list of all matching files
  177. """
  178. for curdir, dirnames, filenames in os.walk(directory):
  179. _handle_blacklist(blacklist, dirnames, filenames)
  180. for fname in fnmatch.filter(filenames, pattern):
  181. yield join(curdir, fname)
  182. def unzip(archive, destdir):
  183. import zipfile
  184. if not exists(destdir):
  185. os.mkdir(destdir)
  186. zfobj = zipfile.ZipFile(archive)
  187. for name in zfobj.namelist():
  188. if name.endswith('/'):
  189. os.mkdir(join(destdir, name))
  190. else:
  191. outfile = open(join(destdir, name), 'wb')
  192. outfile.write(zfobj.read(name))
  193. outfile.close()
  194. class Execute:
  195. """This is a deadlock safe version of popen2 (no stdin), that returns
  196. an object with errorlevel, out and err.
  197. """
  198. def __init__(self, command):
  199. outfile = tempfile.mktemp()
  200. errfile = tempfile.mktemp()
  201. self.status = os.system("( %s ) >%s 2>%s" %
  202. (command, outfile, errfile)) >> 8
  203. self.out = open(outfile, "r").read()
  204. self.err = open(errfile, "r").read()
  205. os.remove(outfile)
  206. os.remove(errfile)
  207. def acquire_lock(lock_file, max_try=10, delay=10, max_delay=3600):
  208. """Acquire a lock represented by a file on the file system
  209. If the process written in lock file doesn't exist anymore, we remove the
  210. lock file immediately
  211. If age of the lock_file is greater than max_delay, then we raise a UserWarning
  212. """
  213. count = abs(max_try)
  214. while count:
  215. try:
  216. fd = os.open(lock_file, os.O_EXCL | os.O_RDWR | os.O_CREAT)
  217. os.write(fd, str_to_bytes(str(os.getpid())) )
  218. os.close(fd)
  219. return True
  220. except OSError, e:
  221. if e.errno == errno.EEXIST:
  222. try:
  223. fd = open(lock_file, "r")
  224. pid = int(fd.readline())
  225. pi = ProcInfo(pid)
  226. age = (time.time() - os.stat(lock_file)[stat.ST_MTIME])
  227. if age / max_delay > 1 :
  228. raise UserWarning("Command '%s' (pid %s) has locked the "
  229. "file '%s' for %s minutes"
  230. % (pi.name(), pid, lock_file, age/60))
  231. except UserWarning:
  232. raise
  233. except NoSuchProcess:
  234. os.remove(lock_file)
  235. except Exception:
  236. # The try block is not essential. can be skipped.
  237. # Note: ProcInfo object is only available for linux
  238. # process information are not accessible...
  239. # or lock_file is no more present...
  240. pass
  241. else:
  242. raise
  243. count -= 1
  244. time.sleep(delay)
  245. else:
  246. raise Exception('Unable to acquire %s' % lock_file)
  247. def release_lock(lock_file):
  248. """Release a lock represented by a file on the file system."""
  249. os.remove(lock_file)
  250. class ProgressBar(object):
  251. """A simple text progression bar."""
  252. def __init__(self, nbops, size=20, stream=sys.stdout, title=''):
  253. if title:
  254. self._fstr = '\r%s [%%-%ss]' % (title, int(size))
  255. else:
  256. self._fstr = '\r[%%-%ss]' % int(size)
  257. self._stream = stream
  258. self._total = nbops
  259. self._size = size
  260. self._current = 0
  261. self._progress = 0
  262. self._current_text = None
  263. self._last_text_write_size = 0
  264. def _get_text(self):
  265. return self._current_text
  266. def _set_text(self, text=None):
  267. if text != self._current_text:
  268. self._current_text = text
  269. self.refresh()
  270. def _del_text(self):
  271. self.text = None
  272. text = property(_get_text, _set_text, _del_text)
  273. def update(self, offset=1, exact=False):
  274. """Move FORWARD to new cursor position (cursor will never go backward).
  275. :offset: fraction of ``size``
  276. :exact:
  277. - False: offset relative to current cursor position if True
  278. - True: offset as an asbsolute position
  279. """
  280. if exact:
  281. self._current = offset
  282. else:
  283. self._current += offset
  284. progress = int((float(self._current)/float(self._total))*self._size)
  285. if progress > self._progress:
  286. self._progress = progress
  287. self.refresh()
  288. def refresh(self):
  289. """Refresh the progression bar display."""
  290. self._stream.write(self._fstr % ('.' * min(self._progress, self._size)) )
  291. if self._last_text_write_size or self._current_text:
  292. template = ' %%-%is' % (self._last_text_write_size)
  293. text = self._current_text
  294. if text is None:
  295. text = ''
  296. self._stream.write(template % text)
  297. self._last_text_write_size = len(text.rstrip())
  298. self._stream.flush()
  299. def finish(self):
  300. self._stream.write('\n')
  301. self._stream.flush()
  302. class DummyProgressBar(object):
  303. __slot__ = ('text',)
  304. def refresh(self):
  305. pass
  306. def update(self):
  307. pass
  308. def finish(self):
  309. pass
  310. _MARKER = object()
  311. class progress(object):
  312. def __init__(self, nbops=_MARKER, size=_MARKER, stream=_MARKER, title=_MARKER, enabled=True):
  313. self.nbops = nbops
  314. self.size = size
  315. self.stream = stream
  316. self.title = title
  317. self.enabled = enabled
  318. def __enter__(self):
  319. if self.enabled:
  320. kwargs = {}
  321. for attr in ('nbops', 'size', 'stream', 'title'):
  322. value = getattr(self, attr)
  323. if value is not _MARKER:
  324. kwargs[attr] = value
  325. self.pb = ProgressBar(**kwargs)
  326. else:
  327. self.pb = DummyProgressBar()
  328. return self.pb
  329. def __exit__(self, exc_type, exc_val, exc_tb):
  330. self.pb.finish()
  331. class RawInput(object):
  332. def __init__(self, input=None, printer=None):
  333. self._input = input or raw_input
  334. self._print = printer
  335. def ask(self, question, options, default):
  336. assert default in options
  337. choices = []
  338. for option in options:
  339. if option == default:
  340. label = option[0].upper()
  341. else:
  342. label = option[0].lower()
  343. if len(option) > 1:
  344. label += '(%s)' % option[1:].lower()
  345. choices.append((option, label))
  346. prompt = "%s [%s]: " % (question,
  347. '/'.join([opt[1] for opt in choices]))
  348. tries = 3
  349. while tries > 0:
  350. answer = self._input(prompt).strip().lower()
  351. if not answer:
  352. return default
  353. possible = [option for option, label in choices
  354. if option.lower().startswith(answer)]
  355. if len(possible) == 1:
  356. return possible[0]
  357. elif len(possible) == 0:
  358. msg = '%s is not an option.' % answer
  359. else:
  360. msg = ('%s is an ambiguous answer, do you mean %s ?' % (
  361. answer, ' or '.join(possible)))
  362. if self._print:
  363. self._print(msg)
  364. else:
  365. print msg
  366. tries -= 1
  367. raise Exception('unable to get a sensible answer')
  368. def confirm(self, question, default_is_yes=True):
  369. default = default_is_yes and 'y' or 'n'
  370. answer = self.ask(question, ('y', 'n'), default)
  371. return answer == 'y'
  372. ASK = RawInput()
  373. def getlogin():
  374. """avoid using os.getlogin() because of strange tty / stdin problems
  375. (man 3 getlogin)
  376. Another solution would be to use $LOGNAME, $USER or $USERNAME
  377. """
  378. if sys.platform != 'win32':
  379. import pwd # Platforms: Unix
  380. return pwd.getpwuid(os.getuid())[0]
  381. else:
  382. return os.environ['USERNAME']
  383. def generate_password(length=8, vocab=string.ascii_letters + string.digits):
  384. """dumb password generation function"""
  385. pwd = ''
  386. for i in xrange(length):
  387. pwd += random.choice(vocab)
  388. return pwd