public string Process() { string output = ""; try { output = TemplatingEngine.Run(assembly, settings.Namespace + "." + settings.Name, host, settings.Culture); } catch (Exception ex) { parsedTemplate.LogError("Error running transform: " + ex); } host.LogErrors(parsedTemplate.Errors); return(output); }
public string ProcessTemplate (string content, ITextTemplatingEngineHost host) { AppDomain appdomain = host.ProvideTemplatingAppDomain (content); ITextTemplatingEngine engine; if (appdomain != null) { engine = (ITextTemplatingEngine) appdomain.CreateInstanceAndUnwrap (typeof (TemplatingEngine).Assembly.FullName, typeof (TemplatingEngine).FullName); } else { engine = new TemplatingEngine (); } return engine.ProcessTemplate (content, host); }
public bool Load() { bool success = false; try { if (AssemblyName != null) { Assembly = Assembly.Load(AssemblyName); } success = true; } catch (Exception ex) { if (TemplatingEngine.IsCriticalException(ex)) { throw; } } return(success); }
static int MainInternal(string [] args) { if (args.Length == 0 && !Console.IsInputRedirected) { ShowHelp(true); } var generator = new ToolTemplateGenerator(); string outputFile = null, inputFile = null; var directives = new List <string> (); var parameters = new List <string> (); var properties = new Dictionary <string, string> (); string preprocessClassName = null; bool debug = false; bool verbose = false; optionSet = new OptionSet { { "o=|out=", "Name or path of the output {<file>}. Defaults to the input filename with its " + "extension changed to `.txt'. Use `-' to output to stdout.", s => outputFile = s }, { "r=", "Name or path of an {<assembly>} reference. Assemblies will be resolved from the " + "framework and the include folders", s => generator.Refs.Add(s) }, { "u=|using=", "Import a {<namespace>}' statement with a `using", s => generator.Imports.Add(s) }, { "I=", "Search {<directory>} when resolving file includes", s => generator.IncludePaths.Add(s) }, { "P=", "Search {<directory>} when resolving assembly references", s => generator.ReferencePaths.Add(s) }, { "c=|class=", "Preprocess the template into class {<name>}", (s) => preprocessClassName = s }, { "p:=", "Add a {<name>}={<value>} key-value pair to the template's `Session' " + "dictionary. These can also be accessed using strongly typed " + "properties declared with `<#@ parameter name=\"<name>\" type=\"<type>\" #> " + "directives.", (k, v) => properties[k] = v }, { "debug", "Generate debug symbols and keep temp files", s => debug = true }, { "v|verbose", "Generate debug symbols and keep temp files", s => verbose = true }, { "h|?|help", "Show help", s => ShowHelp(false) } }; compatOptionSet = new OptionSet { { "dp=", "Directive processor (name!class!assembly)", s => directives.Add(s) }, { "a=", "Parameters (name=value) or ([processorName!][directiveName!]name!value)", s => parameters.Add(s) }, }; var remainingArgs = optionSet.Parse(args); remainingArgs = compatOptionSet.Parse(remainingArgs); string inputContent = null; bool inputIsFromStdin = false; if (remainingArgs.Count != 1) { if (Console.IsInputRedirected) { inputContent = Console.In.ReadToEnd(); inputIsFromStdin = true; } else { Console.Error.WriteLine("No input file specified."); return(1); } } else { inputFile = remainingArgs [0]; if (!File.Exists(inputFile)) { Console.Error.WriteLine("Input file '{0}' does not exist.", inputFile); return(1); } } bool writeToStdout = outputFile == "-" || (inputIsFromStdin && string.IsNullOrEmpty(outputFile)); if (!writeToStdout && string.IsNullOrEmpty(outputFile)) { outputFile = inputFile; if (Path.HasExtension(outputFile)) { var dir = Path.GetDirectoryName(outputFile); var fn = Path.GetFileNameWithoutExtension(outputFile); outputFile = Path.Combine(dir, fn + ".txt"); } else { outputFile = outputFile + ".txt"; } } if (inputFile != null) { try { inputContent = File.ReadAllText(inputFile); } catch (IOException ex) { Console.Error.WriteLine("Could not read input file '" + inputFile + "':\n" + ex); return(1); } } if (inputContent.Length == 0) { Console.Error.WriteLine("Input is empty"); return(1); } foreach (var par in parameters) { if (!generator.TryAddParameter(par)) { Console.Error.WriteLine("Parameter has incorrect format: {0}", par); return(1); } } if (!AddDirectiveProcessors(generator, directives)) { return(1); } var pt = generator.ParseTemplate(inputFile, inputContent); TemplateSettings settings = TemplatingEngine.GetSettings(generator, pt); if (debug) { settings.Debug = true; } if (verbose) { settings.Log = Console.Out; } if (pt.Errors.Count > 0) { generator.Errors.AddRange(pt.Errors); } string outputContent = null; if (!generator.Errors.HasErrors) { AddCoercedSessionParameters(generator, pt, properties); } if (!generator.Errors.HasErrors) { if (preprocessClassName == null) { (outputFile, outputContent) = generator.ProcessTemplateAsync(pt, inputFile, inputContent, outputFile, settings).Result; } else { SplitClassName(preprocessClassName, settings); outputContent = generator.PreprocessTemplate(pt, inputFile, inputContent, settings, out _, out _); } } if (generator.Errors.HasErrors) { Console.Error.WriteLine(inputFile == null ? "Processing failed." : $"Processing '{inputFile}' failed."); } try { if (!generator.Errors.HasErrors) { if (writeToStdout) { Console.WriteLine(outputContent); } else { File.WriteAllText(outputFile, outputContent, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } } } catch (IOException ex) { Console.Error.WriteLine("Could not write output file '" + outputFile + "':\n" + ex); return(1); } LogErrors(generator); return(generator.Errors.HasErrors ? 1 : 0); }
/// <summary> /// Generates this project template to the specified output directory. /// </summary> /// <param name="outputDirectory">The output directory.</param> /// <param name="projectName">Name of the project.</param> /// <param name="projectGuid">The project unique identifier.</param> /// <param name="log">The log to output errors to.</param> /// <param name="options">The options arguments that will be made available through the Session property in each template.</param> /// <param name="generatedOutputFiles">The generated files.</param> /// <exception cref="System.ArgumentNullException">outputDirectory /// or /// projectName</exception> /// <exception cref="System.InvalidOperationException">FilePath cannot be null on this instance</exception> public void Generate(string outputDirectory, string projectName, Guid projectGuid, ILogger log, Dictionary<string, object> options = null, List<string> generatedOutputFiles = null ) { if (outputDirectory == null) throw new ArgumentNullException("outputDirectory"); if (projectName == null) throw new ArgumentNullException("projectName"); if (log == null) throw new ArgumentNullException("log"); if (FilePath == null) throw new InvalidOperationException("FilePath cannot be null on this instance"); try { // Check Project template filepath var templateDirectory = new FileInfo(FilePath).Directory; if (templateDirectory == null || !templateDirectory.Exists) { log.Error("Invalid ProjectTemplate directory [{0}]", FilePath); return; } // Creates the output directory var directory = new DirectoryInfo(outputDirectory); if (!directory.Exists) { directory.Create(); } // Create expando object from options valid for the whole life of generating a project template var expandoOptions = new ExpandoObject(); var expandoOptionsAsDictionary = (IDictionary<string, object>)expandoOptions; expandoOptionsAsDictionary["ProjectName"] = projectName; expandoOptionsAsDictionary["ProjectGuid"] = projectGuid; if (options != null) { foreach (var option in options) { expandoOptionsAsDictionary[option.Key] = option.Value; } } var engine = new TemplatingEngine(); // In case this project template is dynamic, we need to generate its content first through T4 if (IsDynamicTemplate) { var content = File.ReadAllText(FilePath); var host = new ProjectTemplatingHost(log, FilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); var newTemplateAsString = engine.ProcessTemplate(content, host); Files.Clear(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(newTemplateAsString))) { var newTemplate = (ProjectTemplate)YamlSerializer.Deserialize(stream); Files.AddRange(newTemplate.Files); } } // Iterate on each files foreach (var fileItem in Files) { if (fileItem.Source == null) { log.Warning("Invalid empty file item [{0}] with no source location", fileItem); continue; } var sourceFilePath = System.IO.Path.Combine(templateDirectory.FullName, fileItem.Source); var targetLocation = fileItem.Target ?? fileItem.Source; if (Path.IsPathRooted(targetLocation)) { log.Error("Invalid file item [{0}]. TargetLocation must be a relative path", fileItem); continue; } var targetLocationExpanded = Expand(targetLocation, expandoOptionsAsDictionary, log); // If this is a template file, turn template on by default if (fileItem.IsTemplate) { var targetPath = Path.GetDirectoryName(targetLocationExpanded); var targetFileName = Path.GetFileName(targetLocationExpanded); targetLocationExpanded = targetPath != null ? Path.Combine(targetPath, targetFileName) : targetFileName; } var targetFilePath = Path.Combine(outputDirectory, targetLocationExpanded); try { // Make sure that the target directory does exist var targetDirectory = new FileInfo(targetFilePath).Directory; if (!targetDirectory.Exists) { targetDirectory.Create(); } bool fileGenerated = false; if (fileItem.IsTemplate) { var content = File.ReadAllText(sourceFilePath); var host = new ProjectTemplatingHost(log, sourceFilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); var newContent = engine.ProcessTemplate(content, host); if (newContent != null) { fileGenerated = true; File.WriteAllText(targetFilePath, newContent); } } else { fileGenerated = true; File.Copy(sourceFilePath, targetFilePath, true); } if (generatedOutputFiles != null && fileGenerated) { generatedOutputFiles.Add(targetFilePath); } } catch (Exception ex) { log.Error("Unexpected exception while processing [{0}]", fileItem, ex); } } } catch (Exception ex) { log.Error("Unexpected exception while processing project template [{0}] to directory [{1}]", projectName, outputDirectory, ex); } }
public string GeneratePart(string templatePathPart, ILogger log, Dictionary<string, object> options) { if (templatePathPart == null) throw new ArgumentNullException("templatePathPart"); if (log == null) throw new ArgumentNullException("log"); var expandoOptions = new ExpandoObject(); var expandoOptionsAsDictionary = (IDictionary<string, object>)expandoOptions; foreach (var option in options) { expandoOptionsAsDictionary[option.Key] = option.Value; } var templateDirectory = new FileInfo(FilePath).Directory; var sourceFilePath = System.IO.Path.Combine(templateDirectory.FullName, templatePathPart); var content = File.ReadAllText(sourceFilePath); var engine = new TemplatingEngine(); var host = new ProjectTemplatingHost(log, sourceFilePath, templateDirectory.FullName, expandoOptions, Assemblies.Select(assembly => assembly.FullPath)); return engine.ProcessTemplate(content, host); }
public string Process(object textTransformation) { if (textTransformation == null) { throw new ArgumentNullException(nameof(textTransformation)); } try { var ttType = textTransformation.GetType(); var errorProp = ttType.GetProperty("Errors", BindingFlags.Instance | BindingFlags.NonPublic); if (errorProp == null) { throw new ArgumentException("Template must have 'Errors' property"); } var errorMethod = ttType.GetMethod("Error", new Type[] { typeof(string) }); if (errorMethod == null) { throw new ArgumentException("Template must have 'Error(string message)' method"); } var errors = (CompilerErrorCollection)errorProp.GetValue(textTransformation, null); errors.Clear(); //set the culture if (culture != null) { ToStringHelper.FormatProvider = culture; } else { ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; } string output = null; var initMethod = ttType.GetMethod("Initialize"); var transformMethod = ttType.GetMethod("TransformText"); if (initMethod == null) { errorMethod.Invoke(textTransformation, new object[] { "Error running transform: no method Initialize()" }); } else if (transformMethod == null) { errorMethod.Invoke(textTransformation, new object[] { "Error running transform: no method TransformText()" }); } else { try { initMethod.Invoke(textTransformation, null); output = (string)transformMethod.Invoke(textTransformation, null); } catch (Exception ex) { if (TemplatingEngine.IsCriticalException(ex)) { throw; } errorMethod.Invoke(textTransformation, new object[] { "Error running transform: " + ex }); } } host.LogErrors(errors.ToTemplateErrorCollection()); ToStringHelper.FormatProvider = CultureInfo.InvariantCulture; return(output); } finally { #if FEATURE_APPDOMAINS CurrentDomain.AssemblyResolve -= ResolveReferencedAssemblies; #endif } }
public static void UseInProcessCompiler(this TemplatingEngine engine) { engine.SetCompilerFunc((RuntimeInfo r) => new RoslynCodeCompiler(r)); }