yard-yaml 0.1.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.
data/REEK ADDED
File without changes
data/RUBOCOP.md ADDED
@@ -0,0 +1,71 @@
1
+ # RuboCop Usage Guide
2
+
3
+ ## Overview
4
+
5
+ A tale of two RuboCop plugin gems.
6
+
7
+ ### RuboCop Gradual
8
+
9
+ This project uses `rubocop_gradual` instead of vanilla RuboCop for code style checking. The `rubocop_gradual` tool allows for gradual adoption of RuboCop rules by tracking violations in a lock file.
10
+
11
+ ### RuboCop LTS
12
+
13
+ This project uses `rubocop-lts` to ensure, on a best-effort basis, compatibility with Ruby >= 1.9.2.
14
+ RuboCop rules are meticulously configured by the `rubocop-lts` family of gems to ensure that a project is compatible with a specific version of Ruby. See: https://rubocop-lts.gitlab.io for more.
15
+
16
+ ## Checking RuboCop Violations
17
+
18
+ To check for RuboCop violations in this project, always use:
19
+
20
+ ```bash
21
+ bundle exec rake rubocop_gradual:check
22
+ ```
23
+
24
+ **Do not use** the standard RuboCop commands like:
25
+ - `bundle exec rubocop`
26
+ - `rubocop`
27
+
28
+ ## Understanding the Lock File
29
+
30
+ The `.rubocop_gradual.lock` file tracks all current RuboCop violations in the project. This allows the team to:
31
+
32
+ 1. Prevent new violations while gradually fixing existing ones
33
+ 2. Track progress on code style improvements
34
+ 3. Ensure CI builds don't fail due to pre-existing violations
35
+
36
+ ## Common Commands
37
+
38
+ - **Check violations**
39
+ - `bundle exec rake rubocop_gradual`
40
+ - `bundle exec rake rubocop_gradual:check`
41
+ - **(Safe) Autocorrect violations, and update lockfile if no new violations**
42
+ - `bundle exec rake rubocop_gradual:autocorrect`
43
+ - **Force update the lock file (w/o autocorrect) to match violations present in code**
44
+ - `bundle exec rake rubocop_gradual:force_update`
45
+
46
+ ## Workflow
47
+
48
+ 1. Before submitting a PR, run `bundle exec rake rubocop_gradual:autocorrect`
49
+ a. or just the default `bundle exec rake`, as autocorrection is a pre-requisite of the default task.
50
+ 2. If there are new violations, either:
51
+ - Fix them in your code
52
+ - Run `bundle exec rake rubocop_gradual:force_update` to update the lock file (only for violations you can't fix immediately)
53
+ 3. Commit the updated `.rubocop_gradual.lock` file along with your changes
54
+
55
+ ## Never add inline RuboCop disables
56
+
57
+ Do not add inline `rubocop:disable` / `rubocop:enable` comments anywhere in the codebase (including specs, except when following the few existing `rubocop:disable` patterns for a rule already being disabled elsewhere in the code). We handle exceptions in two supported ways:
58
+
59
+ - Permanent/structural exceptions: prefer adjusting the RuboCop configuration (e.g., in `.rubocop.yml`) to exclude a rule for a path or file pattern when it makes sense project-wide.
60
+ - Temporary exceptions while improving code: record the current violations in `.rubocop_gradual.lock` via the gradual workflow:
61
+ - `bundle exec rake rubocop_gradual:autocorrect` (preferred; will autocorrect what it can and update the lock only if no new violations were introduced)
62
+ - If needed, `bundle exec rake rubocop_gradual:force_update` (as a last resort when you cannot fix the newly reported violations immediately)
63
+
64
+ In general, treat the rules as guidance to follow; fix violations rather than ignore them. For example, RSpec conventions in this project expect `described_class` to be used in specs that target a specific class under test.
65
+
66
+ ## Benefits of rubocop_gradual
67
+
68
+ - Allows incremental adoption of code style rules
69
+ - Prevents CI failures due to pre-existing violations
70
+ - Provides a clear record of code style debt
71
+ - Enables focused efforts on improving code quality over time
data/SECURITY.md ADDED
@@ -0,0 +1,21 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ |----------|-----------|
7
+ | 1.latest | ✅ |
8
+
9
+ ## Security contact information
10
+
11
+ To report a security vulnerability, please use the
12
+ [Tidelift security contact](https://tidelift.com/security).
13
+ Tidelift will coordinate the fix and disclosure.
14
+
15
+ ## Additional Support
16
+
17
+ If you are interested in support for versions older than the latest release,
18
+ please consider sponsoring the project / maintainer @ https://liberapay.com/pboling/donate,
19
+ or find other sponsorship links in the [README].
20
+
21
+ [README]: README.md
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Yaml
5
+ # CLI helpers to parse `.yardopts`/argv flags for yard-yaml.
6
+ #
7
+ # Phase 1: Only parses configuration flags and returns a Hash suitable for
8
+ # Yard::Yaml::Config#apply. It does not mutate global state.
9
+ module Cli
10
+ PREFIX = "--yard_yaml-"
11
+ NO_PREFIX = "--no-yard_yaml-"
12
+
13
+ class << self
14
+ # Parse argv for yard-yaml flags.
15
+ #
16
+ # Supported flags:
17
+ # - --yard_yaml-include <glob> (repeatable)
18
+ # - --yard_yaml-exclude <glob> (repeatable)
19
+ # - --yard_yaml-out_dir <dir>
20
+ # - --yard_yaml-index[=true|false] | --no-yard_yaml-index
21
+ # - --yard_yaml-front_matter[=true|false] | --no-yard_yaml-front_matter
22
+ # - --yard_yaml-strict[=true|false] | --no-yard_yaml-strict
23
+ # - --yard_yaml-allow_erb[=true|false] | --no-yard_yaml-allow_erb
24
+ # - --yard_yaml-toc <mode>
25
+ # - --yard_yaml-converter_options key:value[,key:value]
26
+ #
27
+ # @param argv [Array<String>]
28
+ # @return [Hash] normalized overrides
29
+ def parse(argv)
30
+ return {} if argv.nil? || argv.empty?
31
+
32
+ overrides = {}
33
+ i = 0
34
+ while i < argv.length
35
+ token = argv[i]
36
+
37
+ if token.start_with?(NO_PREFIX)
38
+ key = token.delete_prefix(NO_PREFIX).to_sym
39
+ apply_bool(overrides, key, false)
40
+ i += 1
41
+ next
42
+ end
43
+
44
+ unless token.start_with?(PREFIX)
45
+ i += 1
46
+ next
47
+ end
48
+
49
+ # handle --flag=value form
50
+ if token.include?("=")
51
+ flag, raw = token.split("=", 2)
52
+ key = flag.delete_prefix(PREFIX).to_sym
53
+ apply_kv(overrides, key, raw)
54
+ i += 1
55
+ next
56
+ end
57
+
58
+ key = token.delete_prefix(PREFIX).to_sym
59
+
60
+ case key
61
+ when :include, :exclude
62
+ value = argv[i + 1]
63
+ if value.nil? || value.start_with?("--")
64
+ warn_unknown("missing value for #{token}")
65
+ i += 1
66
+ else
67
+ arr = (overrides[key] ||= [])
68
+ arr << value.to_s
69
+ i += 2
70
+ end
71
+ when :out_dir, :toc
72
+ value = argv[i + 1]
73
+ if value.nil? || value.start_with?("--")
74
+ warn_unknown("missing value for #{token}")
75
+ i += 1
76
+ else
77
+ overrides[key] = value.to_s
78
+ i += 2
79
+ end
80
+ when :index, :front_matter, :strict, :allow_erb
81
+ # Bare presence means true
82
+ apply_bool(overrides, key, true)
83
+ i += 1
84
+ when :converter_options
85
+ value = argv[i + 1]
86
+ if value.nil? || value.start_with?("--")
87
+ warn_unknown("missing value for #{token}")
88
+ i += 1
89
+ else
90
+ overrides[:converter_options] = parse_converter_options(value)
91
+ i += 2
92
+ end
93
+ else
94
+ warn_unknown("unknown flag #{token}")
95
+ i += 1
96
+ end
97
+ end
98
+
99
+ overrides
100
+ end
101
+
102
+ private
103
+
104
+ def apply_kv(overrides, key, raw)
105
+ case key
106
+ when :include, :exclude
107
+ arr = (overrides[key] ||= [])
108
+ arr << raw.to_s
109
+ when :out_dir, :toc
110
+ overrides[key] = raw.to_s
111
+ when :index, :front_matter, :strict, :allow_erb
112
+ apply_bool(overrides, key, coerce_bool(raw))
113
+ when :converter_options
114
+ overrides[:converter_options] = parse_converter_options(raw)
115
+ else
116
+ warn_unknown("unknown flag --yard_yaml-#{key}")
117
+ end
118
+ end
119
+
120
+ def apply_bool(overrides, key, value)
121
+ overrides[key] = !!value
122
+ end
123
+
124
+ def coerce_bool(value)
125
+ case value.to_s.strip.downcase
126
+ when "", "true", "1", "yes", "y", "on" then true
127
+ when "false", "0", "no", "n", "off" then false
128
+ else
129
+ warn_unknown("invalid boolean '#{value}'")
130
+ false
131
+ end
132
+ end
133
+
134
+ def parse_converter_options(raw)
135
+ result = {}
136
+ raw.to_s.split(",").each do |pair|
137
+ k, v = pair.split(":", 2)
138
+ if k.nil? || v.nil?
139
+ warn_unknown("invalid converter option '#{pair}'")
140
+ next
141
+ end
142
+ result[k.to_s] = coerce_scalar(v)
143
+ end
144
+ result
145
+ end
146
+
147
+ def coerce_scalar(v)
148
+ s = v.to_s
149
+ low = s.strip.downcase
150
+ return true if %w[true yes y on 1].include?(low)
151
+ return false if %w[false no n off 0].include?(low)
152
+ begin
153
+ return Integer(s)
154
+ rescue
155
+ nil
156
+ end if s.match?(/\A[+-]?\d+\z/)
157
+ begin
158
+ return Float(s)
159
+ rescue
160
+ nil
161
+ end if s.match?(/\A[+-]?(?:\d+\.)?\d+\z/)
162
+ s
163
+ end
164
+
165
+ def warn_unknown(message)
166
+ # Delegate to unified helper to avoid NameError when a partial YARD stub exists.
167
+ if defined?(::Yard) && ::Yard.const_defined?(:Yaml)
168
+ ::Yard::Yaml.warn(message)
169
+ else
170
+ Kernel.warn("yard-yaml: #{message}")
171
+ end
172
+ end
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Yaml
5
+ # Configuration for the yard-yaml plugin.
6
+ #
7
+ # Phase 0: This is a data holder only; wiring into YARD will happen in later phases.
8
+ #
9
+ # Defaults are intentionally conservative and match the PRD/plan.
10
+ # Nothing here modifies YARD behavior when merely required.
11
+ class Config
12
+ # Default glob patterns to include during discovery.
13
+ DEFAULT_INCLUDE = [
14
+ "docs/**/*.y{a,}ml",
15
+ "*.y{a,}ml",
16
+ # CFF (Citation File Format) files are valid YAML; include them by default.
17
+ "docs/**/*.cff",
18
+ "*.cff",
19
+ ].freeze
20
+
21
+ # Default glob patterns to exclude during discovery.
22
+ DEFAULT_EXCLUDE = [
23
+ "**/_*.y{a,}ml",
24
+ "**/_*.cff",
25
+ ].freeze
26
+
27
+ # Directory (under YARD output) where converted pages will be written.
28
+ DEFAULT_OUT_DIR = "yaml"
29
+
30
+ # Whether to generate an index page for YAML documents.
31
+ DEFAULT_INDEX = true
32
+
33
+ # Table of contents generation strategy.
34
+ # "auto" defers to converter/page size; additional options may be added later.
35
+ DEFAULT_TOC = "auto"
36
+
37
+ # Options forwarded to yaml-converter.
38
+ DEFAULT_CONVERTER_OPTIONS = {}.freeze
39
+
40
+ # Whether to respect YAML front matter for title/nav order.
41
+ DEFAULT_FRONT_MATTER = true
42
+
43
+ # When true, errors are raised and should fail the build (later phases).
44
+ DEFAULT_STRICT = false
45
+
46
+ # Whether to allow ERB processing inside YAML (disabled by default for safety).
47
+ DEFAULT_ALLOW_ERB = false
48
+
49
+ attr_accessor :include,
50
+ :exclude,
51
+ :out_dir,
52
+ :index,
53
+ :toc,
54
+ :converter_options,
55
+ :front_matter,
56
+ :strict,
57
+ :allow_erb
58
+
59
+ # Create a new Config with defaults, optionally overridden via a hash.
60
+ #
61
+ # @param overrides [Hash] optional overrides for any attribute
62
+ def initialize(overrides = {})
63
+ @include = DEFAULT_INCLUDE.dup
64
+ @exclude = DEFAULT_EXCLUDE.dup
65
+ @out_dir = DEFAULT_OUT_DIR.dup
66
+ @index = DEFAULT_INDEX
67
+ @toc = DEFAULT_TOC.dup
68
+ @converter_options = DEFAULT_CONVERTER_OPTIONS.dup
69
+ @front_matter = DEFAULT_FRONT_MATTER
70
+ @strict = DEFAULT_STRICT
71
+ @allow_erb = DEFAULT_ALLOW_ERB
72
+
73
+ apply(overrides) unless overrides.nil? || overrides.empty?
74
+ end
75
+
76
+ # Apply a set of overrides to this config instance.
77
+ # Unknown keys are ignored in Phase 0 (later phases may warn).
78
+ #
79
+ # @param hash [Hash]
80
+ # @return [self]
81
+ def apply(hash)
82
+ hash.each do |key, value|
83
+ case key.to_sym
84
+ when :include then @include = Array(value).map(&:to_s)
85
+ when :exclude then @exclude = Array(value).map(&:to_s)
86
+ when :out_dir then @out_dir = value.to_s
87
+ when :index then @index = coerce_bool(value)
88
+ when :toc then @toc = value.to_s
89
+ when :converter_options then @converter_options = value || {}
90
+ when :front_matter then @front_matter = coerce_bool(value)
91
+ when :strict then @strict = coerce_bool(value)
92
+ when :allow_erb then @allow_erb = coerce_bool(value)
93
+ else
94
+ # Intentionally ignore unknown keys in Phase 0
95
+ end
96
+ end
97
+ self
98
+ end
99
+
100
+ private
101
+
102
+ # Coerce various truthy/falsey representations to a boolean.
103
+ # Accepts common string/number forms used in CLI and config files.
104
+ def coerce_bool(value)
105
+ case value
106
+ when true then true
107
+ when false, nil then false
108
+ when Integer
109
+ return true if value == 1
110
+ return false if value == 0
111
+ !!value
112
+ else
113
+ str = value.to_s.strip.downcase
114
+ return true if %w[true 1 yes y on].include?(str)
115
+ return false if %w[false 0 no n off].include?(str)
116
+ # Fallback to Ruby truthiness for anything else
117
+ !!value
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Yaml
5
+ # Thin wrapper around the yaml-converter gem with safe defaults.
6
+ #
7
+ # Phase 2 scope:
8
+ # - Provide class methods to convert from a YAML string or a file path.
9
+ # - Apply safe defaults and respect config toggles (strict, allow_erb, front_matter).
10
+ # - Delegate conversion to an underlying backend (default: ::Yaml::Converter if available).
11
+ # - Return a normalized result Hash: { html:, title:, description:, meta: }.
12
+ #
13
+ # Note: We intentionally keep the contract minimal and stable. Tests stub the backend.
14
+ class Converter
15
+ class << self
16
+ # Assignable backend for dependency injection in tests.
17
+ # Expected to respond to `convert(yaml, options)` and return a Hash with :html, :title, :description, and :meta keys
18
+ attr_writer :backend
19
+
20
+ # Convert a YAML string into an HTML result.
21
+ #
22
+ # @param yaml [String]
23
+ # @param options [Hash] additional options passed to backend
24
+ # @param config [Yard::Yaml::Config] yard-yaml config (defaults to Yard::Yaml.config)
25
+ # @return [Hash] { html:, title:, description:, meta: }
26
+ def from_string(yaml, options = {}, config: Yard::Yaml.config)
27
+ run_convert(yaml.to_s, options, config)
28
+ end
29
+
30
+ # Convert a YAML file from disk.
31
+ #
32
+ # @param path [String]
33
+ # @param options [Hash]
34
+ # @param config [Yard::Yaml::Config]
35
+ # @return [Hash]
36
+ def from_file(path, options = {}, config: Yard::Yaml.config)
37
+ content = read_file(path)
38
+ return empty_result if content.nil?
39
+ run_convert(content, options.merge(source_path: path.to_s), config)
40
+ end
41
+
42
+ # Backend accessor with auto-discovery.
43
+ def backend
44
+ return @backend if defined?(@backend) && @backend
45
+ begin
46
+ require "yaml/converter"
47
+ rescue LoadError
48
+ # ignore; backend may be set by tests
49
+ end
50
+ @backend = if defined?(::Yaml) && ::Yaml.const_defined?(:Converter)
51
+ ::Yaml::Converter
52
+ end
53
+ end
54
+
55
+ private
56
+
57
+ def read_file(path)
58
+ File.read(path.to_s)
59
+ rescue Errno::ENOENT => e
60
+ handle_error(e, strict: Yard::Yaml.config.strict, context: "missing file: #{path}")
61
+ nil
62
+ end
63
+
64
+ def run_convert(yaml, options, config)
65
+ opts = build_options(options, config)
66
+ b = backend
67
+ unless b && b.respond_to?(:convert)
68
+ handle_error(Yard::Yaml::Error.new("yaml-converter backend not available"), strict: config.strict, context: "backend")
69
+ return empty_result
70
+ end
71
+
72
+ begin
73
+ normalize_result(b.convert(yaml, opts))
74
+ rescue StandardError => e
75
+ handle_error(e, strict: config.strict, context: opts[:source_path] || "string")
76
+ empty_result
77
+ end
78
+ end
79
+
80
+ def build_options(options, config)
81
+ safe = {
82
+ allow_erb: !!config.allow_erb,
83
+ front_matter: !!config.front_matter,
84
+ }
85
+ # Merge caller-supplied options and the config's converter_options map (caller wins)
86
+ safe.merge(config.converter_options || {}).merge(options || {})
87
+ end
88
+
89
+ def normalize_result(raw)
90
+ return empty_result if raw.nil?
91
+ {
92
+ html: raw[:html] || raw["html"] || "",
93
+ title: raw[:title] || raw["title"],
94
+ description: raw[:description] || raw["description"],
95
+ meta: raw[:meta] || raw["meta"] || {},
96
+ }
97
+ end
98
+
99
+ def empty_result
100
+ {html: "", title: nil, description: nil, meta: {}}
101
+ end
102
+
103
+ def handle_error(error, strict:, context: nil)
104
+ if strict
105
+ raise Yard::Yaml::Error, error.message
106
+ else
107
+ message = context ? "#{error.class}: #{error.message} (#{context})" : "#{error.class}: #{error.message}"
108
+ if defined?(::Yard) && ::Yard.const_defined?(:Yaml)
109
+ ::Yard::Yaml.__send__(:__warn, message)
110
+ else
111
+ Kernel.warn("yard-yaml: #{message}")
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yard
4
+ module Yaml
5
+ # Discovery helpers to find YAML files and collect converted pages.
6
+ #
7
+ # Phase 3 scope:
8
+ # - Discover files via include/exclude globs from config.
9
+ # - Convert files via Converter and return normalized page hashes.
10
+ # - Errors are handled by Converter according to config.strict.
11
+ module Discovery
12
+ class << self
13
+ # Find YAML files using include and exclude patterns.
14
+ # Patterns are evaluated relative to the current working directory.
15
+ #
16
+ # @param include_globs [Array<String>]
17
+ # @param exclude_globs [Array<String>]
18
+ # @return [Array<String>] sorted list of file paths
19
+ def find_files(include_globs, exclude_globs)
20
+ incs = Array(include_globs).compact
21
+ excs = Array(exclude_globs).compact
22
+
23
+ files = []
24
+ incs.each do |glob|
25
+ next if glob.nil? || glob.to_s.strip.empty?
26
+ Dir.glob(glob.to_s, File::FNM_CASEFOLD | File::FNM_EXTGLOB | File::FNM_PATHNAME).each do |path|
27
+ next unless File.file?(path)
28
+ files << path
29
+ end
30
+ end
31
+
32
+ files.uniq!
33
+
34
+ unless excs.empty?
35
+ files.select! do |path|
36
+ excs.none? { |pat| File.fnmatch?(pat.to_s, path, File::FNM_PATHNAME | File::FNM_EXTGLOB | File::FNM_CASEFOLD) }
37
+ end
38
+ end
39
+
40
+ files.sort.map { |p| File.expand_path(p) }
41
+ end
42
+
43
+ # Collect pages by converting discovered files.
44
+ #
45
+ # @param config [Yard::Yaml::Config]
46
+ # @return [Array<Hash>] Array of page hashes: { path:, html:, title:, description:, meta: }
47
+ def collect(config = Yard::Yaml.config)
48
+ files = find_files(config.include, config.exclude)
49
+ results = []
50
+
51
+ files.each do |path|
52
+ converted = Yard::Yaml::Converter.from_file(path, {}, config: config)
53
+ results << {
54
+ path: path,
55
+ html: converted[:html],
56
+ title: converted[:title],
57
+ description: converted[:description],
58
+ meta: converted[:meta] || {},
59
+ }
60
+ rescue Yard::Yaml::Error
61
+ # In strict mode Converter will raise; re-raise to fail the build
62
+ raise
63
+ rescue StandardError => e
64
+ # Non-strict converter errors are already warned; skip file
65
+ warn_fallback("skipping #{path}: #{e.class}: #{e.message}")
66
+ end
67
+
68
+ # Deterministic ordering by nav_order (if present) then title then path.
69
+ # nav_order values sort numerically; missing/non-numeric values are treated as Infinity (i.e., after any numeric ones).
70
+ results.sort_by { |h| [nav_order_value(h[:meta]), h[:title].to_s.downcase, h[:path]] }
71
+ end
72
+
73
+ private
74
+
75
+ # Extract a numeric nav_order from meta. Returns Infinity when absent or non-numeric
76
+ # so those entries sort after any numeric ones.
77
+ def nav_order_value(meta)
78
+ return Float::INFINITY unless meta.is_a?(Hash)
79
+ val = meta[:nav_order] || meta["nav_order"]
80
+ case val
81
+ when Integer, Float
82
+ val
83
+ when String
84
+ s = val.strip
85
+ if s.match?(/\A[+-]?\d+\z/)
86
+ begin
87
+ Integer(s)
88
+ rescue
89
+ Float::INFINITY
90
+ end
91
+ elsif s.match?(/\A[+-]?(?:\d+\.)?\d+\z/)
92
+ begin
93
+ Float(s)
94
+ rescue
95
+ Float::INFINITY
96
+ end
97
+ else
98
+ Float::INFINITY
99
+ end
100
+ else
101
+ Float::INFINITY
102
+ end
103
+ rescue StandardError
104
+ Float::INFINITY
105
+ end
106
+
107
+ def warn_fallback(message)
108
+ if defined?(::Yard) && ::Yard.const_defined?(:Yaml)
109
+ ::Yard::Yaml.warn(message)
110
+ else
111
+ Kernel.warn("yard-yaml: #{message}")
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end