Transitioned init to Command format
authorW. Trevor King <wking@drexel.edu>
Mon, 14 Dec 2009 08:29:20 +0000 (03:29 -0500)
committerW. Trevor King <wking@drexel.edu>
Mon, 14 Dec 2009 08:29:20 +0000 (03:29 -0500)
libbe/bugdir.py
libbe/command/assign.py
libbe/command/base.py
libbe/command/init.py
libbe/command/list.py
libbe/storage/vcs/base.py
libbe/ui/command_line.py
libbe/ui/util/user.py

index 66bd606e0ab4506f6ae99911977b1f12b61fec2f..7ec84569611d89dbbbb0931e78d4d8cc59cdf132 100644 (file)
@@ -165,9 +165,6 @@ class BugDir (list, settings_object.SavedSettingsObject):
     @doc_property(doc="A dict of (bug-uuid, bug-instance) pairs.")
     def _bug_map(): return {}
 
-    def _get_user_id(self):
-        return "X"
-
     def __init__(self, storage, uuid=None, from_storage=False):
         list.__init__(self)
         settings_object.SavedSettingsObject.__init__(self)
index 287c649108330c8b61ee92232bf33ac01f447385..6d1233c1fba35a9a2dadb77dc1715315bbd5208d 100644 (file)
@@ -34,19 +34,19 @@ class Assign (libbe.command.Command):
 
     >>> bd.bug_from_uuid('a').assigned is None
     True
-    >>> cmd.run(bd, {'user-id':u'Fran\xe7ois'}, ['-', '/a'])
+    >>> cmd.run(bd.storage, bd, {'user-id':u'Fran\xe7ois'}, ['-', '/a'])
     >>> bd.flush_reload()
     >>> bd.bug_from_uuid('a').assigned
     u'Fran\\xe7ois'
 
-    >>> cmd.run(bd, args=['someone', '/a', '/b'])
+    >>> cmd.run(bd.storage, bd, args=['someone', '/a', '/b'])
     >>> bd.flush_reload()
     >>> bd.bug_from_uuid('a').assigned
     'someone'
     >>> bd.bug_from_uuid('b').assigned
     'someone'
 
-    >>> cmd.run(bd, args=['none', '/a'])
+    >>> cmd.run(bd.storage, bd, args=['none', '/a'])
     >>> bd.flush_reload()
     >>> bd.bug_from_uuid('a').assigned is None
     True
@@ -68,7 +68,7 @@ class Assign (libbe.command.Command):
                     completion_callback=libbe.command.util.complete_bug_id),
                 ])
 
-    def _run(self, bugdir, **params):
+    def _run(self, storage, bugdir, **params):
         assignee = params['assignee']
         if assignee == 'none':
             assignee = None
index 2cf75bdeab9ea80faa9476922d446c87d7f2f1fa..b27e1889a2301f0b94145f29ec63992eeadd142d 100644 (file)
@@ -145,6 +145,7 @@ class Command (object):
         self.status = None
         self.result = None
         self.requires_bugdir = False
+        self.requires_unconnected_storage = False
         self.input_encoding = None
         self.output_encoding = None
         self.options = [
@@ -157,7 +158,7 @@ class Command (object):
                 ]
         self.args = []
 
-    def run(self, bugdir, options=None, args=None):
+    def run(self, storage=None, bugdir=None, options=None, args=None):
         if options == None:
             options = {}
         if args == None:
@@ -175,7 +176,7 @@ class Command (object):
         if 'user-id' in options:
             params['user-id'] = options.pop('user-id')
         else:
-            params['user-id'] = libbe.ui.util.user.get_user_id(bugdir.storage)
+            params['user-id'] = libbe.ui.util.user.get_user_id(storage)
         if len(options) > 0:
             raise UserError, 'Invalid option passed to command %s:\n  %s' \
                 % (self.name, '\n  '.join(['%s: %s' % (k,v)
@@ -213,10 +214,10 @@ class Command (object):
             params.pop('complete')
 
         self._setup_io(self.input_encoding, self.output_encoding)
-        self.status = self._run(bugdir, **params)
+        self.status = self._run(storage, bugdir, **params)
         return self.status
 
-    def _run(self, bugdir, **kwargs):
+    def _run(self, storage, bugdir, **kwargs):
         pass
 
     def _setup_io(self, input_encoding=None, output_encoding=None):
index ab9255b305d45c834f6d69904696784b911dcb7a..cdaa14923630bf50bb2bef7e9d051b8babf4e0b4 100644 (file)
 # You should have received a copy of the GNU General Public License along
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-"""Assign the root directory for bug tracking"""
+
 import os.path
-from libbe import cmdutil, bugdir
-__desc__ = __doc__
 
-def execute(args, manipulate_encodings=True, restrict_file_access=False,
-            dir="."):
-    """
-    >>> from libbe import utility, vcs
-    >>> import os
-    >>> dir = utility.Dir()
+import libbe
+import libbe.bugdir
+import libbe.command
+import libbe.command.util
+import libbe.storage
+
+class Init (libbe.command.Command):
+    """Create an on-disk bug repository
+
+    >>> import os, sys
+    >>> import libbe.storage.vcs
+    >>> import libbe.storage.vcs.base
+    >>> import libbe.util.utility
+    >>> cmd = Init()
+    >>> cmd._setup_io = lambda i_enc,o_enc : None
+    >>> cmd.stdout = sys.stdout
+
+    >>> dir = libbe.util.utility.Dir()
+    >>> vcs = libbe.storage.vcs.vcs_by_name('None')
+    >>> vcs.repo = dir.path
     >>> try:
-    ...     bugdir.BugDir(dir.path)
-    ... except bugdir.NoBugDir, e:
+    ...     vcs.connect()
+    ... except libbe.storage.ConnectionError:
     ...     True
     True
-    >>> execute([], manipulate_encodings=False, dir=dir.path)
+    >>> cmd.run(vcs)
     No revision control detected.
-    Directory initialized.
+    BE repository initialized.
+    >>> bd = libbe.bugdir.BugDir(vcs)
+    >>> vcs.disconnect()
+    >>> vcs.destroy()
     >>> dir.cleanup()
 
-    >>> dir = utility.Dir()
-    >>> os.chdir(dir.path)
-    >>> _vcs = vcs.installed_vcs()
-    >>> _vcs.init('.')
-    >>> _vcs.name in vcs.VCS_ORDER
-    True
-    >>> execute([], manipulate_encodings=False)  # doctest: +ELLIPSIS
+    >>> dir = libbe.util.utility.Dir()
+    >>> vcs = libbe.storage.vcs.installed_vcs()
+    >>> if vcs.name in libbe.storage.vcs.base.VCS_ORDER:
+    ...     vcs.repo = dir.path
+    ...     vcs._vcs_init(vcs.repo)
+    ...     cmd.run(vcs) # doctest: +ELLIPSIS
+    ... else:
+    ...     print 'Using ... for revision control.\\nDirectory initialized.'
     Using ... for revision control.
-    Directory initialized.
-    >>> _vcs.cleanup()
-
-    >>> try:
-    ...     execute([], manipulate_encodings=False, dir=".")
-    ... except cmdutil.UserError, e:
-    ...     str(e).startswith("Directory already initialized: ")
-    True
-    >>> execute([], manipulate_encodings=False,
-    ...         dir='/highly-unlikely-to-exist')
-    Traceback (most recent call last):
-    UserError: No such directory: /highly-unlikely-to-exist
-    >>> os.chdir('/')
+    BE repository initialized.
+    >>> vcs.disconnect()
+    >>> vcs.destroy()
     >>> dir.cleanup()
     """
-    parser = get_parser()
-    options, args = parser.parse_args(args)
-    cmdutil.default_complete(options, args, parser)
-    if len(args) > 0:
-        raise cmdutil.UsageError
-    try:
-        bd = bugdir.BugDir(from_disk=False,
-                           sink_to_existing_root=False,
-                           assert_new_BugDir=True,
-                           manipulate_encodings=manipulate_encodings,
-                           root=dir)
-    except bugdir.NoRootEntry:
-        raise cmdutil.UserError("No such directory: %s" % dir)
-    except bugdir.AlreadyInitialized:
-        raise cmdutil.UserError("Directory already initialized: %s" % dir)
-    bd.save()
-    if bd.vcs.name is not "None":
-        print "Using %s for revision control." % bd.vcs.name
-    else:
-        print "No revision control detected."
-    print "Directory initialized."
+    
+    name = 'init'
 
-def get_parser():
-    parser = cmdutil.CmdOptionParser("be init")
-    return parser
+    def __init__(self, *args, **kwargs):
+        libbe.command.Command.__init__(self, *args, **kwargs)
+        self.requires_unconnected_storage = True
 
-longhelp="""
+    def _run(self, storage, bugdir=None, **params):
+        if not os.path.isdir(storage.repo):
+            raise libbe.command.UserError(
+                'No such directory: %s' % storage.repo)
+        try:
+            storage.connect()
+            raise libbe.command.UserError(
+                'Directory already initialized: %s' % storage.repo)
+        except libbe.storage.ConnectionError:
+            pass
+        storage.init()
+        storage.connect()
+        bd = libbe.bugdir.BugDir(storage, from_storage=False)
+        bd.save()
+        if bd.storage.name is not 'None':
+            print >> self.stdout, \
+                'Using %s for revision control.' % storage.name
+        else:
+            print >> self.stdout, 'No revision control detected.'
+        print >> self.stdout, 'BE repository initialized.'
+
+    def _long_help(self):
+        return """
 This command initializes Bugs Everywhere support for the specified directory
 and all its subdirectories.  It will auto-detect any supported revision control
 system.  You can use "be set vcs_name" to change the vcs being used.
 
 The directory defaults to your current working directory, but you can
-change that by passing the --dir option to be
-  $ be --dir path/to/new/bug/root init
+change that by passing the --repo option to be
+  $ be --repo path/to/new/bug/root init
 
-It is usually a good idea to put the Bugs Everywhere root at the source code
-root, but you can put it anywhere.  If you root Bugs Everywhere in a
-subdirectory, then only bugs created in that subdirectory (and its children)
-will appear there.
+When initialized in a version-controlled directory, BE sinks to the
+version-control root.  In that case, the BE repository will be created
+under that directory, rather than the current directory or the one
+passed in --repo.  Consider the following tree, versioned in Git.
+  ~
+  `--projectX
+     |-- .git
+     `-- src
+Calling
+  ~$ be --repo ./projectX/src init
+will create the BE repository rooted in projectX:
+  ~
+  `--projectX
+     |-- .be
+     |-- .git
+     `-- src
 """
-
-def help():
-    return get_parser().help_str() + longhelp
index fd1debf4cbbf0f5277984ea214cb4e6cffa43cef..2a64fe272935870d6073137ed2040c8993389dc6 100644 (file)
@@ -62,9 +62,9 @@ class List (libbe.command.Command):
     >>> cmd = List()
     >>> cmd._setup_io = lambda i_enc,o_enc : None
     >>> cmd.stdout = sys.stdout
-    >>> cmd.run(bd)
+    >>> cmd.run(bd.storage, bd)
     sim/a:om: Bug A
-    >>> cmd.run(bd, {'status':'closed'})
+    >>> cmd.run(bd.storage, bd, {'status':'closed'})
     sim/b:cm: Bug B
     >>> bd.storage.writeable
     True
@@ -131,7 +131,7 @@ class List (libbe.command.Command):
 #                
 #                ])
 
-    def _run(self, bugdir, **params):
+    def _run(self, storage, bugdir, **params):
         writeable = bugdir.storage.writeable
         bugdir.storage.writeable = False
         cmp_list, status, severity, assigned, extra_strings_regexps = \
index a765a8073fc3e2d43e36c7de5006aef1be73cf7a..9ea38d3b13d82ff4bcf39057e96e7bb2d2c01ad8 100644 (file)
@@ -629,7 +629,8 @@ os.listdir(self.get_path("bugs")):
         """
         if not os.path.exists(self.repo) or not os.path.isdir(self.repo):
             raise VCSUnableToRoot(self)
-        self._vcs_init(self.repo)
+        if self._vcs_detect(self.repo) == False:
+            self._vcs_init(self.repo)
         self.root()
         os.mkdir(self.be_dir)
         self._vcs_add(self._u_rel_path(self.be_dir))
@@ -644,6 +645,8 @@ os.listdir(self.get_path("bugs")):
     def _connect(self):
         if self._rooted == False:
             self.root()
+        if not os.path.isdir(self.be_dir):
+            raise libbe.storage.base.ConnectionError(self)
         self._cached_path_id.connect()
         self.check_disk_version()
 
@@ -732,9 +735,8 @@ os.listdir(self.get_path("bugs")):
             return default
         relpath = self._u_rel_path(path)
         contents = self._vcs_get_file_contents(relpath,revision)
-        if contents == libbe.storage.base.InvalidDirectory:
-            raise libbe.storage.base.InvalidDirectory(id)
-        elif contents == libbe.util.InvalidObject:
+        if contents in [libbe.storage.base.InvalidDirectory,
+                        libbe.util.InvalidObject]:
             raise libbe.storage.base.InvalidID(id)
         elif len(contents) == 0:
             return None
index 60741f542b82e86b5748b58fe1b135eb414665c3..c59a302775841d80febeee35ff3f70fdb1469566 100755 (executable)
@@ -255,16 +255,18 @@ def main():
     Class = getattr(module, command_name.capitalize())
     command = Class()
     parser = CmdOptionParser(command)
+    storage = None
+    bugdir = None
     if command.requires_bugdir == True:
+        assert command.requires_unconnected_storage == False
         storage = libbe.storage.get_storage(options['repo'])
         storage.connect()
         bugdir = libbe.bugdir.BugDir(storage, from_storage=True)
-    else:
-        storage = None
-        bugdir = None
+    elif: command.requires_unconnected_storage == True:
+        storage = libbe.storage.get_storage(options['repo'])
     try:
         options,args = parser.parse_args(args[1:])
-        command.run(bugdir, options, args)
+        command.run(storage, bugdir, options, args)
     except CallbackExit:
         if storage != None: storage.disconnect()
         return 0
index 5b16b732284cc5a9c7aa081869205f4986061737..d6af89b537def56ecf9de12cf95bfff8c6f255f1 100644 (file)
@@ -75,7 +75,7 @@ def get_user_id(storage=None):
     if user != None:
         return user
     if storage != None and hasattr(storage, 'get_user_id'):
-        user = vcs.get_user_id()
+        user = storage.get_user_id()
         if user != None:
             return user
     name = get_fallback_username()