This commit is contained in:
2025-01-17 13:10:42 +01:00
commit 4536213c91
15115 changed files with 1442174 additions and 0 deletions

View File

@@ -0,0 +1,253 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEditor.PackageManager;
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal class AssemblyNameProvider : IAssemblyNameProvider
{
private readonly Dictionary<string, PackageInfo> m_PackageInfoCache = new Dictionary<string, PackageInfo>();
private readonly Dictionary<string, ResponseFileData> m_ResponseFilesCache = new Dictionary<string, ResponseFileData>();
private readonly string[] _specialPackagesForProjectGen = new[] { "com.unity.entities", "com.unity.collections" };
ProjectGenerationFlag m_ProjectGenerationFlag = (ProjectGenerationFlag)EditorPrefs.GetInt("unity_project_generation_flag", 3);
public string[] ProjectSupportedExtensions => EditorSettings.projectGenerationUserExtensions;
public string ProjectGenerationRootNamespace => EditorSettings.projectGenerationRootNamespace;
private Assembly[] m_AllEditorAssemblies;
private Assembly[] m_AllPlayerAssemblies;
private Assembly[] m_AllAssemblies;
public ProjectGenerationFlag ProjectGenerationFlag
{
get => m_ProjectGenerationFlag;
private set
{
EditorPrefs.SetInt("unity_project_generation_flag", (int)value);
m_ProjectGenerationFlag = value;
}
}
public string GetAssemblyNameFromScriptPath(string path)
{
return CompilationPipeline.GetAssemblyNameFromScriptPath(path);
}
public Assembly[] GetAllAssemblies()
{
if (m_AllEditorAssemblies == null)
{
m_AllEditorAssemblies = GetAssembliesByType(AssembliesType.Editor);
m_AllAssemblies = m_AllEditorAssemblies;
}
if (ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies))
{
if (m_AllPlayerAssemblies == null)
{
m_AllPlayerAssemblies = GetAssembliesByType(AssembliesType.Player);
m_AllAssemblies = new Assembly[m_AllEditorAssemblies.Length + m_AllPlayerAssemblies.Length];
Array.Copy(m_AllEditorAssemblies, m_AllAssemblies, m_AllEditorAssemblies.Length);
Array.Copy(m_AllPlayerAssemblies, 0, m_AllAssemblies, m_AllEditorAssemblies.Length, m_AllPlayerAssemblies.Length);
}
}
return m_AllAssemblies;
}
private static Assembly[] GetAssembliesByType(AssembliesType type)
{
// This is a very expensive Unity call...
var compilationPipelineAssemblies = CompilationPipeline.GetAssemblies(type);
var assemblies = new Assembly[compilationPipelineAssemblies.Length];
var i = 0;
foreach (var compilationPipelineAssembly in compilationPipelineAssemblies)
{
// The CompilationPipeline's assemblies have an output path of Libraries/ScriptAssemblies
// TODO: It might be worth using the app's copy of Assembly and updating output path when we need it
// But that requires tracking editor and player assemblies separately
var outputPath = type == AssembliesType.Editor
? $@"Temp\Bin\Debug\{compilationPipelineAssembly.name}\"
: $@"Temp\Bin\Debug\{compilationPipelineAssembly.name}\Player\";
assemblies[i] = new Assembly(
compilationPipelineAssembly.name,
outputPath,
compilationPipelineAssembly.sourceFiles,
compilationPipelineAssembly.defines,
compilationPipelineAssembly.assemblyReferences,
compilationPipelineAssembly.compiledAssemblyReferences,
compilationPipelineAssembly.flags,
compilationPipelineAssembly.compilerOptions
#if UNITY_2020_2_OR_NEWER
, compilationPipelineAssembly.rootNamespace
#endif
);
i++;
}
return assemblies;
}
public Assembly GetNamedAssembly(string name)
{
foreach (var assembly in GetAllAssemblies())
{
if (assembly.name == name)
return assembly;
}
return null;
}
public string GetProjectName(string name, string[] defines)
{
if (!ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies))
return name;
return !defines.Contains("UNITY_EDITOR") ? name + ".Player" : name;
}
public IEnumerable<string> GetAllAssetPaths()
{
return AssetDatabase.GetAllAssetPaths();
}
private static string GetPackageRootDirectoryName(string assetPath)
{
const string packagesPrefix = "packages/";
if (!assetPath.StartsWith(packagesPrefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var followupSeparator = assetPath.IndexOf('/', packagesPrefix.Length);
// Note that we return the first path segment without modifying/normalising case!
return followupSeparator == -1 ? assetPath : assetPath.Substring(0, followupSeparator);
}
public PackageInfo GetPackageInfoForAssetPath(string assetPath)
{
var packageName = GetPackageRootDirectoryName(assetPath);
if (packageName == null)
{
return null;
}
// Assume the package name casing is consistent. If it's not, we'll fall back to an uppercase variant that's
// saved in the same dictionary. This gives us cheaper case sensitive matching, with a fallback if our assumption
// is incorrect
if (m_PackageInfoCache.TryGetValue(packageName, out var cachedPackageInfo))
return cachedPackageInfo;
var packageNameUpper = packageName.ToUpperInvariant();
if (m_PackageInfoCache.TryGetValue(packageNameUpper, out cachedPackageInfo))
return cachedPackageInfo;
var result = PackageInfo.FindForAssetPath(packageName);
m_PackageInfoCache[packageName] = result;
m_PackageInfoCache[packageNameUpper] = result;
return result;
}
public void ResetCaches()
{
m_PackageInfoCache.Clear();
m_ResponseFilesCache.Clear();
m_AllEditorAssemblies = null;
m_AllPlayerAssemblies = null;
}
public bool IsInternalizedPackagePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return false;
}
var packageInfo = GetPackageInfoForAssetPath(path);
if (packageInfo == null)
{
return false;
}
if (ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies) && _specialPackagesForProjectGen.Contains(packageInfo.name))
{
// special case for RIDER-104519 Rider is reporting errors in scripts that work fine in Unity when utilizing DOTS
// it would be better to only generate .Player projects and not Editor ones, but that would require big changes in ProjectGeneration
return false;
}
var packageSource = packageInfo.source;
switch (packageSource)
{
case PackageSource.Embedded:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Embedded);
case PackageSource.Registry:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Registry);
case PackageSource.BuiltIn:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.BuiltIn);
case PackageSource.Unknown:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Unknown);
case PackageSource.Local:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Local);
case PackageSource.Git:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.Git);
#if UNITY_2019_3_OR_NEWER
case PackageSource.LocalTarball:
return !ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.LocalTarBall);
#endif
}
return false;
}
public ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory,
ApiCompatibilityLevel apiCompatibilityLevel)
{
var key = responseFilePath + ":" + (int) apiCompatibilityLevel;
if (!m_ResponseFilesCache.TryGetValue(key, out var responseFileData))
{
var systemReferenceDirectories =
CompilationPipeline.GetSystemAssemblyDirectories(apiCompatibilityLevel);
responseFileData = CompilationPipeline.ParseResponseFile(
responseFilePath,
projectDirectory,
systemReferenceDirectories
);
m_ResponseFilesCache.Add(key, responseFileData);
}
return responseFileData;
}
public IEnumerable<string> GetRoslynAnalyzerPaths()
{
return PluginImporter.GetAllImporters()
.Where(i => !i.isNativePlugin && AssetDatabase.GetLabels(i).SingleOrDefault(l => l == "RoslynAnalyzer") != null)
.Select(i => i.assetPath);
}
public void ToggleProjectGeneration(ProjectGenerationFlag preference)
{
if (ProjectGenerationFlag.HasFlag(preference))
{
ProjectGenerationFlag ^= preference;
}
else
{
ProjectGenerationFlag |= preference;
}
}
public void ResetProjectGenerationFlag()
{
ProjectGenerationFlag = ProjectGenerationFlag.None;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 56c8c6e437b14f8e9a91e9832c11bc1a
timeCreated: 1580717719

View File

@@ -0,0 +1,51 @@
using System;
using System.IO;
using System.Security;
using System.Text;
using Packages.Rider.Editor.Util;
namespace Packages.Rider.Editor.ProjectGeneration {
class FileIOProvider : IFileIO
{
public bool Exists(string path)
{
return File.Exists(path);
}
public TextReader GetReader(string path)
{
return new StreamReader(path);
}
public string ReadAllText(string path)
{
return File.ReadAllText(path);
}
public void WriteAllText(string path, string content)
{
File.WriteAllText(path, content, Encoding.UTF8);
LastWriteTracker.UpdateLastWriteIfNeeded(path);
}
public string EscapedRelativePathFor(string file, string rootDirectoryFullPath)
{
// We have to normalize the path, because the PackageManagerRemapper assumes
// dir seperators will be os specific.
var absolutePath = Path.GetFullPath(file.NormalizePath());
var path = SkipPathPrefix(absolutePath, rootDirectoryFullPath);
return SecurityElement.Escape(path);
}
private static string SkipPathPrefix(string path, string prefix)
{
var root = prefix[prefix.Length - 1] == Path.DirectorySeparatorChar
? prefix
: prefix + Path.DirectorySeparatorChar;
return path.StartsWith(root, StringComparison.Ordinal)
? path.Substring(root.Length)
: path;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a6ba838b1348d5e46a7eaacd1646c1d3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
namespace Packages.Rider.Editor.ProjectGeneration {
class GUIDProvider : IGUIDGenerator
{
public string ProjectGuid(string name)
{
return SolutionGuidGenerator.GuidForProject(name);
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8cfde1a59fb35574189691a9de1df93b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Compilation;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal interface IAssemblyNameProvider
{
string[] ProjectSupportedExtensions { get; }
string ProjectGenerationRootNamespace { get; }
ProjectGenerationFlag ProjectGenerationFlag { get; }
string GetAssemblyNameFromScriptPath(string path);
string GetProjectName(string name, string[] defines);
bool IsInternalizedPackagePath(string path);
Assembly[] GetAllAssemblies();
Assembly GetNamedAssembly(string name);
IEnumerable<string> GetAllAssetPaths();
UnityEditor.PackageManager.PackageInfo GetPackageInfoForAssetPath(string assetPath);
ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, ApiCompatibilityLevel systemReferenceDirectories);
IEnumerable<string> GetRoslynAnalyzerPaths();
void ToggleProjectGeneration(ProjectGenerationFlag preference);
void ResetCaches();
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5eea837708474d7e9c1cb4b2eca0213f
timeCreated: 1580717710

View File

@@ -0,0 +1,17 @@
using System.IO;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal interface IFileIO
{
bool Exists(string path);
TextReader GetReader(string path);
string ReadAllText(string path);
void WriteAllText(string path, string content);
// rootDirectoryFullPath is assumed to be the result of Path.GetFullPath
// Passing the directory with a trailing slash (Path.DirectorySeparatorChar) will avoid an allocation
string EscapedRelativePathFor(string path, string rootDirectoryFullPath);
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1bdab5b8331b4506bf4eae379235c053
timeCreated: 1580717666

View File

@@ -0,0 +1,7 @@
namespace Packages.Rider.Editor.ProjectGeneration
{
internal interface IGUIDGenerator
{
string ProjectGuid(string name);
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8c7e8e301f8b4c30bbf9db502d637f0f
timeCreated: 1580717700

View File

@@ -0,0 +1,13 @@
using System.Collections.Generic;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal interface IGenerator
{
bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles, bool checkProjectFiles = false);
void Sync();
bool HasSolutionBeenGenerated();
string SolutionFile();
IAssemblyNameProvider AssemblyNameProvider { get; }
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 39cb9ab8a3b2452cbf58ffbea841d203
timeCreated: 1580717654

View File

@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal static class LastWriteTracker
{
internal static bool HasLastWriteTimeChanged()
{
if (!IsUnityCompatible()) return false;
// any external changes of sln/csproj should cause their regeneration
// Directory.GetCurrentDirectory(), "*.csproj", "*.sln"
var files = new List<FileInfo>();
var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
files.AddRange(directoryInfo.GetFiles("*.csproj"));
files.Add(new FileInfo(Path.Combine(directoryInfo.FullName, directoryInfo.Name + ".sln")));
return files.Any(a => a.LastWriteTime > RiderScriptEditorPersistedState.instance.LastWrite);
}
internal static void UpdateLastWriteIfNeeded(string path)
{
if (!IsUnityCompatible()) return;
var fileInfo = new FileInfo(path);
if (fileInfo.Directory == null)
return;
var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
if (fileInfo.Directory.FullName.Equals(directoryInfo.FullName, StringComparison.OrdinalIgnoreCase) &&
(fileInfo.Extension.Equals(".csproj", StringComparison.OrdinalIgnoreCase)
|| fileInfo.Name.Equals(directoryInfo.Name + ".sln", StringComparison.OrdinalIgnoreCase)))
{
RiderScriptEditorPersistedState.instance.LastWrite = fileInfo.LastWriteTime;
}
}
internal static bool IsUnityCompatible()
{
#if UNITY_2020_1_OR_NEWER
return true;
#else
return false;
#endif
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7019e230344c48d4b81602e2e978e5de
timeCreated: 1645608955

View File

@@ -0,0 +1,41 @@
using System.IO;
#if UNITY_2020_1_OR_NEWER
using UnityEditor.PackageManager;
#endif
namespace Packages.Rider.Editor.ProjectGeneration
{
internal static class PackageManagerTracker
{
private static bool HasManifestJsonLastWriteTimeChanged()
{
if (!LastWriteTracker.IsUnityCompatible()) return false;
var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory());
var manifestFile = new FileInfo(Path.Combine(directoryInfo.FullName, "Packages/manifest.json"));
if (manifestFile.Exists)
{
// for the manifest.json, we store the LastWriteTime here
var res = manifestFile.LastWriteTime > RiderScriptEditorPersistedState.instance.ManifestJsonLastWrite;
if (res) RiderScriptEditorPersistedState.instance.ManifestJsonLastWrite = manifestFile.LastWriteTime;
return res;
}
return false;
}
/// <summary>
/// If the manifest.json was changed outside Unity and Rider calls Unity to Refresh, we should call PM to Refresh its state also
/// </summary>
/// <param name="checkProjectFiles"></param>
internal static void SyncIfNeeded(bool checkProjectFiles)
{
#if UNITY_2020_1_OR_NEWER
if (checkProjectFiles && HasManifestJsonLastWriteTimeChanged())
{
Client.Resolve();
}
#endif
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 32e50e97779a4753a461190076119a99
timeCreated: 1676882821

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7078f19173ceac84fb9e29b9f6175201
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,18 @@
using System;
namespace Packages.Rider.Editor.ProjectGeneration
{
[Flags]
enum ProjectGenerationFlag
{
None = 0,
Embedded = 1,
Local = 2,
Registry = 4,
Git = 8,
BuiltIn = 16,
Unknown = 32,
PlayerAssemblies = 64,
LocalTarBall = 128,
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 78af99d0156944f293b020b49a6830c2
timeCreated: 1580820569

View File

@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
using UnityEditor.Compilation;
using UnityEngine;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal class ProjectPart
{
public string Name { get; }
public string OutputPath { get; }
public Assembly Assembly { get; }
public List<string> AdditionalAssets { get; }
public string[] SourceFiles { get; }
public string RootNamespace { get; }
public Assembly[] AssemblyReferences { get; }
public string[] CompiledAssemblyReferences { get; }
public string[] Defines { get; }
public ScriptCompilerOptions CompilerOptions { get; }
public ProjectPart(string name, Assembly assembly, List<string> additionalAssets)
{
Name = name;
Assembly = assembly;
AdditionalAssets = additionalAssets;
OutputPath = assembly != null ? assembly.outputPath : "Temp/Bin/Debug";
SourceFiles = assembly != null ? assembly.sourceFiles : Array.Empty<string>();
#if UNITY_2020_2_OR_NEWER
RootNamespace = assembly != null ? assembly.rootNamespace : string.Empty;
#else
RootNamespace = UnityEditor.EditorSettings.projectGenerationRootNamespace;
#endif
AssemblyReferences = assembly != null ? assembly.assemblyReferences : Array.Empty<Assembly>();
CompiledAssemblyReferences = assembly != null ? assembly.compiledAssemblyReferences : Array.Empty<string>();
Defines = assembly != null ? assembly.defines : Array.Empty<string>();
CompilerOptions = assembly != null ? assembly.compilerOptions : new ScriptCompilerOptions();
}
public List<ResponseFileData> GetResponseFileData(IAssemblyNameProvider assemblyNameProvider, string projectDirectory)
{
if (Assembly == null)
return new List<ResponseFileData>();
var data = new List<ResponseFileData>();
foreach (var responseFile in Assembly.compilerOptions.ResponseFiles)
{
var responseFileData = assemblyNameProvider.ParseResponseFile(responseFile, projectDirectory, Assembly.compilerOptions.ApiCompatibilityLevel);
foreach (var error in responseFileData.Errors)
Debug.Log($"{responseFile} Parse Error : {error}");
data.Add(responseFileData);
}
return data;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0691c2fe40564a64b3a9b7372c5eca2a
timeCreated: 1604050230

View File

@@ -0,0 +1,23 @@
using System;
using System.Security.Cryptography;
using System.Text;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal static class SolutionGuidGenerator
{
public static string GuidForProject(string projectName)
{
return ComputeGuidHashFor(projectName + "salt");
}
private static string ComputeGuidHashFor(string input)
{
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(Encoding.Default.GetBytes(input));
return new Guid(hash).ToString();
}
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3e4e7fdc19414089a0fb43e43b1bdae1
timeCreated: 1580717740