Utility.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using Mono.Cecil;
  7. namespace BepInEx
  8. {
  9. /// <summary>
  10. /// Generic helper properties and methods.
  11. /// </summary>
  12. public static class Utility
  13. {
  14. /// <summary>
  15. /// Combines multiple paths together, as the specific method is not available in .NET 3.5.
  16. /// </summary>
  17. /// <param name="parts">The multiple paths to combine together.</param>
  18. /// <returns>A combined path.</returns>
  19. public static string CombinePaths(params string[] parts) => parts.Aggregate(Path.Combine);
  20. /// <summary>
  21. /// Tries to parse a bool, with a default value if unable to parse.
  22. /// </summary>
  23. /// <param name="input">The string to parse</param>
  24. /// <param name="defaultValue">The value to return if parsing is unsuccessful.</param>
  25. /// <returns>Boolean value of input if able to be parsed, otherwise default value.</returns>
  26. public static bool SafeParseBool(string input, bool defaultValue = false) { return Boolean.TryParse(input, out bool result) ? result : defaultValue; }
  27. /// <summary>
  28. /// Converts a file path into a UnityEngine.WWW format.
  29. /// </summary>
  30. /// <param name="path">The file path to convert.</param>
  31. /// <returns>A converted file path.</returns>
  32. public static string ConvertToWWWFormat(string path) { return $"file://{path.Replace('\\', '/')}"; }
  33. /// <summary>
  34. /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
  35. /// </summary>
  36. /// <param name="self">The string to test.</param>
  37. /// <returns>True if the value parameter is null or empty, or if value consists exclusively of white-space characters.</returns>
  38. public static bool IsNullOrWhiteSpace(this string self) { return self == null || self.All(Char.IsWhiteSpace); }
  39. public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector)
  40. {
  41. List<TNode> sorted_list = new List<TNode>();
  42. HashSet<TNode> visited = new HashSet<TNode>();
  43. HashSet<TNode> sorted = new HashSet<TNode>();
  44. foreach (TNode input in nodes)
  45. {
  46. Stack<TNode> currentStack = new Stack<TNode>();
  47. if (!Visit(input, currentStack))
  48. {
  49. throw new Exception("Cyclic Dependency:\r\n" + currentStack.Select(x => $" - {x}") //append dashes
  50. .Aggregate((a, b) => $"{a}\r\n{b}")); //add new lines inbetween
  51. }
  52. }
  53. return sorted_list;
  54. bool Visit(TNode node, Stack<TNode> stack)
  55. {
  56. if (visited.Contains(node))
  57. {
  58. if (!sorted.Contains(node))
  59. {
  60. return false;
  61. }
  62. }
  63. else
  64. {
  65. visited.Add(node);
  66. stack.Push(node);
  67. foreach (var dep in dependencySelector(node))
  68. if (!Visit(dep, stack))
  69. return false;
  70. sorted.Add(node);
  71. sorted_list.Add(node);
  72. stack.Pop();
  73. }
  74. return true;
  75. }
  76. }
  77. /// <summary>
  78. /// Try to resolve and load the given assembly DLL.
  79. /// </summary>
  80. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  81. /// <param name="directory">Directory to search the assembly from.</param>
  82. /// <param name="assembly">The loaded assembly.</param>
  83. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  84. private static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class
  85. {
  86. assembly = null;
  87. var potentialDirectories = new List<string> { directory };
  88. potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));
  89. foreach (string subDirectory in potentialDirectories)
  90. {
  91. string path = Path.Combine(subDirectory, $"{assemblyName.Name}.dll");
  92. if (!File.Exists(path))
  93. continue;
  94. try
  95. {
  96. assembly = loader(path);
  97. }
  98. catch (Exception)
  99. {
  100. continue;
  101. }
  102. return true;
  103. }
  104. return false;
  105. }
  106. public static bool IsSubtypeOf(this TypeDefinition self, Type td)
  107. {
  108. if (self.FullName == td.FullName)
  109. return true;
  110. return self.FullName != "System.Object" && (self.BaseType?.Resolve()?.IsSubtypeOf(td) ?? false);
  111. }
  112. /// <summary>
  113. /// Try to resolve and load the given assembly DLL.
  114. /// </summary>
  115. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  116. /// <param name="directory">Directory to search the assembly from.</param>
  117. /// <param name="assembly">The loaded assembly.</param>
  118. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  119. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly) { return TryResolveDllAssembly(assemblyName, directory, Assembly.LoadFile, out assembly); }
  120. /// <summary>
  121. /// Try to resolve and load the given assembly DLL.
  122. /// </summary>
  123. /// <param name="assemblyName">Name of the assembly, of the type <see cref="AssemblyName" />.</param>
  124. /// <param name="directory">Directory to search the assembly from.</param>
  125. /// <param name="assembly">The loaded assembly.</param>
  126. /// <returns>True, if the assembly was found and loaded. Otherwise, false.</returns>
  127. public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly) { return TryResolveDllAssembly(assemblyName, directory, s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly); }
  128. /// <summary>
  129. /// Tries to create a file with the given name
  130. /// </summary>
  131. /// <param name="path">Path of the file to create</param>
  132. /// <param name="mode">File open mode</param>
  133. /// <param name="fileStream">Resulting filestream</param>
  134. /// <param name="access">File access options</param>
  135. /// <param name="share">File share options</param>
  136. /// <returns></returns>
  137. public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
  138. {
  139. try
  140. {
  141. fileStream = new FileStream(path, mode, access, share);
  142. return true;
  143. }
  144. catch (IOException)
  145. {
  146. fileStream = null;
  147. return false;
  148. }
  149. }
  150. }
  151. }