/
configuration.rb
331 lines (268 loc) · 12.5 KB
/
configuration.rb
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
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# frozen_string_literal: true
require "optparse"
module HTMLProofer
class Configuration
DEFAULT_TESTS = ["Links", "Images", "Scripts"].freeze
PROOFER_DEFAULTS = {
allow_hash_href: true,
allow_missing_href: false,
assume_extension: ".html",
check_external_hash: true,
check_internal_hash: true,
checks: DEFAULT_TESTS,
directory_index_file: "index.html",
disable_external: false,
ignore_empty_alt: true,
ignore_empty_mailto: false,
ignore_files: [],
ignore_missing_alt: false,
ignore_status_codes: [],
ignore_urls: [],
enforce_https: true,
extensions: [".html"],
log_level: :info,
only_4xx: false,
swap_attributes: {},
swap_urls: {},
}.freeze
TYPHOEUS_DEFAULTS = {
followlocation: true,
headers: {
"User-Agent" => "Mozilla/5.0 (compatible; HTML Proofer/#{HTMLProofer::VERSION}; +https://github.com/gjtorikian/html-proofer)",
"Accept" => "application/xml,application/xhtml+xml,text/html;q=0.9, text/plain;q=0.8,image/png,*/*;q=0.5",
},
connecttimeout: 10,
timeout: 30,
}.freeze
HYDRA_DEFAULTS = {
max_concurrency: 50,
}.freeze
CACHE_DEFAULTS = {}.freeze
class << self
def generate_defaults(opts)
options = PROOFER_DEFAULTS.merge(opts)
options[:typhoeus] = HTMLProofer::Configuration::TYPHOEUS_DEFAULTS.merge(opts[:typhoeus] || {})
options[:hydra] = HTMLProofer::Configuration::HYDRA_DEFAULTS.merge(opts[:hydra] || {})
options[:cache] = HTMLProofer::Configuration::CACHE_DEFAULTS.merge(opts[:cache] || {})
options.delete(:src)
options
end
end
def initialize
@options = {}
end
def parse_cli_options(args)
define_options.parse!(args)
input = ARGV.empty? ? "." : ARGV.join(",")
[@options, input]
end
private def define_options
OptionParser.new do |opts|
opts.banner = "Usage: htmlproofer [options] PATH/LINK"
section(opts, "Input Options") do
set_option(opts, "--as-links") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--assume-extension EXT") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--directory-index-file FILENAME") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--extensions [EXT1,EXT2,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = list.nil? ? [] : list.split(",")
end
end
section(opts, "Check Configuration") do
set_option(opts, "--[no-]allow-hash-href") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]allow-missing-href") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--checks [CHECK1,CHECK2,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = list.nil? ? [] : list.split(",")
end
set_option(opts, "--[no-]check-external-hash") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]check-internal-hash") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]check-sri") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]disable-external") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]enforce-https") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--root-dir <DIR>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
end
section(opts, "Ignore Configuration") do
set_option(opts, "--ignore-files [FILE1,FILE2,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = if list.nil?
[]
else
list.split(",").map.each do |l|
if l.start_with?("/") && l.end_with?("/")
Regexp.new(l[1...-1])
else
l
end
end
end
end
set_option(opts, "--[no-]ignore-empty-alt") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]ignore-empty-mailto") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--[no-]ignore-missing-alt") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
set_option(opts, "--ignore-status-codes [500,401,420,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = list.nil? ? [] : list.split(",").map(&:to_i)
end
set_option(opts, "--ignore-urls [URL1, URL2,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = if list.nil?
[]
else
list.split(",").each_with_object([]) do |url, arr|
arr << to_regex?(url)
end
end
end
set_option(opts, "--only-status-codes [404,451,...]") do |long_opt_symbol, list|
@options[long_opt_symbol] = list.nil? ? [] : list.split(",")
end
set_option(opts, "--only-4xx") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg
end
end
section(opts, "Transforms Configuration") do
set_option(opts, "--swap-attributes <CONFIG>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = parse_json_option("swap_attributes", arg, symbolize_names: false)
end
set_option(opts, "--swap-urls [re:string,re:string,...]") do |long_opt_symbol, arg|
@options[long_opt_symbol] = str_to_regexp_map(arg)
end
end
section(opts, "Dependencies Configuration") do
set_option(opts, "--typhoeus <CONFIG>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = parse_json_option("typhoeus", arg, symbolize_names: false)
end
set_option(opts, "--hydra <CONFIG>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = parse_json_option("hydra", arg, symbolize_names: true)
end
set_option(opts, "--cache <CONFIG>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = parse_json_option("cache", arg, symbolize_names: true)
end
end
section(opts, "Reporting Configuration") do
set_option(opts, "--log-level <LEVEL>") do |long_opt_symbol, arg|
@options[long_opt_symbol] = arg.to_sym
end
end
section(opts, "General Configuration") do
set_option(opts, "--version") do
puts HTMLProofer::VERSION
exit(0)
end
end
end
end
private def to_regex?(item)
if item.start_with?("/") && item.end_with?("/")
Regexp.new(item[1...-1])
else
item
end
end
private def str_to_regexp_map(arg)
arg.split(",").each_with_object({}) do |s, hsh|
split = s.split(/(?<!\\):/, 2)
re = split[0].gsub(/\\:/, ":")
string = split[1].gsub(/\\:/, ":")
hsh[Regexp.new(re)] = string
end
end
private def section(opts, heading, &_block)
opts.separator("\n#{heading}:\n")
yield
end
private def set_option(opts, long_arg, &block)
long_opt_symbol = parse_long_opt(long_arg)
args = []
args += Array(ConfigurationHelp::TEXT[long_opt_symbol])
opts.on(long_arg, *args) do |arg|
yield long_opt_symbol, arg
end
end
# Converts the option into a symbol,
# e.g. '--allow-hash-href' => :allow_hash_href.
private def parse_long_opt(long_opt)
long_opt[2..].sub("[no-]", "").sub(/ .*/, "").tr("-", "_").gsub(/[\[\]]/, "").to_sym
end
def parse_json_option(option_name, config, symbolize_names: true)
raise ArgumentError, "Must provide an option name in string format." unless option_name.is_a?(String)
raise ArgumentError, "Must provide an option name in string format." if option_name.strip.empty?
return {} if config.nil?
raise ArgumentError, "Must provide a JSON configuration in string format." unless config.is_a?(String)
return {} if config.strip.empty?
begin
JSON.parse(config, { symbolize_names: symbolize_names })
rescue StandardError
raise ArgumentError, "Option '#{option_name} did not contain valid JSON."
end
end
module ConfigurationHelp
TEXT = {
as_links: ["Assumes that `PATH` is a comma-separated array of links to check."],
assume_extension: ["Automatically add specified extension to files for internal links, ",
"to allow extensionless URLs (as supported by most servers) (default: `.html`).",],
directory_index_file: ["Sets the file to look for when a link refers to a directory. (default: `index.html`)."],
extensions: ["A comma-separated list of Strings indicating the file extensions you",
"would like to check (default: `.html`)",],
allow_hash_href: ['"If `true`, assumes `href="#"` anchors are valid (default: `true`)"'],
allow_missing_href: ["If `true`, does not flag `a` tags missing `href`. In HTML5, this is technically ",
"allowed, but could also be human error. (default: `false`)",],
checks: ["A comma-separated list of Strings indicating which checks you",
"want to run (default: `[\"Links\", \"Images\", \"Scripts\"]",],
check_external_hash: ["Checks whether external hashes exist (even if the webpage exists) (default: `true`)."],
check_internal_hash: ["Checks whether internal hashes exist (even if the webpage exists) (default: `true`)."],
check_sri: ["Check that `<link>` and `<script>` external resources use SRI (default: `false`)."],
disable_external: ["If `true`, does not run the external link checker (default: `false`)."],
enforce_https: ["Fails a link if it's not marked as `https` (default: `true`)."],
root_dir: ["The absolute path to the directory serving your html-files."],
ignore_empty_alt: ["If `true`, ignores images with empty/missing ",
"alt tags (in other words, `<img alt>` and `<img alt=\"\">`",
"are valid; set this to `false` to flag those) (default: `true`).",],
ignore_empty_mailto: ["If `true`, allows `mailto:` `href`s which don't",
"contain an email address (default: `false`)'.",],
ignore_missing_alt: ["If `true`, ignores images with missing alt tags (default: `false`)."],
ignore_status_codes: ["A comma-separated list of numbers representing status codes to ignore."],
ignore_files: ["A comma-separated list of Strings or RegExps containing file paths that are safe to ignore"],
ignore_urls: ["A comma-separated list of Strings or RegExps containing URLs that are",
"safe to ignore. This affects all HTML attributes, such as `alt` tags on images.",],
only_status_codes: ["A comma-separated list of numbers representing the only status codes to report on."],
only_4xx: ["Only reports errors for links that fall within the 4xx status code range."],
swap_attributes: ["JSON-formatted config that maps element names to the",
"preferred attribute to check (default: `{}`).",],
swap_urls: ["A comma-separated list containing key-value pairs of `RegExp => String`.",
"It transforms URLs that match `RegExp` into `String` via `gsub`.",
"The escape sequences `\\:` should be used to produce literal `:`s.",],
typhoeus: ["JSON-formatted string of Typhoeus config; if set, overrides the html-proofer defaults."],
hydra: ["JSON-formatted string of Hydra config; if set, overrides the html-proofer defaults."],
cache: ["JSON-formatted string of cache config; if set, overrides the html-proofer defaults."],
log_level: ["Sets the logging level. One of `:debug`, `:info`, ",
"`:warn`, `:error`, or `:fatal`. (default: `:info`)",],
version: ["Prints the version of html-proofer."],
}.freeze
end
end
end