coridoc 3.0.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.
Files changed (148) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/Rakefile +8 -0
  4. data/exe/coridoc +24 -0
  5. data/lib/coridoc/binding_inflater.rb +118 -0
  6. data/lib/coridoc/cli.rb +311 -0
  7. data/lib/coridoc/configurable.rb +530 -0
  8. data/lib/coridoc/core_model/abstract_block.rb +11 -0
  9. data/lib/coridoc/core_model/annotation_block.rb +57 -0
  10. data/lib/coridoc/core_model/attribute_reference_resolver.rb +155 -0
  11. data/lib/coridoc/core_model/base.rb +281 -0
  12. data/lib/coridoc/core_model/bibliography.rb +41 -0
  13. data/lib/coridoc/core_model/bibliography_entry.rb +48 -0
  14. data/lib/coridoc/core_model/block.rb +69 -0
  15. data/lib/coridoc/core_model/callout.rb +32 -0
  16. data/lib/coridoc/core_model/callout_text.rb +35 -0
  17. data/lib/coridoc/core_model/children_content.rb +72 -0
  18. data/lib/coridoc/core_model/comment_block.rb +16 -0
  19. data/lib/coridoc/core_model/comment_line.rb +23 -0
  20. data/lib/coridoc/core_model/definition_item.rb +68 -0
  21. data/lib/coridoc/core_model/definition_list.rb +28 -0
  22. data/lib/coridoc/core_model/element_attribute.rb +14 -0
  23. data/lib/coridoc/core_model/example_block.rb +12 -0
  24. data/lib/coridoc/core_model/footnote.rb +92 -0
  25. data/lib/coridoc/core_model/frontmatter/codec.rb +151 -0
  26. data/lib/coridoc/core_model/frontmatter/field_transform.rb +75 -0
  27. data/lib/coridoc/core_model/frontmatter/frontmatter_entry.rb +22 -0
  28. data/lib/coridoc/core_model/frontmatter/frontmatter_value.rb +78 -0
  29. data/lib/coridoc/core_model/frontmatter/schema_resolver.rb +57 -0
  30. data/lib/coridoc/core_model/frontmatter/text_splitter.rb +75 -0
  31. data/lib/coridoc/core_model/frontmatter.rb +72 -0
  32. data/lib/coridoc/core_model/has_children.rb +23 -0
  33. data/lib/coridoc/core_model/horizontal_rule_block.rb +16 -0
  34. data/lib/coridoc/core_model/id_generator.rb +23 -0
  35. data/lib/coridoc/core_model/image.rb +69 -0
  36. data/lib/coridoc/core_model/include.rb +43 -0
  37. data/lib/coridoc/core_model/include_level_offset.rb +71 -0
  38. data/lib/coridoc/core_model/include_options.rb +101 -0
  39. data/lib/coridoc/core_model/inline_content.rb +78 -0
  40. data/lib/coridoc/core_model/inline_element.rb +198 -0
  41. data/lib/coridoc/core_model/list_block.rb +137 -0
  42. data/lib/coridoc/core_model/list_item.rb +129 -0
  43. data/lib/coridoc/core_model/listing_block.rb +19 -0
  44. data/lib/coridoc/core_model/literal_block.rb +16 -0
  45. data/lib/coridoc/core_model/metadata.rb +71 -0
  46. data/lib/coridoc/core_model/open_block.rb +12 -0
  47. data/lib/coridoc/core_model/output_artifact.rb +48 -0
  48. data/lib/coridoc/core_model/paragraph_block.rb +16 -0
  49. data/lib/coridoc/core_model/partintro_block.rb +11 -0
  50. data/lib/coridoc/core_model/pass_block.rb +16 -0
  51. data/lib/coridoc/core_model/quote_block.rb +14 -0
  52. data/lib/coridoc/core_model/raw_inline_element.rb +16 -0
  53. data/lib/coridoc/core_model/reviewer_block.rb +12 -0
  54. data/lib/coridoc/core_model/sidebar_block.rb +12 -0
  55. data/lib/coridoc/core_model/source_block.rb +16 -0
  56. data/lib/coridoc/core_model/stem_block.rb +25 -0
  57. data/lib/coridoc/core_model/structural_element.rb +157 -0
  58. data/lib/coridoc/core_model/table.rb +148 -0
  59. data/lib/coridoc/core_model/term.rb +53 -0
  60. data/lib/coridoc/core_model/text_content.rb +26 -0
  61. data/lib/coridoc/core_model/toc.rb +99 -0
  62. data/lib/coridoc/core_model/toc_generator.rb +151 -0
  63. data/lib/coridoc/core_model/verse_block.rb +14 -0
  64. data/lib/coridoc/core_model.rb +92 -0
  65. data/lib/coridoc/coridoc.rb +164 -0
  66. data/lib/coridoc/dispatch.rb +96 -0
  67. data/lib/coridoc/errors.rb +387 -0
  68. data/lib/coridoc/format_catalog.rb +102 -0
  69. data/lib/coridoc/format_module.rb +78 -0
  70. data/lib/coridoc/hooks.rb +176 -0
  71. data/lib/coridoc/include_resolver/filesystem.rb +84 -0
  72. data/lib/coridoc/include_resolver.rb +67 -0
  73. data/lib/coridoc/include_selectors/indent.rb +54 -0
  74. data/lib/coridoc/include_selectors/level_offset.rb +84 -0
  75. data/lib/coridoc/include_selectors/lines.rb +60 -0
  76. data/lib/coridoc/include_selectors/tags.rb +136 -0
  77. data/lib/coridoc/include_selectors.rb +26 -0
  78. data/lib/coridoc/introspection/element_counter.rb +48 -0
  79. data/lib/coridoc/introspection.rb +72 -0
  80. data/lib/coridoc/link_rewriter/identity.rb +13 -0
  81. data/lib/coridoc/link_rewriter/visitor.rb +148 -0
  82. data/lib/coridoc/link_rewriter.rb +37 -0
  83. data/lib/coridoc/lint/registry.rb +33 -0
  84. data/lib/coridoc/lint/rule.rb +41 -0
  85. data/lib/coridoc/lint/runner.rb +67 -0
  86. data/lib/coridoc/lint/template.rb +190 -0
  87. data/lib/coridoc/lint/violation.rb +16 -0
  88. data/lib/coridoc/lint.rb +44 -0
  89. data/lib/coridoc/logger.rb +54 -0
  90. data/lib/coridoc/performance_regression.rb +121 -0
  91. data/lib/coridoc/pipeline.rb +169 -0
  92. data/lib/coridoc/query.rb +486 -0
  93. data/lib/coridoc/reference/address/anchor.rb +48 -0
  94. data/lib/coridoc/reference/address/doi.rb +40 -0
  95. data/lib/coridoc/reference/address/isbn.rb +39 -0
  96. data/lib/coridoc/reference/address/path.rb +66 -0
  97. data/lib/coridoc/reference/address/scoped_path.rb +47 -0
  98. data/lib/coridoc/reference/address/url.rb +41 -0
  99. data/lib/coridoc/reference/address.rb +153 -0
  100. data/lib/coridoc/reference/catalog/composite.rb +59 -0
  101. data/lib/coridoc/reference/catalog/local.rb +97 -0
  102. data/lib/coridoc/reference/catalog/memory_index.rb +59 -0
  103. data/lib/coridoc/reference/catalog.rb +33 -0
  104. data/lib/coridoc/reference/edge/citation_options.rb +16 -0
  105. data/lib/coridoc/reference/edge/footnote_ref_options.rb +13 -0
  106. data/lib/coridoc/reference/edge/image_ref_options.rb +15 -0
  107. data/lib/coridoc/reference/edge/include_options.rb +15 -0
  108. data/lib/coridoc/reference/edge/kind.rb +72 -0
  109. data/lib/coridoc/reference/edge/link_options.rb +12 -0
  110. data/lib/coridoc/reference/edge/navigation_options.rb +12 -0
  111. data/lib/coridoc/reference/edge/options.rb +13 -0
  112. data/lib/coridoc/reference/edge.rb +80 -0
  113. data/lib/coridoc/reference/edge_search.rb +128 -0
  114. data/lib/coridoc/reference/materializer/base.rb +44 -0
  115. data/lib/coridoc/reference/materializer/passthrough.rb +31 -0
  116. data/lib/coridoc/reference/materializer/registry.rb +116 -0
  117. data/lib/coridoc/reference/materializer.rb +14 -0
  118. data/lib/coridoc/reference/presentation/base.rb +47 -0
  119. data/lib/coridoc/reference/presentation/custom_hierarchy.rb +104 -0
  120. data/lib/coridoc/reference/presentation/page.rb +20 -0
  121. data/lib/coridoc/reference/presentation/single_document.rb +35 -0
  122. data/lib/coridoc/reference/presentation/split_pages.rb +118 -0
  123. data/lib/coridoc/reference/presentation.rb +16 -0
  124. data/lib/coridoc/reference/resolution.rb +184 -0
  125. data/lib/coridoc/reference/resolver/base.rb +15 -0
  126. data/lib/coridoc/reference/resolver/caching.rb +37 -0
  127. data/lib/coridoc/reference/resolver/catalog.rb +69 -0
  128. data/lib/coridoc/reference/resolver/chain.rb +33 -0
  129. data/lib/coridoc/reference/resolver.rb +20 -0
  130. data/lib/coridoc/reference/result/ambiguous.rb +23 -0
  131. data/lib/coridoc/reference/result/base.rb +46 -0
  132. data/lib/coridoc/reference/result/missing.rb +14 -0
  133. data/lib/coridoc/reference/result/resolved.rb +22 -0
  134. data/lib/coridoc/reference/result.rb +20 -0
  135. data/lib/coridoc/reference.rb +65 -0
  136. data/lib/coridoc/registry.rb +156 -0
  137. data/lib/coridoc/relative_path.rb +32 -0
  138. data/lib/coridoc/resolve_includes.rb +202 -0
  139. data/lib/coridoc/source_graph/file_node.rb +147 -0
  140. data/lib/coridoc/source_graph/graph.rb +165 -0
  141. data/lib/coridoc/source_graph/include_edges.rb +33 -0
  142. data/lib/coridoc/source_graph/sidecar.rb +97 -0
  143. data/lib/coridoc/source_graph.rb +36 -0
  144. data/lib/coridoc/validation.rb +686 -0
  145. data/lib/coridoc/version.rb +5 -0
  146. data/lib/coridoc/visitor.rb +283 -0
  147. data/lib/coridoc.rb +41 -0
  148. metadata +221 -0
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Coridoc
6
+ module Hooks
7
+ HOOK_POINTS = {
8
+ before_parse: 'Called before parsing text content. Receives (content, format:, **options). Should return modified content.',
9
+ after_parse: 'Called after parsing. Receives (model, format:, **options). Should return modified model.',
10
+ before_transform: 'Called before transforming model. Receives (model, direction:, **options). Should return modified model.',
11
+ after_transform: 'Called after transforming model. Receives (model, direction:, **options). Should return modified model.',
12
+ before_serialize: 'Called before serializing model. Receives (model, format:, **options). Should return modified model.',
13
+ after_serialize: 'Called after serializing. Receives (output, format:, **options). Should return modified output.',
14
+ on_error: 'Called when an error occurs. Receives (error, context). Can re-raise or return fallback value.'
15
+ }.freeze
16
+
17
+ class << self
18
+ attr_accessor :strict_mode
19
+
20
+ def register(hook_point, priority: 100, name: nil, &block)
21
+ validate_hook_point!(hook_point)
22
+ validate_block!(block, hook_point)
23
+
24
+ hook_id = name || generate_hook_id(hook_point)
25
+ registry[hook_point] ||= []
26
+ registry[hook_point] << {
27
+ id: hook_id,
28
+ priority: priority,
29
+ sequence: next_sequence,
30
+ callback: block
31
+ }
32
+ registry[hook_point].sort_by! { |h| [h[:priority], h[:sequence]] }
33
+ hook_id
34
+ end
35
+
36
+ def remove(hook_point, hook_id)
37
+ validate_hook_point!(hook_point)
38
+ return false unless registry[hook_point]
39
+
40
+ original_size = registry[hook_point].size
41
+ registry[hook_point].reject! { |h| h[:id] == hook_id }
42
+ registry[hook_point].size < original_size
43
+ end
44
+
45
+ def clear(hook_point)
46
+ validate_hook_point!(hook_point)
47
+ removed = registry[hook_point]&.size || 0
48
+ registry.delete(hook_point)
49
+ removed
50
+ end
51
+
52
+ def clear_all
53
+ total = registry.values.sum(&:size)
54
+ @registry = {}
55
+ @sequence_counter = nil
56
+ total
57
+ end
58
+
59
+ def registered?(hook_point)
60
+ validate_hook_point!(hook_point)
61
+ registry[hook_point]&.any? || false
62
+ end
63
+
64
+ def list(hook_point = nil)
65
+ if hook_point
66
+ validate_hook_point!(hook_point)
67
+ registry[hook_point]&.map { |h| h.merge(point: hook_point) } || []
68
+ else
69
+ registry.flat_map do |point, hooks|
70
+ hooks.map { |h| h.merge(point: point) }
71
+ end
72
+ end
73
+ end
74
+
75
+ def invoke(hook_point, *args, **kwargs)
76
+ validate_hook_point!(hook_point)
77
+ return args.first if args.one? && !registry[hook_point]&.any?
78
+
79
+ result = args.first
80
+ registry[hook_point].each do |hook|
81
+ result = invoke_hook(hook[:callback], result, args, kwargs)
82
+ end
83
+ result
84
+ end
85
+
86
+ def with_hooks(hook_point, *args, **kwargs)
87
+ validate_hook_point!(hook_point)
88
+
89
+ modified_args = invoke(hook_point, *args, **kwargs)
90
+ result = yield(*modified_args)
91
+
92
+ after_point = :"after_#{hook_point.to_s.sub('before_', '')}"
93
+ result = invoke(after_point, result, **kwargs) if HOOK_POINTS.key?(after_point)
94
+
95
+ result
96
+ rescue StandardError => e
97
+ invoke_error_hooks(e, hook_point, args, kwargs)
98
+ end
99
+
100
+ def documentation(hook_point = nil)
101
+ if hook_point
102
+ validate_hook_point!(hook_point)
103
+ HOOK_POINTS[hook_point]
104
+ else
105
+ HOOK_POINTS.dup
106
+ end
107
+ end
108
+
109
+ private
110
+
111
+ def registry
112
+ @registry ||= {}
113
+ end
114
+
115
+ def next_sequence
116
+ @sequence_counter = (@sequence_counter || 0) + 1
117
+ end
118
+
119
+ def validate_hook_point!(hook_point)
120
+ return if HOOK_POINTS.key?(hook_point)
121
+
122
+ valid_points = HOOK_POINTS.keys.join(', ')
123
+ raise ArgumentError,
124
+ "Unknown hook point: #{hook_point}. Valid points: #{valid_points}"
125
+ end
126
+
127
+ def validate_block!(block, hook_point)
128
+ return if block
129
+
130
+ raise ArgumentError,
131
+ "Block required for hook registration: #{hook_point}"
132
+ end
133
+
134
+ def generate_hook_id(hook_point)
135
+ "#{hook_point}_#{SecureRandom.hex(8)}"
136
+ end
137
+
138
+ def invoke_hook(callback, result, _args, kwargs)
139
+ arity = callback.arity
140
+
141
+ if kwargs.empty?
142
+ case arity
143
+ when 0
144
+ callback.call
145
+ else
146
+ callback.call(result)
147
+ end
148
+ else
149
+ callback.call(result, **kwargs)
150
+ end
151
+ rescue StandardError => e
152
+ raise if @strict_mode
153
+
154
+ Coridoc::Logger.warn("Hook failed: #{e.message}")
155
+ result
156
+ end
157
+
158
+ def invoke_error_hooks(error, hook_point, args, kwargs)
159
+ context = {
160
+ hook_point: hook_point,
161
+ args: args,
162
+ kwargs: kwargs
163
+ }
164
+
165
+ if registry[:on_error]&.any?
166
+ registry[:on_error].each do |hook|
167
+ result = hook[:callback].call(error, context)
168
+ return result if result
169
+ end
170
+ end
171
+
172
+ raise error
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+
5
+ module Coridoc
6
+ class IncludeResolver
7
+ # Default include resolver: reads files from the local filesystem,
8
+ # rooted at +base_dir+. Path-traversal protection is ON by default
9
+ # to match asciidoctor's +:safe+ mode.
10
+ #
11
+ # Pass +allow_unsafe: true+ to opt out (matches +:unsafe+ mode).
12
+ class Filesystem < IncludeResolver
13
+ attr_reader :base_dir, :allow_unsafe, :max_bytes
14
+
15
+ # @param base_dir [String] absolute path to the directory includes
16
+ # are resolved against. Usually the directory of the including
17
+ # document. Relative paths inside the resolver are expanded
18
+ # against this.
19
+ # @param allow_unsafe [Boolean] when false (default), refuses any
20
+ # resolved path that escapes +base_dir+ via .. or that is an
21
+ # absolute path outside +base_dir+.
22
+ # @param max_bytes [Integer, nil] if set, refuses files larger
23
+ # than this. Defense against accidental megabyte-include loops.
24
+ def initialize(base_dir:, allow_unsafe: false, max_bytes: nil)
25
+ @base_dir = File.expand_path(base_dir)
26
+ @allow_unsafe = allow_unsafe
27
+ @max_bytes = max_bytes
28
+ end
29
+
30
+ def call(target:, base_dir:, options:, context:)
31
+ full = File.expand_path(target, base_dir)
32
+ enforce_safety!(full, base_dir) unless allow_unsafe
33
+ raise Coridoc::IncludeNotFoundError, target unless File.file?(full)
34
+
35
+ enforce_size!(full, target)
36
+
37
+ encoding = options&.file_encoding || 'utf-8'
38
+ read_with_encoding(full, encoding)
39
+ end
40
+
41
+ private
42
+
43
+ def enforce_safety!(full_path, base_dir)
44
+ base_expanded = File.expand_path(base_dir)
45
+ base_with_sep = "#{base_expanded}#{File::SEPARATOR}"
46
+
47
+ return if full_path == base_expanded || full_path.start_with?(base_with_sep)
48
+
49
+ raise Coridoc::UnsafeIncludeError, full_path
50
+ end
51
+
52
+ def enforce_size!(full_path, target)
53
+ return unless max_bytes
54
+ return unless File.exist?(full_path)
55
+
56
+ size = File.size(full_path)
57
+ return if size <= max_bytes
58
+
59
+ raise Coridoc::IncludeTooLargeError, target
60
+ end
61
+
62
+ def read_with_encoding(full_path, encoding_name)
63
+ content = File.binread(full_path)
64
+ return content if encoding_name.to_s.downcase == 'binary'
65
+
66
+ content.force_encoding(clean_encoding_name(encoding_name))
67
+ encoded = content.encode('utf-8', invalid: :replace, undef: :replace)
68
+ normalize_line_endings(encoded)
69
+ rescue ArgumentError => e
70
+ raise Coridoc::Error, "Unsupported encoding #{encoding_name.inspect}: #{e.message}"
71
+ end
72
+
73
+ # asciidoctor parity: normalize CRLF and lone CR to LF so the parser
74
+ # sees consistent line endings regardless of the source platform.
75
+ def normalize_line_endings(text)
76
+ text.gsub(/\r\n?/, "\n")
77
+ end
78
+
79
+ def clean_encoding_name(name)
80
+ name.to_s.downcase.sub(/^utf-8$/, 'utf-8')
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # Include resolver protocol.
5
+ #
6
+ # A resolver is anything that responds to +#call(target:, base_dir:,
7
+ # options:, context:)+ and returns the raw bytes of the included
8
+ # target, BEFORE tag/line/indent selectors are applied. Selectors
9
+ # live in the processor; the resolver only fetches bytes.
10
+ #
11
+ # The default resolver is {IncludeResolver::Filesystem}. Custom
12
+ # resolvers (HTTP, database, generated) plug in here without changes
13
+ # to the processor (OCP).
14
+ #
15
+ # Contract:
16
+ # call(target:, base_dir:, options:, context:) -> String
17
+ # target String path/URL as authored
18
+ # base_dir String absolute path to the including file's dir
19
+ # options CoreModel::IncludeOptions
20
+ # context Hash recursion state (depth, parent_chain, ...)
21
+ #
22
+ # Raises Coridoc::IncludeNotFoundError if the target cannot be located.
23
+ # The processor's missing-file policy decides what to do with that.
24
+ #
25
+ # This base class is provided for documentation and for is_a? checks.
26
+ # Custom resolvers do NOT need to inherit — duck typing on the call
27
+ # signature is sufficient. ( SPEC 13 uses a bare Object with
28
+ # define_singleton_method, which we support.)
29
+ class IncludeResolver
30
+ autoload :Filesystem, "#{__dir__}/include_resolver/filesystem"
31
+
32
+ def call(target:, base_dir:, options:, context:)
33
+ raise NotImplementedError,
34
+ "#{self.class} must implement #call(target:, base_dir:, options:, context:)"
35
+ end
36
+
37
+ class << self
38
+ # Coerce +value+ into something that quacks like an IncludeResolver.
39
+ # - Already-callable objects (respond to :call) are returned as-is.
40
+ # - Symbols are interpreted as built-in names: +:filesystem+,
41
+ # +:filesystem_strict+ (path-traversal protection on).
42
+ #
43
+ # @param value [Object, nil] the resolver or built-in name
44
+ # @param base_dir [String] required for built-in filesystem resolvers
45
+ # @param allow_unsafe [Boolean] opt-out of path-traversal protection
46
+ # @return [Object] something callable as a resolver
47
+ def coerce(value, base_dir:, allow_unsafe: false)
48
+ return Filesystem.new(base_dir: base_dir, allow_unsafe: allow_unsafe) if value.nil?
49
+
50
+ case value
51
+ when Symbol then coerce_symbol(value, base_dir: base_dir, allow_unsafe: allow_unsafe)
52
+ else value
53
+ end
54
+ end
55
+
56
+ private
57
+
58
+ def coerce_symbol(name, base_dir:, allow_unsafe:)
59
+ case name
60
+ when :filesystem then Filesystem.new(base_dir: base_dir, allow_unsafe: allow_unsafe)
61
+ else
62
+ raise ArgumentError, "Unknown include resolver: #{name.inspect}"
63
+ end
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module IncludeSelectors
5
+ # Indent normalization. Two modes per asciidoctor:
6
+ #
7
+ # indent=0 strip all leading whitespace from every line
8
+ # indent=N normalize leading whitespace to exactly N spaces
9
+ # nil pass through unchanged
10
+ module Indent
11
+ # @param text [String]
12
+ # @param options [Coridoc::CoreModel::IncludeOptions]
13
+ # @return [String]
14
+ def self.call(text, options:)
15
+ return text if options.indent.nil?
16
+
17
+ if options.indent.zero?
18
+ strip_all(text)
19
+ else
20
+ reindent(text, options.indent)
21
+ end
22
+ end
23
+
24
+ class << self
25
+ private
26
+
27
+ def strip_all(text)
28
+ text.lines.map { |line| line.sub(/\A[[:space:]]+/, '') }.join
29
+ end
30
+
31
+ def reindent(text, target)
32
+ min_indent = text.lines
33
+ .reject { |l| l.strip.empty? }
34
+ .map { |l| l.length - l.lstrip.length }
35
+ .min || 0
36
+
37
+ pad = ' ' * target
38
+ text.lines.map do |line|
39
+ stripped = strip_common_prefix(line, min_indent)
40
+ if stripped.strip.empty?
41
+ stripped.strip + "\n"
42
+ else
43
+ pad + stripped
44
+ end
45
+ end.join
46
+ end
47
+
48
+ def strip_common_prefix(line, count)
49
+ line.sub(/\A[[:space:]]{0,#{count}}/, '')
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module IncludeSelectors
5
+ # Shifts section heading levels in a parsed CoreModel subtree.
6
+ #
7
+ # Applied AFTER parsing — works on SectionElement instances. Two modes:
8
+ #
9
+ # relative (+N / -N) every SectionElement#level += delta
10
+ # absolute (N) the FIRST section's level becomes N, and
11
+ # descendants shift by the same delta so their
12
+ # relative structure is preserved (asciidoctor
13
+ # behavior).
14
+ #
15
+ # The processor passes a freshly-parsed subtree to this selector, so
16
+ # there are no external references and in-place mutation is safe.
17
+ module LevelOffset
18
+ # @param core [Coridoc::CoreModel::Base] freshly parsed — mutated
19
+ # @param options [Coridoc::CoreModel::IncludeOptions]
20
+ # @return [Coridoc::CoreModel::Base] the same core (mutated)
21
+ def self.call(core, options:)
22
+ offset = options.leveloffset
23
+ return core if offset.nil?
24
+
25
+ first_level = find_first_level(core)
26
+ actual_delta = compute_actual_delta(offset, first_level)
27
+ return core if actual_delta.zero?
28
+
29
+ walk_and_shift(core, actual_delta)
30
+ core
31
+ end
32
+
33
+ class << self
34
+ private
35
+
36
+ def compute_actual_delta(offset, first_level)
37
+ case offset.mode
38
+ when 'relative' then offset.delta
39
+ when 'absolute'
40
+ return 0 if first_level.nil?
41
+
42
+ offset.delta - first_level
43
+ else 0
44
+ end
45
+ end
46
+
47
+ def find_first_level(node)
48
+ case node
49
+ when Coridoc::CoreModel::SectionElement
50
+ node.level || 1
51
+ when Coridoc::CoreModel::StructuralElement, Coridoc::CoreModel::Block
52
+ walk_for_first_level(node.children)
53
+ end
54
+ end
55
+
56
+ def walk_for_first_level(children)
57
+ return nil if children.nil?
58
+
59
+ children.each do |child|
60
+ lvl = find_first_level(child)
61
+ return lvl unless lvl.nil?
62
+ end
63
+ nil
64
+ end
65
+
66
+ def walk_and_shift(node, delta)
67
+ case node
68
+ when Coridoc::CoreModel::SectionElement
69
+ node.level = [(node.level || 1) + delta, 0].max
70
+ walk_children(node, delta)
71
+ when Coridoc::CoreModel::StructuralElement, Coridoc::CoreModel::Block
72
+ walk_children(node, delta)
73
+ end
74
+ end
75
+
76
+ def walk_children(node, delta)
77
+ return if node.children.nil?
78
+
79
+ node.children.each { |c| walk_and_shift(c, delta) }
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module IncludeSelectors
5
+ # Line-range selection. Parses asciidoctor-style specs:
6
+ #
7
+ # N single line
8
+ # A..B inclusive range
9
+ # A..B;C;D..E multiple, semicolon-separated
10
+ #
11
+ # Out-of-bounds clamps gracefully (SPEC 3.4). One-based indexing
12
+ # (asciidoctor convention).
13
+ module Lines
14
+ SPEC_PART = /
15
+ \A
16
+ (?<start>\d+)
17
+ (?:\.\.(?<finish>\d+))?
18
+ \z
19
+ /x
20
+
21
+ # @param text [String]
22
+ # @param options [Coridoc::CoreModel::IncludeOptions]
23
+ # @return [String]
24
+ def self.call(text, options:)
25
+ return text unless options.lines?
26
+
27
+ ranges = parse_spec(options.lines_spec, max: text.lines.length)
28
+ return '' if ranges.empty?
29
+
30
+ indices = ranges.flat_map { |start, finish| (start..finish).to_a }.uniq.sort
31
+ text.lines.values_at(*indices.map { |i| i - 1 }).join
32
+ end
33
+
34
+ class << self
35
+ private
36
+
37
+ def parse_spec(spec, max:)
38
+ spec.split(';').map(&:strip).filter_map do |part|
39
+ parse_part(part, max: max)
40
+ end
41
+ end
42
+
43
+ def parse_part(part, max:)
44
+ SPEC_PART.match(part) do |m|
45
+ start = m[:start].to_i
46
+ finish = m[:finish] ? m[:finish].to_i : start
47
+ [start, finish].minmax.map { |n| clamp(n, max: max) }
48
+ end
49
+ end
50
+
51
+ def clamp(n, max:)
52
+ return nil if n < 1
53
+ return max if n > max
54
+
55
+ n
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ module IncludeSelectors
5
+ # Extracts regions delimited by +// tag::name[]+ / +// end::name[]+
6
+ # markers from included content. Supports single, multiple,
7
+ # wildcard (*), and inverted (**) selection.
8
+ #
9
+ # Tag markers themselves are never emitted as text (SPEC 2.8).
10
+ # Unknown tag names yield empty content (SPEC 2.6). Nested tag
11
+ # regions are included when an outer tag is selected (SPEC 2.7).
12
+ #
13
+ # Marker forms recognized:
14
+ # // tag::name[] (AsciiDoc line comment)
15
+ # ## tag::name[] (Markdown line comment, permissive)
16
+ #
17
+ # Markers may appear on their own line; they must be the first
18
+ # non-whitespace token on that line (asciidoctor convention).
19
+ module Tags
20
+ MARKER_OPEN = %r{\A[[:space:]]*(?://+|#+)[[:space:]]*tag::([^\[\]]+)\[[[:space:]]*\]}
21
+ MARKER_CLOSE = %r{\A[[:space:]]*(?://+|#+)[[:space:]]*end::([^\[\]]+)\[[[:space:]]*\]}
22
+
23
+ # @param text [String] raw included file content
24
+ # @param options [Coridoc::CoreModel::IncludeOptions]
25
+ # @return [String] filtered content
26
+ def self.call(text, options:)
27
+ return text unless options.tags?
28
+
29
+ if options.tags_inverted
30
+ inverted(text)
31
+ elsif options.tags_wildcard
32
+ wildcard(text)
33
+ else
34
+ named(text, options.tags)
35
+ end
36
+ end
37
+
38
+ class << self
39
+ private
40
+
41
+ def scan_markers(text)
42
+ markers = []
43
+ text.each_line.with_index do |line, idx|
44
+ if (m = MARKER_OPEN.match(line))
45
+ markers << [:open, m[1].strip, idx]
46
+ elsif (m = MARKER_CLOSE.match(line))
47
+ markers << [:close, m[1].strip, idx]
48
+ end
49
+ end
50
+ markers
51
+ end
52
+
53
+ def named(text, names)
54
+ wanted_indices = selected_line_indices(text, names).to_set
55
+ pick_lines(text, wanted_indices)
56
+ end
57
+
58
+ def selected_line_indices(text, wanted_names)
59
+ markers = scan_markers(text)
60
+ wanted = wanted_names.to_set
61
+ open_stack = []
62
+ emit = {}
63
+
64
+ markers.each do |kind, name, idx|
65
+ case kind
66
+ when :open
67
+ next unless wanted.include?(name)
68
+
69
+ open_stack.push([name, idx])
70
+ when :close
71
+ next unless wanted.include?(name)
72
+
73
+ open_idx = open_stack.rindex { |n, _| n == name }
74
+ next unless open_idx
75
+
76
+ _open_name, open_line = open_stack.delete_at(open_idx)
77
+ (open_line + 1...idx).each { |i| emit[i] = true }
78
+ end
79
+ end
80
+
81
+ emit.keys
82
+ end
83
+
84
+ def wildcard(text)
85
+ markers = scan_markers(text)
86
+ open_stack = []
87
+ emit = {}
88
+
89
+ markers.each do |kind, _name, idx|
90
+ case kind
91
+ when :open
92
+ open_stack.push(idx)
93
+ when :close
94
+ next if open_stack.empty?
95
+
96
+ open_line = open_stack.pop
97
+ (open_line + 1...idx).each { |i| emit[i] = true }
98
+ end
99
+ end
100
+
101
+ pick_lines(text, emit.keys.to_set)
102
+ end
103
+
104
+ def inverted(text)
105
+ markers = scan_markers(text)
106
+ open_stack = []
107
+ excluded = {}
108
+
109
+ markers.each do |kind, _name, idx|
110
+ case kind
111
+ when :open
112
+ open_stack.push(idx)
113
+ when :close
114
+ next if open_stack.empty?
115
+
116
+ open_line = open_stack.pop
117
+ (open_line..idx).each { |i| excluded[i] = true }
118
+ end
119
+ end
120
+
121
+ markers.each { |_kind, _name, idx| excluded[idx] = true }
122
+
123
+ lines = text.lines
124
+ kept = lines.each_with_index.reject { |_line, idx| excluded[idx] }
125
+ kept.map(&:first).join
126
+ end
127
+
128
+ def pick_lines(text, wanted_indices)
129
+ lines = text.lines
130
+ lines.each_with_index.select { |_line, idx| wanted_indices.include?(idx) }
131
+ .map(&:first).join
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # Pure-function selectors applied to resolved include content.
5
+ #
6
+ # Each selector owns exactly one transformation (MECE):
7
+ # Tags // tag::X[] ... // end::X[] region extraction
8
+ # Lines line-range selection (1..N;2;3..4)
9
+ # Indent leading-whitespace normalization
10
+ # LevelOffset section-level shift (applied AFTER parsing)
11
+ #
12
+ # Tags, Lines, and Indent take a String and return a String.
13
+ # LevelOffset takes a parsed CoreModel and returns a new CoreModel.
14
+ #
15
+ # The processor orchestrates the order:
16
+ # 1. Tags (or Lines; Lines wins if both specified — SPEC 3.5)
17
+ # 2. Indent
18
+ # 3. parse → CoreModel
19
+ # 4. LevelOffset
20
+ module IncludeSelectors
21
+ autoload :Tags, "#{__dir__}/include_selectors/tags"
22
+ autoload :Lines, "#{__dir__}/include_selectors/lines"
23
+ autoload :Indent, "#{__dir__}/include_selectors/indent"
24
+ autoload :LevelOffset, "#{__dir__}/include_selectors/level_offset"
25
+ end
26
+ end