-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathConditionConfiguration.cs
More file actions
90 lines (74 loc) · 2.33 KB
/
Copy pathConditionConfiguration.cs
File metadata and controls
90 lines (74 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// <copyright file="ConditionConfiguration.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
namespace Datadog.Trace.FeatureFlags.Rcm.Model;
internal sealed class ConditionConfiguration
{
private Regex? _regex;
public ConditionOperator? Operator { get; set; }
public string? Attribute { get; set; }
public object? Value { get; set; }
internal bool HasValidRegex()
{
try
{
_ = GetOrCreateRegex();
return true;
}
catch (FormatException)
{
return false;
}
}
internal bool MatchesRegex(object attributeValue)
{
var regex = GetOrCreateRegex();
try
{
return regex.IsMatch(ToString(attributeValue));
}
catch
{
return false;
}
static string ToString(object attributeValue)
{
if (attributeValue is null) { return string.Empty; }
if (attributeValue is bool boolValue) { return boolValue ? "true" : "false"; }
return Convert.ToString(attributeValue, CultureInfo.InvariantCulture) ?? string.Empty;
}
}
private Regex GetOrCreateRegex()
{
if (_regex is not null)
{
return _regex;
}
var pattern = Value?.ToString() ?? string.Empty;
if (pattern is not { Length: > 0 })
{
throw new FormatException("Condition value can not be null nor empty");
}
if (pattern.StartsWith("(?u)", StringComparison.Ordinal))
{
pattern = pattern.Substring(4);
}
// Rust regex treats POSIX alnum as ASCII, so preserve the canonical semantics.
pattern = pattern.Replace("[:alnum:]", "0-9A-Za-z");
try
{
_regex = new Regex(pattern, RegexOptions.Compiled);
return _regex;
}
catch (ArgumentException ex)
{
throw new FormatException($"Invalid regex pattern: {pattern}", ex);
}
}
}