From 2092189312e158cf01fc972b407624828d1bcd80 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Jul 2021 23:10:48 -0500 Subject: add DiffWith --- src/slskd/Common/Extensions.cs | 46 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index a7a89a71..eab5b02a 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -19,18 +19,56 @@ namespace slskd { using System; using System.Collections.Generic; - using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; - using System.Security.Cryptography; - using System.Text; - using slskd.Validation; + using System.Reflection; /// /// Extensions. /// public static class Extensions { + /// + /// Deeply compares this object with the specified object and returns a list of properties that are different. + /// + /// The left side of the comparison. + /// The right side of the comparison. + /// The root path for recursive calls. + /// A list of differences between the two objects. + public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) + { + if (left.GetType() != right.GetType()) + { + throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}"); + } + + var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); + + foreach (var prop in left.GetType().GetProperties()) + { + var leftVal = prop.GetValue(left); + var rightVal = prop.GetValue(right); + var propType = prop.PropertyType; + var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); + + var quasiPrimitives = new[] { typeof(string), typeof(decimal) }; + + if (propType.IsPrimitive || quasiPrimitives.Contains(propType)) + { + if (!leftVal.Equals(rightVal)) + { + differences.Add((prop, fqn, leftVal, rightVal)); + } + } + else + { + differences.AddRange(DiffWith(leftVal, rightVal, fqn)); + } + } + + return differences; + } + /// /// Returns the directory from the given path, regardless of separator format. /// -- cgit v1.2.3