tools: allow to force UTF-8 encoding for file_set_contents

Rationale: This is used from cfs_write_file, which is now also used to
write utf8-encoded strings that come from Rust. If no encoding is
specified while writing the file, we run into problems with certain
special characters (e.g. 'ü').

Signed-off-by: Lukas Wagner <l.wagner@proxmox.com>
[FG: use flag parameter instead of encoding as a string
     use stricter 'UTF-8' instaed of 'utf8' (see 'perldoc Enocode')]
Suggested-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
[FE: implement changes suggested by Fabian
     move binmode call to where $fh is known to be set]
Signed-off-by: Fiona Ebner <f.ebner@proxmox.com>
This commit is contained in:
Lukas Wagner 2023-08-30 14:37:52 +02:00 committed by Fiona Ebner
parent 41ed439635
commit 2943910ec3

View File

@ -238,7 +238,7 @@ sub lock_file {
}
sub file_set_contents {
my ($filename, $data, $perm) = @_;
my ($filename, $data, $perm, $force_utf8) = @_;
$perm = 0644 if !defined($perm);
@ -253,6 +253,9 @@ sub file_set_contents {
}
}
die "unable to open file '$tmpname' - $!\n" if !$fh;
binmode($fh, ":encoding(UTF-8)") if $force_utf8;
die "unable to write '$tmpname' - $!\n" unless print $fh $data;
die "closing file '$tmpname' failed - $!\n" unless close $fh;
};