/Demo/pdist/rcslib.py

http://unladen-swallow.googlecode.com/ · Python · 334 lines · 299 code · 9 blank · 26 comment · 2 complexity · 8417c1a220e4a58cfa6fb1160ae8e725 MD5 · raw file

  1. """RCS interface module.
  2. Defines the class RCS, which represents a directory with rcs version
  3. files and (possibly) corresponding work files.
  4. """
  5. import fnmatch
  6. import os
  7. import re
  8. import string
  9. import tempfile
  10. class RCS:
  11. """RCS interface class (local filesystem version).
  12. An instance of this class represents a directory with rcs version
  13. files and (possible) corresponding work files.
  14. Methods provide access to most rcs operations such as
  15. checkin/checkout, access to the rcs metadata (revisions, logs,
  16. branches etc.) as well as some filesystem operations such as
  17. listing all rcs version files.
  18. XXX BUGS / PROBLEMS
  19. - The instance always represents the current directory so it's not
  20. very useful to have more than one instance around simultaneously
  21. """
  22. # Characters allowed in work file names
  23. okchars = string.ascii_letters + string.digits + '-_=+'
  24. def __init__(self):
  25. """Constructor."""
  26. pass
  27. def __del__(self):
  28. """Destructor."""
  29. pass
  30. # --- Informational methods about a single file/revision ---
  31. def log(self, name_rev, otherflags = ''):
  32. """Return the full log text for NAME_REV as a string.
  33. Optional OTHERFLAGS are passed to rlog.
  34. """
  35. f = self._open(name_rev, 'rlog ' + otherflags)
  36. data = f.read()
  37. status = self._closepipe(f)
  38. if status:
  39. data = data + "%s: %s" % status
  40. elif data[-1] == '\n':
  41. data = data[:-1]
  42. return data
  43. def head(self, name_rev):
  44. """Return the head revision for NAME_REV"""
  45. dict = self.info(name_rev)
  46. return dict['head']
  47. def info(self, name_rev):
  48. """Return a dictionary of info (from rlog -h) for NAME_REV
  49. The dictionary's keys are the keywords that rlog prints
  50. (e.g. 'head' and its values are the corresponding data
  51. (e.g. '1.3').
  52. XXX symbolic names and locks are not returned
  53. """
  54. f = self._open(name_rev, 'rlog -h')
  55. dict = {}
  56. while 1:
  57. line = f.readline()
  58. if not line: break
  59. if line[0] == '\t':
  60. # XXX could be a lock or symbolic name
  61. # Anything else?
  62. continue
  63. i = string.find(line, ':')
  64. if i > 0:
  65. key, value = line[:i], string.strip(line[i+1:])
  66. dict[key] = value
  67. status = self._closepipe(f)
  68. if status:
  69. raise IOError, status
  70. return dict
  71. # --- Methods that change files ---
  72. def lock(self, name_rev):
  73. """Set an rcs lock on NAME_REV."""
  74. name, rev = self.checkfile(name_rev)
  75. cmd = "rcs -l%s %s" % (rev, name)
  76. return self._system(cmd)
  77. def unlock(self, name_rev):
  78. """Clear an rcs lock on NAME_REV."""
  79. name, rev = self.checkfile(name_rev)
  80. cmd = "rcs -u%s %s" % (rev, name)
  81. return self._system(cmd)
  82. def checkout(self, name_rev, withlock=0, otherflags=""):
  83. """Check out NAME_REV to its work file.
  84. If optional WITHLOCK is set, check out locked, else unlocked.
  85. The optional OTHERFLAGS is passed to co without
  86. interpretation.
  87. Any output from co goes to directly to stdout.
  88. """
  89. name, rev = self.checkfile(name_rev)
  90. if withlock: lockflag = "-l"
  91. else: lockflag = "-u"
  92. cmd = 'co %s%s %s %s' % (lockflag, rev, otherflags, name)
  93. return self._system(cmd)
  94. def checkin(self, name_rev, message=None, otherflags=""):
  95. """Check in NAME_REV from its work file.
  96. The optional MESSAGE argument becomes the checkin message
  97. (default "<none>" if None); or the file description if this is
  98. a new file.
  99. The optional OTHERFLAGS argument is passed to ci without
  100. interpretation.
  101. Any output from ci goes to directly to stdout.
  102. """
  103. name, rev = self._unmangle(name_rev)
  104. new = not self.isvalid(name)
  105. if not message: message = "<none>"
  106. if message and message[-1] != '\n':
  107. message = message + '\n'
  108. lockflag = "-u"
  109. if new:
  110. f = tempfile.NamedTemporaryFile()
  111. f.write(message)
  112. f.flush()
  113. cmd = 'ci %s%s -t%s %s %s' % \
  114. (lockflag, rev, f.name, otherflags, name)
  115. else:
  116. message = re.sub(r'([\"$`])', r'\\\1', message)
  117. cmd = 'ci %s%s -m"%s" %s %s' % \
  118. (lockflag, rev, message, otherflags, name)
  119. return self._system(cmd)
  120. # --- Exported support methods ---
  121. def listfiles(self, pat = None):
  122. """Return a list of all version files matching optional PATTERN."""
  123. files = os.listdir(os.curdir)
  124. files = filter(self._isrcs, files)
  125. if os.path.isdir('RCS'):
  126. files2 = os.listdir('RCS')
  127. files2 = filter(self._isrcs, files2)
  128. files = files + files2
  129. files = map(self.realname, files)
  130. return self._filter(files, pat)
  131. def isvalid(self, name):
  132. """Test whether NAME has a version file associated."""
  133. namev = self.rcsname(name)
  134. return (os.path.isfile(namev) or
  135. os.path.isfile(os.path.join('RCS', namev)))
  136. def rcsname(self, name):
  137. """Return the pathname of the version file for NAME.
  138. The argument can be a work file name or a version file name.
  139. If the version file does not exist, the name of the version
  140. file that would be created by "ci" is returned.
  141. """
  142. if self._isrcs(name): namev = name
  143. else: namev = name + ',v'
  144. if os.path.isfile(namev): return namev
  145. namev = os.path.join('RCS', os.path.basename(namev))
  146. if os.path.isfile(namev): return namev
  147. if os.path.isdir('RCS'):
  148. return os.path.join('RCS', namev)
  149. else:
  150. return namev
  151. def realname(self, namev):
  152. """Return the pathname of the work file for NAME.
  153. The argument can be a work file name or a version file name.
  154. If the work file does not exist, the name of the work file
  155. that would be created by "co" is returned.
  156. """
  157. if self._isrcs(namev): name = namev[:-2]
  158. else: name = namev
  159. if os.path.isfile(name): return name
  160. name = os.path.basename(name)
  161. return name
  162. def islocked(self, name_rev):
  163. """Test whether FILE (which must have a version file) is locked.
  164. XXX This does not tell you which revision number is locked and
  165. ignores any revision you may pass in (by virtue of using rlog
  166. -L -R).
  167. """
  168. f = self._open(name_rev, 'rlog -L -R')
  169. line = f.readline()
  170. status = self._closepipe(f)
  171. if status:
  172. raise IOError, status
  173. if not line: return None
  174. if line[-1] == '\n':
  175. line = line[:-1]
  176. return self.realname(name_rev) == self.realname(line)
  177. def checkfile(self, name_rev):
  178. """Normalize NAME_REV into a (NAME, REV) tuple.
  179. Raise an exception if there is no corresponding version file.
  180. """
  181. name, rev = self._unmangle(name_rev)
  182. if not self.isvalid(name):
  183. raise os.error, 'not an rcs file %r' % (name,)
  184. return name, rev
  185. # --- Internal methods ---
  186. def _open(self, name_rev, cmd = 'co -p', rflag = '-r'):
  187. """INTERNAL: open a read pipe to NAME_REV using optional COMMAND.
  188. Optional FLAG is used to indicate the revision (default -r).
  189. Default COMMAND is "co -p".
  190. Return a file object connected by a pipe to the command's
  191. output.
  192. """
  193. name, rev = self.checkfile(name_rev)
  194. namev = self.rcsname(name)
  195. if rev:
  196. cmd = cmd + ' ' + rflag + rev
  197. return os.popen("%s %r" % (cmd, namev))
  198. def _unmangle(self, name_rev):
  199. """INTERNAL: Normalize NAME_REV argument to (NAME, REV) tuple.
  200. Raise an exception if NAME contains invalid characters.
  201. A NAME_REV argument is either NAME string (implying REV='') or
  202. a tuple of the form (NAME, REV).
  203. """
  204. if type(name_rev) == type(''):
  205. name_rev = name, rev = name_rev, ''
  206. else:
  207. name, rev = name_rev
  208. for c in rev:
  209. if c not in self.okchars:
  210. raise ValueError, "bad char in rev"
  211. return name_rev
  212. def _closepipe(self, f):
  213. """INTERNAL: Close PIPE and print its exit status if nonzero."""
  214. sts = f.close()
  215. if not sts: return None
  216. detail, reason = divmod(sts, 256)
  217. if reason == 0: return 'exit', detail # Exit status
  218. signal = reason&0x7F
  219. if signal == 0x7F:
  220. code = 'stopped'
  221. signal = detail
  222. else:
  223. code = 'killed'
  224. if reason&0x80:
  225. code = code + '(coredump)'
  226. return code, signal
  227. def _system(self, cmd):
  228. """INTERNAL: run COMMAND in a subshell.
  229. Standard input for the command is taken from /dev/null.
  230. Raise IOError when the exit status is not zero.
  231. Return whatever the calling method should return; normally
  232. None.
  233. A derived class may override this method and redefine it to
  234. capture stdout/stderr of the command and return it.
  235. """
  236. cmd = cmd + " </dev/null"
  237. sts = os.system(cmd)
  238. if sts: raise IOError, "command exit status %d" % sts
  239. def _filter(self, files, pat = None):
  240. """INTERNAL: Return a sorted copy of the given list of FILES.
  241. If a second PATTERN argument is given, only files matching it
  242. are kept. No check for valid filenames is made.
  243. """
  244. if pat:
  245. def keep(name, pat = pat):
  246. return fnmatch.fnmatch(name, pat)
  247. files = filter(keep, files)
  248. else:
  249. files = files[:]
  250. files.sort()
  251. return files
  252. def _remove(self, fn):
  253. """INTERNAL: remove FILE without complaints."""
  254. try:
  255. os.unlink(fn)
  256. except os.error:
  257. pass
  258. def _isrcs(self, name):
  259. """INTERNAL: Test whether NAME ends in ',v'."""
  260. return name[-2:] == ',v'