Beispiel #1
0
        private static string GetRelativePathForAssemblyFilePath(string fullPath)
        {
            if (fullPath == null)
            {
                throw new ArgumentNullException("fullPath");
            }

            if (fullPath.StartsWith(Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
            {
                // Path is inside the project dir
                var relativePath = fullPath.Substring(Environment.CurrentDirectory.Length + 1).Replace('\\', '/');

                // See if there is an asmdef file for this assembly - use it if so
                var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(fullPath);
                if (asmdefPath != null)
                {
                    relativePath = asmdefPath;
                }

                // If we don't have a valid path, or it's inside the Assets folder, it's not part of a package
                if (string.IsNullOrEmpty(relativePath) || relativePath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if (relativePath.StartsWith(Folders.GetPackagesMountPoint() + "/", StringComparison.OrdinalIgnoreCase))
                {
                    return(relativePath);
                }
            }
            return(String.Empty);
        }
Beispiel #2
0
        static void OnAssemblyCompilationStarted(string name)
        {
            try
            {
                string assemblyName     = Path.GetFileNameWithoutExtension(name);
                string assemblyFilename = assemblyName + ".dll";

                if (assemblyName != typeof(Core).Assembly.GetName().Name)
                {
                    return;
                }

                Type tEditorCompilationInterface = Type.GetType("UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface, UnityEditor");
                var  compilerTasks  = tEditorCompilationInterface.Get("Instance").Get("compilationTask").Get("compilerTasks") as IDictionary;
                var  scriptAssembly = compilerTasks.Keys.Cast <object>().FirstOrDefault(x => (x.Get("Filename") as string) == assemblyFilename);

                // Should change compiler process for the assembly?
                var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);
                var setting    = Settings.GetAtPath(asmdefPath);
                if (!setting.SholdChangeCompilerProcess)
                {
                    return;
                }

                // Create new compiler to recompile.
                Log("Assembly compilation started: <b>{0} should be recompiled.</b>", assemblyName);
                Core.ChangeCompilerProcess(compilerTasks[scriptAssembly], setting);
            }
            catch (Exception e)
            {
                UnityEngine.Debug.LogException(new Exception(k_LogHeader + e.Message, e.InnerException));
            }
        }
        public static PackageInfo FindForAssembly(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            string fullPath = assembly.Location;

            // See if there is an asmdef file for this assembly - use it if so
            var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(fullPath);

            if (!String.IsNullOrEmpty(asmdefPath))
            {
                return(FindForAssetPath(asmdefPath));
            }

            // No asmdef - this is a precompiled DLL.
            // Do a scan through all packages for one that owns the directory in which it is.
            foreach (var package in GetAll())
            {
                if (fullPath.StartsWith(package.resolvedPath + Path.DirectorySeparatorChar))
                {
                    return(package);
                }
            }

            return(null);
        }
Beispiel #4
0
        private static string OnGeneratedCSProject(string path, string content)
        {
            var assemblyName = Path.GetFileNameWithoutExtension(path);
            var asmDefPath   = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);
            var baseDir      = Path.GetDirectoryName(asmDefPath) ?? "Assets/";

            var templateFiles = Directory.GetFiles(baseDir, "*.tt", SearchOption.AllDirectories);

            if (templateFiles.Length > 0)
            {
                var childAsmDefDirs = Directory.GetFiles(baseDir, "*.asmdef", SearchOption.AllDirectories)
                                      .Select(Path.GetDirectoryName)
                                      .Where(v => baseDir != v)
                                      .ToList();

                bool IsOtherAsmDefTarget(string templatePath) => childAsmDefDirs
                .Any(v => templatePath.StartsWith(v, StringComparison.Ordinal));

                var targets = templateFiles
                              .Where(v => !IsOtherAsmDefTarget(v))
                              .ToList();

                if (targets.Count > 0)
                {
                    return(AppendTemplateContents(content, targets));
                }
            }

            return(content);
        }
        internal static string GetGroupName(this Assembly assembly)
        {
            var path_assemblyDef = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly.GetName().Name);

            bool TryGetPackageName(string path, out string packageName)
            {
                // TODO: handle "Assets/" location
                const string packageKey = "Packages/";

                if (!string.IsNullOrEmpty(path) && path.StartsWith(packageKey))
                {
                    var sub0 = path.Substring(packageKey.Length);
                    packageName = sub0.Substring(0, sub0.IndexOfAny(new[] { '/', '\\' }));
                    // get last part
                    packageName = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal) + 1);
                    packageName = packageName.Replace("-", " ");

                    // packageName = ObjectNames.NicifyVariableName(packageName);
                    var textInfo = new CultureInfo("en-US", false).TextInfo;
                    packageName = textInfo.ToTitleCase(packageName);
                    return(true);
                }

                packageName = null;
                return(false);
            }

            if (TryGetPackageName(path_assemblyDef, out var pn))
            {
                return(pn);
            }

            // if assembly name could not be found
            return(assembly.GetName().Name);
        }
Beispiel #6
0
        public static void ReplaceWithAssembly()
        {
            Debug.Assert(Selection.activeObject != null);

            EditorUtility.DisplayProgressBar("Replacing source with assembly", "Getting things ready...", 0);

            var assetPath              = AssetDatabase.GetAssetPath(Selection.activeObject);
            var directoryPath          = new FileInfo(assetPath).Directory?.FullName;
            var assemblyDefinitionText = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(assetPath).text;
            var scriptAssemblyData     = CustomScriptAssemblyData.FromJson(assemblyDefinitionText);
            var fromAssemblyName       = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(scriptAssemblyData.name);

            Debug.Assert(!string.IsNullOrEmpty(scriptAssemblyData.name));
            Debug.Assert(fromAssemblyName == assetPath, "Failed to get the proper assembly name!");

            if (CompilationPipeline.GetAssemblies(AssembliesType.Editor).ReplaceSourceWithAssembly(ref scriptAssemblyData, directoryPath) ||
                CompilationPipeline.GetAssemblies(AssembliesType.Player).ReplaceSourceWithAssembly(ref scriptAssemblyData, directoryPath))
            {
                EditorUtility.DisplayProgressBar("Replacing source with assembly", "Saving source meta data for later...", 0.95f);
                File.WriteAllText(assetPath, CustomScriptAssemblyData.ToJson(scriptAssemblyData));
                File.WriteAllText($"{Path.GetFullPath(assetPath).Hide()}{JSON}", JsonUtility.ToJson(scriptAssemblyData.Source, true));
            }
            else
            {
                Debug.LogError("Failed to replace source code with assembly!");
            }

            if (!EditorApplication.isUpdating)
            {
                AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
            }

            EditorUtility.ClearProgressBar();
        }
        private List <string> GetAssetsReferencedFromAssemblyDefinition(string assetPath)
        {
            var result = new List <string>();

            var asset = AssetDatabase.LoadAssetAtPath <UnityEditorInternal.AssemblyDefinitionAsset>(assetPath);
            var data  = JsonUtility.FromJson <AssemblyDefinitionData>(asset.text);

            if (data.references != null && data.references.Length > 0)
            {
                foreach (var reference in data.references)
                {
#if !UNITY_2019_1_OR_NEWER
                    var assemblyDefinitionFilePathFromAssemblyName = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(reference);
#else
                    var assemblyDefinitionFilePathFromAssemblyName = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference(reference);
#endif
                    if (!string.IsNullOrEmpty(assemblyDefinitionFilePathFromAssemblyName))
                    {
                        assemblyDefinitionFilePathFromAssemblyName = CSPathTools.EnforceSlashes(assemblyDefinitionFilePathFromAssemblyName);
                        result.Add(assemblyDefinitionFilePathFromAssemblyName);
                    }
                }
            }

            data.references = null;

            return(result);
        }
Beispiel #8
0
        void HandleARKitFaceTrackingAssembly(bool faceTrackingEnabled)
        {
            bool needToUpdate = false;

            var faceTrackingAssemblyPath =
                CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName("Unity.XR.ARKit.FaceTracking");
            var faceTrackingAssembly = JsonUtility.FromJson <AssemblyDefinitionType>(File.ReadAllText(faceTrackingAssemblyPath));

            if (faceTrackingEnabled)
            {
                //enable face tracking
                if (!faceTrackingAssembly.includePlatforms.Contains("iOS"))
                {
                    faceTrackingAssembly.includePlatforms.Add("iOS");
                    needToUpdate = true;
                }
            }
            else
            {
                //disable face tracking
                if (faceTrackingAssembly.includePlatforms.Contains("iOS"))
                {
                    faceTrackingAssembly.includePlatforms.Remove("iOS");
                    needToUpdate = true;
                }
            }

            if (needToUpdate)
            {
                File.WriteAllText(faceTrackingAssemblyPath, JsonUtility.ToJson(faceTrackingAssembly, true));
                AssetDatabase.ImportAsset(faceTrackingAssemblyPath);
            }
        }
Beispiel #9
0
        private static IEnumerable <NPath> AllAssemblyDefinitions()
        {
            var paths = new HashSet <string>();
            var guids = AssetDatabase.FindAssets("t:AssemblyDefinitionAsset");

            foreach (var guid in guids)
            {
                var asmdefPath = AssetDatabase.GUIDToAssetPath(guid);
                paths.Add(asmdefPath);
            }

            foreach (var assembly in CompilationPipeline.GetAssemblies())
            {
                var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly.name);
                if (path == null)
                {
                    continue;
                }
                paths.Add(path);
            }

            foreach (var path in paths.OrderBy(p => p))
            {
                // this creates a world of problems
                //if (AssemblyDefinitionUtility.IsRuntimeAssembly(path))
                {
                    yield return(new NPath(path));
                }
            }
        }
Beispiel #10
0
        private static void FixPaths()
        {
            if (string.IsNullOrEmpty(EditorUtils.dotweenDir)) // It's important to trigger default calculation
            {
                return;
            }

            string pluginPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName("Modules.DOTween");

            pluginPath = $"{Application.dataPath}{pluginPath.Substring(6)}"; // Trim double Assets
            pluginPath = Path.GetDirectoryName(pluginPath.Replace("\\", "/"));

            SetPrivateField(typeof(EditorUtils), "_dotweenDir", $"{pluginPath}/DOTween/");
            SetPrivateField(typeof(EditorUtils), "_dotweenProDir", $"{pluginPath}/DOTweenPro/");
            SetPrivateField(typeof(EditorUtils), "_demigiantDir", pluginPath);
            SetPrivateField(typeof(EditorUtils), "_dotweenProEditorDir", $"{pluginPath}/Editor/DOTweenPro/");
            SetPrivateField(typeof(EditorUtils), "_dotweenModulesDir", $"{pluginPath}/DOTween/Modules/");
            SetPrivateField(typeof(EditorUtils), "_editorADBDir", $"{pluginPath.Substring(Application.dataPath.Length + 1)}/Editor/DOTween/");


            void SetPrivateField(Type type, string fieldName, string fieldValue)
            {
                FieldInfo fieldInfo = type.GetField(fieldName, BindingFlags.Static | BindingFlags.NonPublic);

                if (fieldInfo != null)
                {
                    fieldInfo.SetValue(null, fieldValue);
                }
                else
                {
                    Debug.LogWarning($"Can't file field {fieldName} in type {type}!");
                }
            }
        }
Beispiel #11
0
        static RecompileRequest()
        {
            var assemblyName = typeof(RecompileRequest).Assembly.GetName().Name;

            if (assemblyName == "Coffee.AsmdefEx")
            {
                return;
            }

            // Should change compiler process for the assembly?
            var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);
            var setting    = Settings.GetAtPath(asmdefPath);

            if (!setting.SholdChangeCompilerProcess)
            {
                return;
            }

            if (Core.LogEnabled)
            {
                UnityEngine.Debug.LogFormat("<b>Request to recompile: {0} ({1})</b>", assemblyName, asmdefPath);
            }

            AssetDatabase.ImportAsset(asmdefPath);
        }
        static string GetTemplatesFolder()
        {
            var asmdefPath   = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(k_MarsEditorAssembly);
            var asmdefFolder = Path.GetDirectoryName(asmdefPath);

            return($"{asmdefFolder}/Scripts/CodeGen/Templates/");
        }
Beispiel #13
0
        static void SetAutoRef(string assName, bool val)
        {
            string asmdef = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assName);
            string asmdefText;

            using (StreamReader reader = new StreamReader(asmdef))
                asmdefText = reader.ReadToEnd();

            string newText = "\"autoReferenced\": " + (val? "true":"false");

            if (asmdefText.Contains("\"autoReferenced\": false"))
            {
                asmdefText = asmdefText.Replace("\"autoReferenced\": false", newText);
            }
            else if (asmdefText.Contains("\"autoReferenced\": true"))
            {
                asmdefText = asmdefText.Replace("\"autoReferenced\": true", newText);
            }
            else
            {
                asmdefText = asmdefText.Replace("}", newText + "\n}");
            }

            using (StreamWriter writer = new StreamWriter(asmdef))
                writer.Write(asmdefText);

            AssetDatabase.Refresh();
        }
        private void UpgradeScripts()
        {
#if UNITY_2017_3_OR_NEWER
            if (!string.IsNullOrEmpty(CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName("Unity.TextMeshPro")))
            {
                textMeshProAssemblyDefinitionName = "Unity.TextMeshPro";
            }
            else
            {
                string[] tmpScriptGuid = AssetDatabase.FindAssets("TextMeshProUGUI t:MonoScript");
                if (tmpScriptGuid != null && tmpScriptGuid.Length > 0)
                {
                    textMeshProAssemblyDefinitionName = CompilationPipeline.GetAssemblyNameFromScriptPath(AssetDatabase.GUIDToAssetPath(tmpScriptGuid[0]));
                }
            }
#endif

            stringBuilder.Length = 0;

            int progressCurrent = 0;
#if UNITY_2017_3_OR_NEWER
            int progressTotal = scriptsToUpgrade.EnabledCount + assemblyDefinitionFilesToUpgrade.EnabledCount;
#else
            int progressTotal = scriptsToUpgrade.EnabledCount;
#endif

            try
            {
                foreach (string script in scriptsToUpgrade)
                {
                    EditorUtility.DisplayProgressBar("Upgrading scripts...", script, (float)progressCurrent / progressTotal);
                    progressCurrent++;

                    UpgradeScript(script);
                }

#if UNITY_2017_3_OR_NEWER
                foreach (string assemblyDefinitionFile in assemblyDefinitionFilesToUpgrade)
                {
                    EditorUtility.DisplayProgressBar("Upgrading Assembly Definition Files...", assemblyDefinitionFile, (float)progressCurrent / progressTotal);
                    progressCurrent++;

                    UpgradeAssemblyDefinitionFile(assemblyDefinitionFile);
                }
#endif
            }
            finally
            {
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Insert(0, "<b>Upgrade Scripts Logs:</b>\n");
                    Debug.Log(stringBuilder.ToString());
                }

                EditorUtility.ClearProgressBar();
                AssetDatabase.Refresh();
            }
        }
Beispiel #15
0
        internal static AssemblyInfo AssemblyInfoFromAssembly(Assembly assembly)
        {
            var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly.name);

            if (string.IsNullOrEmpty(path))
            {
                return(null);
            }

            var asmdefPath = Path.GetFullPath(path);

            return(new AssemblyInfo(assembly, asmdefPath));
        }
        static void OnAssemblyCompilationStarted(string assemblyPath)
        {
            var assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);

            if (k_IgnoredAssemblies.Contains(assemblyName))
            {
                return;
            }

            var  asmDefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);
            bool modifiedAsmdef;
            bool addedPackages;

            UpdateOptionalDependencies(asmDefPath, out modifiedAsmdef, out addedPackages);
        }
        private void UpgradeAssemblyDefinitionFile(string path)
        {
            if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(textMeshProAssemblyDefinitionName))
            {
                return;
            }

            if (AssetDatabase.GetMainAssetTypeAtPath(path) != typeof(UnityEditorInternal.AssemblyDefinitionAsset))
            {
                return;
            }

            AssemblyDefinitionFileContents asmFile = JsonUtility.FromJson <AssemblyDefinitionFileContents>(File.ReadAllText(path));

            if (asmFile.references != null)
            {
                for (int i = 0; i < asmFile.references.Length; i++)
                {
#if UNITY_2019_1_OR_NEWER
                    string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference(asmFile.references[i]);
#else
                    string assemblyPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(asmFile.references[i]);
#endif

                    if (assemblyPath == textMeshProAssemblyDefinitionName)
                    {
                        return;
                    }
                }
            }

            if (asmFile.references == null)
            {
                asmFile.references = new string[1] {
                    textMeshProAssemblyDefinitionName
                }
            }
            ;
            else
            {
                Array.Resize(ref asmFile.references, asmFile.references.Length + 1);
                asmFile.references[asmFile.references.Length - 1] = textMeshProAssemblyDefinitionName;
            }

            stringBuilder.AppendLine("Upgrading Assembly Definition File: " + path);
            File.WriteAllText(path, JsonUtility.ToJson(asmFile, true));
        }
Beispiel #18
0
        public static PackageInfo GetForAssembly(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            var fullPath = assembly.Location;

            if (fullPath.StartsWith(Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
            {
                // Path is inside the project dir
                var relativePath = fullPath.Substring(Environment.CurrentDirectory.Length + 1).Replace('\\', '/');

                // See if there is an asmdef file for this assembly - use it if so
                var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly.GetName().Name);
                if (asmdefPath != null)
                {
                    relativePath = asmdefPath;
                }

                // If we don't have a valid path, or it's inside the Assets folder, it's not part of a package
                if (string.IsNullOrEmpty(relativePath) || relativePath.StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if (relativePath.StartsWith(Folders.GetPackagesMountPoint() + "/", StringComparison.OrdinalIgnoreCase))
                {
                    return(GetForAssetPath(relativePath));
                }
            }

            // Path is outside the project dir - or possibly inside the project dir but local (e.g. in LocalPackages in the test project)
            // Might be in the global package cache, might be a built-in engine module, etc. Do a scan through all packages for one that owns
            // this directory.
            foreach (var package in GetAll())
            {
                if (fullPath.StartsWith(package.resolvedPath + System.IO.Path.DirectorySeparatorChar))
                {
                    return(package);
                }
            }

            return(null);
        }
        private static AssemblyDefinitionImporterInspector.AssemblyDefinitionReference CreateAssemblyDefinitionReference(string assemblyName)
        {
            AssemblyDefinitionImporterInspector.AssemblyDefinitionReference assemblyDefinitionReference = new AssemblyDefinitionImporterInspector.AssemblyDefinitionReference();
            string assemblyDefinitionFilePathFromAssemblyName = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);

            if (string.IsNullOrEmpty(assemblyDefinitionFilePathFromAssemblyName))
            {
                throw new Exception(string.Format("Could not get assembly definition filename for assembly '{0}'", assemblyName));
            }
            assemblyDefinitionReference.asset = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(assemblyDefinitionFilePathFromAssemblyName);
            if (assemblyDefinitionReference.asset == null)
            {
                throw new FileNotFoundException(string.Format("Assembly definition file '{0}' not found", assemblyDefinitionReference.path), assemblyDefinitionReference.path);
            }
            assemblyDefinitionReference.data = CustomScriptAssemblyData.FromJson(assemblyDefinitionReference.asset.text);
            return(assemblyDefinitionReference);
        }
Beispiel #20
0
        static RecompileRequest()
        {
            var assemblyName = typeof(RecompileRequest).Assembly.GetName().Name;

            if (assemblyName == "Coffee.AsmdefEx")
            {
                return;
            }

            var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyName);

            if (Core.LogEnabled)
            {
                UnityEngine.Debug.LogFormat("<b>Request to recompile: {0} ({1})</b>", assemblyName, asmdefPath);
            }
            AssetDatabase.ImportAsset(asmdefPath);
        }
    private static void InitAssemblies()
    {
        var assemblies = CompilationPipeline.GetAssemblies();

        _Assemblies          = new Dictionary <string, Assembly>(assemblies.Length);
        _AssemblyDefinitions = new Dictionary <string, AssemblyDefinition>(assemblies.Length);
        foreach (var assembly in assemblies)
        {
            _Assemblies.Add(assembly.name, assembly);
            var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly.name);
            if (!string.IsNullOrEmpty(path))
            {
                var asmdef = new AssemblyDefinition(path);
                _AssemblyDefinitions.Add(assembly.name, asmdef);
            }
        }
    }
Beispiel #22
0
        static bool GetAutoRef(string assName)
        {
            string asmdef = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assName);

            using (StreamReader reader = new StreamReader(asmdef))
            {
                string asmdefText = reader.ReadToEnd();
                if (asmdefText.Contains("\"autoReferenced\": false"))
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
        internal static List <PackageInfo> GetForAssemblyFilePaths(List <string> assemblyPaths)
        {
            // We will first get all the relative asmdef paths from assembly paths
            var pathsToProcess = new HashSet <string>();

            foreach (string assemblyPath in assemblyPaths)
            {
                // See if there is an asmdef file for this assembly - use it if so
                var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyPath);
                pathsToProcess.Add(String.IsNullOrEmpty(asmdefPath) ? assemblyPath : asmdefPath);
            }

            // We will loop through all the packages and see if they match the relative or absolute paths of asmdefs or assemblies
            List <PackageInfo> matchingPackages = new List <PackageInfo>();

            foreach (var package in GetAll())
            {
                foreach (var path in pathsToProcess)
                {
                    bool found;
                    if (Path.IsPathRooted(path))
                    {
                        found = path.StartsWith(package.resolvedPath + Path.DirectorySeparatorChar);
                    }
                    else
                    {
                        found = path.StartsWith(package.assetPath + '/');
                    }

                    if (found)
                    {
                        matchingPackages.Add(package);
                        pathsToProcess.Remove(path);
                        break;
                    }
                }
                if (pathsToProcess.Count == 0)
                {
                    break;
                }
            }
            return(matchingPackages);
        }
Beispiel #24
0
        public bool IsDLLUsed(string dll)
        {
            if (m_UsedTypesPerUserAssembly == null)
            {
                return(true);
            }

            if (Array.IndexOf(CodeStrippingUtils.UserAssemblies, dll) != -1)
            {
                // Don't treat code in packages as used automatically (case 1003047).
                var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(dll);
                if (asmdefPath == null || !EditorCompilationInterface.Instance.IsPathInPackageDirectory(asmdefPath))
                {
                    return(true);
                }
            }

            return(m_UsedTypesPerUserAssembly.ContainsKey(dll));
        }
Beispiel #25
0
        public static AssemblyInfo GetAssemblyInfoFromAssemblyPath(string assemblyPath)
        {
            // by default let's assume it's not a package
            var assemblyInfo = new AssemblyInfo
            {
                name         = Path.GetFileNameWithoutExtension(assemblyPath),
                path         = assemblyPath,
                relativePath = "Assets",
                readOnly     = false
            };

            var asmDefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyInfo.name);

            if (asmDefPath != null)
            {
                assemblyInfo.asmDefPath = asmDefPath;
                var folders = asmDefPath.Split('/');
                if (folders.Length > 2 && folders[0].Equals("Packages"))
                {
                    assemblyInfo.relativePath = Path.Combine(folders[0], folders[1]).Replace("\\", "/");
#if UNITY_2019_3_OR_NEWER
                    var info = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(asmDefPath);
                    if (info != null)
                    {
                        assemblyInfo.readOnly = info.source != UnityEditor.PackageManager.PackageSource.Embedded && info.source != UnityEditor.PackageManager.PackageSource.Local;
                    }
#else
                    assemblyInfo.readOnly = true;
#endif
                }
                else
                {
                    // non-package user-defined assembly
                }
            }
            else
            {
                // default assembly
            }

            return(assemblyInfo);
        }
        static AssemblyInfo GetAssemblyInfoFromAssemblyName(string assemblyName)
        {
            // by default let's assume it's not a package
            var assemblyInfo = new AssemblyInfo
            {
                name         = assemblyName,
                relativePath = "Assets",
                readOnly     = false
            };

            var asmDefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assemblyInfo.name);

            if (asmDefPath != null)
            {
                assemblyInfo.asmDefPath = asmDefPath;
                var folders = asmDefPath.Split('/');
                if (folders.Length > 2 && folders[0].Equals("Packages"))
                {
                    assemblyInfo.relativePath = Path.Combine(folders[0], folders[1]).Replace("\\", "/");
#if UNITY_2019_3_OR_NEWER
                    var info = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(asmDefPath);
                    if (info != null)
                    {
                        assemblyInfo.readOnly = info.source != PackageSource.Embedded && info.source != PackageSource.Local;
                    }
#else
                    assemblyInfo.readOnly = true;
#endif
                }
                else
                {
                    // non-package user-defined assembly
                    return(assemblyInfo);
                }
            }
            else if (!assemblyInfo.name.StartsWith(AssemblyInfo.DefaultAssemblyName))
            {
                Debug.LogErrorFormat("Assembly Definition cannot be found for " + assemblyInfo.name);
            }

            return(assemblyInfo);
        }
Beispiel #27
0
        public static PackageInfo FindForAssembly(Assembly assembly)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }

            string fullPath = assembly.Location;

            // See if there is an asmdef file for this assembly - use it if so
            var asmdefPath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(fullPath);

            if (!String.IsNullOrEmpty(asmdefPath))
            {
                return(FindForAssetPath(asmdefPath));
            }

            // No asmdef - this is a precompiled DLL.
            return(FindForAssetPath(fullPath));
        }
Beispiel #28
0
        public static IEnumerable <Type> FilterSystemsToPackages(IEnumerable <Type> systems, IEnumerable <string> packageNames)
        {
            const string packagePrefix = "Packages";

            foreach (var s in systems)
            {
                var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(s.Assembly.GetName().Name);
                if (path == null)
                {
                    continue;
                }
                if (!path.StartsWith(packagePrefix))
                {
                    continue;
                }
                var packagePath = path.Substring(packagePrefix.Length + 1);
                if (packageNames.Any(packagePath.StartsWith))
                {
                    yield return(s);
                }
            }
        }
Beispiel #29
0
        static void ForEachAssembly(Action <AssemblyDefinition> callback)
        {
            foreach (var assembly in k_AssemblyNames)
            {
                var path = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(assembly);
                if (string.IsNullOrEmpty(path))
                {
                    Debug.LogWarningFormat("Error in EditorXR Pre-Build action: Cannot find asmdef for assembly: {0}", assembly);
                    continue;
                }

                var asmDefAsset = AssetDatabase.LoadAssetAtPath <AssemblyDefinitionAsset>(path);
                if (asmDefAsset == null)
                {
                    Debug.LogWarningFormat("Error in EditorXR Pre-Build action: Cannot load asmdef at: {0}", path);
                    continue;
                }

                var asmDef = JsonUtility.FromJson <AssemblyDefinition>(asmDefAsset.text);
                callback(asmDef);
                File.WriteAllText(path, JsonUtility.ToJson(asmDef, true));
            }
        }
Beispiel #30
0
        private static void Run()
        {
            string runtimeAssemblyFilePath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyName(RuntimeAssemblyDefinitionName);

            try
            {
                UnityEditor.Compilation.Assembly photonNetworkAssembly = null;
                // Attempt to get the Doozy assembly.
                if (!TryGetAssembly(PhotonNetworkAssemblyDefinitionName, out photonNetworkAssembly))
                {
                    throw new Exception("Unable to find a Photon network assembly! Refer to the documentation in Packages/Network Management/DOCUMENTATION to fix this issue.");
                }

                UnityEditor.Compilation.Assembly photonRealtimeAssembly = null;
                // Attempt to get the Doozy assembly.
                if (!TryGetAssembly(PhotonRealtimeAssemblyDefinitionName, out photonRealtimeAssembly))
                {
                    throw new Exception("Unable to find a Photon realtime assembly! Refer to the documentation in Packages/Network Management/DOCUMENTATION to fix this issue.");
                }

                // Attempt to get the EnhancedScroller assembly
                UnityEditor.Compilation.Assembly signalerAssembly = null;
                if (!TryGetAssembly(SignalerAssemblyDefinitionName, out signalerAssembly))
                {
                    throw new Exception("Unable to find an Signaler runtime assembly! Refer to the documentation in Packages/Network Management/DOCUMENTATION to fix this issue.");
                }

                File.WriteAllText(runtimeAssemblyFilePath, GetAssemblyDefinitionString(photonNetworkAssembly.name, photonRealtimeAssembly.name, signalerAssembly.name));
                AddGlobalDefine(DEFINE_900LBSNETWORKING);
            }
            catch (Exception e)
            {
                RemoveGlobalDefine(DEFINE_900LBSNETWORKING);
                UnityEngine.Debug.LogError(e.Message);
            }
        }