[Libguestfs] [libnbd PATCH 08/23] generator/utils: factor out "pr_buf"

Laszlo Ersek lersek at redhat.com
Tue Apr 25 07:10:52 UTC 2023


We're going to reuse the part of "pr_wrap" that runs "code" while
temporarily redirecting the output channel to a buffer. Extract it as
"pr_buf".

Bugzilla: https://bugzilla.redhat.com/show_bug.cgi?id=2172516
Signed-off-by: Laszlo Ersek <lersek at redhat.com>
---
 generator/utils.ml | 22 +++++++++++++-------
 1 file changed, 14 insertions(+), 8 deletions(-)

diff --git a/generator/utils.ml b/generator/utils.ml
index 48bd6dd12ba8..5ae87c1ba786 100644
--- a/generator/utils.ml
+++ b/generator/utils.ml
@@ -151,6 +151,19 @@ let
 
 let spaces n = String.make n ' '
 
+(* Save the current output channel and replace it with a temporary buffer while
+ * running ‘code’.  Return the buffer.
+ *)
+let pr_buf code =
+  let old_chan = !chan in
+  let wrapping_col = !col in
+  let b = Buffer.create 1024 in
+  chan := Buffer b;
+  let exn = try code (); None with exn -> Some exn in
+  chan := old_chan;
+  col := wrapping_col;
+  match exn with None -> b | Some exn -> raise exn
+
 (* Wrap the output at maxcol, breaking up lines when a 'c' character
  * occurs.  For example:
  *   foobar = a, b, c, d, e, f, g
@@ -165,15 +178,8 @@ let
    * temporary buffer while running ‘code’.  Then we wrap the
    * buffer and write it to the restored channel.
    *)
-  let old_chan = !chan in
+  let b = pr_buf code in
   let wrapping_col = !col in
-  let b = Buffer.create 1024 in
-  chan := Buffer b;
-  let exn = try code (); None with exn -> Some exn in
-  chan := old_chan;
-  col := wrapping_col;
-  (match exn with None -> () | Some exn -> raise exn);
-
   let lines = nsplit "\n" (Buffer.contents b) in
   match lines with
   | [] -> ()



More information about the Libguestfs mailing list