Пример #1
0
        public IProcessTransformationRunner PrepareTransformationRunner(string content, ITextTemplatingEngineHost host, IProcessTransformationRunFactory runFactory, bool debugging = false)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }
            if (runFactory == null)
            {
                throw new ArgumentNullException(nameof(runFactory));
            }

            if (host is ITextTemplatingSessionHost sessionHost)
            {
                if (sessionHost.Session == null)
                {
                    sessionHost.Session = sessionHost.CreateSession();
                }
            }

            IProcessTransformationRunner runner = null;

            ParsedTemplate pt = ParsedTemplate.FromText(content, host);

            TemplateSettings settings = GetSettings(host, pt);

            settings.Debug = debugging || settings.CachedTemplates;

            EnsureParameterValuesExist(settings, host, pt);

            try {
                if (pt.Errors.HasErrors)
                {
                    return(null);
                }

                runner = CompileAndPrepareRunner(pt, content, host, runFactory, settings);
            }
            catch (Exception ex) {
                if (IsCriticalException(ex))
                {
                    throw;
                }
                pt.LogError(string.Format(CultureInfo.CurrentCulture, VsTemplatingErrorResources.ExceptionProcessingTemplate, ex), new Location(host.TemplateFile, -1, -1));
            }
            finally {
                host.LogErrors(pt.Errors);
            }

            return(runner);
        }
        public string ProcessTemplate(string content, ITextTemplatingEngineHost host)
        {
            ParsedTemplate pt = ParsedTemplate.FromText(content, host);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            TemplateSettings settings = GetSettings(host, pt);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            CodeCompileUnit ccu = GenerateCompileUnit(host, pt, settings);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            System.Reflection.Assembly results = GenerateCode(host, pt, settings, ccu);
            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            if (!String.IsNullOrEmpty(settings.Extension))
            {
                host.SetFileExtension(settings.Extension);
            }
            if (settings.Encoding != null)
            {
                //FIXME: when is this called with false?
                host.SetOutputEncoding(settings.Encoding, true);
            }

            string output = "";

            try {
                output = Run(results, settings.Namespace + "." + settings.Name, host, settings.Culture);
            } catch (Exception ex) {
                pt.LogError("Error running transform: " + ex.ToString());
            }
            host.LogErrors(pt.Errors);
            return(output);
        }
        public CompiledTemplate CompileTemplate(string content, ITextTemplatingEngineHost host)
        {
            ParsedTemplate pt = ParsedTemplate.FromText(content, host);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            TemplateSettings settings = GetSettings(host, pt);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            CodeCompileUnit ccu = GenerateCompileUnit(host, pt, settings);

            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            System.Reflection.Assembly results = GenerateCode(host, pt, settings, ccu);
            if (pt.Errors.HasErrors)
            {
                host.LogErrors(pt.Errors);
                return(null);
            }

            if (!String.IsNullOrEmpty(settings.Extension))
            {
                host.SetFileExtension(settings.Extension);
            }
            if (settings.Encoding != null)
            {
                //FIXME: when is this called with false?
                host.SetOutputEncoding(settings.Encoding, true);
            }

            return(new CompiledTemplate(pt, host, results, settings));
        }
Пример #4
0
        static int MainInternal(string [] args)
        {
            if (args.Length == 0)
            {
                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;

            if (remainingArgs.Count != 1)
            {
                if (Console.IsInputRedirected)
                {
                    inputContent = Console.In.ReadToEnd();
                }
                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 == "-";

            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 = ParsedTemplate.FromText(inputContent, generator);

            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)
                {
                    outputContent = generator.ProcessTemplate(pt, inputFile, inputContent, ref outputFile, settings);
                }
                else
                {
                    outputContent = generator.PreprocessTemplate(pt, inputFile, inputContent, preprocessClassName, settings);
                }
            }

            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);
        }