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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7f0d1c57e91c55c5986223a32e82b4f7300a230323cd2fdd3d8c295b3f05067e
4
+ data.tar.gz: b673e681104ddeb3097870dd454a36c941f0ef594e0d138c92e40823fb7d4d4e
5
+ SHA512:
6
+ metadata.gz: 9de09e30095b387bf4c63887d9cb609dc86266c288a32a841d98ad29bbff11d75b1fa57872602a80a229c55707d4acc400c5033fb36ef1aeda944d7e142cb495
7
+ data.tar.gz: a2e1f8dbc25cff0021f60f0f58024a513b6f7ebd47f530ed62109158d5fa5c8ad5a4cb016a665b9aeac5a8673080e3afcffa0ad9f64d3de87061b80cacf2c66e
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --require spec_helper
2
+ --format documentation
3
+ --color
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/exe/coridoc ADDED
@@ -0,0 +1,24 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ lib_path = File.expand_path('../lib', __dir__)
5
+ $LOAD_PATH.unshift(lib_path) unless $LOAD_PATH.include?(lib_path)
6
+
7
+ require 'coridoc'
8
+ require 'coridoc/cli'
9
+
10
+ GEM_TO_REQUIRE_PATH = {
11
+ 'coridoc-adoc' => 'coridoc/asciidoc',
12
+ 'coridoc-html' => 'coridoc/html',
13
+ 'coridoc-markdown' => 'coridoc/markdown',
14
+ 'coridoc-docx' => 'coridoc/docx'
15
+ }.freeze
16
+
17
+ GEM_TO_REQUIRE_PATH.each do |gem_name, require_path|
18
+ gem gem_name
19
+ require require_path
20
+ rescue LoadError
21
+ nil
22
+ end
23
+
24
+ Coridoc::CLI.start(ARGV)
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Coridoc
4
+ # Generic raw-tree to typed-model engine behind PARG bindings.
5
+ #
6
+ # A parser yields a raw tree of hashes (capture name => value). A
7
+ # Binding says: a node with exactly these keys is an instance of this
8
+ # model, its attributes assigned from these captures. The inflater
9
+ # instantiates the bound model, recursing through captured
10
+ # collections; everything unbound falls through to a residual (the
11
+ # format's hand-written processing), so a format migrates one rule at
12
+ # a time and nothing changes until a binding exists.
13
+ #
14
+ # inflater = BindingInflater.new(bindings: [binding])
15
+ # inflater.inflate(node) { |unbound| legacy_transform(unbound) }
16
+ class BindingInflater
17
+ # One bound rule.
18
+ #
19
+ # @!attribute keys [Array<Symbol>] the exact capture-key set of a node
20
+ # @!attribute model [Class, #call] the model class, or a callable that
21
+ # returns it (resolved on first use, for lazily loaded classes)
22
+ # @!attribute captures [Hash{Symbol=>Symbol}] attribute => capture key
23
+ # @!attribute defaults [Hash{Symbol=>Object}] attributes fixed by the rule
24
+ # @!attribute via [#call, nil] optional named hook for a rule's semantic
25
+ # step: receives the assigned attributes, returns the attributes the
26
+ # model is built from. Pure capture-to-attribute rules need none.
27
+ # With `model: nil` the hook's return value IS the result (for rules
28
+ # that build a tree, pass a value through, or return plain data).
29
+ # @!attribute raw [Hash{Symbol=>Symbol}] attribute => capture key, assigned
30
+ # as captured: never inflated and never sent to the residual. For hooks
31
+ # that read the raw subtree themselves.
32
+ # @!attribute scoped [Boolean, nil] when true the hook also receives the
33
+ # context passed to {#inflate} (document-scoped state such as a table
34
+ # of definitions), as its second argument.
35
+ Binding = Struct.new(:keys, :model, :captures, :defaults, :via, :raw, :scoped, keyword_init: true) do
36
+ def matches?(node)
37
+ node.is_a?(Hash) && node.keys.sort == keys.sort
38
+ end
39
+
40
+ def model_class
41
+ model.is_a?(Class) || model.nil? ? model : model.call
42
+ end
43
+ end
44
+
45
+ # Build an inflater from the model-bindings table a PARG artifact
46
+ # embeds (`parsanol parg bindings` dumps the same table).
47
+ #
48
+ # @param table [Hash, nil] `{"version"=>1, "rules"=>{name=>rule}}`; nil = no bindings
49
+ # @param models [#call] resolves a model name to its class, lazily
50
+ def self.from_table(table, models:)
51
+ rules = table ? table.fetch('rules') : {}
52
+ version = table && table['version']
53
+ raise ArgumentError, "unsupported model_bindings version #{version.inspect}" if table && version != 1
54
+
55
+ new(bindings: rules.values.map { |rule| binding_from_rule(rule, models) })
56
+ end
57
+
58
+ def self.binding_from_rule(rule, models)
59
+ name = rule.fetch('model')
60
+ # Both attribute => capture maps feed the same recursive inflation:
61
+ # `children` merely names the attributes that hold nested nodes.
62
+ captures = rule.fetch('captures', {}).merge(rule.fetch('children', {}))
63
+ Binding.new(
64
+ keys: rule.fetch('keys').map(&:to_sym),
65
+ model: -> { models.call(name) },
66
+ captures: captures.to_h { |attribute, key| [attribute.to_sym, key.to_sym] },
67
+ defaults: rule.fetch('defaults', {}).transform_keys(&:to_sym)
68
+ )
69
+ end
70
+ private_class_method :binding_from_rule
71
+
72
+ def initialize(bindings:)
73
+ @bindings = bindings
74
+ end
75
+
76
+ # @return [Array<Binding>] the bindings, for callers that need to know
77
+ # which rules are bound (e.g. a corpus guard)
78
+ attr_reader :bindings
79
+
80
+ def bound?(node)
81
+ !binding_for(node).nil?
82
+ end
83
+
84
+ # @param node [Object] a raw tree node
85
+ # @param context [Object, nil] document-scoped state, handed to the hooks
86
+ # of scoped bindings and carried through nested nodes
87
+ # @yield [Object] an unbound node, handed to the residual
88
+ # @return [Object] the model for a bound node, else the residual's result
89
+ def inflate(node, context = nil, &residual)
90
+ binding = binding_for(node)
91
+ return yield(node) unless binding
92
+
93
+ attributes = binding.defaults.dup
94
+ binding.captures.each { |attribute, key| attributes[attribute] = inflate_value(node[key], context, &residual) }
95
+ binding.raw&.each { |attribute, key| attributes[attribute] = node[key] }
96
+ attributes = call_hook(binding, attributes, context) if binding.via
97
+ binding.model ? binding.model_class.new(**attributes) : attributes
98
+ end
99
+
100
+ private
101
+
102
+ def binding_for(node)
103
+ @bindings.find { |binding| binding.matches?(node) }
104
+ end
105
+
106
+ def call_hook(binding, attributes, context)
107
+ binding.scoped ? binding.via.call(attributes, context) : binding.via.call(attributes)
108
+ end
109
+
110
+ def inflate_value(value, context, &residual)
111
+ case value
112
+ when Array then value.map { |item| inflate_value(item, context, &residual) }
113
+ when Hash then inflate(value, context, &residual)
114
+ else value.respond_to?(:to_str) ? value.to_str : value
115
+ end
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,311 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thor'
4
+
5
+ module Coridoc
6
+ class CLI < Thor
7
+ package_name 'Coridoc'
8
+
9
+ def self.exit_on_failure?
10
+ true
11
+ end
12
+
13
+ desc 'convert FILE', 'Convert a document from one format to another'
14
+ option :to, aliases: '-t', desc: 'Target format (adoc, html, md)', type: :string
15
+ option :output, aliases: '-o', desc: 'Output file path (default: stdout)', type: :string
16
+ option :from, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
17
+ option :theme, desc: 'HTML theme (classic, modern)', type: :string, default: 'classic'
18
+ option :verbose, desc: 'Enable verbose output', type: :boolean, default: false
19
+ option :asset_delivery, desc: 'Asset delivery mode (embedded, external)', type: :string, default: 'embedded'
20
+ option :toc, desc: 'Include table of contents', type: :boolean, default: false
21
+ option :toc_levels, desc: 'TOC depth (1-5)', type: :numeric, default: 2
22
+ option :section_numbers, desc: 'Enable section numbering', type: :boolean, default: false
23
+ option :section_number_levels, desc: 'Section numbering depth (1-6)', type: :numeric, default: 3
24
+ option :lang, desc: 'Document language code', type: :string, default: 'en'
25
+ option :resolve_includes, desc: 'Resolve include:: directives inline (default: leave as link nodes)',
26
+ type: :boolean, default: false
27
+ option :base_dir, desc: 'Base directory for include resolution (default: dirname of FILE)',
28
+ type: :string
29
+ option :missing_include, desc: 'Policy for missing includes: error, warn, silent, passthrough',
30
+ type: :string, default: 'error'
31
+ option :max_include_depth, desc: 'Maximum include nesting depth', type: :numeric,
32
+ default: 64
33
+ option :allow_unsafe_includes, desc: 'Disable path-traversal protection (asciidoctor :unsafe mode)',
34
+ type: :boolean, default: false
35
+ option :allow_unresolved_includes, desc: 'Allow serialization with unresolved includes ' \
36
+ '(formats that cannot represent them drop them)',
37
+ type: :boolean, default: false
38
+ def convert(file)
39
+ source_format = resolve_format(file, :from)
40
+ target_format = options[:to] ? Coridoc.normalize_format(options[:to]) : Coridoc.resolve_output_format(options[:output])
41
+
42
+ unless source_format && target_format
43
+ error 'Error: Could not determine format. Use --from and --to options.'
44
+ exit 1
45
+ end
46
+
47
+ unless Coridoc.serialize_format?(target_format)
48
+ error "Error: Converting to #{target_format} is not yet supported."
49
+ exit 1
50
+ end
51
+
52
+ verbose_log "Converting #{file} (#{source_format}) to #{target_format}"
53
+
54
+ doc = Coridoc.parse_file(file, format: source_format)
55
+ doc = resolve_includes!(doc, file) if options[:resolve_includes]
56
+
57
+ opts = build_convert_options
58
+ result = Coridoc.serialize(doc, to: target_format, **opts)
59
+ write_output(result, options[:output])
60
+ rescue Coridoc::Error => e
61
+ error "Error: #{e.message}"
62
+ exit 1
63
+ rescue StandardError => e
64
+ error "Error: #{e.message}"
65
+ verbose_log e.backtrace.join("\n") if options[:verbose]
66
+ exit 1
67
+ end
68
+
69
+ desc 'formats', 'List supported formats'
70
+ def formats
71
+ caps = Coridoc.format_capabilities
72
+
73
+ puts 'Supported formats:'
74
+ puts ''
75
+ puts ' Source formats (can read):'
76
+ caps.each { |name, c| puts " - #{name}" if c[:parse] }
77
+ puts ''
78
+ puts ' Target formats (can write):'
79
+ caps.each { |name, c| puts " - #{name}" if c[:serialize] }
80
+ end
81
+
82
+ desc 'version', 'Display Coridoc version'
83
+ def version
84
+ puts "Coridoc #{Coridoc::VERSION}"
85
+ end
86
+
87
+ desc 'format FILE', 'Canonical-format a document (like rufo, #110)'
88
+ option :format, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
89
+ option :in_place, aliases: '-i', desc: 'Rewrite the file in place', type: :boolean, default: false
90
+ option :check, desc: 'Exit 1 when the file is not canonically formatted (no rewrite)', type: :boolean, default: false
91
+ def format(file)
92
+ source_format = resolve_format(file)
93
+ unless source_format
94
+ error 'Error: Could not determine format. Use --format option.'
95
+ exit 1
96
+ end
97
+
98
+ formatted = FormatCatalog.get_format(source_format).format(File.read(file))
99
+ if formatted.nil?
100
+ error "Error: No formatter available for #{source_format}"
101
+ exit 1
102
+ end
103
+
104
+ if options[:check]
105
+ if formatted == File.read(file)
106
+ puts '✓ Already formatted'
107
+ else
108
+ error "✗ #{file} is not canonically formatted"
109
+ exit 1
110
+ end
111
+ elsif options[:in_place]
112
+ File.write(file, formatted) unless formatted == File.read(file)
113
+ puts "Formatted #{file}"
114
+ else
115
+ puts formatted
116
+ end
117
+ rescue Coridoc::Error => e
118
+ error "Error: #{e.message}"
119
+ exit 1
120
+ end
121
+
122
+ desc 'lint FILE...', 'Lint documents with model-driven rules (ADOC001...)'
123
+ option :format, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
124
+ option :only, desc: 'Run only these rule ids', type: :array
125
+ option :except, desc: 'Skip these rule ids', type: :array
126
+ def lint(*files)
127
+ files.each do |file|
128
+ unless File.exist?(file)
129
+ error "Error: #{file} not found"
130
+ exit 1
131
+ end
132
+ end
133
+
134
+ format = options[:format]&.to_sym
135
+ violations = Coridoc::Lint.run(files, format: format,
136
+ only: options[:only],
137
+ except: options[:except])
138
+ violations.each { |v| puts v }
139
+
140
+ if violations.empty?
141
+ puts '✓ No lint violations'
142
+ else
143
+ error "✗ #{violations.size} violation(s)"
144
+ exit 1
145
+ end
146
+ rescue Coridoc::Error => e
147
+ error "Error: #{e.message}"
148
+ exit 1
149
+ end
150
+
151
+ desc 'validate FILE', 'Validate a document against its schema'
152
+ option :format, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
153
+ option :strict, desc: 'Enable strict validation mode', type: :boolean, default: false
154
+ def validate(file)
155
+ source_format = resolve_format(file)
156
+ unless source_format
157
+ error 'Error: Could not determine format. Use --format option.'
158
+ exit 1
159
+ end
160
+
161
+ verbose_log "Validating #{file} (#{source_format})"
162
+
163
+ result = Coridoc.validate_file(file, format: source_format)
164
+
165
+ if result.valid?
166
+ puts '✓ Document is valid'
167
+ else
168
+ error "✗ #{result}"
169
+ exit 1
170
+ end
171
+ rescue Coridoc::Error => e
172
+ error "Error: #{e.message}"
173
+ exit 1
174
+ rescue StandardError => e
175
+ error "Error: #{e.message}"
176
+ verbose_log e.backtrace.join("\n") if options[:verbose]
177
+ exit 1
178
+ end
179
+
180
+ desc 'query FILE SELECTOR', 'Query document elements using CSS-like selectors'
181
+ option :format, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
182
+ option :output, aliases: '-o', desc: 'Output format (text, json)', type: :string, default: 'text'
183
+ def query(file, selector)
184
+ source_format = resolve_format(file)
185
+ unless source_format
186
+ error 'Error: Could not determine format. Use --format option.'
187
+ exit 1
188
+ end
189
+
190
+ verbose_log "Querying #{file} with selector: #{selector}"
191
+
192
+ doc = Coridoc.parse_file(file, format: source_format)
193
+ results = Coridoc::Query.query(doc, selector)
194
+
195
+ if results.empty?
196
+ puts "No elements found matching: #{selector}"
197
+ else
198
+ case options[:output]
199
+ when 'json'
200
+ require 'json'
201
+ puts JSON.pretty_generate(results.map { |r| Coridoc.describe_element(r) })
202
+ else
203
+ puts "Found #{results.length} element(s):"
204
+ results.each_with_index do |elem, i|
205
+ puts " #{i + 1}. #{Coridoc.describe_element(elem)}"
206
+ end
207
+ end
208
+ end
209
+ rescue Coridoc::Error => e
210
+ error "Error: #{e.message}"
211
+ exit 1
212
+ rescue StandardError => e
213
+ error "Error: #{e.message}"
214
+ verbose_log e.backtrace.join("\n") if options[:verbose]
215
+ exit 1
216
+ end
217
+
218
+ desc 'info FILE', 'Display document metadata and statistics'
219
+ option :format, aliases: '-f', desc: 'Source format (auto-detected from extension)', type: :string
220
+ def info(file)
221
+ source_format = resolve_format(file)
222
+ unless source_format
223
+ error 'Error: Could not determine format. Use --format option.'
224
+ exit 1
225
+ end
226
+
227
+ verbose_log "Analyzing #{file} (#{source_format})"
228
+
229
+ doc = Coridoc.parse_file(file, format: source_format)
230
+ stats = Coridoc.document_stats(doc)
231
+ fi = Coridoc.file_info(file)
232
+
233
+ puts 'Document Information'
234
+ puts '=' * 40
235
+ puts "Format: #{source_format}"
236
+ puts "File size: #{fi[:size]} bytes"
237
+ puts "Line count: #{fi[:lines]}" if fi[:lines]
238
+ puts "Title: #{stats[:title]}" if stats[:title]
239
+ puts "Child elements: #{stats[:child_count]}" if stats[:child_count]
240
+
241
+ if stats[:element_counts]&.any?
242
+ puts ''
243
+ puts 'Element Counts:'
244
+ stats[:element_counts].each { |type, count| puts " #{type}: #{count}" }
245
+ end
246
+ rescue Coridoc::Error => e
247
+ error "Error: #{e.message}"
248
+ exit 1
249
+ rescue StandardError => e
250
+ error "Error: #{e.message}"
251
+ verbose_log e.backtrace.join("\n") if options[:verbose]
252
+ exit 1
253
+ end
254
+
255
+ map '-v' => :version, '--version' => :version
256
+
257
+ private
258
+
259
+ def resolve_format(file, option_key = :format)
260
+ raw = options[option_key]
261
+ raw ? Coridoc.normalize_format(raw) : Coridoc.detect_format(file)
262
+ end
263
+
264
+ def write_output(content, output_file)
265
+ if output_file
266
+ File.write(output_file, content)
267
+ verbose_log "Written to: #{output_file}"
268
+ else
269
+ puts content
270
+ end
271
+ end
272
+
273
+ def verbose_log(message)
274
+ warn "[verbose] #{message}" if options[:verbose]
275
+ end
276
+
277
+ def error(message)
278
+ warn message
279
+ end
280
+
281
+ CONVERT_OPTIONS = %i[
282
+ toc toc_levels section_numbers section_number_levels
283
+ lang theme asset_delivery allow_unresolved_includes
284
+ ].freeze
285
+ private_constant :CONVERT_OPTIONS
286
+
287
+ SYMBOL_OPTIONS = %i[theme asset_delivery].freeze
288
+ private_constant :SYMBOL_OPTIONS
289
+
290
+ def build_convert_options
291
+ CONVERT_OPTIONS.each_with_object({}) do |key, opts|
292
+ value = options[key]
293
+ next unless value
294
+
295
+ opts[key] = SYMBOL_OPTIONS.include?(key) ? value.to_sym : value
296
+ end
297
+ end
298
+
299
+ def resolve_includes!(doc, source_file)
300
+ base_dir = options[:base_dir] || File.expand_path(File.dirname(source_file))
301
+ verbose_log "Resolving includes against #{base_dir}"
302
+ Coridoc.resolve_includes(
303
+ doc,
304
+ base_dir: base_dir,
305
+ missing_include: options[:missing_include].to_sym,
306
+ max_depth: options[:max_include_depth],
307
+ allow_unsafe: options[:allow_unsafe_includes]
308
+ )
309
+ end
310
+ end
311
+ end