[libvirt-ci PATCH 03/13] lcitool: Prefer tempfile's native wrappers over low level primitives

Erik Skultety posted 13 patches 5 years, 9 months ago
[libvirt-ci PATCH 03/13] lcitool: Prefer tempfile's native wrappers over low level primitives
Posted by Erik Skultety 5 years, 9 months ago
Rather than requiring shutil module to get rid of the temporary
directory we're creating for virt-install, let's use the
TemporaryDirectory method instead which returns a file-like object which
can be used to clean up the standard Python way.
Although the internal exit handlers will take care of closing the
temporary directories (and thus removing their contents) automatically,
let's be explicit anyway and use the 'finally' clause to clean these up
on both success and failure.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
---
 guests/lcitool | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)

diff --git a/guests/lcitool b/guests/lcitool
index 9a9326d..51ee211 100755
--- a/guests/lcitool
+++ b/guests/lcitool
@@ -23,7 +23,6 @@ import json
 import os
 import platform
 import random
-import shutil
 import string
 import subprocess
 import sys
@@ -608,8 +607,8 @@ class Application:
                         facts[option]
                     )
 
-            tempdir = tempfile.mkdtemp()
-            initrd_inject = os.path.join(tempdir, install_config)
+            tempdir = tempfile.TemporaryDirectory()
+            initrd_inject = os.path.join(tempdir.name, install_config)
 
             with open(initrd_inject, "w") as inject:
                 inject.write(content)
@@ -663,8 +662,8 @@ class Application:
                 subprocess.check_call(cmd)
             except Exception as ex:
                 raise Exception("Failed to install '{}': {}".format(host, ex))
-
-            shutil.rmtree(tempdir, ignore_errors=True)
+            finally:
+                tempdir.cleanup()
 
     def _action_update(self, args):
         self._execute_playbook("update", args.hosts, args.projects,
-- 
2.25.3

Re: [libvirt-ci PATCH 03/13] lcitool: Prefer tempfile's native wrappers over low level primitives
Posted by Andrea Bolognani 5 years, 9 months ago
On Wed, 2020-04-22 at 15:28 +0200, Erik Skultety wrote:
> Rather than requiring shutil module to get rid of the temporary
> directory we're creating for virt-install, let's use the
> TemporaryDirectory method instead which returns a file-like object which
> can be used to clean up the standard Python way.
> Although the internal exit handlers will take care of closing the
> temporary directories (and thus removing their contents) automatically,
> let's be explicit anyway and use the 'finally' clause to clean these up
> on both success and failure.
> 
> Signed-off-by: Erik Skultety <eskultet@redhat.com>
> ---
>  guests/lcitool | 9 ++++-----
>  1 file changed, 4 insertions(+), 5 deletions(-)

Reviewed-by: Andrea Bolognani <abologna@redhat.com>

-- 
Andrea Bolognani / Red Hat / Virtualization