コード例 #1
0
        private Engine SetupEngine(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
        {
            var rootPath    = (RelativePath)scriptResource.ResourceName;
            var engineCache = new Dictionary <string, Engine>();

            var utility = new TemplateUtility(context);

            _utilityObject = new
            {
                resolveSourceRelativePath = new Func <string, string, string>(utility.ResolveSourceRelativePath)
            };

            var engine = CreateDefaultEngine();

            var requireAction = new Func <string, object>(
                s =>
            {
                if (!s.StartsWith(RequireRelativePathPrefix))
                {
                    throw new ArgumentException($"Only relative path starting with `{RequireRelativePathPrefix}` is supported in require");
                }
                var relativePath = (RelativePath)s.Substring(RequireRelativePathPrefix.Length);
                s = relativePath.BasedOn(rootPath);

                var script = resourceCollection?.GetResource(s);
                if (string.IsNullOrWhiteSpace(script))
                {
                    return(null);
                }

                Engine cachedEngine;
                if (!engineCache.TryGetValue(s, out cachedEngine))
                {
                    cachedEngine   = CreateEngine(engine, RequireFuncVariableName);
                    engineCache[s] = cachedEngine;
                    cachedEngine.Execute(script);
                }

                return(cachedEngine.GetValue(ExportsVariableName));
            });

            engine.SetValue(RequireFuncVariableName, requireAction);
            engineCache[rootPath] = engine;
            engine.Execute(scriptResource.Content);

            var value = engine.GetValue(ExportsVariableName);

            if (value.IsObject())
            {
                var exports = value.AsObject();
                GetOptionsFunc     = GetFunc(GetOptionsFuncVariableName, exports);
                TransformModelFunc = GetFunc(TransformFuncVariableName, exports);
            }
            else
            {
                throw new InvalidPreprocessorException("Invalid 'exports' variable definition. 'exports' MUST be an object.");
            }

            return(engine);
        }
コード例 #2
0
        private Engine SetupEngine(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
        {
            var rootPath = (RelativePath)scriptResource.ResourceName;
            var engineCache = new Dictionary<string, Engine>();

            var utility = new TemplateUtility(context);
            _utilityObject = new
            {
                resolveSourceRelativePath = new Func<string, string, string>(utility.ResolveSourceRelativePath)
            };

            var engine = CreateDefaultEngine();

            var requireAction = new Func<string, object>(
                s =>
                {
                    if (!s.StartsWith(RequireRelativePathPrefix))
                    {
                        throw new ArgumentException($"Only relative path starting with `{RequireRelativePathPrefix}` is supported in require");
                    }
                    var relativePath = (RelativePath)s.Substring(RequireRelativePathPrefix.Length);
                    s = relativePath.BasedOn(rootPath);

                    var script = resourceCollection?.GetResource(s);
                    if (string.IsNullOrWhiteSpace(script))
                    {
                        return null;
                    }

                    Engine cachedEngine;
                    if (!engineCache.TryGetValue(s, out cachedEngine))
                    {
                        cachedEngine = CreateEngine(engine, RequireFuncVariableName);
                        engineCache[s] = cachedEngine;
                        cachedEngine.Execute(script);
                    }

                    return cachedEngine.GetValue(ExportsVariableName);
                });

            engine.SetValue(RequireFuncVariableName, requireAction);
            engineCache[rootPath] = engine;
            engine.Execute(scriptResource.Content);

            var value = engine.GetValue(ExportsVariableName);
            if (value.IsObject())
            {
                var exports = value.AsObject();
                GetOptionsFunc = GetFunc(GetOptionsFuncVariableName, exports);
                TransformModelFunc = GetFunc(TransformFuncVariableName, exports);
            }
            else
            {
                throw new InvalidPreprocessorException("Invalid 'exports' variable definition. 'exports' MUST be an object.");
            }

            return engine;
        }
コード例 #3
0
 public TemplateJintPreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
 {
     if (!string.IsNullOrWhiteSpace(scriptResource.Content))
     {
         _engine = SetupEngine(resourceCollection, scriptResource, context);
     }
     else
     {
         _engine = null;
     }
 }
コード例 #4
0
 public TemplateJintPreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
 {
     if (!string.IsNullOrWhiteSpace(scriptResource.Content))
     {
         _engine = SetupEngine(resourceCollection, scriptResource, context);
     }
     else
     {
         _engine = null;
     }
 }
コード例 #5
0
        public Template(string name, TemplateRendererResource templateResource, TemplatePreprocessorResource scriptResource, ResourceCollection resourceCollection, int maxParallelism)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name = name;
            var templateInfo = GetTemplateInfo(Name);

            Extension    = templateInfo.Extension;
            Type         = templateInfo.DocumentType;
            TemplateType = templateInfo.TemplateType;
            _script      = scriptResource?.Content;
            if (!string.IsNullOrWhiteSpace(_script))
            {
                ScriptName        = Name + ".js";
                _preprocessorPool = ResourcePool.Create(() => CreatePreprocessor(resourceCollection, scriptResource), maxParallelism);
                try
                {
                    using (var preprocessor = _preprocessorPool.Rent())
                    {
                        ContainsGetOptions          = preprocessor.Resource.GetOptionsFunc != null;
                        ContainsModelTransformation = preprocessor.Resource.TransformModelFunc != null;
                    }
                }
                catch (Exception e)
                {
                    _preprocessorPool = null;
                    Logger.LogWarning($"{ScriptName} is not a valid template preprocessor, ignored: {e.Message}");
                }
            }

            if (!string.IsNullOrEmpty(templateResource?.Content) && resourceCollection != null)
            {
                _rendererPool            = ResourcePool.Create(() => CreateRenderer(resourceCollection, templateResource), maxParallelism);
                ContainsTemplateRenderer = true;
            }

            if (!ContainsGetOptions && !ContainsModelTransformation && !ContainsTemplateRenderer)
            {
                Logger.LogWarning($"Template {name} contains neither preprocessor to process model nor template to render model. Please check if the template is correctly defined. Allowed preprocessor functions are [exports.getOptions] and [exports.transform].");
            }

            Resources = ExtractDependentResources(Name);
        }
コード例 #6
0
ファイル: Template.cs プロジェクト: vicancy/docfx
        public Template(string name, DocumentBuildContext context, TemplateRendererResource templateResource, TemplatePreprocessorResource scriptResource, ResourceCollection resourceCollection, int maxParallelism)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException(nameof(name));
            }

            Name = name;
            var templateInfo = GetTemplateInfo(Name);
            Extension = templateInfo.Extension;
            Type = templateInfo.DocumentType;
            TemplateType = templateInfo.TemplateType;
            _script = scriptResource?.Content;
            if (!string.IsNullOrWhiteSpace(_script))
            {
                ScriptName = Name + ".js";
                _preprocessorPool = ResourcePool.Create(() => CreatePreprocessor(resourceCollection, scriptResource, context), maxParallelism);
                try
                {
                    using (var preprocessor = _preprocessorPool.Rent())
                    {
                        ContainsGetOptions = preprocessor.Resource.GetOptionsFunc != null;
                        ContainsModelTransformation = preprocessor.Resource.TransformModelFunc != null;
                    }
                }
                catch (Exception e)
                {
                    _preprocessorPool = null;
                    Logger.LogWarning($"{ScriptName} is not a valid template preprocessor, ignored: {e.Message}");
                }
            }

            if (!string.IsNullOrEmpty(templateResource?.Content) && resourceCollection != null)
            {
                _rendererPool = ResourcePool.Create(() => CreateRenderer(resourceCollection, templateResource), maxParallelism);
                ContainsTemplateRenderer = true;
            }

            if (!ContainsGetOptions && !ContainsModelTransformation && !ContainsTemplateRenderer)
            {
                Logger.LogWarning($"Template {name} contains neither preprocessor to process model nor template to render model. Please check if the template is correctly defined. Allowed preprocessor functions are [exports.getOptions] and [exports.transform].");
            }

            Resources = ExtractDependentResources(Name);
        }
コード例 #7
0
ファイル: Template.cs プロジェクト: vicancy/docfx
 private static ITemplatePreprocessor CreatePreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
 {
     return new TemplateJintPreprocessor(resourceCollection, scriptResource, context);
 }
コード例 #8
0
        private static Dictionary <string, TemplateBundle> ReadTemplate(ResourceCollection resource, DocumentBuildContext context, int maxParallelism)
        {
            // type <=> list of template with different extension
            var dict = new Dictionary <string, List <Template> >(StringComparer.OrdinalIgnoreCase);

            if (resource == null || resource.IsEmpty)
            {
                return(new Dictionary <string, TemplateBundle>());
            }

            // Template file ends with .tmpl(Mustache) or .liquid(Liquid)
            // Template file naming convention: {template file name}.{file extension}.(tmpl|liquid)
            // Only files under root folder is searched
            var templates = resource.GetResources(@"[^/]*\.(tmpl|liquid|js)$").ToList();

            if (templates != null)
            {
                foreach (var group in templates.GroupBy(s => Path.GetFileNameWithoutExtension(s.Key), StringComparer.OrdinalIgnoreCase))
                {
                    var currentTemplates =
                        (from i in @group
                         select new
                    {
                        item = i.Value,
                        extension = Path.GetExtension(i.Key),
                        name = i.Key,
                    } into item
                         where IsSupportedTemplateFile(item.extension)
                         select item).ToArray();
                    var currentScripts =
                        (from i in @group
                         select new
                    {
                        item = i.Value,
                        extension = Path.GetExtension(i.Key),
                        name = i.Key,
                    } into item
                         where IsSupportedScriptFile(item.extension)
                         select item).ToArray();

                    if (currentTemplates.Length == 0 && currentScripts.Length == 0)
                    {
                        continue;
                    }

                    // If template file does not exists, while a js script ends with .tmpl.js exists
                    // we consider .tmpl.js file as a standalone preprocess file
                    var name = group.Key;
                    if (currentTemplates.Length == 0)
                    {
                        if (name.EndsWith(ScriptTemplateExtension, StringComparison.OrdinalIgnoreCase))
                        {
                            name = name.Substring(0, name.Length - ScriptTemplateExtension.Length);
                        }
                        else
                        {
                            continue;
                        }
                    }

                    var currentTemplate = currentTemplates.FirstOrDefault();
                    var currentScript   = currentScripts.FirstOrDefault();
                    if (currentTemplates.Length > 1)
                    {
                        Logger.Log(LogLevel.Warning, $"Multiple templates for type '{name}'(case insensitive) are found, the one from '{currentTemplate.item + currentTemplate.extension}' is taken.");
                    }

                    if (currentScripts.Length > 1)
                    {
                        Logger.Log(LogLevel.Warning, $"Multiple template scripts for type '{name}'(case insensitive) are found, the one from '{currentScript.item + currentScript.extension}' is taken.");
                    }

                    TemplateRendererResource templateResource =
                        currentTemplate == null ?
                        null :
                        new TemplateRendererResource(currentTemplate.name, currentTemplate.item, name);
                    TemplatePreprocessorResource templatePrepocessorResource =
                        currentScript == null ?
                        null :
                        new TemplatePreprocessorResource(currentScript.name, currentScript.item);
                    var template = new Template(name, context, templateResource, templatePrepocessorResource, resource, maxParallelism);
                    if (dict.TryGetValue(template.Type, out List <Template> templateList))
                    {
                        templateList.Add(template);
                    }
                    else
                    {
                        dict[template.Type] = new List <Template> {
                            template
                        };
                    }
                }
            }

            return(dict.ToDictionary(s => s.Key, s => new TemplateBundle(s.Key, s.Value)));
        }
コード例 #9
0
ファイル: Template.cs プロジェクト: zhenjiao-ms/docfx
 private static ITemplatePreprocessor CreatePreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource, DocumentBuildContext context)
 {
     return(new TemplateJintPreprocessor(resourceCollection, scriptResource, context));
 }
コード例 #10
0
 private static ITemplatePreprocessor CreatePreprocessor(ResourceCollection resourceCollection, TemplatePreprocessorResource scriptResource)
 {
     return(new TemplateJintPreprocessor(resourceCollection, scriptResource));
 }