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,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # General-purpose named-item registry.
5
+ #
6
+ # Used by the format registry (Coridoc.registry), Input processors,
7
+ # and Output processors. Each instance stores items keyed by symbol
8
+ # name, with optional per-item options.
9
+ #
10
+ # @example Format registry
11
+ # registry = Registry.new
12
+ # registry.register(:html, Coridoc::Html)
13
+ # registry.get(:html) # => Coridoc::Html
14
+ #
15
+ # @example Processor registry (self-identifying items)
16
+ # registry = Registry.new(error_label: "input processor")
17
+ # registry.define(MyProcessor) # uses MyProcessor.processor_id
18
+ # registry.for_file("doc.html") # checks processor_match? on each item
19
+ #
20
+ class Registry
21
+ attr_reader :error_label
22
+
23
+ # @param error_label [String, nil] label for error messages in #process
24
+ def initialize(error_label: nil)
25
+ @items = {}
26
+ @options = {}
27
+ @error_label = error_label
28
+ end
29
+
30
+ # Register an item by explicit name
31
+ #
32
+ # @param name [Symbol] the item name
33
+ # @param item [Object] the item to register
34
+ # @param opts [Hash] optional per-item configuration
35
+ # @raise [ArgumentError] if name is not a Symbol
36
+ def register(name, item, opts = {})
37
+ raise ArgumentError, "Name must be a Symbol, got #{name.class}" unless name.is_a?(Symbol)
38
+
39
+ @items[name] = item
40
+ @options[name] = opts
41
+ end
42
+
43
+ # Register a self-identifying item (extracts name via processor_id)
44
+ #
45
+ # @param item [Object] item that responds to #processor_id
46
+ # @param options [Hash] optional per-item configuration
47
+ # @return [void]
48
+ def define(item, **opts)
49
+ register(item.processor_id, item, opts)
50
+ end
51
+
52
+ # Get a registered item by name
53
+ #
54
+ # @param name [Symbol, String] the item name (strings are coerced to symbols)
55
+ # @return [Object, nil]
56
+ def get(name)
57
+ @items[name.to_sym]
58
+ end
59
+ alias [] get
60
+
61
+ # Get options for a registered item
62
+ #
63
+ # @param name [Symbol]
64
+ # @return [Hash, nil]
65
+ def options_for(name)
66
+ @options[name]
67
+ end
68
+
69
+ # Check if an item is registered
70
+ #
71
+ # @param name [Symbol]
72
+ # @return [Boolean]
73
+ def registered?(name)
74
+ @items.key?(name)
75
+ end
76
+
77
+ # List all registered item names
78
+ #
79
+ # @return [Array<Symbol>]
80
+ def list
81
+ @items.keys
82
+ end
83
+
84
+ # Direct access to the items hash (for backward compatibility)
85
+ # @return [Hash<Symbol, Object>]
86
+ attr_reader :items
87
+
88
+ # Number of registered items
89
+ #
90
+ # @return [Integer]
91
+ def size
92
+ @items.size
93
+ end
94
+
95
+ # Remove all registered items
96
+ def clear
97
+ @items.clear
98
+ @options.clear
99
+ end
100
+
101
+ # Iterate over all items
102
+ #
103
+ # @yield [Symbol, Object] name and item
104
+ # @return [Enumerator]
105
+ def each(&)
106
+ @items.each(&)
107
+ end
108
+
109
+ # Iterate over item values
110
+ #
111
+ # @yield [Object]
112
+ # @return [Enumerator]
113
+ def each_value(&)
114
+ @items.each_value(&)
115
+ end
116
+
117
+ # Iterate over item names
118
+ #
119
+ # @yield [Symbol]
120
+ # @return [Enumerator]
121
+ def each_key(&)
122
+ @items.each_key(&)
123
+ end
124
+
125
+ # Find an item whose processor_match? returns true for the given filename
126
+ #
127
+ # @param filename [String]
128
+ # @return [Object, nil]
129
+ def for_file(filename)
130
+ @items.values.find do |item|
131
+ item.processor_match?(filename)
132
+ rescue NoMethodError
133
+ false
134
+ end
135
+ end
136
+
137
+ # Resolve and execute: find item by format or filename, call processor_execute
138
+ #
139
+ # @param content [Object] content to process
140
+ # @param options [Hash] :format or :filename for resolution
141
+ # @return [Object] result of processor_execute
142
+ # @raise [ArgumentError] if no matching item found
143
+ def process(content, options = {})
144
+ item = if options[:format]
145
+ get(options[:format])
146
+ elsif options[:filename]
147
+ for_file(options[:filename])
148
+ end
149
+
150
+ label = @error_label || 'processor'
151
+ raise ArgumentError, "No #{label} found for: #{options}" unless item
152
+
153
+ item.processor_execute(content, options)
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # Pure-function module for relative-path arithmetic across output keys.
5
+ #
6
+ # Every SSG wrapper (VitePress, Hugo, Astro) needs to compute "how many
7
+ # directories up do I walk to reach the site root from this output?".
8
+ # The answer is the segment count of the source output_key. Everything
9
+ # else (template, imports) is host-system-specific; this module owns
10
+ # only the one piece of arithmetic that is genuinely shared.
11
+ #
12
+ # No state. No class. No knowledge of any specific SSG.
13
+ #
14
+ # @example Compute a VitePress import path
15
+ # Coridoc::RelativePath.from("author/iso/ref/foo", to: ".vitepress/theme")
16
+ # # => "../../../.vitepress/theme"
17
+ module RelativePath
18
+ module_function
19
+
20
+ # Compute a relative path from an output_key to a site-root-relative
21
+ # target.
22
+ #
23
+ # @param output_key [String, nil] site-relative key for the source
24
+ # page (e.g. "author/iso/ref/foo"). No leading slash, no extension.
25
+ # @param to [String] destination path relative to the site root.
26
+ # @return [String] the composed relative path.
27
+ def from(output_key, to:)
28
+ depth = output_key.to_s.count('/')
29
+ ('../' * depth) + to.to_s
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,202 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # Flat-mode include processor — the explicit "flatten" step.
5
+ #
6
+ # Walks a parsed CoreModel and expands every {CoreModel::Include} link
7
+ # node into the parsed content of its target, recursing into the result.
8
+ # The original CoreModel is NOT modified — a new subtree is constructed
9
+ # and spliced into place.
10
+ #
11
+ # Invoked via the public API +Coridoc.resolve_includes(doc, base_dir:)+.
12
+ # Callers control resolution strategy (filesystem, HTTP, custom),
13
+ # missing-include policy, recursion depth, and path-traversal safety.
14
+ #
15
+ # Honors:
16
+ # - +missing_include+ policy: :error (default) | :warn | :silent | :passthrough
17
+ # - +max_depth+ limit (raises Coridoc::IncludeDepthExceededError)
18
+ # - circular detection (raises Coridoc::CircularIncludeError)
19
+ # - tags/lines/indent selectors (applied to raw text before parse)
20
+ # - leveloffset selector (applied to parsed CoreModel)
21
+ # - +base_dir+ re-rooting (recursive includes resolve relative to
22
+ # the including file — SPEC 7.2)
23
+ class ResolveIncludes
24
+ DEFAULT_MAX_DEPTH = 64
25
+
26
+ class << self
27
+ def call(core, resolver:, base_dir:, **)
28
+ new(resolver: resolver, base_dir: base_dir, **).call(core)
29
+ end
30
+ end
31
+
32
+ # @param resolver [#call] anything responding to +#call(target:, base_dir:, options:, context:)+
33
+ # @param base_dir [String] absolute path to the document root directory
34
+ # @param missing_include [Symbol] :error | :warn | :silent | :passthrough
35
+ # @param max_depth [Integer] recursion cap
36
+ # @param parse_format [Symbol] format to use when re-parsing included content
37
+ def initialize(resolver:, base_dir:,
38
+ missing_include: :error,
39
+ max_depth: DEFAULT_MAX_DEPTH,
40
+ parse_format: :asciidoc)
41
+ @resolver = Coridoc::IncludeResolver.coerce(resolver, base_dir: base_dir)
42
+ @base_dir = base_dir
43
+ @missing_policy = missing_include
44
+ @max_depth = max_depth
45
+ @parse_format = parse_format
46
+ end
47
+
48
+ # Walk + transform. Returns a NEW CoreModel with includes expanded.
49
+ def call(core)
50
+ expand_node(core, base_dir: File.expand_path(@base_dir), chain: [], depth: 0)
51
+ end
52
+
53
+ private
54
+
55
+ def expand_node(node, base_dir:, chain:, depth:)
56
+ return node unless node.is_a?(Coridoc::CoreModel::Base)
57
+
58
+ case node
59
+ when Coridoc::CoreModel::Include
60
+ expand_include(node, base_dir: base_dir, chain: chain, depth: depth)
61
+ when Coridoc::CoreModel::StructuralElement, Coridoc::CoreModel::Block
62
+ expand_container(node, base_dir: base_dir, chain: chain, depth: depth)
63
+ else
64
+ node
65
+ end
66
+ end
67
+
68
+ def expand_container(node, base_dir:, chain:, depth:)
69
+ return node if node.children.nil? || node.children.empty?
70
+
71
+ expanded_children = node.children.flat_map do |child|
72
+ expanded = expand_node(child, base_dir: base_dir, chain: chain, depth: depth)
73
+ Array(expanded)
74
+ end
75
+
76
+ return node if expanded_children.equal?(node.children) || same_children?(expanded_children, node.children)
77
+
78
+ duplicate_with_children(node, expanded_children)
79
+ end
80
+
81
+ # The processor must not mutate its input. Each container that has
82
+ # expanded includes is replaced by a shallow copy with a new
83
+ # +children+ array — the original document tree stays intact so the
84
+ # caller can re-resolve with different options.
85
+ def duplicate_with_children(node, new_children)
86
+ duplicate = node.dup
87
+ duplicate.children = new_children
88
+ duplicate
89
+ end
90
+
91
+ def same_children?(expanded, original)
92
+ return false unless expanded.length == original.length
93
+
94
+ expanded.each_with_index.all? { |node, i| node.equal?(original[i]) }
95
+ end
96
+
97
+ def expand_include(include_node, base_dir:, chain:, depth:)
98
+ enforce_depth!(include_node, depth)
99
+ enforce_cycle!(include_node, base_dir: base_dir, chain: chain)
100
+
101
+ target = include_node.target
102
+ new_chain = chain + [resolve_target_path(target, base_dir)]
103
+
104
+ content = fetch_content(include_node, base_dir: base_dir)
105
+ return replacement_for_missing(include_node) if missing_content?(content)
106
+
107
+ applied = apply_text_selectors(content, include_node.options)
108
+ parsed = parse_included(applied)
109
+
110
+ shifted = Coridoc::IncludeSelectors::LevelOffset.call(parsed, options: include_node.options)
111
+
112
+ new_base_dir = File.dirname(resolve_target_path(target, base_dir))
113
+ expand_subtree(shifted, base_dir: new_base_dir, chain: new_chain, depth: depth + 1)
114
+ end
115
+
116
+ def missing_content?(content)
117
+ content.nil? || content == :passthrough
118
+ end
119
+
120
+ def fetch_content(include_node, base_dir:)
121
+ @resolver.call(
122
+ target: include_node.target,
123
+ base_dir: base_dir,
124
+ options: include_node.options,
125
+ context: {}
126
+ )
127
+ rescue Coridoc::IncludeNotFoundError => e
128
+ handle_missing(include_node, e)
129
+ end
130
+
131
+ def handle_missing(include_node, error)
132
+ case @missing_policy
133
+ when :error then raise error
134
+ when :warn
135
+ Coridoc::Logger.warn("Include target not found: #{include_node.target}")
136
+ nil
137
+ when :silent then nil
138
+ when :passthrough then :passthrough
139
+ else raise error
140
+ end
141
+ end
142
+
143
+ def replacement_for_missing(include_node)
144
+ return [include_node] if @missing_policy == :passthrough
145
+
146
+ []
147
+ end
148
+
149
+ def apply_text_selectors(text, options)
150
+ text = apply_lines_or_tags(text, options)
151
+ Coridoc::IncludeSelectors::Indent.call(text, options: options)
152
+ end
153
+
154
+ def apply_lines_or_tags(text, options)
155
+ # lines wins when both specified (SPEC 3.5)
156
+ return Coridoc::IncludeSelectors::Lines.call(text, options: options) if options.lines?
157
+
158
+ Coridoc::IncludeSelectors::Tags.call(text, options: options)
159
+ end
160
+
161
+ def parse_included(text)
162
+ return empty_core if text.nil? || text.empty?
163
+
164
+ Coridoc.parse(text, format: @parse_format)
165
+ end
166
+
167
+ def empty_core
168
+ Coridoc::CoreModel::DocumentElement.new
169
+ end
170
+
171
+ def expand_subtree(core, base_dir:, chain:, depth:)
172
+ expanded = expand_node(core, base_dir: base_dir, chain: chain, depth: depth)
173
+ return [expanded] unless expanded.is_a?(Coridoc::CoreModel::StructuralElement)
174
+
175
+ expanded.children || []
176
+ end
177
+
178
+ def enforce_depth!(include_node, depth)
179
+ return if depth < @max_depth
180
+
181
+ raise Coridoc::IncludeDepthExceededError.new(
182
+ target: include_node.target,
183
+ depth: depth,
184
+ max: @max_depth
185
+ )
186
+ end
187
+
188
+ def enforce_cycle!(include_node, base_dir:, chain:)
189
+ full = resolve_target_path(include_node.target, base_dir)
190
+ return unless chain.include?(full)
191
+
192
+ raise Coridoc::CircularIncludeError.new(
193
+ target: include_node.target,
194
+ chain: chain
195
+ )
196
+ end
197
+
198
+ def resolve_target_path(target, base_dir)
199
+ File.expand_path(target, base_dir)
200
+ end
201
+ end
202
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+
5
+ module Coridoc
6
+ module SourceGraph
7
+ # One file in the twin. Levels materialize on demand and demote
8
+ # automatically when the underlying file drifts:
9
+ #
10
+ # Level 0 (stat) File::Stat — size and mtime, free
11
+ # Level 1 (digest) SHA256 of the bytes, read only when stat is
12
+ # inconclusive (same size + mtime)
13
+ # Level 2 (parsed) format tree from the registered format module
14
+ #
15
+ # CoreModel is not a level: it is a cached materialization
16
+ # (+core+) derived from the parsed level via the format module's
17
+ # +to_core+. Both caches drop together with the parsed level.
18
+ class FileNode
19
+ attr_accessor :graph_digest
20
+ attr_reader :path
21
+ # Identity minted by the sidecar; assigned after persistence.
22
+ attr_accessor :id
23
+
24
+ # @param path [String] absolute, real path of the file
25
+ # @param id [String] sidecar-minted identity
26
+ # @param format [Symbol, nil] registered format name; nil means
27
+ # detect from the extension
28
+ def initialize(path, id: nil, format: nil)
29
+ @path = File.expand_path(path)
30
+ @id = id
31
+ @format = format
32
+ clear_parsed
33
+ end
34
+
35
+ def format
36
+ @format ||= FormatCatalog.detect_format(@path)
37
+ end
38
+
39
+ # Level 0. Raises if the file is gone — a missing file is a
40
+ # hard fact, not a stale one.
41
+ def stat
42
+ File.stat(@path)
43
+ end
44
+
45
+ # Level 1. Bytes are read only when the cached digest can't be
46
+ # trusted from stat alone (size/mtime drifted).
47
+ def digest
48
+ if @digest && fresh_stat?
49
+ @digest
50
+ else
51
+ @stat_snapshot = stat_snapshot
52
+ @digest = compute_digest
53
+ end
54
+ end
55
+
56
+ # Level 2. The format-specific model tree, parsed on first call.
57
+ # Re-parses after any demotion.
58
+ def parsed
59
+ return @parsed if @parsed
60
+
61
+ format_module.parse(File.read(@path)).tap do |tree|
62
+ @parsed = tree
63
+ @derived_digest = digest
64
+ end
65
+ end
66
+
67
+ # Cached CoreModel materialized from the parsed level. Drops
68
+ # together with the parsed level on demotion.
69
+ def core
70
+ @core ||= format_module.to_core(parsed)
71
+ end
72
+
73
+ def parsed?
74
+ !@parsed.nil?
75
+ end
76
+
77
+ # True when the file's bytes still match the digest the derived
78
+ # state was built from. Byte-accurate: reads the file. A node
79
+ # with no derived state (never parsed, never warmed) is
80
+ # vacuously fresh.
81
+ def fresh?
82
+ @derived_digest.nil? || @derived_digest == compute_digest
83
+ end
84
+
85
+ # Demote to Level 0/1: drop the parsed tree and the derived
86
+ # CoreModel. Called by the graph when this file or one of its
87
+ # includes drifted.
88
+ def demote
89
+ clear_parsed
90
+ end
91
+
92
+ # Digest over the include-graph shape: which files this node
93
+ # pulls in, paired with their content digests. Computed by the
94
+ # graph, which owns the edges.
95
+
96
+ # Digest the current derived state was built from.
97
+ attr_reader :derived_digest
98
+
99
+ # Seed the derived anchor from the sidecar without reading
100
+ # bytes; the stat snapshot taken alongside guards Level-1 reuse.
101
+ def digest_warm(digest)
102
+ return if digest.nil?
103
+
104
+ @derived_digest = digest
105
+ @digest = digest
106
+ @stat_snapshot = stat_snapshot
107
+ end
108
+
109
+ # Stat fingerprint used to decide whether the cached digest can
110
+ # be trusted without reading bytes.
111
+ def stat_snapshot
112
+ s = stat
113
+ [s.size, s.mtime.to_i]
114
+ end
115
+
116
+ private
117
+
118
+ def format_module
119
+ mod = FormatCatalog.get_format(format) unless format.nil?
120
+ if mod.nil?
121
+ raise(Coridoc::UnsupportedFormatError.new(format || File.extname(@path),
122
+ available: FormatCatalog.registered_formats))
123
+ end
124
+
125
+ mod
126
+ end
127
+
128
+ def fresh_stat?
129
+ @stat_snapshot.nil? || @stat_snapshot == stat_snapshot
130
+ end
131
+
132
+ def digest_matches?
133
+ @digest.nil? || @digest == compute_digest
134
+ end
135
+
136
+ def compute_digest
137
+ Digest::SHA256.file(@path).hexdigest
138
+ end
139
+
140
+ def clear_parsed
141
+ @parsed = nil
142
+ @core = nil
143
+ @derived_digest = nil
144
+ end
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+
5
+ module Coridoc
6
+ module SourceGraph
7
+ # The graph facade. Owns nodes by real path, the includer→includee
8
+ # edges derived from parsed documents, and the staleness contract:
9
+ # a node is fresh only if its content digest AND its include-graph
10
+ # digest are unchanged. Drift demotes the node and propagates up
11
+ # the edges (cycle-safe).
12
+ class Graph
13
+ attr_reader :sidecar
14
+
15
+ # @param paths [Array<String>] root files to track
16
+ # @param sidecar [Sidecar, nil] persistence; defaults to the XDG
17
+ # cache sidecar
18
+ def initialize(paths: [], sidecar: Sidecar.default)
19
+ @nodes = {}
20
+ @sidecar = sidecar
21
+ @edges = {} # includer path => [includee paths]
22
+ Array(paths).each { |path| node(path) }
23
+ end
24
+
25
+ # Build a graph from root files, warming digest levels from the
26
+ # sidecar so a warm rebuild parses only changed files.
27
+ def self.build(paths, sidecar: Sidecar.default)
28
+ graph = new(paths: paths, sidecar: sidecar)
29
+ graph.warm
30
+ graph
31
+ end
32
+
33
+ def node(path)
34
+ key = File.expand_path(path)
35
+ @nodes[key] ||= load_node(key)
36
+ end
37
+
38
+ def nodes
39
+ @nodes.values
40
+ end
41
+
42
+ # Parse +core+ (Level 2 + materialization), record include
43
+ # edges, and link target nodes into the graph.
44
+ def materialize(node)
45
+ node.core.tap { record_edges(node) }
46
+ end
47
+
48
+ # Paths a node includes, from its last parse.
49
+ def edges(path)
50
+ @edges[File.expand_path(path)] || []
51
+ end
52
+
53
+ # Includers of a path, from recorded edges.
54
+ def includers(path)
55
+ key = File.expand_path(path)
56
+ @edges.select { |_includer, targets| targets.include?(key) }.keys
57
+ end
58
+
59
+ # Nodes whose derived state no longer mirrors disk: content
60
+ # drift or include-graph drift. Parsed levels are demoted and
61
+ # the demotion propagates to every transitive includer.
62
+ def refresh
63
+ demoted = {}
64
+ nodes.select { |n| !n.fresh? || graph_drifted?(n) }
65
+ .each { |n| demote_up(n, demoted) }
66
+ demoted.values
67
+ end
68
+
69
+ def stale_nodes
70
+ refresh
71
+ end
72
+
73
+ # A node's include-graph digest: the shape of what it pulls in,
74
+ # paired with each target's content digest. Recompute after
75
+ # edge recording; store on the node.
76
+ def compute_graph_digest(node)
77
+ edges(node.path)
78
+ node.graph_digest = digest_shape(edges(node.path))
79
+ end
80
+
81
+ def persist
82
+ nodes.each { |n| compute_graph_digest(n) if n.parsed? }
83
+ records = nodes.map do |n|
84
+ { path: n.path, id: n.id, digest: n.digest,
85
+ edges: edges(n.path) }
86
+ end
87
+ sidecar.write(records).each do |rec|
88
+ n = @nodes[rec[:path]]
89
+ n.id = rec[:id] if n
90
+ end
91
+ self
92
+ end
93
+
94
+ # Seed digest levels and edges from the sidecar without
95
+ # parsing. Graph digests derive from warmed edges + digests —
96
+ # the sidecar stores only source facts, never derived state.
97
+ def warm
98
+ sidecar.entries.each_key do |key|
99
+ node(key) if File.exist?(key)
100
+ end
101
+ sidecar.entries.each do |key, record|
102
+ node(key).digest_warm(record['digest'])
103
+ targets = Array(record['edges']).select { |t| File.exist?(t) }
104
+ next if targets.empty?
105
+
106
+ @edges[key] = targets
107
+ targets.each { |t| node(t) }
108
+ node(key).graph_digest = digest_shape(targets)
109
+ end
110
+ self
111
+ end
112
+
113
+ private
114
+
115
+ def load_node(key)
116
+ record = sidecar.record_for(key)
117
+ FileNode.new(key, id: record && record['id'])
118
+ end
119
+
120
+ def record_edges(node)
121
+ targets = IncludeEdges.targets(node.core, base_dir: File.dirname(node.path))
122
+ @edges[node.path] = targets
123
+ compute_graph_digest(node)
124
+ targets.each { |t| node(t) }
125
+ end
126
+
127
+ # Structural drift: the recorded include-graph digest differs
128
+ # from the one recomputed over current content digests.
129
+ def graph_drifted?(node)
130
+ return false if node.graph_digest.nil?
131
+
132
+ node.graph_digest != current_graph_digest(node)
133
+ end
134
+
135
+ def current_graph_digest(node)
136
+ digest_shape(edges(node.path))
137
+ end
138
+
139
+ # Content digest over the include-graph shape: which files this
140
+ # node pulls in, paired with their content digests.
141
+ def digest_shape(targets)
142
+ lines = targets.map { |t| "#{t}:#{digest_of(t)}" }.sort.join("\n")
143
+ Digest::SHA256.hexdigest(lines)
144
+ end
145
+
146
+ def digest_of(path)
147
+ n = @nodes[File.expand_path(path)]
148
+ n ? n.digest : Digest::SHA256.file(path).hexdigest
149
+ end
150
+
151
+ # Demote the node and every transitive includer. Cycle-safe
152
+ # via a visited set that doubles as the demoted-node ledger.
153
+ def demote_up(node, visited = {})
154
+ return if visited[node.path]
155
+
156
+ visited[node.path] = node
157
+ node.demote
158
+ includers(node.path).each do |includer_path|
159
+ includer = @nodes[includer_path]
160
+ demote_up(includer, visited) if includer
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end