From 2cd85261f195873643da32692dde6e3d815d5015 Mon Sep 17 00:00:00 2001 From: "Daniel (dB.) Doubrovkine" Date: Tue, 20 Oct 2026 11:21:40 -0400 Subject: [PATCH] Support global defaults and per-check overrides for all TOC options Derive plugin accessors and keyword validation from the same option definitions. Snapshot effective configuration for parsing, anchor generation, and reports without mutating defaults. Document each option and check every requested file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- AGENTS.md | 4 +- CHANGELOG.md | 1 + README.md | 110 +++++++++++---- lib/toc/config.rb | 131 ++++++++---------- lib/toc/constructors.rb | 4 - lib/toc/constructors/kramdown_constructor.rb | 2 +- lib/toc/extractor.rb | 3 +- lib/toc/markdown_file.rb | 18 +-- lib/toc/plugin.rb | 62 +++++---- spec/config_spec.rb | 96 +++++-------- spec/danger/toc/markdown_file_options_spec.rb | 27 ++-- spec/toc_spec.rb | 53 ++++--- 12 files changed, 271 insertions(+), 240 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e8dabe8..7a6070a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ Danger plugin for checking Markdown tables of contents. Requires Ruby 3.1 or new ## Structure -* `lib/toc/config.rb`: shared configuration, reset between tests. +* `lib/toc/config.rb`: declared options, validated global defaults, and immutable per-check snapshots. * `lib/toc/markdown_file.rb`: Markdown parsing, TOC extraction, normalization, and comparison. * `lib/toc/constructors/`: heading extraction and GitHub or Kramdown anchor generation. * `lib/toc/extractor.rb`: locates the existing TOC. @@ -17,7 +17,7 @@ Install dependencies with `bundle install` when needed. Run `bundle exec rake sp CI covers Ruby 3.1 through 4.0 with compatible ActiveSupport versions. Set `ACTIVESUPPORT_VERSION` when resolving a particular compatibility bundle. Load `logger` after Bundler setup and before Danger when using older ActiveSupport versions; loading it before Bundler can activate an incompatible default-gem version. -Preserve existing TOC output unless a behavior change is explicitly requested. Keep input parsing separate from anchor generation. Add focused regression tests and reset shared configuration after examples that change it. +Preserve existing TOC output unless a behavior change is explicitly requested. Keep input parsing separate from anchor generation. Declare every option in Config::DEFAULTS and validate it in Config; global plugin accessors and per-check keywords must support the same options. Pass immutable snapshots through parsing and reporting; never read global defaults during a check. Add focused regression tests and reset global defaults after examples that change them. Update README.md for public behavior and keep its TOC in sync. Add changelog entries under the next release with the PR number and contributor attribution; retain the contribution placeholder. Keep Markdown paragraphs on one line. diff --git a/CHANGELOG.md b/CHANGELOG.md index 23bb8a6..cedd6b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ### 0.3.0 (Next) +* [#21](https://github.com/dblock/danger-toc/pull/21): Support every global TOC setting as a per-check keyword override without changing defaults; snapshot configuration and report every failing file - [@dblock](https://github.com/dblock). * [#20](https://github.com/dblock/danger-toc/pull/20): Configure bullets, indentation, maximum heading depth, and input parsers; exclude document titles from missing TOCs and support opt-in diff reports - [@dblock](https://github.com/dblock). * [#19](https://github.com/dblock/danger-toc/pull/19): Require Ruby 3.1, test through Ruby 4.0, declare the GFM parser dependency, and update pinned Danger workflows and contributor and release instructions - [@dblock](https://github.com/dblock). * [#18](https://github.com/dblock/danger-toc/pull/18): Migrate to danger-pr-comment workflow - [@dblock](https://github.com/dblock). diff --git a/README.md b/README.md index d6c4055..73a950f 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,17 @@ A plugin for [danger.systems](https://danger.systems) that makes sure your proje - [Installation](#installation) - [Usage](#usage) - - [toc.files](#tocfiles) - - [toc.header](#tocheader) - [toc.check!](#toccheck) - - [TOC Options](#toc-options) - - [Diff Reports](#diff-reports) + - [Options](#options) + - [files](#files) + - [header](#header) + - [parser](#parser) + - [format](#format) + - [bullet](#bullet) + - [indent](#indent) + - [max_depth](#max_depth) + - [report](#report) + - [Global Defaults](#global-defaults) - [Contributing](#contributing) - [Copyright](#copyright) @@ -31,52 +37,106 @@ Add `toc.check!` to your Dangerfile. Make a pull request and see this plugin in ## Usage -Methods and settings from this plugin are available in your `Dangerfile` under the `toc` namespace. +Methods from this plugin are available in your `Dangerfile` under the `toc` namespace. Every option can be set globally or passed to a check. Per-check options override global defaults without changing them. -### toc.files +### toc.check! -List of files to ensure TOC in, default is `README.md`. +Check README.md with default options, or pass options for a particular set of files: ```ruby -toc.files = ['README.md', 'DEV.md'] +toc.check! +toc.check!(files: ['README.md', 'DEV.md'], header: 'Contents') ``` -### toc.header +The method returns whether all checked TOCs are correct and reports every failing file. Use `toc.toc_changes?(files: ['README.md'])` to detect modified or added files before running a check. -The Table of Contents header, without `#`, default is `Table of Contents`. +### Options ```ruby -toc.header = 'Custom Table of Contents' +toc.check!(files: ['README.md'], max_depth: 3) +toc.check!(files: ['docs/guide.md'], parser: 'Kramdown', format: :kramdown, bullet: '*', indent: 4) ``` -### toc.check! +#### files + +File paths to check. Default: `['README.md']`. -Run all checks. +```ruby +toc.check!(files: ['README.md', 'DEV.md']) +``` + +#### header -### TOC Options +TOC heading text, without `#`. Default: `'Table of Contents'`. ```ruby -toc.bullet = '*' # '-', '*', or '+'; default '-' -toc.indent = 4 # spaces per nesting level; default 2 -toc.max_depth = 3 # absolute Markdown heading level (1–6); default nil (all) -toc.parser = 'Kramdown' # Kramdown input parser; default 'GFM' -toc.format = :kramdown # anchor format; default :github -toc.check! +toc.check!(header: 'Contents') +``` + +When a TOC is missing, a leading `# Title` is excluded if every subsequent heading is nested below it. A lone heading or multiple top-level sections are retained. When a TOC exists, headings before it are excluded. + +#### parser + +Kramdown input parser name. Default: `'GFM'`. GFM and Kramdown input are available out of the box; install and require additional Kramdown parsers before selecting them. + +```ruby +toc.check!(parser: 'Kramdown') +``` + +#### format + +Anchor ID format: `:github` (default) or `:kramdown`. This is independent of the input parser. + +```ruby +toc.check!(parser: 'Kramdown', format: :kramdown) ``` -Parser selection controls how Markdown is read; `format` controls generated anchor IDs. Install and require any additional Kramdown parser before selecting it. GFM and Kramdown input are available out of the box. +#### bullet -When a TOC is missing, a leading `# Title` is excluded if every subsequent heading is nested below it. A lone heading or multiple top-level sections are retained. When a TOC exists, headings before it are excluded as before. +List marker: `'-'` (default), `'*'`, or `'+'`. -### Diff Reports +```ruby +toc.check!(bullet: '*') +``` + +#### indent + +Non-negative number of spaces per nesting level. Default: `2`. + +```ruby +toc.check!(indent: 4) +``` + +#### max_depth + +Maximum absolute Markdown heading level (1–6). Default: `nil`, including all levels. For example, `2` includes `#` and `##` headings but not `###`. + +```ruby +toc.check!(max_depth: 2) +``` + +#### report + +Report style: `:full` (default) shows the complete expected TOC. Use `:diff` to show mismatched entries with two surrounding entries of context. Removed lines are prefixed with `-`, additions with `+`. Missing TOCs always show the full suggestion. + +```ruby +toc.check!(report: :diff) +``` + +### Global Defaults -Full expected TOCs remain the default. Set `toc.report = :diff` to show only mismatched entries with two surrounding entries of context. Removed lines are prefixed with `-`, additions with `+`. Missing TOCs always show the full suggested TOC. +Set shared defaults on `toc`, then override individual settings for a particular check: ```ruby -toc.report = :diff +toc.files = ['README.md', 'DEV.md'] +toc.header = 'Contents' toc.check! +toc.check!(files: ['docs/guide.md'], header: 'Guide Contents', parser: 'Kramdown') +toc.check! # still checks README.md and DEV.md using the Contents header ``` +The same global/per-check choice applies to every option in the table, including `report`, `format`, and `max_depth`. Global settings are shared across plugin instances; each check captures its own immutable configuration snapshot. + ## Contributing See [CONTRIBUTING](CONTRIBUTING.md). diff --git a/lib/toc/config.rb b/lib/toc/config.rb index 5598f09..72845c6 100644 --- a/lib/toc/config.rb +++ b/lib/toc/config.rb @@ -1,96 +1,81 @@ module Danger module Toc - module Config - extend self - - ATTRIBUTES = %i[ - files - header - format - parser - bullet - indent - max_depth - report - ].freeze - - ACCESSORS = ATTRIBUTES.map { |name| :"#{name}=" } - - DELEGATORS = ATTRIBUTES + ACCESSORS - - attr_accessor(*Config::ATTRIBUTES) - - # Files to process - def files=(value) - @files = value + class Config + DEFAULTS = { + files: ['README.md'].freeze, + header: 'Table of Contents', + format: :github, + parser: 'GFM', + bullet: '-', + indent: 2, + max_depth: nil, + report: :full + }.freeze + + ATTRIBUTES = DEFAULTS.keys.freeze + DELEGATORS = (ATTRIBUTES + ATTRIBUTES.map { |name| :"#{name}=" }).freeze + + VALIDATORS = { + files: ->(value) { value.is_a?(Array) && value.all? { |file| file.is_a?(String) && !file.strip.empty? } }, + header: ->(value) { value.is_a?(String) && !value.strip.empty? }, + parser: ->(value) { value.is_a?(String) && !value.strip.empty? }, + format: ->(value) { %i[github kramdown].include?(value) }, + bullet: ->(value) { %w[- * +].include?(value) }, + indent: ->(value) { value.is_a?(Integer) && value >= 0 }, + max_depth: ->(value) { value.nil? || (value.is_a?(Integer) && (1..6).cover?(value)) }, + report: ->(value) { %i[full diff].include?(value) } + }.freeze + + attr_reader(*ATTRIBUTES) + + ATTRIBUTES.each do |name| + define_method("#{name}=") do |value| + validate_option!(name, value) + instance_variable_set("@#{name}", snapshot(value)) + end end - # Table of Contents Header - def header=(value) - @header = value - end + def initialize(**options) + unknown = options.keys - ATTRIBUTES + raise ArgumentError, "Unknown TOC options: #{unknown.join(', ')}" unless unknown.empty? - def format - @format ||= default_format + DEFAULTS.merge(options).each { |name, value| public_send("#{name}=", value) } end - def bullet=(value) - raise ArgumentError, 'bullet must be -, *, or +' unless %w[- * +].include?(value) - - @bullet = value - end - - def indent=(value) - raise ArgumentError, 'indent must be a non-negative Integer' unless value.is_a?(Integer) && value >= 0 - - @indent = value + def with(**options) + self.class.new(**to_h, **options).freeze end - def max_depth=(value) - raise ArgumentError, 'max_depth must be nil or an Integer between 1 and 6' unless value.nil? || (value.is_a?(Integer) && (1..6).cover?(value)) - - @max_depth = value + def to_h + ATTRIBUTES.to_h { |name| [name, public_send(name)] } end - def parser=(value) - raise ArgumentError, 'parser must be a non-empty String' unless value.is_a?(String) && !value.strip.empty? - - @parser = value + def reset + DEFAULTS.each { |name, value| public_send("#{name}=", value) } end - def report=(value) - raise ArgumentError, 'report must be :full or :diff' unless %i[full diff].include?(value) - - @report = value - end + private - def default_format - :github + def validate_option!(name, value) + raise ArgumentError, "Invalid TOC #{name}: #{value.inspect}" unless VALIDATORS.fetch(name).call(value) end - def reset - self.files = ['README.md'] - self.header = 'Table of Contents' - self.format = default_format - self.parser = 'GFM' - self.bullet = '-' - self.indent = 2 - self.max_depth = nil - self.report = :full + def snapshot(value) + case value + when Array then value.map { |item| snapshot(item) }.freeze + when String then value.dup.freeze + else value + end end - - reset end - class << self - def configure - warn '[DEPRECATION] `configure` is deprecated. Please directly configure the Danger plugin via `toc.xyz=` instead.' - block_given? ? yield(Config) : Config - end + def self.config + @config ||= Config.new + end - def config - Config - end + def self.configure + warn '[DEPRECATION] `configure` is deprecated. Please directly configure the Danger plugin via `toc.xyz=` instead.' + block_given? ? yield(config) : config end end end diff --git a/lib/toc/constructors.rb b/lib/toc/constructors.rb index 69bcda9..1ef6ffe 100644 --- a/lib/toc/constructors.rb +++ b/lib/toc/constructors.rb @@ -7,10 +7,6 @@ module Constructors def self.get(name) const_get "#{name.to_s.camelize}Constructor" end - - def self.current - get Danger::Toc.config.format - end end end end diff --git a/lib/toc/constructors/kramdown_constructor.rb b/lib/toc/constructors/kramdown_constructor.rb index 2574add..58479e1 100644 --- a/lib/toc/constructors/kramdown_constructor.rb +++ b/lib/toc/constructors/kramdown_constructor.rb @@ -26,7 +26,7 @@ def convert(el) has_toc = false headers = [] toc.each do |line| - if !has_toc && line[:text] == Danger::Toc.config.header + if !has_toc && line[:text] == (@options[:toc_header] || 'Table of Contents') headers = [] # drop any headers prior to TOC has_toc = true else diff --git a/lib/toc/extractor.rb b/lib/toc/extractor.rb index 9ca5828..662b134 100644 --- a/lib/toc/extractor.rb +++ b/lib/toc/extractor.rb @@ -8,10 +8,11 @@ def initialize(root, options) @toc_start = nil @toc_end = nil @in_toc = false + @toc_header = options.fetch(:toc_header, 'Table of Contents') end def convert(el) - if el.type == :header && el.options[:raw_text] == Danger::Toc.config.header + if el.type == :header && el.options[:raw_text] == @toc_header @in_toc = true @toc_start = el.options[:location] elsif el.type == :header diff --git a/lib/toc/markdown_file.rb b/lib/toc/markdown_file.rb index b0d3d45..1adc221 100644 --- a/lib/toc/markdown_file.rb +++ b/lib/toc/markdown_file.rb @@ -4,13 +4,15 @@ require_relative 'extractor' require_relative 'constructors' +require_relative 'config' module Danger module Toc class MarkdownFile - attr_reader :filename, :exists, :toc, :headers + attr_reader :filename, :exists, :toc, :headers, :config - def initialize(filename = 'README.md') + def initialize(filename = 'README.md', config: Danger::Toc.config.with) + @config = config @filename = filename @exists = File.exist?(filename) return unless @exists @@ -39,8 +41,8 @@ def has_toc? def toc_from_headers headers.map do |header| [ - ' ' * header[:depth] * Danger::Toc.config.indent, - "#{Danger::Toc.config.bullet} [#{header[:text]}]", + ' ' * header[:depth] * config.indent, + "#{config.bullet} [#{header[:text]}]", "(##{header[:id]})" ].compact.join end @@ -78,23 +80,23 @@ def diff_lines(change) # Parse markdown file for TOC. def parse! md = File.read(filename) - doc = Kramdown::Document.new(md, input: Danger::Toc.config.parser) + doc = Kramdown::Document.new(md, input: config.parser) extract_toc!(md, doc) construct_headers!(doc) end def extract_toc!(markdown, doc) - toc_start, toc_end = Danger::Toc::Extractor.convert(doc.root).first + toc_start, toc_end = Danger::Toc::Extractor.convert(doc.root, toc_header: config.header).first toc_end ||= markdown.lines.length + 1 if toc_start @has_toc = toc_start && toc_end @toc = markdown.split("\n")[toc_start, toc_end - toc_start - 1].reject(&:empty?) if @has_toc end def construct_headers!(doc) - @headers = Danger::Toc::Constructors.current.convert(doc.root).first + @headers = Danger::Toc::Constructors.get(config.format).convert(doc.root, toc_header: config.header).first headers.shift if !@has_toc && document_title? - headers.select! { |header| header[:depth] <= Danger::Toc.config.max_depth } if Danger::Toc.config.max_depth + headers.select! { |header| header[:depth] <= config.max_depth } if config.max_depth end def document_title? diff --git a/lib/toc/plugin.rb b/lib/toc/plugin.rb index 4360101..f8221b1 100644 --- a/lib/toc/plugin.rb +++ b/lib/toc/plugin.rb @@ -7,8 +7,7 @@ module Danger # # @example Customize files and remind the requester to update TOCs when necessary. # - # toc.files = ['README.md'] - # toc.is_toc_correct? + # toc.check!(files: ['README.md'], max_depth: 3) # # @see dblock/danger-toc # @tags toc @@ -16,53 +15,58 @@ module Danger class DangerToc < Plugin extend Forwardable - def_delegators Danger::Toc.config, *Danger::Toc::Config::DELEGATORS + def_delegators 'Danger::Toc.config', *Danger::Toc::Config::DELEGATORS # Run all checks. - # @return [void] - def check! - is_toc_correct? + # @param options [Hash] Per-check files, header, parser, format, bullet, indent, max_depth, and report settings. + # @return [boolean] Whether all files have correct TOCs. + def check!(**options) + config = Danger::Toc.config.with(**options) + config.files.map { |filename| check_file(filename, config) }.all? end # Run all checks. - # @return [void] - def check + # @return [boolean] + def check(**options) warn '[DEPRECATION] `check` is deprecated. Please use `check!` instead.' - check! + check!(**options) end # Has the README file been modified? # @return [boolean] - def toc_changes? + def toc_changes?(**options) + files = Danger::Toc.config.with(**options).files git.modified_files.intersect?(files) || git.added_files.intersect?(files) end # Is the TOC format correct? # @return [boolean] - def is_toc_correct? - files.all? do |filename| - toc_file = Danger::Toc::MarkdownFile.new(filename) - if !toc_file.exists? - messaging.fail("The #{filename} file does not exist.", sticky: false) - false - elsif toc_file.good? - true + def is_toc_correct?(**options) + check!(**options) + end + + private + + def check_file(filename, config) + toc_file = Danger::Toc::MarkdownFile.new(filename, config: config) + if !toc_file.exists? + messaging.fail("The #{filename} file does not exist.", sticky: false) + false + elsif toc_file.good? + true + else + report_toc(toc_file) + if toc_file.has_toc? + messaging.fail("The TOC found in #{filename} doesn't match the sections of the file.", sticky: false) else - report_toc(toc_file) - if toc_file.has_toc? - messaging.fail("The TOC found in #{filename} doesn't match the sections of the file.", sticky: false) - else - messaging.fail("The #{filename} file is missing a TOC.", sticky: false) - end - false + messaging.fail("The #{filename} file is missing a TOC.", sticky: false) end + false end end - private - def report_toc(toc_file) - if Danger::Toc.config.report == :diff && toc_file.has_toc? + if toc_file.config.report == :diff && toc_file.has_toc? markdown <<~MARKDOWN Here's the TOC diff for #{toc_file.filename} (- current, + expected): @@ -75,7 +79,7 @@ def report_toc(toc_file) Here's the expected TOC for #{toc_file.filename}: ```markdown - # #{Danger::Toc.config.header} + # #{toc_file.config.header} #{toc_file.toc_from_headers.join("\n")} ``` diff --git a/spec/config_spec.rb b/spec/config_spec.rb index 345987f..94d8750 100644 --- a/spec/config_spec.rb +++ b/spec/config_spec.rb @@ -1,71 +1,51 @@ require File.expand_path('spec_helper', __dir__) describe Danger::Toc::Config do - after do - described_class.reset - end - - it 'rejects invalid options without replacing the configuration' do - { bullet: '.', indent: -1, max_depth: 7, parser: '', report: :unknown }.each do |name, value| - previous = described_class.public_send(name) - expect { described_class.public_send("#{name}=", value) }.to raise_error(ArgumentError) - expect(described_class.public_send(name)).to eq(previous) + it 'rejects invalid options' do + { files: 'README.md', header: '', format: :unknown, bullet: '.', indent: -1, max_depth: 7, parser: '', report: :unknown }.each do |name, value| + expect { described_class.new(**{ name => value }) }.to raise_error(ArgumentError) end end - describe 'configure' do - describe 'files' do - context 'default' do - it 'assumes README.md' do - expect(Danger::Toc.config.files).to eq ['README.md'] - end - end - - context 'custom value' do - before do - Danger::Toc.config.files = ['README.md', 'SOMETHING.md'] - end - - it 'is set' do - expect(Danger::Toc.config.files).to eq ['README.md', 'SOMETHING.md'] - end - end - end - - describe 'header' do - context 'default' do - it 'assumes Table of Contents' do - expect(Danger::Toc.config.header).to eq 'Table of Contents' - end - end + it 'snapshots mutable inputs' do + files = [+'guide.md'] + header = +'Contents' + config = described_class.new(files: files, header: header) + files.first.replace('other.md') + files << 'extra.md' + header.replace('Changed') + expect(config.files).to eq(['guide.md']) + expect(config.header).to eq('Contents') + expect(config.with).to be_frozen + end - context 'custom value' do - before do - Danger::Toc.config.header = 'Custom TOC' - end + it 'supports every option as a global setting and a per-check override' do + custom = { files: ['guide.md'], header: 'Contents', format: :kramdown, parser: 'Kramdown', bullet: '*', indent: 4, max_depth: 3, report: :diff } + global = described_class.new + custom.each { |name, value| global.public_send("#{name}=", value) } + expect(global.to_h).to eq(custom) + expect(global.with(**described_class::DEFAULTS).to_h).to eq(described_class::DEFAULTS) + expect(global.to_h).to eq(custom) + end - it 'is set' do - expect(Danger::Toc.config.header).to eq 'Custom TOC' - end - end + it 'requires validation for every declared option' do + described_class::ATTRIBUTES.each do |name| + expect { described_class.new(**{ name => Object.new }) }.to raise_error(ArgumentError) end + end - describe 'format' do - context 'default' do - it 'assumes github' do - expect(Danger::Toc.config.format).to eq(:github) - end - end - - context 'custom value' do - before do - Danger::Toc.config.format = :kramdown - end + it 'keeps a check snapshot unchanged when defaults are reassigned' do + global = described_class.new(header: 'Contents', bullet: '*') + check = global.with(indent: 4) + global.header = 'New Contents' + global.bullet = '+' + expect([check.header, check.bullet, check.indent]).to eq(['Contents', '*', 4]) + end - it 'is set' do - expect(Danger::Toc.config.format).to eq(:kramdown) - end - end - end + it 'rejects unknown overrides and leaves valid defaults intact after invalid assignment' do + global = described_class.new + expect { global.with(unknown: true) }.to raise_error(ArgumentError, /Unknown TOC options/) + expect { global.indent = -1 }.to raise_error(ArgumentError) + expect(global.indent).to eq(2) end end diff --git a/spec/danger/toc/markdown_file_options_spec.rb b/spec/danger/toc/markdown_file_options_spec.rb index b4196c6..f675dad 100644 --- a/spec/danger/toc/markdown_file_options_spec.rb +++ b/spec/danger/toc/markdown_file_options_spec.rb @@ -2,13 +2,11 @@ require 'tempfile' describe Danger::Toc::MarkdownFile do - after { Danger::Toc::Config.reset } - - def parse_markdown(text) + def parse_markdown(text, **options) Tempfile.create(['toc', '.md']) do |file| file.write(text) file.flush - yield described_class.new(file.path) + yield described_class.new(file.path, config: Danger::Toc::Config.new(**options)) end end @@ -30,46 +28,37 @@ def parse_markdown(text) end it 'uses custom bullets and indentation to generate and validate a TOC' do - Danger::Toc.config.bullet = '*' - Danger::Toc.config.indent = 4 - parse_markdown("# Title\n\n## Table of Contents\n\n* [Install](#install)\n * [Details](#details)\n\n## Install\n\n### Details\n") do |file| + parse_markdown("# Title\n\n## Table of Contents\n\n* [Install](#install)\n * [Details](#details)\n\n## Install\n\n### Details\n", bullet: '*', indent: 4) do |file| expect(file).to be_good expect(file.toc_from_headers).to eq(['* [Install](#install)', ' * [Details](#details)']) end end it 'limits absolute heading depth before normalizing indentation' do - Danger::Toc.config.max_depth = 2 - parse_markdown("# Title\n\n## Install\n\n### Details\n\n## Usage\n") do |file| + parse_markdown("# Title\n\n## Install\n\n### Details\n\n## Usage\n", max_depth: 2) do |file| expect(file.toc_from_headers).to eq(['- [Install](#install)', '- [Usage](#usage)']) end end it 'supports plus bullets with no indentation' do - Danger::Toc.config.bullet = '+' - Danger::Toc.config.indent = 0 - parse_markdown("# Title\n\n## Install\n\n### Details\n") do |file| + parse_markdown("# Title\n\n## Install\n\n### Details\n", bullet: '+', indent: 0) do |file| expect(file.toc_from_headers).to eq(['+ [Install](#install)', '+ [Details](#details)']) end end it 'handles a depth limit that excludes all sections' do - Danger::Toc.config.max_depth = 1 - parse_markdown("# Title\n\n## Install\n") { |file| expect(file.toc_from_headers).to eq([]) } + parse_markdown("# Title\n\n## Install\n", max_depth: 1) { |file| expect(file.toc_from_headers).to eq([]) } end it 'supports Kramdown input separately from the anchor format' do - Danger::Toc.config.parser = 'Kramdown' - Danger::Toc.config.format = :kramdown - parse_markdown("# Table of Contents\n\n- [Install](#custom)\n\n## Install {#custom}\n") do |file| + parse_markdown("# Table of Contents\n\n- [Install](#custom)\n\n## Install {#custom}\n", parser: 'Kramdown', format: :kramdown) do |file| expect(file).to be_good expect(file.headers.first[:id]).to eq('custom') end end it 'propagates unsupported parser errors' do - Danger::Toc.config.parser = 'MissingParser' - expect { parse_markdown("# Title\n", &:headers) }.to raise_error(Kramdown::Error, /MissingParser/) + expect { parse_markdown("# Title\n", parser: 'MissingParser', &:headers) }.to raise_error(Kramdown::Error, /MissingParser/) end it 'recognizes a TOC at the end of a file' do diff --git a/spec/toc_spec.rb b/spec/toc_spec.rb index 5e6432c..c73c2fc 100644 --- a/spec/toc_spec.rb +++ b/spec/toc_spec.rb @@ -1,9 +1,7 @@ require File.expand_path('spec_helper', __dir__) describe Danger::Toc do - after do - Danger::Toc::Config.reset - end + after { Danger::Toc.config.reset } it 'is a Danger plugin' do expect(Danger::DangerToc.new(nil)).to be_a Danger::Plugin @@ -12,10 +10,8 @@ describe 'with Dangerfile' do let(:filename) { File.expand_path('fixtures/markdown_file/one_section_with_toc.md', __dir__) } let(:dangerfile) { testing_dangerfile } - let(:toc) do - dangerfile.toc.files = [filename] - dangerfile.toc - end + let(:toc) { dangerfile.toc } + let(:options) { { files: [filename] } } let(:status_report) { toc.status_report } context 'toc_changes?' do @@ -23,27 +19,27 @@ allow(toc.git).to receive(:modified_files).and_return([filename]) allow(toc.git).to receive(:added_files).and_return([]) - expect(toc).to be_toc_changes + expect(toc.toc_changes?(files: [filename])).to be true end it 'finds added files' do allow(toc.git).to receive(:modified_files).and_return([]) allow(toc.git).to receive(:added_files).and_return([filename]) - expect(toc).to be_toc_changes + expect(toc.toc_changes?(files: [filename])).to be true end it 'does not found changed files' do allow(toc.git).to receive(:modified_files).and_return([]) allow(toc.git).to receive(:added_files).and_return([]) - expect(toc).not_to be_toc_changes + expect(toc.toc_changes?(files: [filename])).to be false end end context 'is_toc_correct?' do subject do - toc.is_toc_correct? + toc.check!(**options) end context 'without a file' do @@ -109,25 +105,42 @@ end it 'provides an opt-in diff while still reporting a failure' do - toc.report = :diff + options[:report] = :diff expect(subject).to be false expect(status_report[:markdowns].first.message).to include('```diff', '- current, + expected') expect(status_report[:errors]).not_to be_empty end end - it 'delegates generation and parser settings through the plugin' do - toc.bullet = '+' - toc.indent = 4 - toc.max_depth = 3 - toc.parser = 'Kramdown' - toc.format = :kramdown - expect([toc.bullet, toc.indent, toc.max_depth, toc.parser, toc.format]).to eq(['+', 4, 3, 'Kramdown', :kramdown]) + it 'does not leak options between calls or plugin instances' do + expect(toc.check!(files: [filename], bullet: '*', parser: 'Kramdown')).to be false + expect(toc.check!(files: [filename])).to be true + expect(testing_dangerfile.toc.check!(files: [filename])).to be true + end + + it 'checks every file even when an earlier file fails' do + expect(toc.check!(files: ['missing-one.md', 'missing-two.md'])).to be false + expect(status_report[:errors]).to eq(['The missing-one.md file does not exist.', 'The missing-two.md file does not exist.']) + end + + it 'uses global defaults but leaves them unchanged by per-check overrides' do + toc.files = [filename] + toc.bullet = '*' + expect(toc.check!(bullet: '-')).to be true + expect(toc.bullet).to eq('*') + expect(toc.check!).to be false + end + + it 'exposes every declared option through the plugin' do + Danger::Toc::Config::ATTRIBUTES.each do |name| + toc.public_send("#{name}=", Danger::Toc::Config::DEFAULTS.fetch(name)) + expect(toc.public_send(name)).to eq(Danger::Toc::Config::DEFAULTS.fetch(name)) + end end context 'with a custom toc header' do before do - Danger::Toc.config.header = 'Custom TOC' + options[:header] = 'Custom TOC' end context 'with missing TOC' do