From feec4cc5c269bd2c49a51a6fbd2ee9b41377e870 Mon Sep 17 00:00:00 2001
From: Michael Hanselmann <hansmi@google.com>
Date: Thu, 25 Oct 2012 17:29:51 +0200
Subject: [PATCH] =?UTF-8?q?Factorize=20job=20selection=20in=20=E2=80=9Cgnt?=
 =?UTF-8?q?-job=20cancel=E2=80=9D?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This will also be used for changing jobs' priorities. All parameters to
the common function are non-optional.

Signed-off-by: Michael Hanselmann <hansmi@google.com>
Reviewed-by: Iustin Pop <iustin@google.com>
---
 lib/client/gnt_job.py | 39 ++++++++++++++++++++++++++++++---------
 1 file changed, 30 insertions(+), 9 deletions(-)

diff --git a/lib/client/gnt_job.py b/lib/client/gnt_job.py
index 93a9ba778..b1fa7f69c 100644
--- a/lib/client/gnt_job.py
+++ b/lib/client/gnt_job.py
@@ -174,19 +174,25 @@ def AutoArchiveJobs(opts, args):
   return 0
 
 
-def CancelJobs(opts, args, cl=None, _stdout_fn=ToStdout, _ask_fn=AskUser):
-  """Cancel not-yet-started jobs.
+def _MultiJobAction(opts, args, cl, stdout_fn, ask_fn, question, action_fn):
+  """Applies a function to multipe jobs.
 
-  @param opts: the command line options selected by the user
+  @param opts: Command line options
   @type args: list
-  @param args: should contain the job IDs to be cancelled
+  @param args: Job IDs
   @rtype: int
-  @return: the desired exit code
+  @return: Exit code
 
   """
   if cl is None:
     cl = GetClient()
 
+  if stdout_fn is None:
+    stdout_fn = ToStdout
+
+  if ask_fn is None:
+    ask_fn = AskUser
+
   result = constants.EXIT_SUCCESS
 
   if bool(args) ^ (opts.status_filter is None):
@@ -206,24 +212,39 @@ def CancelJobs(opts, args, cl=None, _stdout_fn=ToStdout, _ask_fn=AskUser):
       (_, table) = FormatQueryResult(response, header=True,
                                      format_override=_JOB_LIST_FORMAT)
       for line in table:
-        _stdout_fn(line)
+        stdout_fn(line)
 
-      if not _ask_fn("Cancel job(s) listed above?"):
+      if not ask_fn(question):
         return constants.EXIT_CONFIRMATION
   else:
     jobs = args
 
   for job_id in jobs:
-    (success, msg) = cl.CancelJob(job_id)
+    (success, msg) = action_fn(cl, job_id)
 
     if not success:
       result = constants.EXIT_FAILURE
 
-    _stdout_fn(msg)
+    stdout_fn(msg)
 
   return result
 
 
+def CancelJobs(opts, args, cl=None, _stdout_fn=ToStdout, _ask_fn=AskUser):
+  """Cancel not-yet-started jobs.
+
+  @param opts: the command line options selected by the user
+  @type args: list
+  @param args: should contain the job IDs to be cancelled
+  @rtype: int
+  @return: the desired exit code
+
+  """
+  return _MultiJobAction(opts, args, cl, _stdout_fn, _ask_fn,
+                         "Cancel job(s) listed above?",
+                         lambda cl, job_id: cl.CancelJob(job_id))
+
+
 def ShowJobs(opts, args):
   """Show detailed information about jobs.
 
-- 
GitLab