[pmg-devel] [PATCH pve-common 1/2] Systemd: add helpers for parsing unit files
Thomas Lamprecht
t.lamprecht at proxmox.com
Tue Nov 10 09:34:58 CET 2020
On 28.10.20 19:54, Stoiko Ivanov wrote:
> taken from pve-storage/PVE/API2/Disks/Directory.pm (and made available as
> public sub)
we could now replace those usages over there? Not urgent, just as reminder.
>
> Signed-off-by: Stoiko Ivanov <s.ivanov at proxmox.com>
> ---
> refactoring pve-storage to use this (and drop the now duplicated code) will
> be done separately
>
> src/PVE/Systemd.pm | 72 ++++++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 72 insertions(+)
>
> diff --git a/src/PVE/Systemd.pm b/src/PVE/Systemd.pm
> index 85b35a3..bcba5eb 100644
> --- a/src/PVE/Systemd.pm
> +++ b/src/PVE/Systemd.pm
> @@ -7,6 +7,8 @@ use Net::DBus qw(dbus_uint32 dbus_uint64);
> use Net::DBus::Callback;
> use Net::DBus::Reactor;
>
> +use PVE::Tools qw(file_set_contents file_get_contents trim);
> +
> sub escape_unit {
> my ($val, $is_path) = @_;
>
> @@ -163,4 +165,74 @@ sub wait_for_unit_removed($;$) {
> }, $timeout);
> }
>
> +sub read_ini {
> + my ($filename) = @_;
> +
> + my $content = file_get_contents($filename);
> + my @lines = split /\n/, $content;
> +
> + my $result = {};
> + my $section;
> +
> + foreach my $line (@lines) {
> + $line = trim($line);
> + if ($line =~ m/^\[([^\]]+)\]/) {
> + $section = $1;
> + if (!defined($result->{$section})) {
> + $result->{$section} = {};
> + }
> + } elsif ($line =~ m/^(.*?)=(.*)$/) {
> + my ($key, $val) = ($1, $2);
> + if (!$section) {
> + warn "key value pair found without section, skipping\n";
> + next;
> + }
> +
> + if ($result->{$section}->{$key}) {
> + # make duplicate properties to arrays to keep the order
> + my $prop = $result->{$section}->{$key};
> + if (ref($prop) eq 'ARRAY') {
> + push @$prop, $val;
> + } else {
> + $result->{$section}->{$key} = [$prop, $val];
> + }
> + } else {
> + $result->{$section}->{$key} = $val;
> + }
> + }
> + # ignore everything else
> + }
> +
> + return $result;
> +};
> +
> +sub write_ini {
> + my ($ini, $filename) = @_;
> +
> + my $content = "";
> +
> + foreach my $sname (sort keys %$ini) {
> + my $section = $ini->{$sname};
> +
> + $content .= "[$sname]\n";
> +
> + foreach my $pname (sort keys %$section) {
> + my $prop = $section->{$pname};
> +
> + if (!ref($prop)) {
> + $content .= "$pname=$prop\n";
> + } elsif (ref($prop) eq 'ARRAY') {
> + foreach my $val (@$prop) {
> + $content .= "$pname=$val\n";
> + }
> + } else {
> + die "invalid property '$pname'\n";
> + }
> + }
> + $content .= "\n";
> + }
> +
> + file_set_contents($filename, $content);
> +};
> +
> 1;
>
More information about the pmg-devel
mailing list