libbe.storage.vcs.base.VCS._init() now creates the '.be/version' file.
[be.git] / libbe / storage / vcs / base.py
1 # Copyright (C) 2005-2009 Aaron Bentley and Panometrics, Inc.
2 #                         Alexander Belchenko <bialix@ukr.net>
3 #                         Ben Finney <benf@cybersource.com.au>
4 #                         Chris Ball <cjb@laptop.org>
5 #                         Gianluca Montecchi <gian@grys.it>
6 #                         W. Trevor King <wking@drexel.edu>
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with this program; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 """
23 Define the base VCS (Version Control System) class, which should be
24 subclassed by other Version Control System backends.  The base class
25 implements a "do not version" VCS.
26 """
27
28 import codecs
29 import os
30 import os.path
31 import re
32 import shutil
33 import sys
34 import tempfile
35 import types
36
37 import libbe
38 import libbe.storage
39 import libbe.storage.base
40 import libbe.util.encoding
41 from libbe.storage.base import EmptyCommit, InvalidRevision, InvalidID
42 from libbe.util.utility import Dir, search_parent_directories
43 from libbe.util.subproc import CommandError, invoke
44 from libbe.util.plugin import import_by_name
45 import libbe.storage.util.upgrade as upgrade
46
47 if libbe.TESTING == True:
48     import unittest
49     import doctest
50
51     import libbe.ui.util.user
52
53 # List VCS modules in order of preference.
54 # Don't list this module, it is implicitly last.
55 VCS_ORDER = ['arch', 'bzr', 'darcs', 'git', 'hg']
56
57 def set_preferred_vcs(name):
58     global VCS_ORDER
59     assert name in VCS_ORDER, \
60         'unrecognized VCS %s not in\n  %s' % (name, VCS_ORDER)
61     VCS_ORDER.remove(name)
62     VCS_ORDER.insert(0, name)
63
64 def _get_matching_vcs(matchfn):
65     """Return the first module for which matchfn(VCS_instance) is true"""
66     for submodname in VCS_ORDER:
67         module = import_by_name('libbe.storage.vcs.%s' % submodname)
68         vcs = module.new()
69         if matchfn(vcs) == True:
70             return vcs
71     return VCS()
72
73 def vcs_by_name(vcs_name):
74     """Return the module for the VCS with the given name"""
75     if vcs_name == VCS.name:
76         return new()
77     return _get_matching_vcs(lambda vcs: vcs.name == vcs_name)
78
79 def detect_vcs(dir):
80     """Return an VCS instance for the vcs being used in this directory"""
81     return _get_matching_vcs(lambda vcs: vcs._detect(dir))
82
83 def installed_vcs():
84     """Return an instance of an installed VCS"""
85     return _get_matching_vcs(lambda vcs: vcs.installed())
86
87
88 class VCSNotRooted (libbe.storage.base.ConnectionError):
89     def __init__(self, vcs):
90         msg = 'VCS not rooted'
91         libbe.storage.base.ConnectionError.__init__(self, msg)
92         self.vcs = vcs
93
94 class VCSUnableToRoot (libbe.storage.base.ConnectionError):
95     def __init__(self, vcs):
96         msg = 'VCS unable to root'
97         libbe.storage.base.ConnectionError.__init__(self, msg)
98         self.vcs = vcs
99
100 class InvalidPath (InvalidID):
101     def __init__(self, path, root, msg=None):
102         if msg == None:
103             msg = 'Path "%s" not in root "%s"' % (path, root)
104         InvalidID.__init__(self, msg)
105         self.path = path
106         self.root = root
107
108 class SpacerCollision (InvalidPath):
109     def __init__(self, path, spacer):
110         msg = 'Path "%s" collides with spacer directory "%s"' % (path, spacer)
111         InvalidPath.__init__(self, path, root=None, msg=msg)
112         self.spacer = spacer
113
114 class NoSuchFile (InvalidID):
115     def __init__(self, pathname, root='.'):
116         path = os.path.abspath(os.path.join(root, pathname))
117         InvalidID.__init__(self, 'No such file: %s' % path)
118
119
120 class CachedPathID (object):
121     """
122     Storage ID <-> path policy.
123       .../.be/BUGDIR/bugs/BUG/comments/COMMENT
124         ^-- root path
125
126     >>> dir = Dir()
127     >>> os.mkdir(os.path.join(dir.path, '.be'))
128     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc'))
129     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc', 'bugs'))
130     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc', 'bugs', '123'))
131     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc', 'bugs', '123', 'comments'))
132     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc', 'bugs', '123', 'comments', 'def'))
133     >>> os.mkdir(os.path.join(dir.path, '.be', 'abc', 'bugs', '456'))
134     >>> file(os.path.join(dir.path, '.be', 'abc', 'values'),
135     ...      'w').close()
136     >>> file(os.path.join(dir.path, '.be', 'abc', 'bugs', '123', 'values'),
137     ...      'w').close()
138     >>> file(os.path.join(dir.path, '.be', 'abc', 'bugs', '123', 'comments', 'def', 'values'),
139     ...      'w').close()
140     >>> c = CachedPathID()
141     >>> c.root(dir.path)
142     >>> c.id(os.path.join(dir.path, '.be', 'abc', 'bugs', '123', 'comments', 'def', 'values'))
143     'def/values'
144     >>> c.init()
145     >>> sorted(os.listdir(os.path.join(c._root, '.be')))
146     ['abc', 'id-cache']
147     >>> c.connect()
148     >>> c.path('123/values') # doctest: +ELLIPSIS
149     u'.../.be/abc/bugs/123/values'
150     >>> c.disconnect()
151     >>> c.destroy()
152     >>> sorted(os.listdir(os.path.join(c._root, '.be')))
153     ['abc']
154     >>> c.connect() # demonstrate auto init
155     >>> sorted(os.listdir(os.path.join(c._root, '.be')))
156     ['abc', 'id-cache']
157     >>> c.add_id(u'xyz', parent=None) # doctest: +ELLIPSIS
158     u'.../.be/xyz'
159     >>> c.add_id('xyz/def', parent='xyz') # doctest: +ELLIPSIS
160     u'.../.be/xyz/def'
161     >>> c.add_id('qrs', parent='123') # doctest: +ELLIPSIS
162     u'.../.be/abc/bugs/123/comments/qrs'
163     >>> c.disconnect()
164     >>> c.connect()
165     >>> c.path('qrs') # doctest: +ELLIPSIS
166     u'.../.be/abc/bugs/123/comments/qrs'
167     >>> c.remove_id('qrs')
168     >>> c.path('qrs')
169     Traceback (most recent call last):
170       ...
171     InvalidID: 'qrs'
172     >>> c.disconnect()
173     >>> c.destroy()
174     >>> dir.cleanup()
175     """
176     def __init__(self, encoding=None):
177         self.encoding = libbe.util.encoding.get_filesystem_encoding()
178         self._spacer_dirs = ['.be', 'bugs', 'comments']
179
180     def root(self, path):
181         self._root = os.path.abspath(path).rstrip(os.path.sep)
182         self._cache_path = os.path.join(
183             self._root, self._spacer_dirs[0], 'id-cache')
184
185     def init(self):
186         """
187         Create cache file for an existing .be directory.
188         File if multiple lines of the form:
189           UUID\tPATH
190         """
191         self._cache = {}
192         spaced_root = os.path.join(self._root, self._spacer_dirs[0])
193         for dirpath, dirnames, filenames in os.walk(spaced_root):
194             if dirpath == spaced_root:
195                 continue
196             try:
197                 id = self.id(dirpath)
198                 relpath = dirpath[len(self._root)+1:]
199                 if id.count('/') == 0:
200                     if id in self._cache:
201                         print >> sys.stderr, 'Multiple paths for %s: \n  %s\n  %s' % (id, self._cache[id], relpath)
202                     self._cache[id] = relpath
203             except InvalidPath:
204                 pass
205         self._changed = True
206         self.disconnect()
207
208     def destroy(self):
209         if os.path.exists(self._cache_path):
210             os.remove(self._cache_path)
211
212     def connect(self):
213         if not os.path.exists(self._cache_path):
214             try:
215                 self.init()
216             except IOError:
217                 raise libbe.storage.base.ConnectionError
218         self._cache = {} # key: uuid, value: path
219         self._changed = False
220         f = codecs.open(self._cache_path, 'r', self.encoding)
221         for line in f:
222             fields = line.rstrip('\n').split('\t')
223             self._cache[fields[0]] = fields[1]
224         f.close()
225
226     def disconnect(self):
227         if self._changed == True:
228             f = codecs.open(self._cache_path, 'w', self.encoding)
229             for uuid,path in self._cache.items():
230                 f.write('%s\t%s\n' % (uuid, path))
231             f.close()
232         self._cache = {}
233
234     def path(self, id, relpath=False):
235         fields = id.split('/', 1)
236         uuid = fields[0]
237         if len(fields) == 1:
238             extra = []
239         else:
240             extra = fields[1:]
241         if uuid not in self._cache:
242             raise InvalidID(uuid)
243         if relpath == True:
244             return os.path.join(self._cache[uuid], *extra)
245         return os.path.join(self._root, self._cache[uuid], *extra)
246
247     def add_id(self, id, parent=None):
248         if id.count('/') > 0:
249             # not a UUID-level path
250             assert id.startswith(parent), \
251                 'Strange ID: "%s" should start with "%s"' % (id, parent)
252             path = self.path(id)
253         elif id in self._cache:
254             # already added
255             path = self.path(id)
256         else:
257             if parent == None:
258                 parent_path = ''
259                 spacer = self._spacer_dirs[0]
260             else:
261                 assert parent.count('/') == 0, \
262                     'Strange parent ID: "%s" should be UUID' % parent
263                 parent_path = self.path(parent, relpath=True)
264                 parent_spacer = parent_path.split(os.path.sep)[-2]
265                 i = self._spacer_dirs.index(parent_spacer)
266                 spacer = self._spacer_dirs[i+1]
267             path = os.path.join(parent_path, spacer, id)
268             self._cache[id] = path
269             self._changed = True
270             path = os.path.join(self._root, path)
271         return path
272
273     def remove_id(self, id):
274         if id.count('/') > 0:
275             return # not a UUID-level path
276         self._cache.pop(id)
277         self._changed = True
278
279     def id(self, path):
280         path = os.path.abspath(path)
281         if not path.startswith(self._root + os.path.sep):
282             raise InvalidPath('Path %s not in root %s' % (path, self._root))
283         path = path[len(self._root)+1:]
284         orig_path = path
285         if not path.startswith(self._spacer_dirs[0] + os.path.sep):
286             raise InvalidPath(path, self._spacer_dirs[0])
287         for spacer in self._spacer_dirs:
288             if not path.startswith(spacer + os.path.sep):
289                 break
290             id = path[len(spacer)+1:]
291             fields = path[len(spacer)+1:].split(os.path.sep,1)
292             if len(fields) == 1:
293                 break
294             path = fields[1]
295         for spacer in self._spacer_dirs:
296             if id.endswith(os.path.sep + spacer):
297                 raise SpacerCollision(orig_path, spacer)
298         if os.path.sep != '/':
299             id = id.replace(os.path.sep, '/')
300         return id
301
302
303 def new():
304     return VCS()
305
306 class VCS (libbe.storage.base.VersionedStorage):
307     """
308     This class implements a 'no-vcs' interface.
309
310     Support for other VCSs can be added by subclassing this class, and
311     overriding methods _vcs_*() with code appropriate for your VCS.
312
313     The methods _u_*() are utility methods available to the _vcs_*()
314     methods.
315
316     Sink to existing root
317     ======================
318
319     Consider the following usage case:
320     You have a bug directory rooted in
321       /path/to/source
322     by which I mean the '.be' directory is at
323       /path/to/source/.be
324     However, you're of in some subdirectory like
325       /path/to/source/GUI/testing
326     and you want to comment on a bug.  Setting sink_to_root=True when
327     you initialize your BugDir will cause it to search for the '.be'
328     file in the ancestors of the path you passed in as 'root'.
329       /path/to/source/GUI/testing/.be     miss
330       /path/to/source/GUI/.be             miss
331       /path/to/source/.be                 hit!
332     So it still roots itself appropriately without much work for you.
333
334     File-system access
335     ==================
336
337     BugDirs live completely in memory when .sync_with_disk is False.
338     This is the default configuration setup by BugDir(from_disk=False).
339     If .sync_with_disk == True (e.g. BugDir(from_disk=True)), then
340     any changes to the BugDir will be immediately written to disk.
341
342     If you want to change .sync_with_disk, we suggest you use
343     .set_sync_with_disk(), which propogates the new setting through to
344     all bugs/comments/etc. that have been loaded into memory.  If
345     you've been living in memory and want to move to
346     .sync_with_disk==True, but you're not sure if anything has been
347     changed in memory, a call to .save() immediately before the
348     .set_sync_with_disk(True) call is a safe move.
349
350     Regardless of .sync_with_disk, a call to .save() will write out
351     all the contents that the BugDir instance has loaded into memory.
352     If sync_with_disk has been True over the course of all interesting
353     changes, this .save() call will be a waste of time.
354
355     The BugDir will only load information from the file system when it
356     loads new settings/bugs/comments that it doesn't already have in
357     memory and .sync_with_disk == True.
358
359     Allow storage initialization
360     ========================
361
362     This one is for testing purposes.  Setting it to True allows the
363     BugDir to search for an installed Storage backend and initialize
364     it in the root directory.  This is a convenience option for
365     supporting tests of versioning functionality
366     (e.g. .duplicate_bugdir).
367
368     Disable encoding manipulation
369     =============================
370
371     This one is for testing purposed.  You might have non-ASCII
372     Unicode in your bugs, comments, files, etc.  BugDir instances try
373     and support your preferred encoding scheme (e.g. "utf-8") when
374     dealing with stream and file input/output.  For stream output,
375     this involves replacing sys.stdout and sys.stderr
376     (libbe.encode.set_IO_stream_encodings).  However this messes up
377     doctest's output catching.  In order to support doctest tests
378     using BugDirs, set manipulate_encodings=False, and stick to ASCII
379     in your tests.
380
381         if root == None:
382             root = os.getcwd()
383         if sink_to_existing_root == True:
384             self.root = self._find_root(root)
385         else:
386             if not os.path.exists(root):
387                 self.root = None
388                 raise NoRootEntry(root)
389             self.root = root
390         # get a temporary storage until we've loaded settings
391         self.sync_with_disk = False
392         self.storage = self._guess_storage()
393
394             if assert_new_BugDir == True:
395                 if os.path.exists(self.get_path()):
396                     raise AlreadyInitialized, self.get_path()
397             if storage == None:
398                 storage = self._guess_storage(allow_storage_init)
399             self.storage = storage
400             self._setup_user_id(self.user_id)
401
402
403     # methods for getting the BugDir situated in the filesystem
404
405     def _find_root(self, path):
406         '''
407         Search for an existing bug database dir and it's ancestors and
408         return a BugDir rooted there.  Only called by __init__, and
409         then only if sink_to_existing_root == True.
410         '''
411         if not os.path.exists(path):
412             self.root = None
413             raise NoRootEntry(path)
414         versionfile=utility.search_parent_directories(path,
415                                                       os.path.join(".be", "version"))
416         if versionfile != None:
417             beroot = os.path.dirname(versionfile)
418             root = os.path.dirname(beroot)
419             return root
420         else:
421             beroot = utility.search_parent_directories(path, ".be")
422             if beroot == None:
423                 self.root = None
424                 raise NoBugDir(path)
425             return beroot
426
427     def _guess_storage(self, allow_storage_init=False):
428         '''
429         Only called by __init__.
430         '''
431         deepdir = self.get_path()
432         if not os.path.exists(deepdir):
433             deepdir = os.path.dirname(deepdir)
434         new_storage = storage.detect_storage(deepdir)
435         install = False
436         if new_storage.name == "None":
437             if allow_storage_init == True:
438                 new_storage = storage.installed_storage()
439                 new_storage.init(self.root)
440         return new_storage
441
442 os.listdir(self.get_path("bugs")):
443     """
444     name = 'None'
445     client = 'false' # command-line tool for _u_invoke_client
446
447     def __init__(self, *args, **kwargs):
448         if 'encoding' not in kwargs:
449             kwargs['encoding'] = libbe.util.encoding.get_filesystem_encoding()
450         libbe.storage.base.VersionedStorage.__init__(self, *args, **kwargs)
451         self.versioned = False
452         self.interspersed_vcs_files = False
453         self.verbose_invoke = False
454         self._cached_path_id = CachedPathID()
455         self._rooted = False
456
457     def _vcs_version(self):
458         """
459         Return the VCS version string.
460         """
461         return '0'
462
463     def _vcs_get_user_id(self):
464         """
465         Get the VCS's suggested user id (e.g. "John Doe <jdoe@example.com>").
466         If the VCS has not been configured with a username, return None.
467         """
468         return None
469
470     def _vcs_detect(self, path=None):
471         """
472         Detect whether a directory is revision controlled with this VCS.
473         """
474         return True
475
476     def _vcs_root(self, path):
477         """
478         Get the VCS root.  This is the default working directory for
479         future invocations.  You would normally set this to the root
480         directory for your VCS.
481         """
482         if os.path.isdir(path) == False:
483             path = os.path.dirname(path)
484             if path == '':
485                 path = os.path.abspath('.')
486         return path
487
488     def _vcs_init(self, path):
489         """
490         Begin versioning the tree based at path.
491         """
492         pass
493
494     def _vcs_destroy(self):
495         """
496         Remove any files used in versioning (e.g. whatever _vcs_init()
497         created).
498         """
499         pass
500
501     def _vcs_add(self, path):
502         """
503         Add the already created file at path to version control.
504         """
505         pass
506
507     def _vcs_remove(self, path):
508         """
509         Remove the file at path from version control.  Optionally
510         remove the file from the filesystem as well.
511         """
512         pass
513
514     def _vcs_update(self, path):
515         """
516         Notify the versioning system of changes to the versioned file
517         at path.
518         """
519         pass
520
521     def _vcs_is_versioned(self, path):
522         """
523         Return true if a path is under version control, False
524         otherwise.  You only need to set this if the VCS goes about
525         dumping VCS-specific files into the .be directory.
526
527         If you do need to implement this method (e.g. Arch), set
528           self.interspersed_vcs_files = True
529         """
530         assert self.interspersed_vcs_files == False
531         raise NotImplementedError
532
533     def _vcs_get_file_contents(self, path, revision=None):
534         """
535         Get the file contents as they were in a given revision.
536         Revision==None specifies the current revision.
537         """
538         if revision != None:
539             raise libbe.storage.base.InvalidRevision(
540                 'The %s VCS does not support revision specifiers' % self.name)
541         path = os.path.join(self.repo, path)
542         if not os.path.exists(path):
543             return libbe.util.InvalidObject
544         if os.path.isdir(path):
545             return libbe.storage.base.InvalidDirectory
546         f = open(path, 'rb')
547         contents = f.read()
548         f.close()
549         return contents
550
551     def _vcs_commit(self, commitfile, allow_empty=False):
552         """
553         Commit the current working directory, using the contents of
554         commitfile as the comment.  Return the name of the old
555         revision (or None if commits are not supported).
556
557         If allow_empty == False, raise EmptyCommit if there are no
558         changes to commit.
559         """
560         return None
561
562     def _vcs_revision_id(self, index):
563         """
564         Return the name of the <index>th revision.  Index will be an
565         integer (possibly <= 0).  The choice of which branch to follow
566         when crossing branches/merges is not defined.
567
568         Return None if revision IDs are not supported, or if the
569         specified revision does not exist.
570         """
571         return None
572
573     def version(self):
574         # Cache version string for efficiency.
575         if not hasattr(self, '_version'):
576             self._version = self._get_version()
577         return self._version
578
579     def _get_version(self):
580         try:
581             ret = self._vcs_version()
582             return ret
583         except OSError, e:
584             if e.errno == errno.ENOENT:
585                 return None
586             else:
587                 raise OSError, e
588         except CommandError:
589             return None
590
591     def installed(self):
592         if self.version() != None:
593             return True
594         return False
595
596     def get_user_id(self):
597         """
598         Get the VCS's suggested user id (e.g. "John Doe <jdoe@example.com>").
599         If the VCS has not been configured with a username, return None.
600         You can override the automatic lookup procedure by setting the
601         VCS.user_id attribute to a string of your choice.
602         """
603         if not hasattr(self, 'user_id'):
604             self.user_id = self._vcs_get_user_id()
605         return self.user_id
606
607     def _detect(self, path='.'):
608         """
609         Detect whether a directory is revision controlled with this VCS.
610         """
611         return self._vcs_detect(path)
612
613     def root(self):
614         """
615         Set the root directory to the path's VCS root.  This is the
616         default working directory for future invocations.
617         """
618         if self._detect(self.repo) == False:
619             raise VCSUnableToRoot(self)
620         root = self._vcs_root(self.repo)
621         self.repo = os.path.abspath(root)
622         if os.path.isdir(self.repo) == False:
623             self.repo = os.path.dirname(self.repo)
624         self.be_dir = os.path.join(
625             self.repo, self._cached_path_id._spacer_dirs[0])
626         self._cached_path_id.root(self.repo)
627         self._rooted = True
628
629     def _init(self):
630         """
631         Begin versioning the tree based at self.repo.
632         Also roots the vcs at path.
633         """
634         if not os.path.exists(self.repo) or not os.path.isdir(self.repo):
635             raise VCSUnableToRoot(self)
636         if self._vcs_detect(self.repo) == False:
637             self._vcs_init(self.repo)
638         if self._rooted == False:
639             self.root()
640         os.mkdir(self.be_dir)
641         self._vcs_add(self._u_rel_path(self.be_dir))
642         self._setup_storage_version()
643         self._cached_path_id.init()
644
645     def _destroy(self):
646         self._vcs_destroy()
647         self._cached_path_id.destroy()
648         if os.path.exists(self.be_dir):
649             shutil.rmtree(self.be_dir)
650
651     def _connect(self):
652         if self._rooted == False:
653             self.root()
654         if not os.path.isdir(self.be_dir):
655             raise libbe.storage.base.ConnectionError(self)
656         self._cached_path_id.connect()
657         self.check_storage_version()
658
659     def disconnect(self):
660         self._cached_path_id.disconnect()
661
662     def _add_path(self, path, directory=False):
663         relpath = self._u_rel_path(path)
664         reldirs = relpath.split(os.path.sep)
665         if directory == False:
666             reldirs = reldirs[:-1]
667         dir = self.repo
668         for reldir in reldirs:
669             dir = os.path.join(dir, reldir)
670             if not os.path.exists(dir):
671                 os.mkdir(dir)
672                 self._vcs_add(self._u_rel_path(dir))
673             elif not os.path.isdir(dir):
674                 raise libbe.storage.base.InvalidDirectory
675         if directory == False:
676             if not os.path.exists(path):
677                 open(path, 'w').close()
678             self._vcs_add(self._u_rel_path(path))
679
680     def _add(self, id, parent=None, **kwargs):
681         path = self._cached_path_id.add_id(id, parent)
682         self._add_path(path, **kwargs)
683
684     def _remove(self, id):
685         path = self._cached_path_id.path(id)
686         if os.path.exists(path):
687             if os.path.isdir(path) and len(self.children(id)) > 0:
688                 raise libbe.storage.base.DirectoryNotEmpty(id)
689             self._vcs_remove(self._u_rel_path(path))
690             if os.path.exists(path):
691                 if os.path.isdir(path):
692                     os.rmdir(path)
693                 else:
694                     os.remove(path)
695         self._cached_path_id.remove_id(id)
696
697     def _recursive_remove(self, id):
698         path = self._cached_path_id.path(id)
699         for dirpath,dirnames,filenames in os.walk(path, topdown=False):
700             filenames.extend(dirnames)
701             for f in filenames:
702                 fullpath = os.path.join(dirpath, f)
703                 if os.path.exists(fullpath) == False:
704                     continue
705                 self._vcs_remove(self._u_rel_path(fullpath))
706         if os.path.exists(path):
707             shutil.rmtree(path)
708         path = self._cached_path_id.path(id, relpath=True)
709         for id,p in self._cached_path_id._cache.items():
710             if p.startswith(path):
711                 self._cached_path_id.remove_id(id)
712
713     def _children(self, id=None, revision=None):
714         if id==None:
715             path = self.be_dir
716         else:
717             path = self._cached_path_id.path(id)
718         if os.path.isdir(path) == False:
719             return []
720         children = os.listdir(path)
721         for i,c in enumerate(children):
722             if c in self._cached_path_id._spacer_dirs:
723                 children[i] = None
724                 children.extend([os.path.join(c, c2) for c2 in
725                                  os.listdir(os.path.join(path, c))])
726             elif c in ['id-cache', 'version']:
727                 children[i] = None
728         for i,c in enumerate(children):
729             if c == None: continue
730             cpath = os.path.join(path, c)
731             if self.interspersed_vcs_files == True \
732                     and self._vcs_is_versioned(cpath) == False:
733                 children[i] = None
734             else:
735                 children[i] = self._cached_path_id.id(cpath)
736         return [c for c in children if c != None]
737
738     def _get(self, id, default=libbe.util.InvalidObject, revision=None):
739         try:
740             path = self._cached_path_id.path(id)
741         except InvalidID, e:
742             if default == libbe.util.InvalidObject:
743                 raise e
744             return default
745         relpath = self._u_rel_path(path)
746         try:
747             contents = self._vcs_get_file_contents(relpath,revision)
748         except InvalidID, e:
749             raise InvalidID(id)
750         if contents in [libbe.storage.base.InvalidDirectory,
751                         libbe.util.InvalidObject]:
752             raise InvalidID(id)
753         elif len(contents) == 0:
754             return None
755         return contents
756
757     def _set(self, id, value):
758         try:
759             path = self._cached_path_id.path(id)
760         except InvalidID, e:
761             raise e
762         if not os.path.exists(path):
763             raise InvalidID(id)
764         if os.path.isdir(path):
765             raise libbe.storage.base.InvalidDirectory(id)
766         f = open(path, "wb")
767         f.write(value)
768         f.close()
769         self._vcs_update(self._u_rel_path(path))
770
771     def _commit(self, summary, body=None, allow_empty=False):
772         summary = summary.strip()+'\n'
773         if body is not None:
774             summary += '\n' + body.strip() + '\n'
775         descriptor, filename = tempfile.mkstemp()
776         revision = None
777         try:
778             temp_file = os.fdopen(descriptor, 'wb')
779             temp_file.write(summary)
780             temp_file.flush()
781             revision = self._vcs_commit(filename, allow_empty=allow_empty)
782             temp_file.close()
783         finally:
784             os.remove(filename)
785         return revision
786
787     def revision_id(self, index=None):
788         if index == None:
789             return None
790         try:
791             if int(index) != index:
792                 raise InvalidRevision(index)
793         except ValueError:
794             raise InvalidRevision(index)
795         revid = self._vcs_revision_id(index)
796         if revid == None:
797             raise libbe.storage.base.InvalidRevision(index)
798         return revid
799
800     def _u_any_in_string(self, list, string):
801         """
802         Return True if any of the strings in list are in string.
803         Otherwise return False.
804         """
805         for list_string in list:
806             if list_string in string:
807                 return True
808         return False
809
810     def _u_invoke(self, *args, **kwargs):
811         if 'cwd' not in kwargs:
812             kwargs['cwd'] = self.repo
813         if 'verbose' not in kwargs:
814             kwargs['verbose'] = self.verbose_invoke
815         if 'encoding' not in kwargs:
816             kwargs['encoding'] = self.encoding
817         return invoke(*args, **kwargs)
818
819     def _u_invoke_client(self, *args, **kwargs):
820         cl_args = [self.client]
821         cl_args.extend(args)
822         return self._u_invoke(cl_args, **kwargs)
823
824     def _u_search_parent_directories(self, path, filename):
825         """
826         Find the file (or directory) named filename in path or in any
827         of path's parents.
828
829         e.g.
830           search_parent_directories("/a/b/c", ".be")
831         will return the path to the first existing file from
832           /a/b/c/.be
833           /a/b/.be
834           /a/.be
835           /.be
836         or None if none of those files exist.
837         """
838         return search_parent_directories(path, filename)
839
840     def _u_rel_path(self, path, root=None):
841         """
842         Return the relative path to path from root.
843         >>> vcs = new()
844         >>> vcs._u_rel_path("/a.b/c/.be", "/a.b/c")
845         '.be'
846         """
847         if root == None:
848             if self.repo == None:
849                 raise VCSNotRooted(self)
850             root = self.repo
851         path = os.path.abspath(path)
852         absRoot = os.path.abspath(root)
853         absRootSlashedDir = os.path.join(absRoot,"")
854         if not path.startswith(absRootSlashedDir):
855             raise InvalidPath(path, absRootSlashedDir)
856         assert path != absRootSlashedDir, \
857             "file %s == root directory %s" % (path, absRootSlashedDir)
858         relpath = path[len(absRootSlashedDir):]
859         return relpath
860
861     def _u_abspath(self, path, root=None):
862         """
863         Return the absolute path from a path realtive to root.
864         >>> vcs = new()
865         >>> vcs._u_abspath(".be", "/a.b/c")
866         '/a.b/c/.be'
867         """
868         if root == None:
869             assert self.repo != None, "VCS not rooted"
870             root = self.repo
871         return os.path.abspath(os.path.join(root, path))
872
873     def _u_parse_commitfile(self, commitfile):
874         """
875         Split the commitfile created in self.commit() back into
876         summary and header lines.
877         """
878         f = codecs.open(commitfile, 'r', self.encoding)
879         summary = f.readline()
880         body = f.read()
881         body.lstrip('\n')
882         if len(body) == 0:
883             body = None
884         f.close()
885         return (summary, body)
886
887     def check_storage_version(self):
888         version = self.storage_version()
889         if version != libbe.storage.STORAGE_VERSION:
890             upgrade.upgrade(self.repo, version)
891
892     def storage_version(self, revision=None, path=None):
893         """
894         Requires disk access.
895         """
896         if path == None:
897             path = os.path.join(self.repo, '.be', 'version')
898         if not os.path.exists(path):
899             raise libbe.storage.InvalidStorageVersion(None)
900         if revision == None: # don't require connection
901             return libbe.util.encoding.get_file_contents(
902                 path, decode=True).rstrip('\n')
903         contents = self._vcs_get_file_contents(path, revision=revision)
904         if type(contents) != types.UnicodeType:
905             contents = unicode(contents, self.encoding)
906         return contents.strip()
907
908     def _setup_storage_version(self):
909         """
910         Requires disk access.
911         """
912         assert self._rooted == True
913         path = os.path.join(self.be_dir, 'version')
914         if not os.path.exists(path):
915             libbe.util.encoding.set_file_contents(path,
916                 libbe.storage.STORAGE_VERSION+'\n')
917             self._vcs_add(self._u_rel_path(path))
918
919 \f
920 if libbe.TESTING == True:
921     class VCSTestCase (unittest.TestCase):
922         """
923         Test cases for base VCS class (in addition to the Storage test
924         cases).
925         """
926
927         Class = VCS
928
929         def __init__(self, *args, **kwargs):
930             super(VCSTestCase, self).__init__(*args, **kwargs)
931             self.dirname = None
932
933         def setUp(self):
934             """Set up test fixtures for Storage test case."""
935             super(VCSTestCase, self).setUp()
936             self.dir = Dir()
937             self.dirname = self.dir.path
938             self.s = self.Class(repo=self.dirname)
939             if self.s.installed() == True:
940                 self.s.init()
941                 self.s.connect()
942
943         def tearDown(self):
944             super(VCSTestCase, self).tearDown()
945             if self.s.installed() == True:
946                 self.s.disconnect()
947                 self.s.destroy()
948             self.dir.cleanup()
949
950     class VCS_installed_TestCase (VCSTestCase):
951         def test_installed(self):
952             """
953             See if the VCS is installed.
954             """
955             self.failUnless(self.s.installed() == True,
956                             '%(name)s VCS not found' % vars(self.Class))
957
958
959     class VCS_detection_TestCase (VCSTestCase):
960         def test_detection(self):
961             """
962             See if the VCS detects its installed repository
963             """
964             if self.s.installed():
965                 self.s.disconnect()
966                 self.failUnless(self.s._detect(self.dirname) == True,
967                     'Did not detected %(name)s VCS after initialising'
968                     % vars(self.Class))
969                 self.s.connect()
970
971         def test_no_detection(self):
972             """
973             See if the VCS detects its installed repository
974             """
975             if self.s.installed() and self.Class.name != 'None':
976                 self.s.disconnect()
977                 self.s.destroy()
978                 self.failUnless(self.s._detect(self.dirname) == False,
979                     'Detected %(name)s VCS before initialising'
980                     % vars(self.Class))
981                 self.s.init()
982                 self.s.connect()
983
984         def test_vcs_repo_in_specified_root_path(self):
985             """VCS root directory should be in specified root path."""
986             rp = os.path.realpath(self.s.repo)
987             dp = os.path.realpath(self.dirname)
988             vcs_name = self.Class.name
989             self.failUnless(
990                 dp == rp or rp == None,
991                 "%(vcs_name)s VCS root in wrong dir (%(dp)s %(rp)s)" % vars())
992
993     class VCS_get_user_id_TestCase(VCSTestCase):
994         """Test cases for VCS.get_user_id method."""
995
996         def test_gets_existing_user_id(self):
997             """Should get the existing user ID."""
998             if self.s.installed():
999                 user_id = self.s.get_user_id()
1000                 if user_id == None:
1001                     return
1002                 name,email = libbe.ui.util.user.parse_user_id(user_id)
1003                 if email != None:
1004                     self.failUnless('@' in email, email)
1005
1006     def make_vcs_testcase_subclasses(vcs_class, namespace):
1007         c = vcs_class()
1008         if c.installed():
1009             if c.versioned == True:
1010                 libbe.storage.base.make_versioned_storage_testcase_subclasses(
1011                     vcs_class, namespace)
1012             else:
1013                 libbe.storage.base.make_storage_testcase_subclasses(
1014                     vcs_class, namespace)
1015
1016         if namespace != sys.modules[__name__]:
1017             # Make VCSTestCase subclasses for vcs_class in the namespace.
1018             vcs_testcase_classes = [
1019                 c for c in (
1020                     ob for ob in globals().values() if isinstance(ob, type))
1021                 if issubclass(c, VCSTestCase)]
1022
1023             for base_class in vcs_testcase_classes:
1024                 testcase_class_name = vcs_class.__name__ + base_class.__name__
1025                 testcase_class_bases = (base_class,)
1026                 testcase_class_dict = dict(base_class.__dict__)
1027                 testcase_class_dict['Class'] = vcs_class
1028                 testcase_class = type(
1029                     testcase_class_name, testcase_class_bases, testcase_class_dict)
1030                 setattr(namespace, testcase_class_name, testcase_class)
1031
1032     make_vcs_testcase_subclasses(VCS, sys.modules[__name__])
1033
1034     unitsuite =unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
1035     suite = unittest.TestSuite([unitsuite, doctest.DocTestSuite()])