]> git.proxmox.com Git - pve-guest-common.git/commitdiff
tag helpers: add get_unique_tags method for filtering out duplicates
authorThomas Lamprecht <t.lamprecht@proxmox.com>
Mon, 21 Nov 2022 07:09:24 +0000 (08:09 +0100)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Mon, 21 Nov 2022 07:15:21 +0000 (08:15 +0100)
tags must be unique, allow the user some control in how unique (case
sensitive) and honor the ordering settings (even if I doubt any
production setups wants to spent time and $$$ on cautiously
reordering all tags of their dozens to hundreds virtual guests..

Have some duplicate code to avoid checking to much in the loop
itself, as frequent branches can be more expensive.

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
src/PVE/GuestHelpers.pm

index 98cfbf826dab4d549ebb093c839768475380a5ec..b4ccbaa73a3fd08ba5d34350ebd57ee31355035b 100644 (file)
@@ -335,4 +335,35 @@ sub assert_tag_permissions {
     }
 }
 
+sub get_unique_tags {
+    my ($tags, $no_join_result) = @_;
+
+    $tags = [ split_list($tags // '') ] if ref($tags) ne 'ARRAY';
+    return !$no_join_result ? '': [] if !scalar($tags->@*);
+
+    my $datacenter_config = PVE::Cluster::cfs_read_file('datacenter.cfg');
+    my $tag_style_config = $datacenter_config->{'tag-style'} // {};
+    my $case_sensitive = !!$tag_style_config->{'case-sensitive'};
+
+    my $seen_tags = {};
+    my $res = [];
+    if (!defined($tag_style_config->{ordering}) || $tag_style_config->{ordering} ne 'config') {
+       for my $tag ( sort { $case_sensitive ? $a cmp $b : lc($a) cmp lc($b) } $tags->@*) {
+           $tag = lc($tag) if !$case_sensitive;
+           next if $seen_tags->{$tag};
+           $seen_tags->{$tag} = 1;
+           push @$res, $tag;
+       }
+    } else {
+       for my $tag ($tags->@*) {
+           $tag = lc($tag) if !$case_sensitive;
+           next if $seen_tags->{$tag};
+           $seen_tags->{$tag} = 1;
+           push @$res, $tag;
+       }
+    }
+
+    return !$no_join_result ? join(';', $res->@*) : $res;
+}
+
 1;