1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
# frozen_string_literal: true
require "fileutils"
module Jekyll
class JekyllSitemap < Jekyll::Generator
safe true
priority :lowest
# Main plugin action, called by Jekyll-core
def generate(site)
@site = site
@site.pages << sitemap unless file_exists?("sitemap.xml")
@site.pages << robots unless file_exists?("robots.txt")
end
private
INCLUDED_EXTENSIONS = %w(
.htm
.html
.xhtml
.pdf
).freeze
# Matches all whitespace that follows
# 1. A '>' followed by a newline or
# 2. A '}' which closes a Liquid tag
# We will strip all of this whitespace to minify the template
MINIFY_REGEX = %r!(?<=>\n|})\s+!.freeze
# Array of all non-jekyll site files with an HTML extension
def static_files
@site.static_files.select { |file| INCLUDED_EXTENSIONS.include? file.extname }
end
# Path to sitemap.xml template file
def source_path(file = "sitemap.xml")
File.expand_path "../#{file}", __dir__
end
# Destination for sitemap.xml file within the site source directory
def destination_path(file = "sitemap.xml")
@site.in_dest_dir(file)
end
def sitemap
site_map = PageWithoutAFile.new(@site, __dir__, "", "sitemap.xml")
site_map.content = File.read(source_path).gsub(MINIFY_REGEX, "")
site_map.data["layout"] = nil
site_map.data["static_files"] = static_files.map(&:to_liquid)
site_map.data["xsl"] = file_exists?("sitemap.xsl")
site_map
end
def robots
robots = PageWithoutAFile.new(@site, __dir__, "", "robots.txt")
robots.content = File.read(source_path("robots.txt"))
robots.data["layout"] = nil
robots
end
# Checks if a file already exists in the site source
def file_exists?(file_path)
pages_and_files.any? { |p| p.url == "/#{file_path}" }
end
def pages_and_files
@pages_and_files ||= @site.pages + @site.static_files
end
end
end
|