[pve-devel] [PATCH common] add edit_file subroutine

Dominik Csapak d.csapak at proxmox.com
Mon Nov 6 15:15:07 CET 2017


this is a wrapper for editing a file via a temporary file in
/run/pve-edit.tmp.PID with the editor set with update-alternatives
(/usr/bin/editor)

Signed-off-by: Dominik Csapak <d.csapak at proxmox.com>
---
 src/PVE/Tools.pm | 35 +++++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)

diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm
index 2525e55..5782d25 100644
--- a/src/PVE/Tools.pm
+++ b/src/PVE/Tools.pm
@@ -1658,4 +1658,39 @@ sub convert_size {
     return $value;
 }
 
+# used for editing files with /usr/bin/editor
+# expects a readfn which returns the contents
+# and a writefn which writes the file and does additional checks
+# e.g., checking a digest
+sub edit_file {
+    my ($readfn, $writefn) = @_;
+
+    my $content = $readfn->();
+
+    my $tmppath = "/run/pve-edit.tmp.$$";
+    PVE::Tools::file_set_contents($tmppath, $content);
+
+    my $exitcode = system {"/usr/bin/editor"} "/usr/bin/editor", $tmppath;
+
+    if ($exitcode == 0) {
+
+	my $raw = PVE::Tools::file_get_contents($tmppath);
+
+	eval {
+	    $writefn->($raw);
+	};
+
+	if (my $err = $@) {
+	    die "error: \n$err\n".
+	    "unsaved changes are in: '$tmppath'\n";
+	}
+
+    } else {
+	die "/usr/bin/editor exited with '$exitcode' \n";
+    }
+
+    # delete tmpfile
+    unlink($tmppath);
+}
+
 1;
-- 
2.11.0





More information about the pve-devel mailing list