Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
110 changes: 85 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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).
Expand Down
131 changes: 58 additions & 73 deletions lib/toc/config.rb
Original file line number Diff line number Diff line change
@@ -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
4 changes: 0 additions & 4 deletions lib/toc/constructors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion lib/toc/constructors/kramdown_constructor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion lib/toc/extractor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading