judgelint 0.1.9 → 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.
@@ -1,78 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # Presets for the services and servers that answer System One questions.
5
- # Any key can be overridden in .judgelint.yml, and a provider not listed here
6
- # works by setting api_base (and model, path, protocol, auth as needed).
7
- #
8
- # protocol is "system_one" (POST {model, state, questions} keyed by name) or
9
- # "decisions" (OpenAI's Decisions API: input, questions as a list). The path
10
- # doesn't decide it: Perplexity and Hanzo take System One at /v1/decisions.
11
- #
12
- # auth is "bearer", "basic" (user "token", for Databricks), "none", or
13
- # "header:<name>" (Microsoft Foundry's api-key). A preset with no
14
- # api_key_env sends no credentials unless you set one.
15
- #
16
- # ${VAR} in api_base or path reads the environment; {model} in path is the
17
- # model id. batch_size is the provider's most questions per request.
18
- # prices are USD per million input tokens, by model (OpenRouter reports
19
- # each request's cost instead). needs says what a preset can't fill in.
20
- PROVIDERS = {
21
- "typesafe" => {
22
- "api_base" => "https://api.typesafe.ai", "api_key_env" => "TYPESAFE_API_KEY", "model" => "jev-latest",
23
- "prices" => { "jev-latest" => "0.042", "jev-preview" => "0.042" }
24
- },
25
- "openrouter" => {
26
- "api_base" => "https://openrouter.ai/api", "api_key_env" => "OPENROUTER_API_KEY", "model" => "typesafe/jev-1.13"
27
- },
28
- "celeris" => {
29
- "api_base" => "https://inference.celeris.ai/celeris-1-decision", "api_key_env" => "CELERIS_API_KEY",
30
- "model" => "celeris-1-decision", "prices" => { "celeris-1-decision" => "0.04" }
31
- },
32
- "cloudflare" => {
33
- "api_base" => "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/ai/run",
34
- "path" => "/@cf/cloudflare/{model}", "api_key_env" => "CLOUDFLARE_API_TOKEN", "model" => "clef",
35
- "batch_size" => "64", "prices" => { "clef" => "0.24" }
36
- },
37
- "openai" => {
38
- "api_base" => "https://api.openai.com", "path" => "/v1/decisions", "protocol" => "decisions",
39
- "api_key_env" => "OPENAI_API_KEY", "model" => "gpt-6-luna", "prices" => { "gpt-6-luna" => "0.10" }
40
- },
41
- "perplexity" => {
42
- "api_base" => "https://api.perplexity.ai", "path" => "/v1/decisions", "api_key_env" => "PERPLEXITY_API_KEY",
43
- "model" => "pplx-decider-latest", "batch_size" => "128",
44
- "prices" => { "pplx-decider-latest" => "0.02", "pplx-decider-flash-latest" => "0.01" }
45
- },
46
- "vercel" => {
47
- "api_base" => "https://ai-gateway.vercel.sh/typesafe", "api_key_env" => "AI_GATEWAY_API_KEY",
48
- "model" => "typesafe-ai/jev"
49
- },
50
- "digitalocean" => {
51
- "api_base" => "https://inference.do-ai.run", "api_key_env" => "MODEL_ACCESS_KEY", "model" => "typesafe-jev-1.13.0"
52
- },
53
- "upstage" => {
54
- "api_base" => "https://api.upstage.ai", "api_key_env" => "UPSTAGE_API_KEY", "model" => "solar-decide"
55
- },
56
- "hanzo" => {
57
- "api_base" => "https://api.hanzo.ai", "path" => "/v1/decisions", "api_key_env" => "HANZO_API_KEY",
58
- "model" => "kai", "batch_size" => "100", "prices" => { "kai" => "0.021" }
59
- },
60
- "foundry" => {
61
- "path" => "/providers/microsoft/v1/systemone", "auth" => "header:api-key", "api_key_env" => "AZURE_API_KEY",
62
- "needs" => "api_base (your Foundry resource endpoint) and model (your deployment name)"
63
- },
64
- "databricks" => {
65
- "path" => "/ai-gateway/typesafe/v1/systemone", "auth" => "basic", "api_key_env" => "DATABRICKS_TOKEN",
66
- "needs" => "api_base (https://<workspace host>) and model (a Unity Catalog name)"
67
- },
68
- "ollama" => {
69
- "api_base" => "http://localhost:11434", "batch_size" => "64", "needs" => "model (a decision model you've pulled)"
70
- },
71
- "llamacpp" => { "api_base" => "http://localhost:8080" },
72
- "vllm" => { "api_base" => "http://localhost:8000", "batch_size" => "64", "needs" => "model (the model the server runs)" },
73
- "litellm" => {
74
- "api_base" => "http://localhost:4000", "api_key_env" => "LITELLM_API_KEY",
75
- "needs" => "model (a decision model routed by your proxy)"
76
- }
77
- }.freeze
78
- end
@@ -1,148 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # One rule asked about one range of a file. The model sees the whole file;
5
- # the question points at the lines. When a change touched only some of a
6
- # window's lines, it points at those, so code the change didn't touch can't
7
- # fail it.
8
- #
9
- # A spec's bullet is a choice between breaking the rule, following it, and
10
- # the rule not applying. With the three side by side, a decision model
11
- # commits to an answer, where a yes/no question gets a hedge. The same
12
- # request asks which line (or, for a directory, which file) breaks the rule
13
- # most clearly, so a finding can name it.
14
- #
15
- # A rule written as a question is asked yes or no, as written. Code with a
16
- # judgehint comment is also asked, yes or no, whether the hint excuses it.
17
- class Question
18
- BREAKS = "The code clearly breaks the rule."
19
- FOLLOWS = "The code follows the rule."
20
- NOT_APPLICABLE = "The rule doesn't apply to this code."
21
- EXCUSED = "A judgehint comment is about this rule, and gives a reason the code may break it."
22
- NOT_EXCUSED = "No judgehint comment is about this rule. Any judgehint is about a different rule, or gives no reason."
23
-
24
- attr_reader :rule, :first, :last, :lines
25
-
26
- # +kind+ is :verdict, :where, or :excuse. +places+ are a :where question's
27
- # options as the model sees them: the directory's files, or nil for the
28
- # range's line ids (L12).
29
- # +lines+ are the changed lines in the range, or nil to ask about all of it.
30
- def initialize(rule, first, last, kind: :verdict, places: nil, lines: nil)
31
- @rule = rule
32
- @first = first
33
- @last = last
34
- @kind = kind
35
- @places = places
36
- @lines = lines
37
- end
38
-
39
- def places
40
- @places || (first..last).map { |line| "L#{line}" }
41
- end
42
-
43
- def excuse?
44
- @kind == :excuse
45
- end
46
-
47
- def where?
48
- @kind == :where
49
- end
50
-
51
- # A spec's bullet and its location are choices; everything else is yes or no.
52
- def choice?
53
- where? || (@kind == :verdict && !rule.convention.nil?)
54
- end
55
-
56
- def key
57
- base = "#{rule.question_key}.#{first}-#{last}"
58
- return "#{base}.excused" if excuse?
59
- return "#{base}.where" if where?
60
-
61
- base
62
- end
63
-
64
- # A choice's options, as {name => description or nil}.
65
- def options
66
- return places.to_h { |place| [place, nil] } if where?
67
-
68
- { "breaks" => rule.yes_means || BREAKS, "follows" => rule.no_means || FOLLOWS, "not_applicable" => NOT_APPLICABLE }
69
- end
70
-
71
- # The probability the code breaks the rule, from a verdict's answer: a
72
- # choice's probabilities, or a yes/no question's probability of yes.
73
- def violation(answer)
74
- return answer["breaks"].to_f if answer.is_a?(Hash)
75
-
76
- rule.violation_probability(answer)
77
- end
78
-
79
- # "Answer yes only when..." keeps the model from flagging code the rule
80
- # doesn't cover.
81
- def instructions
82
- return excuse_instructions if excuse?
83
- return where_instructions if where?
84
- return "How #{rule.scope == 'file' || lines&.size == 1 ? 'does' : 'do'} #{subject} relate to the following team rule? Rule: #{rule.convention}" if rule.convention
85
-
86
- text = rule.window? ? "Look at #{span} of the file; the rest is context. #{rule.question}" : rule.question
87
- return text unless rule.fail_when == "yes"
88
-
89
- scope = { "window" => "those lines do it", "file" => "the code does it", "directory" => "the files do it" }
90
- .fetch(rule.scope)
91
- "#{text} Answer yes only when #{scope}, not when the question doesn't apply."
92
- end
93
-
94
- def yes_means
95
- return EXCUSED if excuse?
96
- return nil if choice?
97
-
98
- rule.yes_means
99
- end
100
-
101
- def no_means
102
- return NOT_EXCUSED if excuse?
103
- return nil if choice?
104
-
105
- rule.no_means
106
- end
107
-
108
- def digest
109
- @digest ||= Digest::SHA256.hexdigest(JSON.generate([instructions, yes_means.to_s, no_means.to_s,
110
- choice? ? options.to_a : []]))
111
- end
112
-
113
- private
114
-
115
- def subject
116
- { "window" => "#{span} of the file", "file" => "the file", "directory" => "the files" }.fetch(rule.scope)
117
- end
118
-
119
- # The lines asked about: "lines 41-80", or the changed ones, as "line 7" or
120
- # "lines 3, 7-9".
121
- def span
122
- return "lines #{first}-#{last}" if lines.nil?
123
- return "line #{lines.first}" if lines.size == 1
124
-
125
- runs = []
126
- lines.each do |line|
127
- if !runs.empty? && runs.last[1] == line - 1
128
- runs.last[1] = line
129
- else
130
- runs << [line, line]
131
- end
132
- end
133
- "lines #{runs.map { |run| run[0] == run[1] ? run[0].to_s : "#{run[0]}-#{run[1]}" }.join(', ')}"
134
- end
135
-
136
- def where_instructions
137
- which = rule.directory? ? "Which file" : "Which line, given by its number as L<number>,"
138
- "#{which} most clearly breaks the following team rule? Rule: #{rule.convention}"
139
- end
140
-
141
- def excuse_instructions
142
- where = { "window" => "in lines #{first}-#{last} of the file", "file" => "in the file", "directory" => "in the files" }
143
- .fetch(rule.scope)
144
- "Does a judgehint comment #{where} explain why the code intentionally departs from the following team " \
145
- "rule, with a reason specific to this rule? Rule: #{rule.convention || rule.message}"
146
- end
147
- end
148
- end
@@ -1,188 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # Prints results as text, JSON, GitHub Actions annotations, or SARIF. Data
5
- # goes to stdout; anything else goes to stderr.
6
- class Reporter
7
- FORMATS = %w[text json github sarif].freeze
8
- MARKS = { violation: "x", uncertain: "?", skipped: "-", refused: "-", excused: "-" }.freeze
9
- # In color, a violation's mark is a cross.
10
- COLOR_MARKS = { violation: "\u2717", uncertain: "?", skipped: "-", refused: "-", excused: "-" }.freeze
11
- STATUSES = %w[violation uncertain pass skipped refused excused].freeze
12
-
13
- # +paint+ colors the text format; the others are never colored.
14
- def initialize(out, format:, paint: Paint.new(false))
15
- @out = out
16
- @format = format
17
- @paint = paint
18
- end
19
-
20
- def check(verdicts, config:, file_count:, usage:)
21
- case @format
22
- when "json" then json(check_json(verdicts, config, file_count, usage))
23
- when "github" then verdicts.each { |verdict| annotate(verdict) }
24
- when "sarif" then json(sarif(verdicts))
25
- else text(verdicts, file_count)
26
- end
27
- end
28
-
29
- def fixtures(examples, usage:)
30
- return json(fixtures_json(examples, usage)) if @format == "json"
31
-
32
- examples.group_by(&:rule).each do |rule, group|
33
- correct = group.count(&:correct?)
34
- tally = @paint.call("#{correct}/#{group.size}", correct == group.size ? Paint::GREEN : Paint::RED)
35
- @out.puts "#{@paint.call(rule.id, Paint::BOLD)} #{tally}"
36
- group.each do |example|
37
- mark = example.correct? ? cell("ok", 4, Paint::GREEN) : @paint.call("MISS", Paint::BOLD_RED)
38
- @out.puts " #{mark} #{cell(example.expected.to_s, 4, Paint::DIM)} " \
39
- "#{probability(example)} #{@paint.call(example.path, Paint::CYAN)}"
40
- end
41
- end
42
- @out.puts "" unless examples.empty?
43
- correct = examples.count(&:correct?)
44
- @out.puts @paint.call("#{correct}/#{examples.size} examples judged correctly",
45
- correct == examples.size ? Paint::BOLD_GREEN : Paint::BOLD_RED)
46
- end
47
-
48
- private
49
-
50
- def json(data)
51
- @out.puts JSON.pretty_generate(data)
52
- end
53
-
54
- def text(verdicts, file_count)
55
- shown = verdicts.reject { |verdict| verdict.status == :pass }
56
- width = shown.map { |verdict| verdict.rule.id.size }.max
57
- places = [7, *shown.map { |verdict| range(verdict).size }].max
58
- shown.group_by(&:path).each do |path, group|
59
- @out.puts @paint.call(path, Paint::BOLD)
60
- group.each { |verdict| @out.puts " #{line(verdict, width, places)}" }
61
- end
62
- @out.puts "" unless shown.empty?
63
- @out.puts summary(verdicts, file_count)
64
- end
65
-
66
- # Columns are padded before they're colored, so they line up either way.
67
- def line(verdict, width, places)
68
- label = verdict.status == :violation ? verdict.rule.severity : verdict.status.to_s
69
- marks = @paint.on? ? COLOR_MARKS : MARKS
70
- tone = tone(verdict)
71
- [cell("#{marks.fetch(verdict.status)} #{label}", 12, tone), cell(verdict.rule.id, width, Paint::DIM),
72
- " #{cell(range(verdict), places, Paint::CYAN)}", "#{@paint.call(probability(verdict), tone)} ",
73
- verdict.rule.message].join(" ")
74
- end
75
-
76
- # +text+ in color, padded to +width+ outside it.
77
- def cell(text, width, code)
78
- "#{@paint.call(text, code)}#{' ' * [width - text.size, 0].max}"
79
- end
80
-
81
- # Errors are red, warnings and uncertain findings yellow, the rest dim.
82
- def tone(verdict)
83
- return Paint::YELLOW if verdict.status == :uncertain
84
- return Paint::DIM unless verdict.status == :violation
85
-
86
- verdict.rule.error? ? Paint::BOLD_RED : Paint::YELLOW
87
- end
88
-
89
- # The line that breaks the rule, or the range asked about; for a
90
- # directory, the file in it.
91
- def range(verdict)
92
- return verdict.file.delete_prefix("#{verdict.path}/") if verdict.file
93
- return verdict.line.to_s if verdict.line
94
-
95
- verdict.lines ? verdict.lines.join("-") : ""
96
- end
97
-
98
- def probability(verdict)
99
- return " - " if verdict.probability.nil?
100
-
101
- format("%.2f", verdict.probability)
102
- end
103
-
104
- def summary(verdicts, file_count)
105
- counts = verdicts.group_by(&:status).transform_values(&:size)
106
- violations = counts.fetch(:violation, 0)
107
- parts = ["#{file_count} #{file_count == 1 ? 'file' : 'files'}",
108
- @paint.call("#{violations} violations", violations.zero? ? Paint::BOLD_GREEN : Paint::BOLD_RED)]
109
- parts << @paint.call("#{counts[:uncertain]} uncertain", Paint::YELLOW) if counts[:uncertain]
110
- parts << @paint.call("#{counts[:skipped]} skipped (too large)", Paint::DIM) if counts[:skipped]
111
- parts << @paint.call("#{counts[:refused]} refused by the model", Paint::DIM) if counts[:refused]
112
- parts << @paint.call("#{counts[:excused]} excused by judgehints", Paint::DIM) if counts[:excused]
113
- parts.join(", ")
114
- end
115
-
116
- def check_json(verdicts, config, file_count, usage)
117
- counts = verdicts.group_by(&:status).transform_values(&:size)
118
- {
119
- "version" => VERSION,
120
- "models" => config.models.map(&:label),
121
- "files" => file_count,
122
- "summary" => STATUSES.to_h { |status| [status, counts.fetch(status.to_sym, 0)] },
123
- "usage" => usage.to_h,
124
- "results" => verdicts.map(&:to_h)
125
- }
126
- end
127
-
128
- def fixtures_json(examples, usage)
129
- {
130
- "version" => VERSION,
131
- "correct" => examples.count(&:correct?),
132
- "total" => examples.size,
133
- "usage" => usage.to_h,
134
- "examples" => examples.map(&:to_h)
135
- }
136
- end
137
-
138
- # GitHub Actions workflow commands, which show up on the pull request's lines.
139
- def annotate(verdict)
140
- level = { violation: verdict.rule.error? ? "error" : "warning", uncertain: "notice" }[verdict.status]
141
- return unless level
142
-
143
- properties = ["file=#{escape(verdict.file || verdict.path, true)}"]
144
- if verdict.line
145
- properties << "line=#{verdict.line}"
146
- elsif verdict.lines
147
- properties += ["line=#{verdict.lines[0]}", "endLine=#{verdict.lines[1]}"]
148
- end
149
- properties << "title=#{escape("judgelint #{verdict.rule.id}", true)}"
150
- @out.puts "::#{level} #{properties.join(',')}::#{escape("#{verdict.rule.message} (#{probability(verdict)})", false)}"
151
- end
152
-
153
- def escape(text, property)
154
- escaped = text.gsub("%", "%25").gsub("\r", "%0D").gsub("\n", "%0A")
155
- property ? escaped.gsub(":", "%3A").gsub(",", "%2C") : escaped
156
- end
157
-
158
- def sarif(verdicts)
159
- shown = verdicts.select { |verdict| %i[violation uncertain].include?(verdict.status) }
160
- rules = shown.map(&:rule).uniq
161
- {
162
- "$schema" => "https://json.schemastore.org/sarif-2.1.0.json",
163
- "version" => "2.1.0",
164
- "runs" => [{
165
- "tool" => { "driver" => {
166
- "name" => "judgelint", "version" => VERSION, "informationUri" => "https://github.com/jpcamara/judgelint",
167
- "rules" => rules.map { |rule| { "id" => rule.id, "shortDescription" => { "text" => rule.message } } }
168
- } },
169
- "results" => shown.map { |verdict| sarif_result(verdict) }
170
- }]
171
- }
172
- end
173
-
174
- def sarif_result(verdict)
175
- region =
176
- if verdict.line then { "startLine" => verdict.line }
177
- elsif verdict.lines then { "startLine" => verdict.lines[0], "endLine" => verdict.lines[1] }
178
- else {}
179
- end
180
- level = verdict.status == :uncertain ? "note" : (verdict.rule.error? ? "error" : "warning")
181
- {
182
- "ruleId" => verdict.rule.id, "level" => level,
183
- "message" => { "text" => "#{verdict.rule.message} (#{probability(verdict)})" },
184
- "locations" => [{ "physicalLocation" => { "artifactLocation" => { "uri" => verdict.file || verdict.path }, "region" => region } }]
185
- }
186
- end
187
- end
188
- end
@@ -1,167 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Judgelint
4
- # One convention, asked of a file as a single yes/no question. Rules are
5
- # markdown files with YAML frontmatter:
6
- #
7
- # ---
8
- # question: Does this code rescue an exception and carry on as if nothing happened?
9
- # yes_means: The rescue neither logs, re-raises, nor returns an explicit failure.
10
- # no_means: Every rescue logs, re-raises, or turns the error into a result.
11
- # paths: ["app/**/*.rb", "lib/**/*.rb"]
12
- # ---
13
- # Swallowed exceptions hide bugs until they cost us data.
14
- #
15
- # The body is the rationale people read. The model sees only the question
16
- # and the meanings of yes and no. +fail_when+ is the answer that means the
17
- # file breaks the convention, so a rule can ask "Does this rescue and discard
18
- # an exception?" (fail on yes) or "Does this service validate its input
19
- # first?" (fail on no).
20
- #
21
- # +scope+ "window" asks about each range of lines, so a finding says where
22
- # it is; "file" asks once about the whole file, for conventions no range can
23
- # show on its own; "directory" asks once about each directory its paths
24
- # match, with all of the directory's files, for conventions about how files
25
- # relate. A fail_when: no rule is about the whole file by default.
26
- #
27
- # +context+ globs name files the model reads alongside, such as shared
28
- # types, which are never judged themselves.
29
- class Rule
30
- FRONTMATTER = /\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\z)(.*)\z/m
31
- KEYS = %w[id question convention yes_means no_means fail_when scope paths excludes context severity threshold message].freeze
32
-
33
- attr_reader :id, :question, :convention, :yes_means, :no_means, :fail_when, :scope, :paths, :excludes,
34
- :context, :severity, :threshold, :message, :source, :examples_dir, :prose, :inline_examples
35
-
36
- # The rules in +dir+ alone (Spec.discover also finds READMEs).
37
- def self.load_dir(dir, default_threshold:)
38
- Spec.discover(rules_dir: dir, default_threshold: default_threshold, readmes: false)
39
- end
40
-
41
- # A rule is a question asked exactly as written, or a convention (a
42
- # spec's bullet) asked whether the code breaks it.
43
- # +prose+ is a spec's body, which the model reads alongside the file.
44
- # +inline_examples+ are the Bad and Good code blocks under a spec's bullet.
45
- def initialize(data, source:, body: "", default_threshold: 0.7, examples_dir: nil, prose: nil, inline_examples: [])
46
- unknown = data.keys - KEYS
47
- raise ConfigError, "#{source}: unknown keys #{unknown.join(', ')}" unless unknown.empty?
48
-
49
- @source = source
50
- @id = (data["id"] || File.basename(source, ".md")).to_s
51
- @question = text(data["question"])
52
- @convention = text(data["convention"])
53
- raise ConfigError, "#{source}: a rule needs a question" if @question.nil? && @convention.nil?
54
-
55
- @examples_dir = examples_dir || source.delete_suffix(".md")
56
- @prose = prose
57
- @inline_examples = inline_examples
58
- @yes_means = text(data["yes_means"])
59
- @no_means = text(data["no_means"])
60
- @fail_when = one_of("fail_when", yes_or_no(data.fetch("fail_when", "yes")), %w[yes no])
61
- @scope = one_of("scope", data.fetch("scope", @fail_when == "yes" ? "window" : "file"), %w[window file directory])
62
- @severity = one_of("severity", data.fetch("severity", "error"), %w[error warning])
63
- @paths = list(data["paths"], ["**/*"])
64
- @excludes = list(data["excludes"], [])
65
- @context = list(data["context"], [])
66
- @threshold = parse_threshold(data.key?("threshold") ? data["threshold"] : default_threshold)
67
- @message = (data["message"] || first_paragraph(body) || @question || @convention).to_s.strip
68
- end
69
-
70
- def applies_to?(path)
71
- Glob.match_any?(paths, path) && !Glob.match_any?(excludes, path)
72
- end
73
-
74
- def question_key
75
- id.gsub(/[^A-Za-z0-9_]/, "_")
76
- end
77
-
78
- def window?
79
- scope == "window"
80
- end
81
-
82
- def directory?
83
- scope == "directory"
84
- end
85
-
86
- def context_files
87
- Glob.expand(context)
88
- end
89
-
90
- # The directories a directory rule governs.
91
- def directories
92
- paths.flat_map { |pattern| Glob.glob(pattern) }.select { |path| File.directory?(path) && applies_to?(path) }.uniq.sort
93
- end
94
-
95
- # The ranges to ask about: windows of +size+ lines, or the whole file.
96
- def ranges(source, size)
97
- window? ? source.windows(size) : [[1, source.line_count]].reject { |_first, last| last.zero? }
98
- end
99
-
100
- def violation_probability(yes_probability)
101
- fail_when == "yes" ? yes_probability : 1.0 - yes_probability
102
- end
103
-
104
- def error?
105
- severity == "error"
106
- end
107
-
108
- private
109
-
110
- # YAML reads a bare yes/no as true/false.
111
- def yes_or_no(value)
112
- return "yes" if value == true
113
- return "no" if value == false
114
-
115
- value
116
- end
117
-
118
- def one_of(key, value, allowed)
119
- value = value.to_s
120
- raise ConfigError, "#{source}: #{key} is #{allowed.join(' or ')}, not #{value}" unless allowed.include?(value)
121
-
122
- value
123
- end
124
-
125
- def parse_threshold(value)
126
- number = Judgelint.number(value)
127
- raise ConfigError, "#{source}: threshold must be a number, not #{value}" if number.nil?
128
- raise ConfigError, "#{source}: threshold must be between 0 and 1" unless number.positive? && number <= 1
129
-
130
- number
131
- end
132
-
133
- def list(value, default)
134
- return default if value.nil?
135
-
136
- value.is_a?(Array) ? value.map(&:to_s) : [value.to_s]
137
- end
138
-
139
- def text(value)
140
- string = value.to_s.strip
141
- string.empty? ? nil : string
142
- end
143
-
144
- def first_paragraph(body)
145
- paragraph = body.split(/\n\s*\n/).map(&:strip).find { |part| !part.empty? && !part.start_with?("#") }
146
- paragraph&.gsub(/\s*\n\s*/, " ")
147
- end
148
- end
149
-
150
- # A Bad or Good code block under a spec's bullet. `judgelint test` judges it
151
- # like a file in the rule's fail/ or pass/ examples.
152
- class InlineExample
153
- attr_reader :expected, :code, :line, :language
154
-
155
- def initialize(label, code, line, language)
156
- @expected = label == "bad" ? :fail : :pass
157
- @code = code
158
- @line = line
159
- @language = language
160
- end
161
-
162
- # The file name the model sees.
163
- def name
164
- language.empty? ? "example" : "example.#{language}"
165
- end
166
- end
167
- end