Skip to content

Commit

Permalink
made debug print much more advanced
Browse files Browse the repository at this point in the history
  • Loading branch information
Eddio0141 committed Oct 27, 2023
1 parent 68a26eb commit cccaa22
Showing 1 changed file with 96 additions and 3 deletions.
99 changes: 96 additions & 3 deletions UniTAS/Patcher/Utils/DebugHelp.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,112 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
using Object = UnityEngine.Object;

namespace UniTAS.Patcher.Utils;

public static class DebugHelp
{
public static string PrintClass(object obj)
{
var indent = 0;
return PrintClass(obj, ref indent, new());
}

private static string PrintClass(object obj, ref int indent, List<object> foundReferences,
bool ignoreInitialIndent = false)
{
var type = obj.GetType();
var fields = AccessTools.GetDeclaredFields(type);
var str = $"{type.Name} " + "{\n";
var str = $"{(ignoreInitialIndent ? "" : IndentString(indent))}{type.Name} {{\n";
indent++;

if (type.IsClass)
{
foundReferences.Add(obj);
}

var fields = AccessTools.GetDeclaredFields(obj.GetType());

foreach (var field in fields)
{
str += $" {field.Name}: {field.GetValue(obj)},\n";
if (field.IsStatic || field.IsLiteral) continue;

str += $"{IndentString(indent)}{field.Name}: ";

var value = field.GetValue(obj);

// circular reference
if (foundReferences.Contains(value))
{
str += "...,\n";
continue;
}

var fieldType = field.FieldType;

if (value is null)
{
str += "null,\n";
continue;
}

// direct use cases
if (fieldType.IsPrimitive || fieldType.IsEnum ||
value is Object and not MonoBehaviour and not ScriptableObject)
{
str += $"{value},\n";
continue;
}

if (value is string)
{
str += $"\"{value}\",\n";
continue;
}

if (value is Array array)
{
str += "[";

if (array.Length == 0)
{
str += "],\n";
continue;
}

str += "\n";

indent++;

foreach (var item in array)
{
str += $"{PrintClass(item, ref indent, foundReferences)}\n";
}

indent--;
str += $"{IndentString(indent)}],\n";
continue;
}

var ns = fieldType.Namespace;
if (ns == "System" || (ns?.StartsWith("System.") ?? false))
{
str += $"{value},\n";
continue;
}

// fallback
str += $"{PrintClass(value, ref indent, foundReferences, true)},\n";
}

indent--;
str += $"{IndentString(indent)}}}";
return str;
}

private static string IndentString(int indent)
{
return new(' ', indent * 2);
}
}

0 comments on commit cccaa22

Please sign in to comment.