jekyll-ruby-link-checker 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0223d27659e72a5fc9fd72e6fb89bb2436cca1d50f732c4d7f10c64c5609f1c8
4
- data.tar.gz: 884bb29d0304ec21c3c45b6d8e97de7268b9e0e48bc0b81e4deefc1fa934f992
3
+ metadata.gz: 9fabcbc1e1724a1a4d93a13c197448afb786a97ab9adb614a66b71fb8c21a4c1
4
+ data.tar.gz: 40bacd0542bde74859ab551420d8c6cf6c4e810e981f69ca5a02d5c7157ccb24
5
5
  SHA512:
6
- metadata.gz: 6e8976c6da5fb91932127a4e4ae6001fe7598162aa2c49428c869754ef0c3463cb355c679289aadcf1ab21ec852a7675768835abd52de175650e77f94b15391b
7
- data.tar.gz: 4e5c6adba491066ba6b758ed0ef520d6a3f4c4457f4544d5cceb4a6fe107a6d65c9ec83701d2a513901ad37c02ead3fb33d874c552cb331e94f7440cb9d200c6
6
+ metadata.gz: 69a2af01d7db5a915031894f700c7accfbce758be19e7a36c55b3825f1a430cb23ae7d0e023428361ac967bb97f9098fe658bc95bc437cb43948ae7342197742
7
+ data.tar.gz: c78b4c7c8d2b256c90d5b09e3100898ad1cea61a69a275ec415f1fae8be74f4931aa4b6ce6b18bc932a0c97080f4a97b103549a58062858c375e7e5be2695c11
data/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026/11/23)
4
+
5
+ - [#31](https://github.com/dblock/jekyll-ruby-link-checker/pull/31): Add screenshots of reports from code.dblock.org to the documentation - [@dblock](https://github.com/dblock).
6
+ - [#32](https://github.com/dblock/jekyll-ruby-link-checker/pull/32): Check images, in `img src` and `srcset`, and choose what's checked, where, and inside or outside the site, with `check` - [@dblock](https://github.com/dblock).
7
+ - [#33](https://github.com/dblock/jekyll-ruby-link-checker/pull/33): Check scripts and stylesheets - [@dblock](https://github.com/dblock).
8
+ - [#35](https://github.com/dblock/jekyll-ruby-link-checker/pull/35): Check what layouts and includes reference, such as navigation, once per layout, with the `layouts` option to turn it off - [@dblock](https://github.com/dblock).
9
+ - [#37](https://github.com/dblock/jekyll-ruby-link-checker/pull/37): List dead references of a kind as warnings with `fail: false`, exclude references of one kind with `exclude`, and skip anchors with `links.anchors: false` - [@dblock](https://github.com/dblock).
10
+ - [#38](https://github.com/dblock/jekyll-ruby-link-checker/pull/38): Check video, audio, and iframes, and kinds of references of your own, such as lazy-loaded images - [@dblock](https://github.com/dblock).
11
+ - [#39](https://github.com/dblock/jekyll-ruby-link-checker/pull/39): Add `rake benchmark`, which times the plugin on a generated site, or on an existing one - [@dblock](https://github.com/dblock).
12
+ - [#40](https://github.com/dblock/jekyll-ruby-link-checker/pull/40): Collect references three times faster, and only find anchors in `id` and `name` attributes - [@dblock](https://github.com/dblock).
13
+ - [#41](https://github.com/dblock/jekyll-ruby-link-checker/pull/41): List features in `README.md`, and simplify the documentation - [@dblock](https://github.com/dblock).
14
+ - [#42](https://github.com/dblock/jekyll-ruby-link-checker/pull/42): Only fail on new dead links with `LINK_CHECKER_FAIL=new`, compared with the dead links of an earlier build in `LINK_CHECKER_BASELINE`, which `LINK_CHECKER_DEAD_LINKS` writes - [@dblock](https://github.com/dblock).
15
+ - [#43](https://github.com/dblock/jekyll-ruby-link-checker/pull/43): List new, existing, and fixed dead links in their own sections of the report - [@dblock](https://github.com/dblock).
16
+ - [#45](https://github.com/dblock/jekyll-ruby-link-checker/pull/45): Fail pull requests only on new dead links by default, compared with the dead links of the default branch, which the workflow and the action save in the cache. `fail-on-dead-links` of `check-links.yml` is now text: quote `'true'` and `'false'` - [@dblock](https://github.com/dblock).
17
+
3
18
  ## 0.1.0 (2026/11/23)
4
19
 
5
20
  - [#2](https://github.com/dblock/jekyll-ruby-link-checker/pull/2): Check internal, anchor, relative, and external links during the build, with configuration, a persistent cache, and a reusable workflow that keeps the cache between runs - [@dblock](https://github.com/dblock).
data/README.md CHANGED
@@ -4,7 +4,19 @@
4
4
 
5
5
  [![Test](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/test.yml/badge.svg)](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/test.yml) [![Lint](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/lint.yml/badge.svg)](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/lint.yml) [![Package](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/package.yml/badge.svg)](https://github.com/dblock/jekyll-ruby-link-checker/actions/workflows/package.yml) [![Coverage Status](https://coveralls.io/repos/github/dblock/jekyll-ruby-link-checker/badge.svg?branch=master)](https://coveralls.io/github/dblock/jekyll-ruby-link-checker?branch=master)
6
6
 
7
- A Jekyll plugin that checks the links in your site while it builds, and fails the build when a link is dead. It uses [ruby-link-checker](https://github.com/dblock/ruby-link-checker) for external links and remembers the ones that worked, so later builds are fast. It also comes with GitHub Actions workflows that check links on every push and pull request.
7
+ A Jekyll plugin that checks the links, images, and other references of your site while it builds, and fails the build when one is dead. It comes with GitHub Actions workflows that check links on every push and pull request.
8
+
9
+ ## Features
10
+
11
+ - Checks links to pages of your site, anchors such as `#usage`, relative links, and links to other sites.
12
+ - Also checks images, including `srcset` and `<picture>`, scripts, stylesheets, icons, video, audio, and iframes, all on by default.
13
+ - Checks what layouts and includes reference, such as navigation, and reports a broken one once, from the layout, rather than from every page.
14
+ - Follows `jekyll-redirect-from` redirects, and checks other sites with [ruby-link-checker](https://github.com/dblock/ruby-link-checker), concurrently, with retries.
15
+ - Remembers links that worked in a cache, so later builds only check what's new.
16
+ - Reports links blocked by bot protection, such as Cloudflare challenges, as unverified, rather than as dead.
17
+ - Lets you choose what's checked, find references in tags of your own, exclude sites, URLs, and paths, and list some kinds as warnings rather than fail the build.
18
+ - Writes a Markdown report that suggests exclusions for links whose results change from one run to the next.
19
+ - In pull requests, only checks the pages they change, only fails on dead links that aren't already dead on your default branch, and comments with the dead links; on your default branch, keeps an issue of dead links up to date.
8
20
 
9
21
  ## Installation
10
22
 
@@ -56,6 +68,8 @@ jobs:
56
68
 
57
69
  A run fails when it finds dead links, and lists them in its summary. Fix them, push, and repeat until the run passes.
58
70
 
71
+ To also comment on pull requests with their dead links, and keep an issue of the dead links on your default branch up to date, add this workflow:
72
+
59
73
  ```yaml
60
74
  # .github/workflows/publish-link-checker-report.yml
61
75
  name: Publish Link Checker Report
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Jekyll
6
+ module RubyLinkChecker
7
+ # The dead links of an earlier build, such as of the default branch, by URL, with their reason and the pages that
8
+ # linked to them, in a JSON file. A build compares its dead links with them to tell new ones from existing ones.
9
+ class Baseline
10
+ VERSION = 1
11
+
12
+ attr_reader :links
13
+
14
+ # Returns nil when there's no file. A file that can't be read is ignored with a warning, rather than failing the
15
+ # build, because it's usually a cache that a later build replaces.
16
+ def self.read(file)
17
+ return nil unless file && File.file?(file)
18
+
19
+ new(parse(JSON.parse(File.read(file))))
20
+ rescue JSON::ParserError, KeyError, TypeError, NoMethodError => e
21
+ Jekyll.logger.warn('LinkChecker:', "Ignoring the baseline in #{file}, which can't be read: #{e.message}")
22
+ nil
23
+ end
24
+
25
+ def self.parse(data)
26
+ raise JSON::ParserError, "expected version #{VERSION}" unless data.is_a?(Hash) && data['version'] == VERSION
27
+
28
+ data.fetch('dead_links').to_h do |link|
29
+ [link.fetch('url'), { reason: link.fetch('reason'), locations: Set.new(link.fetch('locations')) }]
30
+ end
31
+ end
32
+
33
+ # Writes `links`, by URL, with their reason and locations.
34
+ def self.write(file, links)
35
+ FileUtils.mkdir_p(File.dirname(file))
36
+ dead_links = links.sort.map do |url, link|
37
+ { 'url' => url, 'reason' => link[:reason], 'locations' => link[:locations].sort }
38
+ end
39
+ File.write(file, "#{JSON.pretty_generate('version' => VERSION, 'dead_links' => dead_links)}\n")
40
+ end
41
+
42
+ def initialize(links)
43
+ @links = links
44
+ end
45
+
46
+ def include?(url)
47
+ @links.key?(url)
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ # The `check` section of `link_checker`: which kinds of references are checked, where each is found, with `tags`,
6
+ # and how, with `internal`, `external`, `fail`, and `exclude`. `defaults` applies to every kind that doesn't set
7
+ # its own, and its `exclude` adds to each kind's. Any other key is a kind of the site's own, which sets `tags`, and
8
+ # is reported by its name.
9
+ class Check
10
+ # Each built-in kind, with its label in reports and the attributes of the elements, by selector, that hold it.
11
+ KINDS = {
12
+ 'links' => ['link', {
13
+ 'a' => %w[href], 'area' => %w[href],
14
+ 'link:not([rel~=stylesheet], [rel~=preconnect], [rel~=dns-prefetch])' => %w[href]
15
+ }],
16
+ 'images' => ['image', { 'img' => %w[src srcset], 'source' => %w[srcset] }],
17
+ 'scripts' => ['script', { 'script' => %w[src] }],
18
+ 'stylesheets' => ['stylesheet', { 'link[rel~=stylesheet]' => %w[href] }],
19
+ 'media' => ['media', {
20
+ 'video' => %w[src poster], 'audio' => %w[src], 'source' => %w[src], 'track' => %w[src]
21
+ }],
22
+ 'iframes' => ['iframe', { 'iframe' => %w[src] }]
23
+ }.freeze
24
+
25
+ NAME = /\A[a-z][a-z0-9_-]*\z/
26
+
27
+ OPTIONS = %w[internal external fail exclude].freeze
28
+ BOOLEANS = %w[internal external fail anchors].freeze
29
+ # Options of one kind only.
30
+ SPECIFIC = { 'links' => %w[anchors] }.freeze
31
+
32
+ attr_reader :kinds
33
+
34
+ def initialize(raw)
35
+ raw ||= {}
36
+ Values.invalid!('check', raw, 'a set of options') unless raw.is_a?(Hash)
37
+ defaults = options(raw.fetch('defaults', {}), 'check.defaults', OPTIONS)
38
+ @kinds = all(raw).filter_map { |name, (label, tags)| kind(name, label, tags, raw[name], defaults) }
39
+ end
40
+
41
+ private
42
+
43
+ # The built-in kinds, then those of the site, labeled by their name. A misspelled built-in kind, such as
44
+ # `image`, has no `tags`, so it fails rather than being ignored.
45
+ def all(raw)
46
+ KINDS.merge((raw.keys - ['defaults', *KINDS.keys]).to_h do |name|
47
+ unless name.to_s.match?(NAME) && raw[name].is_a?(Hash) && raw[name].key?('tags')
48
+ Values.invalid!("check.#{name}", raw[name], "a kind with tags, as it isn't one of #{KINDS.keys.join(', ')}")
49
+ end
50
+
51
+ [name, [name, nil]]
52
+ end)
53
+ end
54
+
55
+ # A kind is checked unless it's `false`; `true`, or leaving it out, keeps its defaults.
56
+ def kind(name, label, tags, value, defaults)
57
+ return nil if value == false
58
+
59
+ value = options(value.nil? || value == true ? {} : value, "check.#{name}",
60
+ ['tags', *OPTIONS, *SPECIFIC.fetch(name, [])])
61
+ Kind.new(name: name, label: label, tags: tags(value.fetch('tags', tags), "check.#{name}.tags"),
62
+ exclude: [defaults['exclude'], value['exclude']].compact,
63
+ **BOOLEANS.to_h { |option| [option.to_sym, value.fetch(option, defaults.fetch(option, true))] })
64
+ end
65
+
66
+ def options(value, name, valid)
67
+ Values.invalid!(name, value, 'true, false, or a set of options') unless value.is_a?(Hash)
68
+ Values.known!(value, valid, name)
69
+ BOOLEANS.each { |option| Values.boolean(value[option], "#{name}.#{option}") if value.key?(option) }
70
+ value.key?('exclude') ? value.merge('exclude' => exclude(value['exclude'], "#{name}.exclude")) : value
71
+ end
72
+
73
+ # The same lists as the top-level `exclude`.
74
+ def exclude(value, name)
75
+ Values.invalid!(name, value, 'a set of options') unless value.is_a?(Hash)
76
+ Values.known!(value, Exclude.members, name)
77
+ Exclude.new(**value.transform_keys(&:to_sym), name: name)
78
+ end
79
+
80
+ # Selectors, such as `img` or `link[rel~=stylesheet]`, and the names of the attributes that hold URLs.
81
+ def tags(value, name)
82
+ Values.invalid!(name, value, 'a set of selectors and attributes') unless value.is_a?(Hash) && !value.empty?
83
+
84
+ value.map { |selector, attributes| [Selector.parse(selector, name), names(attributes, "#{name}.#{selector}")] }
85
+ end
86
+
87
+ def names(value, name)
88
+ names = Array(value)
89
+ return names.map(&:downcase) if names.all? { |item| item.is_a?(String) && item.match?(/\A[a-z][\w:-]*\z/i) }
90
+
91
+ Values.invalid!(name, value, 'a list of attribute names')
92
+ end
93
+ end
94
+ end
95
+ end
@@ -6,7 +6,6 @@ module Jekyll
6
6
  module RubyLinkChecker
7
7
  # Collects the links of one build and checks them once the site is written.
8
8
  class Checker
9
- HREF = /<a\s[^>]*?href=(["'])(.*?)\1/im
10
9
  HTML_EXTENSIONS = %w[.html .htm].freeze
11
10
 
12
11
  class << self
@@ -38,17 +37,15 @@ module Jekyll
38
37
  @only = ChangedFiles.pages(site, @config.changed_files(site.source))
39
38
  @report = new_report
40
39
  @links = Hash.new { |hash, url| hash[url] = Set.new }
40
+ @kinds = {}
41
41
  end
42
42
 
43
43
  def collect(page)
44
44
  return unless checked?(page)
45
45
 
46
46
  @report.page(page.relative_path, title: page.data['title'], url: page_url(page))
47
- hrefs(page).each do |href|
48
- next check_anchor(page, href) if href.start_with?('#')
49
-
50
- @links[@urls.resolve(page.url, href)] << page.relative_path
51
- end
47
+ @ids = nil
48
+ sources.each(page) { |location, kind, href| reference(page, location, kind, href) }
52
49
  end
53
50
 
54
51
  def verify
@@ -61,10 +58,35 @@ module Jekyll
61
58
 
62
59
  private
63
60
 
61
+ def sources = @sources ||= Sources.new(@site, References.new(@config.check.kinds), layouts: @config.layouts?)
62
+
63
+ # Anchors on the same page are checked against it, and anything else once the site is written. A layout is
64
+ # listed in the report without a title or a link.
65
+ def reference(page, location, kind, href)
66
+ @report.page(location) unless location == page.relative_path
67
+ return (check_anchor(page, kind, href, location) if kind.anchors) if kind.link? && href.start_with?('#')
68
+
69
+ add(location, kind, @urls.resolve(page.url, href))
70
+ end
71
+
72
+ # A URL that is both linked and shown as an image keeps the kind it was first found as.
73
+ def add(location, kind, url)
74
+ @links[url] << location
75
+ @kinds[url] ||= kind
76
+ end
77
+
64
78
  def new_report
65
- Report.new(verbose: @config.verbose?, file: @config.report_file(@site.source),
66
- fail_on_dead_links: @config.fail_on_dead_links?, changed_pages: @only&.size,
67
- permanent_redirects: @config.permanent_redirects?).tap { |report| report.site_url = site_url }
79
+ Report.new(verbose: @config.verbose?, file: @config.report_file(@site.source), fail_on: @config.fail_on,
80
+ changed_pages: @only&.size, permanent_redirects: @config.permanent_redirects?).tap do |report|
81
+ report.site_url = site_url
82
+ compare(report)
83
+ end
84
+ end
85
+
86
+ # Dead links are compared with those of an earlier build, and written for a later one, when files are given.
87
+ def compare(report)
88
+ report.baseline = Baseline.read(@config.baseline_file(@site.source))
89
+ report.dead_links_file = @config.dead_links_file(@site.source)
68
90
  end
69
91
 
70
92
  # Pages that opt out with `link_checker: false`, outputs other than HTML, and, with LINK_CHECKER_CHANGED_FILES,
@@ -74,64 +96,49 @@ module Jekyll
74
96
  (@only.nil? || @only.include?(page.relative_path))
75
97
  end
76
98
 
77
- def hrefs(page)
78
- page.content.to_s.scan(HREF).map { |_, href| CGI.unescapeHTML(href.strip) }.reject do |href|
79
- href.empty? || href == '#'
80
- end
81
- end
82
-
83
- def site_url
84
- @site.config['url'].to_s.empty? ? nil : @site.config['url']
85
- end
99
+ def site_url = @site.config['url'].to_s.empty? ? nil : @site.config['url']
86
100
 
87
101
  def page_url(page)
88
102
  "#{site_url}#{@site.baseurl}#{page.url}" if site_url
89
103
  end
90
104
 
91
- def check_anchor(page, href)
92
- return if InternalLinks.anchor?(page.output.to_s, href[1..])
105
+ # An anchor in a layout is reported once, from the layout, rather than for every page.
106
+ def check_anchor(page, kind, href, location)
107
+ return if (@ids ||= InternalLinks.ids(page.output.to_s)).include?(CGI.unescape(href[1..]))
93
108
 
94
- @report.fail("#{page.url}#{href}", page.relative_path, 'anchor not found')
109
+ @report.fail(location == page.relative_path ? "#{page.url}#{href}" : href, location, 'anchor not found',
110
+ warn: !kind.fail)
95
111
  end
96
112
 
97
113
  def queue(href, locations, internal, external)
114
+ kind = @kinds[href]
98
115
  url = @urls.localize(href)
99
- return @report.count(:excluded) if @urls.excluded?(url)
116
+ return @report.count(:excluded) if @urls.excluded?(url, kind.exclude) || !kind.checks?(Urls.external?(url))
100
117
 
101
118
  if Urls.external?(url)
102
119
  @report.count(:external)
103
- external.check(url, locations: locations)
120
+ external.check(url, locations: locations, kind: kind.label, warn: !kind.fail)
104
121
  else
105
- check_internal(href, url, locations, internal)
122
+ check_internal(kind, href, url, locations, internal)
106
123
  end
107
124
  end
108
125
 
109
- def check_internal(href, url, locations, internal)
126
+ # A missing image is reported as such, rather than as a missing page. Without `anchors`, only the page is checked.
127
+ def check_internal(kind, href, url, locations, internal)
110
128
  @report.count(:internal)
111
- reason = internal.check(url)
129
+ reason = internal.check(kind.anchors ? url : url.split('#', 2).first)
130
+ reason = "#{kind.label} not found" if reason == 'page not found' && !kind.link?
112
131
  @report.log(href, reason || 'OK')
113
- @report.fail(href, locations, reason) if reason
132
+ @report.fail(href, locations, reason, warn: !kind.fail) if reason
114
133
  end
115
134
 
116
135
  def external_checker
117
- checker = LinkChecker::Typhoeus::Hydra::Checker.new(**checker_options)
136
+ checker = LinkChecker::Typhoeus::Hydra::Checker.new(**@config.checker_options(@site.source, full: @only.nil?))
118
137
  # `complete` is published once per link with its final result, unlike `result`, which is published for every
119
138
  # attempt, including each redirect. Cache hits are reported when a link is queued, before the checker runs.
120
139
  checker.on(:complete) { |result| @report.record(result) }
121
140
  checker
122
141
  end
123
-
124
- def checker_options
125
- options = {
126
- logger: @config.verbose? ? Jekyll.logger : Logger.new(IO::NULL),
127
- hydra: { max_concurrency: @config.concurrency },
128
- retries: @config.retries,
129
- cache: @config.cache_options(@site.source, full: @only.nil?),
130
- **@config.request_options
131
- }
132
- options[:user_agent] = @config.user_agent if @config.user_agent
133
- options
134
- end
135
142
  end
136
143
  end
137
144
  end
@@ -4,6 +4,8 @@ module Jekyll
4
4
  module RubyLinkChecker
5
5
  # Settings from `link_checker` in `_config.yml`, validated when the build starts.
6
6
  class Configuration
7
+ include Environment
8
+
7
9
  # Reuses successful external checks for `ttl`, and unverified ones for `blocked_ttl`, from a cache `file`,
8
10
  # relative to the site source, and with `prune`, removes entries of links that a full check no longer checks.
9
11
  Cache = Data.define(:file, :ttl, :blocked_ttl, :prune) do
@@ -17,17 +19,6 @@ module Jekyll
17
19
  end
18
20
  end
19
21
 
20
- # Links that are never checked: external hosts and their subdomains, exact URLs, and path patterns.
21
- Exclude = Data.define(:domains, :urls, :paths) do
22
- def initialize(domains: [], urls: [], paths: [])
23
- super(
24
- domains: Values.list(domains, 'exclude.domains').map(&:downcase),
25
- urls: Values.list(urls, 'exclude.urls').map { |url| Values.string_or_pattern(url, 'exclude.urls') },
26
- paths: Values.list(paths, 'exclude.paths').map { |path| Values.pattern(path, 'exclude.paths') }
27
- )
28
- end
29
- end
30
-
31
22
  # Options passed to ruby-link-checker, with its name and a reader; unset options keep its defaults.
32
23
  REQUEST_OPTIONS = {
33
24
  'blocked' => %i[blocked_status_codes status_codes],
@@ -40,10 +31,11 @@ module Jekyll
40
31
  'host_headers' => %i[host_headers host_headers]
41
32
  }.freeze
42
33
 
43
- OPTIONS = (%w[cache exclude concurrency retries user_agent verbose permanent_redirects] + REQUEST_OPTIONS.keys)
34
+ OPTIONS = (%w[cache exclude check layouts concurrency retries user_agent verbose permanent_redirects] +
35
+ REQUEST_OPTIONS.keys)
44
36
  .freeze
45
37
 
46
- attr_reader :cache, :exclude, :concurrency, :retries, :user_agent, :request_options
38
+ attr_reader :cache, :exclude, :check, :concurrency, :retries, :user_agent, :request_options
47
39
 
48
40
  def initialize(raw)
49
41
  raw ||= {}
@@ -56,10 +48,27 @@ module Jekyll
56
48
  @verbose
57
49
  end
58
50
 
51
+ def layouts?
52
+ @layouts
53
+ end
54
+
59
55
  def permanent_redirects?
60
56
  @permanent_redirects
61
57
  end
62
58
 
59
+ # Options of ruby-link-checker's checker; `full` is a check of every page, see `cache_options`.
60
+ def checker_options(source, full:)
61
+ options = {
62
+ logger: verbose? ? Jekyll.logger : Logger.new(IO::NULL),
63
+ hydra: { max_concurrency: concurrency },
64
+ retries: retries,
65
+ cache: cache_options(source, full: full),
66
+ **request_options
67
+ }
68
+ options[:user_agent] = user_agent if user_agent
69
+ options
70
+ end
71
+
63
72
  # LINK_CHECKER_CACHE overrides the configured cache file, for example in a CI workflow. Only a `full` check
64
73
  # prunes, because a check of some pages would remove the entries of the links on the others.
65
74
  def cache_options(source, full: true)
@@ -73,37 +82,25 @@ module Jekyll
73
82
  options
74
83
  end
75
84
 
76
- # LINK_CHECKER_REPORT names a file for a Markdown report, for example in a CI workflow.
77
- def report_file(source)
78
- file = ENV.fetch('LINK_CHECKER_REPORT', '').strip
79
- file.empty? ? nil : File.expand_path(file, source)
80
- end
81
-
82
- # LINK_CHECKER_CHANGED_FILES names a file that lists changed files, one per line, relative to the site source,
83
- # to only check the pages that changed, for example in a pull request.
84
- def changed_files(source)
85
- file = ENV.fetch('LINK_CHECKER_CHANGED_FILES', '').strip
86
- file.empty? ? nil : File.expand_path(file, source)
87
- end
88
-
89
- # LINK_CHECKER_FAIL=0 reports dead links without failing the build, for example on pull requests.
90
- def fail_on_dead_links?
91
- !%w[0 false no off].include?(ENV.fetch('LINK_CHECKER_FAIL', '').strip.downcase)
92
- end
93
-
94
85
  private
95
86
 
96
87
  def read(raw)
97
- @cache = section(Cache, raw['cache'], 'cache')
98
- @exclude = section(Exclude, raw['exclude'], 'exclude')
88
+ read_sections(raw)
99
89
  @concurrency = Values.positive_integer(raw.fetch('concurrency', 5), 'concurrency')
100
90
  @retries = Values.non_negative_integer(raw.fetch('retries', 1), 'retries')
101
91
  @user_agent = raw['user_agent']&.to_s
102
92
  @verbose = raw.fetch('verbose', false) == true
93
+ @layouts = Values.boolean(raw.fetch('layouts', true), 'layouts')
103
94
  @permanent_redirects = Values.boolean(raw.fetch('permanent_redirects', false), 'permanent_redirects')
104
95
  @request_options = read_request_options(raw)
105
96
  end
106
97
 
98
+ def read_sections(raw)
99
+ @cache = section(Cache, raw['cache'], 'cache')
100
+ @exclude = section(Exclude, raw['exclude'], 'exclude')
101
+ @check = Check.new(raw['check'])
102
+ end
103
+
107
104
  def read_request_options(raw)
108
105
  REQUEST_OPTIONS.select { |name, _| raw.key?(name) }.to_h do |name, (option, reader)|
109
106
  [option, Values.public_send(reader, raw[name], name)]
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ class Configuration
6
+ # Settings from environment variables, which change how one build checks links, mostly in CI. Files are relative
7
+ # to the site source.
8
+ module Environment
9
+ # LINK_CHECKER_REPORT names a file for a Markdown report, for example in a CI workflow.
10
+ def report_file(source) = env_file('LINK_CHECKER_REPORT', source)
11
+
12
+ # LINK_CHECKER_CHANGED_FILES names a file that lists changed files, one per line, relative to the site source,
13
+ # to only check the pages that changed, for example in a pull request.
14
+ def changed_files(source) = env_file('LINK_CHECKER_CHANGED_FILES', source)
15
+
16
+ # LINK_CHECKER_FAIL=0 reports dead links without failing the build, and LINK_CHECKER_FAIL=new only fails on dead
17
+ # links that aren't in the baseline, for example on pull requests.
18
+ def fail_on
19
+ value = ENV.fetch('LINK_CHECKER_FAIL', '').strip.downcase
20
+ return :none if %w[0 false no off].include?(value)
21
+
22
+ value == 'new' ? :new : :all
23
+ end
24
+
25
+ # LINK_CHECKER_BASELINE names a file of the dead links of an earlier build, such as of the default branch, and
26
+ # LINK_CHECKER_DEAD_LINKS a file to write the dead links of this build to, both relative to the site source.
27
+ def baseline_file(source) = env_file('LINK_CHECKER_BASELINE', source)
28
+
29
+ def dead_links_file(source) = env_file('LINK_CHECKER_DEAD_LINKS', source)
30
+
31
+ private
32
+
33
+ def env_file(name, source)
34
+ file = ENV.fetch(name, '').strip
35
+ file.empty? ? nil : File.expand_path(file, source)
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ # Links that are never checked: external hosts and their subdomains, exact URLs, and path patterns.
6
+ Exclude = Data.define(:domains, :urls, :paths) do
7
+ # `name` is where the exclusions are configured, such as `check.images.exclude`, for errors.
8
+ def initialize(domains: [], urls: [], paths: [], name: 'exclude')
9
+ super(
10
+ domains: Values.list(domains, "#{name}.domains").map(&:downcase),
11
+ urls: Values.list(urls, "#{name}.urls").map { |url| Values.string_or_pattern(url, "#{name}.urls") },
12
+ paths: Values.list(paths, "#{name}.paths").map { |path| Values.pattern(path, "#{name}.paths") }
13
+ )
14
+ end
15
+ end
16
+ end
17
+ end
@@ -9,12 +9,15 @@ module Jekyll
9
9
  MAX_REDIRECTS = 10
10
10
  REDIRECT_TITLE = '<title>Redirecting'
11
11
  HREF = /<a\s[^>]*?href=(["'])(.*?)\1/im
12
+ ELEMENT_WITH_ID = /<[a-z][a-z0-9-]*\s[^>]*?(?:id|name)\s*=[^>]*>/im
13
+ ANCHOR_ATTRIBUTES = %w[id name].freeze
12
14
 
13
15
  # `localize` turns absolute links to the site itself into paths.
14
16
  def initialize(destination, localize: ->(url) { url })
15
17
  @destination = destination
16
18
  @localize = localize
17
19
  @contents = {}
20
+ @ids = {}.compare_by_identity
18
21
  end
19
22
 
20
23
  # Returns nil when the link works, or a reason it doesn't.
@@ -24,18 +27,25 @@ module Jekyll
24
27
  content = read(path)
25
28
  return 'page not found' if content.nil?
26
29
  return follow(content, fragment, redirects) if content.include?(REDIRECT_TITLE)
27
- return nil if fragment.nil? || self.class.anchor?(content, fragment)
30
+ return nil if fragment.nil? || ids(content).include?(CGI.unescape(fragment))
28
31
 
29
32
  "anchor ##{fragment} not found"
30
33
  end
31
34
 
32
- def self.anchor?(content, fragment)
33
- id = Regexp.escape(CGI.unescape(fragment))
34
- content.match?(/<[a-z0-9-]+\s[^>]*?(?:id|name)=(["'])#{id}\1/i)
35
+ # The `id` and `name` attributes of the elements of a page, which anchors link to. A page is read once, rather
36
+ # than once for each anchor.
37
+ def self.ids(content)
38
+ content.scan(ELEMENT_WITH_ID).each_with_object(Set.new) do |element, ids|
39
+ References.attributes(element).each { |name, value| ids << value if ANCHOR_ATTRIBUTES.include?(name) }
40
+ end
35
41
  end
36
42
 
37
43
  private
38
44
 
45
+ def ids(content)
46
+ @ids[content] ||= self.class.ids(content)
47
+ end
48
+
39
49
  # Redirects to other sites are left unchecked here, and a redirect loop stops after MAX_REDIRECTS.
40
50
  def follow(content, fragment, redirects)
41
51
  target = redirect_target(content)
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ # A kind of reference, such as links or images: the elements and attributes that hold it, its `label` in reports,
6
+ # whether references to the site itself (`internal`) and to other sites (`external`) are checked, whether dead
7
+ # ones `fail` the build, its own `exclude` lists, and, for links, whether `anchors` are checked.
8
+ Kind = Data.define(:name, :label, :tags, :internal, :external, :fail, :exclude, :anchors) do
9
+ # Returns the URLs that an element with a lowercase `tag` and `attributes`, by lowercase name, holds.
10
+ def urls(tag, attributes)
11
+ tags.flat_map do |selector, names|
12
+ next [] unless selector.match?(tag, attributes)
13
+
14
+ names.flat_map { |name| attributes.key?(name) ? Kind.values(name, attributes[name]) : [] }
15
+ end
16
+ end
17
+
18
+ def link?
19
+ name == 'links'
20
+ end
21
+
22
+ # The names of the tags that its selectors match, such as `img`.
23
+ def tag_names
24
+ tags.map { |selector, _names| selector.tag }.uniq
25
+ end
26
+
27
+ # Kinds are told apart by their name, which is unique in a configuration; hashing every selector instead would
28
+ # make counting references slow.
29
+ def hash = name.hash
30
+
31
+ def eql?(other) = other.is_a?(Kind) && name == other.name
32
+
33
+ # Whether references of this kind to other sites, or to the site itself, are checked.
34
+ def checks?(external_url)
35
+ external_url ? external : internal
36
+ end
37
+
38
+ # A srcset, including data-srcset, holds URLs followed by descriptors, such as `2x` or `640w`, separated by
39
+ # commas. Browsers remove tabs and newlines from URLs, so a URL split across lines in the source still works.
40
+ def self.values(name, value)
41
+ urls = [value]
42
+ urls = value.split(',').map { |candidate| candidate.strip.split(/\s+/).first } if name.end_with?('srcset')
43
+ urls.map { |url| url.to_s.delete("\t\n\r") }
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'cgi'
4
+
5
+ module Jekyll
6
+ module RubyLinkChecker
7
+ # Finds what a page references that should be checked, with its kind, by matching each element against the
8
+ # selectors of each kind. Attribute values are HTML-decoded; empty links and a bare `#` are left out.
9
+ class References
10
+ ATTRIBUTE = %r{([^\s=/>"']+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>"']+))}m
11
+
12
+ # Attributes by lowercase name, HTML-decoded.
13
+ def self.attributes(text)
14
+ text.scan(ATTRIBUTE).to_h do |name, double, single, bare|
15
+ [name.downcase, CGI.unescapeHTML((double || single || bare).strip)]
16
+ end
17
+ end
18
+
19
+ # Only the tags that a kind's selectors name are read, which skips the attributes of most elements of a page.
20
+ def initialize(kinds)
21
+ @kinds = kinds.flat_map { |kind| kind.tag_names.map { |tag| [tag, kind] } }
22
+ .group_by(&:first).transform_values { |pairs| pairs.map(&:last) }
23
+ @tag = /<(#{alternatives(@kinds.keys)})(\s[^>]*)?>/im
24
+ end
25
+
26
+ # Returns pairs of a kind and a URL.
27
+ def scan(html)
28
+ references = []
29
+ html.scan(@tag) do |tag, text|
30
+ attributes = self.class.attributes(text.to_s)
31
+ tag = tag.downcase
32
+ @kinds[tag].each { |kind| kind.urls(tag, attributes).each { |url| references << [kind, url] } }
33
+ end
34
+ references.reject { |_kind, href| href.empty? || href == '#' }
35
+ end
36
+
37
+ private
38
+
39
+ # Longer names first, so that `area` isn't read as `a`.
40
+ def alternatives(tags)
41
+ tags.sort_by { |tag| -tag.length }.map { |tag| Regexp.escape(tag) }.join('|')
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ class Report
6
+ # Compares dead links with a baseline, such as those of the default branch. A dead link whose URL is in the
7
+ # baseline already existed, and one in the baseline that the checked pages no longer link to as dead is fixed.
8
+ # When only new dead links fail the build, new ones that failed in a way that may be temporary are warnings, and
9
+ # without a baseline, no dead link fails the build.
10
+ module Comparison
11
+ EXISTING = 'These links were already dead in the baseline, such as on the default branch.'
12
+ FIXED = 'These links were dead in the baseline, and work now, or the checked pages no longer link to them.'
13
+ UNCLASSIFIED = "There's no baseline, such as from the default branch, to tell new dead links from existing " \
14
+ "ones, so these don't fail the build. The next check of the default branch saves one."
15
+
16
+ attr_reader :existing, :fixed, :unclassified
17
+
18
+ # The dead links that fail the build.
19
+ def failing
20
+ @fail_on == :new ? @failures : @failures.merge(@existing)
21
+ end
22
+
23
+ private
24
+
25
+ # The dead links that fail the build, or, without a baseline to compare them with, those that would.
26
+ def dead_section
27
+ return section(@unclassified, 'Dead Link', UNCLASSIFIED) unless @unclassified.empty?
28
+
29
+ links = @baseline ? @failures : failing
30
+ return ["No #{'new ' if @baseline}dead links."] if links.empty?
31
+
32
+ section(links, @baseline ? 'New Dead Link' : 'Dead Link')
33
+ end
34
+
35
+ # Existing and fixed links are collapsed, because there are often many, and nothing to do about them here.
36
+ def comparison_sections
37
+ fixed = @fixed.transform_values { |link| link.merge(reason: "was #{link[:reason]}") }
38
+ [(collapsed(@existing, 'Existing Dead Link', EXISTING) unless @existing.empty?),
39
+ (collapsed(fixed, 'Fixed Link', FIXED) unless fixed.empty?)]
40
+ end
41
+
42
+ def collapsed(links, noun, note)
43
+ ["### #{plural(links.size, noun)}", '', note, '', "<details><summary>#{plural(links.size, 'link')}</summary>",
44
+ '', *links.sort.flat_map { |url, link| item(url, link, false) }, '', '</details>']
45
+ end
46
+
47
+ def compare
48
+ @dead = @failures.merge(@warnings)
49
+ @existing, @fixed, @unclassified = Array.new(3) { {} }
50
+ split_existing if @baseline
51
+ return unless @fail_on == :new
52
+
53
+ @baseline ? warn_flaky : unclassify
54
+ end
55
+
56
+ def split_existing
57
+ @existing, @failures = @failures.partition { |url, _link| @baseline.include?(url) }.map(&:to_h)
58
+ @fixed = @baseline.links.reject do |url, link|
59
+ @dead.key?(url) || !link[:locations].all? { |location| @pages.key?(location) }
60
+ end
61
+ end
62
+
63
+ def unclassify
64
+ @unclassified = @failures
65
+ @failures = {}
66
+ end
67
+
68
+ def warn_flaky
69
+ flaky, @failures = @failures.partition { |_url, link| link[:reason].match?(Exclusions::FLAKY) }.map(&:to_h)
70
+ @warnings.merge!(flaky)
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -7,7 +7,7 @@ module Jekyll
7
7
  # site when a site has several, and dead links that failed because the site didn't answer properly. Pages that
8
8
  # are gone are left out, because they need to be fixed.
9
9
  module Exclusions
10
- FLAKY = /\A(?:HTTP 5\d\d|Timeout|Connection error)/
10
+ FLAKY = /\A(?:\w+: )?(?:HTTP 5\d\d|Timeout|Connection error)/
11
11
  EXCLUSIONS = "These links may work, but couldn't be checked reliably. After checking them in a browser, " \
12
12
  'add this to `_config.yml` to stop checking them.'
13
13
 
@@ -47,7 +47,7 @@ module Jekyll
47
47
  end
48
48
 
49
49
  def flaky_failures
50
- @failures.select { |url, link| url.match?(%r{\Ahttps?://}) && link[:reason].match?(FLAKY) }.to_a
50
+ (@dead || @failures).select { |url, link| url.match?(%r{\Ahttps?://}) && link[:reason].match?(FLAKY) }.to_a
51
51
  end
52
52
  end
53
53
  end
@@ -7,11 +7,21 @@ module Jekyll
7
7
  module Formatting
8
8
  def summary
9
9
  "Checked #{@counts[:internal]} internal and #{@counts[:external]} external links " \
10
- "(#{@counts[:cached]} cached)#{scope}, skipped #{@counts[:excluded]}.#{unverified_summary}#{moved_summary}"
10
+ "(#{@counts[:cached]} cached)#{scope}, skipped #{@counts[:excluded]}.#{notes}"
11
11
  end
12
12
 
13
13
  def message
14
- "Found #{plural(@failures.size, 'dead link')}:\n#{list(@failures)}"
14
+ noun = @baseline && @fail_on == :new ? 'new dead link' : 'dead link'
15
+ "Found #{plural(failing.size, noun)}:\n#{list(failing)}"
16
+ end
17
+
18
+ def unclassified_message
19
+ "There's no baseline to tell new dead links from existing ones, so " \
20
+ "#{plural(@unclassified.size, 'dead link')} don't fail the build:\n#{list(@unclassified)}"
21
+ end
22
+
23
+ def warnings_message
24
+ "Found #{plural(@warnings.size, 'dead link')} that don't fail the build:\n#{list(@warnings)}"
15
25
  end
16
26
 
17
27
  def unverified_message
@@ -34,6 +44,21 @@ module Jekyll
34
44
  end.join("\n")
35
45
  end
36
46
 
47
+ def notes
48
+ "#{comparison_summary}#{warnings_summary}#{unverified_summary}#{moved_summary}"
49
+ end
50
+
51
+ # How many dead links already existed, and how many were fixed, compared with the baseline.
52
+ def comparison_summary
53
+ return '' unless @baseline
54
+
55
+ " #{plural(@existing.size, 'dead link')} already existed, #{plural(@fixed.size, 'link')} fixed."
56
+ end
57
+
58
+ def warnings_summary
59
+ @warnings.empty? ? '' : " #{plural(@warnings.size, 'warning')}."
60
+ end
61
+
37
62
  def unverified_summary
38
63
  @unverified.empty? ? '' : " Couldn't verify #{plural(@unverified.size, 'link')}."
39
64
  end
@@ -10,6 +10,8 @@ module Jekyll
10
10
  MARKER = 'jekyll-ruby-link-checker dead links:'
11
11
  UNVERIFIED = 'Bot protection blocked these checks, so these links may work. Check them in a browser.'
12
12
  MOVED = 'These links work, but redirect permanently. Update them to link to where they moved.'
13
+ WARNINGS = "These links are dead, but don't fail the build, because their kind is set to `fail: false`, or " \
14
+ 'because they failed in a way that may be temporary.'
13
15
  GUIDE = 'See [how to fix these links](https://github.com/dblock/jekyll-ruby-link-checker/blob/master/docs/fixing-links.md).'
14
16
  # Pages listed under a link before the rest are collapsed.
15
17
  PAGES_SHOWN = 3
@@ -17,18 +19,27 @@ module Jekyll
17
19
  TEXT_LENGTH = 60
18
20
 
19
21
  def markdown
20
- lines = ["<!-- #{MARKER} #{@failures.size} -->", '', summary, '']
21
- lines += @failures.empty? ? ['No dead links.'] : section(@failures, 'Dead Link')
22
- lines += ['', *unverified_section] unless @unverified.empty?
23
- lines += ['', *section(@moved, 'Link', MOVED, moved: true)] unless @moved.empty?
24
- exclusions = exclusions_section
25
- lines += ['', *exclusions] unless exclusions.empty?
26
- lines += ['', GUIDE] unless [@failures, @unverified, @moved].all?(&:empty?)
22
+ lines = ["<!-- #{MARKER} #{failing.size} -->", '', summary, '']
23
+ lines += dead_section
24
+ lines += other_sections
25
+ lines += ['', GUIDE] unless [@dead, @unverified, @moved].all?(&:empty?)
27
26
  "#{lines.join("\n")}\n"
28
27
  end
29
28
 
30
29
  private
31
30
 
31
+ # Warnings, unverified and moved links, and suggested exclusions, each after a blank line, when there are any.
32
+ def other_sections
33
+ sections = [
34
+ (section(@warnings, 'Warning', WARNINGS) unless @warnings.empty?),
35
+ *comparison_sections,
36
+ (unverified_section unless @unverified.empty?),
37
+ (section(@moved, 'Link', MOVED, moved: true) unless @moved.empty?),
38
+ exclusions_section
39
+ ]
40
+ sections.compact.reject(&:empty?).flat_map { |lines| ['', *lines] }
41
+ end
42
+
32
43
  def section(links, noun, note = nil, moved: false)
33
44
  title = moved ? "#{plural(links.size, noun)} Moved Permanently" : plural(links.size, noun)
34
45
  ["### #{title}", '', *([note, ''] if note), *links.sort.flat_map { |url, link| item(url, link, moved) }]
@@ -4,6 +4,7 @@ require 'fileutils'
4
4
  require_relative 'report/formatting'
5
5
  require_relative 'report/markdown'
6
6
  require_relative 'report/exclusions'
7
+ require_relative 'report/comparison'
7
8
 
8
9
  module Jekyll
9
10
  module RubyLinkChecker
@@ -15,23 +16,24 @@ module Jekyll
15
16
  include Formatting
16
17
  include Markdown
17
18
  include Exclusions
19
+ include Comparison
18
20
 
19
- attr_reader :counts, :failures, :unverified, :moved
21
+ attr_reader :counts, :failures, :warnings, :unverified, :moved
22
+ # A `Baseline` to compare dead links with, and a file to write the dead links of this build to, as a baseline.
23
+ attr_writer :baseline, :dead_links_file
20
24
 
21
- # Writes a Markdown report to `file`, when set, at the end of the build, and fails the build on dead links
22
- # unless `fail_on_dead_links` is false. `changed_pages` counts the pages checked when only changed ones are.
23
- # With `permanent_redirects`, working links that moved permanently are reported with their new URL.
24
- def initialize(verbose:, file: nil, fail_on_dead_links: true, changed_pages: nil, permanent_redirects: false)
25
+ # Writes a Markdown report to `file`, when set, at the end of the build, and fails the build on dead links when
26
+ # `fail_on` is `:all`, only on new ones when it's `:new`, and never when it's `:none`. `changed_pages` counts the
27
+ # pages checked when only changed ones are. With `permanent_redirects`, working links that moved permanently are
28
+ # reported with their new URL.
29
+ def initialize(verbose:, file: nil, fail_on: :all, changed_pages: nil, permanent_redirects: false)
25
30
  @verbose = verbose
26
31
  @file = file
27
- @fail_on_dead_links = fail_on_dead_links
32
+ @fail_on = fail_on
28
33
  @changed_pages = changed_pages
29
34
  @permanent_redirects = permanent_redirects
30
35
  @counts = Hash.new(0)
31
- @failures = {}
32
- @unverified = {}
33
- @moved = {}
34
- @pages = {}
36
+ @failures, @warnings, @unverified, @moved, @pages = Array.new(5) { {} }
35
37
  end
36
38
 
37
39
  # With the site's URL, the report links to the site's pages and its dead links.
@@ -48,8 +50,9 @@ module Jekyll
48
50
  @counts[kind] += 1
49
51
  end
50
52
 
51
- def fail(url, locations, reason)
52
- add(@failures, url, locations, reason)
53
+ # With `warn`, a dead link is listed as a warning, and doesn't fail the build.
54
+ def fail(url, locations, reason, warn: false)
55
+ add(warn ? @warnings : @failures, url, locations, reason)
53
56
  end
54
57
 
55
58
  # Records the final result of an external link from ruby-link-checker. Links blocked by bot protection may work,
@@ -59,8 +62,7 @@ module Jekyll
59
62
  count(:cached) if result.cached?
60
63
  return success(url, result) if result.success?
61
64
 
62
- log(url, result.blocked? ? "#{result.reason}, unverified" : result.reason)
63
- add(result.blocked? ? @unverified : @failures, url, result.options[:locations], result.reason)
65
+ dead(url, result, with_kind(result.reason, result.options[:kind]))
64
66
  end
65
67
 
66
68
  def log(url, status)
@@ -68,23 +70,40 @@ module Jekyll
68
70
  end
69
71
 
70
72
  def finish
73
+ compare
71
74
  Jekyll.logger.info('LinkChecker:', summary)
72
75
  write(@file) if @file
76
+ Baseline.write(@dead_links_file, @dead) if @dead_links_file
73
77
  warn_unverified_and_moved
74
- return if @failures.empty?
75
- return Jekyll.logger.warn('LinkChecker:', message) unless @fail_on_dead_links
78
+ fail_on_dead_links unless failing.empty?
79
+ end
80
+
81
+ private
82
+
83
+ def fail_on_dead_links
84
+ return Jekyll.logger.warn('LinkChecker:', message) if @fail_on == :none
76
85
 
77
86
  Jekyll.logger.error('LinkChecker:', message)
78
87
  raise DeadLinksError, message
79
88
  end
80
89
 
81
- private
90
+ def dead(url, result, reason)
91
+ log(url, result.blocked? ? "#{reason}, unverified" : reason)
92
+ return add(@unverified, url, result.options[:locations], reason) if result.blocked?
93
+
94
+ fail(url, result.options[:locations], reason, warn: result.options[:warn])
95
+ end
82
96
 
83
97
  def add(links, url, locations, reason)
84
98
  links[url] ||= { reason: reason, locations: Set.new }
85
99
  links[url][:locations].merge(Array(locations))
86
100
  end
87
101
 
102
+ # Says what kind of reference failed, unless it's a link, such as `image: HTTP 404`.
103
+ def with_kind(reason, kind)
104
+ kind.nil? || kind == 'link' ? reason : "#{kind}: #{reason}"
105
+ end
106
+
88
107
  def success(url, result)
89
108
  log(url, result.cached? ? 'OK (cached)' : 'OK')
90
109
  return unless @permanent_redirects && result.permanent_redirect?
@@ -92,8 +111,11 @@ module Jekyll
92
111
  add(@moved, url, result.options[:locations], result.result_uri.to_s)
93
112
  end
94
113
 
95
- # Unverified and moved links don't fail the build.
114
+ # Warnings, dead links without a baseline to compare them with, and unverified and moved links, don't fail the
115
+ # build.
96
116
  def warn_unverified_and_moved
117
+ Jekyll.logger.warn('LinkChecker:', warnings_message) unless @warnings.empty?
118
+ Jekyll.logger.warn('LinkChecker:', unclassified_message) unless @unclassified.empty?
97
119
  Jekyll.logger.warn('LinkChecker:', unverified_message) unless @unverified.empty?
98
120
  Jekyll.logger.warn('LinkChecker:', moved_message) unless @moved.empty?
99
121
  end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ # A small CSS selector that says which elements hold a kind of reference: a tag, such as `img`, words its attributes
6
+ # must contain, such as `link[rel~=stylesheet]`, and words that rule it out, such as `a:not([rel~=external])`.
7
+ class Selector
8
+ PATTERN = /\A([a-z][a-z0-9-]*)((?:\[[^\]]*\])*)(?::not\(([^)]*)\))?\z/i
9
+ CONDITION = /\A\[\s*([a-z][\w:-]*)\s*~=\s*(["']?)([^"'\]\s]+)\2\s*\]\z/i
10
+
11
+ attr_reader :text, :tag
12
+
13
+ # Raises an error naming `name` when `text` isn't a selector.
14
+ def self.parse(text, name)
15
+ text = text.to_s.strip
16
+ match = PATTERN.match(text)
17
+ Values.invalid!(name, text, 'a selector, such as img or link[rel~=stylesheet]') unless match
18
+
19
+ new(text, match[1].downcase, conditions(match[2].scan(/\[[^\]]*\]/), name, text),
20
+ conditions(match[3].to_s.split(','), name, text))
21
+ end
22
+
23
+ def self.conditions(list, name, text)
24
+ list.map(&:strip).reject(&:empty?).map do |condition|
25
+ match = CONDITION.match(condition)
26
+ Values.invalid!(name, text, 'a selector with conditions such as [rel~=stylesheet]') unless match
27
+
28
+ [match[1].downcase, match[3].downcase]
29
+ end
30
+ end
31
+
32
+ def initialize(text, tag, required, excluded)
33
+ @text = text
34
+ @tag = tag
35
+ @required = required
36
+ @excluded = excluded
37
+ end
38
+
39
+ # Whether an element with a lowercase `tag` and `attributes`, by lowercase name, matches.
40
+ def match?(tag, attributes)
41
+ tag == @tag && @required.all? { |condition| word?(attributes, *condition) } &&
42
+ @excluded.none? { |condition| word?(attributes, *condition) }
43
+ end
44
+
45
+ private
46
+
47
+ def word?(attributes, name, word)
48
+ attributes[name].to_s.downcase.split.include?(word)
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Jekyll
4
+ module RubyLinkChecker
5
+ # Splits what a page references by where it comes from: its content, reported from the page, and, with
6
+ # `layouts`, its layouts and includes, such as navigation, reported from the page's layout. Layouts repeat
7
+ # on every page, so a broken link in them is reported once, from the layout, rather than from every page.
8
+ class Sources
9
+ def initialize(site, references, layouts:)
10
+ @site = site
11
+ @references = references
12
+ @layouts = layouts
13
+ end
14
+
15
+ # Yields the location, the kind, and the URL of each reference of the page.
16
+ def each(page, &)
17
+ content = page.content.to_s
18
+ scan(content, page.relative_path, &)
19
+ layout = @layouts && @site.layouts[page.data['layout']]
20
+ each_in_layout(page.output.to_s, content, layout.relative_path.delete_prefix('/'), &) if layout
21
+ end
22
+
23
+ private
24
+
25
+ # The output usually contains the content as it is, so only what's around it is scanned again. A layout can
26
+ # change the content, for example with a filter, and then the references of the content are left out of the
27
+ # whole output once each.
28
+ def each_in_layout(output, content, location, &)
29
+ start = output.index(content)
30
+ return each_not_in(output, content, location, &) unless start
31
+
32
+ scan(output[0, start], location, &)
33
+ scan(output[(start + content.length)..], location, &)
34
+ end
35
+
36
+ def each_not_in(output, content, location)
37
+ remaining = @references.scan(content).tally
38
+ @references.scan(output).each do |reference|
39
+ next remaining[reference] -= 1 if remaining[reference].to_i.positive?
40
+
41
+ yield location, *reference
42
+ end
43
+ end
44
+
45
+ def scan(html, location)
46
+ @references.scan(html).each { |kind, href| yield location, kind, href }
47
+ end
48
+ end
49
+ end
50
+ end
@@ -38,25 +38,29 @@ module Jekyll
38
38
  match[1].empty? ? '/' : match[1]
39
39
  end
40
40
 
41
- # Links with other schemes, such as `mailto:`, and configured exclusions are not checked.
42
- def excluded?(url)
41
+ # Links with other schemes, such as `mailto:`, and configured exclusions, including those of a kind of
42
+ # reference, are not checked.
43
+ def excluded?(url, exclusions = [])
43
44
  return true if url.match?(SCHEME) && !self.class.external?(url)
44
- return true if excluded_url?(url)
45
- return true if @exclude.paths.any? { |pattern| pattern.match?(url) }
46
45
 
47
- self.class.external?(url) && excluded_domain?(url)
46
+ [@exclude, *exclusions].any? { |exclude| excluded_by?(url, exclude) }
48
47
  end
49
48
 
50
49
  private
51
50
 
51
+ def excluded_by?(url, exclude)
52
+ excluded_url?(url, exclude) || exclude.paths.any? { |pattern| pattern.match?(url) } ||
53
+ (self.class.external?(url) && excluded_domain?(url, exclude))
54
+ end
55
+
52
56
  # Excluded URLs are exact, or regular expressions.
53
- def excluded_url?(url)
54
- @exclude.urls.any? { |excluded| excluded.is_a?(Regexp) ? excluded.match?(url) : excluded == url }
57
+ def excluded_url?(url, exclude)
58
+ exclude.urls.any? { |excluded| excluded.is_a?(Regexp) ? excluded.match?(url) : excluded == url }
55
59
  end
56
60
 
57
- def excluded_domain?(url)
61
+ def excluded_domain?(url, exclude)
58
62
  host = URI.parse(url).host.to_s.downcase
59
- @exclude.domains.any? { |domain| host == domain || host.end_with?(".#{domain}") }
63
+ exclude.domains.any? { |domain| host == domain || host.end_with?(".#{domain}") }
60
64
  rescue URI::InvalidURIError
61
65
  false
62
66
  end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Jekyll
4
4
  module RubyLinkChecker
5
- VERSION = '0.1.0'
5
+ VERSION = '0.2.0'
6
6
  end
7
7
  end
@@ -6,9 +6,17 @@ require 'ruby-link-checker'
6
6
 
7
7
  require_relative 'jekyll-ruby-link-checker/version'
8
8
  require_relative 'jekyll-ruby-link-checker/values'
9
+ require_relative 'jekyll-ruby-link-checker/exclude'
10
+ require_relative 'jekyll-ruby-link-checker/environment'
9
11
  require_relative 'jekyll-ruby-link-checker/configuration'
10
12
  require_relative 'jekyll-ruby-link-checker/internal_links'
11
13
  require_relative 'jekyll-ruby-link-checker/urls'
14
+ require_relative 'jekyll-ruby-link-checker/selector'
15
+ require_relative 'jekyll-ruby-link-checker/kind'
16
+ require_relative 'jekyll-ruby-link-checker/check'
17
+ require_relative 'jekyll-ruby-link-checker/references'
18
+ require_relative 'jekyll-ruby-link-checker/sources'
19
+ require_relative 'jekyll-ruby-link-checker/baseline'
12
20
  require_relative 'jekyll-ruby-link-checker/report'
13
21
  require_relative 'jekyll-ruby-link-checker/changed_files'
14
22
  require_relative 'jekyll-ruby-link-checker/checker'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: jekyll-ruby-link-checker
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel Doubrovkine
@@ -69,15 +69,24 @@ files:
69
69
  - LICENSE.txt
70
70
  - README.md
71
71
  - lib/jekyll-ruby-link-checker.rb
72
+ - lib/jekyll-ruby-link-checker/baseline.rb
72
73
  - lib/jekyll-ruby-link-checker/changed_files.rb
74
+ - lib/jekyll-ruby-link-checker/check.rb
73
75
  - lib/jekyll-ruby-link-checker/checker.rb
74
76
  - lib/jekyll-ruby-link-checker/configuration.rb
77
+ - lib/jekyll-ruby-link-checker/environment.rb
78
+ - lib/jekyll-ruby-link-checker/exclude.rb
75
79
  - lib/jekyll-ruby-link-checker/hooks.rb
76
80
  - lib/jekyll-ruby-link-checker/internal_links.rb
81
+ - lib/jekyll-ruby-link-checker/kind.rb
82
+ - lib/jekyll-ruby-link-checker/references.rb
77
83
  - lib/jekyll-ruby-link-checker/report.rb
84
+ - lib/jekyll-ruby-link-checker/report/comparison.rb
78
85
  - lib/jekyll-ruby-link-checker/report/exclusions.rb
79
86
  - lib/jekyll-ruby-link-checker/report/formatting.rb
80
87
  - lib/jekyll-ruby-link-checker/report/markdown.rb
88
+ - lib/jekyll-ruby-link-checker/selector.rb
89
+ - lib/jekyll-ruby-link-checker/sources.rb
81
90
  - lib/jekyll-ruby-link-checker/urls.rb
82
91
  - lib/jekyll-ruby-link-checker/values.rb
83
92
  - lib/jekyll-ruby-link-checker/version.rb