コード例 #1
0
ファイル: ProjectGeneration.cs プロジェクト: super-180/first
        IEnumerable <ResponseFileData> ParseResponseFileData(Assembly assembly)
        {
            var systemReferenceDirectories =
                CompilationPipeline.GetSystemAssemblyDirectories(assembly.compilerOptions.ApiCompatibilityLevel);

            Dictionary <string, ResponseFileData> responseFilesData = assembly.compilerOptions.ResponseFiles.ToDictionary(
                x => x, x => m_AssemblyNameProvider.ParseResponseFile(
                    x,
                    ProjectDirectory,
                    systemReferenceDirectories
                    ));

            Dictionary <string, ResponseFileData> 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));
        }
コード例 #2
0
 public bool WillProcess(UnityEditor.Compilation.Assembly editorAssembly)
 {
     if (editorAssembly.name.Contains(".Generated"))
     {
         return(false);
     }
     if (GhostAuthoringModifiers.AssembliesDefaultOverrides.Contains(editorAssembly.name))
     {
         return(true);
     }
     if (!editorAssembly.assemblyReferences.Any(a => a.name == "Unity.Entities"))
     {
         return(false);
     }
     if (!editorAssembly.assemblyReferences.Any(a => a.name == "Unity.NetCode"))
     {
         return(false);
     }
     if (flags.HasFlag(AssemblyFilterExcludeFlag.EditorOnly) && editorAssembly.flags.HasFlag(AssemblyFlags.EditorAssembly))
     {
         return(false);
     }
     if (flags.HasFlag(AssemblyFilterExcludeFlag.Tests) && editorAssembly.compiledAssemblyReferences.Any(a => a.EndsWith("nunit.framework.dll")))
     {
         return(false);
     }
     return(true);
 }
コード例 #3
0
        private static string GetRootNamespace(Assembly assembly)
        {
#if UNITY_2020_2_OR_NEWER
            return(assembly.rootNamespace);
#else
            return(EditorSettings.projectGenerationRootNamespace);
#endif
        }
コード例 #4
0
 void SyncProject(
     Assembly island,
     Dictionary <string, string> allAssetsProjectParts,
     IEnumerable <ResponseFileData> responseFilesData,
     List <Assembly> allProjectIslands,
     Type[] types)
 {
     SyncProjectFileIfNotChanged(ProjectFile(island),
                                 ProjectText(island, allAssetsProjectParts, responseFilesData.ToList(), allProjectIslands), types);
 }
 public CompilationContext(UnityEditor.Compilation.Assembly assembly, GeneratedFileGuidCache cache, Dictionary <string, GhostCodeGen> genCache)
 {
     assemblyName          = assembly.name;
     assemblyNameGenerated = AssemblyNameGenerated(assembly.name);
     compilerCache         = cache;
     generatedAssembly     = default;
     generatedBatch        = default;
     isRuntimeAssembly     = !assembly.flags.HasFlag(AssemblyFlags.EditorAssembly) &&
                             !assembly.compiledAssemblyReferences.Any(a => a.EndsWith("nunit.framework.dll"));
     codeGenCache = genCache;
 }
コード例 #6
0
        static void OnCompilationFinished(string assemblyPath, CompilerMessage[] messages)
        {
            // Do nothing if there were compile errors on the target
            if (CompilerMessagesContainError(messages))
            {
                Debug.Log("Weaver: stop because compile errors on target");
                return;
            }

            // Should not run on the editor only assemblies
            if (assemblyPath.Contains("-Editor") || assemblyPath.Contains(".Editor"))
            {
                return;
            }

            // don't weave mirror files
            string assemblyName = Path.GetFileNameWithoutExtension(assemblyPath);

            if (assemblyName == MirrorRuntimeAssemblyName || assemblyName == MirrorWeaverAssemblyName || assemblyName == "Zenject")
            {
                return;
            }

            UnityAssembly assembly = CompilationPipeline.GetAssemblies().FirstOrDefault(ass => ass.outputPath == assemblyPath);

            if (assembly == null)
            {
                // no assembly found, this can happen if you use the AssemblyBuilder
                // happens with our weaver tests.
                // create an assembly object manually

                assembly = CreateUnityAssembly(assemblyPath);
            }

            // don't weave if this does not depend on mirror
            if (!assembly.allReferences.Any(path => Path.GetFileNameWithoutExtension(path) == MirrorRuntimeAssemblyName))
            {
                return;
            }

            Log.WarningMethod = HandleWarning;
            Log.ErrorMethod   = HandleError;

            if (!Weaver.WeaveAssembly(assembly))
            {
                // Set false...will be checked in \Editor\EnterPlayModeSettingsCheck.CheckSuccessfulWeave()
                SessionState.SetBool("MIRROR_WEAVE_SUCCESS", false);
                if (UnityLogEnabled)
                {
                    Debug.LogError("Weaving failed for: " + assemblyPath);
                }
            }
        }
コード例 #7
0
ファイル: ProjectGeneration.cs プロジェクト: super-180/first
 void SyncProject(
     Assembly island,
     Dictionary <string, string> allAssetsProjectParts,
     IEnumerable <ResponseFileData> responseFilesData,
     Type[] types,
     string[] roslynAnalyzerDllPaths)
 {
     SyncProjectFileIfNotChanged(
         ProjectFile(island),
         ProjectText(island, allAssetsProjectParts, responseFilesData.ToList(), roslynAnalyzerDllPaths),
         types);
 }
コード例 #8
0
        private string ProjectHeader(
            Assembly assembly,
            List <ResponseFileData> responseFilesData,
            string[] roslynAnalyzerDllPaths
            )
        {
            var otherResponseFilesData = GetOtherArgumentsFromResponseFilesData(responseFilesData);
            var arguments = new object[]
            {
                k_ToolsVersion,
                k_ProductVersion,
                ProjectGuid(assembly),
                InternalEditorUtility.GetEngineAssemblyPath(),
                InternalEditorUtility.GetEditorAssemblyPath(),
                string.Join(";", assembly.defines.Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
                MSBuildNamespaceUri,
                assembly.name,
                assembly.outputPath,
                GetRootNamespace(assembly),
                k_TargetFrameworkVersion,
                GenerateLangVersion(otherResponseFilesData["langversion"]),
                k_BaseDirectory,
                assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
                GenerateNoWarn(otherResponseFilesData["nowarn"].Distinct().ToArray()),
                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"])
            };

            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);
            }
        }
コード例 #9
0
    protected bool TryGetAssembly(string path, out UnityEditor.Compilation.Assembly assembly)
    {
        if (TryGetAssemblyName(path, out string asmName))
        {
            assembly = Array.Find(CompilationPipeline.GetAssemblies(), (x) => x.name == asmName);
        }
        else
        {
            assembly = null;
        }

        return(assembly != null);
    }
コード例 #10
0
 private static bool TryGetAssembly(string assemblyName, out UnityEditor.Compilation.Assembly assembly)
 {
     foreach (var compiledAssembly in CompilationPipeline.GetAssemblies())
     {
         if (compiledAssembly.name == assemblyName)
         {
             assembly = compiledAssembly;
             return(true);
         }
     }
     assembly = null;
     return(false);
 }
コード例 #11
0
        private static UnityAssembly CreateUnityAssembly(string assemblyPath)
        {
            // copy from one of the assemblies
            UnityAssembly mirrordll = CompilationPipeline.GetAssemblies().First(assembly => assembly.name == "Mirror");

            return(new UnityAssembly(
                       Path.GetFileNameWithoutExtension(assemblyPath),
                       assemblyPath,
                       new string[] { },
                       CompilationPipeline.GetDefinesFromAssemblyName(assemblyPath),
                       CompilationPipeline.GetAssemblies(),
                       mirrordll.compiledAssemblyReferences,
                       AssemblyFlags.None));
        }
コード例 #12
0
        private string ProjectText(Assembly assembly,
                                   Dictionary <string, string> allAssetsProjectParts,
                                   List <ResponseFileData> responseFilesData,
                                   string[] roslynAnalyzerDllPaths)
        {
            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);
            }

            // Append additional non-script files that should be included in project generation.
            if (allAssetsProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject))
            {
                projectBuilder.Append(additionalAssetsForProject);
            }

            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)).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());
        }
コード例 #13
0
        private static void CollectAssemblyNames(UnityEditor.Compilation.Assembly assembly, HashSet <string> collect)
        {
            if (assembly == null || assembly.name == null)
            {
                return;
            }

            if (!collect.Add(assembly.name))
            {
                return;
            }

            foreach (var assemblyRef in assembly.assemblyReferences)
            {
                CollectAssemblyNames(assemblyRef, collect);
            }
        }
コード例 #14
0
        string ProjectHeader(
            Assembly assembly,
            List <ResponseFileData> responseFilesData
            )
        {
            var otherResponseFilesData = GetOtherArgumentsFromResponseFilesData(responseFilesData);
            var arguments = new object[]
            {
                k_ToolsVersion,
                k_ProductVersion,
                m_GUIDGenerator.ProjectGuid(m_ProjectName, assembly.name),
                InternalEditorUtility.GetEngineAssemblyPath(),
                InternalEditorUtility.GetEditorAssemblyPath(),
                string.Join(";",
                            new[] { "DEBUG", "TRACE" }.Concat(EditorUserBuildSettings.activeScriptCompilationDefines).Concat(assembly.defines)
                            .Concat(responseFilesData.SelectMany(x => x.Defines)).Distinct().ToArray()),
                MSBuildNamespaceUri,
                assembly.name,
                m_AssemblyNameProvider.ProjectGenerationRootNamespace,
                k_TargetFrameworkVersion,
                GenerateLangVersion(otherResponseFilesData["langversion"]),
                k_BaseDirectory,
                assembly.compilerOptions.AllowUnsafeCode | responseFilesData.Any(x => x.Unsafe),
                GenerateNoWarn(otherResponseFilesData["nowarn"].Distinct().ToArray()),
                GenerateAnalyserItemGroup(otherResponseFilesData["analyzer"].Concat(otherResponseFilesData["a"]).SelectMany(x => x.Split(';')).Distinct().ToArray()),
                GenerateAnalyserAdditionalFiles(otherResponseFilesData["additionalfile"].SelectMany(x => x.Split(';')).Distinct().ToArray()),
                GenerateAnalyserRuleSet(otherResponseFilesData["ruleset"].Distinct().ToArray()),
                GenerateWarningLevel(otherResponseFilesData["warn"].Concat(otherResponseFilesData["w"]).Distinct()),
                GenerateWarningAsError(otherResponseFilesData["warnaserror"]),
                GenerateDocumentationFile(otherResponseFilesData["doc"])
            };

            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);
            }
        }
コード例 #15
0
        private static IEnumerable <string> GetAssemblyReferenceDirectories(UnityEditor.Compilation.Assembly assembly)
        {
            HashSet <string> directories = new HashSet <string>();

            if (assembly == null)
            {
                return(directories);
            }

            if (assembly.compiledAssemblyReferences == null || assembly.compiledAssemblyReferences.Length <= 0)
            {
                return(directories);
            }

            foreach (string assemblyRef in assembly.compiledAssemblyReferences)
            {
                directories.Add(Path.GetDirectoryName(assemblyRef));
            }
            return(directories);
        }
コード例 #16
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);
            }
        }
コード例 #17
0
 public Info(string path, UnityEditor.Compilation.Assembly compilationAssembly, System.Reflection.Assembly assembly)
 {
     Path = path;
     CompilationAssembly = compilationAssembly;
     Assembly            = assembly;
 }
コード例 #18
0
ファイル: ProjectGeneration.cs プロジェクト: super-180/first
 public string ProjectFile(Assembly assembly)
 {
     return(Path.Combine(ProjectDirectory, $"{m_AssemblyNameProvider.GetProjectName(assembly.outputPath, assembly.name)}.csproj"));
 }
コード例 #19
0
        string ProjectText(Assembly assembly,
                           Dictionary <string, string> allAssetsProjectParts,
                           List <ResponseFileData> responseFilesData,
                           List <Assembly> allProjectIslands)
        {
            var projectBuilder    = new StringBuilder(ProjectHeader(assembly, responseFilesData));
            var references        = new List <string>();
            var projectReferences = new List <Match>();

            foreach (string file in assembly.sourceFiles)
            {
                if (!ShouldFileBePartOfSolution(file))
                {
                    continue;
                }

                var extension = Path.GetExtension(file).ToLower();
                var fullFile  = EscapedRelativePathFor(file);
                if (".dll" != extension)
                {
                    projectBuilder.Append("     <Compile Include=\"").Append(fullFile).Append("\" />").Append(Environment.NewLine);
                }
                else
                {
                    references.Add(fullFile);
                }
            }

            // Append additional non-script files that should be included in project generation.
            if (allAssetsProjectParts.TryGetValue(assembly.name, out var additionalAssetsForProject))
            {
                projectBuilder.Append(additionalAssetsForProject);
            }

            var islandRefs = references.Union(assembly.allReferences);

            foreach (string reference in islandRefs)
            {
                var match = k_ScriptReferenceExpression.Match(reference);
                if (match.Success)
                {
                    // assume csharp language
                    // Add a reference to a project except if it's a reference to a script assembly
                    // that we are not generating a project for. This will be the case for assemblies
                    // coming from .assembly.json files in non-internalized packages.
                    var dllName = match.Groups["dllname"].Value;
                    if (allProjectIslands.Any(i => Path.GetFileName(i.outputPath) == dllName))
                    {
                        projectReferences.Add(match);
                        continue;
                    }
                }

                string fullReference = Path.IsPathRooted(reference) ? reference : Path.Combine(ProjectDirectory, reference);

                AppendReference(fullReference, projectBuilder);
            }

            var responseRefs = responseFilesData.SelectMany(x => x.FullPathReferences.Select(r => r));

            foreach (var reference in responseRefs)
            {
                AppendReference(reference, projectBuilder);
            }

            if (0 < projectReferences.Count)
            {
                projectBuilder.AppendLine("  </ItemGroup>");
                projectBuilder.AppendLine("  <ItemGroup>");
                foreach (Match reference in projectReferences)
                {
                    var referencedProject = reference.Groups["project"].Value;

                    projectBuilder.Append("    <ProjectReference Include=\"").Append(referencedProject)
                    .Append(GetProjectExtension()).Append("\">").Append(Environment.NewLine);
                    projectBuilder
                    .Append("      <Project>{")
                    .Append(m_GUIDGenerator.ProjectGuid(m_ProjectName, reference.Groups["project"].Value))
                    .Append("}</Project>")
                    .Append(Environment.NewLine);
                    projectBuilder.Append("      <Name>").Append(referencedProject).Append("</Name>").Append(Environment.NewLine);
                    projectBuilder.AppendLine("    </ProjectReference>");
                }
            }

            projectBuilder.Append(ProjectFooter());
            return(projectBuilder.ToString());
        }
コード例 #20
0
 public string ProjectFile(Assembly assembly)
 {
     return(Path.Combine(ProjectDirectory, $"{assembly.name}.csproj"));
 }
コード例 #21
0
ファイル: ProjectGeneration.cs プロジェクト: super-180/first
 static ScriptingLanguage ScriptingLanguageFor(Assembly island)
 {
     return(ScriptingLanguageFor(GetExtensionOfSourceFiles(island.sourceFiles)));
 }
コード例 #22
0
ファイル: ProjectGeneration.cs プロジェクト: super-180/first
 string ProjectGuid(Assembly assembly)
 {
     return(m_GUIDGenerator.ProjectGuid(
                m_ProjectName,
                m_AssemblyNameProvider.GetProjectName(assembly.outputPath, assembly.name)));
 }
コード例 #23
0
 private static string[] ReferencesFromAssembly(UnityEditor.Compilation.Assembly a)
 {
     // on 2018.1 `allReferences` returns the list of referenced assemblies
     return(a.allReferences);
 }