Jekyll Plugin: Index Generator

Before I knew about this file called .htaccess, I was trying to figure out a way to stop people from visiting my asset directory pages. If you don’t know what I mean, have you ever seen a page that looks like this?

Many servers, by default, allow a user to browse the files of whatever directory they specify, unless there is an index.html file in that directory. If the index file exists, that will be shown instead. My original idea was to make a build script that would automatically generate and place these index files in places where no index files existed. I got it working, too! However, shortly after I finished the script, I learned that I could add this line to my .htaccess file and get the exact same effect:

Options -Indexes.

Crazy, right? Well, if you don’t have access to a .htaccess file on your website, and you use Jekyll (or you just want to see how it works), here’s the source.

You can also find the source for the plugin on Github.

require 'find'

module Jekyll
class IndexGenerator < Generator
def generate(site)
@site = site
if site.config["index_generate"] == "true"
Jekyll::Hooks.register :site, :post_write do |site|
generate_index_files(site)
end
end
if site.config["index_generate"] != "true"
print(site, "Index generation disabled. Set 'index_generate' to 'true' in your config file to enable generation.")
end
end

def generate_index_files(site)
@site = site
if site.config.include? "index_ref_path"
ref_path = site.config["index_ref_path"]
if File.file?(File.join(site.dest, ref_path))
print(site, "Reference file: " + ref_path)
content = File.read(File.join(site.dest, ref_path))
Find.find(site.dest) do |path|
if File.directory?(path) && !File.file?(File.join(path, "index.html"))
print(site, "Writing to " + path)
FileUtils.mkdir_p(path)
File.open(File.join(path, "index.html"), 'w') do |file|
file.write(content)
end
end
end
else
print(site, "Can't generate index files. Reference file '" + ref_path + "' does not exist.")
end
else
print(site, "Can't generate index files. No reference file path specified.")
end
end

def print(site, value)
if site.config["index_verbose"] == "true"
puts value
end
end
end
end