This commit is contained in:
2021-06-13 10:28:03 +02:00
parent eb70603c85
commit df2d24cbd3
7487 changed files with 943244 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf

View File

@@ -0,0 +1,159 @@
# Code Editor Package for Rider
## [3.0.6] - 2021-04-06
Fix bug: For Unity 2021.1+ Switching external editor from VS => Rider won't create the connection between Unity and Rider.
When PlayerSettings.suppressCommonWarnings is true, it is reflected in the generated csproj with NoWarn "0169", "0649"
By default include T4 templates in the generated solution (RIDER-37159)
RIDER-60554 Unity crash in case of project without Unity Test Framework Package.
RIDER-60445 Fix presentation of Rider external editor, when it is installed in a custom location.
Improve project files generation performance
RIDER-60508 Project Generation for projects without any cs files - add reference to UnityEditor/UnityEngine, so that Rider would detect Unity path and version and provide rich features for shader file.
## [3.0.5] - 2021-02-25
More stable in case of possible Rider product code change, improve test. Allows using "Rider for Unreal" with Unity projects (https://youtrack.jetbrains.com/issue/RIDER-51203)
Remove implicit dependency to Test-Framework package
Fix "Unreachable code detected" warning (https://youtrack.jetbrains.com/issue/RIDER-57930)
## [3.0.4] - 2021-01-26
Use LangVersion provided by Unity for generated csproj
Improve documentation
Support nullable provided in csc,rsp
Avoid doing work in Unity seconary processes in UNITY_2021_1_OR_NEWER with UnityEditor.MPE.ProcessLevel.Secondary
## [3.0.3] - 2020-11-18
- Update License
- Avoid connecting Rider from secondary UnityEditor instances
- Fix RIDER-53082 - Generate csproj without cs files, when there are any assets inside
## [3.0.2] - 2020-10-27
- Speedup ProjectGeneration
- Fix RIDER-51958. Callbacks OnGeneratedCSProjectFiles would not work, but show a Warning instead.
- Remove release configuration
- Call RequestScriptReload, when External Editor is changed in Unity.
## [3.0.1] - 2020-10-02
- RIDER-46658 Rider does not run PlayMode tests when ValueSource is combined with parameterized TestFixture
- RIDER-49947 Invoking `PlayerSettings.SetScriptingDefineSymbolsForGroup()` does not update definitions in Rider.
- Add static entrypoint `Packages.Rider.Editor.RiderScriptEditor.SyncSolution` to allow generating solution from commandline.
## [2.0.7] - 2020-08-18
- Improve performance
- Add support for asmdef Root Namespace in .csproj generation
- ProjectGeneration for custom roslyn analysers https://docs.unity3d.com/2020.2/Documentation/Manual/roslyn-analyzers.html
- Switch target platform in Unity would regenerate csproj files (https://github.com/JetBrains/resharper-unity/issues/1740)
## [2.0.6] - 2020-08-10
- Improve performance
- Add support for asmdef Root Namespace in .csproj generation
- ProjectGeneration for custom roslyn analysers https://docs.unity3d.com/2020.2/Documentation/Manual/roslyn-analyzers.html
- Switch target platform in Unity would regenerate csproj files (https://github.com/JetBrains/resharper-unity/issues/1740)
## [2.0.5] - 2020-05-27
- Fix Regression in 2.0.3: In Unity 2019.2.9 on Mac, changing csproj and calling AssetDatabase.Refresh is not regenerating csproj.
- Regenerate projects on changes in manifest.json and Project Settings (EditorOnlyScriptingUserSettings.json) (#51)
- Fix: Assembly references to package assemblies break IDE projects.
- Fix: Reporting test duration.
## [2.0.2] - 2020-03-18
- fix bug in searching Rider path on MacOS
## [2.0.1] - 2020-03-05
- Speed improvements,
- ProjectTypeGuids for unity-generated project
- Improve UI for Project Generation settings
- Changes in csc.rsp would cause project-generation
- Remove NoWarn 0169 from generated csproj
- Support custom JetBrains Toolbox installation location
## [1.2.1] - 2019-12-09
- Load optimised EditorPlugin version compiled to net 461, with fallback to previous version.
- On ExternalEditor settings page: reorder Generate all ... after Extensions handled
- Better presentation for Rider of some version in ExternalEditors list
- Initial support for Code Coverage with dotCover plugin in Rider
- Added support for Player Project generation
## [1.1.4] - 2019-11-21
- Fix warning - unreachable code
## [1.1.3] - 2019-10-17
- Update External Editor, when new toolbox build was installed
- Add xaml to default list of extensions to include in csproj
- Avoid initializing Rider package in secondary Unity process, which does Asset processing
- Reflect multiple csc.rsp arguments to generated csproj files: https://github.com/JetBrains/resharper-unity/issues/1337
- Setting, which allowed to override LangVersion removed in favor of langversion in csc.rsp
- Environment.NewLine is used in generated project files instead of Windows line separator.
## [1.1.2] - 2019-09-18
performance optimizations:
- avoid multiple evaluations
- avoid reflection in DisableSyncSolutionOnceCallBack
- project generation optimization
fixes:
- avoid compilation error with incompatible `Test Framework` package
## [1.1.1] - 2019-08-26
parse nowarn in csc.rsp
warning, when Unity was started from Rider, but external editor was different
improved unit test support
workaround to avoid Unity internal project-generation (fix #28)
## [1.1.0] - 2019-07-02
new setting to manage list of extensions to be opened with Rider
avoid breaking everything on any unhandled exception in RiderScriptEditor cctor
hide Rider settings, when different Editor is selected
dynamically load only newer rider plugins
path detection (work on unix symlinks)
speed up for project generation
lots of bug fixing
## [1.0.8] - 2019-05-20
Fix NullReferenceException when External editor was pointing to non-existing Rider everything was broken by null-ref.
## [1.0.7] - 2019-05-16
Initial migration steps from rider plugin to package.
Fix OSX check and opening of files.
## [1.0.6] - 2019-04-30
Ensure asset database is refreshed when generating csproj and solution files.
## [1.0.5] - 2019-04-27
Add support for generating all csproj files.
## [1.0.4] - 2019-04-18
Fix relative package paths.
Fix opening editor on mac.
## [1.0.3] - 2019-04-12
Fixing null reference issue for callbacks to Asset pipeline.
## [1.0.2] - 2019-01-01
### This is the first release of *Unity Package rider_editor*.
Using the newly created api to integrate Rider with Unity.

View File

@@ -0,0 +1,6 @@
# Contributing
## All contributions are subject to the [Unity Contribution Agreement(UCA)](https://unity3d.com/legal/licenses/Unity_Contribution_Agreement)
By making a pull request, you are confirming agreement to the terms and conditions of the UCA, including that your Contributions are your original creation and that you have complete right and authority to make your Contributions.
## Once you have a change ready following these ground rules. Simply make a pull request

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Unity Technologies Copyright (c) 2019 JetBrains s.r.o. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,577 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.Win32;
using Packages.Rider.Editor.Util;
using Unity.CodeEditor;
using UnityEngine;
namespace Packages.Rider.Editor
{
internal interface IDiscovery
{
CodeEditor.Installation[] PathCallback();
}
internal class Discovery : IDiscovery
{
public CodeEditor.Installation[] PathCallback()
{
var res = RiderPathLocator.GetAllRiderPaths()
.Select(riderInfo => new CodeEditor.Installation
{
Path = riderInfo.Path,
Name = riderInfo.Presentation
})
.ToList();
var editorPath = RiderScriptEditor.CurrentEditor;
if (RiderScriptEditor.IsRiderInstallation(editorPath) &&
!res.Any(a => a.Path == editorPath) &&
FileSystemUtil.EditorPathExists(editorPath))
{
// External editor manually set from custom location
var info = new RiderPathLocator.RiderInfo(editorPath, false);
var installation = new CodeEditor.Installation
{
Path = info.Path,
Name = info.Presentation
};
res.Add(installation);
}
return res.ToArray();
}
}
/// <summary>
/// This code is a modified version of the JetBrains resharper-unity plugin listed here:
/// https://github.com/JetBrains/resharper-unity/blob/master/unity/JetBrains.Rider.Unity.Editor/EditorPlugin/RiderPathLocator.cs
/// </summary>
internal static class RiderPathLocator
{
#if !(UNITY_4_7 || UNITY_5_5)
public static RiderInfo[] GetAllRiderPaths()
{
try
{
switch (SystemInfo.operatingSystemFamily)
{
case OperatingSystemFamily.Windows:
{
return CollectRiderInfosWindows();
}
case OperatingSystemFamily.MacOSX:
{
return CollectRiderInfosMac();
}
case OperatingSystemFamily.Linux:
{
return CollectAllRiderPathsLinux();
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
return new RiderInfo[0];
}
#endif
#if RIDER_EDITOR_PLUGIN // can't be used in com.unity.ide.rider
internal static RiderInfo[] GetAllFoundInfos(OperatingSystemFamilyRider operatingSystemFamily)
{
try
{
switch (operatingSystemFamily)
{
case OperatingSystemFamilyRider.Windows:
{
return CollectRiderInfosWindows();
}
case OperatingSystemFamilyRider.MacOSX:
{
return CollectRiderInfosMac();
}
case OperatingSystemFamilyRider.Linux:
{
return CollectAllRiderPathsLinux();
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
return new RiderInfo[0];
}
internal static string[] GetAllFoundPaths(OperatingSystemFamilyRider operatingSystemFamily)
{
return GetAllFoundInfos(operatingSystemFamily).Select(a=>a.Path).ToArray();
}
#endif
private static RiderInfo[] CollectAllRiderPathsLinux()
{
var installInfos = new List<RiderInfo>();
var home = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(home))
{
var toolboxRiderRootPath = GetToolboxBaseDir();
installInfos.AddRange(CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider.sh", false)
.Select(a => new RiderInfo(a, true)).ToList());
//$Home/.local/share/applications/jetbrains-rider.desktop
var shortcut = new FileInfo(Path.Combine(home, @".local/share/applications/jetbrains-rider.desktop"));
if (shortcut.Exists)
{
var lines = File.ReadAllLines(shortcut.FullName);
foreach (var line in lines)
{
if (!line.StartsWith("Exec=\""))
continue;
var path = line.Split('"').Where((item, index) => index == 1).SingleOrDefault();
if (string.IsNullOrEmpty(path))
continue;
if (installInfos.Any(a => a.Path == path)) // avoid adding similar build as from toolbox
continue;
installInfos.Add(new RiderInfo(path, false));
}
}
}
// snap install
var snapInstallPath = "/snap/rider/current/bin/rider.sh";
if (new FileInfo(snapInstallPath).Exists)
installInfos.Add(new RiderInfo(snapInstallPath, false));
return installInfos.ToArray();
}
private static RiderInfo[] CollectRiderInfosMac()
{
var installInfos = new List<RiderInfo>();
// "/Applications/*Rider*.app"
var folder = new DirectoryInfo("/Applications");
if (folder.Exists)
{
installInfos.AddRange(folder.GetDirectories("*Rider*.app")
.Select(a => new RiderInfo(a.FullName, false))
.ToList());
}
// /Users/user/Library/Application Support/JetBrains/Toolbox/apps/Rider/ch-1/181.3870.267/Rider EAP.app
var toolboxRiderRootPath = GetToolboxBaseDir();
var paths = CollectPathsFromToolbox(toolboxRiderRootPath, "", "Rider*.app", true)
.Select(a => new RiderInfo(a, true));
installInfos.AddRange(paths);
return installInfos.ToArray();
}
private static RiderInfo[] CollectRiderInfosWindows()
{
var installInfos = new List<RiderInfo>();
var toolboxRiderRootPath = GetToolboxBaseDir();
var installPathsToolbox = CollectPathsFromToolbox(toolboxRiderRootPath, "bin", "rider64.exe", false).ToList();
installInfos.AddRange(installPathsToolbox.Select(a => new RiderInfo(a, true)).ToList());
var installPaths = new List<string>();
const string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
CollectPathsFromRegistry(registryKey, installPaths);
const string wowRegistryKey = @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
CollectPathsFromRegistry(wowRegistryKey, installPaths);
installInfos.AddRange(installPaths.Select(a => new RiderInfo(a, false)).ToList());
return installInfos.ToArray();
}
private static string GetToolboxBaseDir()
{
switch (SystemInfo.operatingSystemFamily)
{
case OperatingSystemFamily.Windows:
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return GetToolboxRiderRootPath(localAppData);
}
case OperatingSystemFamily.MacOSX:
{
var home = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(home))
{
var localAppData = Path.Combine(home, @"Library/Application Support");
return GetToolboxRiderRootPath(localAppData);
}
break;
}
case OperatingSystemFamily.Linux:
{
var home = Environment.GetEnvironmentVariable("HOME");
if (!string.IsNullOrEmpty(home))
{
var localAppData = Path.Combine(home, @".local/share");
return GetToolboxRiderRootPath(localAppData);
}
break;
}
}
return string.Empty;
}
private static string GetToolboxRiderRootPath(string localAppData)
{
var toolboxPath = Path.Combine(localAppData, @"JetBrains/Toolbox");
var settingsJson = Path.Combine(toolboxPath, ".settings.json");
if (File.Exists(settingsJson))
{
var path = SettingsJson.GetInstallLocationFromJson(File.ReadAllText(settingsJson));
if (!string.IsNullOrEmpty(path))
toolboxPath = path;
}
var toolboxRiderRootPath = Path.Combine(toolboxPath, @"apps/Rider");
return toolboxRiderRootPath;
}
internal static ProductInfo GetBuildVersion(string path)
{
var buildTxtFileInfo = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt()));
var dir = buildTxtFileInfo.DirectoryName;
if (!Directory.Exists(dir))
return null;
var buildVersionFile = new FileInfo(Path.Combine(dir, "product-info.json"));
if (!buildVersionFile.Exists)
return null;
var json = File.ReadAllText(buildVersionFile.FullName);
return ProductInfo.GetProductInfo(json);
}
internal static Version GetBuildNumber(string path)
{
var file = new FileInfo(Path.Combine(path, GetRelativePathToBuildTxt()));
if (!file.Exists)
return null;
var text = File.ReadAllText(file.FullName);
var index = text.IndexOf("-", StringComparison.Ordinal) + 1; // RD-191.7141.355
if (index <= 0)
return null;
var versionText = text.Substring(index);
return Version.TryParse(versionText, out var v) ? v : null;
}
internal static bool GetIsToolbox(string path)
{
return Path.GetFullPath(path).StartsWith(Path.GetFullPath(GetToolboxBaseDir()));
}
private static string GetRelativePathToBuildTxt()
{
switch (SystemInfo.operatingSystemFamily)
{
case OperatingSystemFamily.Windows:
case OperatingSystemFamily.Linux:
return "../../build.txt";
case OperatingSystemFamily.MacOSX:
return "Contents/Resources/build.txt";
}
throw new Exception("Unknown OS");
}
private static void CollectPathsFromRegistry(string registryKey, List<string> installPaths)
{
using (var key = Registry.CurrentUser.OpenSubKey(registryKey))
{
CollectPathsFromRegistry(installPaths, key);
}
using (var key = Registry.LocalMachine.OpenSubKey(registryKey))
{
CollectPathsFromRegistry(installPaths, key);
}
}
private static void CollectPathsFromRegistry(List<string> installPaths, RegistryKey key)
{
if (key == null) return;
foreach (var subkeyName in key.GetSubKeyNames().Where(a => a.Contains("Rider")))
{
using (var subkey = key.OpenSubKey(subkeyName))
{
var folderObject = subkey?.GetValue("InstallLocation");
if (folderObject == null) continue;
var folder = folderObject.ToString();
var possiblePath = Path.Combine(folder, @"bin\rider64.exe");
if (File.Exists(possiblePath))
installPaths.Add(possiblePath);
}
}
}
private static string[] CollectPathsFromToolbox(string toolboxRiderRootPath, string dirName, string searchPattern,
bool isMac)
{
if (!Directory.Exists(toolboxRiderRootPath))
return new string[0];
var channelDirs = Directory.GetDirectories(toolboxRiderRootPath);
var paths = channelDirs.SelectMany(channelDir =>
{
try
{
// use history.json - last entry stands for the active build https://jetbrains.slack.com/archives/C07KNP99D/p1547807024066500?thread_ts=1547731708.057700&cid=C07KNP99D
var historyFile = Path.Combine(channelDir, ".history.json");
if (File.Exists(historyFile))
{
var json = File.ReadAllText(historyFile);
var build = ToolboxHistory.GetLatestBuildFromJson(json);
if (build != null)
{
var buildDir = Path.Combine(channelDir, build);
var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir);
if (executablePaths.Any())
return executablePaths;
}
}
var channelFile = Path.Combine(channelDir, ".channel.settings.json");
if (File.Exists(channelFile))
{
var json = File.ReadAllText(channelFile).Replace("active-application", "active_application");
var build = ToolboxInstallData.GetLatestBuildFromJson(json);
if (build != null)
{
var buildDir = Path.Combine(channelDir, build);
var executablePaths = GetExecutablePaths(dirName, searchPattern, isMac, buildDir);
if (executablePaths.Any())
return executablePaths;
}
}
// changes in toolbox json files format may brake the logic above, so return all found Rider installations
return Directory.GetDirectories(channelDir)
.SelectMany(buildDir => GetExecutablePaths(dirName, searchPattern, isMac, buildDir));
}
catch (Exception e)
{
// do not write to Debug.Log, just log it.
Logger.Warn($"Failed to get RiderPath from {channelDir}", e);
}
return new string[0];
})
.Where(c => !string.IsNullOrEmpty(c))
.ToArray();
return paths;
}
private static string[] GetExecutablePaths(string dirName, string searchPattern, bool isMac, string buildDir)
{
var folder = new DirectoryInfo(Path.Combine(buildDir, dirName));
if (!folder.Exists)
return new string[0];
if (!isMac)
return new[] {Path.Combine(folder.FullName, searchPattern)}.Where(File.Exists).ToArray();
return folder.GetDirectories(searchPattern).Select(f => f.FullName)
.Where(Directory.Exists).ToArray();
}
// Disable the "field is never assigned" compiler warning. We never assign it, but Unity does.
// Note that Unity disable this warning in the generated C# projects
#pragma warning disable 0649
[Serializable]
class SettingsJson
{
// ReSharper disable once InconsistentNaming
public string install_location;
[CanBeNull]
public static string GetInstallLocationFromJson(string json)
{
try
{
#if UNITY_4_7 || UNITY_5_5
return JsonConvert.DeserializeObject<SettingsJson>(json).install_location;
#else
return JsonUtility.FromJson<SettingsJson>(json).install_location;
#endif
}
catch (Exception)
{
Logger.Warn($"Failed to get install_location from json {json}");
}
return null;
}
}
[Serializable]
class ToolboxHistory
{
public List<ItemNode> history;
[CanBeNull]
public static string GetLatestBuildFromJson(string json)
{
try
{
#if UNITY_4_7 || UNITY_5_5
return JsonConvert.DeserializeObject<ToolboxHistory>(json).history.LastOrDefault()?.item.build;
#else
return JsonUtility.FromJson<ToolboxHistory>(json).history.LastOrDefault()?.item.build;
#endif
}
catch (Exception)
{
Logger.Warn($"Failed to get latest build from json {json}");
}
return null;
}
}
[Serializable]
class ItemNode
{
public BuildNode item;
}
[Serializable]
class BuildNode
{
public string build;
}
[Serializable]
internal class ProductInfo
{
public string version;
public string versionSuffix;
[CanBeNull]
internal static ProductInfo GetProductInfo(string json)
{
try
{
var productInfo = JsonUtility.FromJson<ProductInfo>(json);
return productInfo;
}
catch (Exception)
{
Logger.Warn($"Failed to get version from json {json}");
}
return null;
}
}
// ReSharper disable once ClassNeverInstantiated.Global
[Serializable]
class ToolboxInstallData
{
// ReSharper disable once InconsistentNaming
public ActiveApplication active_application;
[CanBeNull]
public static string GetLatestBuildFromJson(string json)
{
try
{
#if UNITY_4_7 || UNITY_5_5
var toolbox = JsonConvert.DeserializeObject<ToolboxInstallData>(json);
#else
var toolbox = JsonUtility.FromJson<ToolboxInstallData>(json);
#endif
var builds = toolbox.active_application.builds;
if (builds != null && builds.Any())
return builds.First();
}
catch (Exception)
{
Logger.Warn($"Failed to get latest build from json {json}");
}
return null;
}
}
[Serializable]
class ActiveApplication
{
// ReSharper disable once InconsistentNaming
public List<string> builds;
}
#pragma warning restore 0649
internal struct RiderInfo
{
public bool IsToolbox;
public string Presentation;
public Version BuildNumber;
public ProductInfo ProductInfo;
public string Path;
public RiderInfo(string path, bool isToolbox)
{
if (path == RiderScriptEditor.CurrentEditor)
{
RiderScriptEditorData.instance.Init();
BuildNumber = RiderScriptEditorData.instance.editorBuildNumber.ToVersion();
ProductInfo = RiderScriptEditorData.instance.productInfo;
}
else
{
BuildNumber = GetBuildNumber(path);
ProductInfo = GetBuildVersion(path);
}
Path = new FileInfo(path).FullName; // normalize separators
var presentation = $"Rider {BuildNumber}";
if (ProductInfo != null && !string.IsNullOrEmpty(ProductInfo.version))
{
var suffix = string.IsNullOrEmpty(ProductInfo.versionSuffix) ? "" : $" {ProductInfo.versionSuffix}";
presentation = $"Rider {ProductInfo.version}{suffix}";
}
if (isToolbox)
presentation += " (JetBrains Toolbox)";
Presentation = presentation;
IsToolbox = isToolbox;
}
}
private static class Logger
{
internal static void Warn(string message, Exception e = null)
{
#if RIDER_EDITOR_PLUGIN // can't be used in com.unity.ide.rider
Log.GetLog(typeof(RiderPathLocator).Name).Warn(message);
if (e != null)
Log.GetLog(typeof(RiderPathLocator).Name).Warn(e);
#else
Debug.LogError(message);
if (e != null)
Debug.LogException(e);
#endif
}
}
}
}

View File

@@ -0,0 +1,151 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Debug = UnityEngine.Debug;
namespace Packages.Rider.Editor
{
internal static class EditorPluginInterop
{
private static string EditorPluginAssemblyNamePrefix = "JetBrains.Rider.Unity.Editor.Plugin.";
public static readonly string EditorPluginAssemblyName = $"{EditorPluginAssemblyNamePrefix}Net46.Repacked";
public static readonly string EditorPluginAssemblyNameFallback = $"{EditorPluginAssemblyNamePrefix}Full.Repacked";
private static string ourEntryPointTypeName = "JetBrains.Rider.Unity.Editor.PluginEntryPoint";
private static Assembly ourEditorPluginAssembly;
public static Assembly EditorPluginAssembly
{
get
{
if (ourEditorPluginAssembly != null)
return ourEditorPluginAssembly;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
ourEditorPluginAssembly = assemblies.FirstOrDefault(a =>
{
try
{
return a.GetName().Name.StartsWith(EditorPluginAssemblyNamePrefix); // some user assemblies may fail here
}
catch (Exception)
{
// ignored
}
return default;
});
return ourEditorPluginAssembly;
}
}
private static void DisableSyncSolutionOnceCallBack()
{
// RiderScriptableSingleton.Instance.CsprojProcessedOnce = true;
// Otherwise EditorPlugin regenerates all on every AppDomain reload
var assembly = EditorPluginAssembly;
if (assembly == null) return;
var type = assembly.GetType("JetBrains.Rider.Unity.Editor.Utils.RiderScriptableSingleton");
if (type == null) return;
var baseType = type.BaseType;
if (baseType == null) return;
var instance = baseType.GetProperty("Instance");
if (instance == null) return;
var instanceVal = instance.GetValue(null);
var member = type.GetProperty("CsprojProcessedOnce");
if (member==null) return;
member.SetValue(instanceVal, true);
}
public static string LogPath
{
get
{
try
{
var assembly = EditorPluginAssembly;
if (assembly == null) return null;
var type = assembly.GetType(ourEntryPointTypeName);
if (type == null) return null;
var field = type.GetField("LogPath", BindingFlags.NonPublic | BindingFlags.Static);
if (field == null) return null;
return field.GetValue(null) as string;
}
catch (Exception)
{
Debug.Log("Unable to do OpenFile to Rider from dll, fallback to com.unity.ide.rider implementation.");
}
return null;
}
}
public static bool OpenFileDllImplementation(string path, int line, int column)
{
var openResult = false;
// reflection for fast OpenFileLineCol, when Rider is started and protocol connection is established
try
{
var assembly = EditorPluginAssembly;
if (assembly == null) return false;
var type = assembly.GetType(ourEntryPointTypeName);
if (type == null) return false;
var field = type.GetField("OpenAssetHandler", BindingFlags.NonPublic | BindingFlags.Static);
if (field == null) return false;
var handlerInstance = field.GetValue(null);
var method = handlerInstance.GetType()
.GetMethod("OnOpenedAsset", new[] {typeof(string), typeof(int), typeof(int)});
if (method == null) return false;
var assetFilePath = path;
if (!string.IsNullOrEmpty(path))
assetFilePath = Path.GetFullPath(path);
openResult = (bool) method.Invoke(handlerInstance, new object[] {assetFilePath, line, column});
}
catch (Exception e)
{
Debug.Log("Unable to do OpenFile to Rider from dll, fallback to com.unity.ide.rider implementation.");
Debug.LogException(e);
}
return openResult;
}
public static bool EditorPluginIsLoadedFromAssets(Assembly assembly)
{
if (assembly == null)
return false;
var location = assembly.Location;
var currentDir = Directory.GetCurrentDirectory();
return location.StartsWith(currentDir, StringComparison.InvariantCultureIgnoreCase);
}
internal static void InitEntryPoint(Assembly assembly)
{
try
{
var version = RiderScriptEditorData.instance.editorBuildNumber;
if (version != null)
{
if (version.Major < 192)
DisableSyncSolutionOnceCallBack(); // is require for Rider prior to 2019.2
}
else
DisableSyncSolutionOnceCallBack();
var type = assembly.GetType("JetBrains.Rider.Unity.Editor.AfterUnity56.EntryPoint");
if (type == null)
type = assembly.GetType("JetBrains.Rider.Unity.Editor.UnitTesting.EntryPoint"); // oldRider
RuntimeHelpers.RunClassConstructor(type.TypeHandle);
}
catch (TypeInitializationException ex)
{
Debug.LogException(ex);
if (ex.InnerException != null)
Debug.LogException(ex.InnerException);
}
}
}
}

View File

@@ -0,0 +1,22 @@
namespace Packages.Rider.Editor
{
internal enum LoggingLevel
{
/// <summary>
/// Do not use it in logging. Only in config to disable logging.
/// </summary>
OFF,
/// <summary>For errors that lead to application failure</summary>
FATAL,
/// <summary>For errors that must be shown in Exception Browser</summary>
ERROR,
/// <summary>Suspicious situations but not errors</summary>
WARN,
/// <summary>Regular level for important events</summary>
INFO,
/// <summary>Additional info for debbuging</summary>
VERBOSE,
/// <summary>Methods &amp; callstacks tracing, more than verbose</summary>
TRACE,
}
}

View File

@@ -0,0 +1,115 @@
using Unity.CodeEditor;
using UnityEditor;
using UnityEngine;
namespace Packages.Rider.Editor
{
internal static class PluginSettings
{
public static LoggingLevel SelectedLoggingLevel
{
get => (LoggingLevel) EditorPrefs.GetInt("Rider_SelectedLoggingLevel", 0);
private set => EditorPrefs.SetInt("Rider_SelectedLoggingLevel", (int) value);
}
public static bool LogEventsCollectorEnabled
{
get => EditorPrefs.GetBool("Rider_LogEventsCollectorEnabled", true);
private set => EditorPrefs.SetBool("Rider_LogEventsCollectorEnabled", value);
}
/// <summary>
/// Preferences menu layout
/// </summary>
/// <remarks>
/// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
/// </remarks>
[SettingsProvider]
private static SettingsProvider RiderPreferencesItem()
{
if (!RiderScriptEditor.IsRiderInstallation(RiderScriptEditor.CurrentEditor))
return null;
if (!RiderScriptEditorData.instance.shouldLoadEditorPlugin)
return null;
var provider = new SettingsProvider("Preferences/Rider", SettingsScope.User)
{
label = "Rider",
keywords = new[] { "Rider" },
guiHandler = (searchContext) =>
{
EditorGUIUtility.labelWidth = 200f;
EditorGUILayout.BeginVertical();
GUILayout.BeginVertical();
LogEventsCollectorEnabled =
EditorGUILayout.Toggle(new GUIContent("Pass Console to Rider:"), LogEventsCollectorEnabled);
GUILayout.EndVertical();
GUILayout.Label("");
if (!string.IsNullOrEmpty(EditorPluginInterop.LogPath))
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Log file:");
var previous = GUI.enabled;
GUI.enabled = previous && SelectedLoggingLevel != LoggingLevel.OFF;
var button = GUILayout.Button(new GUIContent("Open log"));
if (button)
{
//UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal(PluginEntryPoint.LogPath, 0);
// works much faster than the commented code, when Rider is already started
CodeEditor.CurrentEditor.OpenProject(EditorPluginInterop.LogPath, 0, 0);
}
GUI.enabled = previous;
GUILayout.EndHorizontal();
}
var loggingMsg =
@"Sets the amount of Rider Debug output. If you are about to report an issue, please select Verbose logging level and attach Unity console output to the issue.";
SelectedLoggingLevel =
(LoggingLevel) EditorGUILayout.EnumPopup(new GUIContent("Logging Level:", loggingMsg),
SelectedLoggingLevel);
EditorGUILayout.HelpBox(loggingMsg, MessageType.None);
LinkButton("https://github.com/JetBrains/resharper-unity");
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
var assembly = EditorPluginInterop.EditorPluginAssembly;
if (assembly != null)
{
var version = assembly.GetName().Version;
GUILayout.Label("Plugin version: " + version, new GUIStyle(GUI.skin.label)
{
margin = new RectOffset(4, 4, 4, 4),
});
}
GUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
};
return provider;
}
private static void LinkButton(string url)
{
var style = EditorStyles.linkLabel;
var bClicked = GUILayout.Button(url, style);
var rect = GUILayoutUtility.GetLastRect();
rect.width = style.CalcSize(new GUIContent(url)).x;
EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
if (bClicked)
Application.OpenURL(url);
}
}
}

View File

@@ -0,0 +1,16 @@
using Unity.CodeEditor;
using UnityEditor;
namespace Packages.Rider.Editor.PostProcessors
{
internal class RiderAssetPostprocessor: AssetPostprocessor
{
public static bool OnPreGeneratingCSProjectFiles()
{
var path = RiderScriptEditor.GetEditorRealPath(CodeEditor.CurrentEditorInstallation);
if (RiderScriptEditor.IsRiderInstallation(path))
return !ProjectGeneration.ProjectGeneration.isRiderProjectGeneration;
return false;
}
}
}

View File

@@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEditor.PackageManager;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal class AssemblyNameProvider : IAssemblyNameProvider
{
private readonly Dictionary<string, UnityEditor.PackageManager.PackageInfo> m_PackageInfoCache = new Dictionary<string, UnityEditor.PackageManager.PackageInfo>();
ProjectGenerationFlag m_ProjectGenerationFlag = (ProjectGenerationFlag)EditorPrefs.GetInt("unity_project_generation_flag", 3);
public string[] ProjectSupportedExtensions => EditorSettings.projectGenerationUserExtensions;
public string ProjectGenerationRootNamespace => EditorSettings.projectGenerationRootNamespace;
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 IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution)
{
var assemblies = GetAssembliesByType(AssembliesType.Editor, shouldFileBePartOfSolution, "Temp\\Bin\\Debug\\");
if (ProjectGenerationFlag.HasFlag(ProjectGenerationFlag.PlayerAssemblies))
{
var playerAssemblies = GetAssembliesByType(AssembliesType.Player, shouldFileBePartOfSolution, "Temp\\Bin\\Debug\\Player\\");
assemblies = assemblies.Concat(playerAssemblies);
}
return assemblies;
}
private IEnumerable<Assembly> GetAssembliesByType(AssembliesType type, Func<string, bool> shouldFileBePartOfSolution, string outputPath)
{
foreach (var assembly in CompilationPipeline.GetAssemblies(type))
{
var options = new ScriptCompilerOptions()
{
ResponseFiles = assembly.compilerOptions.ResponseFiles,
AllowUnsafeCode = assembly.compilerOptions.AllowUnsafeCode,
ApiCompatibilityLevel = assembly.compilerOptions.ApiCompatibilityLevel
};
if (assembly.sourceFiles.Any(shouldFileBePartOfSolution))
{
yield return new Assembly(assembly.name
, outputPath, assembly.sourceFiles, assembly.defines
, assembly.assemblyReferences, assembly.compiledAssemblyReferences, assembly.flags, options
#if UNITY_2020_2_OR_NEWER
, assembly.rootNamespace
#endif
);
}
}
}
public string GetProjectName(string assemblyOutputPath, string assemblyName)
{
return assemblyOutputPath.EndsWith("\\Player\\", StringComparison.Ordinal) ? assemblyName + ".Player" : assemblyName;
}
public IEnumerable<string> GetAllAssetPaths()
{
return AssetDatabase.GetAllAssetPaths();
}
private static string ResolvePotentialParentPackageAssetPath(string assetPath)
{
const string packagesPrefix = "packages/";
if (!assetPath.StartsWith(packagesPrefix, StringComparison.OrdinalIgnoreCase))
{
return null;
}
var followupSeparator = assetPath.IndexOf('/', packagesPrefix.Length);
if (followupSeparator == -1)
{
return assetPath.ToLowerInvariant();
}
return assetPath.Substring(0, followupSeparator).ToLowerInvariant();
}
public UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath)
{
var parentPackageAssetPath = ResolvePotentialParentPackageAssetPath(assetPath);
if (parentPackageAssetPath == null)
{
return null;
}
if (m_PackageInfoCache.TryGetValue(parentPackageAssetPath, out var cachedPackageInfo))
{
return cachedPackageInfo;
}
var result = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(parentPackageAssetPath);
m_PackageInfoCache[parentPackageAssetPath] = result;
return result;
}
public void ResetPackageInfoCache()
{
m_PackageInfoCache.Clear();
}
public bool IsInternalizedPackagePath(string path)
{
if (string.IsNullOrEmpty(path.Trim()))
{
return false;
}
var packageInfo = FindForAssetPath(path);
if (packageInfo == null)
{
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, string[] systemReferenceDirectories)
{
return CompilationPipeline.ParseResponseFile(
responseFilePath,
projectDirectory,
systemReferenceDirectories
);
}
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,22 @@
using System.IO;
using System.Text;
namespace Packages.Rider.Editor.ProjectGeneration {
class FileIOProvider : IFileIO
{
public bool Exists(string fileName)
{
return File.Exists(fileName);
}
public string ReadAllText(string fileName)
{
return File.ReadAllText(fileName);
}
public void WriteAllText(string fileName, string content)
{
File.WriteAllText(fileName, content, Encoding.UTF8);
}
}
}

View File

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

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
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 assemblyOutputPath, string assemblyName);
bool IsInternalizedPackagePath(string path);
IEnumerable<Assembly> GetAssemblies(Func<string, bool> shouldFileBePartOfSolution);
IEnumerable<string> GetAllAssetPaths();
UnityEditor.PackageManager.PackageInfo FindForAssetPath(string assetPath);
ResponseFileData ParseResponseFile(string responseFilePath, string projectDirectory, string[] systemReferenceDirectories);
IEnumerable<string> GetRoslynAnalyzerPaths();
void ToggleProjectGeneration(ProjectGenerationFlag preference);
void ResetPackageInfoCache();
}
}

View File

@@ -0,0 +1,10 @@
namespace Packages.Rider.Editor.ProjectGeneration
{
internal interface IFileIO
{
bool Exists(string fileName);
string ReadAllText(string fileName);
void WriteAllText(string fileName, string content);
}
}

View File

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

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);
void Sync();
bool HasSolutionBeenGenerated();
string SolutionFile();
IAssemblyNameProvider AssemblyNameProvider { get; }
}
}

View File

@@ -0,0 +1,896 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using Packages.Rider.Editor.Util;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEditorInternal;
using UnityEngine;
namespace Packages.Rider.Editor.ProjectGeneration
{
internal class ProjectGeneration : IGenerator
{
private enum ScriptingLanguage
{
None,
CSharp
}
public static readonly string MSBuildNamespaceUri = "http://schemas.microsoft.com/developer/msbuild/2003";
/// <summary>
/// Map source extensions to ScriptingLanguages
/// </summary>
private static readonly Dictionary<string, ScriptingLanguage> k_BuiltinSupportedExtensions =
new Dictionary<string, ScriptingLanguage>
{
{ "cs", ScriptingLanguage.CSharp },
{ "uxml", ScriptingLanguage.None },
{ "uss", ScriptingLanguage.None },
{ "shader", ScriptingLanguage.None },
{ "compute", ScriptingLanguage.None },
{ "cginc", ScriptingLanguage.None },
{ "hlsl", ScriptingLanguage.None },
{ "glslinc", ScriptingLanguage.None },
{ "template", ScriptingLanguage.None },
{ "raytrace", ScriptingLanguage.None },
{ "json", ScriptingLanguage.None},
{ "asmdef", ScriptingLanguage.None},
{ "xaml", ScriptingLanguage.None},
{ "tt", ScriptingLanguage.None},
{ "t4", ScriptingLanguage.None},
{ "ttinclude", ScriptingLanguage.None}
};
private string m_SolutionProjectEntryTemplate = string.Join(Environment.NewLine,
@"Project(""{{{0}}}"") = ""{1}"", ""{2}"", ""{{{3}}}""",
@"EndProject").Replace(" ", "\t");
private string m_SolutionProjectConfigurationTemplate = string.Join(Environment.NewLine,
@" {{{0}}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU",
@" {{{0}}}.Debug|Any CPU.Build.0 = Debug|Any CPU").Replace(" ", "\t");
private static readonly string[] k_ReimportSyncExtensions = { ".dll", ".asmdef" };
/// <summary>
/// Map ScriptingLanguages to project extensions
/// </summary>
/*static readonly Dictionary<ScriptingLanguage, string> k_ProjectExtensions = new Dictionary<ScriptingLanguage, string>
{
{ ScriptingLanguage.CSharp, ".csproj" },
{ ScriptingLanguage.None, ".csproj" },
};*/
private static readonly Regex k_ScriptReferenceExpression = new Regex(
@"^Library.ScriptAssemblies.(?<dllname>(?<project>.*)\.dll$)",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
private string[] m_ProjectSupportedExtensions = new string[0];
public string ProjectDirectory { get; }
private readonly string m_ProjectName;
private readonly IAssemblyNameProvider m_AssemblyNameProvider;
private readonly IFileIO m_FileIOProvider;
private readonly IGUIDGenerator m_GUIDGenerator;
internal static bool isRiderProjectGeneration; // workaround to https://github.cds.internal.unity3d.com/unity/com.unity.ide.rider/issues/28
private const string k_ToolsVersion = "4.0";
private const string k_ProductVersion = "10.0.20506";
private const string k_BaseDirectory = ".";
private const string k_TargetFrameworkVersion = "v4.7.1";
private const string k_TargetLanguageVersion = "latest";
IAssemblyNameProvider IGenerator.AssemblyNameProvider => m_AssemblyNameProvider;
public ProjectGeneration()
: this(Directory.GetParent(Application.dataPath).FullName) { }
public ProjectGeneration(string tempDirectory)
: this(tempDirectory, new AssemblyNameProvider(), new FileIOProvider(), new GUIDProvider()) { }
public ProjectGeneration(string tempDirectory, IAssemblyNameProvider assemblyNameProvider, IFileIO fileIoProvider, IGUIDGenerator guidGenerator)
{
ProjectDirectory = tempDirectory.Replace('\\', '/');
m_ProjectName = Path.GetFileName(ProjectDirectory);
m_AssemblyNameProvider = assemblyNameProvider;
m_FileIOProvider = fileIoProvider;
m_GUIDGenerator = guidGenerator;
}
/// <summary>
/// Syncs the scripting solution if any affected files are relevant.
/// </summary>
/// <returns>
/// Whether the solution was synced.
/// </returns>
/// <param name='affectedFiles'>
/// A set of files whose status has changed
/// </param>
/// <param name="reimportedFiles">
/// A set of files that got reimported
/// </param>
public bool SyncIfNeeded(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
{
SetupSupportedExtensions();
if (HasFilesBeenModified(affectedFiles, reimportedFiles) || RiderScriptEditorData.instance.hasChanges || RiderScriptEditorData.instance.HasChangesInCompilationDefines())
{
Sync();
RiderScriptEditorData.instance.hasChanges = false;
RiderScriptEditorData.instance.InvalidateSavedCompilationDefines();
return true;
}
return false;
}
private bool HasFilesBeenModified(IEnumerable<string> affectedFiles, IEnumerable<string> reimportedFiles)
{
return affectedFiles.Any(ShouldFileBePartOfSolution) || reimportedFiles.Any(ShouldSyncOnReimportedAsset);
}
private static bool ShouldSyncOnReimportedAsset(string asset)
{
return k_ReimportSyncExtensions.Contains(Path.GetExtension(asset)) || Path.GetFileName(asset) == "csc.rsp";
}
public void Sync()
{
m_AssemblyNameProvider.ResetPackageInfoCache();
SetupSupportedExtensions();
var types = GetAssetPostprocessorTypes();
isRiderProjectGeneration = true;
var externalCodeAlreadyGeneratedProjects = OnPreGeneratingCSProjectFiles(types);
isRiderProjectGeneration = false;
if (!externalCodeAlreadyGeneratedProjects)
{
GenerateAndWriteSolutionAndProjects(types);
}
OnGeneratedCSProjectFiles(types);
}
public bool HasSolutionBeenGenerated()
{
return m_FileIOProvider.Exists(SolutionFile());
}
private void SetupSupportedExtensions()
{
m_ProjectSupportedExtensions = m_AssemblyNameProvider.ProjectSupportedExtensions;
}
private bool ShouldFileBePartOfSolution(string file)
{
// Exclude files coming from packages except if they are internalized.
if (m_AssemblyNameProvider.IsInternalizedPackagePath(file))
{
return false;
}
return HasValidExtension(file);
}
private bool HasValidExtension(string file)
{
var extension = Path.GetExtension(file);
// Dll's are not scripts but still need to be included..
if (extension.Equals(".dll", StringComparison.OrdinalIgnoreCase))
return true;
if (extension.Equals(".asmdef", StringComparison.OrdinalIgnoreCase))
return true;
return IsSupportedExtension(extension);
}
private bool IsSupportedExtension(string extension)
{
extension = extension.TrimStart('.');
return k_BuiltinSupportedExtensions.ContainsKey(extension) || m_ProjectSupportedExtensions.Contains(extension);
}
public void GenerateAndWriteSolutionAndProjects(Type[] types)
{
// Only synchronize islands that have associated source files and ones that we actually want in the project.
// This also filters out DLLs coming from .asmdef files in packages.
var assemblies = m_AssemblyNameProvider.GetAssemblies(ShouldFileBePartOfSolution).ToArray();
var assemblyNames = new HashSet<string>(assemblies.Select(a => a.name));
var allAssetProjectParts = GenerateAllAssetProjectParts();
var projectParts = new List<ProjectPart>();
foreach (var assembly in assemblies)
{
allAssetProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject);
projectParts.Add(new ProjectPart(assembly.name, assembly, additionalAssetsForProject));
}
var riderAssembly = m_AssemblyNameProvider.GetAssemblies(_ => true).FirstOrDefault(a=>a.name == "Unity.Rider.Editor");
var projectPartsWithoutAssembly = allAssetProjectParts.Where(a => !assemblyNames.Contains(a.Key));
projectParts.AddRange(projectPartsWithoutAssembly.Select(allAssetProjectPart =>
{
Assembly assembly = null;
if (riderAssembly != null)
// We want to add those references, so that Rider would detect Unity path and version and provide rich features for shader files
assembly = new Assembly(allAssetProjectPart.Key, riderAssembly.outputPath, new string[0], new string[0],
new Assembly[0],
riderAssembly.compiledAssemblyReferences.Where(a =>
a.EndsWith("UnityEditor.dll") || a.EndsWith("UnityEngine.dll") ||
a.EndsWith("UnityEngine.CoreModule.dll")).ToArray(), riderAssembly.flags);
return new ProjectPart(allAssetProjectPart.Key, assembly, allAssetProjectPart.Value);
}));
SyncSolution(projectParts.ToArray(), types);
foreach (var projectPart in projectParts)
{
SyncProject(projectPart, types, GetAllRoslynAnalyzerPaths().ToArray());
}
}
private IEnumerable<string> GetAllRoslynAnalyzerPaths()
{
return m_AssemblyNameProvider.GetRoslynAnalyzerPaths();
}
private Dictionary<string, string> GenerateAllAssetProjectParts()
{
var stringBuilders = new Dictionary<string, StringBuilder>();
foreach (var asset in m_AssemblyNameProvider.GetAllAssetPaths())
{
// Exclude files coming from packages except if they are internalized.
if (m_AssemblyNameProvider.IsInternalizedPackagePath(asset))
{
continue;
}
var extension = Path.GetExtension(asset);
if (IsSupportedExtension(extension) && !extension.Equals(".cs", StringComparison.OrdinalIgnoreCase))
{
// Find assembly the asset belongs to by adding script extension and using compilation pipeline.
var assemblyName = m_AssemblyNameProvider.GetAssemblyNameFromScriptPath(asset + ".cs");
if (string.IsNullOrEmpty(assemblyName))
{
continue;
}
assemblyName = FileSystemUtil.FileNameWithoutExtension(assemblyName);
if (!stringBuilders.TryGetValue(assemblyName, out var projectBuilder))
{
projectBuilder = new StringBuilder();
stringBuilders[assemblyName] = projectBuilder;
}
projectBuilder.Append(" <None Include=\"").Append(EscapedRelativePathFor(asset)).Append("\" />")
.Append(Environment.NewLine);
}
}
var result = new Dictionary<string, string>();
foreach (var entry in stringBuilders)
result[entry.Key] = entry.Value.ToString();
return result;
}
private void SyncProject(
ProjectPart island,
Type[] types,
string[] roslynAnalyzerDllPaths)
{
SyncProjectFileIfNotChanged(
ProjectFile(island),
ProjectText(island, roslynAnalyzerDllPaths),
types);
}
private void SyncProjectFileIfNotChanged(string path, string newContents, Type[] types)
{
if (Path.GetExtension(path) == ".csproj")
{
newContents = OnGeneratedCSProject(path, newContents, types);
}
SyncFileIfNotChanged(path, newContents);
}
private void SyncSolutionFileIfNotChanged(string path, string newContents, Type[] types)
{
newContents = OnGeneratedSlnSolution(path, newContents, types);
SyncFileIfNotChanged(path, newContents);
}
private static void OnGeneratedCSProjectFiles(Type[] types)
{
foreach (var type in types)
{
var method = type.GetMethod("OnGeneratedCSProjectFiles",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
if (method == null)
{
continue;
}
Debug.LogWarning("OnGeneratedCSProjectFiles is not supported.");
// RIDER-51958
//method.Invoke(null, args);
}
}
public static Type[] GetAssetPostprocessorTypes()
{
return TypeCache.GetTypesDerivedFrom<AssetPostprocessor>().ToArray(); // doesn't find types from EditorPlugin, which is fine
}
private static bool OnPreGeneratingCSProjectFiles(Type[] types)
{
var result = false;
foreach (var type in types)
{
var args = new object[0];
var method = type.GetMethod("OnPreGeneratingCSProjectFiles",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
if (method == null)
{
continue;
}
var returnValue = method.Invoke(null, args);
if (method.ReturnType == typeof(bool))
{
result |= (bool)returnValue;
}
}
return result;
}
private static string OnGeneratedCSProject(string path, string content, Type[] types)
{
foreach (var type in types)
{
var args = new[] { path, content };
var method = type.GetMethod("OnGeneratedCSProject",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
if (method == null)
{
continue;
}
var returnValue = method.Invoke(null, args);
if (method.ReturnType == typeof(string))
{
content = (string)returnValue;
}
}
return content;
}
private static string OnGeneratedSlnSolution(string path, string content, Type[] types)
{
foreach (var type in types)
{
var args = new[] { path, content };
var method = type.GetMethod("OnGeneratedSlnSolution",
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Static);
if (method == null)
{
continue;
}
var returnValue = method.Invoke(null, args);
if (method.ReturnType == typeof(string))
{
content = (string)returnValue;
}
}
return content;
}
private void SyncFileIfNotChanged(string filename, string newContents)
{
try
{
if (m_FileIOProvider.Exists(filename) && newContents == m_FileIOProvider.ReadAllText(filename))
{
return;
}
}
catch (Exception exception)
{
Debug.LogException(exception);
}
m_FileIOProvider.WriteAllText(filename, newContents);
}
private string ProjectText(ProjectPart assembly,
string[] roslynAnalyzerDllPaths)
{
var responseFilesData = assembly.ParseResponseFileData(m_AssemblyNameProvider, ProjectDirectory).ToList();
var projectBuilder = new StringBuilder(ProjectHeader(assembly, responseFilesData, roslynAnalyzerDllPaths));
foreach (var file in assembly.SourceFiles)
{
var fullFile = EscapedRelativePathFor(file);
projectBuilder.Append(" <Compile Include=\"").Append(fullFile).Append("\" />").Append(Environment.NewLine);
}
projectBuilder.Append(assembly.AssetsProjectPart);
var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));
var internalAssemblyReferences = assembly.AssemblyReferences
.Where(reference => !reference.sourceFiles.Any(ShouldFileBePartOfSolution)).Select(i => i.outputPath);
var allReferences =
assembly.CompiledAssemblyReferences
.Union(responseRefs)
.Union(internalAssemblyReferences).ToArray();
foreach (var reference in allReferences)
{
var fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference);
AppendReference(fullReference, projectBuilder);
}
if (0 < assembly.AssemblyReferences.Length)
{
projectBuilder.Append(" </ItemGroup>").Append(Environment.NewLine);
projectBuilder.Append(" <ItemGroup>").Append(Environment.NewLine);
foreach (var reference in assembly.AssemblyReferences.Where(i => i.sourceFiles.Any(ShouldFileBePartOfSolution)))
{
projectBuilder.Append(" <ProjectReference Include=\"").Append(reference.name).Append(GetProjectExtension()).Append("\">").Append(Environment.NewLine);
projectBuilder.Append(" <Project>{").Append(ProjectGuid(reference.name, reference.outputPath)).Append("}</Project>").Append(Environment.NewLine);
projectBuilder.Append(" <Name>").Append(reference.name).Append("</Name>").Append(Environment.NewLine);
projectBuilder.Append(" </ProjectReference>").Append(Environment.NewLine);
}
}
projectBuilder.Append(ProjectFooter());
return projectBuilder.ToString();
}
private static void AppendReference(string fullReference, StringBuilder projectBuilder)
{
//replace \ with / and \\ with /
var escapedFullPath = SecurityElement.Escape(fullReference);
escapedFullPath = escapedFullPath.Replace("\\\\", "/").Replace("\\", "/");
projectBuilder.Append(" <Reference Include=\"").Append(FileSystemUtil.FileNameWithoutExtension(escapedFullPath))
.Append("\">").Append(Environment.NewLine);
projectBuilder.Append(" <HintPath>").Append(escapedFullPath).Append("</HintPath>").Append(Environment.NewLine);
projectBuilder.Append(" </Reference>").Append(Environment.NewLine);
}
private string ProjectFile(ProjectPart projectPart)
{
return Path.Combine(ProjectDirectory, $"{m_AssemblyNameProvider.GetProjectName(projectPart.OutputPath, projectPart.Name)}.csproj");
}
public string SolutionFile()
{
return Path.Combine(ProjectDirectory, $"{m_ProjectName}.sln");
}
private string ProjectHeader(
ProjectPart assembly,
List<ResponseFileData> responseFilesData,
string[] roslynAnalyzerDllPaths
)
{
var otherResponseFilesData = GetOtherArgumentsFromResponseFilesData(responseFilesData);
var arguments = new object[]
{
k_ToolsVersion,
k_ProductVersion,
ProjectGuid(assembly.Name, assembly.OutputPath),
InternalEditorUtility.GetEngineAssemblyPath(),
InternalEditorUtility.GetEditorAssemblyPath(),
string.Join(";", assembly.Defines.Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
MSBuildNamespaceUri,
assembly.Name,
assembly.OutputPath,
assembly.RootNamespace,
k_TargetFrameworkVersion,
GenerateLangVersion(otherResponseFilesData["langversion"], assembly),
k_BaseDirectory,
assembly.CompilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
GenerateNoWarn(otherResponseFilesData["nowarn"].ToList()),
GenerateAnalyserItemGroup(
otherResponseFilesData["analyzer"].Concat(otherResponseFilesData["a"])
.SelectMany(x=>x.Split(';'))
.Concat(roslynAnalyzerDllPaths)
.Distinct()
.ToArray()),
GenerateAnalyserAdditionalFiles(otherResponseFilesData["additionalfile"].SelectMany(x=>x.Split(';')).Distinct().ToArray()),
#if UNITY_2020_2_OR_NEWER
GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Append(assembly.CompilerOptions.RoslynAnalyzerRulesetPath).Where(a=>!string.IsNullOrEmpty(a)).Distinct().ToArray()),
#else
GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Distinct().ToArray()),
#endif
GenerateWarningLevel(otherResponseFilesData["warn"].Concat(otherResponseFilesData["w"]).Distinct()),
GenerateWarningAsError(otherResponseFilesData["warnaserror"]),
GenerateDocumentationFile(otherResponseFilesData["doc"].ToArray()),
GenerateNullable(otherResponseFilesData["nullable"])
};
try
{
return string.Format(GetProjectHeaderTemplate(), arguments);
}
catch (Exception)
{
throw new NotSupportedException(
"Failed creating c# project because the c# project header did not have the correct amount of arguments, which is " +
arguments.Length);
}
}
private string GenerateNullable(IEnumerable<string> enumerable)
{
if (!enumerable.Any())
return string.Empty;
var returnValue = string.Empty;
var val = string.Empty;
foreach (var s in enumerable)
{
if (s == "+") val = "enable";
else if (s == "-") val = "disable";
else val = s;
}
returnValue += $@" <Nullable>{val}</Nullable>";
return $"{Environment.NewLine}{returnValue}";
}
private static string GenerateDocumentationFile(string[] paths)
{
if (!paths.Any())
return String.Empty;
return $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <DocumentationFile>{a}</DocumentationFile>"))}";
}
private static string GenerateWarningAsError(IEnumerable<string> enumerable)
{
var returnValue = String.Empty;
var allWarningsAsErrors = false;
var warningIds = new List<string>();
foreach (var s in enumerable)
{
if (s == "+") allWarningsAsErrors = true;
else if (s == "-") allWarningsAsErrors = false;
else
{
warningIds.Add(s);
}
}
returnValue += $@" <TreatWarningsAsErrors>{allWarningsAsErrors}</TreatWarningsAsErrors>";
if (warningIds.Any())
{
returnValue += $"{Environment.NewLine} <WarningsAsErrors>{string.Join(";", warningIds)}</WarningsAsErrors>";
}
return $"{Environment.NewLine}{returnValue}";
}
private static string GenerateWarningLevel(IEnumerable<string> warningLevel)
{
var level = warningLevel.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(level))
return level;
return 4.ToString();
}
private static string GetSolutionText()
{
return string.Join(Environment.NewLine,
@"",
@"Microsoft Visual Studio Solution File, Format Version {0}",
@"# Visual Studio {1}",
@"{2}",
@"Global",
@" GlobalSection(SolutionConfigurationPlatforms) = preSolution",
@" Debug|Any CPU = Debug|Any CPU",
@" EndGlobalSection",
@" GlobalSection(ProjectConfigurationPlatforms) = postSolution",
@"{3}",
@" EndGlobalSection",
@" GlobalSection(SolutionProperties) = preSolution",
@" HideSolutionNode = FALSE",
@" EndGlobalSection",
@"EndGlobal",
@"").Replace(" ", "\t");
}
private static string GetProjectFooterTemplate()
{
return string.Join(Environment.NewLine,
@" </ItemGroup>",
@" <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" />",
@" <!-- To modify your build process, add your task inside one of the targets below and uncomment it.",
@" Other similar extension points exist, see Microsoft.Common.targets.",
@" <Target Name=""BeforeBuild"">",
@" </Target>",
@" <Target Name=""AfterBuild"">",
@" </Target>",
@" -->",
@"</Project>",
@"");
}
private static string GetProjectHeaderTemplate()
{
var header = new[]
{
@"<?xml version=""1.0"" encoding=""utf-8""?>",
@"<Project ToolsVersion=""{0}"" DefaultTargets=""Build"" xmlns=""{6}"">",
@" <PropertyGroup>",
@" <LangVersion>{11}</LangVersion>",
@" <_TargetFrameworkDirectories>non_empty_path_generated_by_unity.rider.package</_TargetFrameworkDirectories>",
@" <_FullFrameworkReferenceAssemblyPaths>non_empty_path_generated_by_unity.rider.package</_FullFrameworkReferenceAssemblyPaths>",
@" <DisableHandlePackageFileConflicts>true</DisableHandlePackageFileConflicts>{17}",
@" </PropertyGroup>",
@" <PropertyGroup>",
@" <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration>",
@" <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform>",
@" <ProductVersion>{1}</ProductVersion>",
@" <SchemaVersion>2.0</SchemaVersion>",
@" <RootNamespace>{9}</RootNamespace>",
@" <ProjectGuid>{{{2}}}</ProjectGuid>",
@" <ProjectTypeGuids>{{E097FAD1-6243-4DAD-9C02-E9B9EFC3FFC1}};{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}</ProjectTypeGuids>",
@" <OutputType>Library</OutputType>",
@" <AppDesignerFolder>Properties</AppDesignerFolder>",
@" <AssemblyName>{7}</AssemblyName>",
@" <TargetFrameworkVersion>{10}</TargetFrameworkVersion>",
@" <FileAlignment>512</FileAlignment>",
@" <BaseDirectory>{12}</BaseDirectory>",
@" </PropertyGroup>",
@" <PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "">",
@" <DebugSymbols>true</DebugSymbols>",
@" <DebugType>full</DebugType>",
@" <Optimize>false</Optimize>",
@" <OutputPath>{8}</OutputPath>",
@" <DefineConstants>{5}</DefineConstants>",
@" <ErrorReport>prompt</ErrorReport>",
@" <WarningLevel>{18}</WarningLevel>",
@" <NoWarn>{14}</NoWarn>",
@" <AllowUnsafeBlocks>{13}</AllowUnsafeBlocks>{19}{20}{21}",
@" </PropertyGroup>"
};
var forceExplicitReferences = new[]
{
@" <PropertyGroup>",
@" <NoConfig>true</NoConfig>",
@" <NoStdLib>true</NoStdLib>",
@" <AddAdditionalExplicitAssemblyReferences>false</AddAdditionalExplicitAssemblyReferences>",
@" <ImplicitlyExpandNETStandardFacades>false</ImplicitlyExpandNETStandardFacades>",
@" <ImplicitlyExpandDesignTimeFacades>false</ImplicitlyExpandDesignTimeFacades>",
@" </PropertyGroup>"
};
var footer = new[]
{
@"{15}{16} <ItemGroup>",
@""
};
var pieces = header.Concat(forceExplicitReferences).Concat(footer).ToArray();
return string.Join(Environment.NewLine, pieces);
}
private void SyncSolution(ProjectPart[] islands, Type[] types)
{
SyncSolutionFileIfNotChanged(SolutionFile(), SolutionText(islands), types);
}
private string SolutionText(ProjectPart[] islands)
{
var fileversion = "11.00";
var vsversion = "2010";
var projectEntries = GetProjectEntries(islands);
var projectConfigurations = string.Join(Environment.NewLine,
islands.Select(i => GetProjectActiveConfigurations(ProjectGuid(i.Name, i.OutputPath))).ToArray());
return string.Format(GetSolutionText(), fileversion, vsversion, projectEntries, projectConfigurations);
}
private static string GenerateAnalyserItemGroup(string[] paths)
{
// <ItemGroup>
// <Analyzer Include="..\packages\Comments_analyser.1.0.6626.21356\analyzers\dotnet\cs\Comments_analyser.dll" />
// <Analyzer Include="..\packages\UnityEngineAnalyzer.1.0.0.0\analyzers\dotnet\cs\UnityEngineAnalyzer.dll" />
// </ItemGroup>
if (!paths.Any())
return string.Empty;
var analyserBuilder = new StringBuilder();
analyserBuilder.AppendLine(" <ItemGroup>");
foreach (var path in paths)
{
analyserBuilder.AppendLine($" <Analyzer Include=\"{path}\" />");
}
analyserBuilder.AppendLine(" </ItemGroup>");
return analyserBuilder.ToString();
}
private static ILookup<string, string> GetOtherArgumentsFromResponseFilesData(List<ResponseFileData> responseFilesData)
{
var paths = responseFilesData.SelectMany(x =>
{
return x.OtherArguments
.Where(a => a.StartsWith("/") || a.StartsWith("-"))
.Select(b =>
{
var index = b.IndexOf(":", StringComparison.Ordinal);
if (index > 0 && b.Length > index)
{
var key = b.Substring(1, index - 1);
return new KeyValuePair<string, string>(key, b.Substring(index + 1));
}
const string warnaserror = "warnaserror";
if (b.Substring(1).StartsWith(warnaserror))
{
return new KeyValuePair<string, string>(warnaserror, b.Substring(warnaserror.Length + 1));
}
const string nullable = "nullable";
if (b.Substring(1).Equals(nullable))
{
return new KeyValuePair<string, string>(nullable, "enable");
}
return default;
});
})
.Distinct()
.ToLookup(o => o.Key, pair => pair.Value);
return paths;
}
private string GenerateLangVersion(IEnumerable<string> langVersionList, ProjectPart assembly)
{
var langVersion = langVersionList.FirstOrDefault();
if (!string.IsNullOrWhiteSpace(langVersion))
return langVersion;
#if UNITY_2020_2_OR_NEWER
return assembly.CompilerOptions.LanguageVersion;
#else
return k_TargetLanguageVersion;
#endif
}
private static string GenerateAnalyserRuleSet(string[] paths)
{
//<CodeAnalysisRuleSet>..\path\to\myrules.ruleset</CodeAnalysisRuleSet>
if (!paths.Any())
return string.Empty;
return $"{Environment.NewLine}{string.Join(Environment.NewLine, paths.Select(a => $" <CodeAnalysisRuleSet>{a}</CodeAnalysisRuleSet>"))}";
}
private static string GenerateAnalyserAdditionalFiles(string[] paths)
{
if (!paths.Any())
return string.Empty;
var analyserBuilder = new StringBuilder();
analyserBuilder.AppendLine(" <ItemGroup>");
foreach (var path in paths)
{
analyserBuilder.AppendLine($" <AdditionalFiles Include=\"{path}\" />");
}
analyserBuilder.AppendLine(" </ItemGroup>");
return analyserBuilder.ToString();
}
public static string GenerateNoWarn(List<string> codes)
{
#if UNITY_2020_1_OR_NEWER
if (PlayerSettings.suppressCommonWarnings)
codes.AddRange(new[] {"0169", "0649"});
#endif
if (!codes.Any())
return string.Empty;
return string.Join(",", codes.Distinct());
}
private string GetProjectEntries(ProjectPart[] islands)
{
var projectEntries = islands.Select(i => string.Format(
m_SolutionProjectEntryTemplate,
SolutionGuidGenerator.GuidForSolution(),
i.Name,
Path.GetFileName(ProjectFile(i)),
ProjectGuid(i.Name, i.OutputPath)
));
return string.Join(Environment.NewLine, projectEntries.ToArray());
}
/// <summary>
/// Generate the active configuration string for a given project guid
/// </summary>
private string GetProjectActiveConfigurations(string projectGuid)
{
return string.Format(
m_SolutionProjectConfigurationTemplate,
projectGuid);
}
private string EscapedRelativePathFor(string file)
{
var projectDir = ProjectDirectory.Replace('/', '\\');
file = file.Replace('/', '\\');
var path = SkipPathPrefix(file, projectDir);
var packageInfo = m_AssemblyNameProvider.FindForAssetPath(path.Replace('\\', '/'));
if (packageInfo != null)
{
// We have to normalize the path, because the PackageManagerRemapper assumes
// dir seperators will be os specific.
var absolutePath = Path.GetFullPath(NormalizePath(path)).Replace('/', '\\');
path = SkipPathPrefix(absolutePath, projectDir);
}
return SecurityElement.Escape(path);
}
private static string SkipPathPrefix(string path, string prefix)
{
if (path.StartsWith($@"{prefix}\"))
return path.Substring(prefix.Length + 1);
return path;
}
private static string NormalizePath(string path)
{
if (Path.DirectorySeparatorChar == '\\')
return path.Replace('/', Path.DirectorySeparatorChar);
return path.Replace('\\', Path.DirectorySeparatorChar);
}
private static string ProjectFooter()
{
return GetProjectFooterTemplate();
}
private static string GetProjectExtension()
{
return ".csproj";
}
private string ProjectGuid(string name, string outputPath)
{
return m_GUIDGenerator.ProjectGuid(
m_ProjectName,
m_AssemblyNameProvider.GetProjectName(outputPath, name));
}
}
}

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,69 @@
using System.Collections.Generic;
using System.Linq;
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 string AssetsProjectPart { 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, string assetsProjectPart)
{
Name = name;
Assembly = assembly;
AssetsProjectPart = assetsProjectPart;
OutputPath = assembly != null ? assembly.outputPath : "Temp/Bin/Debug";
SourceFiles = assembly != null ? assembly.sourceFiles : new string[0];
#if UNITY_2020_2_OR_NEWER
RootNamespace = assembly != null ? assembly.rootNamespace : string.Empty;
#else
RootNamespace = UnityEditor.EditorSettings.projectGenerationRootNamespace;
#endif
AssemblyReferences = assembly != null ? assembly.assemblyReferences : new Assembly[0];
CompiledAssemblyReferences = assembly!=null? assembly.compiledAssemblyReferences:new string[0];
Defines = assembly != null ? assembly.defines : new string[0];
CompilerOptions = assembly != null ? assembly.compilerOptions : new ScriptCompilerOptions();
}
public IEnumerable<ResponseFileData> ParseResponseFileData(IAssemblyNameProvider assemblyNameProvider, string projectDirectory)
{
if (Assembly == null)
return new ResponseFileData[0];
var systemReferenceDirectories =
CompilationPipeline.GetSystemAssemblyDirectories(Assembly.compilerOptions.ApiCompatibilityLevel);
var responseFilesData = Assembly.compilerOptions.ResponseFiles.ToDictionary(
x => x, x => assemblyNameProvider.ParseResponseFile(
x,
projectDirectory,
systemReferenceDirectories
));
var responseFilesWithErrors = responseFilesData.Where(x => x.Value.Errors.Any())
.ToDictionary(x => x.Key, x => x.Value);
if (responseFilesWithErrors.Any())
{
foreach (var error in responseFilesWithErrors)
foreach (var valueError in error.Value.Errors)
{
Debug.LogError($"{error.Key} Parse Error : {valueError}");
}
}
return responseFilesData.Select(x => x.Value);
}
}
}

View File

@@ -0,0 +1,29 @@
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");
}
public static string GuidForSolution()
{
// GUID for a C# class library: http://www.codeproject.com/Reference/720512/List-of-Visual-Studio-Project-Type-GUIDs
return "FAE04EC0-301F-11D3-BF4B-00C04F79EFBC";
}
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,10 @@
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("Unity.Rider.Editor")]
[assembly: InternalsVisibleTo("Unity.Rider.EditorTests")]
[assembly: InternalsVisibleTo("Unity.PackageValidationSuite.Editor")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
[assembly: AssemblyVersion("3.0.4")]

View File

@@ -0,0 +1,41 @@
using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
namespace Packages.Rider.Editor
{
internal static class RiderFileSystemWatcher
{
public static void InitWatcher(string watchDirectory,
string filter, FileSystemEventHandler onChanged)
{
Task.Run(() =>
{
var watcher = new FileSystemWatcher();
watcher.Path = watchDirectory;
watcher.NotifyFilter = NotifyFilters.LastWrite; //Watch for changes in LastWrite times
watcher.Filter = filter;
watcher.Changed += onChanged;
watcher.Deleted += onChanged;
watcher.EnableRaisingEvents = true;// Begin watching.
return watcher;
}).ContinueWith(task =>
{
try
{
var watcher = task.Result;
AppDomain.CurrentDomain.DomainUnload += (EventHandler) ((_, __) =>
{
watcher.Dispose();
});
}
catch (Exception ex)
{
Debug.LogError(ex);
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Rider.Editor.Util;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Packages.Rider.Editor
{
internal class RiderInitializer
{
public void Initialize(string editorPath)
{
var assembly = EditorPluginInterop.EditorPluginAssembly;
if (EditorPluginInterop.EditorPluginIsLoadedFromAssets(assembly))
{
Debug.LogError($"Please delete {assembly.Location}. Unity 2019.2+ loads it directly from Rider installation. To disable this, open Rider's settings, search and uncheck 'Automatically install and update Rider's Unity editor plugin'.");
return;
}
// for debugging rider editor plugin
if (RiderPathUtil.IsRiderDevEditor(editorPath))
{
LoadEditorPluginForDevEditor(editorPath);
}
else
{
var relPath = "../../plugins/rider-unity/EditorPlugin";
if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
relPath = "Contents/plugins/rider-unity/EditorPlugin";
var baseDir = Path.Combine(editorPath, relPath);
var dllFile = new FileInfo(Path.Combine(baseDir, $"{EditorPluginInterop.EditorPluginAssemblyName}.dll"));
if (!dllFile.Exists)
dllFile = new FileInfo(Path.Combine(baseDir,
$"{EditorPluginInterop.EditorPluginAssemblyNameFallback}.dll"));
if (dllFile.Exists)
{
var bytes = File.ReadAllBytes(dllFile.FullName);
assembly = AppDomain.CurrentDomain.Load(bytes); // doesn't lock assembly on disk
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider EditorPlugin loaded from {dllFile.FullName}");
EditorPluginInterop.InitEntryPoint(assembly);
}
else
{
Debug.Log($"Unable to find Rider EditorPlugin {dllFile.FullName} for Unity ");
}
}
}
private static void LoadEditorPluginForDevEditor(string editorPath)
{
var file = new FileInfo(editorPath);
if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
file = new FileInfo(Path.Combine(editorPath, "rider-dev.bat"));
if (!file.Exists)
{
Debug.Log($"Unable to determine path to EditorPlugin from {file}");
return;
}
var dllPath = File.ReadLines(file.FullName).FirstOrDefault();
if (dllPath == null)
{
Debug.Log($"Unable to determine path to EditorPlugin from {file}");
return;
}
var dllFile = new FileInfo(dllPath);
if (!dllFile.Exists)
{
Debug.Log($"Unable to find Rider EditorPlugin {dllPath} for Unity ");
return;
}
var assembly = AppDomain.CurrentDomain.Load(AssemblyName.GetAssemblyName(dllFile.FullName));
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider EditorPlugin loaded from {dllFile.FullName}");
EditorPluginInterop.InitEntryPoint(assembly);
}
}
}

View File

@@ -0,0 +1,466 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Packages.Rider.Editor.ProjectGeneration;
using Packages.Rider.Editor.Util;
using Unity.CodeEditor;
using UnityEditor;
using UnityEngine;
using Debug = UnityEngine.Debug;
namespace Packages.Rider.Editor
{
[InitializeOnLoad]
internal class RiderScriptEditor : IExternalCodeEditor
{
IDiscovery m_Discoverability;
static IGenerator m_ProjectGeneration;
RiderInitializer m_Initiliazer = new RiderInitializer();
static RiderScriptEditor()
{
try
{
// todo: make ProjectGeneration lazy
var projectGeneration = new ProjectGeneration.ProjectGeneration();
var editor = new RiderScriptEditor(new Discovery(), projectGeneration);
CodeEditor.Register(editor);
var path = GetEditorRealPath(CurrentEditor);
if (IsRiderInstallation(path))
{
RiderPathLocator.RiderInfo[] installations = null;
if (!RiderScriptEditorData.instance.initializedOnce)
{
installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
// is likely outdated
if (installations.Any() && installations.All(a => GetEditorRealPath(a.Path) != path))
{
if (RiderPathLocator.GetIsToolbox(path)) // is toolbox - update
{
var toolboxInstallations = installations.Where(a => a.IsToolbox).ToArray();
if (toolboxInstallations.Any())
{
var newEditor = toolboxInstallations.Last().Path;
CodeEditor.SetExternalScriptEditor(newEditor);
path = newEditor;
}
else
{
var newEditor = installations.Last().Path;
CodeEditor.SetExternalScriptEditor(newEditor);
path = newEditor;
}
}
else // is non toolbox - notify
{
var newEditorName = installations.Last().Presentation;
Debug.LogWarning($"Consider updating External Editor in Unity to {newEditorName}.");
}
}
ShowWarningOnUnexpectedScriptEditor(path);
RiderScriptEditorData.instance.initializedOnce = true;
}
if (!FileSystemUtil.EditorPathExists(path)) // previously used rider was removed
{
if (installations == null)
installations = RiderPathLocator.GetAllRiderPaths().OrderBy(a => a.BuildNumber).ToArray();
if (installations.Any())
{
var newEditor = installations.Last().Path;
CodeEditor.SetExternalScriptEditor(newEditor);
path = newEditor;
}
}
RiderScriptEditorData.instance.Init();
editor.CreateSolutionIfDoesntExist();
if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
{
editor.m_Initiliazer.Initialize(path);
}
RiderFileSystemWatcher.InitWatcher(
Directory.GetCurrentDirectory(), "*.csproj", (sender, args) =>
{
RiderScriptEditorData.instance.hasChanges = true;
});
RiderFileSystemWatcher.InitWatcher(
Directory.GetCurrentDirectory(), "*.sln", (sender, args) =>
{
RiderScriptEditorData.instance.hasChanges = true;
});
RiderFileSystemWatcher.InitWatcher(
Path.Combine(Directory.GetCurrentDirectory(), "Packages"),
"manifest.json", (sender, args) => { RiderScriptEditorData.instance.hasChanges = true; });
// can't switch to non-deprecated api, because UnityEditor.Build.BuildPipelineInterfaces.processors is internal
#pragma warning disable 618
EditorUserBuildSettings.activeBuildTargetChanged += () =>
#pragma warning restore 618
{
RiderScriptEditorData.instance.hasChanges = true;
};
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private static void ShowWarningOnUnexpectedScriptEditor(string path)
{
// Show warning, when Unity was started from Rider, but external editor is different https://github.com/JetBrains/resharper-unity/issues/1127
try
{
var args = Environment.GetCommandLineArgs();
var commandlineParser = new CommandLineParser(args);
if (commandlineParser.Options.ContainsKey("-riderPath"))
{
var originRiderPath = commandlineParser.Options["-riderPath"];
var originRealPath = GetEditorRealPath(originRiderPath);
var originVersion = RiderPathLocator.GetBuildNumber(originRealPath);
var version = RiderPathLocator.GetBuildNumber(path);
if (originVersion != null && originVersion != version)
{
Debug.LogWarning("Unity was started by a version of Rider that is not the current default external editor. Advanced integration features cannot be enabled.");
Debug.Log($"Unity was started by Rider {originVersion}, but external editor is set to: {path}");
}
}
}
catch (Exception e)
{
Debug.LogException(e);
}
}
internal static string GetEditorRealPath(string path)
{
if (string.IsNullOrEmpty(path))
{
return path;
}
if (!FileSystemUtil.EditorPathExists(path))
return path;
if (SystemInfo.operatingSystemFamily != OperatingSystemFamily.Windows)
{
var realPath = FileSystemUtil.GetFinalPathName(path);
// case of snap installation
if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.Linux)
{
if (new FileInfo(path).Name.ToLowerInvariant() == "rider" &&
new FileInfo(realPath).Name.ToLowerInvariant() == "snap")
{
var snapInstallPath = "/snap/rider/current/bin/rider.sh";
if (new FileInfo(snapInstallPath).Exists)
return snapInstallPath;
}
}
// in case of symlink
return realPath;
}
return path;
}
public RiderScriptEditor(IDiscovery discovery, IGenerator projectGeneration)
{
m_Discoverability = discovery;
m_ProjectGeneration = projectGeneration;
}
private static string[] defaultExtensions
{
get
{
var customExtensions = new[] {"log"};
return EditorSettings.projectGenerationBuiltinExtensions.Concat(EditorSettings.projectGenerationUserExtensions)
.Concat(customExtensions).Distinct().ToArray();
}
}
private static string[] HandledExtensions
{
get
{
return HandledExtensionsString.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries).Select(s => s.TrimStart('.', '*'))
.ToArray();
}
}
private static string HandledExtensionsString
{
get { return EditorPrefs.GetString("Rider_UserExtensions", string.Join(";", defaultExtensions));}
set { EditorPrefs.SetString("Rider_UserExtensions", value); }
}
private static bool SupportsExtension(string path)
{
var extension = Path.GetExtension(path);
if (string.IsNullOrEmpty(extension))
return false;
// cs is a default extension, which should always be handled
return extension == ".cs" || HandledExtensions.Contains(extension.TrimStart('.'));
}
public void OnGUI()
{
if (RiderScriptEditorData.instance.shouldLoadEditorPlugin)
{
HandledExtensionsString = EditorGUILayout.TextField(new GUIContent("Extensions handled: "), HandledExtensionsString);
}
EditorGUILayout.LabelField("Generate .csproj files for:");
EditorGUI.indentLevel++;
SettingsButton(ProjectGenerationFlag.Embedded, "Embedded packages", "");
SettingsButton(ProjectGenerationFlag.Local, "Local packages", "");
SettingsButton(ProjectGenerationFlag.Registry, "Registry packages", "");
SettingsButton(ProjectGenerationFlag.Git, "Git packages", "");
SettingsButton(ProjectGenerationFlag.BuiltIn, "Built-in packages", "");
#if UNITY_2019_3_OR_NEWER
SettingsButton(ProjectGenerationFlag.LocalTarBall, "Local tarball", "");
#endif
SettingsButton(ProjectGenerationFlag.Unknown, "Packages from unknown sources", "");
SettingsButton(ProjectGenerationFlag.PlayerAssemblies, "Player projects", "For each player project generate an additional csproj with the name 'project-player.csproj'");
RegenerateProjectFiles();
EditorGUI.indentLevel--;
}
void RegenerateProjectFiles()
{
var rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(new GUILayoutOption[] {}));
rect.width = 252;
if (GUI.Button(rect, "Regenerate project files"))
{
m_ProjectGeneration.Sync();
}
}
void SettingsButton(ProjectGenerationFlag preference, string guiMessage, string toolTip)
{
var prevValue = m_ProjectGeneration.AssemblyNameProvider.ProjectGenerationFlag.HasFlag(preference);
var newValue = EditorGUILayout.Toggle(new GUIContent(guiMessage, toolTip), prevValue);
if (newValue != prevValue)
{
m_ProjectGeneration.AssemblyNameProvider.ToggleProjectGeneration(preference);
}
}
public void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles,
string[] importedFiles)
{
m_ProjectGeneration.SyncIfNeeded(addedFiles.Union(deletedFiles).Union(movedFiles).Union(movedFromFiles),
importedFiles);
}
public void SyncAll()
{
AssetDatabase.Refresh();
m_ProjectGeneration.SyncIfNeeded(new string[] { }, new string[] { });
}
[UsedImplicitly]
public static void SyncSolution() // generate-the-sln-file-via-script-or-command-line
{
m_ProjectGeneration.Sync();
}
[UsedImplicitly]
public static void SyncSolutionAndOpenExternalEditor()
{
m_ProjectGeneration.Sync();
CodeEditor.CurrentEditor.OpenProject();
}
public void Initialize(string editorInstallationPath) // is called each time ExternalEditor is changed
{
var prevEditorBuildNumber = RiderScriptEditorData.instance.prevEditorBuildNumber;
RiderScriptEditorData.instance.Invalidate(editorInstallationPath, true);
if (prevEditorBuildNumber.ToVersion() != RiderScriptEditorData.instance.editorBuildNumber.ToVersion()) // in Unity 2019.3 any change in preference causes `Initialize` call
{
m_ProjectGeneration.Sync(); // regenerate csproj and sln for new editor
#if UNITY_2019_3_OR_NEWER
EditorUtility.RequestScriptReload(); // EditorPlugin would get loaded
#else
UnityEditorInternal.InternalEditorUtility.RequestScriptReload();
#endif
}
}
public bool OpenProject(string path, int line, int column)
{
if (path != "" && !SupportsExtension(path)) // Assets - Open C# Project passes empty path here
{
return false;
}
if (!IsUnityScript(path))
{
m_ProjectGeneration.SyncIfNeeded(affectedFiles: new string[] { }, new string[] { });
var fastOpenResult = EditorPluginInterop.OpenFileDllImplementation(path, line, column);
if (fastOpenResult)
return true;
}
if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
{
return OpenOSXApp(path, line, column);
}
var solution = GetSolutionFile(path); // TODO: If solution file doesn't exist resync.
solution = solution == "" ? "" : $"\"{solution}\"";
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = CodeEditor.CurrentEditorInstallation,
Arguments = $"{solution} -l {line} \"{path}\"",
UseShellExecute = true,
}
};
process.Start();
return true;
}
private bool OpenOSXApp(string path, int line, int column)
{
var solution = GetSolutionFile(path);
solution = solution == "" ? "" : $"\"{solution}\"";
var pathArguments = path == "" ? "" : $"-l {line} \"{path}\"";
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "open",
Arguments = $"-n -j \"{CodeEditor.CurrentEditorInstallation}\" --args {solution} {pathArguments}",
CreateNoWindow = true,
UseShellExecute = true,
}
};
process.Start();
return true;
}
private string GetSolutionFile(string path)
{
if (IsUnityScript(path))
{
return Path.Combine(GetBaseUnityDeveloperFolder(), "Projects/CSharp/Unity.CSharpProjects.gen.sln");
}
var solutionFile = m_ProjectGeneration.SolutionFile();
if (File.Exists(solutionFile))
{
return solutionFile;
}
return "";
}
static bool IsUnityScript(string path)
{
if (UnityEditor.Unsupported.IsDeveloperBuild())
{
var baseFolder = GetBaseUnityDeveloperFolder().Replace("\\", "/");
var lowerPath = path.ToLowerInvariant().Replace("\\", "/");
if (lowerPath.Contains((baseFolder + "/Runtime").ToLowerInvariant())
|| lowerPath.Contains((baseFolder + "/Editor").ToLowerInvariant()))
{
return true;
}
}
return false;
}
static string GetBaseUnityDeveloperFolder()
{
return Directory.GetParent(EditorApplication.applicationPath).Parent.Parent.FullName;
}
public bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation)
{
if (FileSystemUtil.EditorPathExists(editorPath) && IsRiderInstallation(editorPath))
{
var info = new RiderPathLocator.RiderInfo(editorPath, false);
installation = new CodeEditor.Installation
{
Name = info.Presentation,
Path = info.Path
};
return true;
}
installation = default;
return false;
}
public static bool IsRiderInstallation(string path)
{
if (IsAssetImportWorkerProcess())
return false;
#if UNITY_2021_1_OR_NEWER
if (UnityEditor.MPE.ProcessService.level == UnityEditor.MPE.ProcessLevel.Secondary)
return false;
#elif UNITY_2020_2_OR_NEWER
if (UnityEditor.MPE.ProcessService.level == UnityEditor.MPE.ProcessLevel.Slave)
return false;
#elif UNITY_2020_1_OR_NEWER
if (Unity.MPE.ProcessService.level == Unity.MPE.ProcessLevel.UMP_SLAVE)
return false;
#endif
if (string.IsNullOrEmpty(path))
return false;
var fileInfo = new FileInfo(path);
var filename = fileInfo.Name.ToLowerInvariant();
return filename.StartsWith("rider", StringComparison.Ordinal);
}
private static bool IsAssetImportWorkerProcess()
{
#if UNITY_2020_2_OR_NEWER
return UnityEditor.AssetDatabase.IsAssetImportWorkerProcess();
#elif UNITY_2019_3_OR_NEWER
return UnityEditor.Experimental.AssetDatabaseExperimental.IsAssetImportWorkerProcess();
#else
return false;
#endif
}
public static string CurrentEditor // works fast, doesn't validate if executable really exists
=> EditorPrefs.GetString("kScriptsDefaultApp");
public CodeEditor.Installation[] Installations => m_Discoverability.PathCallback();
private void CreateSolutionIfDoesntExist()
{
if (!m_ProjectGeneration.HasSolutionBeenGenerated())
{
m_ProjectGeneration.Sync();
}
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using System.Linq;
using Packages.Rider.Editor.Util;
using Rider.Editor.Util;
using UnityEditor;
using UnityEngine;
namespace Packages.Rider.Editor
{
internal class RiderScriptEditorData : ScriptableSingleton<RiderScriptEditorData>
{
[SerializeField] internal bool hasChanges = true; // sln/csproj files were changed
[SerializeField] internal bool shouldLoadEditorPlugin;
[SerializeField] internal bool initializedOnce;
[SerializeField] internal SerializableVersion editorBuildNumber;
[SerializeField] internal SerializableVersion prevEditorBuildNumber;
[SerializeField] internal RiderPathLocator.ProductInfo productInfo;
[SerializeField] internal string[] activeScriptCompilationDefines;
public void Init()
{
if (editorBuildNumber == null)
{
Invalidate(RiderScriptEditor.CurrentEditor);
}
}
public void InvalidateSavedCompilationDefines()
{
activeScriptCompilationDefines = EditorUserBuildSettings.activeScriptCompilationDefines;
}
public bool HasChangesInCompilationDefines()
{
if (activeScriptCompilationDefines == null)
return false;
return !EditorUserBuildSettings.activeScriptCompilationDefines.SequenceEqual(activeScriptCompilationDefines);
}
public void Invalidate(string editorInstallationPath, bool shouldInvalidatePrevEditorBuildNumber = false)
{
var riderBuildNumber = RiderPathLocator.GetBuildNumber(editorInstallationPath);
editorBuildNumber = riderBuildNumber.ToSerializableVersion();
if (shouldInvalidatePrevEditorBuildNumber)
prevEditorBuildNumber = editorBuildNumber;
productInfo = RiderPathLocator.GetBuildVersion(editorInstallationPath);
if (riderBuildNumber == null) // if we fail to parse for some reason
shouldLoadEditorPlugin = true;
shouldLoadEditorPlugin = riderBuildNumber >= new Version("191.7141.156");
if (RiderPathUtil.IsRiderDevEditor(editorInstallationPath))
{
shouldLoadEditorPlugin = true;
editorBuildNumber = new SerializableVersion(new Version("999.999.999.999"));
}
}
}
}

View File

@@ -0,0 +1,36 @@
#if TEST_FRAMEWORK
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEditor;
namespace Packages.Rider.Editor.UnitTesting
{
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[UsedImplicitly] // from Rider Unity plugin
public class CallbackData : ScriptableSingleton<CallbackData>
{
public bool isRider;
[UsedImplicitly] public static event EventHandler Changed = (sender, args) => { };
internal void RaiseChangedEvent()
{
Changed(null, EventArgs.Empty);
}
public List<TestEvent> events = new List<TestEvent>();
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[UsedImplicitly]
public void Clear()
{
events.Clear();
}
}
}
#endif

View File

@@ -0,0 +1,18 @@
#if TEST_FRAMEWORK
using UnityEditor;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
[InitializeOnLoad]
internal static class CallbackInitializer
{
static CallbackInitializer()
{
if (CallbackData.instance.isRider)
ScriptableObject.CreateInstance<TestRunnerApi>().RegisterCallbacks(ScriptableObject.CreateInstance<TestsCallback>(), 0);
}
}
}
#endif

View File

@@ -0,0 +1,91 @@
using JetBrains.Annotations;
using UnityEngine;
#if TEST_FRAMEWORK
using UnityEditor;
using UnityEditor.TestTools.TestRunner.Api;
#else
using System;
#endif
namespace Packages.Rider.Editor.UnitTesting
{
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
[UsedImplicitly]
public static class RiderTestRunner
{
#if TEST_FRAMEWORK
private static readonly TestsCallback Callback = ScriptableObject.CreateInstance<TestsCallback>();
#endif
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
/// <param name="sessionId"></param>
/// <param name="testMode"></param>
/// <param name="assemblyNames"></param>
/// <param name="testNames"></param>
/// <param name="categoryNames"></param>
/// <param name="groupNames"></param>
/// <param name="buildTarget"></param>
/// <param name="callbacksHandlerCodeBase"></param>
/// <param name="callbacksHandlerTypeName"></param>
/// <param name="callbacksHandlerDependencies"></param>
[UsedImplicitly]
public static void RunTestsWithSyncCallbacks(string sessionId, int testMode, string[] assemblyNames,
string[] testNames, string[] categoryNames, string[] groupNames, int? buildTarget,
string callbacksHandlerCodeBase, string callbacksHandlerTypeName, string[] callbacksHandlerDependencies)
{
#if !TEST_FRAMEWORK
Debug.LogError("Update Test Framework package to v.1.1.1+ to run tests from Rider.");
throw new NotSupportedException("Incompatible `Test Framework` package in Unity. Update to v.1.1.1+");
#else
SyncTestRunEventsHandler.instance.InitRun(sessionId, callbacksHandlerCodeBase, callbacksHandlerTypeName, callbacksHandlerDependencies);
RunTests(testMode, assemblyNames, testNames, categoryNames, groupNames, buildTarget);
#endif
}
/// <summary>
/// Is called by Rider Unity plugin via reflections
/// </summary>
/// <param name="testMode"></param>
/// <param name="assemblyNames"></param>
/// <param name="testNames"></param>
/// <param name="categoryNames"></param>
/// <param name="groupNames"></param>
/// <param name="buildTarget"></param>
[UsedImplicitly]
public static void RunTests(int testMode, string[] assemblyNames, string[] testNames, string[] categoryNames, string[] groupNames, int? buildTarget)
{
#if !TEST_FRAMEWORK
Debug.LogError("Update Test Framework package to v.1.1.1+ to run tests from Rider.");
throw new NotSupportedException("Incompatible `Test Framework` package in Unity. Update to v.1.1.1+");
#else
CallbackData.instance.isRider = true;
var api = ScriptableObject.CreateInstance<TestRunnerApi>();
var settings = new ExecutionSettings();
var filter = new Filter
{
assemblyNames = assemblyNames,
testNames = testNames,
categoryNames = categoryNames,
groupNames = groupNames,
targetPlatform = (BuildTarget?) buildTarget
};
if (testMode > 0) // for future use - test-framework would allow running both Edit and Play test at once
filter.testMode = (TestMode) testMode;
settings.filters = new []{
filter
};
api.Execute(settings);
api.UnregisterCallbacks(Callback); // avoid multiple registrations
api.RegisterCallbacks(Callback); // This can be used to receive information about when the test suite and individual tests starts and stops. Provide this with a scriptable object implementing ICallbacks
#endif
}
}
}

View File

@@ -0,0 +1,49 @@
#if TEST_FRAMEWORK
using NUnit.Framework.Interfaces;
using Packages.Rider.Editor.UnitTesting;
using UnityEngine.TestRunner;
[assembly: TestRunCallback(typeof(SyncTestRunCallback))]
namespace Packages.Rider.Editor.UnitTesting
{
public class SyncTestRunCallback : ITestRunCallback
{
public void RunStarted(ITest testsToRun)
{
}
public void RunFinished(ITestResult testResults)
{
SyncTestRunEventsHandler.instance.OnRunFinished();
}
public void TestStarted(ITest test)
{
if (!test.IsSuite)
SyncTestRunEventsHandler.instance.OnTestStarted(GenerateId(test));
}
public void TestFinished(ITestResult result)
{
if (!result.Test.IsSuite)
SyncTestRunEventsHandler.instance.OnTestFinished();
}
// https://jetbrains.team/p/net/code/dotnet-libs/files/f04cde7d1dd70ee13bf5532e30f929b9b5ed08a4/ReSharperTestRunner/src/Adapters/TestRunner.Adapters.NUnit3/RemoteTaskDepot.cs?tab=source&line=129
private static string GenerateId(ITest node)
{
// ES: Parameterized tests defined in a parametrized test fixture, though
// constructed for a particular test fixture with the given parameter, have identical fullname that does
// not include parameters of parent testfixture (name of the without parameters is used instead).
// This leads to 'Test with {id} id is already running' message.
var typeName = node.GetType().Name;
if (typeName == "ParameterizedMethod" ||
typeName == "GenericMethod")
return $"{node.Parent.FullName}.{node.Name}";
return node.FullName;
}
}
}
#endif

View File

@@ -0,0 +1,148 @@
#if TEST_FRAMEWORK
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
internal class SyncTestRunEventsHandler : ScriptableSingleton<SyncTestRunEventsHandler>
{
[SerializeField] private string m_SessionId;
[SerializeField] private string m_HandlerCodeBase;
[SerializeField] private string m_HandlerTypeName;
[SerializeField] private string[] m_HandlerDependencies;
[SerializeField] private bool m_RunInitialized;
private object m_Handler;
private MethodInfo m_OnSessionStartedMethodInfo;
private MethodInfo m_OnTestStartedMethodInfo;
private MethodInfo m_OnTestFinishedMethodInfo;
private MethodInfo m_OnSessionFinishedMethodInfo;
internal void InitRun(string sessionId, string handlerCodeBase, string handlerTypeName, string[] handlerDependencies)
{
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log("Rider Test Runner: initializing sync callbacks handler: " +
$"sessionId={sessionId}, " +
$"codeBase={handlerCodeBase}, " +
$"typeName={handlerTypeName}, " +
$"dependencies={(handlerDependencies == null ? "" : string.Join("; ", handlerDependencies))}");
m_SessionId = sessionId;
m_HandlerCodeBase = handlerCodeBase;
m_HandlerTypeName = handlerTypeName;
m_HandlerDependencies = handlerDependencies;
m_RunInitialized = true;
CreateHandlerInstance();
SafeInvokeHandlerMethod(m_OnSessionStartedMethodInfo, Array.Empty<object>());
}
private void OnEnable()
{
if (m_RunInitialized)
CreateHandlerInstance();
}
internal void OnTestStarted(string testId)
{
if (m_RunInitialized)
SafeInvokeHandlerMethod(m_OnTestStartedMethodInfo, new object[] {testId});
}
internal void OnTestFinished()
{
if (m_RunInitialized)
SafeInvokeHandlerMethod(m_OnTestFinishedMethodInfo, Array.Empty<object>());
}
internal void OnRunFinished()
{
if (!m_RunInitialized)
return;
SafeInvokeHandlerMethod(m_OnSessionFinishedMethodInfo, Array.Empty<object>());
CleanUp();
m_RunInitialized = false;
}
private void SafeInvokeHandlerMethod(MethodInfo methodInfo, object[] args)
{
try
{
methodInfo?.Invoke(m_Handler, args);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private void CreateHandlerInstance()
{
try
{
if (m_HandlerDependencies != null)
foreach (var dependency in m_HandlerDependencies)
{
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: loading assembly from {dependency}");
Assembly.LoadFrom(dependency);
}
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: loading assembly from {m_HandlerCodeBase}");
var assembly = Assembly.LoadFrom(m_HandlerCodeBase);
var type = assembly.GetType(m_HandlerTypeName);
if (type == null)
{
Debug.LogError($"Rider Test Runner: type '{m_HandlerTypeName}' not found in assembly '{assembly.FullName}'");
return;
}
if (PluginSettings.SelectedLoggingLevel >= LoggingLevel.TRACE)
Debug.Log($"Rider Test Runner: creating instance of type '{type.AssemblyQualifiedName}'");
m_Handler = Activator.CreateInstance(type, m_SessionId);
m_OnSessionStartedMethodInfo = type.GetMethod("OnSessionStarted", BindingFlags.Instance | BindingFlags.Public);
if (m_OnSessionStartedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnSessionStarted method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnTestStartedMethodInfo = type.GetMethod("OnTestStarted", BindingFlags.Instance | BindingFlags.Public);
if (m_OnTestStartedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnTestStarted method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnTestFinishedMethodInfo = type.GetMethod("OnTestFinished", BindingFlags.Instance | BindingFlags.Public);
if (m_OnTestFinishedMethodInfo == null)
{
Debug.LogError($"Rider Test Runner: OnTestFinished method not found in type='{type.AssemblyQualifiedName}'");
return;
}
m_OnSessionFinishedMethodInfo = type.GetMethod("OnSessionFinished", BindingFlags.Instance | BindingFlags.Public);
if (m_OnSessionFinishedMethodInfo == null)
Debug.LogError($"Rider Test Runner: OnSessionFinished method not found in type='{type.AssemblyQualifiedName}'");
}
catch (Exception e)
{
Debug.LogException(e);
}
}
private void CleanUp()
{
m_Handler = null;
m_OnSessionStartedMethodInfo = null;
m_OnSessionFinishedMethodInfo = null;
m_OnTestStartedMethodInfo = null;
m_OnTestFinishedMethodInfo = null;
}
}
}
#endif

View File

@@ -0,0 +1,39 @@
#if TEST_FRAMEWORK
using System;
using NUnit.Framework.Interfaces;
namespace Packages.Rider.Editor.UnitTesting
{
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[Serializable]
public enum EventType { TestStarted, TestFinished, RunFinished, RunStarted } // do not reorder
/// <summary>
/// Is used by Rider Unity plugin by reflection
/// </summary>
[Serializable]
public class TestEvent
{
public EventType type;
public string id;
public string assemblyName;
public string output;
public TestStatus testStatus;
public double duration;
public string parentId;
public TestEvent(EventType type, string id, string assemblyName, string output, double duration, TestStatus testStatus, string parentID)
{
this.type = type;
this.id = id;
this.assemblyName = assemblyName;
this.output = output;
this.testStatus = testStatus;
this.duration = duration;
parentId = parentID;
}
}
}
#endif

View File

@@ -0,0 +1,101 @@
#if TEST_FRAMEWORK
using System;
using System.Text;
using UnityEditor.TestTools.TestRunner.Api;
using UnityEngine;
namespace Packages.Rider.Editor.UnitTesting
{
public class TestsCallback : ScriptableObject, IErrorCallbacks
{
public void RunFinished(ITestResultAdaptor result)
{
CallbackData.instance.isRider = false;
CallbackData.instance.events.Add(
new TestEvent(EventType.RunFinished, "", "","", 0, ParseTestStatus(result.TestStatus), ""));
CallbackData.instance.RaiseChangedEvent();
}
public void RunStarted(ITestAdaptor testsToRun)
{
CallbackData.instance.events.Add(
new TestEvent(EventType.RunStarted, "", "","", 0, NUnit.Framework.Interfaces.TestStatus.Passed, ""));
CallbackData.instance.RaiseChangedEvent();
}
public void TestStarted(ITestAdaptor result)
{
if (result.Method == null) return;
CallbackData.instance.events.Add(
new TestEvent(EventType.TestStarted, GenerateId(result), result.Method.TypeInfo.Assembly.GetName().Name, "", 0, NUnit.Framework.Interfaces.TestStatus.Passed, GenerateId(result.Parent)));
CallbackData.instance.RaiseChangedEvent();
}
public void TestFinished(ITestResultAdaptor result)
{
if (result.Test.Method == null) return;
CallbackData.instance.events.Add(
new TestEvent(EventType.TestFinished, GenerateId(result.Test), result.Test.Method.TypeInfo.Assembly.GetName().Name, ExtractOutput(result), (result.EndTime-result.StartTime).Milliseconds, ParseTestStatus(result.TestStatus), GenerateId(result.Test.Parent)));
CallbackData.instance.RaiseChangedEvent();
}
public void OnError(string message)
{
CallbackData.instance.isRider = false;
CallbackData.instance.events.Add(
new TestEvent(EventType.RunFinished, "", "",message, 0, NUnit.Framework.Interfaces.TestStatus.Failed, ""));
CallbackData.instance.RaiseChangedEvent();
}
// see explanation in https://jetbrains.team/p/net/code/dotnet-libs/files/f04cde7d1dd70ee13bf5532e30f929b9b5ed08a4/ReSharperTestRunner/src/Adapters/TestRunner.Adapters.NUnit3/RemoteTaskDepot.cs?tab=source&line=129
private static string GenerateId(ITestAdaptor node)
{
// ES: Parameterized tests defined in a parametrized test fixture, though
// constructed for a particular test fixture with the given parameter, have identical fullname that does
// not include parameters of parent testfixture (name of the without parameters is used instead).
// This leads to 'Test with {id} id is already running' message.
if (node.TypeInfo == null)
return $"{node.Parent.FullName}.{node.Name}";
return node.FullName;
}
private static NUnit.Framework.Interfaces.TestStatus ParseTestStatus(TestStatus testStatus)
{
return (NUnit.Framework.Interfaces.TestStatus)Enum.Parse(typeof(NUnit.Framework.Interfaces.TestStatus), testStatus.ToString());
}
private static string ExtractOutput(ITestResultAdaptor testResult)
{
var stringBuilder = new StringBuilder();
if (testResult.Message != null)
{
stringBuilder.AppendLine("Message: ");
stringBuilder.AppendLine(testResult.Message);
}
if (!string.IsNullOrEmpty(testResult.Output))
{
stringBuilder.AppendLine("Output: ");
stringBuilder.AppendLine(testResult.Output);
}
if (!string.IsNullOrEmpty(testResult.StackTrace))
{
stringBuilder.AppendLine("Stacktrace: ");
stringBuilder.AppendLine(testResult.StackTrace);
}
var result = stringBuilder.ToString();
if (result.Length > 0)
return result;
return testResult.Output ?? string.Empty;
}
}
}
#endif

View File

@@ -0,0 +1,36 @@
using System.Collections.Generic;
namespace Packages.Rider.Editor.Util
{
internal class CommandLineParser
{
public Dictionary<string, string> Options = new Dictionary<string, string>();
public CommandLineParser(string[] args)
{
var i = 0;
while (i < args.Length)
{
var arg = args[i];
if (!arg.StartsWith("-"))
{
i++;
continue;
}
string value = null;
if (i + 1 < args.Length && !args[i + 1].StartsWith("-"))
{
value = args[i + 1];
i++;
}
if (!(Options.ContainsKey(arg)))
{
Options.Add(arg, value);
}
i++;
}
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using JetBrains.Annotations;
using UnityEngine;
namespace Packages.Rider.Editor.Util
{
internal static class FileSystemUtil
{
[NotNull]
public static string GetFinalPathName([NotNull] string path)
{
if (path == null) throw new ArgumentNullException("path");
// up to MAX_PATH. MAX_PATH on Linux currently 4096, on Mac OS X 1024
// doc: http://man7.org/linux/man-pages/man3/realpath.3.html
var sb = new StringBuilder(8192);
var result = LibcNativeInterop.realpath(path, sb);
if (result == IntPtr.Zero)
{
throw new Win32Exception($"{path} was not resolved.");
}
return new FileInfo(sb.ToString()).FullName;
}
public static string FileNameWithoutExtension(string path)
{
if (string.IsNullOrEmpty(path))
{
return "";
}
var indexOfDot = -1;
var indexOfSlash = 0;
for (var i = path.Length - 1; i >= 0; i--)
{
if (indexOfDot == -1 && path[i] == '.')
{
indexOfDot = i;
}
if (indexOfSlash == 0 && path[i] == '/' || path[i] == '\\')
{
indexOfSlash = i + 1;
break;
}
}
if (indexOfDot == -1)
{
indexOfDot = path.Length;
}
return path.Substring(indexOfSlash, indexOfDot - indexOfSlash);
}
public static bool EditorPathExists(string editorPath)
{
return SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX && new DirectoryInfo(editorPath).Exists
|| SystemInfo.operatingSystemFamily != OperatingSystemFamily.MacOSX && new FileInfo(editorPath).Exists;
}
}
}

View File

@@ -0,0 +1,12 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace Packages.Rider.Editor.Util
{
internal static class LibcNativeInterop
{
[DllImport("libc", SetLastError = true)]
public static extern IntPtr realpath(string path, StringBuilder resolved_path);
}
}

View File

@@ -0,0 +1,30 @@
using JetBrains.Annotations;
using Packages.Rider.Editor;
using Unity.CodeEditor;
// ReSharper disable once CheckNamespace
namespace JetBrains.Rider.Unity.Editor
{
/// <summary>
/// Is called via commandline from Rider Notification after checking out from source control.
/// </summary>
[UsedImplicitly]
public static class RiderMenu
{
/// <summary>
/// Is called via commandline from Rider Notification after checking out from source control.
/// </summary>
[UsedImplicitly]
public static void MenuOpenProject()
{
if (RiderScriptEditor.IsRiderInstallation(RiderScriptEditor.CurrentEditor))
{
// Force the project files to be sync
CodeEditor.CurrentEditor.SyncAll();
// Load Project
CodeEditor.CurrentEditor.OpenProject();
}
}
}
}

View File

@@ -0,0 +1,14 @@
using System.IO;
namespace Rider.Editor.Util
{
internal static class RiderPathUtil
{
public static bool IsRiderDevEditor(string editorPath)
{
if (editorPath == null)
return false;
return "rider-dev".Equals(Path.GetFileNameWithoutExtension(editorPath));
}
}
}

View File

@@ -0,0 +1,51 @@
using System;
namespace Packages.Rider.Editor.Util
{
[Serializable]
internal class SerializableVersion
{
public SerializableVersion(Version version)
{
Major = version.Major;
Minor = version.Minor;
if (version.Build >= 0)
Build = version.Build;
if (version.Revision >= 0)
Revision = version.Revision;
}
public int Build;
public int Major;
public int Minor;
public int Revision;
}
internal static class VersionExtension
{
public static SerializableVersion ToSerializableVersion(this Version version)
{
if (version == null)
return null;
return new SerializableVersion(version);
}
public static Version ToVersion(this SerializableVersion serializableVersion)
{
if (serializableVersion == null)
return null;
var build = serializableVersion.Build;
if (build < 0)
build = 0;
var revision = serializableVersion.Revision;
if (revision < 0)
revision = 0;
return new Version(serializableVersion.Major, serializableVersion.Minor, build,
revision);
}
}
}

View File

@@ -0,0 +1,27 @@
{
"name": "Unity.Rider.Editor",
"rootNamespace": "Packages",
"references": [
"GUID:0acc523941302664db1f4e527237feb3",
"GUID:27619889b8ba8c24980f49ee34dbb44a"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.test-framework",
"expression": "1.1.1",
"define": "TEST_FRAMEWORK"
}
],
"noEngineReferences": false
}

View File

@@ -0,0 +1,22 @@
{
"name": "com.unity.ide.rider",
"displayName": "JetBrains Rider Editor",
"description": "The JetBrains Rider Editor package provides an integration for using the JetBrains Rider IDE as a code editor for Unity. It adds support for generating .csproj files for code completion and auto-discovery of installations.",
"version": "3.0.6",
"unity": "2019.2",
"unityRelease": "6f1",
"dependencies": {
"com.unity.ext.nunit": "1.0.6"
},
"relatedPackages": {
"com.unity.ide.rider.tests": "3.0.6"
},
"upmCi": {
"footprint": "2ae3fdf63a5d6c16bc62ceb0bb8980fe330ced80"
},
"repository": {
"url": "https://github.cds.internal.unity3d.com/unity/com.unity.ide.rider.git",
"type": "git",
"revision": "0be4afe0ac726df5939a6ce50f8b7575968c5d6f"
}
}