Sha256: 4462f2c59ec4f6d4ceec4b883f2e8508654c8b34cfaa6590b34df09170494c3e

Contents?: true

Size: 1.64 KB

Versions: 6

Compression:

Stored size: 1.64 KB

Contents

# encoding: utf-8

module Nanoc::Extra::Checking::Checks

  # A check that verifies that all internal links point to a location that exists.
  class InternalLinks < ::Nanoc::Extra::Checking::Check

    # Starts the validator. The results will be printed to stdout.
    #
    # @return [void]
    def run
      # TODO de-duplicate this (duplicated in external links check)
      filenames = self.output_filenames.select { |f| File.extname(f) == '.html' }
      hrefs_with_filenames = ::Nanoc::Extra::LinkCollector.new(filenames, :internal).filenames_per_href
      hrefs_with_filenames.each_pair do |href, filenames|
        filenames.each do |filename|
          unless valid?(href, filename)
          self.add_issue(
            "reference to #{href}",
            :subject  => filename)
          end
        end
      end
    end

  protected

    def valid?(href, origin)
      # Skip hrefs that point to self
      # FIXME this is ugly and won’t always be correct
      return true if href == '.'

      # Remove target
      path = href.sub(/#.*$/, '')
      return true if path.empty?

      # Remove query string
      path = path.sub(/\?.*$/, '')
      return true if path.empty?

      # Make absolute
      if path[0, 1] == '/'
        path = @site.config[:output_dir] + path
      else
        path = ::File.expand_path(path, ::File.dirname(origin))
      end

      # Check whether file exists
      return true if File.file?(path)

      # Check whether directory with index file exists
      return true if File.directory?(path) && @site.config[:index_filenames].any? { |fn| File.file?(File.join(path, fn)) }

      # Nope :(
      return false
    end

  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
nanoc-3.6.3 lib/nanoc/extra/checking/checks/internal_links.rb
nanoc-3.6.2 lib/nanoc/extra/checking/checks/internal_links.rb
nanoc-3.6.1 lib/nanoc/extra/checking/checks/internal_links.rb
nanoc-3.6.0 lib/nanoc/extra/checking/checks/internal_links.rb
nanoc-3.5.0 lib/nanoc/extra/checking/checks/internal_links.rb
nanoc-3.5.0b2 lib/nanoc/extra/checking/checks/internal_links.rb