svnurl.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """
  2. module defining a subversion path object based on the external
  3. command 'svn'. This modules aims to work with svn 1.3 and higher
  4. but might also interact well with earlier versions.
  5. """
  6. import os, sys, time, re
  7. import py
  8. from py import path, process
  9. from py._path import common
  10. from py._path import svnwc as svncommon
  11. from py._path.cacheutil import BuildcostAccessCache, AgingCache
  12. DEBUG=False
  13. class SvnCommandPath(svncommon.SvnPathBase):
  14. """ path implementation that offers access to (possibly remote) subversion
  15. repositories. """
  16. _lsrevcache = BuildcostAccessCache(maxentries=128)
  17. _lsnorevcache = AgingCache(maxentries=1000, maxseconds=60.0)
  18. def __new__(cls, path, rev=None, auth=None):
  19. self = object.__new__(cls)
  20. if isinstance(path, cls):
  21. rev = path.rev
  22. auth = path.auth
  23. path = path.strpath
  24. svncommon.checkbadchars(path)
  25. path = path.rstrip('/')
  26. self.strpath = path
  27. self.rev = rev
  28. self.auth = auth
  29. return self
  30. def __repr__(self):
  31. if self.rev == -1:
  32. return 'svnurl(%r)' % self.strpath
  33. else:
  34. return 'svnurl(%r, %r)' % (self.strpath, self.rev)
  35. def _svnwithrev(self, cmd, *args):
  36. """ execute an svn command, append our own url and revision """
  37. if self.rev is None:
  38. return self._svnwrite(cmd, *args)
  39. else:
  40. args = ['-r', self.rev] + list(args)
  41. return self._svnwrite(cmd, *args)
  42. def _svnwrite(self, cmd, *args):
  43. """ execute an svn command, append our own url """
  44. l = ['svn %s' % cmd]
  45. args = ['"%s"' % self._escape(item) for item in args]
  46. l.extend(args)
  47. l.append('"%s"' % self._encodedurl())
  48. # fixing the locale because we can't otherwise parse
  49. string = " ".join(l)
  50. if DEBUG:
  51. print("execing %s" % string)
  52. out = self._svncmdexecauth(string)
  53. return out
  54. def _svncmdexecauth(self, cmd):
  55. """ execute an svn command 'as is' """
  56. cmd = svncommon.fixlocale() + cmd
  57. if self.auth is not None:
  58. cmd += ' ' + self.auth.makecmdoptions()
  59. return self._cmdexec(cmd)
  60. def _cmdexec(self, cmd):
  61. try:
  62. out = process.cmdexec(cmd)
  63. except py.process.cmdexec.Error:
  64. e = sys.exc_info()[1]
  65. if (e.err.find('File Exists') != -1 or
  66. e.err.find('File already exists') != -1):
  67. raise py.error.EEXIST(self)
  68. raise
  69. return out
  70. def _svnpopenauth(self, cmd):
  71. """ execute an svn command, return a pipe for reading stdin """
  72. cmd = svncommon.fixlocale() + cmd
  73. if self.auth is not None:
  74. cmd += ' ' + self.auth.makecmdoptions()
  75. return self._popen(cmd)
  76. def _popen(self, cmd):
  77. return os.popen(cmd)
  78. def _encodedurl(self):
  79. return self._escape(self.strpath)
  80. def _norev_delentry(self, path):
  81. auth = self.auth and self.auth.makecmdoptions() or None
  82. self._lsnorevcache.delentry((str(path), auth))
  83. def open(self, mode='r'):
  84. """ return an opened file with the given mode. """
  85. if mode not in ("r", "rU",):
  86. raise ValueError("mode %r not supported" % (mode,))
  87. assert self.check(file=1) # svn cat returns an empty file otherwise
  88. if self.rev is None:
  89. return self._svnpopenauth('svn cat "%s"' % (
  90. self._escape(self.strpath), ))
  91. else:
  92. return self._svnpopenauth('svn cat -r %s "%s"' % (
  93. self.rev, self._escape(self.strpath)))
  94. def dirpath(self, *args, **kwargs):
  95. """ return the directory path of the current path joined
  96. with any given path arguments.
  97. """
  98. l = self.strpath.split(self.sep)
  99. if len(l) < 4:
  100. raise py.error.EINVAL(self, "base is not valid")
  101. elif len(l) == 4:
  102. return self.join(*args, **kwargs)
  103. else:
  104. return self.new(basename='').join(*args, **kwargs)
  105. # modifying methods (cache must be invalidated)
  106. def mkdir(self, *args, **kwargs):
  107. """ create & return the directory joined with args.
  108. pass a 'msg' keyword argument to set the commit message.
  109. """
  110. commit_msg = kwargs.get('msg', "mkdir by py lib invocation")
  111. createpath = self.join(*args)
  112. createpath._svnwrite('mkdir', '-m', commit_msg)
  113. self._norev_delentry(createpath.dirpath())
  114. return createpath
  115. def copy(self, target, msg='copied by py lib invocation'):
  116. """ copy path to target with checkin message msg."""
  117. if getattr(target, 'rev', None) is not None:
  118. raise py.error.EINVAL(target, "revisions are immutable")
  119. self._svncmdexecauth('svn copy -m "%s" "%s" "%s"' %(msg,
  120. self._escape(self), self._escape(target)))
  121. self._norev_delentry(target.dirpath())
  122. def rename(self, target, msg="renamed by py lib invocation"):
  123. """ rename this path to target with checkin message msg. """
  124. if getattr(self, 'rev', None) is not None:
  125. raise py.error.EINVAL(self, "revisions are immutable")
  126. self._svncmdexecauth('svn move -m "%s" --force "%s" "%s"' %(
  127. msg, self._escape(self), self._escape(target)))
  128. self._norev_delentry(self.dirpath())
  129. self._norev_delentry(self)
  130. def remove(self, rec=1, msg='removed by py lib invocation'):
  131. """ remove a file or directory (or a directory tree if rec=1) with
  132. checkin message msg."""
  133. if self.rev is not None:
  134. raise py.error.EINVAL(self, "revisions are immutable")
  135. self._svncmdexecauth('svn rm -m "%s" "%s"' %(msg, self._escape(self)))
  136. self._norev_delentry(self.dirpath())
  137. def export(self, topath):
  138. """ export to a local path
  139. topath should not exist prior to calling this, returns a
  140. py.path.local instance
  141. """
  142. topath = py.path.local(topath)
  143. args = ['"%s"' % (self._escape(self),),
  144. '"%s"' % (self._escape(topath),)]
  145. if self.rev is not None:
  146. args = ['-r', str(self.rev)] + args
  147. self._svncmdexecauth('svn export %s' % (' '.join(args),))
  148. return topath
  149. def ensure(self, *args, **kwargs):
  150. """ ensure that an args-joined path exists (by default as
  151. a file). If you specify a keyword argument 'dir=True'
  152. then the path is forced to be a directory path.
  153. """
  154. if getattr(self, 'rev', None) is not None:
  155. raise py.error.EINVAL(self, "revisions are immutable")
  156. target = self.join(*args)
  157. dir = kwargs.get('dir', 0)
  158. for x in target.parts(reverse=True):
  159. if x.check():
  160. break
  161. else:
  162. raise py.error.ENOENT(target, "has not any valid base!")
  163. if x == target:
  164. if not x.check(dir=dir):
  165. raise dir and py.error.ENOTDIR(x) or py.error.EISDIR(x)
  166. return x
  167. tocreate = target.relto(x)
  168. basename = tocreate.split(self.sep, 1)[0]
  169. tempdir = py.path.local.mkdtemp()
  170. try:
  171. tempdir.ensure(tocreate, dir=dir)
  172. cmd = 'svn import -m "%s" "%s" "%s"' % (
  173. "ensure %s" % self._escape(tocreate),
  174. self._escape(tempdir.join(basename)),
  175. x.join(basename)._encodedurl())
  176. self._svncmdexecauth(cmd)
  177. self._norev_delentry(x)
  178. finally:
  179. tempdir.remove()
  180. return target
  181. # end of modifying methods
  182. def _propget(self, name):
  183. res = self._svnwithrev('propget', name)
  184. return res[:-1] # strip trailing newline
  185. def _proplist(self):
  186. res = self._svnwithrev('proplist')
  187. lines = res.split('\n')
  188. lines = [x.strip() for x in lines[1:]]
  189. return svncommon.PropListDict(self, lines)
  190. def info(self):
  191. """ return an Info structure with svn-provided information. """
  192. parent = self.dirpath()
  193. nameinfo_seq = parent._listdir_nameinfo()
  194. bn = self.basename
  195. for name, info in nameinfo_seq:
  196. if name == bn:
  197. return info
  198. raise py.error.ENOENT(self)
  199. def _listdir_nameinfo(self):
  200. """ return sequence of name-info directory entries of self """
  201. def builder():
  202. try:
  203. res = self._svnwithrev('ls', '-v')
  204. except process.cmdexec.Error:
  205. e = sys.exc_info()[1]
  206. if e.err.find('non-existent in that revision') != -1:
  207. raise py.error.ENOENT(self, e.err)
  208. elif e.err.find("E200009:") != -1:
  209. raise py.error.ENOENT(self, e.err)
  210. elif e.err.find('File not found') != -1:
  211. raise py.error.ENOENT(self, e.err)
  212. elif e.err.find('not part of a repository')!=-1:
  213. raise py.error.ENOENT(self, e.err)
  214. elif e.err.find('Unable to open')!=-1:
  215. raise py.error.ENOENT(self, e.err)
  216. elif e.err.lower().find('method not allowed')!=-1:
  217. raise py.error.EACCES(self, e.err)
  218. raise py.error.Error(e.err)
  219. lines = res.split('\n')
  220. nameinfo_seq = []
  221. for lsline in lines:
  222. if lsline:
  223. info = InfoSvnCommand(lsline)
  224. if info._name != '.': # svn 1.5 produces '.' dirs,
  225. nameinfo_seq.append((info._name, info))
  226. nameinfo_seq.sort()
  227. return nameinfo_seq
  228. auth = self.auth and self.auth.makecmdoptions() or None
  229. if self.rev is not None:
  230. return self._lsrevcache.getorbuild((self.strpath, self.rev, auth),
  231. builder)
  232. else:
  233. return self._lsnorevcache.getorbuild((self.strpath, auth),
  234. builder)
  235. def listdir(self, fil=None, sort=None):
  236. """ list directory contents, possibly filter by the given fil func
  237. and possibly sorted.
  238. """
  239. if isinstance(fil, str):
  240. fil = common.FNMatcher(fil)
  241. nameinfo_seq = self._listdir_nameinfo()
  242. if len(nameinfo_seq) == 1:
  243. name, info = nameinfo_seq[0]
  244. if name == self.basename and info.kind == 'file':
  245. #if not self.check(dir=1):
  246. raise py.error.ENOTDIR(self)
  247. paths = [self.join(name) for (name, info) in nameinfo_seq]
  248. if fil:
  249. paths = [x for x in paths if fil(x)]
  250. self._sortlist(paths, sort)
  251. return paths
  252. def log(self, rev_start=None, rev_end=1, verbose=False):
  253. """ return a list of LogEntry instances for this path.
  254. rev_start is the starting revision (defaulting to the first one).
  255. rev_end is the last revision (defaulting to HEAD).
  256. if verbose is True, then the LogEntry instances also know which files changed.
  257. """
  258. assert self.check() #make it simpler for the pipe
  259. rev_start = rev_start is None and "HEAD" or rev_start
  260. rev_end = rev_end is None and "HEAD" or rev_end
  261. if rev_start == "HEAD" and rev_end == 1:
  262. rev_opt = ""
  263. else:
  264. rev_opt = "-r %s:%s" % (rev_start, rev_end)
  265. verbose_opt = verbose and "-v" or ""
  266. xmlpipe = self._svnpopenauth('svn log --xml %s %s "%s"' %
  267. (rev_opt, verbose_opt, self.strpath))
  268. from xml.dom import minidom
  269. tree = minidom.parse(xmlpipe)
  270. result = []
  271. for logentry in filter(None, tree.firstChild.childNodes):
  272. if logentry.nodeType == logentry.ELEMENT_NODE:
  273. result.append(svncommon.LogEntry(logentry))
  274. return result
  275. #01234567890123456789012345678901234567890123467
  276. # 2256 hpk 165 Nov 24 17:55 __init__.py
  277. # XXX spotted by Guido, SVN 1.3.0 has different aligning, breaks the code!!!
  278. # 1312 johnny 1627 May 05 14:32 test_decorators.py
  279. #
  280. class InfoSvnCommand:
  281. # the '0?' part in the middle is an indication of whether the resource is
  282. # locked, see 'svn help ls'
  283. lspattern = re.compile(
  284. r'^ *(?P<rev>\d+) +(?P<author>.+?) +(0? *(?P<size>\d+))? '
  285. r'*(?P<date>\w+ +\d{2} +[\d:]+) +(?P<file>.*)$')
  286. def __init__(self, line):
  287. # this is a typical line from 'svn ls http://...'
  288. #_ 1127 jum 0 Jul 13 15:28 branch/
  289. match = self.lspattern.match(line)
  290. data = match.groupdict()
  291. self._name = data['file']
  292. if self._name[-1] == '/':
  293. self._name = self._name[:-1]
  294. self.kind = 'dir'
  295. else:
  296. self.kind = 'file'
  297. #self.has_props = l.pop(0) == 'P'
  298. self.created_rev = int(data['rev'])
  299. self.last_author = data['author']
  300. self.size = data['size'] and int(data['size']) or 0
  301. self.mtime = parse_time_with_missing_year(data['date'])
  302. self.time = self.mtime * 1000000
  303. def __eq__(self, other):
  304. return self.__dict__ == other.__dict__
  305. #____________________________________________________
  306. #
  307. # helper functions
  308. #____________________________________________________
  309. def parse_time_with_missing_year(timestr):
  310. """ analyze the time part from a single line of "svn ls -v"
  311. the svn output doesn't show the year makes the 'timestr'
  312. ambigous.
  313. """
  314. import calendar
  315. t_now = time.gmtime()
  316. tparts = timestr.split()
  317. month = time.strptime(tparts.pop(0), '%b')[1]
  318. day = time.strptime(tparts.pop(0), '%d')[2]
  319. last = tparts.pop(0) # year or hour:minute
  320. try:
  321. if ":" in last:
  322. raise ValueError()
  323. year = time.strptime(last, '%Y')[0]
  324. hour = minute = 0
  325. except ValueError:
  326. hour, minute = time.strptime(last, '%H:%M')[3:5]
  327. year = t_now[0]
  328. t_result = (year, month, day, hour, minute, 0,0,0,0)
  329. if t_result > t_now:
  330. year -= 1
  331. t_result = (year, month, day, hour, minute, 0,0,0,0)
  332. return calendar.timegm(t_result)
  333. class PathEntry:
  334. def __init__(self, ppart):
  335. self.strpath = ppart.firstChild.nodeValue.encode('UTF-8')
  336. self.action = ppart.getAttribute('action').encode('UTF-8')
  337. if self.action == 'A':
  338. self.copyfrom_path = ppart.getAttribute('copyfrom-path').encode('UTF-8')
  339. if self.copyfrom_path:
  340. self.copyfrom_rev = int(ppart.getAttribute('copyfrom-rev'))