Beispiel #1
0
        public bool TryLoadAndValidateToc(Config?config, out ToC?toc)
        {
            toc = null;

            if (config == null)
            {
                return(false);
            }

            var tocFile = new FsPath(_workdir).Combine(config.TOCFile);

            _log.Info("Parsing TOC file...");

            toc = MarkdownUtils.ParseToc(tocFile.ReadFile(_log));

            _log.Info("Found {0} chapters and {1} files", toc.ChapterCount, toc.FilesCount);
            TocValidator tocValidator = new TocValidator(toc, _workdir);

            tocValidator.Validate();

            if (!tocValidator.IsValid)
            {
                _log.Warning("Errors found in TOC file: ");
                foreach (var error in tocValidator.Errors)
                {
                    _log.Warning(error);
                }
                return(false);
            }

            _log.Info("Config file and TOC contain no errors");
            return(true);
        }
Beispiel #2
0
        public async Task <ActionResult <GetResult> > Get([FromQuery] string pluginId)
        {
            if (!await _authManager.HasAppPermissionsAsync(Types.AppPermissions.PluginsManagement))
            {
                return(Unauthorized());
            }

            var plugin    = _pluginManager.GetPlugin(pluginId);
            var content   = string.Empty;
            var changeLog = string.Empty;

            if (plugin != null)
            {
                var readmePath = PathUtils.Combine(plugin.ContentRootPath, Constants.ReadmeFileName);
                if (FileUtils.IsFileExists(readmePath))
                {
                    content = MarkdownUtils.ToHtml(FileUtils.ReadText(readmePath));
                }
                var changeLogPath = PathUtils.Combine(plugin.ContentRootPath, Constants.ChangeLogFileName);
                if (FileUtils.IsFileExists(changeLogPath))
                {
                    changeLog = MarkdownUtils.ToHtml(FileUtils.ReadText(changeLogPath));
                }
            }

            return(new GetResult
            {
                Version = _settingsManager.Version,
                LocalPlugin = plugin,
                Content = content,
                ChangeLog = changeLog
            });
        }
        private string GetHtmlFromChapter(Chapter chapter)
        {
            string result = $"<h3>{chapter.Title}</h3>";

            if (chapter.PicturePath != null)
            {
                result += $"<img src=\"{StorageUtils.GetPictureUri(chapter.PicturePath)}\" alt=\"...\" style=\"max-height: 250px\">";
            }
            result += MarkdownUtils.MarkdownParser(chapter.Text);
            return(result);
        }
Beispiel #4
0
        public void RunStep(RuntimeSettings settings, ILog log)
        {
            if (Content == null)
            {
                throw new DependencyException(nameof(Content));
            }

            if (Template == null)
            {
                throw new DependencyException(nameof(Template));
            }

            log.Info("Generating Sub Markdown Files...");

            using var pipeline = new BookGenPipeline(BookGenPipeline.Web);
            pipeline.InjectRuntimeConfig(settings);

            var bag = new ConcurrentBag <(string source, FsPath target, string title, string content)>();

            Parallel.ForEach(settings.TocContents.Files, file =>
            {
                (string source, FsPath target, string title, string content)result;

                var input     = settings.SourceDirectory.Combine(file);
                result.target = settings.OutputDirectory.Combine(Path.ChangeExtension(file, ".html"));

                log.Detail("Processing file: {0}", input);

                var inputContent = input.ReadFile(log);

                result.title = MarkdownUtils.GetTitle(inputContent);

                if (string.IsNullOrEmpty(result.title))
                {
                    log.Warning("No title found in document: {0}", file);
                    result.title = file;
                }

                result.source  = file;
                result.content = pipeline.RenderMarkdown(inputContent);

                bag.Add(result);
            });

            log.Info("Writing files to disk...");
            foreach (var item in bag)
            {
                Content.Title    = item.title;
                Content.Metadata = settings.MetataCache[item.source];
                Content.Content  = item.content;
                item.target.WriteFile(log, Template.Render());
            }
        }
Beispiel #5
0
        /// <summary>
        /// Parses the markdown for a title, renders to HTML and returns a model that
        /// contains the relevant items.
        /// </summary>
        /// <param name="markdown"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        private MarkdownModel ParseMarkdownToModel(string markdown, MarkdownModel model = null)
        {
            if (model == null)
            {
                model = new MarkdownModel();
            }


            var firstLines     = MarkdownUtils.GetLines(markdown, 30);
            var firstLinesText = String.Join("\n", firstLines);

            // Assume YAML
            if (markdown.StartsWith("---"))
            {
                var yaml = MarkdownUtils.ExtractString(firstLinesText, "---", "---", returnDelimiters: true);
                if (yaml != null)
                {
                    model.Title      = MarkdownUtils.ExtractString(yaml, "title: ", "\n");
                    model.YamlHeader = yaml.Replace("---", "").Trim();
                }
            }

            if (model.Title == null)
            {
                foreach (var line in firstLines.Take(10))
                {
                    if (line.TrimStart().StartsWith("# "))
                    {
                        model.Title = line.TrimStart(new char[] { ' ', '\t', '#' });
                        break;
                    }
                }
            }

            model.RawMarkdown      = markdown;
            model.RenderedMarkdown = Markdown.ParseHtmlString(markdown, sanitizeHtml: Configuration.SanitizeHtml);

            model.PhysicalPath = HttpContext.Current.Request.PhysicalPath;
            model.RelativePath = HttpContext.Current.Request.Path;

            return(model);
        }
Beispiel #6
0
        public void RunStep(RuntimeSettings settings, ILog log)
        {
            if (Content == null)
            {
                throw new DependencyException(nameof(Content));
            }

            if (Template == null)
            {
                throw new DependencyException(nameof(Template));
            }

            log.Info("Generating epub pages...");

            int index = 1;

            using var pipeline = new BookGenPipeline(BookGenPipeline.Epub);
            pipeline.InjectRuntimeConfig(settings);

            foreach (var file in settings.TocContents.Files)
            {
                _session.GeneratedFiles.Add($"page_{index:D3}");

                FsPath?target = settings.OutputDirectory.Combine($"epubtemp\\OPS\\page_{index:D3}.xhtml");


                log.Detail("Processing file for epub output: {0}", file);
                var input = settings.SourceDirectory.Combine(file);

                var inputContent = input.ReadFile(log);

                Content.Title   = MarkdownUtils.GetTitle(inputContent);
                Content.Content = pipeline.RenderMarkdown(inputContent);

                var html = XhtmlNormalizer.NormalizeToXHTML(Template.Render());

                target.WriteFile(log, html);
                ++index;
            }
        }
        public override Task Execute(Pipeline pipeline)
        {
            AssetDatabase.SaveAssets();

            var mainManifest = pipeline.Manifest;
            var folderTrees  = mainManifest.Data.OfType <LanguageFolderTree>().ToList();

            var hasValidTreeFolders = folderTrees.Any(ft => ft.languageFolders.Any(lf => !lf.languageName.IsNullOrEmptyOrWhitespace() && lf.languageFiles.Any()));

            if (!hasValidTreeFolders)
            {
                var scriptPath = UnityWebRequest.EscapeURL(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)));
                pipeline.Log(LogLevel.Warning, $"No valid LanguageTreeFolder defined, skipping {MarkdownUtils.GenerateAssetLink(nameof(StageLanguageFiles), scriptPath)} PipelineJob");
                return(Task.CompletedTask);
            }

            var languageArtifactPath = PathReference.ResolvePath(LanguageArtifactPath, pipeline, this);

            IOUtils.EnsureDirectory(languageArtifactPath);

            var allLanguageFiles = folderTrees
                                   .SelectMany(lft => lft.languageFolders)
                                   .SelectMany(lf => lf.languageFiles)
                                   .ToArray();

            var logBuilder = new List <string>();

            if (CheckForInvalidFiles(allLanguageFiles, out var invalidFiles))
            {
                foreach (var(asset, error) in invalidFiles)
                {
                    var scriptPath = UnityWebRequest.EscapeURL(AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)));
                    switch (error)
                    {
                    case InvalidLangfile.InvalidExtension:
                        logBuilder.Add($"* File {MarkdownUtils.GenerateAssetLink(asset)} has an invalid extension ({Path.GetExtension(AssetDatabase.GetAssetPath(asset))}), extension should be either **\".txt\"** or **\".json\"**, skipping {MarkdownUtils.GenerateAssetLink(nameof(StageLanguageFiles), scriptPath)} PipelineJob");
                        break;

                    case InvalidLangfile.FormatError:
                        logBuilder.Add($"* File {MarkdownUtils.GenerateAssetLink(asset)} has JSON related format errors, skipping {MarkdownUtils.GenerateAssetLink(nameof(StageLanguageFiles), scriptPath)} PipelineJob");
                        break;

                    case InvalidLangfile.NodeError:
                        logBuilder.Add($"* File {MarkdownUtils.GenerateAssetLink(asset)} has an invalid JSON Node, the name for the json dictionary needs to be **\"strings\"**, skipping {MarkdownUtils.GenerateAssetLink(nameof(StageLanguageFiles), scriptPath)} PipelineJob");
                        break;
                    }
                }
                pipeline.Log(LogLevel.Warning, $"Found a total of {invalidFiles.Length} invalid language files on manifest {MarkdownUtils.GenerateAssetLink(mainManifest)}", logBuilder.ToArray());
                logBuilder.Clear();
                return(Task.CompletedTask);
            }

            foreach (var languageFolderTree in folderTrees)
            {
                string rootLanguageFolderPath = Path.Combine(languageArtifactPath, languageFolderTree.rootFolderName);
                IOUtils.EnsureDirectory(rootLanguageFolderPath);

                foreach (LanguageFolder languageFolder in languageFolderTree.languageFolders)
                {
                    string langFolder = Path.Combine(rootLanguageFolderPath, languageFolder.languageName);
                    IOUtils.EnsureDirectory(langFolder);
                    foreach (TextAsset asset in languageFolder.languageFiles)
                    {
                        string relativeAssetPath = AssetDatabase.GetAssetPath(asset);
                        string fullAssetPath     = Path.GetFullPath(relativeAssetPath);
                        string fullAssetName     = Path.GetFileName(fullAssetPath);
                        string destPath          = Path.Combine(langFolder, fullAssetName);
                        FileUtil.ReplaceFile(relativeAssetPath, destPath);
                        logBuilder.Add($"* Moved {MarkdownUtils.GenerateAssetLink(asset)} from ***{relativeAssetPath}*** to ***{destPath}***");
                    }
                }
            }
            pipeline.Log(LogLevel.Information, $"Finished moving language files to {LanguageArtifactPath} ({languageArtifactPath})", logBuilder.ToArray());
            logBuilder.Clear();

            foreach (var languageFolderTree in folderTrees)
            {
                var languageNames = languageFolderTree.languageFolders.Select(lf => lf.languageName).ToArray();
                foreach (var outputPath in languageFolderTree.StagingPaths.Select(path => path.Resolve(pipeline, this)))
                {
                    foreach (string dirPath in Directory.GetDirectories(languageArtifactPath, "*", SearchOption.AllDirectories))
                    {
                        IOUtils.EnsureDirectory(dirPath.Replace(languageArtifactPath, outputPath));
                    }

                    foreach (string filePath in Directory.GetFiles(languageArtifactPath, "*", SearchOption.AllDirectories))
                    {
                        bool found = false;
                        foreach (var languageName in languageNames)
                        {
                            if (filePath.IndexOf(languageName, StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                found = true;
                                break;
                            }
                        }
                        if (!found)
                        {
                            continue;
                        }

                        string destFileName = filePath.Replace(languageArtifactPath, outputPath);
                        Directory.CreateDirectory(Path.GetDirectoryName(destFileName));
                        FileUtil.ReplaceFile(filePath, destFileName);
                        logBuilder.Add($"* Moved {Path.GetFileName(filePath)} from ***{filePath}*** to ***{destFileName}***");
                    }
                }
            }
            pipeline.Log(LogLevel.Information, $"Finished moving language files to manifest's Staging Paths.", logBuilder.ToArray());
            return(Task.CompletedTask);
        }
Beispiel #8
0
        public object Scope(string id)
        {
            var data = Data.Children.FirstOrDefault(c => c.IsSameName("scope") && c.ValOf("run-id").EqualsOrdIgnoreCase(id));

            if (data == null)
            {
                return(new Http404NotFound());
            }
            if (WorkContext.RequestedJson)
            {
                return(data);
            }

            var scopeContent = data.ValOf("doc-content");
            var excision     = MarkdownUtils.ExciseSection(scopeContent, "## Endpoints");

            var epContent = new StringBuilder();

            epContent.AppendLine("## Endpoints");

            foreach (var nep in data.Children.Where(c => c.IsSameName("endpoint")))
            {
                var epdoc      = nep.ValOf("doc-content-tpl");
                var hadContent = false;
                if (epdoc.IsNotNullOrWhiteSpace())
                {
                    hadContent = true;
                    //epoint content in ep section scope
                    epdoc = MarkdownUtils.EvaluateVariables(epdoc, (v) =>
                    {
                        if (v.IsNullOrWhiteSpace())
                        {
                            return(v);
                        }
                        //Escape: ``{{a}}`` -> `{a}`
                        if (v.StartsWith("{") && v.EndsWith("}"))
                        {
                            return(v.Substring(1, v.Length - 2));
                        }
                        if (v.StartsWith("@"))
                        {
                            return($"`{{{v}}}`");      //do not expand TYPE spec here
                        }
                        //else navigate config path
                        return(nep.Navigate(v).Value);
                    });
                    epContent.AppendLine(epdoc);
                }
                else
                {
                    //otherwise build EPOINT documentation here
                    epContent.AppendLine("### {0} - {1}".Args(nep.ValOf("uri"), nep.ValOf("title")));
                    var d = nep.ValOf("description");
                    if (d.IsNotNullOrWhiteSpace())
                    {
                        epContent.AppendLine(d);
                    }
                }

                //Add type map sections:
                var refTypes = nep.Attributes.Where(a => a.IsSameName("tp-ref"));
                if (refTypes.Any())
                {
                    epContent.AppendLine("##### Referenced Types");
                    foreach (var tref in refTypes)
                    {
                        var nt  = Data["type-schemas"][tref.Value];
                        var sku = nt.ValOf("sku");
                        if (sku.IsNullOrWhiteSpace())
                        {
                            continue;
                        }
                        hadContent = true;
                        epContent.AppendLine("* <a href=\"schema?id={0}\">{1}</a>".Args(tref.Value, sku));
                    }
                }

                if (hadContent)
                {
                    epContent.AppendLine("##### Definition Metadata");
                }

                epContent.AppendLine("```");
                epContent.AppendLine(nep.ToLaconicString(CodeAnalysis.Laconfig.LaconfigWritingOptions.PrettyPrint));
                epContent.AppendLine("```");
                epContent.AppendLine("---");
            }//foreach endpoint



            //eval variables
            var finalMarkdown = "{0}\n{1}\n{2}".Args(excision.content?.Substring(0, excision.iexcision),
                                                     epContent.ToString(),
                                                     excision.content?.Substring(excision.iexcision));

            //eval type references
            finalMarkdown = MarkdownUtils.EvaluateVariables(finalMarkdown, v =>
            {
                if (v.IsNotNullOrWhiteSpace() && v.StartsWith("@"))
                {
                    v = v.Substring(1);
                    return("<a href=\"{0}\">{1} Schema</a>".Args("schema?id={0}".Args(v), v));
                }
                return(v);
            });

            var html = MarkdownUtils.MarkdownToHtml(finalMarkdown);

            return(ScopeView(html));
        }
Beispiel #9
0
        public void EnsureThat_MarkdownUtils_GetTitleWorksCorrectly(string input, string expected)
        {
            var result = MarkdownUtils.GetTitle(input);

            Assert.AreEqual(expected, result);
        }
        private ConfigSectionNode describe(Type tController, object instance, ApiDocGenerator.ControllerContext apictx, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules)
        {
            var cdata          = dataRoot.AddChildNode("scope");
            var cattr          = apictx.ApiDocAttr;
            var docContent     = tController.GetText(cattr.DocFile ?? "{0}.md".Args(tController.Name));
            var ctlTitle       = MarkdownUtils.GetTitle(docContent);
            var ctlDescription = MarkdownUtils.GetTitleDescription(docContent);

            (var drequest, var dresponse) = writeCommon(ctlTitle, ctlDescription, tController, apictx.Generator, cattr, cdata);
            cdata.AddAttributeNode("uri-base", cattr.BaseUri);
            cdata.AddAttributeNode("auth", cattr.Authentication);

            cdata.AddAttributeNode("doc-content", docContent);

            var allMethodContexts = apictx.Generator.GetApiMethods(tController, apictx.ApiDocAttr);

            foreach (var mctx in allMethodContexts)
            {
                var edata = cdata.AddChildNode("endpoint");
                (var mrequest, var mresponse) = writeCommon(null, null, mctx.Method, apictx.Generator, mctx.ApiEndpointDocAttr, edata);

                var epuri = mctx.ApiEndpointDocAttr.Uri.AsString().Trim();
                if (epuri.IsNullOrWhiteSpace())
                {
                    // infer from action attribute
                    var action = mctx.Method.GetCustomAttributes <ActionBaseAttribute>().FirstOrDefault();
                    if (action != null)
                    {
                        epuri = action.Name;
                    }
                    if (epuri.IsNullOrWhiteSpace())
                    {
                        epuri = mctx.Method.Name;
                    }
                }


                if (!epuri.StartsWith("/"))
                {
                    var bu = cattr.BaseUri.Trim();
                    if (!bu.EndsWith("/"))
                    {
                        bu += "/";
                    }
                    epuri = bu + epuri;
                }

                edata.AddAttributeNode("uri", epuri);
                writeCollection(mctx.ApiEndpointDocAttr.Methods, "method", mrequest, ':');

                //docAnchor
                var docAnchor = mctx.ApiEndpointDocAttr.DocAnchor.Default("### " + epuri);
                edata.AddAttributeNode("doc-content", MarkdownUtils.GetSectionContent(docContent, docAnchor));

                //Get all method attributes except ApiDoc
                var epattrs = mctx.Method
                              .GetCustomAttributes(true)
                              .Where(a => !(a is ApiDocAttribute) && !(a is ActionBaseAttribute));

                writeInstanceCollection(epattrs.Where(a => !(a is IInstanceCustomMetadataProvider) ||
                                                      (a is IInstanceCustomMetadataProvider cip &&
                                                       cip.ShouldProvideInstanceMetadata(apictx.Generator, edata))).ToArray(), TYPE_REF, edata, apictx.Generator);

                writeTypeCollection(epattrs.Select(a => a.GetType())
                                    .Where(t => !apictx.Generator.IsWellKnownType(t))
                                    .Distinct()
                                    .ToArray(),
                                    TYPE_REF, edata, apictx.Generator);//distinct attr types

                //todo Get app parameters look for Docs and register them and also permissions
                var epargs = mctx.Method.GetParameters()
                             .Where(pi => !pi.IsOut && !pi.ParameterType.IsByRef && !apictx.Generator.IsWellKnownType(pi.ParameterType))
                             .Select(pi => pi.ParameterType).ToArray();
                writeTypeCollection(epargs, TYPE_REF, edata, apictx.Generator);
            }

            return(cdata);
        }
 /// <summary>
 /// Parses out script tags that might not be encoded yet
 /// </summary>
 /// <param name="html"></param>
 /// <returns></returns>
 protected virtual string SanitizeHtml(string html)
 {
     return(MarkdownUtils.SanitizeHtml(html));
 }
        private ConfigSectionNode describe(Type tController, object instance, ApiDocGenerator.ControllerContext apictx, ConfigSectionNode dataRoot, NodeOverrideRules overrideRules)
        {
            var cdata          = dataRoot.AddChildNode("scope");
            var cattr          = apictx.ApiDocAttr;
            var docContent     = tController.GetText(cattr.DocFile ?? "{0}.md".Args(tController.Name));
            var ctlTitle       = MarkdownUtils.GetTitle(docContent);
            var ctlDescription = MarkdownUtils.GetTitleDescription(docContent);

            (var drequest, var dresponse) = writeCommon(ctlTitle, ctlDescription, tController, apictx.Generator, cattr, cdata);
            cdata.AddAttributeNode("uri-base", cattr.BaseUri);
            cdata.AddAttributeNode("auth", cattr.Authentication);

            cdata.AddAttributeNode("doc-content-tpl", docContent);

            var allMethodContexts = apictx.Generator.GetApiMethods(tController, apictx.ApiDocAttr);

            foreach (var mctx in allMethodContexts)
            {
                var edata = cdata.AddChildNode("endpoint");
                (var mrequest, var mresponse) = writeCommon(null, null, mctx.Method, apictx.Generator, mctx.ApiEndpointDocAttr, edata);

                var epuri = mctx.ApiEndpointDocAttr.Uri.AsString().Trim();
                if (epuri.IsNullOrWhiteSpace())
                {
                    // infer from action attribute
                    var action = mctx.Method.GetCustomAttributes <ActionBaseAttribute>().FirstOrDefault();
                    if (action != null)
                    {
                        epuri = action.Name;
                    }
                    if (epuri.IsNullOrWhiteSpace())
                    {
                        epuri = mctx.Method.Name;
                    }
                }


                if (!epuri.StartsWith("/"))
                {
                    var bu = cattr.BaseUri.Trim();
                    if (!bu.EndsWith("/"))
                    {
                        bu += "/";
                    }
                    epuri = bu + epuri;
                }

                edata.AddAttributeNode("uri", epuri);
                writeCollection(mctx.ApiEndpointDocAttr.Methods, "method", mrequest, ':');

                //Get all method attributes except ApiDoc
                var epattrs = mctx.Method
                              .GetCustomAttributes(true)
                              .Where(a => !(a is ApiDocAttribute) &&
                                     !(a is ActionBaseAttribute) &&
                                     !apictx.Generator.IgnoreTypePatterns.Any(ignore => a.GetType().FullName.MatchPattern(ignore))
                                     );

                writeInstanceCollection(epattrs.Where(a => !(a is IInstanceCustomMetadataProvider) ||
                                                      (a is IInstanceCustomMetadataProvider cip &&
                                                       cip.ShouldProvideInstanceMetadata(apictx.Generator, edata))).ToArray(), TYPE_REF, edata, apictx.Generator);

                writeTypeCollection(epattrs.Select(a => a.GetType())
                                    .Where(t => !apictx.Generator.IsWellKnownType(t))
                                    .Distinct()
                                    .ToArray(),
                                    TYPE_REF, edata, apictx.Generator);//distinct attr types

                //get method parameters
                var epargs = mctx.Method.GetParameters()
                             .Where(pi => !pi.IsOut &&
                                    !pi.ParameterType.IsByRef &&
                                    !apictx.Generator.IsWellKnownType(pi.ParameterType) &&
                                    !apictx.Generator.IgnoreTypePatterns.Any(ignore => pi.ParameterType.FullName.MatchPattern(ignore))
                                    )
                             .Select(pi => pi.ParameterType).ToArray();
                writeTypeCollection(epargs, TYPE_REF, edata, apictx.Generator);

                //docAnchor
                var docAnchor    = mctx.ApiEndpointDocAttr.DocAnchor.Default("### " + epuri);
                var epDocContent = MarkdownUtils.GetSectionContent(docContent, docAnchor);

                edata.AddAttributeNode("doc-content-tpl", epDocContent);

                //finally regenerate doc content expanding all variables
                epDocContent = MarkdownUtils.EvaluateVariables(epDocContent, (v) =>
                {
                    if (v.IsNullOrWhiteSpace())
                    {
                        return(v);
                    }
                    //Escape: ``{{a}}`` -> `{a}`
                    if (v.StartsWith("{") && v.EndsWith("}"))
                    {
                        return(v.Substring(1, v.Length - 2));
                    }
                    if (v.StartsWith("@"))
                    {
                        return($"`{{{v}}}`");        //do not expand TYPE spec here
                    }
                    //else navigate config path
                    return(edata.Navigate(v).Value);
                });

                edata.AddAttributeNode("doc-content", epDocContent);
            }//all endpoints

            //finally regenerate doc content expanding all variables for the controller
            docContent = MarkdownUtils.EvaluateVariables(docContent, (v) =>
            {
                if (v.IsNullOrWhiteSpace())
                {
                    return(v);
                }
                //Escape: ``{{a}}`` -> `{a}`
                if (v.StartsWith("{") && v.EndsWith("}"))
                {
                    return(v.Substring(1, v.Length - 2));
                }
                if (v.StartsWith("@"))
                {
                    return($"`{{{v}}}`");          //do not expand TYPE spec here
                }
                //else navigate config path
                return(cdata.Navigate(v).Value);
            });

            cdata.AddAttributeNode("doc-content", docContent);

            return(cdata);
        }
Beispiel #13
0
        public static async Task <(bool Success, string name, string filePath)> PackageAsync(IPathManager pathManager, ICacheManager cacheManager, IDatabaseManager databaseManager, string directory, bool isOverride)
        {
            var site = await databaseManager.SiteRepository.GetSiteByDirectoryAsync(directory);

            var sitePath = await pathManager.GetSitePathAsync(site);

            if (site == null || !DirectoryUtils.IsDirectoryExists(sitePath))
            {
                await WriteUtils.PrintErrorAsync($@"Invalid site directory path: ""{directory}""");

                return(false, null, null);
            }

            var   readme = string.Empty;
            Theme theme  = null;

            var readmePath = PathUtils.Combine(sitePath, "README.md");

            if (FileUtils.IsFileExists(readmePath))
            {
                readme = FileUtils.ReadText(readmePath);
                var yaml = MarkdownUtils.GetYamlFrontMatter(readme);
                if (!string.IsNullOrEmpty(yaml))
                {
                    readme = MarkdownUtils.RemoveYamlFrontMatter(readme);
                    theme  = YamlUtils.Deserialize <Theme>(yaml);
                }
            }

            var writeReadme = false;

            if (theme == null || string.IsNullOrEmpty(theme.Name) || string.IsNullOrEmpty(theme.CoverUrl))
            {
                writeReadme = true;
                theme       = new Theme
                {
                    Name            = ReadUtils.GetString("name:"),
                    CoverUrl        = ReadUtils.GetString("cover image url:"),
                    Summary         = ReadUtils.GetString("repository url:"),
                    Tags            = ReadUtils.GetStringList("tags:"),
                    ThumbUrls       = ReadUtils.GetStringList("thumb image urls:"),
                    Compatibilities = ReadUtils.GetStringList("compatibilities:"),
                    Price           = ReadUtils.GetYesNo("is free?") ? 0 : ReadUtils.GetDecimal("price:"),
                };
            }

            if (writeReadme)
            {
                readme = @$ "---
{YamlUtils.Serialize(theme)}
---

" + readme;
                FileUtils.WriteText(readmePath, readme);
            }

            var packageName = "T_" + theme.Name.Replace(" ", "_");
            var packagePath = pathManager.GetSiteTemplatesPath(packageName);
            var fileName    = packageName + ".zip";
            var filePath    = pathManager.GetSiteTemplatesPath(fileName);

            if (!isOverride && FileUtils.IsFileExists(filePath))
            {
                return(true, theme.Name, filePath);
            }

            FileUtils.DeleteFileIfExists(filePath);
            DirectoryUtils.DeleteDirectoryIfExists(packagePath);

            await Console.Out.WriteLineAsync($"Theme name: {theme.Name}");

            await Console.Out.WriteLineAsync($"Theme folder: {packagePath}");

            await Console.Out.WriteLineAsync("Theme packaging...");

            var caching = new CacheUtils(cacheManager);
            var manager = new SiteTemplateManager(pathManager, databaseManager, caching);

            if (manager.IsSiteTemplateDirectoryExists(packageName))
            {
                manager.DeleteSiteTemplate(packageName);
            }

            var directoryNames = DirectoryUtils.GetDirectoryNames(sitePath);

            var directories = new List <string>();
            var siteDirList = await databaseManager.SiteRepository.GetSiteDirsAsync(0);

            foreach (var directoryName in directoryNames)
            {
                var isSiteDirectory = false;
                if (site.Root)
                {
                    foreach (var siteDir in siteDirList)
                    {
                        if (StringUtils.EqualsIgnoreCase(siteDir, directoryName))
                        {
                            isSiteDirectory = true;
                        }
                    }
                }
                if (!isSiteDirectory && !pathManager.IsSystemDirectory(directoryName))
                {
                    directories.Add(directoryName);
                }
            }

            var files = DirectoryUtils.GetFileNames(sitePath);

            var exportObject = new ExportObject(pathManager, databaseManager, caching, site);
            await exportObject.ExportFilesToSiteAsync(packagePath, true, directories, files, true);

            var siteContentDirectoryPath = pathManager.GetSiteTemplateMetadataPath(packagePath, DirectoryUtils.SiteFiles.SiteTemplates.SiteContent);

            await exportObject.ExportSiteContentAsync(siteContentDirectoryPath, true, true, new List <int>());

            await SiteTemplateManager.ExportSiteToSiteTemplateAsync(pathManager, databaseManager, caching, site, packageName);

            var siteTemplateInfo = new SiteTemplateInfo
            {
                SiteTemplateName = theme.Name,
                PicFileName      = string.Empty,
                WebSiteUrl       = string.Empty,
                Description      = string.Empty
            };
            var xmlPath = pathManager.GetSiteTemplateMetadataPath(packagePath,
                                                                  DirectoryUtils.SiteFiles.SiteTemplates.FileMetadata);

            XmlUtils.SaveAsXml(siteTemplateInfo, xmlPath);

            pathManager.CreateZip(filePath, packagePath);

            return(true, theme.Name, filePath);
        }
Beispiel #14
0
        public void RunStep(RuntimeSettings settings, ILog log)
        {
            if (Content == null)
            {
                throw new DependencyException(nameof(Content));
            }

            if (Template == null)
            {
                throw new DependencyException(nameof(Template));
            }

            log.Info("Generating Wordpress export content...");
            _session.CurrentChannel.Item = new List <Item>();

            var host = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpressTargetHost];

            bool parentpageCreate = settings.CurrentBuildConfig.TemplateOptions.TryGetOption(TemplateOptions.WordpressCreateParent, out bool createparent) && createparent;
            bool createfillers    = settings.CurrentBuildConfig.TemplateOptions.TryGetOption(TemplateOptions.WordpressCreateFillerPages, out bool filler) && filler;

            int mainorder    = 0;
            int uid          = 2000;
            int globalparent = 0;

            if (parentpageCreate)
            {
                string fillerPage = createfillers ? CreateFillerPage(settings.TocContents.GetLinksForChapter()) : "";
                string title      = settings.CurrentBuildConfig.TemplateOptions[TemplateOptions.WordpresCreateParentTitle];
                string path       = $"{host}{Encode(title)}";
                Item   parent     = CreateItem(uid, 0, mainorder, fillerPage, title, path, settings.CurrentBuildConfig.TemplateOptions);
                _session.CurrentChannel.Item.Add(parent);
                globalparent = uid;
                ++uid;
            }

            using var pipeline = new BookGenPipeline(BookGenPipeline.Wordpress);
            pipeline.InjectRuntimeConfig(settings);

            foreach (var chapter in settings.TocContents.Chapters)
            {
                string fillerPage = createfillers ? CreateFillerPage(settings.TocContents.GetLinksForChapter(chapter)) : "";
                string path       = $"{host}{Encode(chapter)}";
                int    parent_uid = uid;

                Item parent = CreateItem(uid, globalparent, mainorder, fillerPage, chapter, path, settings.CurrentBuildConfig.TemplateOptions);
                _session.CurrentChannel.Item.Add(parent);
                int suborder = 0;
                uid++;

                foreach (var file in settings.TocContents.GetLinksForChapter(chapter).Select(l => l.Url))
                {
                    log.Detail("Processing {0}...", file);
                    var input = settings.SourceDirectory.Combine(file);
                    var raw   = input.ReadFile(log);
                    Content.Content = pipeline.RenderMarkdown(raw);

                    var title = MarkdownUtils.GetTitle(raw);

                    string subpath = $"{host}{Encode(chapter)}/{Encode(title)}";
                    var    result  = CreateItem(uid, parent_uid, suborder, Template.Render(), title, subpath, settings.CurrentBuildConfig.TemplateOptions);

                    _session.CurrentChannel.Item.Add(result);
                    ++suborder;
                    ++uid;
                }
                ++mainorder;
            }
        }