Compare commits

...

7 Commits

Author SHA1 Message Date
Pieter-Jan Briers
69daaca399 Remove CVar.SECURE and replace auth CVars with env variables. 2021-02-09 01:50:42 +01:00
DrSmugleaf
5af7e60043 Add KeyValuePair YAML serialization (#1538) 2021-02-08 21:49:08 +01:00
DrSmugleaf
ab823dcd12 Add component registration lookup with case insensitive names (#1535) 2021-02-08 18:07:23 +01:00
Paul Ritter
b3976eb8d7 Analyzer Bongaloo 2: The Return (#1512)
Co-authored-by: Paul <ritter.paul1+git@googlemail.com>
2021-02-08 18:05:27 +01:00
Pieter-Jan Briers
91759cdd3c Harder DynamicTree against NaN.
B2DynamicTree<T> has asserts, DynamicTree<T> handles them gracefully.

NaNs in DynamicTree were causing the internal state to corrupt resulting in the sprite flickering issues.

Fixes https://github.com/space-wizards/space-station-14/issues/2896
2021-02-08 05:03:56 +01:00
Pieter-Jan Briers
b000c3178b FileLogHandler is now internal.
Sandboxing thing.
2021-02-07 23:07:57 +01:00
Vera Aguilera Puerto
63b3ecdd13 Fix SpawnRepeating timer extensions 2021-02-07 17:04:43 +01:00
41 changed files with 786 additions and 121 deletions

View File

@@ -0,0 +1,5 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)\..\Robust.Analyzers\Robust.Analyzers.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"/>
</ItemGroup>
</Project>

View File

@@ -1,2 +1,3 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
<Import Project="Robust.Analyzers.targets" />
</Project>

View File

@@ -0,0 +1,92 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Document = Microsoft.CodeAnalysis.Document;
namespace Robust.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ExplicitInterfaceAnalyzer : DiagnosticAnalyzer
{
public readonly SyntaxKind[] ExcludedModifiers =
{
SyntaxKind.VirtualKeyword,
SyntaxKind.AbstractKeyword,
SyntaxKind.OverrideKeyword
};
public const string DiagnosticId = "RA0000";
private const string Title = "No explicit interface specified";
private const string MessageFormat = "No explicit interface specified";
private const string Description = "Make sure to specify the interface in your method-declaration.";
private const string Category = "Usage";
[SuppressMessage("ReSharper", "RS2008")] private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
private const string RequiresExplicitImplementationAttributeMetadataName =
"Robust.Shared.Analyzers.RequiresExplicitImplementationAttribute";
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration);
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PropertyDeclaration);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
ISymbol symbol;
Location location;
switch (context.Node)
{
//we already have a explicit interface specified, no need to check further
case MethodDeclarationSyntax methodDecl when methodDecl.ExplicitInterfaceSpecifier != null || methodDecl.Modifiers.Any(m => ExcludedModifiers.Contains(m.Kind())):
return;
case PropertyDeclarationSyntax propertyDecl when propertyDecl.ExplicitInterfaceSpecifier != null || propertyDecl.Modifiers.Any(m => ExcludedModifiers.Contains(m.Kind())):
return;
case MethodDeclarationSyntax methodDecl:
symbol = context.SemanticModel.GetDeclaredSymbol(methodDecl);
location = methodDecl.Identifier.GetLocation();
break;
case PropertyDeclarationSyntax propertyDecl:
symbol = context.SemanticModel.GetDeclaredSymbol(propertyDecl);
location = propertyDecl.Identifier.GetLocation();
break;
default:
return;
}
var attrSymbol = context.Compilation.GetTypeByMetadataName(RequiresExplicitImplementationAttributeMetadataName);
var isInterfaceMember = symbol?.ContainingType.AllInterfaces.Any(
i =>
i.GetMembers().Any(m => SymbolEqualityComparer.Default.Equals(symbol, symbol.ContainingType.FindImplementationForInterfaceMember(m)))
&& i.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attrSymbol))
) ?? false;
if (isInterfaceMember)
{
//we do not have an explicit interface specified. bad!
var diagnostic = Diagnostic.Create(
Rule,
location);
context.ReportDiagnostic(diagnostic);
}
}
}
}

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.Common" Version="3.8.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,150 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Robust.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SerializableAnalyzer : DiagnosticAnalyzer
{
// Metadata of the analyzer
public const string DiagnosticId = "RA0001";
// You could use LocalizedString but it's a little more complicated for this sample
private const string Title = "Class not marked as (Net)Serializable";
private const string MessageFormat = "Class not marked as (Net)Serializable";
private const string Description = "The class should be marked as (Net)Serializable.";
private const string Category = "Usage";
private const string RequiresSerializableAttributeMetadataName = "Robust.Shared.Analyzers.RequiresSerializableAttribute";
private const string SerializableAttributeMetadataName = "System.SerializableAttribute";
private const string NetSerializableAttributeMetadataName = "Robust.Shared.Serialization.NetSerializableAttribute";
[SuppressMessage("ReSharper", "RS2008")] private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration);
}
private bool Marked(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol attrSymbol)
{
if (namedTypeSymbol == null) return false;
if (namedTypeSymbol.GetAttributes()
.Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attrSymbol))) return true;
return Marked(namedTypeSymbol.BaseType, attrSymbol);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var attrSymbol = context.Compilation.GetTypeByMetadataName(RequiresSerializableAttributeMetadataName);
var classDecl = (ClassDeclarationSyntax) context.Node;
var classSymbol = context.SemanticModel.GetDeclaredSymbol(classDecl);
if (classSymbol == null) return;
if (Marked(classSymbol, attrSymbol))
{
var attributes = classSymbol.GetAttributes();
var serAttr = context.Compilation.GetTypeByMetadataName(SerializableAttributeMetadataName);
var netSerAttr = context.Compilation.GetTypeByMetadataName(NetSerializableAttributeMetadataName);
var hasSerAttr = attributes.Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, serAttr));
var hasNetSerAttr =
attributes.Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, netSerAttr));
if (!hasSerAttr || !hasNetSerAttr)
{
var requiredAttributes = new List<string>();
if(!hasSerAttr) requiredAttributes.Add(SerializableAttributeMetadataName);
if(!hasNetSerAttr) requiredAttributes.Add(NetSerializableAttributeMetadataName);
context.ReportDiagnostic(
Diagnostic.Create(
Rule,
classDecl.Identifier.GetLocation(),
ImmutableDictionary.CreateRange(new Dictionary<string, string>()
{
{
"requiredAttributes", string.Join(",", requiredAttributes)
}
})));
}
}
}
}
[ExportCodeFixProvider(LanguageNames.CSharp)]
public class SerializableCodeFixProvider : CodeFixProvider
{
private const string Title = "Annotate class as (Net)Serializable.";
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken);
foreach (var diagnostic in context.Diagnostics)
{
var span = diagnostic.Location.SourceSpan;
var classDecl = root.FindToken(span.Start).Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().First();
if(!diagnostic.Properties.TryGetValue("requiredAttributes", out var requiredAttributes)) return;
context.RegisterCodeFix(
CodeAction.Create(
Title,
c => FixAsync(context.Document, classDecl, requiredAttributes, c),
Title),
diagnostic);
}
}
private async Task<Document> FixAsync(Document document, ClassDeclarationSyntax classDecl,
string requiredAttributes, CancellationToken cancellationToken)
{
var attributes = new List<AttributeSyntax>();
var namespaces = new List<string>();
foreach (var attribute in requiredAttributes.Split(','))
{
var tempSplit = attribute.Split('.');
namespaces.Add(string.Join(".",tempSplit.Take(tempSplit.Length-1)));
var @class = tempSplit.Last();
@class = @class.Substring(0, @class.Length - 9); //cut out "Attribute" at the end
attributes.Add(SyntaxFactory.Attribute(SyntaxFactory.ParseName(@class)));
}
var newClassDecl =
classDecl.AddAttributeLists(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(attributes)));
var root = (CompilationUnitSyntax) await document.GetSyntaxRootAsync(cancellationToken);
root = root.ReplaceNode(classDecl, newClassDecl);
foreach (var ns in namespaces)
{
if(root.Usings.Any(u => u.Name.ToString() == ns)) continue;
root = root.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(ns)));
}
return document.WithSyntaxRoot(root);
}
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(SerializableAnalyzer.DiagnosticId);
public override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
}
}

View File

@@ -82,6 +82,7 @@ namespace Robust.Client
IoCManager.Register<IFontManager, FontManager>();
IoCManager.Register<IFontManagerInternal, FontManager>();
IoCManager.Register<IMidiManager, MidiManager>();
IoCManager.Register<IAuthManager, AuthManager>();
switch (mode)
{
case GameController.DisplayMode.Headless:

View File

@@ -1,13 +1,13 @@
#if !FULL_RELEASE
using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using Robust.Client.Utility;
using Robust.Shared;
using Robust.Shared.Console;
using Robust.Shared.Interfaces.Configuration;
using Robust.Shared.IoC;
using Robust.Shared.Network;
namespace Robust.Client.Console.Commands
{
@@ -39,9 +39,9 @@ namespace Robust.Client.Console.Commands
var token = login.Token.Token;
var userId = login.UserId;
var cfg = IoCManager.Resolve<IConfigurationManagerInternal>();
cfg.SetSecureCVar(CVars.AuthUserId, userId);
cfg.SetSecureCVar(CVars.AuthToken, token);
var cfg = IoCManager.Resolve<IAuthManager>();
cfg.Token = token;
cfg.UserId = new NetUserId(Guid.Parse(userId));
}
private sealed class LauncherConfig

View File

@@ -31,6 +31,7 @@ using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Interfaces.Timers;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Network;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
@@ -67,6 +68,7 @@ namespace Robust.Client
[Dependency] private readonly IComponentManager _componentManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IRobustMappedStringSerializer _stringSerializer = default!;
[Dependency] private readonly IAuthManager _authManager = default!;
private CommandLineArgs? _commandLineArgs;
private bool _disableAssemblyLoadContext;
@@ -186,6 +188,8 @@ namespace Robust.Client
_client.PlayerNameOverride = _commandLineArgs.Username;
}
_authManager.LoadFromEnv();
_clyde.Ready();
if ((_commandLineArgs?.Connect == true || _commandLineArgs?.Launcher == true)

View File

@@ -18,7 +18,7 @@ namespace Robust.Client.Interfaces.Input
public bool CanRepeat;
public bool AllowSubCombs;
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref Function, "function", default);
serializer.DataField(ref Type, "type", KeyBindingType.State);

View File

@@ -289,7 +289,7 @@ namespace Robust.Server.GameObjects.Components.Container
Type = type;
}
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref Entities, "entities", new List<EntityUid>());
serializer.DataField(ref Type, "type", null);

View File

@@ -73,6 +73,7 @@ namespace Robust.Server
IoCManager.Register<IWatchdogApi, WatchdogApi>();
IoCManager.Register<IScriptHost, ScriptHost>();
IoCManager.Register<IMetricsManager, MetricsManager>();
IoCManager.Register<IAuthManager, AuthManager>();
}
}
}

View File

@@ -0,0 +1,7 @@
using System;
namespace Robust.Shared.Analyzers
{
[AttributeUsage(AttributeTargets.Interface)]
public class RequiresExplicitImplementationAttribute : Attribute { }
}

View File

@@ -0,0 +1,7 @@
using System;
namespace Robust.Shared.Analyzers
{
[AttributeUsage(AttributeTargets.Class)]
public class RequiresSerializableAttribute : Attribute { }
}

View File

@@ -55,7 +55,7 @@ namespace Robust.Shared.Audio
/// </summary>
public static readonly AudioParams Default = new(0, 1, "Master", 62.5f, 1, AudioMixTarget.Stereo, false, 0f);
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
Volume = serializer.ReadDataField("volume", 0f);
PitchScale = serializer.ReadDataField("pitchscale", 1f);

View File

@@ -2,6 +2,7 @@ using System;
using System.Runtime.InteropServices;
using Robust.Shared.Configuration;
using Robust.Shared.Log;
using Robust.Shared.Network;
namespace Robust.Shared
{
@@ -218,17 +219,9 @@ namespace Robust.Shared
public static readonly CVarDef<bool> AuthAllowLocal =
CVarDef.Create("auth.allowlocal", true, CVar.SERVERONLY);
public static readonly CVarDef<string> AuthServerPubKey =
CVarDef.Create("auth.serverpubkey", "", CVar.SECURE | CVar.CLIENTONLY);
public static readonly CVarDef<string> AuthToken =
CVarDef.Create("auth.token", "", CVar.SECURE | CVar.CLIENTONLY);
public static readonly CVarDef<string> AuthUserId =
CVarDef.Create("auth.userid", "", CVar.SECURE | CVar.CLIENTONLY);
// Only respected on server, client goes through IAuthManager for security.
public static readonly CVarDef<string> AuthServer =
CVarDef.Create("auth.server", "https://central.spacestation14.io/auth/", CVar.SECURE);
CVarDef.Create("auth.server", AuthManager.DefaultAuthServer, CVar.SERVERONLY);
/*
* DISPLAY

View File

@@ -57,11 +57,6 @@ namespace Robust.Shared.Configuration
/// <remarks>
/// This is intended to aid shared code.
/// </remarks>
CLIENTONLY = 128,
/// <summary>
/// This var has to kept secure and may not be accessed by content.
/// </summary>
SECURE = 256
CLIENTONLY = 128
}
}

View File

@@ -82,14 +82,6 @@ namespace Robust.Shared.Configuration
var tomlValue = TypeConvert(obj);
if (_configVars.TryGetValue(tablePath, out var cfgVar))
{
if ((cfgVar.Flags & CVar.SECURE) != 0)
{
// DO NOT read SECURE CVars.
// client config is in a location content can access via the user data API.
// Basically all secure CVars are something
// the launcher should be passing in via env vars anyways.
return;
}
// overwrite the value with the saved one
cfgVar.Value = tomlValue;
cfgVar.ValueChanged?.Invoke(cfgVar.Value);
@@ -298,15 +290,13 @@ namespace Robust.Shared.Configuration
/// <inheritdoc />
public bool IsCVarRegistered(string name)
{
return _configVars.TryGetValue(name, out var cVar) && cVar.Registered && (cVar.Flags & CVar.SECURE) == 0;
return _configVars.TryGetValue(name, out var cVar) && cVar.Registered;
}
/// <inheritdoc />
public IEnumerable<string> GetRegisteredCVars()
{
return _configVars
.Where(p => (p.Value.Flags & CVar.SECURE) == 0)
.Select(p => p.Key);
return _configVars.Select(p => p.Key);
}
/// <inheritdoc />
@@ -315,10 +305,10 @@ namespace Robust.Shared.Configuration
SetCVarInternal(name, value);
}
private void SetCVarInternal(string name, object value, bool allowSecure = false)
private void SetCVarInternal(string name, object value)
{
//TODO: Make flags work, required non-derpy net system.
if (_configVars.TryGetValue(name, out var cVar) && cVar.Registered && (allowSecure || (cVar.Flags & CVar.SECURE) == 0))
if (_configVars.TryGetValue(name, out var cVar) && cVar.Registered)
{
if (!Equals(cVar.OverrideValueParsed ?? cVar.Value, value))
{
@@ -341,15 +331,6 @@ namespace Robust.Shared.Configuration
/// <inheritdoc />
public T GetCVar<T>(string name)
{
if (_configVars.TryGetValue(name, out var cVar) && cVar.Registered && (cVar.Flags & CVar.SECURE) == 0)
//TODO: Make flags work, required non-derpy net system.
return (T)(cVar.OverrideValueParsed ?? cVar.Value ?? cVar.DefaultValue)!;
throw new InvalidConfigurationException($"Trying to get unregistered variable '{name}'");
}
public T GetSecureCVar<T>(string name)
{
if (_configVars.TryGetValue(name, out var cVar) && cVar.Registered)
//TODO: Make flags work, required non-derpy net system.
@@ -358,18 +339,6 @@ namespace Robust.Shared.Configuration
throw new InvalidConfigurationException($"Trying to get unregistered variable '{name}'");
}
public void SetSecureCVar(string name, object value)
{
SetCVarInternal(name, value, allowSecure: true);
}
public void SetSecureCVar<T>(CVarDef<T> def, T value) where T : notnull
{
SetSecureCVar(def.Name, value);
}
public T GetCVar<T>(CVarDef<T> def) where T : notnull
{
return GetCVar<T>(def.Name);
@@ -377,7 +346,7 @@ namespace Robust.Shared.Configuration
public Type GetCVarType(string name)
{
if (!_configVars.TryGetValue(name, out var cVar) || !cVar.Registered || (cVar.Flags & CVar.SECURE) != 0)
if (!_configVars.TryGetValue(name, out var cVar) || !cVar.Registered)
{
throw new InvalidConfigurationException($"Trying to get type of unregistered variable '{name}'");
}

View File

@@ -45,6 +45,11 @@ namespace Robust.Shared.GameObjects
/// </summary>
private readonly Dictionary<string, ComponentRegistration> names = new();
/// <summary>
/// Mapping of lowercase component names to their registration.
/// </summary>
private readonly Dictionary<string, string> _lowerCaseNames = new();
/// <summary>
/// Mapping of network ID to type.
/// </summary>
@@ -70,7 +75,7 @@ namespace Robust.Shared.GameObjects
Register(typeof(T), overwrite);
}
private void Register(Type type, bool overwrite=false)
private void Register(Type type, bool overwrite = false)
{
if (types.ContainsKey(type))
{
@@ -82,6 +87,7 @@ namespace Robust.Shared.GameObjects
var dummy = (IComponent)Activator.CreateInstance(type)!;
var name = dummy.Name;
var lowerCaseName = name.ToLowerInvariant();
var netID = dummy.NetID;
var netSyncExist = dummy.NetworkSynchronizeExistence;
@@ -105,6 +111,14 @@ namespace Robust.Shared.GameObjects
RemoveComponent(name);
}
if (_lowerCaseNames.ContainsKey(lowerCaseName))
{
if (!overwrite)
{
throw new InvalidOperationException($"{lowerCaseName} is already registered, previous: {_lowerCaseNames[lowerCaseName]}");
}
}
if (netID != null && netIDs.ContainsKey(netID.Value))
{
if (!overwrite)
@@ -117,6 +131,7 @@ namespace Robust.Shared.GameObjects
var registration = new ComponentRegistration(name, type, netID, netSyncExist);
names[name] = registration;
_lowerCaseNames[lowerCaseName] = name;
types[type] = registration;
if (netID != null)
{
@@ -169,6 +184,7 @@ namespace Robust.Shared.GameObjects
var registration = names[name];
names.Remove(registration.Name);
_lowerCaseNames.Remove(registration.Name.ToLowerInvariant());
types.Remove(registration.Type);
if (registration.NetID != null)
{
@@ -176,8 +192,13 @@ namespace Robust.Shared.GameObjects
}
}
public ComponentAvailability GetComponentAvailability(string componentName)
public ComponentAvailability GetComponentAvailability(string componentName, bool ignoreCase = false)
{
if (ignoreCase && _lowerCaseNames.TryGetValue(componentName, out var lowerCaseName))
{
componentName = lowerCaseName;
}
if (names.ContainsKey(componentName))
{
return ComponentAvailability.Available;
@@ -209,8 +230,13 @@ namespace Robust.Shared.GameObjects
return _typeFactory.CreateInstanceUnchecked<T>(types[typeof(T)].Type);
}
public IComponent GetComponent(string componentName)
public IComponent GetComponent(string componentName, bool ignoreCase = false)
{
if (ignoreCase && _lowerCaseNames.TryGetValue(componentName, out var lowerCaseName))
{
componentName = lowerCaseName;
}
return _typeFactory.CreateInstanceUnchecked<IComponent>(GetRegistration(componentName).Type);
}
@@ -219,8 +245,13 @@ namespace Robust.Shared.GameObjects
return _typeFactory.CreateInstanceUnchecked<IComponent>(GetRegistration(netId).Type);
}
public IComponentRegistration GetRegistration(string componentName)
public IComponentRegistration GetRegistration(string componentName, bool ignoreCase = false)
{
if (ignoreCase && _lowerCaseNames.TryGetValue(componentName, out var lowerCaseName))
{
componentName = lowerCaseName;
}
try
{
return names[componentName];
@@ -265,8 +296,13 @@ namespace Robust.Shared.GameObjects
return GetRegistration(component.GetType());
}
public bool TryGetRegistration(string componentName, [NotNullWhen(true)] out IComponentRegistration? registration)
public bool TryGetRegistration(string componentName, [NotNullWhen(true)] out IComponentRegistration? registration, bool ignoreCase = false)
{
if (ignoreCase && _lowerCaseNames.TryGetValue(componentName, out var lowerCaseName))
{
componentName = lowerCaseName;
}
if (names.TryGetValue(componentName, out var tempRegistration))
{
registration = tempRegistration;

View File

@@ -1,8 +1,10 @@
using Robust.Shared.Serialization;
using System;
using Robust.Shared.Analyzers;
namespace Robust.Shared.GameObjects
{
[RequiresSerializable]
[Serializable, NetSerializable]
public class ComponentState
{

View File

@@ -80,7 +80,7 @@ namespace Robust.Shared.GameObjects.Components.Renderable
};
}
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref Shader, "shader", null);
serializer.DataField(ref TexturePath, "texture", null);

View File

@@ -86,7 +86,7 @@ namespace Robust.Shared.GameObjects.Components.Timers
{
entity
.EnsureComponent<TimerComponent>()
.Spawn(milliseconds, onFired, cancellationToken);
.SpawnRepeating(milliseconds, onFired, cancellationToken);
}
/// <summary>
@@ -100,7 +100,7 @@ namespace Robust.Shared.GameObjects.Components.Timers
{
entity
.EnsureComponent<TimerComponent>()
.Spawn(duration, onFired, cancellationToken);
.SpawnRepeating(duration, onFired, cancellationToken);
}
}
}

View File

@@ -14,7 +14,7 @@ namespace Robust.Shared.GameObjects.Components.UserInterface
public object UiKey { get; private set; } = default!;
public string ClientType { get; private set; } = default!;
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
UiKey = serializer.ReadStringEnumKey("key");
ClientType = serializer.ReadDataField<string>("type");

View File

@@ -9,11 +9,6 @@ namespace Robust.Shared.Interfaces.Configuration
void OverrideConVars(IEnumerable<(string key, string value)> cVars);
void LoadCVarsFromAssembly(Assembly assembly);
T GetSecureCVar<T>(string name);
void SetSecureCVar(string name, object value);
void SetSecureCVar<T>(CVarDef<T> def, T value) where T : notnull;
void Initialize(bool isServer);
/// <summary>

View File

@@ -54,12 +54,13 @@ namespace Robust.Shared.Interfaces.GameObjects
/// </summary>
IEnumerable<Type> AllRegisteredTypes { get; }
/// <summary>
/// <summary>
/// Get whether a component is available right now.
/// </summary>
/// <param name="componentName">The name of the component to check.</param>
/// <param name="ignoreCase">Whether or not to ignore casing on <see cref="componentName"/></param>
/// <returns>The availability of the component.</returns>
ComponentAvailability GetComponentAvailability(string componentName);
ComponentAvailability GetComponentAvailability(string componentName, bool ignoreCase = false);
/// <summary>
/// Registers a prototype to be available for spawning.
@@ -109,11 +110,12 @@ namespace Robust.Shared.Interfaces.GameObjects
/// Gets a new component instantiated of the specified <see cref="IComponent.Name"/>.
/// </summary>
/// <param name="componentName">name of component to make</param>
/// <param name="ignoreCase">Whether or not to ignore casing on <see cref="componentName"/></param>
/// <returns>A Component</returns>
/// <exception cref="UnknownComponentException">
/// Thrown if no component exists with the given name <see cref="componentName"/>.
/// </exception>
IComponent GetComponent(string componentName);
IComponent GetComponent(string componentName, bool ignoreCase = false);
/// <summary>
/// Gets a new component instantiated of the specified network ID.
@@ -129,10 +131,11 @@ namespace Robust.Shared.Interfaces.GameObjects
/// Gets the registration belonging to a component, throwing an exception if it does not exist.
/// </summary>
/// <param name="componentName">The name of the component.</param>
/// <param name="ignoreCase">Whether or not to ignore casing on <see cref="componentName"/></param>
/// <exception cref="UnknownComponentException">
/// Thrown if no component exists with the given name <see cref="componentName"/>.
/// </exception>
IComponentRegistration GetRegistration(string componentName);
IComponentRegistration GetRegistration(string componentName, bool ignoreCase = false);
/// <summary>
/// Gets the registration belonging to a component, throwing an exception if it does not exist.
@@ -179,8 +182,9 @@ namespace Robust.Shared.Interfaces.GameObjects
/// </summary>
/// <param name="componentName">The name of the component.</param>
/// <param name="registration">The registration if found, null otherwise.</param>
/// <param name="ignoreCase">Whether or not to ignore casing on <see cref="componentName"/></param>
/// <returns>true it found, false otherwise.</returns>
bool TryGetRegistration(string componentName, [NotNullWhen(true)] out IComponentRegistration? registration);
bool TryGetRegistration(string componentName, [NotNullWhen(true)] out IComponentRegistration? registration, bool ignoreCase = false);
/// <summary>
/// Tries to get the registration belonging to a component.

View File

@@ -1,3 +1,4 @@
using Robust.Shared.Analyzers;
using Robust.Shared.Serialization;
namespace Robust.Shared.Interfaces.Serialization
@@ -5,6 +6,7 @@ namespace Robust.Shared.Interfaces.Serialization
/// <summary>
/// Interface for the "expose data" system, which is basically our method of handling data serialization.
/// </summary>
[RequiresExplicitImplementation]
public interface IExposeData
{
/// <summary>

View File

@@ -6,7 +6,7 @@ using Serilog.Events;
namespace Robust.Shared.Log
{
public sealed class FileLogHandler : ILogHandler, IDisposable
internal sealed class FileLogHandler : ILogHandler, IDisposable
{
private readonly TextWriter writer;

View File

@@ -1,5 +1,6 @@
using System;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
@@ -83,7 +84,7 @@ namespace Robust.Shared.Map
}
/// <inheritdoc />
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _gridId, "grid", GridId.Invalid);

View File

@@ -0,0 +1,59 @@
using System;
using System.Diagnostics.CodeAnalysis;
namespace Robust.Shared.Network
{
// Basically turbo-lightweight IConfigurationManager for the purposes of auth var loading from env.
/// <summary>
/// Stores client authentication parameters.
/// </summary>
internal interface IAuthManager
{
NetUserId? UserId { get; set; }
string? Server { get; set; }
string? Token { get; set; }
string? PubKey { get; set; }
void LoadFromEnv();
}
internal sealed class AuthManager : IAuthManager
{
public const string DefaultAuthServer = "https://central.spacestation14.io/auth/";
public NetUserId? UserId { get; set; }
public string? Server { get; set; } = DefaultAuthServer;
public string? Token { get; set; }
public string? PubKey { get; set; }
public void LoadFromEnv()
{
if (TryGetVar("ROBUST_AUTH_SERVER", out var server))
{
Server = server;
}
if (TryGetVar("ROBUST_AUTH_USERID", out var userId))
{
UserId = new NetUserId(Guid.Parse(userId));
}
if (TryGetVar("ROBUST_AUTH_PUBKEY", out var pubKey))
{
PubKey = pubKey;
}
if (TryGetVar("ROBUST_AUTH_TOKEN", out var token))
{
Token = token;
}
static bool TryGetVar(string var, [NotNullWhen(true)] out string? val)
{
val = Environment.GetEnvironmentVariable(var);
return val != null;
}
}
}
}

View File

@@ -122,10 +122,10 @@ namespace Robust.Shared.Network
private async Task CCDoHandshake(NetPeerData peer, NetConnection connection, string userNameRequest,
CancellationToken cancel)
{
var authToken = _config.GetSecureCVar<string>("auth.token");
var pubKey = _config.GetSecureCVar<string>("auth.serverpubkey");
var authServer = _config.GetSecureCVar<string>("auth.server");
var userIdStr = _config.GetSecureCVar<string>("auth.userid");
var authToken = _authManager.Token;
var pubKey = _authManager.PubKey;
var authServer = _authManager.Server;
var userId = _authManager.UserId;
var hasPubKey = !string.IsNullOrEmpty(pubKey);
var authenticate = !string.IsNullOrEmpty(authToken);
@@ -160,7 +160,7 @@ namespace Robust.Shared.Network
if (hasPubKey)
{
// public key provided by launcher.
keyBytes = Convert.FromBase64String(pubKey);
keyBytes = Convert.FromBase64String(pubKey!);
}
else
{
@@ -190,7 +190,7 @@ namespace Robust.Shared.Network
{
SharedSecret = encryptedSecret,
VerifyToken = encryptedVerifyToken,
UserId = new Guid(userIdStr)
UserId = userId!.Value.UserId
};
var outEncRespMsg = peer.Peer.CreateMessage();

View File

@@ -51,8 +51,7 @@ namespace Robust.Shared.Network
var isLocal = IPAddress.IsLoopback(ip) && _config.GetCVar(CVars.AuthAllowLocal);
var canAuth = msgLogin.CanAuth;
var needPk = msgLogin.NeedPubKey;
var authServer = _config.GetSecureCVar<string>("auth.server");
var authServer = _config.GetCVar(CVars.AuthServer);
if (Auth == AuthMode.Required && !isLocal)
{

View File

@@ -111,6 +111,7 @@ namespace Robust.Shared.Network
private readonly Dictionary<Type, long> _bandwidthUsage = new();
[Dependency] private readonly IConfigurationManagerInternal _config = default!;
[Dependency] private readonly IAuthManager _authManager = default!;
/// <summary>
/// Holds lookup table for NetMessage.Id -> NetMessage.Type

View File

@@ -18,6 +18,8 @@
* 3. This notice may not be removed or altered from any source distribution.
*/
// #define DEBUG_DYNAMIC_TREE
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -268,6 +270,9 @@ namespace Robust.Shared.Physics
/// </summary>
public Proxy CreateProxy(in Box2 aabb, T userData)
{
// Also catches NaN fuckery.
Assert(aabb.Right >= aabb.Left && aabb.Top >= aabb.Bottom);
ref var proxy = ref AllocateNode(out var proxyId);
// Fatten the aabb.
@@ -292,6 +297,8 @@ namespace Robust.Shared.Physics
public bool MoveProxy(Proxy proxy, in Box2 aabb, Vector2 displacement)
{
Assert(0 <= proxy && proxy < Capacity);
// Also catches NaN fuckery.
Assert(aabb.Right >= aabb.Left && aabb.Top >= aabb.Bottom);
ref var leafNode = ref _nodes[proxy];

View File

@@ -71,7 +71,7 @@ namespace Robust.Shared.Physics
private readonly ExtractAabbDelegate _extractAabb;
// avoids "Collection was modified; enumeration operation may not execute."
private IDictionary<T, Proxy> _nodeLookup;
private Dictionary<T, Proxy> _nodeLookup;
private readonly B2DynamicTree<T> _b2Tree;
public DynamicTree(ExtractAabbDelegate extractAabbFunc, IEqualityComparer<T>? comparer = null, float aabbExtendSize = 1f / 32, int capacity = 256, Func<int, int>? growthFunc = null)
@@ -134,6 +134,12 @@ namespace Robust.Shared.Physics
var box = _extractAabb(item);
if (CheckNaNs(box))
{
_nodeLookup[item] = Proxy.Free;
return true;
}
proxy = _b2Tree.CreateProxy(box, item);
_nodeLookup[item] = proxy;
@@ -162,7 +168,11 @@ namespace Robust.Shared.Physics
return false;
}
_b2Tree.DestroyProxy(proxy);
if (proxy != Proxy.Free)
{
_b2Tree.DestroyProxy(proxy);
}
return true;
}
@@ -178,6 +188,25 @@ namespace Robust.Shared.Physics
}
var newBox = _extractAabb(item);
if (CheckNaNs(newBox))
{
if (proxy == Proxy.Free)
{
return false;
}
_b2Tree.DestroyProxy(proxy);
_nodeLookup[item] = Proxy.Free;
return true;
}
if (proxy == Proxy.Free)
{
_nodeLookup[item] = _b2Tree.CreateProxy(newBox, item);
return true;
}
return _b2Tree.MoveProxy(proxy, newBox, Vector2.Zero);
}
@@ -304,6 +333,14 @@ namespace Robust.Shared.Physics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AddOrUpdate(T item) => Update(item) || Add(item);
private static bool CheckNaNs(in Box2 box)
{
return float.IsNaN(box.Left)
|| float.IsNaN(box.Top)
|| float.IsNaN(box.Bottom)
|| float.IsNaN(box.Right);
}
[Conditional("DEBUG_DYNAMIC_TREE")]
[Conditional("DEBUG_DYNAMIC_TREE_ASSERTS")]
[DebuggerNonUserCode]

View File

@@ -1,4 +1,5 @@
using System;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
@@ -80,7 +81,7 @@ namespace Robust.Shared.Physics
}
/// <inheritdoc />
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _collisionLayer, "layer", 0, WithFormat.Flags<CollisionLayer>());
serializer.DataField(ref _collisionMask, "mask", 0, WithFormat.Flags<CollisionMask>());

View File

@@ -1,4 +1,5 @@
using System;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
@@ -61,7 +62,7 @@ namespace Robust.Shared.Physics
}
/// <inheritdoc />
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _collisionLayer, "layer", 0, WithFormat.Flags<CollisionLayer>());
serializer.DataField(ref _collisionMask, "mask", 0, WithFormat.Flags<CollisionMask>());

View File

@@ -1,4 +1,5 @@
using System;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
@@ -64,7 +65,7 @@ namespace Robust.Shared.Physics
handle.SetTransform(Matrix3.Identity);
}
public void ExposeData(ObjectSerializer serializer)
void IExposeData.ExposeData(ObjectSerializer serializer)
{
serializer.DataField(ref _collisionLayer, "layer", 0, WithFormat.Flags<CollisionLayer>());
serializer.DataField(ref _collisionMask, "mask", 0, WithFormat.Flags<CollisionMask>());

View File

@@ -5,7 +5,6 @@ using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using Robust.Shared.ContentPack;
using Robust.Shared.Interfaces.Reflection;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.IoC;
@@ -546,6 +545,33 @@ namespace Robust.Shared.Serialization
return newSet;
}
// KeyValuePair<K, V>
if (TryGenericKeyValuePairType(type, out var kvpKeyType, out var kvpValType))
{
var pairType = typeof(KeyValuePair<,>).MakeGenericType(kvpKeyType, kvpValType);
var pairNode = (YamlMappingNode) node;
switch (pairNode.Children.Count)
{
case 0:
return Activator.CreateInstance(pairType)!;
case 1:
{
using var enumerator = pairNode.GetEnumerator();
enumerator.MoveNext();
var yamlPair = enumerator.Current;
var keyValue = NodeToType(kvpKeyType, yamlPair.Key);
var valValue = NodeToType(kvpValType, yamlPair.Value);
var pair = Activator.CreateInstance(pairType, keyValue, valValue)!;
return pair;
}
default:
throw new InvalidOperationException(
$"Cannot read KeyValuePair from mapping node with more than one child.");
}
}
// Hand it to the context.
if (_context != null && _context.TryNodeToType(node, type, out var contextObj))
{
@@ -749,6 +775,21 @@ namespace Robust.Shared.Serialization
return node;
}
if (TryGenericKeyValuePairType(type, out var kvpKeyType, out var kvpValType))
{
var node = new YamlMappingNode {Tag = TagSkipTag};
dynamic pair = obj;
var keyNode = TypeToNode(pair.Key);
var valNode = TypeToNode(pair.Value);
// write the concrete type tag
AssignTag<object?>(kvpValType, pair, null, valNode);
node.Add(keyNode, valNode);
return node;
}
// Hand it to the context.
if (_context != null && _context.TryTypeToNode(obj, out var contextNode))
{
@@ -896,6 +937,24 @@ namespace Robust.Shared.Serialization
return true;
}
if (TryGenericKeyValuePairType(type!, out _, out _))
{
dynamic tupleA = a;
dynamic tupleB = b!;
if (!IsSerializedEqual(tupleA.Key, tupleB.Key))
{
return false;
}
if (!IsSerializedEqual(tupleA.Value, tupleB.Value))
{
return false;
}
return true;
}
if (typeof(IExposeData).IsAssignableFrom(type))
{
// Serialize both, see if output matches.
@@ -1035,6 +1094,27 @@ namespace Robust.Shared.Serialization
return false;
}
private static bool TryGenericKeyValuePairType(
Type type,
[NotNullWhen(true)] out Type? keyType,
[NotNullWhen(true)] out Type? valType)
{
var isPair = type.GetTypeInfo().IsGenericType &&
type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>);
if (isPair)
{
var genArgs = type.GetGenericArguments();
keyType = genArgs[0];
valType = genArgs[1];
return true;
}
keyType = default;
valType = default;
return false;
}
public abstract class TypeSerializer
{
public abstract object NodeToType(Type type, YamlNode node, YamlObjectSerializer serializer);

View File

@@ -1,23 +0,0 @@
using NUnit.Framework;
using Robust.Shared.Configuration;
namespace Robust.UnitTesting.Shared.Configuration
{
internal sealed class ConfigurationManagerTest
{
[Test]
public void TestSecureCVar()
{
var cfg = new ConfigurationManager();
cfg.RegisterCVar("auth.token", "honk", CVar.SECURE);
Assert.That(() => cfg.GetCVar<string>("auth.token"), Throws.TypeOf<InvalidConfigurationException>());
Assert.That(() => cfg.GetCVarType("auth.token"), Throws.TypeOf<InvalidConfigurationException>());
Assert.That(() => cfg.SetCVar("auth.token", "foo"), Throws.TypeOf<InvalidConfigurationException>());
Assert.That(cfg.GetSecureCVar<string>("auth.token"), Is.EqualTo("honk"));
Assert.That(cfg.IsCVarRegistered("auth.token"), Is.False);
Assert.That(cfg.GetRegisteredCVars(), Does.Not.Contain("auth.token"));
}
}
}

View File

@@ -0,0 +1,118 @@
using NUnit.Framework;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Reflection;
// ReSharper disable AccessToStaticMemberViaDerivedType
namespace Robust.UnitTesting.Shared.GameObjects
{
[TestFixture]
[TestOf(typeof(ComponentFactory))]
public class ComponentFactory_Tests : RobustUnitTest
{
private const string TestComponentName = "A";
private const string LowercaseTestComponentName = "a";
private const string NonexistentComponentName = "B";
[OneTimeSetUp]
public void OneTimeSetUp()
{
IoCManager.Resolve<IComponentFactory>().Register<TestComponent>();
}
[Test]
public void GetComponentAvailabilityTest()
{
var componentFactory = IoCManager.Resolve<IComponentFactory>();
// Should not exist
Assert.That(componentFactory.GetComponentAvailability(NonexistentComponentName), Is.EqualTo(ComponentAvailability.Unknown));
Assert.That(componentFactory.GetComponentAvailability(NonexistentComponentName, true), Is.EqualTo(ComponentAvailability.Unknown));
// Normal casing, do not ignore case, should exist
Assert.That(componentFactory.GetComponentAvailability(TestComponentName), Is.EqualTo(ComponentAvailability.Available));
// Normal casing, ignore case, should exist
Assert.That(componentFactory.GetComponentAvailability(TestComponentName, true), Is.EqualTo(ComponentAvailability.Available));
// Lower casing, do not ignore case, should not exist
Assert.That(componentFactory.GetComponentAvailability(LowercaseTestComponentName), Is.EqualTo(ComponentAvailability.Unknown));
// Lower casing, ignore case, should exist
Assert.That(componentFactory.GetComponentAvailability(LowercaseTestComponentName, true), Is.EqualTo(ComponentAvailability.Available));
}
[Test]
public void GetComponentTest()
{
var componentFactory = IoCManager.Resolve<IComponentFactory>();
// Should not exist
Assert.Throws<UnknownComponentException>(() => componentFactory.GetComponent(NonexistentComponentName));
Assert.Throws<UnknownComponentException>(() => componentFactory.GetComponent(NonexistentComponentName, true));
// Normal casing, do not ignore case, should exist
Assert.IsInstanceOf<TestComponent>(componentFactory.GetComponent(TestComponentName));
// Normal casing, ignore case, should exist
Assert.IsInstanceOf<TestComponent>(componentFactory.GetComponent(TestComponentName, true));
// Lower casing, do not ignore case, should not exist
Assert.Throws<UnknownComponentException>(() => componentFactory.GetComponent(LowercaseTestComponentName));
// Lower casing, ignore case, should exist
Assert.IsInstanceOf<TestComponent>(componentFactory.GetComponent(LowercaseTestComponentName, true));
}
[Test]
public void GetRegistrationTest()
{
var componentFactory = IoCManager.Resolve<IComponentFactory>();
// Should not exist
Assert.Throws<UnknownComponentException>(() => componentFactory.GetRegistration(NonexistentComponentName));
Assert.Throws<UnknownComponentException>(() => componentFactory.GetRegistration(NonexistentComponentName, true));
// Normal casing, do not ignore case, should exist
Assert.DoesNotThrow(() => componentFactory.GetRegistration(TestComponentName));
// Normal casing, ignore case, should exist
Assert.DoesNotThrow(() => componentFactory.GetRegistration(TestComponentName, true));
// Lower casing, do not ignore case, should not exist
Assert.Throws<UnknownComponentException>(() => componentFactory.GetRegistration(LowercaseTestComponentName));
// Lower casing, ignore case, should exist
Assert.DoesNotThrow(() => componentFactory.GetRegistration(LowercaseTestComponentName, true));
}
[Test]
public void TryGetRegistrationTest()
{
var componentFactory = IoCManager.Resolve<IComponentFactory>();
// Should not exist
Assert.False(componentFactory.TryGetRegistration(NonexistentComponentName, out _));
Assert.False(componentFactory.TryGetRegistration(NonexistentComponentName, out _, true));
// Normal casing, do not ignore case, should exist
Assert.True(componentFactory.TryGetRegistration(TestComponentName, out _));
// Normal casing, ignore case, should exist
Assert.True(componentFactory.TryGetRegistration(TestComponentName, out _, true));
// Lower casing, do not ignore case, should not exist
Assert.False(componentFactory.TryGetRegistration(LowercaseTestComponentName, out _));
// Lower casing, ignore case, should exist
Assert.True(componentFactory.TryGetRegistration(LowercaseTestComponentName, out _, true));
}
private class TestComponent : Component
{
public override string Name => TestComponentName;
}
}
}

View File

@@ -3,15 +3,13 @@ using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Moq;
using NUnit.Framework;
using Robust.Shared.ContentPack;
using Robust.Shared.Interfaces.Serialization;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Serialization;
using Robust.Shared.Utility;
using YamlDotNet.RepresentationModel;
// ReSharper disable AccessToStaticMemberViaDerivedType
namespace Robust.UnitTesting.Shared.Serialization
{
@@ -327,6 +325,103 @@ namespace Robust.UnitTesting.Shared.Serialization
private readonly string SerializedSetYaml = "dataSet:\n- 1\n- 2\n- 3\n...\n";
private readonly HashSet<int> SerializableSet = new() { 1, 2, 3 };
[Test]
public void SerializePairTest()
{
var mapping = new YamlMappingNode();
var pair = SerializablePair;
var writer = YamlObjectSerializer.NewWriter(mapping);
writer.DataField(ref pair, "dataPair", new KeyValuePair<string, int>("val0", 0));
var result = NodeToYamlText(mapping);
Assert.That(result, Is.EqualTo(SerializedPairYaml));
}
[Test]
public void DeserializePairTest()
{
KeyValuePair<string, int> data = default;
var rootNode = YamlTextToNode(SerializedPairYaml);
var serializer = YamlObjectSerializer.NewReader(rootNode);
serializer.DataField(ref data, "dataPair", new KeyValuePair<string, int>("val0", 0));
Assert.That(data, Is.Not.EqualTo(default(KeyValuePair<string, int>)));
Assert.That(data.Key, Is.EqualTo(SerializablePair.Key));
Assert.That(data.Value, Is.EqualTo(SerializablePair.Value));
}
[Test]
public void SerializeDefaultPairTest()
{
var mapping = new YamlMappingNode();
var pair = SerializableDefaultPair;
var writer = YamlObjectSerializer.NewWriter(mapping);
writer.DataField(ref pair, "dataPair", new KeyValuePair<int, int>(0, 0));
var result = NodeToYamlText(mapping);
Assert.That(result, Is.EqualTo(SerializedDefaultPairYaml));
}
[Test]
public void DeserializeDefaultPairTest()
{
KeyValuePair<int, int> data = default;
var rootNode = YamlTextToNode(SerializedDefaultPairYaml);
var serializer = YamlObjectSerializer.NewReader(rootNode);
serializer.DataField(ref data, "dataPair", new KeyValuePair<int, int>(0, 0));
Assert.That(data, Is.EqualTo(default(KeyValuePair<int, int>)));
Assert.That(data.Key, Is.EqualTo(SerializableDefaultPair.Key));
Assert.That(data.Value, Is.EqualTo(SerializableDefaultPair.Value));
}
[Test]
public void DeserializeNoPairTest()
{
KeyValuePair<int, int> data = default;
var rootNode = YamlTextToNode(SerializedNoPairYaml);
var serializer = YamlObjectSerializer.NewReader(rootNode);
serializer.DataField(ref data, "dataPair", new KeyValuePair<int, int>(0, 0));
Assert.That(data, Is.EqualTo(default(KeyValuePair<int, int>)));
Assert.That(data.Key, Is.EqualTo(SerializedNoPair.Key));
Assert.That(data.Value, Is.EqualTo(SerializedNoPair.Value));
}
[Test]
public void SerializedEqualPairTest()
{
var pair = new KeyValuePair<string, int>("val0", 0);
var pair2 = new KeyValuePair<string, int>("val0", 0);
Assert.That(YamlObjectSerializer.IsSerializedEqual(pair, pair2), Is.True);
}
[Test]
public void SerializedNotEqualPairTest()
{
var pair = new KeyValuePair<string, int>("val0", 0);
var pair2 = new KeyValuePair<string, int>("val0", 1);
Assert.That(YamlObjectSerializer.IsSerializedEqual(pair, pair2), Is.False);
}
private readonly string SerializedPairYaml = "dataPair:\n val1: 1\n...\n";
private readonly KeyValuePair<string, int> SerializablePair = new("val1", 1);
private readonly string SerializedDefaultPairYaml = "{}\n...\n";
private readonly KeyValuePair<int, int> SerializableDefaultPair = new(0, 0);
private readonly string SerializedNoPairYaml = "dataPair: {}\n...\n";
private readonly KeyValuePair<int, int> SerializedNoPair = new(0, 0);
[Test]
public void NullablePrimitiveSerializeNullTest()
{

View File

@@ -32,6 +32,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ManagedHttpListener", "ManagedHttpListener", "{15D28C35-25F6-4EA8-8D53-29DA7C8A24A7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.HttpListener", "ManagedHttpListener\src\System.Net.HttpListener.csproj", "{C3EB43AF-31FD-48F5-A4FB-552D0F13948B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Robust.Client.Injectors", "Robust.Client.Injectors\Robust.Client.Injectors.csproj", "{EEF2C805-5E03-41EA-A916-49C1DD15EF41}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Robust.Client.NameGenerator", "Robust.Client.NameGenerator\Robust.Client.NameGenerator.csproj", "{EFB7A05D-71D0-47D1-B7B4-35D4FF661F13}"
@@ -44,6 +45,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XamlX.IL.Cecil", "XamlX\src
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XamlX.Runtime", "XamlX\src\XamlX.Runtime\XamlX.Runtime.csproj", "{B05EFB71-AEC7-4C6E-984A-A1BCC58F9AD1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Robust.Analyzers", "Robust.Analyzers\Robust.Analyzers.csproj", "{3173712A-9E75-4685-B657-9AF9B7D54EFB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -188,6 +191,14 @@ Global
{B05EFB71-AEC7-4C6E-984A-A1BCC58F9AD1}.Release|Any CPU.Build.0 = Release|Any CPU
{B05EFB71-AEC7-4C6E-984A-A1BCC58F9AD1}.Release|x64.ActiveCfg = Release|Any CPU
{B05EFB71-AEC7-4C6E-984A-A1BCC58F9AD1}.Release|x64.Build.0 = Release|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Debug|x64.ActiveCfg = Debug|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Debug|x64.Build.0 = Debug|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Release|Any CPU.Build.0 = Release|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Release|x64.ActiveCfg = Release|Any CPU
{3173712A-9E75-4685-B657-9AF9B7D54EFB}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE