Fix RCS1118

This commit is contained in:
RoosterDragon
2023-03-18 12:58:22 +00:00
committed by Gustas
parent eb287d9b8d
commit fbe147ce61
11 changed files with 115 additions and 107 deletions

View File

@@ -1028,6 +1028,9 @@ dotnet_diagnostic.RCS1112.severity = warning
# Use 'string.IsNullOrEmpty' method. # Use 'string.IsNullOrEmpty' method.
dotnet_diagnostic.RCS1113.severity = warning dotnet_diagnostic.RCS1113.severity = warning
# Mark local variable as const.
dotnet_diagnostic.RCS1118.severity = warning
# Bitwise operation on enum without Flags attribute. # Bitwise operation on enum without Flags attribute.
dotnet_diagnostic.RCS1130.severity = warning dotnet_diagnostic.RCS1130.severity = warning

View File

@@ -42,11 +42,11 @@ namespace OpenRA.Graphics
// in rendering a line of texels that sample outside the sprite rectangle. // in rendering a line of texels that sample outside the sprite rectangle.
// Insetting the texture coordinates by a small fraction of a pixel avoids this // Insetting the texture coordinates by a small fraction of a pixel avoids this
// with negligible impact on the 1:1 rendering case. // with negligible impact on the 1:1 rendering case.
var inset = 1 / 128f; const float Inset = 1 / 128f;
Left = (Math.Min(bounds.Left, bounds.Right) + inset) / sheet.Size.Width; Left = (Math.Min(bounds.Left, bounds.Right) + Inset) / sheet.Size.Width;
Top = (Math.Min(bounds.Top, bounds.Bottom) + inset) / sheet.Size.Height; Top = (Math.Min(bounds.Top, bounds.Bottom) + Inset) / sheet.Size.Height;
Right = (Math.Max(bounds.Left, bounds.Right) - inset) / sheet.Size.Width; Right = (Math.Max(bounds.Left, bounds.Right) - Inset) / sheet.Size.Width;
Bottom = (Math.Max(bounds.Top, bounds.Bottom) - inset) / sheet.Size.Height; Bottom = (Math.Max(bounds.Top, bounds.Bottom) - Inset) / sheet.Size.Height;
} }
} }

View File

@@ -685,16 +685,16 @@ namespace OpenRA
writer.Write((ushort)MapSize.Y); writer.Write((ushort)MapSize.Y);
// Data offsets // Data offsets
var tilesOffset = 17; const int TilesOffset = 17;
var heightsOffset = Grid.MaximumTerrainHeight > 0 ? 3 * MapSize.X * MapSize.Y + 17 : 0; var heightsOffset = Grid.MaximumTerrainHeight > 0 ? 3 * MapSize.X * MapSize.Y + 17 : 0;
var resourcesOffset = (Grid.MaximumTerrainHeight > 0 ? 4 : 3) * MapSize.X * MapSize.Y + 17; var resourcesOffset = (Grid.MaximumTerrainHeight > 0 ? 4 : 3) * MapSize.X * MapSize.Y + 17;
writer.Write((uint)tilesOffset); writer.Write((uint)TilesOffset);
writer.Write((uint)heightsOffset); writer.Write((uint)heightsOffset);
writer.Write((uint)resourcesOffset); writer.Write((uint)resourcesOffset);
// Tile data // Tile data
if (tilesOffset != 0) if (TilesOffset != 0)
{ {
for (var i = 0; i < MapSize.X; i++) for (var i = 0; i < MapSize.X; i++)
{ {
@@ -805,7 +805,7 @@ namespace OpenRA
bitmapWidth = 2 * bitmapWidth - 1; bitmapWidth = 2 * bitmapWidth - 1;
var stride = bitmapWidth * 4; var stride = bitmapWidth * 4;
var pxStride = 4; const int PxStride = 4;
var minimapData = new byte[stride * height]; var minimapData = new byte[stride * height];
(Color Left, Color Right) terrainColor = default; (Color Left, Color Right) terrainColor = default;
@@ -827,10 +827,10 @@ namespace OpenRA
{ {
// Odd rows are shifted right by 1px // Odd rows are shifted right by 1px
var dx = uv.V & 1; var dx = uv.V & 1;
var xOffset = pxStride * (2 * x + dx); var xOffset = PxStride * (2 * x + dx);
if (x + dx > 0) if (x + dx > 0)
{ {
var z = y * stride + xOffset - pxStride; var z = y * stride + xOffset - PxStride;
var c = actorColor.A == 0 ? terrainColor.Left : actorColor; var c = actorColor.A == 0 ? terrainColor.Left : actorColor;
minimapData[z++] = c.R; minimapData[z++] = c.R;
minimapData[z++] = c.G; minimapData[z++] = c.G;
@@ -850,7 +850,7 @@ namespace OpenRA
} }
else else
{ {
var z = y * stride + pxStride * x; var z = y * stride + PxStride * x;
var c = actorColor.A == 0 ? terrainColor.Left : actorColor; var c = actorColor.A == 0 ? terrainColor.Left : actorColor;
minimapData[z++] = c.R; minimapData[z++] = c.R;
minimapData[z++] = c.G; minimapData[z++] = c.G;

View File

@@ -282,11 +282,11 @@ namespace OpenRA
Log.Write("debug", "MapCache.LoadAsyncInternal started"); Log.Write("debug", "MapCache.LoadAsyncInternal started");
// Milliseconds to wait on one loop when nothing to do // Milliseconds to wait on one loop when nothing to do
var emptyDelay = 50; const int EmptyDelay = 50;
// Keep the thread alive for at least 5 seconds after the last minimap generation // Keep the thread alive for at least 5 seconds after the last minimap generation
var maxKeepAlive = 5000 / emptyDelay; const int MaxKeepAlive = 5000 / EmptyDelay;
var keepAlive = maxKeepAlive; var keepAlive = MaxKeepAlive;
while (true) while (true)
{ {
@@ -306,11 +306,11 @@ namespace OpenRA
if (todo.Count == 0) if (todo.Count == 0)
{ {
Thread.Sleep(emptyDelay); Thread.Sleep(EmptyDelay);
continue; continue;
} }
else else
keepAlive = maxKeepAlive; keepAlive = MaxKeepAlive;
// Render the minimap into the shared sheet // Render the minimap into the shared sheet
foreach (var p in todo) foreach (var p in todo)

View File

@@ -133,8 +133,8 @@ namespace OpenRA
public ConstructorInfo GetCtor(Type type) public ConstructorInfo GetCtor(Type type)
{ {
var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance; const BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
var ctors = type.GetConstructors(flags).Where(x => x.HasAttribute<UseCtorAttribute>()).ToList(); var ctors = type.GetConstructors(Flags).Where(x => x.HasAttribute<UseCtorAttribute>()).ToList();
if (ctors.Count > 1) if (ctors.Count > 1)
throw new InvalidOperationException("ObjectCreator: UseCtor on multiple constructors; invalid."); throw new InvalidOperationException("ObjectCreator: UseCtor on multiple constructors; invalid.");
return ctors.FirstOrDefault(); return ctors.FirstOrDefault();

View File

@@ -125,8 +125,8 @@ namespace OpenRA.Scripting
public static IEnumerable<MemberInfo> WrappableMembers(Type t) public static IEnumerable<MemberInfo> WrappableMembers(Type t)
{ {
// Only expose defined public non-static methods that were explicitly declared by the author // Only expose defined public non-static methods that were explicitly declared by the author
var flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; const BindingFlags Flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
foreach (var mi in t.GetMembers(flags)) foreach (var mi in t.GetMembers(Flags))
{ {
// Properties are always wrappable // Properties are always wrappable
if (mi is PropertyInfo) if (mi is PropertyInfo)

View File

@@ -876,13 +876,13 @@ namespace OpenRA.Server
public void DispatchServerOrdersToClients(byte[] data, int frame = 0) public void DispatchServerOrdersToClients(byte[] data, int frame = 0)
{ {
var from = 0; const int From = 0;
var frameData = CreateFrame(from, frame, data); var frameData = CreateFrame(From, frame, data);
foreach (var c in Conns.ToList()) foreach (var c in Conns.ToList())
if (c.Validated) if (c.Validated)
DispatchFrameToClient(c, from, frameData); DispatchFrameToClient(c, From, frameData);
RecordOrder(frame, data, from); RecordOrder(frame, data, From);
} }
public void ReceiveOrders(Connection conn, int frame, byte[] data) public void ReceiveOrders(Connection conn, int frame, byte[] data)

View File

@@ -70,40 +70,40 @@ namespace OpenRA.Mods.Common.Lint
return; return;
// TODO: Check all available languages. // TODO: Check all available languages.
var language = "en"; const string Language = "en";
var modTranslation = new Translation(language, modData.Manifest.Translations, modData.DefaultFileSystem, _ => { }); var modTranslation = new Translation(Language, modData.Manifest.Translations, modData.DefaultFileSystem, _ => { });
var mapTranslation = new Translation(language, FieldLoader.GetValue<string[]>("value", map.TranslationDefinitions.Value), map, error => emitError(error.ToString())); var mapTranslation = new Translation(Language, FieldLoader.GetValue<string[]>("value", map.TranslationDefinitions.Value), map, error => emitError(error.ToString()));
TestTraits(map.Rules, emitError, key => TestTraits(map.Rules, emitError, key =>
{ {
if (modTranslation.HasMessage(key)) if (modTranslation.HasMessage(key))
{ {
if (mapTranslation.HasMessage(key)) if (mapTranslation.HasMessage(key))
emitWarning($"Map translation key `{key}` already exists in `{language}` mod translations and will not be used."); emitWarning($"Map translation key `{key}` already exists in `{Language}` mod translations and will not be used.");
} }
else if (!mapTranslation.HasMessage(key)) else if (!mapTranslation.HasMessage(key))
emitWarning($"`{key}` is not present in `{language}` translation."); emitWarning($"`{key}` is not present in `{Language}` translation.");
}); });
} }
void ILintPass.Run(Action<string> emitError, Action<string> emitWarning, ModData modData) void ILintPass.Run(Action<string> emitError, Action<string> emitWarning, ModData modData)
{ {
// TODO: Check all available languages. // TODO: Check all available languages.
var language = "en"; const string Language = "en";
Console.WriteLine($"Testing translation: {language}"); Console.WriteLine($"Testing translation: {Language}");
var translation = new Translation(language, modData.Manifest.Translations, modData.DefaultFileSystem, error => emitError(error.ToString())); var translation = new Translation(Language, modData.Manifest.Translations, modData.DefaultFileSystem, error => emitError(error.ToString()));
TestTraits(modData.DefaultRules, emitError, key => TestTraits(modData.DefaultRules, emitError, key =>
{ {
if (!translation.HasMessage(key)) if (!translation.HasMessage(key))
emitWarning($"`{key}` is not present in `{language}` translation."); emitWarning($"`{key}` is not present in `{Language}` translation.");
}); });
var gameSpeeds = modData.Manifest.Get<GameSpeeds>(); var gameSpeeds = modData.Manifest.Get<GameSpeeds>();
foreach (var speed in gameSpeeds.Speeds.Values) foreach (var speed in gameSpeeds.Speeds.Values)
{ {
if (!translation.HasMessage(speed.Name)) if (!translation.HasMessage(speed.Name))
emitWarning($"`{speed.Name}` is not present in `{language}` translation."); emitWarning($"`{speed.Name}` is not present in `{Language}` translation.");
referencedKeys.Add(speed.Name); referencedKeys.Add(speed.Name);
} }
@@ -126,7 +126,7 @@ namespace OpenRA.Mods.Common.Lint
continue; continue;
if (!translation.HasMessage(key)) if (!translation.HasMessage(key))
emitWarning($"`{key}` is not present in `{language}` translation."); emitWarning($"`{key}` is not present in `{Language}` translation.");
var translationReference = Utility.GetCustomAttributes<TranslationReferenceAttribute>(fieldInfo, true)[0]; var translationReference = Utility.GetCustomAttributes<TranslationReferenceAttribute>(fieldInfo, true)[0];
if (translationReference.RequiredVariableNames != null && translationReference.RequiredVariableNames.Length > 0) if (translationReference.RequiredVariableNames != null && translationReference.RequiredVariableNames.Length > 0)
@@ -150,7 +150,7 @@ namespace OpenRA.Mods.Common.Lint
{ {
var nodes = MiniYaml.FromStream(modData.DefaultFileSystem.Open(filename)); var nodes = MiniYaml.FromStream(modData.DefaultFileSystem.Open(filename));
foreach (var node in nodes) foreach (var node in nodes)
CheckChrome(node, translation, language, emitError, emitWarning, translatableFields); CheckChrome(node, translation, Language, emitError, emitWarning, translatableFields);
} }
foreach (var file in modData.Manifest.Translations) foreach (var file in modData.Manifest.Translations)

View File

@@ -496,8 +496,8 @@ namespace OpenRA.Mods.Common.Projectiles
lastHt = 0; // Height just before the last height change lastHt = 0; // Height just before the last height change
// NOTE: Might be desired to unhardcode the lookahead step size // NOTE: Might be desired to unhardcode the lookahead step size
var stepSize = 32; const int StepSize = 32;
var step = new WVec(0, -stepSize, 0) var step = new WVec(0, -StepSize, 0)
.Rotate(new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(hFacing))); // Step vector of length 128 .Rotate(new WRot(WAngle.Zero, WAngle.Zero, WAngle.FromFacing(hFacing))); // Step vector of length 128
// Probe terrain ahead of the missile // Probe terrain ahead of the missile
@@ -505,7 +505,7 @@ namespace OpenRA.Mods.Common.Projectiles
var maxLookaheadDistance = loopRadius * 4; var maxLookaheadDistance = loopRadius * 4;
var posProbe = pos; var posProbe = pos;
var curDist = 0; var curDist = 0;
var tickLimit = System.Math.Min(maxLookaheadDistance, distCheck) / stepSize; var tickLimit = System.Math.Min(maxLookaheadDistance, distCheck) / StepSize;
var prevHt = 0; var prevHt = 0;
// TODO: Make sure cell on map!!! // TODO: Make sure cell on map!!!
@@ -517,7 +517,7 @@ namespace OpenRA.Mods.Common.Projectiles
var ht = world.Map.Height[world.Map.CellContaining(posProbe)] * 512; var ht = world.Map.Height[world.Map.CellContaining(posProbe)] * 512;
curDist += stepSize; curDist += StepSize;
if (ht > predClfHgt) if (ht > predClfHgt)
{ {
predClfHgt = ht; predClfHgt = ht;

View File

@@ -224,14 +224,14 @@ namespace OpenRA.Platforms.Default
Console.WriteLine($"Using resolution: {windowSize.Width}x{windowSize.Height}"); Console.WriteLine($"Using resolution: {windowSize.Width}x{windowSize.Height}");
var windowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI; const SDL.SDL_WindowFlags WindowFlags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI;
// HiDPI doesn't work properly on OSX with (legacy) fullscreen mode // HiDPI doesn't work properly on OSX with (legacy) fullscreen mode
if (Platform.CurrentPlatform == PlatformType.OSX && windowMode == WindowMode.Fullscreen) if (Platform.CurrentPlatform == PlatformType.OSX && windowMode == WindowMode.Fullscreen)
SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_HIGHDPI_DISABLED, "1"); SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_HIGHDPI_DISABLED, "1");
window = SDL.SDL_CreateWindow("OpenRA", SDL.SDL_WINDOWPOS_CENTERED_DISPLAY(videoDisplay), SDL.SDL_WINDOWPOS_CENTERED_DISPLAY(videoDisplay), window = SDL.SDL_CreateWindow("OpenRA", SDL.SDL_WINDOWPOS_CENTERED_DISPLAY(videoDisplay), SDL.SDL_WINDOWPOS_CENTERED_DISPLAY(videoDisplay),
windowSize.Width, windowSize.Height, windowFlags); windowSize.Width, windowSize.Height, WindowFlags);
if (Platform.CurrentPlatform == PlatformType.Linux) if (Platform.CurrentPlatform == PlatformType.Linux)
{ {
@@ -551,8 +551,8 @@ namespace OpenRA.Platforms.Default
SetSDLAttributes(profile); SetSDLAttributes(profile);
var flags = SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL; const SDL.SDL_WindowFlags Flags = SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL;
var window = SDL.SDL_CreateWindow("", 0, 0, 1, 1, flags); var window = SDL.SDL_CreateWindow("", 0, 0, 1, 1, Flags);
if (window == IntPtr.Zero || !string.IsNullOrEmpty(SDL.SDL_GetError())) if (window == IntPtr.Zero || !string.IsNullOrEmpty(SDL.SDL_GetError()))
{ {
errorLog.Add($"{profile}: SDL window creation failed: {SDL.SDL_GetError()}"); errorLog.Add($"{profile}: SDL window creation failed: {SDL.SDL_GetError()}");

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Test
[TestCase(TestName = "Parse tree roundtrips")] [TestCase(TestName = "Parse tree roundtrips")]
public void TestParseRoundtrip() public void TestParseRoundtrip()
{ {
var yaml = const string Yaml =
@"1: @"1:
2: Test 2: Test
3: # Test 3: # Test
@@ -44,15 +44,15 @@ namespace OpenRA.Test
9.1.2: Test 9.1.2: Test
9.1.3: # Test 9.1.3: # Test
"; ";
var serialized = MiniYaml.FromString(yaml, discardCommentsAndWhitespace: false).WriteToString(); var serialized = MiniYaml.FromString(Yaml, discardCommentsAndWhitespace: false).WriteToString();
Console.WriteLine(); Console.WriteLine();
Assert.That(serialized, Is.EqualTo(yaml)); Assert.That(serialized, Is.EqualTo(Yaml));
} }
[TestCase(TestName = "Parse tree can handle empty lines")] [TestCase(TestName = "Parse tree can handle empty lines")]
public void TestParseEmptyLines() public void TestParseEmptyLines()
{ {
var yaml = const string Yaml =
@"1: @"1:
2: Test 2: Test
@@ -97,7 +97,7 @@ namespace OpenRA.Test
"; ";
var expectedYaml = const string ExpectedYaml =
@"1: @"1:
2: Test 2: Test
3: 3:
@@ -120,14 +120,14 @@ namespace OpenRA.Test
9.1.2: Test 9.1.2: Test
9.1.3: 9.1.3:
"; ";
var serialized = MiniYaml.FromString(yaml).WriteToString(); var serialized = MiniYaml.FromString(Yaml).WriteToString();
Assert.That(serialized, Is.EqualTo(expectedYaml)); Assert.That(serialized, Is.EqualTo(ExpectedYaml));
} }
[TestCase(TestName = "Mixed tabs & spaces indents")] [TestCase(TestName = "Mixed tabs & spaces indents")]
public void TestIndents() public void TestIndents()
{ {
var yamlTabStyle = @" const string YamlTabStyle = @"
Root1: Root1:
Child1: Child1:
Attribute1: Test Attribute1: Test
@@ -140,7 +140,7 @@ Root2:
Attribute1: Test Attribute1: Test
"; ";
var yamlMixedStyle = @" const string YamlMixedStyle = @"
Root1: Root1:
Child1: Child1:
Attribute1: Test Attribute1: Test
@@ -152,9 +152,9 @@ Root2:
Child1: Child1:
Attribute1: Test Attribute1: Test
"; ";
var tabs = MiniYaml.FromString(yamlTabStyle, "yamlTabStyle").WriteToString(); var tabs = MiniYaml.FromString(YamlTabStyle, "yamlTabStyle").WriteToString();
Console.WriteLine(tabs); Console.WriteLine(tabs);
var mixed = MiniYaml.FromString(yamlMixedStyle, "yamlMixedStyle").WriteToString(); var mixed = MiniYaml.FromString(YamlMixedStyle, "yamlMixedStyle").WriteToString();
Console.WriteLine(mixed); Console.WriteLine(mixed);
Assert.That(tabs, Is.EqualTo(mixed)); Assert.That(tabs, Is.EqualTo(mixed));
} }
@@ -162,25 +162,25 @@ Root2:
[TestCase(TestName = "Inheritance and removal can be composed")] [TestCase(TestName = "Inheritance and removal can be composed")]
public void InheritanceAndRemovalCanBeComposed() public void InheritanceAndRemovalCanBeComposed()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockA2: MockA2:
^BaseB: ^BaseB:
Inherits@a: ^BaseA Inherits@a: ^BaseA
MockB2: MockB2:
"; ";
var extendedYaml = @" const string ExtendedYaml = @"
Test: Test:
Inherits@b: ^BaseB Inherits@b: ^BaseB
-MockA2: -MockA2:
"; ";
var mapYaml = @" const string MapYaml = @"
^BaseC: ^BaseC:
MockC2: MockC2:
Test: Test:
Inherits@c: ^BaseC Inherits@c: ^BaseC
"; ";
var result = MiniYaml.Merge(new[] { baseYaml, extendedYaml, mapYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml, ExtendedYaml, MapYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsFalse(result.Any(n => n.Key == "MockA2"), "Node should not have the MockA2 child, but does."); Assert.IsFalse(result.Any(n => n.Key == "MockA2"), "Node should not have the MockA2 child, but does.");
@@ -191,19 +191,19 @@ Test:
[TestCase(TestName = "Child can be removed after multiple inheritance")] [TestCase(TestName = "Child can be removed after multiple inheritance")]
public void ChildCanBeRemovedAfterMultipleInheritance() public void ChildCanBeRemovedAfterMultipleInheritance()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockA2: MockA2:
Test: Test:
Inherits: ^BaseA Inherits: ^BaseA
MockA2: MockA2:
"; ";
var overrideYaml = @" const string OverrideYaml = @"
Test: Test:
-MockA2 -MockA2
"; ";
var result = MiniYaml.Merge(new[] { baseYaml, overrideYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml, OverrideYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsFalse(result.Any(n => n.Key == "MockA2"), "Node should not have the MockA2 child, but does."); Assert.IsFalse(result.Any(n => n.Key == "MockA2"), "Node should not have the MockA2 child, but does.");
@@ -212,7 +212,7 @@ Test:
[TestCase(TestName = "Child can be immediately removed")] [TestCase(TestName = "Child can be immediately removed")]
public void ChildCanBeImmediatelyRemoved() public void ChildCanBeImmediatelyRemoved()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
AString: Base AString: Base
@@ -223,7 +223,7 @@ Test:
-MockString: -MockString:
"; ";
var result = MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsFalse(result.Any(n => n.Key == "MockString"), "Node should not have the MockString child, but does."); Assert.IsFalse(result.Any(n => n.Key == "MockString"), "Node should not have the MockString child, but does.");
@@ -232,7 +232,7 @@ Test:
[TestCase(TestName = "Child can be removed and immediately overridden")] [TestCase(TestName = "Child can be removed and immediately overridden")]
public void ChildCanBeRemovedAndImmediatelyOverridden() public void ChildCanBeRemovedAndImmediatelyOverridden()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
AString: Base AString: Base
@@ -243,7 +243,7 @@ Test:
AString: Override AString: Override
"; ";
var result = MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not."); Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not.");
@@ -254,7 +254,7 @@ Test:
[TestCase(TestName = "Child can be removed and later overridden")] [TestCase(TestName = "Child can be removed and later overridden")]
public void ChildCanBeRemovedAndLaterOverridden() public void ChildCanBeRemovedAndLaterOverridden()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
AString: Base AString: Base
@@ -262,13 +262,13 @@ Test:
Inherits: ^BaseA Inherits: ^BaseA
-MockString: -MockString:
"; ";
var overrideYaml = @" const string OverrideYaml = @"
Test: Test:
MockString: MockString:
AString: Override AString: Override
"; ";
var result = MiniYaml.Merge(new[] { baseYaml, overrideYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml, OverrideYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not."); Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not.");
@@ -279,7 +279,7 @@ Test:
[TestCase(TestName = "Child can be removed from intermediate parent")] [TestCase(TestName = "Child can be removed from intermediate parent")]
public void ChildCanBeOverriddenThenRemoved() public void ChildCanBeOverriddenThenRemoved()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
AString: Base AString: Base
@@ -288,14 +288,14 @@ Test:
MockString: MockString:
AString: Override AString: Override
"; ";
var overrideYaml = @" const string OverrideYaml = @"
Test: Test:
Inherits: ^BaseB Inherits: ^BaseB
MockString: MockString:
-AString: -AString:
"; ";
var result = MiniYaml.Merge(new[] { baseYaml, overrideYaml }.Select(s => MiniYaml.FromString(s, ""))) var result = MiniYaml.Merge(new[] { BaseYaml, OverrideYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test").Value.Nodes; .First(n => n.Key == "Test").Value.Nodes;
Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not."); Assert.IsTrue(result.Any(n => n.Key == "MockString"), "Node should have the MockString child, but does not.");
Assert.IsFalse(result.First(n => n.Key == "MockString").Value.Nodes.Any(n => n.Key == "AString"), Assert.IsFalse(result.First(n => n.Key == "MockString").Value.Nodes.Any(n => n.Key == "AString"),
@@ -305,7 +305,7 @@ Test:
[TestCase(TestName = "Child subnode can be removed and immediately overridden")] [TestCase(TestName = "Child subnode can be removed and immediately overridden")]
public void ChildSubNodeCanBeRemovedAndImmediatelyOverridden() public void ChildSubNodeCanBeRemovedAndImmediatelyOverridden()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
CollectionOfStrings: CollectionOfStrings:
@@ -319,7 +319,7 @@ Test:
StringC: C StringC: C
"; ";
var merged = MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, ""))) var merged = MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test"); .First(n => n.Key == "Test");
var traitNode = merged.Value.Nodes.Single(); var traitNode = merged.Value.Nodes.Single();
@@ -334,7 +334,7 @@ Test:
[TestCase(TestName = "Child subnode can be removed and later overridden")] [TestCase(TestName = "Child subnode can be removed and later overridden")]
public void ChildSubNodeCanBeRemovedAndLaterOverridden() public void ChildSubNodeCanBeRemovedAndLaterOverridden()
{ {
var baseYaml = @" const string BaseYaml = @"
^BaseA: ^BaseA:
MockString: MockString:
CollectionOfStrings: CollectionOfStrings:
@@ -346,14 +346,14 @@ Test:
-CollectionOfStrings: -CollectionOfStrings:
"; ";
var overrideYaml = @" const string OverrideYaml = @"
Test: Test:
MockString: MockString:
CollectionOfStrings: CollectionOfStrings:
StringC: C StringC: C
"; ";
var merged = MiniYaml.Merge(new[] { baseYaml, overrideYaml }.Select(s => MiniYaml.FromString(s, ""))) var merged = MiniYaml.Merge(new[] { BaseYaml, OverrideYaml }.Select(s => MiniYaml.FromString(s, "")))
.First(n => n.Key == "Test"); .First(n => n.Key == "Test");
var traitNode = merged.Value.Nodes.Single(); var traitNode = merged.Value.Nodes.Single();
@@ -368,7 +368,7 @@ Test:
[TestCase(TestName = "Empty lines should count toward line numbers")] [TestCase(TestName = "Empty lines should count toward line numbers")]
public void EmptyLinesShouldCountTowardLineNumbers() public void EmptyLinesShouldCountTowardLineNumbers()
{ {
var yaml = @" const string Yaml = @"
TestA: TestA:
Nothing: Nothing:
@@ -376,14 +376,14 @@ TestB:
Nothing: Nothing:
"; ";
var result = MiniYaml.FromString(yaml).First(n => n.Key == "TestB"); var result = MiniYaml.FromString(Yaml).First(n => n.Key == "TestB");
Assert.AreEqual(5, result.Location.Line); Assert.AreEqual(5, result.Location.Line);
} }
[TestCase(TestName = "Duplicated nodes are correctly merged")] [TestCase(TestName = "Duplicated nodes are correctly merged")]
public void TestSelfMerging() public void TestSelfMerging()
{ {
var baseYaml = @" const string BaseYaml = @"
Test: Test:
Merge: original Merge: original
Child: original Child: original
@@ -394,7 +394,7 @@ Test:
Override: Override:
"; ";
var result = MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, ""))); var result = MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "")));
Assert.That(result.Count(n => n.Key == "Test"), Is.EqualTo(1), "Result should have exactly one Test node."); Assert.That(result.Count(n => n.Key == "Test"), Is.EqualTo(1), "Result should have exactly one Test node.");
var testNodes = result.First(n => n.Key == "Test").Value.Nodes; var testNodes = result.First(n => n.Key == "Test").Value.Nodes;
@@ -408,13 +408,13 @@ Test:
[TestCase(TestName = "Duplicated nodes across multiple sources are correctly merged")] [TestCase(TestName = "Duplicated nodes across multiple sources are correctly merged")]
public void TestSelfMergingMultiSource() public void TestSelfMergingMultiSource()
{ {
var firstYaml = @" const string FirstYaml = @"
Test: Test:
Merge: original Merge: original
Child: original Child: original
Original: Original:
"; ";
var secondYaml = @" const string SecondYaml = @"
Test: Test:
Merge: original Merge: original
Child: original Child: original
@@ -425,7 +425,7 @@ Test:
Override: Override:
"; ";
var result = MiniYaml.Merge(new[] { firstYaml, secondYaml }.Select(s => MiniYaml.FromString(s, ""))); var result = MiniYaml.Merge(new[] { FirstYaml, SecondYaml }.Select(s => MiniYaml.FromString(s, "")));
Assert.That(result.Count(n => n.Key == "Test"), Is.EqualTo(1), "Result should have exactly one Test node."); Assert.That(result.Count(n => n.Key == "Test"), Is.EqualTo(1), "Result should have exactly one Test node.");
var testNodes = result.First(n => n.Key == "Test").Value.Nodes; var testNodes = result.First(n => n.Key == "Test").Value.Nodes;
@@ -439,14 +439,14 @@ Test:
[TestCase(TestName = "Duplicated child nodes do not throw if parent does not require merging")] [TestCase(TestName = "Duplicated child nodes do not throw if parent does not require merging")]
public void TestMergeConflictsNoMerge() public void TestMergeConflictsNoMerge()
{ {
var baseYaml = @" const string BaseYaml = @"
Test: Test:
Merge: Merge:
Child: Child:
Child: Child:
"; ";
var result = MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, ""))); var result = MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "")));
var testNodes = result.First(n => n.Key == "Test").Value.Nodes; var testNodes = result.First(n => n.Key == "Test").Value.Nodes;
var mergeNode = testNodes.First(n => n.Key == "Merge").Value; var mergeNode = testNodes.First(n => n.Key == "Merge").Value;
Assert.That(mergeNode.Nodes.Count, Is.EqualTo(2)); Assert.That(mergeNode.Nodes.Count, Is.EqualTo(2));
@@ -455,7 +455,7 @@ Test:
[TestCase(TestName = "Duplicated child nodes throw merge error if first parent requires merging")] [TestCase(TestName = "Duplicated child nodes throw merge error if first parent requires merging")]
public void TestMergeConflictsFirstParent() public void TestMergeConflictsFirstParent()
{ {
var baseYaml = @" const string BaseYaml = @"
Test: Test:
Merge: Merge:
Child1: Child1:
@@ -463,7 +463,8 @@ Test:
Merge: Merge:
"; ";
void Merge() => MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, "test-filename"))); static void Merge() => MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "test-filename")));
Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo( Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo(
"MiniYaml.Merge, duplicate values found for the following keys: Child1: [Child1 (at test-filename:4),Child1 (at test-filename:5)]")); "MiniYaml.Merge, duplicate values found for the following keys: Child1: [Child1 (at test-filename:4),Child1 (at test-filename:5)]"));
} }
@@ -471,14 +472,16 @@ Test:
[TestCase(TestName = "Duplicated child nodes throw merge error if second parent requires merging")] [TestCase(TestName = "Duplicated child nodes throw merge error if second parent requires merging")]
public void TestMergeConflictsSecondParent() public void TestMergeConflictsSecondParent()
{ {
var baseYaml = @" const string BaseYaml = @"
Test: Test:
Merge: Merge:
Merge: Merge:
Child2: Child2:
Child2: Child2:
"; ";
void Merge() => MiniYaml.Merge(new[] { baseYaml }.Select(s => MiniYaml.FromString(s, "test-filename")));
static void Merge() => MiniYaml.Merge(new[] { BaseYaml }.Select(s => MiniYaml.FromString(s, "test-filename")));
Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo( Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo(
"MiniYaml.Merge, duplicate values found for the following keys: Child2: [Child2 (at test-filename:5),Child2 (at test-filename:6)]")); "MiniYaml.Merge, duplicate values found for the following keys: Child2: [Child2 (at test-filename:5),Child2 (at test-filename:6)]"));
} }
@@ -486,18 +489,18 @@ Test:
[TestCase(TestName = "Duplicated child nodes across multiple sources do not throw")] [TestCase(TestName = "Duplicated child nodes across multiple sources do not throw")]
public void TestMergeConflictsMultiSourceMerge() public void TestMergeConflictsMultiSourceMerge()
{ {
var firstYaml = @" const string FirstYaml = @"
Test: Test:
Merge: Merge:
Child: Child:
"; ";
var secondYaml = @" const string SecondYaml = @"
Test: Test:
Merge: Merge:
Child: Child:
"; ";
var result = MiniYaml.Merge(new[] { firstYaml, secondYaml }.Select(s => MiniYaml.FromString(s, ""))); var result = MiniYaml.Merge(new[] { FirstYaml, SecondYaml }.Select(s => MiniYaml.FromString(s, "")));
var testNodes = result.First(n => n.Key == "Test").Value.Nodes; var testNodes = result.First(n => n.Key == "Test").Value.Nodes;
var mergeNode = testNodes.First(n => n.Key == "Merge").Value; var mergeNode = testNodes.First(n => n.Key == "Merge").Value;
Assert.That(mergeNode.Nodes.Count, Is.EqualTo(1)); Assert.That(mergeNode.Nodes.Count, Is.EqualTo(1));
@@ -506,18 +509,19 @@ Test:
[TestCase(TestName = "Duplicated child nodes across multiple sources throw merge error if first parent requires merging")] [TestCase(TestName = "Duplicated child nodes across multiple sources throw merge error if first parent requires merging")]
public void TestMergeConflictsMultiSourceFirstParent() public void TestMergeConflictsMultiSourceFirstParent()
{ {
var firstYaml = @" const string FirstYaml = @"
Test: Test:
Merge: Merge:
Child1: Child1:
Child1: Child1:
"; ";
var secondYaml = @" const string SecondYaml = @"
Test: Test:
Merge: Merge:
"; ";
void Merge() => MiniYaml.Merge(new[] { firstYaml, secondYaml }.Select(s => MiniYaml.FromString(s, "test-filename"))); static void Merge() => MiniYaml.Merge(new[] { FirstYaml, SecondYaml }.Select(s => MiniYaml.FromString(s, "test-filename")));
Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo( Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo(
"MiniYaml.Merge, duplicate values found for the following keys: Child1: [Child1 (at test-filename:4),Child1 (at test-filename:5)]")); "MiniYaml.Merge, duplicate values found for the following keys: Child1: [Child1 (at test-filename:4),Child1 (at test-filename:5)]"));
} }
@@ -525,18 +529,19 @@ Test:
[TestCase(TestName = "Duplicated child nodes across multiple sources throw merge error if second parent requires merging")] [TestCase(TestName = "Duplicated child nodes across multiple sources throw merge error if second parent requires merging")]
public void TestMergeConflictsMultiSourceSecondParent() public void TestMergeConflictsMultiSourceSecondParent()
{ {
var firstYaml = @" const string FirstYaml = @"
Test: Test:
Merge: Merge:
"; ";
var secondYaml = @" const string SecondYaml = @"
Test: Test:
Merge: Merge:
Child2: Child2:
Child2: Child2:
"; ";
void Merge() => MiniYaml.Merge(new[] { firstYaml, secondYaml }.Select(s => MiniYaml.FromString(s, "test-filename"))); static void Merge() => MiniYaml.Merge(new[] { FirstYaml, SecondYaml }.Select(s => MiniYaml.FromString(s, "test-filename")));
Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo( Assert.That(Merge, Throws.Exception.TypeOf<ArgumentException>().And.Message.EqualTo(
"MiniYaml.Merge, duplicate values found for the following keys: Child2: [Child2 (at test-filename:4),Child2 (at test-filename:5)]")); "MiniYaml.Merge, duplicate values found for the following keys: Child2: [Child2 (at test-filename:4),Child2 (at test-filename:5)]"));
} }
@@ -573,15 +578,15 @@ Test:
[TestCase(TestName = "Leading and trailing whitespace can be guarded using a backslash")] [TestCase(TestName = "Leading and trailing whitespace can be guarded using a backslash")]
public void TestGuardedWhitespace() public void TestGuardedWhitespace()
{ {
var testYaml = @"key: \ test value \ "; const string TestYaml = @"key: \ test value \ ";
var nodes = MiniYaml.FromString(testYaml, "testYaml"); var nodes = MiniYaml.FromString(TestYaml, "testYaml");
Assert.AreEqual(" test value ", nodes[0].Value.Value); Assert.AreEqual(" test value ", nodes[0].Value.Value);
} }
[TestCase(TestName = "Comments should count toward line numbers")] [TestCase(TestName = "Comments should count toward line numbers")]
public void CommentsShouldCountTowardLineNumbers() public void CommentsShouldCountTowardLineNumbers()
{ {
var yaml = @" const string Yaml = @"
TestA: TestA:
Nothing: Nothing:
@@ -589,12 +594,12 @@ TestA:
TestB: TestB:
Nothing: Nothing:
"; ";
var resultDiscard = MiniYaml.FromString(yaml); var resultDiscard = MiniYaml.FromString(Yaml);
var resultDiscardLine = resultDiscard.First(n => n.Key == "TestB").Location.Line; var resultDiscardLine = resultDiscard.First(n => n.Key == "TestB").Location.Line;
Assert.That(resultDiscardLine, Is.EqualTo(6), "Node TestB should report its location as line 6, but is not (discarding comments)"); Assert.That(resultDiscardLine, Is.EqualTo(6), "Node TestB should report its location as line 6, but is not (discarding comments)");
Assert.That(resultDiscard[1].Key, Is.EqualTo("TestB"), "Node TestB should be the second child of the root node, but is not (discarding comments)"); Assert.That(resultDiscard[1].Key, Is.EqualTo("TestB"), "Node TestB should be the second child of the root node, but is not (discarding comments)");
var resultKeep = MiniYaml.FromString(yaml, discardCommentsAndWhitespace: false); var resultKeep = MiniYaml.FromString(Yaml, discardCommentsAndWhitespace: false);
var resultKeepLine = resultKeep.First(n => n.Key == "TestB").Location.Line; var resultKeepLine = resultKeep.First(n => n.Key == "TestB").Location.Line;
Assert.That(resultKeepLine, Is.EqualTo(6), "Node TestB should report its location as line 6, but is not (parsing comments)"); Assert.That(resultKeepLine, Is.EqualTo(6), "Node TestB should report its location as line 6, but is not (parsing comments)");
Assert.That(resultKeep[4].Key, Is.EqualTo("TestB"), "Node TestB should be the fifth child of the root node, but is not (parsing comments)"); Assert.That(resultKeep[4].Key, Is.EqualTo("TestB"), "Node TestB should be the fifth child of the root node, but is not (parsing comments)");
@@ -621,7 +626,7 @@ Parent: # comment without value
[TestCase(TestName = "Comments should be removed when discardCommentsAndWhitespace is false")] [TestCase(TestName = "Comments should be removed when discardCommentsAndWhitespace is false")]
public void CommentsShouldntSurviveRoundTrip() public void CommentsShouldntSurviveRoundTrip()
{ {
var yaml = @" const string Yaml = @"
# Top level comment node # Top level comment node
Parent: # comment without value Parent: # comment without value
# Indented comment node # Indented comment node
@@ -634,7 +639,7 @@ Parent: # comment without value
Second: value Second: value
".Replace("\r\n", "\n"); ".Replace("\r\n", "\n");
var result = MiniYaml.FromString(yaml).WriteToString(); var result = MiniYaml.FromString(Yaml).WriteToString();
Assert.AreEqual(strippedYaml, result); Assert.AreEqual(strippedYaml, result);
} }
} }