Inheritance: OutputFile
Esempio n. 1
0
        private string RenderContentForExtension(SourceFile source, string content, string extension, DocumentFile contextDocument, string documentContent, LayoutFile contextLayout)
        {
            RenderingEngine engine;

            if (this.Transaction.Engines.TryGetValue(extension, out engine))
            {
                var backupContent = contextDocument.Content;

                try
                {
                    contextDocument.Content = documentContent;

                    dynamic data = new DynamicRenderDocument(contextDocument, contextLayout, this.Transaction.Site);

                    var result = engine.Render(source, content, data);

                    return result;
                }
                finally
                {
                    contextDocument.Content = backupContent;
                }
            }
            else
            {
                Console.WriteLine("Cannot find a rendering engine for extension: {0}", extension);
                return null;
            }
        }
Esempio n. 2
0
        private DocumentFile(DocumentFile original)
            : base(original)
        {
            this.Author = original.Author;
            this.Draft  = original.Draft;
            this.Id     = original.Id;
            this.ExtensionsForRendering = new List <string>(original.ExtensionsForRendering);
            this.Metadata = new MetadataCollection(original.Metadata);
            this.Order    = original.Order;
            this.Paginate = original.Paginate; // TODO: probably should not be shallow copying this, right?
            this.ParentId = original.ParentId;

            this.SourceContent = original.SourceContent;
            this.Summary       = original.Summary;

            this.NextDocument     = original.NextDocument;
            this.ParentDocument   = original.ParentDocument;
            this.PreviousDocument = original.PreviousDocument;

            this.Book      = original.Book;
            this.Chapter   = original.Chapter;
            this.Paginator = original.Paginator;

            this.Now = original.Now;
        }
Esempio n. 3
0
        public BookPage GetWithRenderingDocument(DocumentFile activeDocument)
        {
            var page = this;

            if (this.Document == activeDocument)
            {
                page = new BookPage(this.Document, this.Chapter);

                page.Active = true;

                page.SubPageActive = false;

                page.SubPages = this.SubPages;
            }
            else if (this.SubPages != null)
            {
                var subPages = this.SubPages.Select(p => p.GetWithRenderingDocument(activeDocument)).ToList();

                if (subPages.Any(c => c.Active || c.SubPageActive))
                {
                    page = new BookPage(this.Document, this.Chapter);

                    page.Active = false;

                    page.SubPageActive = true;

                    page.SubPages = subPages;
                }
            }

            return page;
        }
Esempio n. 4
0
        private static IEnumerable <DocumentFile> LoadDocuments(string rootPath, string outputPath, string url, string rootUrl, Author author, IEnumerable <string> renderedExtensions)
        {
            if (!Directory.Exists(rootPath))
            {
                return(Enumerable.Empty <DocumentFile>());
            }

            return(Directory.GetFiles(rootPath, "*", SearchOption.AllDirectories)
                   .AsParallel()
                   .Select(
                       file =>
            {
                var documentFile = new DocumentFile(file, rootPath, outputPath, url, rootUrl, author);

                documentFile.Load(LoadDocumentFlags.DateFromFileName | LoadDocumentFlags.DateInPath | LoadDocumentFlags.CleanUrls, renderedExtensions);

                return documentFile;
            }));

            //foreach (var file in Directory.GetFiles(rootPath, "*", SearchOption.AllDirectories))
            //{
            //    var documentFile = new DocumentFile(file, rootPath, outputPath, url, rootUrl, author);

            //    documentFile.Load(LoadDocumentFlags.DateFromFileName | LoadDocumentFlags.DateInPath | LoadDocumentFlags.CleanUrls, renderedExtensions);

            //    yield return documentFile;
            //}
        }
Esempio n. 5
0
        public DocumentFile RenderDocumentContent(DocumentFile document)
        {
            var content = document.SourceContent;

            var layout = document?.Layouts.FirstOrDefault();

            foreach (var extension in document.ExtensionsForRendering)
            {
                content = this.RenderContentForExtension(document, content, extension, document, content, layout);
            }

            document.Content = content;

            if (String.IsNullOrEmpty(document.Summary) && !String.IsNullOrEmpty(document.Content))
            {
                document.Summary = Summarize(document.Content);
            }

            if (String.IsNullOrEmpty(document.Description) && !String.IsNullOrEmpty(document.Summary))
            {
                document.Description = StripHtml(document.Summary);
            }

            if (layout != null)
            {
                this.AssignLayoutMetadataToDocument(document, layout);
            }

            return document;
        }
Esempio n. 6
0
        private DocumentFile(DocumentFile original)
            : base(original)
        {
            this.ExtensionsForRendering = new List<string>(original.ExtensionsForRendering);
            this.Layouts = new List<LayoutFile>(original.Layouts);
            this.Queries = original.Queries;
            this.Partial = original.Partial;

            this.Author = original.Author;
            this.Layout = original.Layout;
            this.Content = original.Content;
            this.Description = original.Description;
            this.Draft = original.Draft;
            this.Id = original.Id;
            this.Order = original.Order;
            this.PaginateQuery = original.PaginateQuery;
            this.ParentId = original.ParentId;
            this.SourceContent = original.SourceContent;
            this.Summary = original.Summary;
            this.NextDocument = original.NextDocument;
            this.ParentDocument = original.ParentDocument;
            this.PreviousDocument = original.PreviousDocument;
            this.Book = original.Book;
            this.Chapter = original.Chapter;
            this.Paginator = original.Paginator;
            this.Now = original.Now;
            this.Metadata = original.Metadata;

            this.Cloned = true;
        }
Esempio n. 7
0
        public string RenderDocumentContentUsingLayout(DocumentFile document, string documentContent, LayoutFile layout)
        {
            var content = this.RenderContentForExtension(layout, layout.SourceContent, layout.Extension, document, documentContent, layout);

            document.AddContributingFile(layout);

            this.AssignLayoutMetadataToDocument(document, layout);

            return content;
        }
Esempio n. 8
0
        public Book(string id, List<BookPage> chapters, DocumentFile parentDocument, DocumentFile renderingDocument)
        {
            this.Id = id;

            this.ParentDocument = parentDocument;

            this.Chapters = chapters;

            this.RenderingDocument = renderingDocument;
        }
Esempio n. 9
0
        public dynamic GetAsDynamic(DocumentFile activeDocument)
        {
            var data = new CaseInsensitiveExpando();

            var chapters = this.Chapters.Select(c => c.GetAsDynamic(activeDocument)).ToList();

            data["Id"]       = this.Id;
            data["Chapters"] = chapters;

            return(data);
        }
Esempio n. 10
0
        public BookPage(DocumentFile document, bool chapterPage = false)
        {
            this.Document = document;

            this.Chapter = chapterPage;

            if (this.Chapter)
            {
                this.SubPages = new List<BookPage>();
            }
        }
Esempio n. 11
0
        private DocumentFile(DocumentFile original)
            : base(original)
        {
            this.Author   = original.Author;
            this.Draft    = original.Draft;
            this.Date     = original.Date;
            this.Paginate = original.Paginate; // TODO: probably should not be shallow copying this, right?

            _summary         = original._summary;
            _explicitSummary = original._explicitSummary;

            this.Metadata = new MetadataCollection(original.Metadata);
            this.ExtensionsForRendering = new List <string>(original.ExtensionsForRendering);
        }
Esempio n. 12
0
        public override dynamic GetAsDynamic(DocumentFile activeDocument)
        {
            var data = base.GetAsDynamic(activeDocument) as CaseInsensitiveExpando;

            data["Chapter"] = true;
            data["Page"]    = false;

            var children    = this.PagesOrSubChapters.Select(p => p.GetAsDynamic(activeDocument)).ToList();
            var childActive = children.Any(c => c.Active || c.ChildActive);

            data["Children"]    = children;
            data["ChildActive"] = childActive;

            return(data);
        }
Esempio n. 13
0
        public virtual dynamic GetAsDynamic(DocumentFile activeDocument)
        {
            var data = new CaseInsensitiveExpando();

            data["Active"]   = (this.Document == activeDocument);
            data["Document"] = this.Document.GetAsDynamic();

            data["Chapter"] = false;
            data["Page"]    = true;

            data["ChildActive"] = false;
            data["Children"]    = null;

            return(data);
        }
        public void CanCastDynamicDocumentToDocument()
        {
            var sitePath = @"C:\site\";
            var documentsPath = sitePath + @"documents\";
            var layoutsPath = sitePath + @"layouts\";
            var outputPath = sitePath + @"build\";

            var doc = new DocumentFile(documentsPath + "foo.html.md", documentsPath, outputPath + "foo.html", outputPath, String.Empty, String.Empty, null, null, null);
            var dyn = new DynamicDocumentFile(null, doc, null);

            Assert.Same(doc, dyn.GetDocument());

            var ds = new[] { dyn };
            var s = ds.Select(d => d.GetDocument()).Single();
            Assert.Same(doc, s);
        }
Esempio n. 15
0
        private DocumentFile(DocumentFile original)
            : base(original)
        {
            this.ExtensionsForRendering = new List<string>(original.ExtensionsForRendering);

            this.Layouts = new List<LayoutFile>(original.Layouts);

            this.Partial = original.Partial;

            this.Metadata = original.Metadata;

            this.Queries = original.Queries;

            this.Unmodified = original.Unmodified;

            this.Cloned = true;
        }
        public void CanReadDynamicRenderingData()
        {
            var sitePath = @"C:\site\";
            var documentsPath = sitePath + @"documents\";
            var layoutsPath = sitePath + @"layouts\";
            var outputPath = sitePath + @"build\";

            var document = new DocumentFile(documentsPath + "foo.html.md", documentsPath, outputPath + "foo.html", outputPath, String.Empty, String.Empty, null, null, null);
            var layout = new LayoutFile(layoutsPath + "default.cshtml", layoutsPath, String.Empty, null, null);
            var config = new SiteConfig() { OutputPath = outputPath, Url = "http://example.com", RootUrl = String.Empty, };
            var site = new Site(config, Enumerable.Empty<DataFile>(), new[] { document }, Enumerable.Empty<StaticFile>(), new LayoutFileCollection(new[] { layout }));

            dynamic data = new DynamicRenderDocument(document, layout, site);
            Assert.Equal(outputPath, data.Site.OutputPath);
            Assert.Single(data.Site.Documents);

            foreach (var d in data.Site.Documents)
            {
                Assert.Equal(outputPath + "foo.html", d.OutputPath);
            }
        }
Esempio n. 17
0
 public Book(string id, List<BookPage> chapters, DocumentFile parentDocument)
     : this(id, chapters, parentDocument, null)
 {
 }
Esempio n. 18
0
 private void AssignLayoutMetadataToDocument(DocumentFile document, LayoutFile layout)
 {
     foreach (var metadataKeyValue in layout.Metadata)
     {
         if (!metadataKeyValue.Key.Equals("Id", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("Extension", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("Layout", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("Modified", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("Name", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("SourcePath", StringComparison.OrdinalIgnoreCase) &&
             !metadataKeyValue.Key.Equals("SourceContent", StringComparison.OrdinalIgnoreCase) &&
             !document.Metadata.Contains(metadataKeyValue.Key))
         {
             document.Metadata.Add(metadataKeyValue.Key, metadataKeyValue.Value);
         }
     }
 }
Esempio n. 19
0
        public Book GetBookWithRenderingDocument(DocumentFile renderingDocument)
        {
            var chapters = this.Chapters.Select(c => c.GetWithRenderingDocument(renderingDocument)).ToList();

            return new Book(this.Id, chapters, this.ParentDocument, renderingDocument);
        }
Esempio n. 20
0
        private static DocumentFile ProcessBookAndChapterOrder(Book book, BookPage chapter, DocumentFile parent, DocumentFile previous)
        {
            var bookWithActiveDocument = book.GetBookWithRenderingDocument(chapter.Document);

            chapter.Document.Book = bookWithActiveDocument;

            chapter.Document.Chapter = AllChapters(bookWithActiveDocument).Where(c => c.Document == chapter.Document).Single();

            previous = SetNextPreviousAndParent(previous, chapter.Document, parent);

            foreach (var page in chapter.SubPages)
            {
                previous = SetNextPreviousAndParent(previous, page.Document, chapter.Document);

                if (page.SubPages != null && page.SubPages.Any())
                {
                    previous = ProcessBookAndChapterOrder(book, page, chapter.Document, previous);
                }
                else
                {
                    page.Document.Book = book.GetBookWithRenderingDocument(page.Document);
                }
            }

            return previous;
        }
Esempio n. 21
0
        private string RenderContentForExtension(SourceFile source, string content, string extension, DocumentFile contextDocument, string documentContent, LayoutFile contextLayout)
        {
            RenderingEngine engine;

            if (this.Transaction.Engines.TryGetValue(extension, out engine))
            {
                var backupContent = contextDocument.Content;

                try
                {
                    contextDocument.Content = documentContent;

                    var data = new DynamicRenderDocument(contextDocument, contextLayout, this.Transaction.Site);

                    var result = engine.Render(source, content, data);

                    return result;
                }
                catch (RuntimeBinderException e)
                {
                    Console.WriteLine("{0} : error TS0101: Internal failure while processing template. This almost always indicates a failure in a Razor template @Include() by this file. Additional detail: {1}", source.SourcePath, e.Message);
                    return String.Empty;
                }
                finally
                {
                    contextDocument.Content = backupContent;
                }
            }
            else
            {
                Console.WriteLine("Cannot find a rendering engine for extension: {0}", extension);
                return null;
            }
        }
Esempio n. 22
0
        private static DocumentFile SetNextPreviousAndParent(DocumentFile previous, DocumentFile document, DocumentFile parent)
        {
            if (previous != null)
            {
                previous.NextDocument = document;
            }

            document.ParentDocument = parent;

            document.PreviousDocument = previous;

            return document;
        }
        private static DocumentFile WriteDocument(DocumentFile document)
        {
            var folder = Path.GetDirectoryName(document.OutputPath);

            Directory.CreateDirectory(folder);

            var utf8 = Encoding.UTF8.GetBytes(document.RenderedContent);

            using (var writer = File.Open(document.OutputPath, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Delete))
            {
                writer.Write(utf8, 0, utf8.Length);
            }

            var modified = document.LatestModifiedOfContributingFiles();

            File.SetCreationTime(document.OutputPath, document.Date);

            File.SetLastWriteTime(document.OutputPath, modified);

            return document;
        }
Esempio n. 24
0
        public DocumentFile Clone()
        {
            var clone = new DocumentFile(this);

            return(clone);
        }
Esempio n. 25
0
        public DocumentFile CloneForPage(string urlFormat, string prependPathFormat, Paginator paginator)
        {
            var prependPath = String.Format(prependPathFormat, paginator.Pagination.Page);

            var prependUrl = String.Format(urlFormat, paginator.Pagination.Page);

            var dupe = new DocumentFile(this);

            var updateFileName = Path.GetFileName(dupe.OutputRelativePath);

            dupe.OutputRelativePath = Path.Combine(prependPath, updateFileName);

            dupe.OutputPath = Path.Combine(dupe.OutputRootPath, prependPath, updateFileName);

            dupe.RelativeUrl = String.Concat(prependUrl, updateFileName.Equals("index.html", StringComparison.OrdinalIgnoreCase) ? String.Empty : updateFileName);

            dupe.Paginator = paginator;

            return dupe;
        }
        private async Task<DocumentFile> LoadDocumentAsync(string file, IEnumerable<string> knownExtensions, LayoutFileCollection availableLayouts)
        {
            // Parse the document and update our document metadata.
            //
            var parser = new ParseDocumentCommand(file);
            await parser.ExecuteAsync();

            if (this.AdditionalMetadataForFiles != null)
            {
                var rootPath = Path.GetDirectoryName(this.DocumentsPath.TrimEnd('\\'));
                var relativePath = file.Substring(rootPath.Length + 1);

                foreach (var additionalMetadataConfig in this.AdditionalMetadataForFiles)
                {
                    if (additionalMetadataConfig.Match.IsMatch(relativePath))
                    {
                        parser.Metadata.AssignFrom(file, additionalMetadataConfig.Metadata);
                    }
                }
            }

            var metadataDate = parser.Date;

            var partial = false;

            var order = 0;

            var relativeDocumentPath = Path.GetFullPath(file).Substring(this.DocumentsPath.Length);

            var outputRelativePath = parser.Metadata.GetAndRemove("output", relativeDocumentPath);

            // The rest of this function is about calculating the correct
            // name for the file.
            //
            var fileName = Path.GetFileName(outputRelativePath);

            var outputRelativeFolder = Path.GetDirectoryName(outputRelativePath);

            // See if this file should be processed by any of the
            // rendering engines.
            //
            var extensionsForRendering = new List<string>();

            for (;;)
            {
                var extension = Path.GetExtension(fileName).TrimStart('.');
                if (extension.Equals("partial", StringComparison.OrdinalIgnoreCase))
                {
                    partial = true;
                    fileName = Path.GetFileNameWithoutExtension(fileName);
                }
                else if (knownExtensions.Contains(extension))
                {
                    extensionsForRendering.Add(extension);
                    fileName = Path.GetFileNameWithoutExtension(fileName);
                }
                else
                {
                    break;
                }
            }

            var targetExtension = Path.GetExtension(fileName).TrimStart('.');

            var layoutName = parser.Metadata.Get<string>("layout");

            var layouts = GetLayouts(layoutName, targetExtension, file);

            var disableDateFromFileName = parser.Metadata.GetAndRemove("DisableDateFromFileName", false);

            if (!disableDateFromFileName)
            {
                var match = DateFromFileName.Match(fileName);

                if (match.Success)
                {
                    // If the parser metadata didn't specify the date, use the date from the filename.
                    //
                    if (!metadataDate.HasValue)
                    {
                        var year = Convert.ToInt32(match.Groups[1].Value, 10);
                        var month = Convert.ToInt32(match.Groups[2].Value, 10);
                        var day = Convert.ToInt32(match.Groups[3].Value, 10);
                        var hour = match.Groups[4].Success ? Convert.ToInt32(match.Groups[4].Value, 10) : 0;
                        var minute = match.Groups[5].Success ? Convert.ToInt32(match.Groups[5].Value, 10) : 0;
                        var second = match.Groups[6].Success ? Convert.ToInt32(match.Groups[6].Value, 10) : 0;

                        metadataDate = new DateTime(year, month, day, hour, minute, second);
                    }

                    fileName = fileName.Substring(match.Length);
                }
            }

            var disableOrderFromFileName = parser.Metadata.GetAndRemove("DisableOrderFromFileName", false);

            if (!disableOrderFromFileName)
            {
                var match = OrderFromFileName.Match(fileName);

                if (match.Success)
                {
                    order = Convert.ToInt32(match.Groups[1].Value, 10);

                    fileName = fileName.Substring(match.Length);
                }
            }

            var parentId = String.IsNullOrEmpty(outputRelativeFolder) ? null : SanitizePath(outputRelativeFolder);

            var disableInsertDateIntoPath = parser.Metadata.GetAndRemove("DisableInsertDateIntoPath", false);

            if (!disableInsertDateIntoPath && metadataDate.HasValue)
            {
                outputRelativeFolder = Path.Combine(outputRelativeFolder, metadataDate.Value.Year.ToString(), metadataDate.Value.Month.ToString(), metadataDate.Value.Day.ToString());
            }

            if (!parser.Metadata.Contains("title"))
            {
                parser.Metadata.Add("title", Path.GetFileNameWithoutExtension(fileName));
            }

            // Sanitize the filename into a good URL.
            //
            var sanitized = SanitizeEntryId(fileName);

            if (!fileName.Equals(sanitized))
            {
                fileName = sanitized;
            }

            var disableSanitizePath = parser.Metadata.GetAndRemove("DisableSanitizePath", false);

            if (!disableSanitizePath)
            {
                outputRelativeFolder = SanitizePath(outputRelativeFolder);
            }

            var disableCleanUrls = parser.Metadata.GetAndRemove("DisableCleanUrls", false);

            if (!disableCleanUrls && !"index.html".Equals(fileName, StringComparison.OrdinalIgnoreCase) && ".html".Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase))
            {
                outputRelativeFolder = Path.Combine(outputRelativeFolder, Path.GetFileNameWithoutExtension(fileName)) + "\\";

                fileName = null;
            }

            var id = String.IsNullOrEmpty(fileName) ? outputRelativeFolder : Path.Combine(outputRelativeFolder, Path.GetFileNameWithoutExtension(fileName));

            var output = Path.Combine(outputRelativeFolder, fileName ?? "index.html");

            var relativeUrl = this.ApplicationUrl.EnsureEndsWith("/") + Path.Combine(outputRelativeFolder, fileName ?? String.Empty).Replace('\\', '/');

            // Finally create the document.
            //
            var documentFile = new DocumentFile(file, this.DocumentsPath, output, this.OutputRootPath, relativeUrl, this.RootUrl, this.Author, parser.Metadata, parser.Queries);

            documentFile.Partial = partial;

            if (metadataDate.HasValue)
            {
                documentFile.SetTimes(metadataDate.Value);
            }

            documentFile.Id = parser.Metadata.GetAndRemove("id", id.Trim('\\'));

            documentFile.ParentId = parser.Metadata.GetAndRemove("parent", parentId ?? String.Empty);

            documentFile.Draft = (parser.Draft || documentFile.Date > DateTime.Now);

            documentFile.ExtensionsForRendering = extensionsForRendering;

            documentFile.AssignLayouts(layouts);

            documentFile.Order = parser.Metadata.GetAndRemove("order", order);

            documentFile.PaginateQuery = parser.Metadata.GetAndRemove<string>("paginate");

            documentFile.SourceContent = parser.Content;

            return documentFile;
        }