Transitioned target to Command-format
authorW. Trevor King <wking@drexel.edu>
Tue, 15 Dec 2009 07:38:51 +0000 (02:38 -0500)
committerW. Trevor King <wking@drexel.edu>
Tue, 15 Dec 2009 07:38:51 +0000 (02:38 -0500)
libbe/command/diff.py
libbe/command/tag.py
libbe/command/target.py
libbe/ui/command_line.py

index de8cf678e863e2a6792621e7e19b9db3956f9b89..05242db906ab9f3cbd612e10d497a7bf65bd8117 100644 (file)
@@ -25,7 +25,7 @@ import libbe.storage
 import libbe.diff
 
 class Diff (libbe.command.Command):
-    """Compare bug reports with older tree
+    __doc__ = """Compare bug reports with older tree
 
     >>> import sys
     >>> import libbe.bugdir
index 191dbc935e08be96e589d661ff0494de958a0346..26ff1b5474177e0182f917ea402726eeb7ea095e 100644 (file)
 import libbe
 import libbe.command
 import libbe.command.util
-import libbe.util.utility
 
 
 TAG_TAG = 'TAG:'
 
 
-import os, copy
-
 class Tag (libbe.command.Command):
     __doc__ = """Tag a bug, or search bugs for tags
 
index 5dd5d38f5d2e4b3f1064283f5857742fb3f4be21..39e12b2e8c59bfe1bbdeeadb3c26a51bdaab95a9 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.
-"""Assorted bug target manipulations and queries"""
-from libbe import cmdutil, bugdir
-from becommands import depend
-__desc__ = __doc__
 
-def execute(args, manipulate_encodings=True, restrict_file_access=False,
-            dir="."):
-    """
+import libbe
+import libbe.command
+import libbe.command.util
+import libbe.command.depend
+
+
+
+class Target (libbe.command.Command):
+    """Assorted bug target manipulations and queries
+
     >>> import os, StringIO, sys
-    >>> bd = bugdir.SimpleBugDir()
-    >>> os.chdir(bd.root)
-    >>> execute(["a"], manipulate_encodings=False)
+    >>> import libbe.bugdir
+    >>> bd = libbe.bugdir.SimpleBugDir(memory=False)
+    >>> cmd = Target()
+    >>> cmd._storage = bd.storage
+    >>> cmd._setup_io = lambda i_enc,o_enc : None
+    >>> cmd.stdout = sys.stdout
+
+    >>> ret = cmd.run(args=['/a'])
     No target assigned.
-    >>> execute(["a", "tomorrow"], manipulate_encodings=False)
-    >>> execute(["a"], manipulate_encodings=False)
+    >>> ret = cmd.run(args=['/a', 'tomorrow'])
+    >>> ret = cmd.run(args=['/a'])
     tomorrow
 
-    >>> orig_stdout = sys.stdout
-    >>> tmp_stdout = StringIO.StringIO()
-    >>> sys.stdout = tmp_stdout
-    >>> execute(["--resolve", "tomorrow"], manipulate_encodings=False)
-    >>> sys.stdout = orig_stdout
-    >>> output = tmp_stdout.getvalue().strip()
+    >>> cmd.stdout = StringIO.StringIO()
+    >>> ret = cmd.run({'resolve':True}, ['tomorrow'])
+    >>> output = cmd.stdout.getvalue().strip()
     >>> target = bd.bug_from_uuid(output)
     >>> print target.summary
     tomorrow
     >>> print target.severity
     target
 
-    >>> execute(["a", "none"], manipulate_encodings=False)
-    >>> execute(["a"], manipulate_encodings=False)
+    >>> cmd.stdout = sys.stdout
+    >>> ret = cmd.run(args=['/a', 'none'])
+    >>> ret = cmd.run(args=['/a'])
     No target assigned.
     >>> bd.cleanup()
     """
-    parser = get_parser()
-    options, args = parser.parse_args(args)
-    cmdutil.default_complete(options, args, parser,
-                             bugid_args={0: lambda bug : bug.active==True})
-                             
-    if (options.resolve == False and len(args) not in (1, 2)) \
-            or (options.resolve == True and len(args) not in (0, 1)):
-            raise cmdutil.UsageError('Incorrect number of arguments.')
-    bd = bugdir.BugDir(from_disk=True,
-                       manipulate_encodings=manipulate_encodings,
-                       root=dir)
-    if options.resolve == True:
-        if len(args) == 0:
-            summary = None
-        else:
-            summary = args[0]
-        bug = bug_from_target_summary(bd, summary)
-        if bug == None:
-            print 'No target assigned.'
-        else:
-            print bug.uuid
-        return
-    bug = cmdutil.bug_from_id(bd, args[0])
-    if len(args) == 1:
-        target = bug_target(bd, bug)
-        if target is None:
-            print "No target assigned."
+    name = 'target'
+    
+    def __init__(self, *args, **kwargs):
+        libbe.command.Command.__init__(self, *args, **kwargs)
+        self.options.extend([
+                libbe.command.Option(name='resolve', short_name='r',
+                    help="Print the UUID for the target bug whose summary "
+                    "matches TARGET.  If TARGET is not given, print the UUID "
+                    "of the current bugdir target."),
+                ])
+        self.args.extend([
+                libbe.command.Argument(
+                    name='id', metavar='BUG-ID', default=None,
+                    optional=True,
+                    completion_callback=libbe.command.util.complete_bug_id),
+                libbe.command.Argument(
+                    name='target', metavar='TARGET', default=None,
+                    optional=True,
+                    completion_callback=complete_target),
+                ])
+
+    def _run(self, **params):
+        if params['resolve'] == False:
+            if params['id'] == None:
+                raise libbe.command.UserError('Please specify a bug id.')
         else:
-            print target.summary
-    else:
-        if args[1] == "none":
-            target = remove_target(bd, bug)
+            if params['target'] != None:
+                raise libbe.command.UserError('Too many arguments')
+            params['target'] = params.pop('id')
+        bugdir = self._get_bugdir()
+        if params['resolve'] == True:
+            bug = bug_from_target_summary(bugdir, params['target'])
+            if bug == None:
+                print >> self.stdout, 'No target assigned.'
+            else:
+                print >> self.stdout, bug.uuid
+            return 0
+        bug,dummy_comment = libbe.command.util.bug_comment_from_user_id(
+            bugdir, params['id'])
+        if params['target'] == None:
+            target = bug_target(bugdir, bug)
+            if target == None:
+                print >> self.stdout, 'No target assigned.'
+            else:
+                print >> self.stdout, target.summary
         else:
-            target = add_target(bd, bug, args[1])
+            if params['target'] == 'none':
+                target = remove_target(bugdir, bug)
+            else:
+                target = add_target(bugdir, bug, params['target'])
+        return 0
 
-def get_parser():
-    parser = cmdutil.CmdOptionParser("be target BUG-ID [TARGET]\nor:    be target --resolve [TARGET]")
-    parser.add_option("-r", "--resolve", action="store_true", dest="resolve",
-                      help="Print the UUID for the target bug whose summary matches TARGET.  If TARGET is not given, print the UUID of the current bugdir target.  If that is not set, don't print anything.",
-                      default=False)
-    return parser
+    def _usage(self):
+        return 'usage: be %(name)s BUG-ID [TARGET]\nor:    be %(name)s --resolve [TARGET]' \
+            % vars(self)
 
-longhelp="""
+    def _long_help(self):
+        return """
 Assorted bug target manipulations and queries.
 
 If no target is specified, the bug's current target is printed.  If
@@ -118,9 +139,6 @@ by UUID), try
   $ be set target $(be target --resolve SUMMARY)
 """
 
-def help():
-    return get_parser().help_str() + longhelp
-
 def bug_from_target_summary(bugdir, summary=None):
     if summary == None:
         if bugdir.target == None:
@@ -143,7 +161,7 @@ def bug_target(bugdir, bug):
     if bug.severity == 'target':
         return bug
     matched = []
-    for blocked in depend.get_blocks(bugdir, bug):
+    for blocked in libbe.command.depend.get_blocks(bugdir, bug):
         if blocked.severity == 'target':
             matched.append(blocked)
     if len(matched) == 0:
@@ -156,7 +174,7 @@ def bug_target(bugdir, bug):
 
 def remove_target(bugdir, bug):
     target = bug_target(bugdir, bug)
-    depend.remove_block(target, bug)
+    libbe.command.depend.remove_block(target, bug)
     return target
 
 def add_target(bugdir, bug, summary):
@@ -164,5 +182,19 @@ def add_target(bugdir, bug, summary):
     if target == None:
         target = bugdir.new_bug(summary=summary)
         target.severity = 'target'
-    depend.add_block(target, bug)
+    libbe.command.depend.add_block(target, bug)
     return target
+
+def targets(bugdir):
+    bugdir.load_all_bugs()
+    for bug in bugdir:
+        if bug.severity == 'target':
+            yield bug.summary
+
+def complete_target(command, argument, fragment=None):
+    """
+    List possible command completions for fragment.
+
+    argument argument is not used.
+    """
+    return targets(command._get_bugdir())
index 2dff930137cffc3bfe71b0d535a7694b3d822a09..ce0e55e9170e27a67ee1d469819a638dafaaae46 100755 (executable)
@@ -223,6 +223,8 @@ class BE (libbe.command.Command):
         for name in libbe.command.commands():
             module = libbe.command.get_command(name)
             Class = libbe.command.get_command_class(module, name)
+            assert hasattr(Class, '__doc__') and Class.__doc__ != None, \
+                'Command class %s missing docstring' % Class
             cmdlist.append((name, Class.__doc__.splitlines()[0]))
         cmdlist.sort()
         longest_cmd_len = max([len(name) for name,desc in cmdlist])