PageRenderTime 67ms CodeModel.GetById 37ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/windows.py

https://bitbucket.org/mirror/mercurial/
Python | 338 lines | 267 code | 29 blank | 42 comment | 27 complexity | 7d5dcabd251f4e05a24599a4cd7ba726 MD5 | raw file
Possible License(s): GPL-2.0
  1. # windows.py - Windows utility function implementations for Mercurial
  2. #
  3. # Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. from i18n import _
  8. import osutil, encoding
  9. import errno, msvcrt, os, re, stat, sys, _winreg
  10. import win32
  11. executablepath = win32.executablepath
  12. getuser = win32.getuser
  13. hidewindow = win32.hidewindow
  14. makedir = win32.makedir
  15. nlinks = win32.nlinks
  16. oslink = win32.oslink
  17. samedevice = win32.samedevice
  18. samefile = win32.samefile
  19. setsignalhandler = win32.setsignalhandler
  20. spawndetached = win32.spawndetached
  21. split = os.path.split
  22. termwidth = win32.termwidth
  23. testpid = win32.testpid
  24. unlink = win32.unlink
  25. umask = 0022
  26. # wrap osutil.posixfile to provide friendlier exceptions
  27. def posixfile(name, mode='r', buffering=-1):
  28. try:
  29. return osutil.posixfile(name, mode, buffering)
  30. except WindowsError, err:
  31. raise IOError(err.errno, '%s: %s' % (name, err.strerror))
  32. posixfile.__doc__ = osutil.posixfile.__doc__
  33. class winstdout(object):
  34. '''stdout on windows misbehaves if sent through a pipe'''
  35. def __init__(self, fp):
  36. self.fp = fp
  37. def __getattr__(self, key):
  38. return getattr(self.fp, key)
  39. def close(self):
  40. try:
  41. self.fp.close()
  42. except IOError:
  43. pass
  44. def write(self, s):
  45. try:
  46. # This is workaround for "Not enough space" error on
  47. # writing large size of data to console.
  48. limit = 16000
  49. l = len(s)
  50. start = 0
  51. self.softspace = 0
  52. while start < l:
  53. end = start + limit
  54. self.fp.write(s[start:end])
  55. start = end
  56. except IOError, inst:
  57. if inst.errno != 0:
  58. raise
  59. self.close()
  60. raise IOError(errno.EPIPE, 'Broken pipe')
  61. def flush(self):
  62. try:
  63. return self.fp.flush()
  64. except IOError, inst:
  65. if inst.errno != errno.EINVAL:
  66. raise
  67. self.close()
  68. raise IOError(errno.EPIPE, 'Broken pipe')
  69. sys.__stdout__ = sys.stdout = winstdout(sys.stdout)
  70. def _is_win_9x():
  71. '''return true if run on windows 95, 98 or me.'''
  72. try:
  73. return sys.getwindowsversion()[3] == 1
  74. except AttributeError:
  75. return 'command' in os.environ.get('comspec', '')
  76. def openhardlinks():
  77. return not _is_win_9x()
  78. def parsepatchoutput(output_line):
  79. """parses the output produced by patch and returns the filename"""
  80. pf = output_line[14:]
  81. if pf[0] == '`':
  82. pf = pf[1:-1] # Remove the quotes
  83. return pf
  84. def sshargs(sshcmd, host, user, port):
  85. '''Build argument list for ssh or Plink'''
  86. pflag = 'plink' in sshcmd.lower() and '-P' or '-p'
  87. args = user and ("%s@%s" % (user, host)) or host
  88. return port and ("%s %s %s" % (args, pflag, port)) or args
  89. def setflags(f, l, x):
  90. pass
  91. def copymode(src, dst, mode=None):
  92. pass
  93. def checkexec(path):
  94. return False
  95. def checklink(path):
  96. return False
  97. def setbinary(fd):
  98. # When run without console, pipes may expose invalid
  99. # fileno(), usually set to -1.
  100. fno = getattr(fd, 'fileno', None)
  101. if fno is not None and fno() >= 0:
  102. msvcrt.setmode(fno(), os.O_BINARY)
  103. def pconvert(path):
  104. return path.replace(os.sep, '/')
  105. def localpath(path):
  106. return path.replace('/', '\\')
  107. def normpath(path):
  108. return pconvert(os.path.normpath(path))
  109. def normcase(path):
  110. return encoding.upper(path)
  111. def samestat(s1, s2):
  112. return False
  113. # A sequence of backslashes is special iff it precedes a double quote:
  114. # - if there's an even number of backslashes, the double quote is not
  115. # quoted (i.e. it ends the quoted region)
  116. # - if there's an odd number of backslashes, the double quote is quoted
  117. # - in both cases, every pair of backslashes is unquoted into a single
  118. # backslash
  119. # (See http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx )
  120. # So, to quote a string, we must surround it in double quotes, double
  121. # the number of backslashes that precede double quotes and add another
  122. # backslash before every double quote (being careful with the double
  123. # quote we've appended to the end)
  124. _quotere = None
  125. def shellquote(s):
  126. global _quotere
  127. if _quotere is None:
  128. _quotere = re.compile(r'(\\*)("|\\$)')
  129. return '"%s"' % _quotere.sub(r'\1\1\\\2', s)
  130. def quotecommand(cmd):
  131. """Build a command string suitable for os.popen* calls."""
  132. if sys.version_info < (2, 7, 1):
  133. # Python versions since 2.7.1 do this extra quoting themselves
  134. return '"' + cmd + '"'
  135. return cmd
  136. def popen(command, mode='r'):
  137. # Work around "popen spawned process may not write to stdout
  138. # under windows"
  139. # http://bugs.python.org/issue1366
  140. command += " 2> %s" % os.devnull
  141. return os.popen(quotecommand(command), mode)
  142. def explainexit(code):
  143. return _("exited with status %d") % code, code
  144. # if you change this stub into a real check, please try to implement the
  145. # username and groupname functions above, too.
  146. def isowner(st):
  147. return True
  148. def findexe(command):
  149. '''Find executable for command searching like cmd.exe does.
  150. If command is a basename then PATH is searched for command.
  151. PATH isn't searched if command is an absolute or relative path.
  152. An extension from PATHEXT is found and added if not present.
  153. If command isn't found None is returned.'''
  154. pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD')
  155. pathexts = [ext for ext in pathext.lower().split(os.pathsep)]
  156. if os.path.splitext(command)[1].lower() in pathexts:
  157. pathexts = ['']
  158. def findexisting(pathcommand):
  159. 'Will append extension (if needed) and return existing file'
  160. for ext in pathexts:
  161. executable = pathcommand + ext
  162. if os.path.exists(executable):
  163. return executable
  164. return None
  165. if os.sep in command:
  166. return findexisting(command)
  167. for path in os.environ.get('PATH', '').split(os.pathsep):
  168. executable = findexisting(os.path.join(path, command))
  169. if executable is not None:
  170. return executable
  171. return findexisting(os.path.expanduser(os.path.expandvars(command)))
  172. _wantedkinds = set([stat.S_IFREG, stat.S_IFLNK])
  173. def statfiles(files):
  174. '''Stat each file in files. Yield each stat, or None if a file
  175. does not exist or has a type we don't care about.
  176. Cluster and cache stat per directory to minimize number of OS stat calls.'''
  177. dircache = {} # dirname -> filename -> status | None if file does not exist
  178. getkind = stat.S_IFMT
  179. for nf in files:
  180. nf = normcase(nf)
  181. dir, base = os.path.split(nf)
  182. if not dir:
  183. dir = '.'
  184. cache = dircache.get(dir, None)
  185. if cache is None:
  186. try:
  187. dmap = dict([(normcase(n), s)
  188. for n, k, s in osutil.listdir(dir, True)
  189. if getkind(s.st_mode) in _wantedkinds])
  190. except OSError, err:
  191. # handle directory not found in Python version prior to 2.5
  192. # Python <= 2.4 returns native Windows code 3 in errno
  193. # Python >= 2.5 returns ENOENT and adds winerror field
  194. # EINVAL is raised if dir is not a directory.
  195. if err.errno not in (3, errno.ENOENT, errno.EINVAL,
  196. errno.ENOTDIR):
  197. raise
  198. dmap = {}
  199. cache = dircache.setdefault(dir, dmap)
  200. yield cache.get(base, None)
  201. def username(uid=None):
  202. """Return the name of the user with the given uid.
  203. If uid is None, return the name of the current user."""
  204. return None
  205. def groupname(gid=None):
  206. """Return the name of the group with the given gid.
  207. If gid is None, return the name of the current group."""
  208. return None
  209. def _removedirs(name):
  210. """special version of os.removedirs that does not remove symlinked
  211. directories or junction points if they actually contain files"""
  212. if osutil.listdir(name):
  213. return
  214. os.rmdir(name)
  215. head, tail = os.path.split(name)
  216. if not tail:
  217. head, tail = os.path.split(head)
  218. while head and tail:
  219. try:
  220. if osutil.listdir(head):
  221. return
  222. os.rmdir(head)
  223. except (ValueError, OSError):
  224. break
  225. head, tail = os.path.split(head)
  226. def unlinkpath(f, ignoremissing=False):
  227. """unlink and remove the directory if it is empty"""
  228. try:
  229. unlink(f)
  230. except OSError, e:
  231. if not (ignoremissing and e.errno == errno.ENOENT):
  232. raise
  233. # try removing directories that might now be empty
  234. try:
  235. _removedirs(os.path.dirname(f))
  236. except OSError:
  237. pass
  238. def rename(src, dst):
  239. '''atomically rename file src to dst, replacing dst if it exists'''
  240. try:
  241. os.rename(src, dst)
  242. except OSError, e:
  243. if e.errno != errno.EEXIST:
  244. raise
  245. unlink(dst)
  246. os.rename(src, dst)
  247. def gethgcmd():
  248. return [sys.executable] + sys.argv[:1]
  249. def groupmembers(name):
  250. # Don't support groups on Windows for now
  251. raise KeyError
  252. def isexec(f):
  253. return False
  254. class cachestat(object):
  255. def __init__(self, path):
  256. pass
  257. def cacheable(self):
  258. return False
  259. def lookupreg(key, valname=None, scope=None):
  260. ''' Look up a key/value name in the Windows registry.
  261. valname: value name. If unspecified, the default value for the key
  262. is used.
  263. scope: optionally specify scope for registry lookup, this can be
  264. a sequence of scopes to look up in order. Default (CURRENT_USER,
  265. LOCAL_MACHINE).
  266. '''
  267. if scope is None:
  268. scope = (_winreg.HKEY_CURRENT_USER, _winreg.HKEY_LOCAL_MACHINE)
  269. elif not isinstance(scope, (list, tuple)):
  270. scope = (scope,)
  271. for s in scope:
  272. try:
  273. val = _winreg.QueryValueEx(_winreg.OpenKey(s, key), valname)[0]
  274. # never let a Unicode string escape into the wild
  275. return encoding.tolocal(val.encode('UTF-8'))
  276. except EnvironmentError:
  277. pass
  278. expandglobs = True
  279. def statislink(st):
  280. '''check whether a stat result is a symlink'''
  281. return False
  282. def statisexec(st):
  283. '''check whether a stat result is an executable file'''
  284. return False