public void Should_Compile_Single_Less_File()
        {
            var lessContent = @"@brand_color: #4D926F;

                                    #header {
                                        color: @brand_color;
                                    }
 
                                    h2 {
                                        color: @brand_color;
                                    }";

            var lessOutput = @"#header{color:#4d926f}h2{color:#4d926f}";

            var filepath = @"c:\css\style.less";
            var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
            {
                { HtmlFilePath, new MockFileData(PageContent)},
                { filepath, new MockFileData(lessContent) }
            });

            var minifier = new LessTransform(fileSystem);
            var context = new SiteContext { SourceFolder = @"C:\", OutputFolder = @"C:\_site" };
            context.Pages.Add(new NonProcessedPage { OutputFile = HtmlFilePath, Content = PageContent });
            context.Pages.Add(new NonProcessedPage { OutputFile = filepath, Content = lessContent, Filepath = filepath });
            minifier.Transform(context);

            var minifiedFile = fileSystem.File.ReadAllText(@"c:\css\style.css", Encoding.UTF8);
            Assert.Equal(lessOutput, minifiedFile);
        }
        public SiteContext BuildContext(string path, string destinationPath, bool includeDrafts)
        {
            try
            {
                var context = new SiteContext
                {
                    SourceFolder = path,
                    OutputFolder = destinationPath,
                    Posts = new List<Page>(),
                    Pages = new List<Page>(),
                    Config = _config,
                    Time = DateTime.Now,
                    UseDrafts = includeDrafts
                };

                context.Posts = BuildPosts(_config, context).OrderByDescending(p => p.Date).ToList();
                BuildTagsAndCategories(context);

                context.Pages = BuildPages(_config, context).ToList();

                if (BeforeProcessingTransforms != null)
                {
                    foreach (var transform in BeforeProcessingTransforms)
                    {
                        transform.Transform(context);
                    }
                }

                return context;
            }
            finally
            {
                pageCache.Clear();
            }
        }
Esempio n. 3
0
        public void Process(SiteContext siteContext, bool skipFileOnError = false)
        {
            // Default rendering engine
            if (_lightweightMarkupEngine == null)
            {
                _lightweightMarkupEngine = new CommonMarkEngine();
            }

            Tracing.Logger.Write(string.Format("LightweightMarkupEngine: {0}", _lightweightMarkupEngine.GetType().Name), Tracing.Category.Debug);

            Context = siteContext;
            PreProcess();

            for (int index = 0; index < siteContext.Posts.Count; index++)
            {
                var p = siteContext.Posts[index];
                var previous = GetPrevious(siteContext.Posts, index);
                var next = GetNext(siteContext.Posts, index);
                ProcessFile(siteContext.OutputFolder, p, previous, next, skipFileOnError, p.Filepath);
            }

            for (int index = 0; index < siteContext.Pages.Count; index++)
            {
                var p = siteContext.Pages[index];
                var previous = GetPrevious(siteContext.Pages, index);
                var next = GetNext(siteContext.Pages, index);
                ProcessFile(siteContext.OutputFolder, p, previous, next, skipFileOnError);
            }
        }
Esempio n. 4
0
        public void Transform(SiteContext siteContext)
        {
            var tipueContent = new TipueContent();
            foreach (var post in siteContext.Posts)
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(post.Content);

                tipueContent.Pages.Add(new TipuePage
                {
                    Title = post.Title,
                    Tags = string.Join(" ", post.Tags),
                    Url = post.Url,
                    Text = doc.DocumentNode.InnerText
                });
            }

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            var text = $"var tipuesearch = {JsonConvert.SerializeObject(tipueContent, settings)}";

            File.WriteAllText(Path.Combine(siteContext.OutputFolder, @"assets\js\tipuesearch_content.js"), text);
        }
Esempio n. 5
0
#pragma warning restore 0649

        public SiteContext BuildContext(string path)
        {
            var config = new Dictionary<string, object>();
            if (File.Exists(Path.Combine(path, "_config.yml")))
                config = (Dictionary<string, object>)File.ReadAllText(Path.Combine(path, "_config.yml")).YamlHeader(true);

            if (!config.ContainsKey("permalink"))
                config.Add("permalink", "/:year/:month/:day/:title.html");

            var context = new SiteContext
            {
                SourceFolder = path,
                OutputFolder = Path.Combine(path, "_site"),
                Posts = new List<Page>(),
                Pages = new List<Page>(),
                Config = config,
                Time = DateTime.Now,
            };

            BuildPosts(config, context);

            BuildPages(config, context);

            return context;
        }
        public SiteContext BuildContext(string path)
        {
            try
            {
                var config = new Dictionary<string, object>();
                var configPath = Path.Combine(path, "_config.yml");
                if (fileSystem.File.Exists(configPath))
                    config = (Dictionary<string, object>)fileSystem.File.ReadAllText(configPath).YamlHeader(true);

                if (!config.ContainsKey("permalink"))
                    config.Add("permalink", "/:year/:month/:day/:title.html");

                var context = new SiteContext
                {
                    SourceFolder = path,
                    OutputFolder = Path.Combine(path, "_site"),
                    Posts = new List<Page>(),
                    Pages = new List<Page>(),
                    Config = config,
                    Time = DateTime.Now,
                };

                context.Posts = BuildPosts(config, context).OrderByDescending(p => p.Date).ToList();
                BuildTagsAndCategories(context);

                context.Pages = BuildPages(config, context).ToList();

                return context;
            }
            finally
            {
                pageCache.Clear();
            }
        }
Esempio n. 7
0
        public void EvaluateLink_url_is_well_formatted(string filePath, string expectedUrl)
        {
            var siteContext = new SiteContext { OutputFolder = @"C:\TestSite\_site" };
            var page = new Page { Filepath = filePath };

            Assert.Equal(expectedUrl, LinkHelper.EvaluateLink(siteContext, page));
        }
Esempio n. 8
0
        public void Execute(string[] arguments)
        {
            Tracing.Info("bake - transforming content into a website");

            Settings.Parse(arguments);

            if (string.IsNullOrWhiteSpace(Path))
            {
                Path = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Engine))
            {
                Engine = InferEngineFromDirectory(Path);
            }

            var engine = templateEngines[Engine];
            if (engine != null)
            {
                var watch = new Stopwatch();
                watch.Start();
                var context = new SiteContext { Folder = Path };
                engine.Initialize();
                engine.Process(context);
                watch.Stop();
                Tracing.Info(string.Format("done - took {0}ms", watch.ElapsedMilliseconds));
            }
            else
            {
                Tracing.Info(String.Format("Cannot find engine for input: '{0}'", Engine));
            }
        }
Esempio n. 9
0
        //public static PageContext FromDictionary(SiteContext siteContext, IDictionary<string, object> metadata, string outputPath, string defaultOutputPath)
        //{
        //    var context = new PageContext(siteContext, TODO)
        //                      {
        //                          OutputPath =
        //                              metadata.ContainsKey("permalink")
        //                                  ? Path.Combine(outputPath, metadata["permalink"].ToString().ToRelativeFile())
        //                                  : defaultOutputPath
        //                      };
        //    if (metadata.ContainsKey("title"))
        //    {
        //        context.Title = metadata["title"].ToString();
        //    }
        //    context.Bag = metadata;
        //    return context;
        //}
        public static PageContext FromPage(SiteContext siteContext, Page page, string outputPath, string defaultOutputPath)
        {
            var context = new PageContext(siteContext, page);

            if (page.Bag.ContainsKey("permalink"))
            {
                context.OutputPath = Path.Combine(outputPath, page.Url.ToRelativeFile());
            }
            else
            {
                context.OutputPath = defaultOutputPath;
                page.Bag.Add("permalink", page.File);
            }

            if (context.OutputPath.EndsWith("\\"))
            {
                context.OutputPath = Path.Combine(context.OutputPath, "index.html");
            }

            page.OutputFile = context.OutputPath;

            if (page.Bag.ContainsKey("title"))
            {
                context.Title = page.Bag["title"].ToString();
            }

            if (string.IsNullOrEmpty(context.Title))
                context.Title = siteContext.Title;

            context.Content = page.Content;
            context.Bag = page.Bag;
            context.Bag.Add("id", page.Id);
            context.Bag.Add("url", page.Url);
            return context;
        }
        private IEnumerable<Page> BuildPages(IConfiguration config, SiteContext context)
        {
            var files = from file in fileSystem.Directory.GetFiles(context.SourceFolder, "*.*", SearchOption.AllDirectories)
                        let relativePath = MapToOutputPath(context, file)
                        where CanBeIncluded(relativePath)
                        select file;

            foreach (var file in files)
            {
                if (!ContainsYamlFrontMatter(file))
                {
                    yield return new NonProcessedPage
                                     {
                                         File = file,
                                         Filepath = Path.Combine(context.OutputFolder, MapToOutputPath(context, file))
                                     };
                }
                else
                {
                    var page = CreatePage(context, config, file, false);

                    if (page != null)
                        yield return page;
                }
            }
        }
Esempio n. 11
0
#pragma warning restore 0649

        public SiteContext BuildContext(string path)
        {
            if (!Path.IsPathRooted(path))
                path = Path.Combine(Environment.CurrentDirectory, path);

            var config = new Dictionary<string, object>();
            if (File.Exists(Path.Combine(path, "_config.yml")))
                config = (Dictionary<string, object>)File.ReadAllText(Path.Combine(path, "_config.yml")).YamlHeader(true);

            if (!config.ContainsKey("permalink"))
                config.Add("permalink", "/:year/:month/:day/:title.html");

            var context = new SiteContext
            {
                SourceFolder = path,
                OutputFolder = Path.Combine(path, "_site"),
                Posts = new List<Page>(),
                Pages = new List<Page>(),
            };

            BuildPosts(config, context);

            foreach (var file in fileSystem.Directory.GetFiles(context.SourceFolder, "*.*", SearchOption.AllDirectories))
            {
                var relativePath = MapToOutputPath(context, file);
                if (relativePath.StartsWith("_"))
                    continue;

                if (relativePath.StartsWith("."))
                    continue;

                var postFirstLine = SafeReadLine(file);
                if (postFirstLine == null || !postFirstLine.StartsWith("---"))
                {
                    context.Pages.Add(new NonProcessedPage
                                            {
                                                File = file, 
                                                Filepath = Path.Combine(context.OutputFolder, file)
                                            });
                    continue;
                }

                var contents = SafeReadContents(file);
                var header = contents.YamlHeader();
                var page = new Page
                {
                    Title = header.ContainsKey("title") ? header["title"].ToString() : "this is a post", // should this be the Site title?
                    Date = header.ContainsKey("date") ? DateTime.Parse(header["date"].ToString()) : DateTime.Now,
                    Content = Markdown.Transform(contents.ExcludeHeader()),
                    Filepath = GetPathWithTimestamp(context.OutputFolder, file),
                    File = file,
                    Bag = header,
                };

                context.Pages.Add(page);
            }

            return context;
        }
Esempio n. 12
0
 public Paginator(SiteContext site, int totalPages, int perPage, int page)
 {
     this.site = site;
     TotalPosts = site.Posts.Count;
     TotalPages = totalPages;
     PerPage = perPage;
     Page = page;
 }
Esempio n. 13
0
        private void BuildPosts(Dictionary<string, object> config, SiteContext context)
        {
            var postsFolder = Path.Combine(context.SourceFolder, "_posts");
            if (fileSystem.Directory.Exists(postsFolder))
            {
                foreach (var file in fileSystem.Directory.GetFiles(postsFolder, "*.*", SearchOption.AllDirectories))
                {
                    BuildPost(config, context, file);
                }

                context.Posts = context.Posts.OrderByDescending(p => p.Date).ToList();
            }
        }
Esempio n. 14
0
        public void Transform(SiteContext siteContext)
        {
            var shouldCompile = new List<Page>();
            //Process to see if the site has a CSS file that doesn't exist, and should be created from LESS files.
            //This is "smarter" than just compiling all Less files, which will crash if they're part of a larger Less project 
            //ie, one file pulls in imports, individually they don't know about each other but use variables
            foreach (var file in siteContext.Pages.Where(p => p.OutputFile.EndsWith(".html") && fileSystem.File.Exists(p.OutputFile)))
            {
                var doc = new HtmlDocument();
                var fileContents = fileSystem.File.ReadAllText(file.OutputFile);
                doc.LoadHtml(fileContents);

                var nodes = doc.DocumentNode.SelectNodes("/html/head/link[@rel='stylesheet']");
                if (nodes != null)
                    foreach (HtmlNode link in nodes)
                    {
                        var cssfile = link.Attributes["href"].Value;

                        // If the file is not local, ignore it
                        var matchingIgnoreProtocol = ExternalProtocols.FirstOrDefault(cssfile.StartsWith);
                        if (matchingIgnoreProtocol != null)
                            continue;

                        //If the file exists, ignore it
                        if (fileSystem.File.Exists(Path.Combine(siteContext.OutputFolder, cssfile)))
                            continue;

                        //If there is a CSS file that matches the name, ignore, could be another issue
                        if (siteContext.Pages.Any(p => p.OutputFile.Contains(cssfile)))
                            continue;


                        var n = cssfile.Replace(".css", ".less");
                        n = n.Replace('/', '\\');

                        var cssPageToCompile = siteContext.Pages.FirstOrDefault(f => f.OutputFile.Contains(n));
                        if (cssPageToCompile != null && !shouldCompile.Contains(cssPageToCompile))
                        {
                            shouldCompile.Add(cssPageToCompile);
                        }
                    }
            }

            foreach (var less in shouldCompile)
            {
                filePath = less.OutputFile;
                fileSystem.File.WriteAllText(less.OutputFile.Replace(".less", ".css"), ProcessCss(siteContext, less.Filepath));
                fileSystem.File.Delete(less.OutputFile);
            }
        }
 public void Transform(SiteContext siteContext) {
     foreach (var post in siteContext.Posts.Concat(siteContext.Pages).Where(p => !(p is NonProcessedPage))) {
         object obj;
         if (post.Bag.TryGetValue("redirect_from", out obj)) {
             var sourceUrls = obj as IEnumerable<string>;
             if (sourceUrls != null) {
                 WriteRedirectFile(siteContext, post, sourceUrls);
             } else {
                 var sourceUrl = obj as string;
                 if (sourceUrl != null) {
                     WriteRedirectFile(siteContext, post, new[] { sourceUrl });
                 }
             }
         }
     }
 }
        private void WriteRedirectFile(SiteContext siteContext, Page post, IEnumerable<string> sourceUrls) {
            var targetUrl = post.Url;
            var content = String.Format(Templates.Redirect, targetUrl);

            foreach (var sourceUrl in sourceUrls) {
                try {
                    var directory = _fileSystem.Path.Combine(siteContext.OutputFolder, sourceUrl.TrimStart('/').Replace('/', _fileSystem.Path.DirectorySeparatorChar));
                    if (!_fileSystem.Directory.Exists(directory)) {
                        _fileSystem.Directory.CreateDirectory(directory);
                    }
                    _fileSystem.File.WriteAllText(_fileSystem.Path.Combine(directory, "index.html"), content);
                } catch (Exception ex) {
                    Console.WriteLine("Generating redirect for {0} at {1} failed:{2}{3}", post.Id, sourceUrl, Environment.NewLine, ex);
                }
            }
        }
Esempio n. 17
0
        public void config_permalink_sets_relative_file_output_path()
        {
            var context = new SiteContext();
            context.Config = new Dictionary<string, object>();
            context.Config.Add("permalink", "/blog/:year/:month/:day/:title.html");

            var page = new Page()
            {
                Url = "/blog/2010/08/21/title-of-my-post.html"
            };

            var outputPath = "c:\\temp";
            var defaultOutputPath = "c:\\default";

            var pageContext = PageContext.FromPage(context, page, outputPath, defaultOutputPath);

            Assert.Equal("c:\\temp\\blog\\2010\\08\\21\\title-of-my-post.html", pageContext.OutputPath);
        }
Esempio n. 18
0
        public void Execute(string[] arguments)
        {
            Tracing.Info("taste - testing a site locally");
            Settings.Parse(arguments);
            if (Port == 0)
            {
                Port = 8080;
            }

            var f = new FileContentProvider();
            if (string.IsNullOrWhiteSpace(Path))
            {
                Path = Directory.GetCurrentDirectory();
            }

            if (string.IsNullOrWhiteSpace(Engine))
            {
                Engine = InferEngineFromDirectory(Path);
            }

            engine = templateEngines[Engine];

            if (engine == null)
                return;

            var context = new SiteContext { Folder = Path };
            engine.Initialize();
            engine.Process(context);

            var watcher = new SimpleFileSystemWatcher();
            watcher.OnChange(Path, WatcherOnChanged);

            var w = new WebHost(engine.GetOutputDirectory(Path), f);
            w.Start();

            Tracing.Info("Press 'Q' to stop the web host...");
            ConsoleKeyInfo key;
            do
            {
                key = Console.ReadKey();
            }
            while (key.Key != ConsoleKey.Q);
        }
Esempio n. 19
0
        public string EvaluateLink(SiteContext context, Page page)
        {
            var directory = Path.GetDirectoryName(page.Filepath);
            var relativePath = directory.Replace(context.OutputFolder, string.Empty);
            var fileExtension = Path.GetExtension(page.Filepath);

            if (HtmlExtensions.Contains(fileExtension, StringComparer.InvariantCultureIgnoreCase))
            {
                fileExtension = ".html";
            }

            var link = relativePath.Replace('\\', '/').TrimStart('/') + "/" + GetPageTitle(page.Filepath) + fileExtension;
            if (!link.StartsWith("/"))
            {
                link = "/" + link;
            }

            return link;
        }
Esempio n. 20
0
        public static void CompressSitemap(this ISiteEngine engine, SiteContext siteContext, IFileSystem fileSystem) 
        {
            var sitemap = fileSystem.Path.Combine(siteContext.OutputFolder, @"sitemap.xml");
            var compressedSitemap = sitemap + ".gz";

            if (fileSystem.File.Exists(sitemap))
            {
                using (var sitemapStream = fileSystem.File.OpenRead(sitemap))
                {
                    using (var compressedMap = fileSystem.File.Create(compressedSitemap))
                    {
                        using (var gzip = new System.IO.Compression.GZipStream(compressedMap, System.IO.Compression.CompressionMode.Compress))
                        {
                            sitemapStream.CopyTo(gzip);
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        private void BuildPages(Dictionary<string, object> config, SiteContext context)
        {
            foreach (var file in fileSystem.Directory.GetFiles(context.SourceFolder, "*.*", SearchOption.AllDirectories))
            {
                var relativePath = MapToOutputPath(context, file);
                if (relativePath.StartsWith("_"))
                    continue;

                if (relativePath.StartsWith("."))
                    continue;

                var postFirstLine = SafeReadLine(file);
                if (postFirstLine == null || !postFirstLine.StartsWith("---"))
                {
                    context.Pages.Add(new NonProcessedPage
                    {
                        File = file,
                        Filepath = Path.Combine(context.OutputFolder, file)
                    });
                    continue;
                }

                var contents = SafeReadContents(file);
                var header = contents.YamlHeader();
                var page = new Page
                {
                    Title = header.ContainsKey("title") ? header["title"].ToString() : "this is a post", // should this be the Site title?
                    Date = header.ContainsKey("date") ? DateTime.Parse(header["date"].ToString()) : file.Datestamp(),
                    Content = RenderContent(file, contents, header), 
                    Filepath = GetPathWithTimestamp(context.OutputFolder, file),
                    File = file,
                    Bag = header,
                };

                if (header.ContainsKey("permalink"))
                {
                    page.Url = EvaluatePagePermalink(header["permalink"].ToString(), page);
                }

                context.Pages.Add(page);
            }
        }
Esempio n. 22
0
        public void Process(SiteContext siteContext, bool skipFileOnError = false)
        {
            Context = siteContext;
            PreProcess();

            for (int index = 0; index < siteContext.Posts.Count; index++)
            {
                var p = siteContext.Posts[index];
                var previous = GetPrevious(siteContext.Posts, index);
                var next = GetNext(siteContext.Posts, index);
                ProcessFile(siteContext.OutputFolder, p, previous, next, skipFileOnError, p.Filepath);
            }

            for (int index = 0; index < siteContext.Pages.Count; index++)
            {
                var p = siteContext.Pages[index];
                var previous = GetPrevious(siteContext.Pages, index);
                var next = GetNext(siteContext.Pages, index);
                ProcessFile(siteContext.OutputFolder, p, previous, next, skipFileOnError);
            }
        }
Esempio n. 23
0
        public void no_permalink_sets_default_output_path_and_page_bag_permalink()
        {
            var context = new SiteContext();
            context.Config = new Dictionary<string, object>();

            var file = "title-of-my-post.html";
            var page = new Page()
            {
                File = file
            };

            page.Bag = new Dictionary<string, object>();

            var outputPath = "c:\\temp";
            var defaultOutputPath = "c:\\default\\title-of-my-post.html";

            var pageContext = PageContext.FromPage(context, page, outputPath, defaultOutputPath);

            Assert.Equal("c:\\default\\title-of-my-post.html", pageContext.OutputPath);
            Assert.Equal(file, page.Bag["permalink"]);
        }
        public void Transform(SiteContext siteContext)
        {
            if (string.IsNullOrEmpty(VirtualDirectory)) return;

            var href = new Regex("href=\"(?<url>/.*?)\"", RegexOptions.Compiled);
            var src = new Regex("src=\"(?<url>/.*?)\"", RegexOptions.Compiled);
            var hrefReplacement = string.Format("href=\"/{0}${{url}}\"", VirtualDirectory);
            var srcReplacement = string.Format("src=\"/{0}${{url}}\"", VirtualDirectory);

            foreach (var page in siteContext.Pages.Where(p => p.OutputFile.EndsWith(".html") || p.OutputFile.EndsWith(".htm") || p.OutputFile.EndsWith(".css")))
            {
                var fileContents = fileSystem.File.ReadAllText(page.OutputFile);

                var processedContents = href.Replace(fileContents, hrefReplacement);
                processedContents = src.Replace(processedContents, srcReplacement);

                if (fileContents != processedContents)
                {
                    fileSystem.File.WriteAllText(page.OutputFile, processedContents);
                }
            }
        }
Esempio n. 25
0
        private void BuildPosts(Dictionary<string, object> config, SiteContext context)
        {
            var postsFolder = Path.Combine(context.SourceFolder, "_posts");
            if (fileSystem.Directory.Exists(postsFolder))
            {
                foreach (var file in fileSystem.Directory.GetFiles(postsFolder, "*.*", SearchOption.AllDirectories))
                {
                    var contents = SafeReadContents(file);
                    var header = contents.YamlHeader();
                    var post = new Page
                    {
                        Title = header.ContainsKey("title") ? header["title"].ToString() : "this is a post",
                        // NOTE: should this be the Site title?
                        Date =
                            header.ContainsKey("date")
                                ? DateTime.Parse(header["date"].ToString())
                                : file.Datestamp(),
                        Content = Markdown.Transform(contents.ExcludeHeader()),
                        Filepath = GetPathWithTimestamp(context.OutputFolder, file),
                        File = file,
                        Bag = header,
                    };

                    if (header.ContainsKey("permalink"))
                        post.Url = EvaluatePermalink(header["permalink"].ToString(), post);
                    else if (config.ContainsKey("permalink"))
                        post.Url = EvaluatePermalink(config["permalink"].ToString(), post);

                    if (string.IsNullOrEmpty(post.Url))
                    {
                        Tracing.Info("whaaa");
                    }
                    context.Posts.Add(post);
                }

                context.Posts = context.Posts.OrderByDescending(p => p.Date).ToList();
            }
        }
Esempio n. 26
0
        public void Process(SiteContext siteContext)
        {
            Context = siteContext;
            PreProcess();

            var outputDirectory = Path.Combine(Context.SourceFolder, "_site");

            for (int index = 0; index < siteContext.Posts.Count; index++)
            {
                var p = siteContext.Posts[index];
                var previous = GetPrevious(siteContext.Posts, index);
                var next = GetNext(siteContext.Posts, index);
                ProcessFile(outputDirectory, p, previous, next, p.Filepath);
            }

            for (int index = 0; index < siteContext.Pages.Count; index++)
            {
                var p = siteContext.Pages[index];
                var previous = GetPrevious(siteContext.Pages, index);
                var next = GetNext(siteContext.Pages, index);
                ProcessFile(outputDirectory, p, previous, next);
            }
        }
Esempio n. 27
0
        public string ProcessCss(SiteContext siteContext, string file)
        {
            var content = fileSystem.File.ReadAllText(file);
            var engine = GetEngine();
            var css = engine.TransformToCss(content, file);

            var rootFolder = fileSystem.Path.GetDirectoryName(file);
            var foldersToDelete = new List<string>();
            foreach (string import in engine.GetImports())
            {
                var importRootFolder = fileSystem.Path.Combine(rootFolder, fileSystem.Path.GetDirectoryName(import));
                if (siteContext.OutputFolder != importRootFolder && !foldersToDelete.Contains(importRootFolder))
                {
                    foldersToDelete.Add(importRootFolder);
                }
                fileSystem.File.Delete(fileSystem.Path.Combine(rootFolder, import));
            }

            // Clean the leftover directories
            foreach (var folder in foldersToDelete)
            {
                if(!fileSystem.Directory.EnumerateFileSystemEntries(folder, "*").Any())
                {
                    fileSystem.Directory.Delete(folder);
                }
            }

            return css;
        }
Esempio n. 28
0
        private Page CreatePage(SiteContext context, IConfiguration config, string file, bool isPost)
        {
            try
            {
                if (pageCache.ContainsKey(file))
                {
                    return(pageCache[file]);
                }
                var content = SafeReadContents(file);

                var relativePath   = MapToOutputPath(context, file);
                var scopedDefaults = context.Config.Defaults.ForScope(relativePath);

                var header = scopedDefaults.Merge(content.YamlHeader());

                if (header.ContainsKey("published") && header["published"].ToString().ToLower(CultureInfo.InvariantCulture) == "false")
                {
                    return(null);
                }

                var page = new Page
                {
                    Title    = header.ContainsKey("title") ? header["title"].ToString() : "this is a post",
                    Date     = header.ContainsKey("date") ? DateTime.Parse(header["date"].ToString()) : file.Datestamp(fileSystem),
                    Content  = content,
                    Filepath = isPost ? GetPathWithTimestamp(context.OutputFolder, file) : GetFilePathForPage(context, file),
                    File     = file,
                    Bag      = header,
                };

                // resolve categories and tags
                if (isPost)
                {
                    page.Categories = ResolveCategories(context, header, page);

                    if (header.ContainsKey("tags"))
                    {
                        page.Tags = header["tags"] as IEnumerable <string>;
                    }
                }

                // resolve permalink
                if (header.ContainsKey("permalink"))
                {
                    page.Url = linkHelper.EvaluatePermalink(header["permalink"].ToString(), page);
                }
                else if (isPost && config.ContainsKey("permalink"))
                {
                    page.Url = linkHelper.EvaluatePermalink(config["permalink"].ToString(), page);
                }
                else
                {
                    page.Url = linkHelper.EvaluateLink(context, page);
                }

                // resolve id
                page.Id = page.Url.Replace(".html", string.Empty).Replace("index", string.Empty);

                // always write date back to Bag as DateTime
                page.Bag["date"] = page.Date;

                // The GetDirectoryPage method is reentrant, we need a cache to stop a stack overflow :)
                pageCache.Add(file, page);
                page.DirectoryPages = GetDirectoryPages(context, config, Path.GetDirectoryName(file), isPost).ToList();

                return(page);
            }
            catch (Exception e)
            {
                Tracing.Info("Failed to build post from File: {0}", file);
                Tracing.Info(e.Message);
                Tracing.Debug(e.ToString());
            }

            return(null);
        }
Esempio n. 29
0
 public SiteContextDrop(SiteContext context)
 {
     this.context = context;
 }
Esempio n. 30
0
 public bool CanProcess(SiteContext context)
 {
     var engineInfo = GetType().GetCustomAttributes(typeof (SiteEngineInfoAttribute), true).SingleOrDefault() as SiteEngineInfoAttribute;
     if (engineInfo == null) return false;
     return context.Engine == engineInfo.Engine;
 }
Esempio n. 31
0
 private string MapToOutputPath(SiteContext context, string file)
 {
     return file.Replace(context.SourceFolder, "").TrimStart('\\');
 }
Esempio n. 32
0
 private string MapToOutputPath(SiteContext context, string file)
 {
     return(file.Replace(context.SourceFolder, "")
            .TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
 }
Esempio n. 33
0
 public PageContext(SiteContext context, Page page)
 {
     Site = context;
     Page = page;
 }
Esempio n. 34
0
        private Page CreatePage(SiteContext context, IDictionary <string, object> config, string file, bool isPost)
        {
            try
            {
                if (pageCache.ContainsKey(file))
                {
                    return(pageCache[file]);
                }
                var contents = SafeReadContents(file);
                var header   = contents.YamlHeader();

                if (header.ContainsKey("published") && header["published"].ToString().ToLower() == "false")
                {
                    return(null);
                }

                var page = new Page
                {
                    Title    = header.ContainsKey("title") ? header["title"].ToString() : "this is a post",
                    Date     = header.ContainsKey("date") ? DateTime.Parse(header["date"].ToString()) : file.Datestamp(),
                    Content  = RenderContent(file, contents, header),
                    Filepath = isPost ? GetPathWithTimestamp(context.OutputFolder, file) : GetFilePathForPage(context, file),
                    File     = file,
                    Bag      = header,
                };

                if (header.ContainsKey("permalink"))
                {
                    page.Url = EvaluatePermalink(header["permalink"].ToString(), page);
                }
                else if (isPost && config.ContainsKey("permalink"))
                {
                    page.Url = EvaluatePermalink(config["permalink"].ToString(), page);
                }
                else
                {
                    page.Url = EvaluateLink(context, page);
                }

                // The GetDirectoryPage method is reentrant, we need a cache to stop a stack overflow :)
                pageCache.Add(file, page);
                page.DirectoryPages = GetDirectoryPages(context, config, Path.GetDirectoryName(file), isPost).ToList();

                if (isPost)
                {
                    if (header.ContainsKey("categories"))
                    {
                        page.Categories = header["categories"] as IEnumerable <string>;
                    }

                    if (header.ContainsKey("tags"))
                    {
                        page.Tags = header["tags"] as IEnumerable <string>;
                    }
                }
                return(page);
            }
            catch (Exception e)
            {
                Tracing.Info(String.Format("Failed to build post from File: {0}", file));
                Tracing.Info(e.Message);
                Tracing.Debug(e.ToString());
            }

            return(null);
        }
Esempio n. 35
0
 private string GetFilePathForPage(SiteContext context, string file)
 {
     return(Path.Combine(context.OutputFolder, MapToOutputPath(context, file)));
 }
Esempio n. 36
0
 private string MapToOutputPath(SiteContext context, string file)
 {
     return(file.Replace(context.SourceFolder, "").TrimStart('\\'));
 }