Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#921 and #935 enable s134 and s3776 #1260

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Steeltoe.Debug.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
<Rule Id="S1186" Action="None" />
<Rule Id="S1244" Action="Warning" />
<Rule Id="S125" Action="Info" />
<Rule Id="S134" Action="Warning" />
<Rule Id="S1449" Action="Warning" />
<Rule Id="S1479" Action="Warning" />
<Rule Id="S1481" Action="Info" />
Expand Down
2 changes: 2 additions & 0 deletions Steeltoe.Release.ruleset
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<Rule Id="S1151" Action="Warning" />
<Rule Id="S1186" Action="None" />
<Rule Id="S1244" Action="Warning" />
<Rule Id="S134" Action="Warning" />
<Rule Id="S1449" Action="Warning" />
<Rule Id="S1479" Action="Warning" />
<Rule Id="S1659" Action="Warning" />
Expand All @@ -42,6 +43,7 @@
<Rule Id="S3433" Action="None" />
<Rule Id="S3597" Action="None" />
<Rule Id="S3598" Action="None" />
<Rule Id="S3776" Action="Warning" />
<Rule Id="S3872" Action="Warning" />
<Rule Id="S3874" Action="Warning" />
<Rule Id="S3889" Action="None" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ protected TypeAccessor ResolveType(params string[] typeNames)

foreach (string typeName in typeNames)
{
#pragma warning disable S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply
try
{
Type type = assembly.GetType(typeName, true)!;
Expand All @@ -97,6 +98,7 @@ protected TypeAccessor ResolveType(params string[] typeNames)
{
exceptions.Add(exception);
}
#pragma warning restore S134 // Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply
}
}
catch (Exception exception) when (exception is ArgumentException or IOException or BadImageFormatException)
Expand Down
123 changes: 55 additions & 68 deletions src/Common/src/Common/Configuration/PropertyPlaceHolderHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.

using System.Linq;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -77,99 +78,85 @@ public static IEnumerable<KeyValuePair<string, string>> GetResolvedConfiguration
private static string ParseStringValue(string property, IConfiguration configuration, ISet<string> visitedPlaceHolders, ILogger logger = null,
bool useEmptyStringIfNotFound = false)
{
if (configuration == null)
{
return property;
}

if (string.IsNullOrEmpty(property))
if (configuration == null || string.IsNullOrEmpty(property))
{
return property;
}

int startIndex = property.IndexOf(Prefix, StringComparison.Ordinal);

if (startIndex == -1)
{
return property;
}

var result = new StringBuilder(property);

while (startIndex != -1)
int endIndex;
while (startIndex != -1 && (endIndex = FindEndIndex(result, startIndex)) != -1)
{
int endIndex = FindEndIndex(result, startIndex);

if (endIndex != -1)
{
string placeholder = result.Substring(startIndex + Prefix.Length, endIndex);

string originalPlaceholder = placeholder;
string placeholder = result.Substring(startIndex + Prefix.Length, endIndex);

if (!visitedPlaceHolders.Add(originalPlaceholder))
{
throw new InvalidOperationException($"Found circular placeholder reference '{originalPlaceholder}' in property definitions.");
}
string originalPlaceholder = placeholder;

// Recursive invocation, parsing placeholders contained in the placeholder key.
placeholder = ParseStringValue(placeholder, configuration, visitedPlaceHolders);
if (!visitedPlaceHolders.Add(originalPlaceholder))
{
throw new InvalidOperationException($"Found circular placeholder reference '{originalPlaceholder}' in property definitions.");
}

// Handle array references foo:bar[1]:baz format -> foo:bar:1:baz
string lookup = placeholder.Replace('[', ':').Replace("]", string.Empty, StringComparison.Ordinal);
// Recursive invocation, parsing placeholders contained in the placeholder key.
placeholder = ParseStringValue(placeholder, configuration, visitedPlaceHolders);

// Now obtain the value for the fully resolved key...
string propVal = configuration[lookup];
// Handle array references foo:bar[1]:baz format -> foo:bar:1:baz
string lookup = placeholder.Replace('[', ':').Replace("]", string.Empty, StringComparison.Ordinal);

if (propVal == null)
{
int separatorIndex = placeholder.IndexOf(Separator, StringComparison.Ordinal);

if (separatorIndex != -1)
{
string actualPlaceholder = placeholder.Substring(0, separatorIndex);
string defaultValue = placeholder.Substring(separatorIndex + Separator.Length);
propVal = configuration[actualPlaceholder] ?? defaultValue;
}
else if (useEmptyStringIfNotFound)
{
propVal = string.Empty;
}
}
// Now obtain the value for the fully resolved key...
string propVal = configuration[lookup];

// Attempt to resolve as a spring-compatible placeholder
if (propVal == null)
{
// Replace Spring delimiters ('.') with MS-friendly delimiters (':') so Spring placeholders can also be resolved
lookup = placeholder.Replace('.', ':');
propVal = configuration[lookup];
}
propVal ??= ResolveValue(configuration, placeholder, propVal, useEmptyStringIfNotFound);

if (propVal != null)
{
// Recursive invocation, parsing placeholders contained in these
// previously resolved placeholder value.
propVal = ParseStringValue(propVal, configuration, visitedPlaceHolders);
result.Replace(startIndex, endIndex + Suffix.Length, propVal);
logger?.LogDebug("Resolved placeholder '{placeholder}'", placeholder);
startIndex = result.IndexOf(Prefix, startIndex + propVal.Length);
}
else
{
// Proceed with unprocessed value.
startIndex = result.IndexOf(Prefix, endIndex + Prefix.Length);
}

visitedPlaceHolders.Remove(originalPlaceholder);
if (propVal != null)
{
// Recursive invocation, parsing placeholders contained in these
// previously resolved placeholder value.
propVal = ParseStringValue(propVal, configuration, visitedPlaceHolders);
result.Replace(startIndex, endIndex + Suffix.Length, propVal);
logger?.LogDebug("Resolved placeholder '{placeholder}'", placeholder);
startIndex = result.IndexOf(Prefix, startIndex + propVal.Length);
}
else
{
startIndex = -1;
// Proceed with unprocessed value.
startIndex = result.IndexOf(Prefix, endIndex + Prefix.Length);
}

visitedPlaceHolders.Remove(originalPlaceholder);

}

return result.ToString();
}

private static string ResolveValue(IConfiguration configuration, string placeholder, string propVal, bool useEmptyStringIfNotFound)
{
int separatorIndex = placeholder.IndexOf(Separator, StringComparison.Ordinal);

if (separatorIndex != -1)
{
string actualPlaceholder = placeholder.Substring(0, separatorIndex);
string defaultValue = placeholder.Substring(separatorIndex + Separator.Length);
propVal = configuration[actualPlaceholder] ?? defaultValue;
}
else if (useEmptyStringIfNotFound)
{
propVal = string.Empty;
}

// Attempt to resolve as a spring-compatible placeholder
if (propVal == null)
{
// Replace Spring delimiters ('.') with MS-friendly delimiters (':') so Spring placeholders can also be resolved
string lookup = placeholder.Replace('.', ':');
propVal = configuration[lookup];
}
return propVal;
}

private static int FindEndIndex(StringBuilder property, int startIndex)
{
int index = startIndex + Prefix.Length;
Expand Down
65 changes: 22 additions & 43 deletions src/Common/src/Common/Net/InetUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,39 +46,30 @@ public IPAddress FindFirstNonLoopbackAddress()
try
{
int lowest = int.MaxValue;
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces()
.Where(x => x.OperationalStatus == OperationalStatus.Up && !x.IsReceiveOnly && !IgnoreInterface(x.Name))
.ToArray();

foreach (NetworkInterface @interface in interfaces)
{
if (@interface.OperationalStatus == OperationalStatus.Up && [email protected])
_logger?.LogTrace("Testing interface: {name}, {id}", @interface.Name, @interface.Id);

IPInterfaceProperties props = @interface.GetIPProperties();
IPv4InterfaceProperties ipProps = props.GetIPv4Properties();

if (ipProps.Index < lowest || result == null)
{
lowest = ipProps.Index;
}
else
{
_logger?.LogTrace("Testing interface: {name}, {id}", @interface.Name, @interface.Id);

IPInterfaceProperties props = @interface.GetIPProperties();
IPv4InterfaceProperties ipProps = props.GetIPv4Properties();

if (ipProps.Index < lowest || result == null)
{
lowest = ipProps.Index;
}
else
{
continue;
}

if (!IgnoreInterface(@interface.Name))
{
foreach (UnicastIPAddressInformation addressInfo in props.UnicastAddresses)
{
IPAddress address = addressInfo.Address;

if (IsInet4Address(address) && !IsLoopbackAddress(address) && IsPreferredAddress(address))
{
_logger?.LogTrace("Found non-loopback interface: {name}", @interface.Name);
result = address;
}
}
}
continue;
}
foreach (UnicastIPAddressInformation addressInfo in props.UnicastAddresses
.Where(x => IsInet4Address(x.Address) && !IsLoopbackAddress(x.Address) && IsPreferredAddress(x.Address)))
{
_logger?.LogTrace("Found non-loopback interface: {name}", @interface.Name);
result = addressInfo.Address;
}
}
}
Expand Down Expand Up @@ -195,30 +186,18 @@ internal HostInfo ConvertAddress(IPAddress address)

internal IPAddress ResolveHostAddress(string hostName)
{
IPAddress result = null;

try
{
IPAddress[] results = Dns.GetHostAddresses(hostName);

if (results.Length > 0)
{
foreach (IPAddress address in results)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
result = address;
break;
}
}
}
return Array.Find(results, x => x.AddressFamily == AddressFamily.InterNetwork);
}
catch (Exception e)
{
_logger?.LogWarning(e, "Unable to resolve host address");
}

return result;
return null;
}

internal string ResolveHostName()
Expand Down
33 changes: 19 additions & 14 deletions src/Common/src/Common/Reflection/ReflectionHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -213,16 +213,17 @@ public static Type FindType(string[] assemblyNames, string[] typeNames)
{
Assembly assembly = FindAssembly(assemblyName);

if (assembly != null)
if (assembly == null)
{
foreach (string type in typeNames)
{
Type result = FindType(assembly, type);
continue;
}
foreach (string type in typeNames)
{
Type result = FindType(assembly, type);

if (result != null)
{
return result;
}
if (result != null)
{
return result;
}
}
}
Expand Down Expand Up @@ -462,12 +463,7 @@ private static void TryLoadAssembliesWithAttribute<T>()
try
{
Assembly assemblyRef = loadContext.LoadFromAssemblyPath(assembly);

// haven't been able to get actual type comparison to work (assembly of the attribute not found?), falling back on matching the type name
if (CustomAttributeData.GetCustomAttributes(assemblyRef).Any(attr => attr.AttributeType.FullName == typeof(T).FullName))
{
FindAssembly(filename);
}
FindAssemblyByFullName<T>(assemblyRef, filename);
}
catch
{
Expand All @@ -477,6 +473,15 @@ private static void TryLoadAssembliesWithAttribute<T>()
}
}

private static void FindAssemblyByFullName<T>(Assembly assemblyRef, string filename)
{
// haven't been able to get actual type comparison to work (assembly of the attribute not found?), falling back on matching the type name
if (CustomAttributeData.GetCustomAttributes(assemblyRef).Any(attr => attr.AttributeType.FullName == typeof(T).FullName))
{
FindAssembly(filename);
}
}

/// <summary>
/// Build a list of file paths that are relevant to this task.
/// </summary>
Expand Down
Loading
Loading