schemic 0.1.1

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.
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'schemic/parser'
4
+ require 'uri'
5
+ require 'set'
6
+
7
+ # Bounded page collection; source-specific selectors remain in the application.
8
+ class Schemic::Crawler
9
+ autoload :Navigation, 'schemic/crawler/navigation'
10
+
11
+ include Navigation
12
+
13
+ autoload :Cache, 'schemic/crawler/cache'
14
+ autoload :HTTP, 'schemic/crawler/http'
15
+ autoload :Pipeline, 'schemic/crawler/pipeline'
16
+
17
+ class Error < StandardError; end
18
+ class CacheMiss < Error; end
19
+ class FetchError < Error; end
20
+ class ScopeError < Error; end
21
+
22
+ Page = Struct.new(:url, :status, :headers, :body, :fetched_at, keyword_init: true)
23
+
24
+ # Configures an explicit source boundary; no network request is made here.
25
+ # @param origins [Array<String>] Allowed HTTP(S) origins, including ports.
26
+ # @param cache [Cache] Persistent raw-page cache.
27
+ # @param path_prefix [String] Allowed path or directory boundary.
28
+ # @param transport [HTTP, #call] Page delivery implementation.
29
+ # @param max_pages [Integer] Maximum distinct requested pages per collection.
30
+ # @param delay [Numeric] Pause between requests, including redirects and retries.
31
+ # @param sleeper [#call] Pause implementation, injectable for tests.
32
+ # @return [Crawler] A collector that defaults to reading existing cache entries.
33
+ # Public named limits stay individually configurable.
34
+ # rubocop:disable Metrics/ParameterLists
35
+ def initialize origins:, cache:, path_prefix: '/', transport: HTTP.new, max_pages: 100,
36
+ delay: 1, sleeper: Kernel.method(:sleep)
37
+ check_collection_limits(origins, path_prefix, max_pages, delay)
38
+
39
+ @origins = origins.map {|value| origin(checked_url(value)) }
40
+
41
+ @origins.uniq!
42
+ @origins.freeze
43
+
44
+ @path_prefix = path_prefix.sub(%r{/+\z}, '')
45
+ @cache = cache
46
+ @transport = transport
47
+ @max_pages = max_pages
48
+ @delay = delay
49
+ @sleeper = sleeper
50
+ end
51
+
52
+ # rubocop:enable Metrics/ParameterLists
53
+
54
+ # Reads one cached page; refresh performs conditional HTTP, offline forbids delivery.
55
+ # If the cache is missing while offline, raises CacheMiss rather than silently downloading.
56
+ # @param url [String] Absolute URL within the configured boundary.
57
+ # @param refresh [Boolean] Revalidate an existing page with ETag/Last-Modified.
58
+ # @param offline [Boolean] Require a saved page.
59
+ # @return [Page] Exact bytes and response metadata.
60
+ def fetch url, refresh: false, offline: false
61
+ raise(ArgumentError, 'refresh and offline cannot be combined') if refresh && offline
62
+
63
+ key = scoped_url(url)
64
+ saved = @cache.read(key)
65
+
66
+ return saved if saved && !refresh
67
+ raise(CacheMiss, "No cached page: #{key}") if offline
68
+
69
+ delivered_page(key, saved)
70
+ end
71
+
72
+ # Collects deduplicated URLs in breadth-first order, optionally following selected links.
73
+ # If a discovered link is outside the boundary it is skipped; an invalid seed is an error.
74
+ # @param urls [Array<String>] Explicit seeds, including application-generated date ranges.
75
+ # @param links [String, Hash, nil] CSS href selector, selector=>attribute rules, or nil for seeds only.
76
+ # @param options [Hash] fetch options, such as offline or refresh.
77
+ # @yieldparam page [Page] Each collected page.
78
+ # @return [Enumerator, nil] A lazy enumerator without a block, or nil after yielding every page.
79
+ def each_page urls, links: nil, **options, &block
80
+ return enum_for(__method__, urls, links: links, **options) unless block
81
+
82
+ check_collection_input(urls, links)
83
+
84
+ queue = urls.map {|url| scoped_url(url) }
85
+ seen = Set.new
86
+
87
+ queue.uniq!
88
+
89
+ visit_queue(queue, seen, links, options, &block)
90
+ end
91
+
92
+ private
93
+
94
+ # Selects validators from a saved response, omitting absent values.
95
+ # @param page [Page] Previously saved response.
96
+ # @return [Hash<String, String>] Conditional HTTP request headers.
97
+ def conditional_headers page
98
+ { 'If-None-Match' => page.headers['etag'], 'If-Modified-Since' => page.headers['last-modified'] }.compact
99
+ end
100
+
101
+ # Applies the configured pause after the first request in this collector.
102
+ # @return [Boolean] Records that a request has occurred.
103
+ def pause
104
+ @sleeper.call(@delay) if @requested && @delay.positive?
105
+
106
+ @requested = true
107
+ end
108
+
109
+ # Delivers and caches a page, merging 304 metadata when a previous response exists.
110
+ # Any other unsuccessful status raises FetchError and leaves the cache unchanged.
111
+ # @param key [String] Canonical request URL.
112
+ # @param saved [Page, nil] Previously cached response.
113
+ # @return [Page] Successful response.
114
+ def delivered_page key, saved
115
+ headers = saved ? conditional_headers(saved) : {}
116
+ page = @transport.call(key, headers: headers, check: method(:scoped_url), before_request: method(:pause))
117
+
118
+ page = refreshed_page(saved, page) if page.status == 304
119
+
120
+ raise(FetchError, "HTTP #{page.status}: #{key}") unless page.status == 200
121
+
122
+ @cache.write(key, page)
123
+
124
+ page
125
+ end
126
+
127
+ # Merges a conditional response into cached bytes; a 304 without cache raises FetchError.
128
+ # @param saved [Page, nil] Previous page.
129
+ # @param page [Page] HTTP 304 response.
130
+ # @return [Page] Revalidated page retaining original bytes.
131
+ def refreshed_page saved, page
132
+ raise(FetchError, 'Received 304 without a cached page') unless saved
133
+
134
+ headers = saved.headers.merge(page.headers.except('content-length'))
135
+
136
+ Page.new(**saved.to_h, headers: headers, fetched_at: page.fetched_at)
137
+ end
138
+
139
+ # Walks a breadth-first queue; duplicates are skipped and the page limit is enforced before delivery.
140
+ # @param queue [Array<String>] Mutable pending URL queue.
141
+ # @param seen [Set] Visited URLs.
142
+ # @param links [String, Hash, nil] Link declarations.
143
+ # @param options [Hash] Fetch options.
144
+ # @yieldparam page [Page] Collected response.
145
+ # @return [nil] Exhausted queue.
146
+ def visit_queue queue, seen, links, options
147
+ until queue.empty?
148
+ url = queue.shift
149
+
150
+ next if seen.include?(url)
151
+ raise(FetchError, "Page limit #{@max_pages} exceeded") if seen.size >= @max_pages
152
+
153
+ seen.add(url)
154
+
155
+ page = fetch(url, **options)
156
+
157
+ yield(page)
158
+ queue.concat(discovered_links(page, links)) if links
159
+ end
160
+ end
161
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'schemic/generator'
4
+ require 'schemic/parser'
5
+
6
+ # Loads extraction schemas from trusted Ruby files.
7
+ module Schemic::Generator::Ruby
8
+ class << self
9
+ # Evaluates a trusted Ruby file in a fresh module and runs its single generator.
10
+ # Raises ArgumentError for a syntax error or if the file defines zero or multiple generators.
11
+ # @param file_name [String] Path to a Ruby schema file.
12
+ # @return [OpenStruct] Schema returned by the generator's generate method.
13
+ def load_from file_name
14
+ path = File.expand_path(file_name)
15
+ namespace = Module.new
16
+
17
+ namespace.module_eval(File.read(path, encoding: Encoding::UTF_8), path, 1)
18
+
19
+ generators = generator_modules(namespace)
20
+
21
+ raise(ArgumentError, "Expected one Ruby schema generator in #{path}") unless generators.one?
22
+
23
+ generators.first.generate
24
+ rescue SyntaxError => error
25
+ raise(ArgumentError, error.message)
26
+ end
27
+
28
+ private
29
+
30
+ # Finds generator modules and classes defined directly by a schema file.
31
+ # @param namespace [Module] Module in which the file ran.
32
+ # @return [Array<Module>] Definitions that expose a public generate method.
33
+ def generator_modules namespace
34
+ namespace.constants(false).filter_map do |name|
35
+ candidate = namespace.const_get(name, false)
36
+
37
+ candidate if candidate.is_a?(Module) && candidate.respond_to?(:generate)
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require 'rdoba/os'
5
+
6
+ require 'schemic/generator'
7
+
8
+ # Safe loading of YAML extraction schemas.
9
+ module Schemic::Generator::YAML
10
+ class << self
11
+ # Reads a trusted schema document without constructing arbitrary Ruby objects.
12
+ # If the root is not a mapping, rejects it before converting to OpenStruct.
13
+ # @param file_name [String] YAML extraction-schema filename.
14
+ # @return [OpenStruct] Schema compatible with the existing Parser API.
15
+ def load_from file_name
16
+ config = ::YAML.safe_load_file(file_name, permitted_classes: [Symbol], aliases: false)
17
+
18
+ raise(ArgumentError, 'Expected a YAML schema mapping') unless config.is_a?(Hash)
19
+
20
+ config.to_os
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Extraction schema loaders.
4
+ # Nested form establishes Schemic when this entry point is required on its own.
5
+ # rubocop:disable Style/ClassAndModuleChildren
6
+ module Schemic
7
+ # Extraction schema loaders.
8
+ module Generator
9
+ autoload :Ruby, 'schemic/generator/ruby'
10
+ autoload :YAML, 'schemic/generator/yaml'
11
+
12
+ # Loads an extraction schema for Parser.
13
+ # Runs a trusted Ruby generator for the .rb extension and uses safe YAML loading otherwise.
14
+ # @param file_name [String] Path to a schema file.
15
+ # @return [OpenStruct] Schema for Schemic::Parser.
16
+ def self.load file_name
17
+ File.extname(file_name) == '.rb' ? Ruby.load_from(file_name) : YAML.load_from(file_name)
18
+ end
19
+ end
20
+ end
21
+ # rubocop:enable Style/ClassAndModuleChildren
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'schemic/version'
4
+
5
+ # Inflects the names used by extraction schemas.
6
+ module Schemic::Inflector
7
+ PLURALS = {
8
+ /[aeiouy]o\z/i => '\0s',
9
+ /o\z/i => '\0es',
10
+ /en\z/i => 'ina',
11
+ /us\z/i => 'i',
12
+ /um\z/i => 'a',
13
+ /(?:i|(?<!e)a)\z/i => '\0',
14
+ /(\A|_)([Pp])erson\z/ => '\1\2eople',
15
+ /(\A|_)([Cc])hild\z/ => '\1\2hildren',
16
+ /(?:\A|_)(?:people|children|news|series|species)\z/i => '\0',
17
+ /([^aeiou])y\z/i => '\1ies',
18
+ /(?:ss|us|ch|sh|x|zz)\z/i => '\0es',
19
+ /s\z/i => '\0',
20
+ /.\z/ => '\0s'
21
+ }.freeze
22
+ SINGULARS = {
23
+ /(?:\A|_)(?:news|series|species|okei)\z/i => '\0',
24
+ /(o)e?s\z/i => '\1',
25
+ /ina\z/i => 'en',
26
+ /i\z/i => 'us',
27
+ /(?<!e)a\z/i => 'um',
28
+ /(\A|_)([Pp])eople\z/ => '\1\2erson',
29
+ /(\A|_)([Cc])hildren\z/ => '\1\2hild',
30
+ /([^aeiou])ies\z/i => '\1y',
31
+ /(ss|us|ch|sh|x|zz)es\z/i => '\1',
32
+ /(?:ss|us|is)\z/i => '\0',
33
+ /s\z/i => ''
34
+ }.freeze
35
+
36
+ private_constant :PLURALS, :SINGULARS
37
+
38
+ # Forms the plural key for a collection.
39
+ # @param name [String] Schema name.
40
+ # @return [String] Plural form.
41
+ def self.pluralize name
42
+ inflect(name, :pluralize, PLURALS)
43
+ end
44
+
45
+ # Forms the singular key used to find a schema.
46
+ # @param name [String] Schema declaration name or alias.
47
+ # @return [String] Singular form.
48
+ def self.singularize name
49
+ inflect(name, :singularize, SINGULARS)
50
+ end
51
+
52
+ # Uses the application's inflector when loaded, or the first matching built-in suffix rule.
53
+ # @param name [String] Schema name.
54
+ # @param direction [Symbol] Inflector method to call.
55
+ # @param rules [Hash<Regexp, String>] Ordered suffix transformations.
56
+ # @return [String] Transformed name, or the name itself if no rule matches.
57
+ def self.inflect name, direction, rules
58
+ return ::ActiveSupport::Inflector.public_send(direction, name) if defined?(::ActiveSupport::Inflector)
59
+
60
+ pattern, replacement = rules.find {|suffix, _| suffix.match?(name) }
61
+
62
+ pattern ? name.sub(pattern, replacement) : name
63
+ end
64
+
65
+ private_class_method :inflect
66
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Named and inline callbacks with the existing positional handler API.
4
+ module Schemic::Parser::Callbacks
5
+ protected
6
+
7
+ def handler_for handler
8
+ case handler
9
+ when Proc, Method
10
+ handler
11
+ when NilClass
12
+ method(:undefined_handler)
13
+ when TrueClass
14
+ method(:true_handler)
15
+ when FalseClass
16
+ method(:false_handler)
17
+ else
18
+ respond_to?(handler.to_s, true) ? method(handler.to_s) : method(:undefined_handler)
19
+ end
20
+ end
21
+
22
+ # Schema callback name is part of the existing API.
23
+ # rubocop:disable Naming/PredicateMethod
24
+ def true_handler *args
25
+ debug("True handler is used for '#{args[1]}' field with value '#{args.first}'")
26
+
27
+ true
28
+ end
29
+ # rubocop:enable Naming/PredicateMethod
30
+
31
+ # Schema callback name is part of the existing API.
32
+ # rubocop:disable Naming/PredicateMethod
33
+ def false_handler _value, *args
34
+ debug("False handler is used for '#{args[1]}' field with value '#{args.first}'")
35
+
36
+ false
37
+ end
38
+ # rubocop:enable Naming/PredicateMethod
39
+
40
+ # Schema callback name is part of the existing API.
41
+ def undefined_handler value, *args
42
+ warn("Undefined handler is used for '#{args.first}' field with value '#{value}'")
43
+
44
+ value
45
+ end
46
+
47
+ def handled_value handler, value, name, xml_context, options
48
+ callback = handler_for(handler)
49
+
50
+ return invoke_handler(callback, value, name, xml_context, options) unless value.is_a?(Nokogiri::XML::NodeSet)
51
+
52
+ value.each_with_object(Nokogiri::XML::NodeSet.new(value.document)) do |node, result|
53
+ transformed = invoke_handler(callback, node, name, xml_context, options)
54
+
55
+ result << transformed if transformed
56
+ end
57
+ end
58
+
59
+ # Passes only the declared callback arguments, retaining the existing positional API.
60
+ # @param callback [Proc, Method] Resolved handler.
61
+ # @param value [Object] Selected value or node.
62
+ # @param name [String] Field name.
63
+ # @param context [Nokogiri::XML::Node] Current subtree.
64
+ # @param options [OpenStruct] Field options.
65
+ # @return [Object] Callback result.
66
+ def invoke_handler callback, value, name, context, options
67
+ args = [value, name, context, options]
68
+
69
+ callback[*args[0...callback.arity]]
70
+ end
71
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Explicit local input and bounded HTTP collection for CLI conversion.
4
+ module Schemic::Parser::CLI::Input
5
+ private
6
+
7
+ # Builds a lazy collection from explicit local files or bounded HTTP seeds.
8
+ # If both input modes are provided, rejects the ambiguous command before fetching.
9
+ # @return [Enumerator<Page>, Array<Page>] Pages for the existing parser pipeline.
10
+ def collection_pages
11
+ raise(ArgumentError, 'Use either --url or --input') if options.urls && options.inputs
12
+
13
+ return options.inputs.map {|path| local_page(path) } if options.inputs
14
+
15
+ page_collector.each_page(options.urls, **fetch_options)
16
+ end
17
+
18
+ # Reads one local file without a network request.
19
+ # @param path [String] Filename, including optional spaces.
20
+ # @return [Schemic::Crawler::Page] Raw local document.
21
+ def local_page path
22
+ Schemic::Crawler::Page.new(url: File.expand_path(path), status: 200, headers: {}, body: File.binread(path))
23
+ end
24
+
25
+ # Builds a collector with explicit source origins and delivery limits.
26
+ # @return [Schemic::Crawler] Bounded collector with persistent raw cache.
27
+ def page_collector
28
+ origins = options.urls.map {|url| source_origin(url) }
29
+ transport = Schemic::Crawler::HTTP.new(timeout: options.timeout || 15, retries: options.retries || 2)
30
+ cache = Schemic::Crawler::Cache.new(cache_directory)
31
+
32
+ Schemic::Crawler.new(origins: origins, cache: cache, transport: transport, **collector_limits)
33
+ end
34
+
35
+ # Formats the URL origin, including a nondefault port when specified.
36
+ # @param url [String] HTTP(S) seed URL.
37
+ # @return [String] Scheme, hostname and optional port.
38
+ def source_origin url
39
+ uri = URI(url)
40
+ port = uri.port == uri.default_port ? '' : ":#{uri.port}"
41
+
42
+ "#{uri.scheme}://#{uri.host}#{port}"
43
+ end
44
+
45
+ # Selects fetch settings, defaulting absent offline/refresh switches to false.
46
+ # @return [Hash] Options accepted by each_page/fetch.
47
+ def fetch_options
48
+ { links: options.links, offline: options.offline || false, refresh: options.refresh || false }
49
+ end
50
+
51
+ # Applies documented collection defaults when the command did not supply individual limits.
52
+ # @return [Hash] Path boundary, page limit and delay.
53
+ def collector_limits
54
+ { path_prefix: options.path_prefix || '/', max_pages: options.max_pages || 100, delay: options.delay || 1 }
55
+ end
56
+
57
+ # Uses an explicit cache directory when provided, otherwise stores it below rootdir.
58
+ # @return [String] Raw page cache path.
59
+ def cache_directory
60
+ options.cache || File.join(options.rootdir, '.schemic-cache')
61
+ end
62
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Declarative command switches for collection and extraction.
4
+ module Schemic::Parser::CLI::Switches
5
+ private
6
+
7
+ # Declares independent collection/conversion options alongside the original CLI options.
8
+ # @param opts [OptionParser] Command parser.
9
+ # @return [OptionParser] Parser with repeated URL/file inputs and bounded delivery controls.
10
+ def collection_options opts
11
+ Schemic::Parser::CLI::VALUE_OPTIONS.each do |name, declaration|
12
+ opts.on(*declaration) {|value| options[name] = value }
13
+ end
14
+ Schemic::Parser::CLI::FLAG_OPTIONS.each do |name, description|
15
+ opts.on("--#{name.to_s.tr('_', '-')}", description) { options[name] = true }
16
+ end
17
+ opts.on('--url=URL', String, 'Seed URL; repeat for a date range') {|value| append_input(:urls, value) }
18
+ opts.on('--input=FILE', String, 'Saved local document; repeat for multiple files') do |value|
19
+ append_input(:inputs, value)
20
+ end
21
+
22
+ opts
23
+ end
24
+
25
+ # Creates the base parser and adds extraction/delivery options.
26
+ # @return [OptionParser] Parser with help, schema and collection switches.
27
+ def built_option_parser
28
+ OptionParser.new do |opts|
29
+ opts.banner = 'Usage: schemic [options] [FILE...]'
30
+
31
+ base_options(opts)
32
+ collection_options(opts)
33
+ end
34
+ end
35
+
36
+ # Declares the YAML or Ruby schema switch, output root, verbosity and help.
37
+ # @param opts [OptionParser] Command parser.
38
+ # @return [OptionParser] Parser with the base declarations.
39
+ def base_options opts
40
+ opts.on('-r', '--rootdir=FOLDER', String, 'Root folder to store output to') {|value| options.rootdir = value }
41
+ opts.on('-s', '--scheme-file=FILE', String, 'YAML or trusted Ruby extraction schema') do |file|
42
+ options.scheme_file = file
43
+ options.scheme = Schemic::Generator.load(file)
44
+ end
45
+ opts.on('-v', '--[no-]verbose', 'Run verbosely') {|value| options.verbose = value }
46
+
47
+ opts.on('-h', '--help', 'This help') do
48
+ puts(opts)
49
+ exit
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+ require 'ostruct'
5
+ require 'yaml'
6
+ require 'pry'
7
+ require 'rdoba/os'
8
+ require 'shellwords'
9
+
10
+ require 'schemic/parser'
11
+ require 'schemic/generator'
12
+ require 'schemic/crawler'
13
+
14
+ # Command-line collection, offline replay and schema-driven extraction.
15
+ class Schemic::Parser::CLI
16
+ autoload :Input, 'schemic/parser/cli/input'
17
+
18
+ autoload :Switches, 'schemic/parser/cli/switches'
19
+
20
+ include Input
21
+ include Switches
22
+
23
+ VALUE_OPTIONS = {
24
+ output: ['--output=FILE', String, 'Complete import YAML output'],
25
+ cache: ['--cache=FOLDER', String, 'Raw page cache directory'],
26
+ format: ['--format=FORMAT', %w[html xml], 'html (default) or xml'],
27
+ collection: ['--collection=KEY', String, 'Extract this top-level array'],
28
+ links: ['--links=CSS', String, 'Follow selected links inside the source boundary'],
29
+ path_prefix: ['--path-prefix=PATH', String, 'Restrict collection to this path boundary'],
30
+ max_pages: ['--max-pages=COUNT', Integer, 'Maximum distinct pages (default 100)'],
31
+ delay: ['--delay=SECONDS', Float, 'Delay between HTTP attempts (default 1)'],
32
+ timeout: ['--timeout=SECONDS', Float, 'HTTP connection/read/write timeout (default 15)'],
33
+ retries: ['--retries=COUNT', Integer, 'Additional transient-error attempts (default 2)']
34
+ }.freeze
35
+ FLAG_OPTIONS = {
36
+ offline: 'Read only cached pages', refresh: 'Conditionally refresh the raw-page cache',
37
+ fetch_only: 'Save raw pages without extracting or writing YAML'
38
+ }.freeze
39
+
40
+ DEFAULT_OPTIONS = {
41
+ rootdir: Dir.pwd,
42
+ scheme: {}.to_os
43
+ }.to_os
44
+
45
+ def option_parser
46
+ @option_parser ||= built_option_parser
47
+
48
+ apply_argv
49
+
50
+ @option_parser
51
+ end
52
+
53
+ def options
54
+ @options ||= DEFAULT_OPTIONS.dup
55
+ end
56
+
57
+ # Parses command options and adds positional filenames to the local input list.
58
+ # Takes no arguments.
59
+ # @return [OpenStruct] Parsed options for this command.
60
+ def parse!
61
+ return @parse if @parse
62
+
63
+ @positional_files = option_parser.parse!
64
+
65
+ options.inputs = Array(options.inputs) + @positional_files unless @positional_files.empty?
66
+
67
+ @parse = OpenStruct.new(options: options)
68
+ end
69
+
70
+ def parse
71
+ parse!
72
+ end
73
+
74
+ def run
75
+ parse
76
+
77
+ return fetch_summary if options.fetch_only
78
+ return @parse if !options.urls && !options.inputs
79
+
80
+ conversion_summary
81
+ end
82
+
83
+ def initialize argv = nil
84
+ @argv = argv.is_a?(String) ? Shellwords.split(argv) : argv
85
+ end
86
+
87
+ private
88
+
89
+ # Applies supplied argv once; empty invocation requests help, preserving the existing CLI API.
90
+ # @return [Array, Boolean, nil] Last argv initialization result.
91
+ def apply_argv
92
+ if @argv && !@argv_applied
93
+ @option_parser.default_argv.replace(@argv.empty? ? ['--help'] : @argv)
94
+
95
+ @argv_applied = true
96
+ elsif @option_parser.default_argv.empty?
97
+ @option_parser.default_argv << '-h'
98
+ end
99
+ end
100
+
101
+ # Appends a repeated seed/file option, retaining all previously supplied values.
102
+ # @param name [Symbol] Input option name.
103
+ # @param value [String] New URL or filename.
104
+ # @return [Array<String>] Updated input list.
105
+ def append_input name, value
106
+ options[name] = (options[name] || []) + [value]
107
+ end
108
+
109
+ # Requires URL input in fetch-only mode; files or missing URLs raise ArgumentError.
110
+ # @return [Hash] Number of collected pages.
111
+ def fetch_summary
112
+ raise(ArgumentError, '--fetch-only requires --url') unless options.urls && !options.inputs
113
+
114
+ { pages: collection_pages.to_a.size }
115
+ end
116
+
117
+ # Checks that conversion has a schema and has output configured when no positional files were supplied.
118
+ # Takes no arguments. Raises MissingArgument when a required option is missing.
119
+ # @return [nil] No result after successful validation.
120
+ def check_output_options
121
+ raise(OptionParser::MissingArgument, '--scheme-file') unless options.scheme_file
122
+
123
+ raise(OptionParser::MissingArgument, '--output') unless options.output || !@positional_files.empty?
124
+ end
125
+
126
+ # Builds the existing parser/pipeline from the selected schema and output format.
127
+ # @return [Schemic::Crawler::Pipeline] Converter for the requested output collection.
128
+ def extraction_pipeline
129
+ Schemic::Crawler::Pipeline.new(parser: Schemic::Parser.new(options.scheme),
130
+ format: (options.format || 'html').to_sym, collection: options.collection)
131
+ end
132
+
133
+ # Converts all selected input after checking the schema and output settings.
134
+ # Takes no arguments.
135
+ # @return [Hash] Extracted records, or the record count and YAML path when writing a file.
136
+ def conversion_summary
137
+ check_output_options
138
+
139
+ pipeline = extraction_pipeline
140
+ pages = collection_pages
141
+
142
+ return { records: pipeline.records(pages) } unless options.output
143
+
144
+ records = pipeline.write(pages, output: options.output)
145
+
146
+ { records: records.size, output: options.output }
147
+ end
148
+ end