Class: Jekyll::Commands::MigratePermalinks

Inherits:
Command
  • Object
show all
Defined in:
lib/jekyll/commands/migrate_permalink.rb

Class Method Summary collapse

Class Method Details

.init_with_program(prog) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/jekyll/commands/migrate_permalink.rb', line 5

def init_with_program(prog)
  prog.command(:"migrate-permalink") do |c|
    c.description "Migrate your permalinks"
    c.option "strategy", "-s", "--strategy STRATEGY", "Strategy"

    add_build_options(c)

    c.action do |args, opts|
      opts["serving"] = false
      Jekyll::Commands::MigratePermalinks.process(args, opts)
    end
  end
end

.process(args, opts) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/jekyll/commands/migrate_permalink.rb', line 19

def process(args, opts)
  Jekyll.logger.adjust_verbosity(opts)
  options = configuration_from_options(opts)
  site = Jekyll::Site.new(options)

  site.reset
  site.read

  site.posts.docs.each do |post|
    content = File.read(post.path, Utils.merged_file_read_opts(site, options))
    output = process_content(content, post.url, opts["stategy"])
    File.write(post.path, output, :mode => "w")
  end
end

.process_content(content, url, strategy) ⇒ Object



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
# File 'lib/jekyll/commands/migrate_permalink.rb', line 34

def process_content(content, url, strategy)
  if content =~ Document::YAML_FRONT_MATTER_REGEXP
    content = $POSTMATCH
    frontmatter = SafeYAML.load(Regexp.last_match(1))
  end

  if frontmatter.nil?
    frontmatter = frontmatter.to_h
  end

  if strategy == "retain" && !frontmatter["permalink"]
    frontmatter["permalink"] = url
  else
    if frontmatter["redirect_from"].is_a? Array
      frontmatter["redirect_from"].push(url)
    elsif frontmatter["redirect_from"].is_a? String
      frontmatter["redirect_from"] = [frontmatter["redirect_from"], url]
    else
      frontmatter["redirect_from"] = [url]
    end
  end

  output = "#{frontmatter.to_yaml}---\n\n#{content}"

  output
end