Migrate to Hugo from Jekyll


Table of Contents


Move static content to static

Jekyll has a rule that any directory not starting with _ will be copied as-is to the _site output. Hugo keeps all static content under static. You should therefore move it all there. With Jekyll, something that looked like

▾ <root>/
    ▾ images/
        logo.png

should become

▾ <root>/
    ▾ static/
        ▾ images/
            logo.png

Additionally, you’ll want any files that should reside at the root (such as CNAME) to be moved to static.

Fenced code blocks

Without file-type specification:

# this is an extremely looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong comment

With file-type specification:

# this is an extremely looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong comment

With file-type specification and line numbers:

1
# this is an extremely looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong comment

Create your Hugo configuration file

Hugo can read your configuration as JSON, YAML or TOML. Hugo supports parameters custom configuration too. Refer to the Hugo configuration documentation for details.

Set your configuration publish folder to _site

The default is for Jekyll to publish to _site and for Hugo to publish to public. If, like me, you have _site mapped to a git submodule on the gh-pages branch, you’ll want to do one of two alternatives:

  1. Change your submodule to point to map gh-pages to public instead of _site (recommended).
git submodule deinit _site
git rm _site
git submodule add -b gh-pages git@github.com:your-username/your-repo.git public
  1. Or, change the Hugo configuration to use _site instead of public.
{
    ..
    "publishdir": "_site",
    ..
}

Convert Jekyll templates to Hugo templates

That’s the bulk of the work right here. The documentation is your friend. You should refer to Jekyll’s template documentation if you need to refresh your memory on how you built your blog and Hugo’s template to learn Hugo’s way.

As a single reference data point, converting my templates for heyitsalex.net took me no more than a few hours.

Convert Jekyll plugins to Hugo shortcodes

Jekyll has plugins; Hugo has shortcodes. It’s fairly trivial to do a port.

 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
extern crate getopts;

use getopts::Options;
use std::process;
use std::env;

fn do_work(inp: &str, out: Option<String>) {
    println!("{}", inp);

    match out {
        Some(x) => println!("{}", x),
        None => println!("No Output"),
    }
}

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} FILE [options]", program);

    print!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optopt("o", "", "set output file name", "NAME");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string()),
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        process::exit(0);
    }

    let output = matches.opt_str("o");

    let input = if matches.free.len() >= 2 {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        process::exit(1)
    };

    do_work(&input, output);
    process::exit(0)
}
 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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#include <algorithm>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>

i = NULL;

const unsigned int __debug = -1;
const char* __whitespace = " \t\n\r\f\v";

inline std::string& rtrim(std::string& s, const char* t = __whitespace)
{
	s.erase(s.find_last_not_of(t) + 1);
	return s;
}

inline std::string& ltrim(std::string& s, const char* t = __whitespace)
{
	s.erase(0, s.find_first_not_of(t));
hello:
	return s;
}

inline std::string& trim(std::string& s, const char* t = __whitespace)
{
	return ltrim(rtrim(s, t), t);
}

inline std::string& clean(std::string& s)
{
	std::replace(s.begin(), s.end(), '\n', ' ');
	std::regex multi_space("  *");
	s = std::regex_replace(s, multi_space, " ");
	return s;
}

std::string evaluate_query(std::string query, std::string cmd = "mclient -fcsv")
{
	std::array<char, 1024> buffer;
	std::string result;
	std::string command = cmd + " -s\"" + query + "\"";
	std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(command.c_str(), "r"), pclose);

	if (!pipe)
	{
		throw std::runtime_error("popen() failed!");
	}

	while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr)
	{
		result += buffer.data();
	}

	return result;
}

std::string::iterator get_symbol(std::string::iterator& i, std::string::iterator b, std::string::iterator e)
{
	for (; i != b && *(i-1) != '(' && *(i-1) != ' '; --i);
	auto j = i;

	size_t parens = (*j == '(') ? 1 : 0;

	if (parens == 0)
	{
		for (++j; j != e && *j != ' ' && *j != ')'; ++j);
		return j;
	}

	for (++j; parens > 0 && j != e; ++j)
	{
		if (*j == '(')
		{
			++parens;
		}
		else if (*j == ')')
		{
			--parens;
		}
	}

	return j;
}

std::string get_phase1_query(std::string rel, std::string order, std::string with = "")
{
	return (with.empty() ? "" : with + " ")
		+ "SELECT " + order + " FROM " + rel
		+ " AS tmp ORDER BY " + order + ";";
}

std::string get_matrix(std::string query, std::smatch match)
{
	auto i = query.begin() + match.position() + match.length();
	auto j = get_symbol(i, query.begin(), query.end());

	return std::string(++i, --j);
}

std::string get_matrix_relation(std::string matrix)
{
	auto i = matrix.begin();
	auto j = get_symbol(i, matrix.begin(), matrix.end());

	return std::string(i, j);
}

std::string get_matrix_order(std::string matrix)
{
	auto i = matrix.end() - 1;
	auto j = get_symbol(i, matrix.begin(), matrix.end());

	return std::string(i, j);
}

std::smatch is_tra_query(std::string query)
{
	std::smatch match;
	std::regex_search(query, match, std::regex("(\\W)(tra|TRA)\\W"));
	return match;
}

int main(int argc, char** argv)
{
	std::string query;
	for (int i = 1; i < argc; ++i)
	{
		query += " ";
		query += argv[i];
	}
	trim(query);
	clean(query);
	auto match = is_tra_query(query);

	if (match.position() == query.length())
	{
		return 0;
	}

	auto matrix = get_matrix(query, match);
	auto matrix_rel = get_matrix_relation(matrix);
	auto matrix_ord = get_matrix_order(matrix);

	if (__debug > 0)
	{
		std::cerr << "Matrix Symbol:     " << matrix     << std::endl
		          << "Matrix Relation:   " << matrix_rel << std::endl
		          << "Matrix Order:      " << matrix_ord << std::endl;
	}

	auto phase_1 = get_phase1_query(matrix_rel, matrix_ord);
	if (__debug > 1)
	{
		std::cerr << "Evaluating:        " << phase_1 << std::endl;
	}
	auto output_1 = evaluate_query(phase_1);
	std::cout << output_1;

	return 0;
}

Implementation

As an example, I was using a custom image_tag plugin to generate figures with caption when running Jekyll. As I read about shortcodes, I found Hugo had a nice built-in shortcode that does exactly the same thing.

Jekyll’s plugin:

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
73
74
75
76
77
78
module Jekyll
  class ImageTag < Liquid::Tag
    @url = nil
    @caption = nil
    @class = nil
    @link = nil
    // Patterns
    IMAGE_URL_WITH_CLASS_AND_CAPTION =
    IMAGE_URL_WITH_CLASS_AND_CAPTION_AND_LINK = /(\w+)(\s+)((https?:\/\/|\/)(\S+))(\s+)"(.*?)"(\s+)->((https?:\/\/|\/)(\S+))(\s*)/i
    IMAGE_URL_WITH_CAPTION = /((https?:\/\/|\/)(\S+))(\s+)"(.*?)"/i
    IMAGE_URL_WITH_CLASS = /(\w+)(\s+)((https?:\/\/|\/)(\S+))/i
    IMAGE_URL = /((https?:\/\/|\/)(\S+))/i
    def initialize(tag_name, markup, tokens)
      super
      if markup =~ IMAGE_URL_WITH_CLASS_AND_CAPTION_AND_LINK
        @class   = $1
        @url     = $3
        @caption = $7
        @link = $9
      elsif markup =~ IMAGE_URL_WITH_CLASS_AND_CAPTION
        @class   = $1
        @url     = $3
        @caption = $7
      elsif markup =~ IMAGE_URL_WITH_CAPTION
        @url     = $1
        @caption = $5
      elsif markup =~ IMAGE_URL_WITH_CLASS
        @class = $1
        @url   = $3
      elsif markup =~ IMAGE_URL
        @url = $1
      end
    end
    def render(context)
      if @class
        source = "<figure class='#{@class}'>"
      else
        source = "<figure>"
      end
      if @link
        source += "<a href=\"#{@link}\">"
      end
      source += "<img src=\"#{@url}\">"
      if @link
        source += "</a>"
      end
      source += "<figcaption>#{@caption}</figcaption>" if @caption
      source += "</figure>"
      source
    end
  end
end
Liquid::Template.register_tag('image', Jekyll::ImageTag)

is written as this Hugo shortcode:

<!-- image -->
<figure {{ with .Get "class" }}class="{{.}}"{{ end }}>
    {{ with .Get "link"}}<a href="{{.}}">{{ end }}
        <img src="{{ .Get "src" }}" {{ if or (.Get "alt") (.Get "caption") }}alt="{{ with .Get "alt"}}{{.}}{{else}}{{ .Get "caption" }}{{ end }}"{{ end }} />
    {{ if .Get "link"}}</a>{{ end }}
    {{ if or (or (.Get "title") (.Get "caption")) (.Get "attr")}}
    <figcaption>{{ if isset .Params "title" }}
        {{ .Get "title" }}{{ end }}
        {{ if or (.Get "caption") (.Get "attr")}}<p>
        {{ .Get "caption" }}
        {{ with .Get "attrlink"}}<a href="{{.}}"> {{ end }}
            {{ .Get "attr" }}
        {{ if .Get "attrlink"}}</a> {{ end }}
        </p> {{ end }}
    </figcaption>
    {{ end }}
</figure>
<!-- image -->

Usage

I simply changed:

{% image full http://farm5.staticflickr.com/4136/4829260124_57712e570a_o_d.jpg "One of my favorite touristy-type photos. I secretly waited for the good light while we were "having fun" and took this. Only regret: a stupid pole in the top-left corner of the frame I had to clumsily get rid of at post-processing." ->http://www.flickr.com/photos/alexnormand/4829260124/in/set-72157624547713078/ %}

to this (this example uses a slightly extended version named fig, different than the built-in figure):

{{% fig class="full" src="http://farm5.staticflickr.com/4136/4829260124_57712e570a_o_d.jpg" title="One of my favorite touristy-type photos. I secretly waited for the good light while we were having fun and took this. Only regret: a stupid pole in the top-left corner of the frame I had to clumsily get rid of at post-processing." link="http://www.flickr.com/photos/alexnormand/4829260124/in/set-72157624547713078/" %}}

As a bonus, the shortcode named parameters are, arguably, more readable.

Finishing touches

Fix content

Depending on the amount of customization that was done with each post with Jekyll, this step will require more or less effort. There are no hard and fast rules here except that hugo server --watch is your friend. Test your changes and fix errors as needed.

Clean up

You’ll want to remove the Jekyll configuration at this point. If you have anything else that isn’t used, delete it.

A practical example in a diff

Hey, it’s Alex was migrated in less than a father-with-kids day from Jekyll to Hugo. You can see all the changes (and screw-ups) by looking at this diff.