Class: JekyllLastCommit::Generator

Inherits:
Jekyll::Generator
  • Object
show all
Defined in:
lib/jekyll-last-commit/generator.rb

Instance Method Summary collapse

Instance Method Details

#generate(site) ⇒ Object



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
# File 'lib/jekyll-last-commit/generator.rb', line 6

def generate(site)
  repo_man = JekyllLastCommit::RepoMan.new(site.source)
  repo_man.discover_repo()
  repo_man.discover_commits(site.documents.map {|d| d.relative_path })
  repo_man.discover_commits(site.pages.map {|p| p.relative_path })

  date_format = site.config.dig('jekyll-last-commit', 'date_format')
  date_format ||= '%B %d, %Y'

  should_fall_back_to_mtime = site.config.dig('jekyll-last-commit', 'should_fall_back_to_mtime')
  should_fall_back_to_mtime = should_fall_back_to_mtime.nil? ? true : should_fall_back_to_mtime

  site.documents.each do |document|
    commit = repo_man.find_commit(document.relative_path)

    if commit.nil?
      if should_fall_back_to_mtime
        path_document = Jekyll.sanitized_path(site.source, document.relative_path)

        if File.file?(path_document)
          raw_time = Time.at(File.mtime(path_document).to_i)

          Jekyll.logger.warn "JekyllLastCommit: unable to find commit information for #{document.relative_path}. falling back to `mtime` for last_modified_at"
          document.data['last_modified_at'] = raw_time
          document.data['last_modified_at_formatted'] = raw_time.strftime(date_format)
        end
      end
    else
      raw_time = Time.at(commit["time"].to_i)

      document.data['last_commit'] = commit
      document.data['last_modified_at'] = raw_time
      document.data['last_modified_at_formatted'] = raw_time.strftime(date_format)
    end
  end

  site.pages.each do |page|
    commit = repo_man.find_commit(page.relative_path)

    if commit.nil?
      if should_fall_back_to_mtime
        path_page = Jekyll.sanitized_path(site.source, page.relative_path)

        if File.file?(path_page)
          raw_time = Time.at(File.mtime(path_page).to_i)
          page.data['last_modified_at'] = raw_time
          page.data['last_modified_at_formatted'] = raw_time.strftime(date_format)
        end
      end

    else
      raw_time = Time.at(commit["time"].to_i)

      page.data['last_commit'] = commit
      page.data['last_modified_at'] = raw_time
      page.data['last_modified_at_formatted'] = raw_time.strftime(date_format)
    end
  end
end