Exemplo n.º 1
0
        private static void CheckChangedAssets()
        {
            var changedAssetsCopy = default(string[]);

            lock (changedAssets)
            {
                if (changedAssets.Count > 0)
                {
                    changedAssetsCopy = changedAssets.ToArray();
                    changedAssets.Clear();
                }
            }

            if (changedAssetsCopy == null)
            {
                return;
            }


            //if (Settings.Current.Verbose)
            //	Debug.Log("Watched paths: " + string.Join(", ", templatePathByWatchedPaths.Keys.ToArray()));

            var triggeredTemplatePaths = new HashSet <string>();

            foreach (var changedAsset in changedAssetsCopy)
            {
                if (!File.Exists(changedAsset))
                {
                    continue;
                }

                //if (Settings.Current.Verbose)
                //	Debug.Log("Changed Asset: " + changedAsset);

                foreach (var watchedPath in templatePathByWatchedPaths.Keys)
                {
                    if (changedAsset.StartsWith(watchedPath, StringComparison.Ordinal))
                    {
                        foreach (var templatePath in templatePathByWatchedPaths[watchedPath])
                        {
                            triggeredTemplatePaths.Add(templatePath);
                        }
                    }
                }
            }

            foreach (var templatePath in triggeredTemplatePaths)
            {
                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("Asset modification is triggered T4 template's generator at '{0}'.", templatePath));
                }

                var settings = TemplateSettings.Load(templatePath);
                UnityTemplateGenerator.RunForTemplateWithDelay(templatePath, TimeSpan.FromMilliseconds(settings.TriggerDelay));
            }
        }
Exemplo n.º 2
0
 private static void T4TransformAllAssets()
 {
     foreach (var templatePath in TemplateSettings.ListTemplatesInProject())
     {
         var assetName = Path.GetFileName(templatePath);
         Debug.Log(string.Format("Running transformation for '{0}' asset...", assetName));
         var result = UnityTemplateGenerator.RunForTemplate(templatePath);
         Debug.Log(string.Format("Transformation for '{0}' asset is completed. Result: {1}", assetName, result));
     }
     AssetChangesTrigger.DoDelayedAssetRefresh();
 }
Exemplo n.º 3
0
        private static void Initialize()
        {
            EditorApplication.update -= InitializeCallback;

            System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(TemplateInspector).TypeHandle);

            foreach (var templatePath in TemplateSettings.ListTemplatesInProject())
            {
                var settings = TemplateSettings.Load(templatePath);
                if ((settings.Trigger & (int)TemplateSettings.Triggers.CodeCompilation) == 0)
                {
                    continue;
                }

                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("Code compilation in project is triggered T4 template's generator at '{0}'.", templatePath));
                }

                UnityTemplateGenerator.RunForTemplateWithDelay(templatePath, TimeSpan.FromMilliseconds(settings.TriggerDelay));
            }
        }
        /// <summary>
        /// Run T4 template transformation with at <paramref name="templatePath"/> with additional settings.
        /// </summary>
        /// <param name="templatePath">Path to T4 template.</param>
        /// <param name="outputPath">Output path. It will override <see cref="TemplateSettings.OutputPath"/> from <paramref name="settings"/> parameter.</param>
        /// <param name="settings">Settings override for this run.</param>
        /// <param name="parameters">Additional template parameters. They could be retrieved with following code. <code>this.Host.ResolveParameterValue("-", "-", "someKey");</code>.</param>
        /// <param name="assemblyReferences">Additional assemblies to load during transformation. Could be assembly name or full path to assembly.</param>
        /// <param name="assemblyReferencesLookupPaths">Additional assembly lookup paths. Used during referenced assemblies resolution.</param>
        /// <param name="includeLookupPaths">Additional lookup path for &lt;#=include#&gt; directives.</param>
        /// <returns>Result of transformation.</returns>
        public static TransformationResult RunForTemplate
        (
            string templatePath,
            string outputPath,
            TemplateSettings settings = null,
            Dictionary <string, string> parameters      = null,
            List <string> assemblyReferences            = null,
            List <string> assemblyReferencesLookupPaths = null,
            List <string> includeLookupPaths            = null
        )
        {
            if (templatePath == null)
            {
                throw new ArgumentNullException("templatePath");
            }

            templatePath = PathUtils.MakeProjectRelative(templatePath);

            settings = settings ?? TemplateSettings.Load(templatePath);
            var generator           = new UnityTemplateGenerator();
            var templateName        = Path.GetFileNameWithoutExtension(templatePath);
            var templateDir         = Path.GetDirectoryName(templatePath) ?? "Assets";
            var templateNamespace   = string.Join(".", templateDir.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries));
            var generatorOutputDir  = Path.Combine("Temp", "T4");
            var outputFile          = Path.Combine(generatorOutputDir, Path.GetFileNameWithoutExtension(templatePath) + "_" + Guid.NewGuid().ToString().Replace("-", "") + ".txt");
            var generatorOutputFile = Path.ChangeExtension(outputFile, ".gen.cs");

            var language   = default(string);
            var references = default(string[]);

            if (Directory.Exists(generatorOutputDir) == false)
            {
                Directory.CreateDirectory(generatorOutputDir);
            }

            if (Settings.Current.Verbose)
            {
                Debug.Log(string.Format("Pre-process T4 template '{0}'. Output directory: '{1}'.", templatePath, generatorOutputDir));
            }
            if (generator.PreprocessTemplate(templatePath, templateName, templateNamespace, generatorOutputFile, Encoding.UTF8, out language, out references) == false)
            {
                Debug.LogWarning(string.Format("Failed to pre-process template '{0}'.", templatePath));
                foreach (var error in generator.Errors)
                {
                    var log = (Action <object>)Debug.LogError;
                    log.BeginInvoke(error, null, null);
                }
                FocusConsoleWindow();
                return(TransformationResult.TemplateCompilationError);
            }

            if (Settings.Current.Verbose)
            {
                Debug.Log(string.Format("Pre-process T4 template '{0}' is complete successfully. Language: '{1}', References: '{2}', Reference location paths: {3}, Include paths: {4}, Output file: '{5}'.",
                                        templatePath, language, string.Join(", ", references ?? new string[0]),
                                        string.Join(", ", generator.ReferencePaths.ToArray()), string.Join(", ", generator.IncludePaths.ToArray()), generatorOutputFile));
            }

            if (assemblyReferences != null)
            {
                generator.Refs.AddRange(assemblyReferences);
            }

            if (assemblyReferencesLookupPaths != null)
            {
                generator.ReferencePaths.AddRange(assemblyReferencesLookupPaths);
            }

            if (includeLookupPaths != null)
            {
                generator.IncludePaths.AddRange(includeLookupPaths);
            }

            if (parameters != null)
            {
                foreach (var kv in parameters)
                {
                    generator.AddParameter("-", "-", kv.Key, kv.Value);
                    generator.AddParameter(null, null, kv.Key, kv.Value);
                }
            }

            if (Settings.Current.Verbose)
            {
                Debug.Log(string.Format("Process T4 template '{0}'. Output File: '{1}'.", templatePath, outputFile));
            }

            if (generator.ProcessTemplate(templatePath, ref outputFile) == false)
            {
                Debug.LogWarning(string.Format("Failed to process template '{0}'.", templatePath));
                foreach (CompilerError error in generator.Errors)
                {
                    var log = (Action <object>)Debug.LogError;
                    log.BeginInvoke(error, null, null);
                }
                FocusConsoleWindow();
                return(TransformationResult.TemplateProcessingError);
            }
            if (Settings.Current.Verbose)
            {
                Debug.Log(string.Format("Process T4 template '{0}' is complete successfully. Output file: '{1}'.", templatePath, outputFile));
            }

            var sourceFile = default(string);

            switch ((TemplateSettings.OutputTypes)settings.OutputType)
            {
            case TemplateSettings.OutputTypes.Text:
                sourceFile = outputFile;
                break;

            case TemplateSettings.OutputTypes.TextGenerator:
                sourceFile = generatorOutputFile;
                break;

            default:
                Debug.LogWarning("Invalid 'OutputType' is specified in template's settings.");
                return(TransformationResult.UnknownOutputType);
            }
            var targetFile = outputPath ?? settings.OutputPath;

            if (targetFile == null)
            {
                targetFile = Path.GetFullPath(Path.ChangeExtension(templatePath, Path.GetExtension(sourceFile)));
            }
            else
            {
                targetFile = Path.GetFullPath(targetFile);
            }

            if (File.Exists(targetFile) && PathUtils.ComputeMd5Hash(targetFile) == PathUtils.ComputeMd5Hash(sourceFile))
            {
                if (Settings.Current.Verbose)
                {
                    Debug.Log(string.Format("Generated file is same as existing at location '{0}'.", targetFile));
                }
                return(TransformationResult.NoChanges);
            }

            var targetDir = Path.GetDirectoryName(targetFile);

            if (targetDir != null && Directory.Exists(targetDir) == false)
            {
                Directory.CreateDirectory(targetDir);
            }

            File.Copy(sourceFile, targetFile, overwrite: true);
            File.Delete(outputFile);
            File.Delete(generatorOutputFile);

            return(TransformationResult.Success);
        }